From c8a524c368ace54c88a4f9720ffad486e61f75f6 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 19:59:04 -0500 Subject: [PATCH 001/102] Keep the .d.ts-only types of a package compiled from its JavaScript --- .../frontend/npm-static-type-exports-host.ts | 164 +++++++++++++++ .../frontend/npm-static-type-exports.test.ts | 76 +++++++ .../src/frontend/npm-static-type-exports.ts | 188 ++++++++++++++++++ packages/compiler/src/frontend/npm-static.ts | 28 +++ packages/compiler/src/frontend/program.ts | 6 + .../7001-package-declared-types/main.ts.json | 6 + .../7001-package-declared-types/main.ts | 19 ++ .../node_modules/issue-list/lib/index.d.ts | 17 ++ .../node_modules/issue-list/lib/index.js | 24 +++ .../node_modules/issue-list/lib/paging.d.ts | 4 + .../node_modules/issue-list/lib/paging.js | 2 + .../node_modules/issue-list/package.json | 1 + .../7001-package-declared-types/main.ts.json | 1 + 13 files changed, 536 insertions(+) create mode 100644 packages/compiler/src/frontend/npm-static-type-exports-host.ts create mode 100644 packages/compiler/src/frontend/npm-static-type-exports.test.ts create mode 100644 packages/compiler/src/frontend/npm-static-type-exports.ts create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7001-package-declared-types/main.ts.json create mode 100644 tests/corpus/7001-package-declared-types/main.ts create mode 100644 tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/index.d.ts create mode 100644 tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/index.js create mode 100644 tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/paging.d.ts create mode 100644 tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/paging.js create mode 100644 tests/corpus/7001-package-declared-types/node_modules/issue-list/package.json create mode 100644 tests/harness/corpus-costs/7001-package-declared-types/main.ts.json diff --git a/packages/compiler/src/frontend/npm-static-type-exports-host.ts b/packages/compiler/src/frontend/npm-static-type-exports-host.ts new file mode 100644 index 000000000..809464763 --- /dev/null +++ b/packages/compiler/src/frontend/npm-static-type-exports-host.ts @@ -0,0 +1,164 @@ +/** Filesystem side of npm-static-type-exports.ts: finds each opted-in + * package's declaration entry and runtime entry, copies the declaration + * files the entry reaches, and builds the runtime entry's typedefs. */ +import { dirname, relative, resolve as resolvePath } from "node:path"; +import { trackedFileExists, trackedReadFile } from "./input-tracker.js"; +import { resolveBareModule } from "./resolve.js"; +import { isJsSourceFileName } from "./tsc-codes.js"; +import type { FrontendServices } from "./services.js"; +import * as ts from "./ts7/syntax.js"; +import { + NPM_STATIC_TYPES_SUFFIX, + npmStaticDeclarationCopy, + npmStaticDeclarationExports, + npmStaticDeclarationSpecifiers, + npmStaticTypedefBlock, + type NpmStaticDeclarationExports, + type NpmStaticTypeDeclaration, +} from "./npm-static-type-exports.js"; + +export interface NpmStaticTypeExportPlan { + /** Copies of the declaration files, by copy path. */ + copies: Map; + /** The typedef block to append, by runtime entry (forward slashes). */ + typedefs: Map; +} + +/** The copy path of a declaration file. */ +function copyPathOf(declarationFile: string): string { + return declarationFile.replace(/\.d\.ts$/, NPM_STATIC_TYPES_SUFFIX); +} + +/** The declaration file a relative specifier names from `fromFile`, or null. */ +function declarationTargetOf(fromFile: string, specifier: string): string | null { + const base = resolvePath(dirname(fromFile), specifier); + const candidates = [ + `${base}.d.ts`, + `${base.replace(/\.(c|m)?js$/, "")}.d.ts`, + resolvePath(base, "index.d.ts"), + ]; + for (const candidate of candidates) if (trackedFileExists(candidate)) return candidate; + return null; +} + +/** A specifier for `target` from `fromFile`'s directory, without `.d.ts`. */ +function specifierFor(fromFile: string, target: string): string { + const rel = relative(dirname(fromFile), target) + .split("\\") + .join("/") + .replace(/\.d\.ts$/, ""); + return rel.startsWith(".") ? rel : `./${rel}`; +} + +/** The names the runtime JavaScript declares as types itself: classes, + * JSDoc typedefs and callbacks, and `@enum` constants. */ +function runtimeTypeNames(services: FrontendServices, file: string, text: string): Set { + const names = new Set(); + for (const m of text.matchAll(/@(?:typedef|callback)\s+(?:\{[^}]*\}\s*)?([A-Za-z_$][\w$]*)/g)) + names.add(m[1]!); + // `/** @enum {number} */ const Kind = { ... }`: the constant names a type too. + for (const m of text.matchAll( + /@enum\b[^\n]*\n(?:\s*\*[^\n]*\n)*?\s*(?:\*\/\s*)?(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g, + )) + names.add(m[1]!); + const sf = services.parse(file, text, "js"); + for (const stmt of sf.statements.nodes) + if (ts.isClassDeclaration(stmt) && stmt.name !== undefined) names.add(stmt.name.text); + return names; +} + +export function npmStaticTypeExportPlan( + services: FrontendServices, + entryPath: string, + packages: readonly string[], +): NpmStaticTypeExportPlan { + const copies = new Map(); + const typedefs = new Map(); + const parsed = new Map(); + const parse = (file: string): ts.SourceFile | null => { + let sf = parsed.get(file); + if (sf === undefined) { + const text = trackedReadFile(file); + sf = text === null ? null : services.parse(file, text, "ts"); + parsed.set(file, sf); + } + return sf; + }; + // Copies every declaration file reachable from `file` through relative + // specifiers, each specifier respelled to its target's copy. + const copy = (file: string): void => { + const copyPath = copyPathOf(file); + if (copies.has(copyPath)) return; + const sf = parse(file); + if (sf === null) return; + copies.set(copyPath, ""); + const targets = new Map(); + for (const specifier of npmStaticDeclarationSpecifiers(sf)) { + const target = declarationTargetOf(file, specifier); + if (target !== null) targets.set(specifier, target); + } + copies.set( + copyPath, + npmStaticDeclarationCopy(sf, (specifier) => { + const target = targets.get(specifier); + return target === undefined ? null : specifierFor(copyPath, copyPathOf(target)); + }), + ); + for (const target of targets.values()) copy(target); + }; + // The exported type-only declarations of `file`, through its re-exports. + const typesOf = ( + file: string, + seen: Set, + ): { types: Map; values: Set } => { + const result = { + types: new Map(), + values: new Set(), + }; + if (seen.has(file)) return result; + seen.add(file); + const sf = parse(file); + if (sf === null) return result; + const own: NpmStaticDeclarationExports = npmStaticDeclarationExports(sf); + for (const t of own.types) result.types.set(t.name, t); + for (const v of own.values) result.values.add(v); + for (const n of own.named) { + const target = n.specifier === null ? null : declarationTargetOf(file, n.specifier); + if (target === null) continue; + const inner = typesOf(target, new Set(seen)); + const t = inner.types.get(n.local); + if (t !== undefined) result.types.set(n.exported, { ...t, name: n.exported }); + else if (inner.values.has(n.local)) result.values.add(n.exported); + } + for (const specifier of own.stars) { + const target = declarationTargetOf(file, specifier); + if (target === null) continue; + const inner = typesOf(target, new Set(seen)); + for (const [name, t] of inner.types) if (!result.types.has(name)) result.types.set(name, t); + for (const v of inner.values) result.values.add(v); + } + return result; + }; + for (const pkg of packages) { + const declared = resolveBareModule(entryPath, pkg, "types-only"); + if (declared === null || declared.packageName !== pkg || !declared.typesFile.endsWith(".d.ts")) + continue; + const runtime = resolveBareModule(entryPath, pkg, "js-only"); + if (runtime === null || !isJsSourceFileName(runtime.typesFile)) continue; + const runtimeText = trackedReadFile(runtime.typesFile); + if (runtimeText === null) continue; + const { types, values } = typesOf(declared.typesFile, new Set()); + const declaredByRuntime = runtimeTypeNames(services, runtime.typesFile, runtimeText); + const exported = [...types.values()].filter( + (t) => !values.has(t.name) && !declaredByRuntime.has(t.name), + ); + if (exported.length === 0) continue; + copy(declared.typesFile); + const specifier = specifierFor(runtime.typesFile, copyPathOf(declared.typesFile)); + typedefs.set( + runtime.typesFile.split("\\").join("/"), + npmStaticTypedefBlock(exported, specifier), + ); + } + return { copies, typedefs }; +} diff --git a/packages/compiler/src/frontend/npm-static-type-exports.test.ts b/packages/compiler/src/frontend/npm-static-type-exports.test.ts new file mode 100644 index 000000000..fa95c0fe0 --- /dev/null +++ b/packages/compiler/src/frontend/npm-static-type-exports.test.ts @@ -0,0 +1,76 @@ +import { expect, test } from "vitest"; +import { nodeFrontendServices } from "./services-node.js"; +import { + npmStaticDeclarationCopy, + npmStaticDeclarationExports, + npmStaticTypedefBlock, +} from "./npm-static-type-exports.js"; + +function parse(text: string) { + return nodeFrontendServices().parse("/pkg/lib/index.d.ts", text, "ts"); +} + +test("type-only exports are told from values and re-exports", () => { + const exports = npmStaticDeclarationExports( + parse(`import type { Page } from "./paging"; +export * from "./paging"; +export { Entry as Item, Kind } from "./entries"; +export interface Options { value: T; label: U } +export type Mode = "a" | "b"; +export declare const enum Level { Low = 1 } +export declare class Client { url: string } +export declare function make(options: Options): Client; +export declare const version: string; +interface Hidden { x: number } +export { Hidden as Visible }; +declare function helper(): void; +export { helper };`), + ); + expect(exports.types.map((t) => [t.name, t.params, t.templates])).toEqual([ + ["Options", ["T", "U"], ["{object} [T={}]", "[U=string]"]], + ["Mode", [], []], + ["Level", [], []], + ["Visible", [], []], + ]); + expect(exports.values).toEqual(["Client", "make", "version", "helper"]); + expect(exports.named).toEqual([ + { exported: "Item", local: "Entry", specifier: "./entries" }, + { exported: "Kind", local: "Kind", specifier: "./entries" }, + ]); + expect(exports.stars).toEqual(["./paging"]); +}); + +test("a copy respells the relative specifiers it is told", () => { + const sf = parse(`import type { Page } from "./paging"; +export * from './entries'; +export type Box = import("./paging").Page; +export { readFile } from "fs"; +`); + const copy = npmStaticDeclarationCopy(sf, (s) => + s === "./paging" ? "./paging.scriptc-types" : null, + ); + expect(copy).toBe(`import type { Page } from "./paging.scriptc-types"; +export * from './entries'; +export type Box = import("./paging.scriptc-types").Page; +export { readFile } from "fs"; +`); +}); + +test("the typedef block re-exports each type with its parameters", () => { + expect( + npmStaticTypedefBlock( + [ + { name: "Mode", params: [], templates: [] }, + { name: "Options", params: ["T", "U"], templates: ["{object} [T={}]", "[U=string]"] }, + ], + "./index.scriptc-types", + ), + ).toBe(`/** + * @typedef {import("./index.scriptc-types").Mode} Mode + */ +/** + * @template {object} [T={}] + * @template [U=string] + * @typedef {import("./index.scriptc-types").Options} Options + */`); +}); diff --git a/packages/compiler/src/frontend/npm-static-type-exports.ts b/packages/compiler/src/frontend/npm-static-type-exports.ts new file mode 100644 index 000000000..844afa590 --- /dev/null +++ b/packages/compiler/src/frontend/npm-static-type-exports.ts @@ -0,0 +1,188 @@ +/* The type-only exports of an opted-in package's declaration files. + * + * An opted-in package compiles from its JavaScript, and the checker types + * the package from it: the package's shipped .d.ts is hidden from + * resolution (npmStaticFsShadow). Values keep their JavaScript types, but a + * type that exists only in the .d.ts (an interface, a type alias, an enum + * used as a type) has no declaration in the JavaScript, so a program's + * `import type { Options } from "pkg"` resolved to `any`. TypeScript and + * Node see the .d.ts types. + * + * The package's declaration files stay available as copies under another + * name (`.scriptc-types.d.ts`, relative specifiers respelled to the + * copies), and the runtime entry gains a JSDoc typedef per type-only export + * that names the declaration in the copy: + * + * / ** @template T @typedef {import("./main.scriptc-types").Box} Box * / + * + * Classes and values keep the JavaScript's own declarations. */ +import * as ts from "./ts7/syntax.js"; +import { tokenStartOfNode } from "./ts7/node-functions.js"; + +/** The suffix that replaces `.d.ts` in a copy's name. */ +export const NPM_STATIC_TYPES_SUFFIX = ".scriptc-types.d.ts"; + +/** A type-only declaration: its name, its type parameters' names and their + * JSDoc @template tag bodies. */ +export interface NpmStaticTypeDeclaration { + name: string; + params: readonly string[]; + templates: readonly string[]; +} + +/** What a declaration file declares and re-exports, by exported name. */ +export interface NpmStaticDeclarationExports { + /** Exported interfaces, type aliases and enums, with their parameters. */ + types: readonly NpmStaticTypeDeclaration[]; + /** Exported classes, functions, variables and namespaces: names the + * JavaScript declares itself, or that are not type-only. */ + values: readonly string[]; + /** `export { local as exported } from "specifier"` and local + * `export { a, b }` (specifier null). */ + named: readonly { exported: string; local: string; specifier: string | null }[]; + /** `export * from "specifier"`. */ + stars: readonly string[]; +} + +function isExported(node: ts.Node): boolean { + const modifiers = (node as { modifiers?: { nodes: readonly ts.Node[] } }).modifiers?.nodes ?? []; + return modifiers.some((m) => m.kind === ts.SyntaxKind.ExportKeyword); +} + +function templatesOf(sf: ts.SourceFile, params: readonly ts.TypeParameterDeclaration[]): string[] { + const text = (n: ts.Node): string => sf.text.slice(tokenStartOfNode(n), n.end); + return params.map((p) => { + const name = p.name.text; + const constraint = p.constraint === undefined ? "" : `{${text(p.constraint)}} `; + return p.defaultType === undefined + ? `${constraint}${name}` + : `${constraint}[${name}=${text(p.defaultType)}]`; + }); +} + +/** The exports of one declaration file. */ +export function npmStaticDeclarationExports(sf: ts.SourceFile): NpmStaticDeclarationExports { + const types: NpmStaticTypeDeclaration[] = []; + const values: string[] = []; + const named: { exported: string; local: string; specifier: string | null }[] = []; + const stars: string[] = []; + const localTypes = new Map(); + const localValues = new Set(); + for (const stmt of sf.statements.nodes) { + const exported = isExported(stmt); + if (ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)) { + const params = stmt.typeParameters?.nodes ?? []; + const decl = { + name: stmt.name.text, + params: params.map((p) => p.name.text), + templates: templatesOf(sf, params), + }; + localTypes.set(decl.name, decl); + if (exported) types.push(decl); + } else if (ts.isEnumDeclaration(stmt)) { + const decl = { name: stmt.name.text, params: [], templates: [] }; + localTypes.set(decl.name, decl); + if (exported) types.push(decl); + } else if ( + ts.isClassDeclaration(stmt) || + ts.isFunctionDeclaration(stmt) || + ts.isModuleDeclaration(stmt) + ) { + const name = stmt.name !== undefined && ts.isIdentifier(stmt.name) ? stmt.name.text : null; + if (name !== null) { + localValues.add(name); + if (exported) values.push(name); + } + } else if (ts.isVariableStatement(stmt)) { + for (const d of stmt.declarationList.declarations.nodes) { + if (!ts.isIdentifier(d.name)) continue; + localValues.add(d.name.text); + if (exported) values.push(d.name.text); + } + } else if (ts.isExportDeclaration(stmt)) { + const specifier = + stmt.moduleSpecifier !== undefined && ts.isStringLiteral(stmt.moduleSpecifier) + ? stmt.moduleSpecifier.text + : null; + const clause = stmt.exportClause; + if (clause === undefined) { + if (specifier !== null) stars.push(specifier); + } else if (ts.isNamedExports(clause)) { + for (const e of clause.elements.nodes) { + const exportedName = e.name.text; + const local = (e.propertyName ?? e.name).text; + named.push({ exported: exportedName, local, specifier }); + } + } + } + } + // Local `export { a as b }` of the file's own declarations. + const resolvedNamed: typeof named = []; + for (const n of named) { + if (n.specifier !== null) { + resolvedNamed.push(n); + continue; + } + const local = localTypes.get(n.local); + if (local !== undefined) types.push({ ...local, name: n.exported }); + else if (localValues.has(n.local)) values.push(n.exported); + } + return { types, values, named: resolvedNamed, stars }; +} + +/** The relative module specifiers of a declaration file's imports, exports + * and `import("...")` types, with their spans. */ +function relativeSpecifiers(sf: ts.SourceFile): { start: number; end: number; text: string }[] { + const found: { start: number; end: number; text: string }[] = []; + const add = (literal: ts.Node | undefined): void => { + if (literal === undefined || !ts.isStringLiteral(literal)) return; + if (!literal.text.startsWith("./") && !literal.text.startsWith("../")) return; + found.push({ start: tokenStartOfNode(literal), end: literal.end, text: literal.text }); + }; + ts.walkPreorder(sf, (n) => { + if (ts.isImportDeclaration(n) || ts.isExportDeclaration(n)) add(n.moduleSpecifier); + else if (ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument)) add(n.argument.literal); + return undefined; + }); + return found; +} + +/** The relative specifiers a declaration file names. */ +export function npmStaticDeclarationSpecifiers(sf: ts.SourceFile): string[] { + return relativeSpecifiers(sf).map((s) => s.text); +} + +/** The declaration file's text with each relative specifier `rename` + * answers respelled (quoted with the original's quote). */ +export function npmStaticDeclarationCopy( + sf: ts.SourceFile, + rename: (specifier: string) => string | null, +): string { + const spans = relativeSpecifiers(sf).sort((a, b) => a.start - b.start); + let text = ""; + let at = 0; + for (const span of spans) { + const renamed = rename(span.text); + if (renamed === null) continue; + const quote = sf.text[span.start] ?? '"'; + text += sf.text.slice(at, span.start) + quote + renamed + quote; + at = span.end; + } + return text + sf.text.slice(at); +} + +/** The JSDoc typedefs that re-export `types` from the copy at `specifier`. */ +export function npmStaticTypedefBlock( + types: readonly NpmStaticTypeDeclaration[], + specifier: string, +): string { + const lines: string[] = []; + for (const t of types) { + const args = t.params.length === 0 ? "" : `<${t.params.join(", ")}>`; + lines.push("/**"); + for (const tag of t.templates) lines.push(` * @template ${tag}`); + lines.push(` * @typedef {import(${JSON.stringify(specifier)}).${t.name}${args}} ${t.name}`); + lines.push(" */"); + } + return lines.join("\n"); +} diff --git a/packages/compiler/src/frontend/npm-static.ts b/packages/compiler/src/frontend/npm-static.ts index 56edafc48..33ff54cfd 100644 --- a/packages/compiler/src/frontend/npm-static.ts +++ b/packages/compiler/src/frontend/npm-static.ts @@ -16,12 +16,14 @@ import { } from "./workspace-registry.js"; import { clearVirtualSources, + isVirtualSource, setVirtualSource, trackedExists, trackedReadFile, trackedRealpath, } from "./input-tracker.js"; import { npmBuiltinAliasOf } from "./builtin-modules.js"; +import { NPM_STATIC_TYPES_SUFFIX } from "./npm-static-type-exports.js"; let activePackages: ReadonlySet = new Set(); let declarationOverloads: ReadonlyMap = new Map(); @@ -53,10 +55,27 @@ export function npmStaticLexerVisibleNames(path: string): readonly string[] { return lexerNames.get(path.split("\\").join("/")) ?? []; } +/** Per runtime entry (forward slashes), the JSDoc typedefs that re-export + * its package's type-only declarations (npm-static-type-exports.ts). */ +let typeExportTypedefs = new Map(); + +/** Registers the copies of the opted-in packages' declaration files and the + * typedefs their runtime entries gain (after setNpmStaticPackages, which + * clears virtual sources). */ +export function setNpmStaticTypeExports( + copies: ReadonlyMap, + typedefs: ReadonlyMap, +): void { + for (const [path, text] of copies) setVirtualSource(path, text); + typeExportTypedefs = new Map(typedefs); + rewriteCache.clear(); +} + export function setNpmStaticPackages>(packages: T): void { // npm packages served as builtins (graceful-fs as fs) never compile // their JavaScript, even when named. activePackages = new Set([...packages].filter((name) => npmBuiltinAliasOf(name) === null)); + typeExportTypedefs = new Map(); declarationOverloads = new Map(); declarationProperties = new Map(); offenders.clear(); @@ -524,12 +543,21 @@ export function npmStaticFsShadow(services: FrontendServices): NpmStaticFsShadow } catch { rewritten = null; // unreadable/unparseable: fall through untouched } + // The runtime entry re-exports the type-only declarations of the + // package's .d.ts, after every respelling, so positions stay. + const typedefs = typeExportTypedefs.get(path.split("\\").join("/")); + if (typedefs !== undefined) { + const text = rewritten ?? trackedReadFile(path); + if (text !== null) rewritten = `${text}\n${typedefs}\n`; + } rewriteCache.set(path, rewritten); return rewritten ?? undefined; } return undefined; }, hideFile: (path) => { + // The copies of the package's declaration files the typedefs name. + if (path.endsWith(NPM_STATIC_TYPES_SUFFIX) && isVirtualSource(path)) return false; const target = shadowTargetOf(path); if (!target) return false; if (isBundledShimForwarder(path)) return false; diff --git a/packages/compiler/src/frontend/program.ts b/packages/compiler/src/frontend/program.ts index db43b7749..e398e59df 100644 --- a/packages/compiler/src/frontend/program.ts +++ b/packages/compiler/src/frontend/program.ts @@ -76,8 +76,10 @@ import { reportNpmStaticOffender, setNpmStaticDeclarationOverloads, setNpmStaticPackages, + setNpmStaticTypeExports, } from "./npm-static.js"; import { isPrunedNpmReexport, planNpmStaticReexports } from "./npm-static-prune.js"; +import { npmStaticTypeExportPlan } from "./npm-static-type-exports-host.js"; import { isNpmStaticSubclassArgument } from "./npm-static-subtyping.js"; import { npmStaticDeclarationReexports, @@ -1032,6 +1034,10 @@ export function loadProgram( } setNpmStaticPackages(npmStaticPackages); setNpmStaticDeclarationOverloads(declarationOverloads, declarationProperties); + // Types only the packages' .d.ts declares keep their declarations + // (npm-static-type-exports.ts). + const typeExports = npmStaticTypeExportPlan(services, entryPath, npmStaticPackages); + setNpmStaticTypeExports(typeExports.copies, typeExports.typedefs); // Workspace-package registrations reset per load (same discipline as the // npm-static set), then the opted-in names are probed UP FRONT: a // workspace-linked opt-in resolves to files whose realpaths carry no diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7001-package-declared-types/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7001-package-declared-types/main.ts.json new file mode 100644 index 000000000..c5aa8bb42 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7001-package-declared-types/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7001-package-declared-types/main.ts" + ], + "diags": [] +} diff --git a/tests/corpus/7001-package-declared-types/main.ts b/tests/corpus/7001-package-declared-types/main.ts new file mode 100644 index 000000000..c5194d33d --- /dev/null +++ b/tests/corpus/7001-package-declared-types/main.ts @@ -0,0 +1,19 @@ +// A package that compiles from its JavaScript, whose interfaces, type +// aliases and enums exist only in its .d.ts. A program that imports its +// values compiles the JavaScript, and the type-only names it imports keep +// the declarations TypeScript reads from the .d.ts. +import { Severity, collect, firstOf, label, type Issue, type Page, type Report } from "issue-list"; + +function report(text: string): Report { + const issues: Issue[] = []; + const count = collect(text, issues); + return { count, issues }; +} + +const result = report("a?b!c?"); +console.log(result.count, result.issues.length); +const first = result.issues[0]!; +console.log(label(first.severity), first.offset, first.severity === Severity.Warning); +const page: Page = { items: result.issues.slice(1), next: null }; +console.log(page.items.map((issue) => `${label(issue.severity)}@${issue.offset}`).join(","), page.next); +console.log(firstOf(page)?.offset); diff --git a/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/index.d.ts b/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/index.d.ts new file mode 100644 index 000000000..5ba9d04ac --- /dev/null +++ b/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/index.d.ts @@ -0,0 +1,17 @@ +import type { Page } from "./paging"; +export * from "./paging"; +export declare enum Severity { + Warning = 1, + Error = 2 +} +export interface Issue { + severity: Severity; + offset: number; +} +export type Report = { + count: number; + issues: Issue[]; +}; +export declare function collect(text: string, issues: Issue[]): number; +export declare function label(severity: Severity): string; +export declare function firstOf(page: Page): T | undefined; diff --git a/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/index.js b/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/index.js new file mode 100644 index 000000000..516d2fa30 --- /dev/null +++ b/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/index.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Severity = void 0; +exports.collect = collect; +exports.label = label; +exports.firstOf = firstOf; +var Severity; +(function (Severity) { + Severity[Severity["Warning"] = 1] = "Warning"; + Severity[Severity["Error"] = 2] = "Error"; +})(Severity || (exports.Severity = Severity = {})); +function collect(text, issues) { + for (let i = 0; i < text.length; i++) { + if (text[i] === "?") issues.push({ severity: Severity.Warning, offset: i }); + else if (text[i] === "!") issues.push({ severity: Severity.Error, offset: i }); + } + return issues.length; +} +function label(severity) { + return severity === Severity.Warning ? "warning" : "error"; +} +function firstOf(page) { + return page.items[0]; +} diff --git a/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/paging.d.ts b/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/paging.d.ts new file mode 100644 index 000000000..c427d5ce0 --- /dev/null +++ b/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/paging.d.ts @@ -0,0 +1,4 @@ +export interface Page { + items: T[]; + next: string | null; +} diff --git a/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/paging.js b/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/paging.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/tests/corpus/7001-package-declared-types/node_modules/issue-list/lib/paging.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/tests/corpus/7001-package-declared-types/node_modules/issue-list/package.json b/tests/corpus/7001-package-declared-types/node_modules/issue-list/package.json new file mode 100644 index 000000000..dcb8f20c3 --- /dev/null +++ b/tests/corpus/7001-package-declared-types/node_modules/issue-list/package.json @@ -0,0 +1 @@ +{ "name": "issue-list", "version": "1.0.0", "main": "./lib/index.js", "types": "./lib/index.d.ts" } diff --git a/tests/harness/corpus-costs/7001-package-declared-types/main.ts.json b/tests/harness/corpus-costs/7001-package-declared-types/main.ts.json new file mode 100644 index 000000000..d34ce5c69 --- /dev/null +++ b/tests/harness/corpus-costs/7001-package-declared-types/main.ts.json @@ -0,0 +1 @@ +{ "plain": 2683, "san": 1176 } From 462f93d50802826e771341ec81d101b43c45bc1d Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 20:42:16 -0500 Subject: [PATCH 002/102] Type the enum entry of a package's declaration exports explicitly The compiler compiles itself natively, and an empty array in an object literal took number[] there, so the enum entry did not match the declaration record. The coverage snapshot of native-npm-imports now counts one dynamic-tier statement instead of three: the program's `const point: Vector` takes the interface from the package's .d.ts instead of any. --- packages/compiler/src/frontend/npm-static-type-exports.ts | 2 +- tests/harness/__snapshots__/coverage-npm-packages.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/compiler/src/frontend/npm-static-type-exports.ts b/packages/compiler/src/frontend/npm-static-type-exports.ts index 844afa590..bdea8eb03 100644 --- a/packages/compiler/src/frontend/npm-static-type-exports.ts +++ b/packages/compiler/src/frontend/npm-static-type-exports.ts @@ -80,7 +80,7 @@ export function npmStaticDeclarationExports(sf: ts.SourceFile): NpmStaticDeclara localTypes.set(decl.name, decl); if (exported) types.push(decl); } else if (ts.isEnumDeclaration(stmt)) { - const decl = { name: stmt.name.text, params: [], templates: [] }; + const decl: NpmStaticTypeDeclaration = { name: stmt.name.text, params: [], templates: [] }; localTypes.set(decl.name, decl); if (exported) types.push(decl); } else if ( diff --git a/tests/harness/__snapshots__/coverage-npm-packages.txt b/tests/harness/__snapshots__/coverage-npm-packages.txt index 475b10e45..6150b08c2 100644 --- a/tests/harness/__snapshots__/coverage-npm-packages.txt +++ b/tests/harness/__snapshots__/coverage-npm-packages.txt @@ -2,7 +2,7 @@ scriptc coverage tests/corpus/native-npm-imports/main.ts statements analyzed 14 compile statically 14 (100%) - in dynamic tier 3 (operate on values typed only at runtime; --explain-dynamic lists them) + in dynamic tier 1 (operate on values typed only at runtime; --explain-dynamic lists them) npm package compilation: mathkit static From 283a504fe02195a7d5337127fe35a40c2c8c8a34 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 21:55:47 -0500 Subject: [PATCH 003/102] Support crypto.createDiffieHellman and getDiffieHellman crypto.createDiffieHellman, crypto.getDiffieHellman and crypto.createDiffieHellmanGroup return native DiffieHellman and DiffieHellmanGroup handles backed by mbedTLS bignums. generateKeys, computeSecret, getPrime, getGenerator, getPublicKey, getPrivateKey, setPublicKey, setPrivateKey and verifyError follow Node 24.22: - the modp1, modp2, modp5 and modp14 through modp18 groups, with the private key widths of Node's OpenSSL 3 path (200 to 400 bits for modp5 and up, [2, p - 2] for modp1 and modp2); - explicit primes and generators in every argument form and encoding, with keys of bits(p) - 2 bits, or below min(2^N, q) when the parameters equal an OpenSSL named group (RFC 3526, RFC 7919, RFC 5114); - generated safe primes with OpenSSL's congruences for the generator; - verifyError's DH_check bits, computed when it is first read; - Node's argument, generator, modulus, key range, state and encoding errors, including the OpenSSL errors' library and reason properties. Safe-prime generation sieves candidates with the odd primes below a bound that grows with the prime's length and tests them with Miller-Rabin rounds over a variable-time Montgomery exponentiation that only reads public values; key and secret exponentiations stay on mbedTLS's constant-time path. Primes longer than 8192 bits, property reads other than verifyError, property writes, Object.prototype methods, and calls whose output encoding is typed any or matches no @types/node overload are refused. The runtime unit scr_dh.c links, with the mbedTLS archive, only into programs that use DiffieHellman. wasm32-wasi builds refuse it. The ECDH unit's argument and encoding helpers move to scr_crypto_args.h, which both units include. --- .../limitations/builtin-apis/crypto.mdx | 6 + .../src/generated/node-v24-compatibility.json | 110 +- .../generated/node-v24-internal.json | 237 +++- internal/compatibility/src/generate.mjs | 16 +- internal/compatibility/static-support.json | 5 + .../ambient/scriptc-node-fallback.d.ts | 62 + .../src/backend/executable-features.ts | 1 + packages/compiler/src/backend/library-pack.ts | 1 + .../compiler/src/backend/llvm/lib-shared.ts | 2 + .../src/backend/native-link-info-core.ts | 3 + .../compiler/src/backend/native/contracts.ts | 4 + .../compiler/src/backend/native/executable.ts | 9 +- .../src/backend/runtime-pack-targets.test.ts | 1 + .../compiler/src/backend/runtime-pack.test.ts | 1 + .../src/backend/target-diagnostics.ts | 7 + packages/compiler/src/backend/warm-cache.ts | 1 + .../src/executable/executable-cache.test.ts | 1 + .../src/executable/executable-cache.ts | 2 + .../src/frontend/lowering/builtins/crypto.ts | 4 + .../src/frontend/lowering/builtins/dh.ts | 166 +++ .../src/frontend/lowering/builtins/ecdh.ts | 19 +- .../compiler/src/frontend/lowering/lowerer.ts | 13 +- .../src/frontend/lowering/surfaces.ts | 13 +- packages/compiler/src/frontend/type-mapper.ts | 17 + packages/compiler/src/index.ts | 1 + packages/compiler/src/ir/builtin-effects.ts | 3 + .../compiler/src/ir/builtin-signatures.ts | 7 + packages/compiler/src/ir/runtime-features.ts | 6 + packages/compiler/src/library/ir-policy.ts | 2 + packages/compiler/src/native/cli.ts | 1 + packages/compiler/src/native/prepare.ts | 1 + .../compiler/src/native/sanitizer.test.ts | 1 + packages/compiler/surface-manifest.json | 14 +- packages/compiler/test/cc-driver.test.ts | 5 + .../tests/corpus/6706-dh-groups.ts.json | 6 + .../corpus/6707-dh-explicit-params.ts.json | 6 + .../tests/corpus/6708-dh-errors.js.json | 6 + .../tests/corpus/6709-dh-generate.ts.json | 6 + .../tests/corpus/6710-dh-encodings.cjs.json | 6 + .../tests/corpus/6711-dh-handles.ts.json | 6 + .../tests/fixtures/node-types/dh.ts.json | 6 + .../runtime-pack-matrix.mjs | 2 +- .../runtime-darwin-arm64/scripts/build.mjs | 3 +- .../runtime-pack-matrix.mjs | 3 +- .../runtime-pack-common/scripts/build.mjs | 3 +- .../runtime-wasm32-wasi/scripts/build.mjs | 1 + packages/runtime/src/scr_crypto.h | 7 + packages/runtime/src/scr_crypto_args.h | 181 +++ packages/runtime/src/scr_dh.c | 1186 +++++++++++++++++ packages/runtime/src/scr_dh_groups.h | 557 ++++++++ packages/runtime/src/scr_dyn.h | 2 + packages/runtime/src/scr_ecdh.c | 192 +-- packages/runtime/test/dh.test.ts | 85 ++ packages/runtime/test/test_dh.c | 228 ++++ tests/corpus/6706-dh-groups.ts | 52 + tests/corpus/6707-dh-explicit-params.ts | 169 +++ tests/corpus/6708-dh-errors.js | 147 ++ tests/corpus/6709-dh-generate.ts | 47 + tests/corpus/6710-dh-encodings.cjs | 73 + tests/corpus/6711-dh-handles.ts | 56 + tests/fixtures/node-types/dh.ts | 22 + tests/fixtures/node-types/fenced.ts | 6 + .../__snapshots__/node-types-fenced.txt | 36 +- .../corpus-costs/6706-dh-groups.ts.json | 1 + .../6707-dh-explicit-params.ts.json | 1 + .../corpus-costs/6708-dh-errors.js.json | 1 + .../corpus-costs/6709-dh-generate.ts.json | 1 + .../corpus-costs/6710-dh-encodings.cjs.json | 1 + .../corpus-costs/6711-dh-handles.ts.json | 1 + tests/harness/errors.test.ts | 47 + tests/harness/project-config.test.ts | 14 + .../self-hosting-native-toolchain.test.ts | 1 + .../harness/self-hosting-runtime-pack.test.ts | 1 + 73 files changed, 3602 insertions(+), 309 deletions(-) create mode 100644 packages/compiler/src/frontend/lowering/builtins/dh.ts create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6706-dh-groups.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6707-dh-explicit-params.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6708-dh-errors.js.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6709-dh-generate.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6710-dh-encodings.cjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6711-dh-handles.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/dh.ts.json create mode 100644 packages/runtime/src/scr_crypto_args.h create mode 100644 packages/runtime/src/scr_dh.c create mode 100644 packages/runtime/src/scr_dh_groups.h create mode 100644 packages/runtime/test/dh.test.ts create mode 100644 packages/runtime/test/test_dh.c create mode 100644 tests/corpus/6706-dh-groups.ts create mode 100644 tests/corpus/6707-dh-explicit-params.ts create mode 100644 tests/corpus/6708-dh-errors.js create mode 100644 tests/corpus/6709-dh-generate.ts create mode 100644 tests/corpus/6710-dh-encodings.cjs create mode 100644 tests/corpus/6711-dh-handles.ts create mode 100644 tests/fixtures/node-types/dh.ts create mode 100644 tests/harness/corpus-costs/6706-dh-groups.ts.json create mode 100644 tests/harness/corpus-costs/6707-dh-explicit-params.ts.json create mode 100644 tests/harness/corpus-costs/6708-dh-errors.js.json create mode 100644 tests/harness/corpus-costs/6709-dh-generate.ts.json create mode 100644 tests/harness/corpus-costs/6710-dh-encodings.cjs.json create mode 100644 tests/harness/corpus-costs/6711-dh-handles.ts.json diff --git a/docs/content/limitations/builtin-apis/crypto.mdx b/docs/content/limitations/builtin-apis/crypto.mdx index 3c830c63d..b07cd6962 100644 --- a/docs/content/limitations/builtin-apis/crypto.mdx +++ b/docs/content/limitations/builtin-apis/crypto.mdx @@ -15,5 +15,11 @@ `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. + `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. + 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 asymmetric KeyObjects, and the `DiffieHellman` and `DiffieHellmanGroup` constructors are not available. Other public-key operations remain unsupported. Native derivations finish before their deferred callbacks, so computation blocks the caller. diff --git a/docs/src/generated/node-v24-compatibility.json b/docs/src/generated/node-v24-compatibility.json index 66b0ba3dd..09bc7df29 100644 --- a/docs/src/generated/node-v24-compatibility.json +++ b/docs/src/generated/node-v24-compatibility.json @@ -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" } }, @@ -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" } }, { @@ -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" } }, { @@ -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" } }, { diff --git a/internal/compatibility/generated/node-v24-internal.json b/internal/compatibility/generated/node-v24-internal.json index c6a7a102c..7ebd09df8 100644 --- a/internal/compatibility/generated/node-v24-internal.json +++ b/internal/compatibility/generated/node-v24-internal.json @@ -19313,11 +19313,18 @@ "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/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/harness/npm-static.test.ts" ] @@ -19759,8 +19766,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 +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" }, @@ -19805,8 +19830,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" }, @@ -20387,8 +20421,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" }, @@ -22153,8 +22196,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 +22228,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 +22260,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 +22292,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 +22324,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 +22356,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 +22388,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 +22420,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 +22452,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 +22484,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 +22516,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" }, @@ -27448,8 +27590,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 +32342,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 +33753,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 +33882,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 +34155,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" }, diff --git a/internal/compatibility/src/generate.mjs b/internal/compatibility/src/generate.mjs index 9bd3927b8..536d4ce5e 100644 --- a/internal/compatibility/src/generate.mjs +++ b/internal/compatibility/src/generate.mjs @@ -582,17 +582,27 @@ 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."; } diff --git a/internal/compatibility/static-support.json b/internal/compatibility/static-support.json index 23c7a159b..b6cfed75d 100644 --- a/internal/compatibility/static-support.json +++ b/internal/compatibility/static-support.json @@ -44,6 +44,8 @@ "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.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 +120,7 @@ "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.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"], @@ -414,6 +417,8 @@ { "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": ["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"] }, diff --git a/packages/compiler/ambient/scriptc-node-fallback.d.ts b/packages/compiler/ambient/scriptc-node-fallback.d.ts index dbb3cd8fd..ab4b59eb8 100644 --- a/packages/compiler/ambient/scriptc-node-fallback.d.ts +++ b/packages/compiler/ambient/scriptc-node-fallback.d.ts @@ -2968,6 +2968,68 @@ 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 interface ScryptOptions { N?: number; r?: number; diff --git a/packages/compiler/src/backend/executable-features.ts b/packages/compiler/src/backend/executable-features.ts index f7cae8508..92b16965d 100644 --- a/packages/compiler/src/backend/executable-features.ts +++ b/packages/compiler/src/backend/executable-features.ts @@ -56,6 +56,7 @@ export function executableLinkFeatures(mod: IrModule): NativeLinkFeatures { tlsCa: features.tlsCa, cipher: features.cipher, ecdh: features.ecdh, + dh: features.dh, webcrypto: features.webcrypto, perfLoop: features.perfLoop, }; diff --git a/packages/compiler/src/backend/library-pack.ts b/packages/compiler/src/backend/library-pack.ts index 805198df1..a58203688 100644 --- a/packages/compiler/src/backend/library-pack.ts +++ b/packages/compiler/src/backend/library-pack.ts @@ -60,6 +60,7 @@ export async function compilePackedLibrary( tls: false, cipher: false, ecdh: false, + dh: false, webcrypto: false, perfLoop: false, tlsCa: false, diff --git a/packages/compiler/src/backend/llvm/lib-shared.ts b/packages/compiler/src/backend/llvm/lib-shared.ts index 8bb8bc3aa..0745b8806 100644 --- a/packages/compiler/src/backend/llvm/lib-shared.ts +++ b/packages/compiler/src/backend/llvm/lib-shared.ts @@ -577,6 +577,8 @@ 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.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", diff --git a/packages/compiler/src/backend/native-link-info-core.ts b/packages/compiler/src/backend/native-link-info-core.ts index a476e1f7f..ad8b662ea 100644 --- a/packages/compiler/src/backend/native-link-info-core.ts +++ b/packages/compiler/src/backend/native-link-info-core.ts @@ -90,6 +90,9 @@ export interface NativeLinkFeatures { /** 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; /** 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..f268e67b2 100644 --- a/packages/compiler/src/backend/native/contracts.ts +++ b/packages/compiler/src/backend/native/contracts.ts @@ -249,6 +249,10 @@ export interface CcOptions { /** 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; /** 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..8caf79a07 100644 --- a/packages/compiler/src/backend/native/executable.ts +++ b/packages/compiler/src/backend/native/executable.ts @@ -114,6 +114,7 @@ interface RuntimeUnitContext { tlsCa: boolean; cipher: boolean; ecdh: boolean; + dh: boolean; lreObjects: readonly string[]; zlibObjects: readonly string[]; tlsArchive: string | null; @@ -308,6 +309,7 @@ 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.tlsArchive, // mbedTLS's win32 entropy poll is BCryptGenRandom (bcrypt.h). // The unconditional win32 libs above do not carry it. @@ -372,10 +374,12 @@ 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 mbedtls = tls || cipher || ecdh || dh; const driver = resolveCc(); const darwinDebugSymbols = needsDarwinDebugSymbols( targetPlatform(driver), @@ -733,6 +737,7 @@ export async function compileCInternal( tlsCa, cipher, ecdh, + dh, lreObjects, zlibObjects, tlsArchive, diff --git a/packages/compiler/src/backend/runtime-pack-targets.test.ts b/packages/compiler/src/backend/runtime-pack-targets.test.ts index 19519e1f2..e2ba393a2 100644 --- a/packages/compiler/src/backend/runtime-pack-targets.test.ts +++ b/packages/compiler/src/backend/runtime-pack-targets.test.ts @@ -125,6 +125,7 @@ const features = { tlsCa: false, cipher: false, ecdh: false, + dh: 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 ee2301172..2a1c46f72 100644 --- a/packages/compiler/src/backend/runtime-pack.test.ts +++ b/packages/compiler/src/backend/runtime-pack.test.ts @@ -61,6 +61,7 @@ const BASE: NativeLinkFeatures = { tlsCa: false, cipher: false, ecdh: false, + dh: false, webcrypto: false, perfLoop: false, }; diff --git a/packages/compiler/src/backend/target-diagnostics.ts b/packages/compiler/src/backend/target-diagnostics.ts index b7049f6fe..e480beae4 100644 --- a/packages/compiler/src/backend/target-diagnostics.ts +++ b/packages/compiler/src/backend/target-diagnostics.ts @@ -215,6 +215,13 @@ export function moduleWasiUnavailableSurface( }; return false; } + if (node.fn === "crypto.dhNew" || node.fn === "crypto.dhGroupNew") { + found = { + surface: "DiffieHellman (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)", diff --git a/packages/compiler/src/backend/warm-cache.ts b/packages/compiler/src/backend/warm-cache.ts index 2d8ae6641..8870e21e7 100644 --- a/packages/compiler/src/backend/warm-cache.ts +++ b/packages/compiler/src/backend/warm-cache.ts @@ -67,6 +67,7 @@ export async function warmNativeCaches( tls: false, cipher: false, ecdh: false, + dh: false, webcrypto: false, perfLoop: false, tlsCa: false, diff --git a/packages/compiler/src/executable/executable-cache.test.ts b/packages/compiler/src/executable/executable-cache.test.ts index 94b136c90..3770a6bd6 100644 --- a/packages/compiler/src/executable/executable-cache.test.ts +++ b/packages/compiler/src/executable/executable-cache.test.ts @@ -65,6 +65,7 @@ const native: EarlyExecutableNativeFeatures = { tlsCa: false, cipher: false, ecdh: false, + dh: false, webcrypto: false, perfLoop: false, }; diff --git a/packages/compiler/src/executable/executable-cache.ts b/packages/compiler/src/executable/executable-cache.ts index 2312f5e85..6f96f8f75 100644 --- a/packages/compiler/src/executable/executable-cache.ts +++ b/packages/compiler/src/executable/executable-cache.ts @@ -96,6 +96,7 @@ export interface EarlyExecutableNativeFeatures { tls: boolean; cipher: boolean; ecdh: boolean; + dh: boolean; perfLoop: boolean; tlsCa: boolean; webcrypto: boolean; @@ -228,6 +229,7 @@ const BOOLEAN_NATIVE_KEYS = [ "tlsCa", "cipher", "ecdh", + "dh", "webcrypto", "perfLoop", ] as const satisfies readonly (keyof EarlyExecutableNativeFeatures)[]; diff --git a/packages/compiler/src/frontend/lowering/builtins/crypto.ts b/packages/compiler/src/frontend/lowering/builtins/crypto.ts index f4270dbe8..6ea83fce5 100644 --- a/packages/compiler/src/frontend/lowering/builtins/crypto.ts +++ b/packages/compiler/src/frontend/lowering/builtins/crypto.ts @@ -1,6 +1,7 @@ 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"; @@ -410,6 +411,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( 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/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/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index 870e21b1f..8072e410d 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -58,6 +58,7 @@ 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 { lowerNetAddressCall, lowerNetAddressNew } from "./builtins/net-address.js"; @@ -3620,9 +3621,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) || @@ -3630,7 +3631,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), + ) ); } @@ -12737,6 +12741,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) ?? diff --git a/packages/compiler/src/frontend/lowering/surfaces.ts b/packages/compiler/src/frontend/lowering/surfaces.ts index c77938337..75bf42516 100644 --- a/packages/compiler/src/frontend/lowering/surfaces.ts +++ b/packages/compiler/src/frontend/lowering/surfaces.ts @@ -1574,6 +1574,12 @@ 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 }, }, zlib: { // The default-options convenience family is special-cased in @@ -3063,10 +3069,6 @@ export const BUILTIN_MODULE_FENCE_HINTS: Record< "createVerify", "sign", "verify", - "createDiffieHellman", - "createDiffieHellmanGroup", - "getDiffieHellman", - "diffieHellman", "publicEncrypt", "publicDecrypt", "privateEncrypt", @@ -3078,6 +3080,9 @@ export const BUILTIN_MODULE_FENCE_HINTS: Record< "can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics", ]), ), + diffieHellman: + "crypto.diffieHellman takes asymmetric KeyObjects, which the static runtime does not have; " + + "the objects of createDiffieHellman, getDiffieHellman and createECDH compute shared secrets", ...Object.fromEntries( ["getCipherInfo"].map((m) => [ m, diff --git a/packages/compiler/src/frontend/type-mapper.ts b/packages/compiler/src/frontend/type-mapper.ts index a233f0186..189efaac0 100644 --- a/packages/compiler/src/frontend/type-mapper.ts +++ b/packages/compiler/src/frontend/type-mapper.ts @@ -2973,6 +2973,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 diff --git a/packages/compiler/src/index.ts b/packages/compiler/src/index.ts index 92ee6b75e..acd9f168a 100644 --- a/packages/compiler/src/index.ts +++ b/packages/compiler/src/index.ts @@ -620,6 +620,7 @@ async function compileExecutableNative( tlsCa: features.tlsCa, cipher: features.cipher, ecdh: features.ecdh, + dh: features.dh, webcrypto: features.webcrypto, perfLoop: features.perfLoop, ...(onArtifactReady === undefined ? {} : { onArtifactReady }), diff --git a/packages/compiler/src/ir/builtin-effects.ts b/packages/compiler/src/ir/builtin-effects.ts index ca8c52118..21215d28f 100644 --- a/packages/compiler/src/ir/builtin-effects.ts +++ b/packages/compiler/src/ir/builtin-effects.ts @@ -13,6 +13,9 @@ 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:test's { timeout } and { concurrency } range checks. "test.register", "test.registerEmpty", diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index 771b53152..d362e13fa 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -2782,6 +2782,13 @@ 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 }, "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 }, diff --git a/packages/compiler/src/ir/runtime-features.ts b/packages/compiler/src/ir/runtime-features.ts index 4142b6efe..eec599e94 100644 --- a/packages/compiler/src/ir/runtime-features.ts +++ b/packages/compiler/src/ir/runtime-features.ts @@ -744,6 +744,9 @@ 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; unknown encodings render through + * the inspect unit. */ + dh: rule({ fns: ["crypto.dhNew", "crypto.dhGroupNew"] }), emitter: rule({ initial: (mod) => mod.workers === true || (mod.classes ?? []).some((c) => c.name === RUNTIME_EMITTER_CLASS), @@ -789,6 +792,8 @@ const RUNTIME_FEATURE_RULES = { "crypto.cipherNew", "crypto.ecdhNew", "crypto.ecdhConvertKey", + "crypto.dhNew", + "crypto.dhGroupNew", ...BUILTIN_CLASS_LIB_FNS, ...UTIL_CALLABLE_LIB_FNS, ], @@ -910,6 +915,7 @@ function noRuntimeFeatures(): RuntimeFeatures { dynInvoke: false, dynTier: false, ecdh: false, + dh: false, emitter: false, eventTarget: false, eventsOnceSignal: false, diff --git a/packages/compiler/src/library/ir-policy.ts b/packages/compiler/src/library/ir-policy.ts index 51aeb6146..4fc912ea6 100644 --- a/packages/compiler/src/library/ir-policy.ts +++ b/packages/compiler/src/library/ir-policy.ts @@ -52,6 +52,8 @@ 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"], ["webcrypto.", "WebCrypto (crypto.subtle)"], ["fs.watch", "fs.watch"], ["watcher.", "fs.watch"], diff --git a/packages/compiler/src/native/cli.ts b/packages/compiler/src/native/cli.ts index ed8d52293..8529678ff 100644 --- a/packages/compiler/src/native/cli.ts +++ b/packages/compiler/src/native/cli.ts @@ -110,6 +110,7 @@ async function main(): Promise { tls: false, cipher: false, ecdh: false, + dh: false, webcrypto: false, perfLoop: false, tlsCa: false, diff --git a/packages/compiler/src/native/prepare.ts b/packages/compiler/src/native/prepare.ts index b90760616..1a1263035 100644 --- a/packages/compiler/src/native/prepare.ts +++ b/packages/compiler/src/native/prepare.ts @@ -161,6 +161,7 @@ function validFeatures(value: unknown): value is NativeLinkFeatures { "tlsCa", "cipher", "ecdh", + "dh", "webcrypto", "perfLoop", ].every((name) => typeof features[name] === "boolean"); diff --git a/packages/compiler/src/native/sanitizer.test.ts b/packages/compiler/src/native/sanitizer.test.ts index e6beb24cc..ec9580ccc 100644 --- a/packages/compiler/src/native/sanitizer.test.ts +++ b/packages/compiler/src/native/sanitizer.test.ts @@ -120,6 +120,7 @@ test.skipIf(process.platform !== "linux" && process.platform !== "darwin")( tlsCa: false, cipher: false, ecdh: false, + dh: false, webcrypto: false, perfLoop: false, nativeFetch: false, diff --git a/packages/compiler/surface-manifest.json b/packages/compiler/surface-manifest.json index c05e994a8..6998a574e 100644 --- a/packages/compiler/surface-manifest.json +++ b/packages/compiler/surface-manifest.json @@ -496,17 +496,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", @@ -570,7 +566,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 asymmetric KeyObjects, which the static runtime does not have; the objects of createDiffieHellman, getDiffieHellman and createECDH compute shared secrets" }, { "id": "node-builtin.crypto.generateKey", @@ -612,9 +608,7 @@ "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", 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/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/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/runtime-darwin-arm64/runtime-pack-matrix.mjs b/packages/runtime-darwin-arm64/runtime-pack-matrix.mjs index db72284f6..16fe348f2 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") }, ], 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 856de4b86..e44ba4a33 100644 --- a/packages/runtime-darwin-arm64/scripts/build.mjs +++ b/packages/runtime-darwin-arm64/scripts/build.mjs @@ -172,7 +172,8 @@ 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" ? ["-I", join(mbedtls, "include")] : []), ...(unit.source === "scr_zlib.c" || unit.source === "scr_fetch.c" diff --git a/packages/runtime-pack-common/runtime-pack-matrix.mjs b/packages/runtime-pack-common/runtime-pack-matrix.mjs index 0f40218a1..ad426c953 100644 --- a/packages/runtime-pack-common/runtime-pack-matrix.mjs +++ b/packages/runtime-pack-common/runtime-pack-matrix.mjs @@ -149,6 +149,7 @@ export const OPTIONAL_RUNTIME_SOURCES = [ ["scr_tls.c", "tlsEffective"], ["scr_cipher.c", "cipher"], ["scr_ecdh.c", "ecdh"], + ["scr_dh.c", "dh"], ["scr_wasm.c", "wasm"], ["scr_webcrypto.c", "webcrypto"], ["scr_fetch.c", "nativeFetch"], @@ -212,7 +213,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") }, ]; const matrix = withLibraryRuntimeFlavors( withWorkerRuntimeVariants({ diff --git a/packages/runtime-pack-common/scripts/build.mjs b/packages/runtime-pack-common/scripts/build.mjs index fa84e9c4d..b99bd8438 100644 --- a/packages/runtime-pack-common/scripts/build.mjs +++ b/packages/runtime-pack-common/scripts/build.mjs @@ -223,7 +223,8 @@ 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" ? ["-I", join(mbedtls, "include")] : []), ...(unit.source === "scr_zlib.c" || unit.source === "scr_fetch.c" diff --git a/packages/runtime-wasm32-wasi/scripts/build.mjs b/packages/runtime-wasm32-wasi/scripts/build.mjs index 2dd983973..818ebac94 100644 --- a/packages/runtime-wasm32-wasi/scripts/build.mjs +++ b/packages/runtime-wasm32-wasi/scripts/build.mjs @@ -22,6 +22,7 @@ process.env.SCRIPTC_RUNTIME_PACK_CONFIG = JSON.stringify({ "scr_tls.c", "scr_cipher.c", "scr_ecdh.c", + "scr_dh.c", "scr_wasm.c", "scr_fetch.c", ], diff --git a/packages/runtime/src/scr_crypto.h b/packages/runtime/src/scr_crypto.h index d12858abf..65a6245ef 100644 --- a/packages/runtime/src/scr_crypto.h +++ b/packages/runtime/src/scr_crypto.h @@ -94,6 +94,13 @@ 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); 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, 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_dh.c b/packages/runtime/src/scr_dh.c new file mode 100644 index 000000000..c514b45ba --- /dev/null +++ b/packages/runtime/src/scr_dh.c @@ -0,0 +1,1186 @@ +/* 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. 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 + +/* 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"); +} + +/* validateInt32(value, name). */ +static bool sd_validate_int32(const char *name, double value) { + bool integer = isfinite(value) && trunc(value) == value; + if (integer && value >= INT32_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 >= -2147483648 && <= 2147483647. " + "Received %s", + name, 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; +} + +/* ── 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) { + MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&digit, e)); + MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&digit, offset)); + for (size_t bit = SD_DIGIT_BITS; bit < mbedtls_mpi_bitlen(&digit); bit++) + MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&digit, bit, 0)); + 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; +} + +/* 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_check_prime: trial division by the small primes, then Miller-Rabin + * rounds with random bases. */ +static bool sd_is_prime(ScDhSmallPrimes *t, const mbedtls_mpi *x) { + 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)); + for (int i = 0; i < rounds && prime; i++) prime = sd_mr_round(&m, x, false) == 1; + sd_mr_free(&m); + return prime; +} + +/* 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. */ +static bool sd_generate_safe_prime(mbedtls_mpi *p, size_t bits, unsigned add, unsigned rem) { + 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) || 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) || 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(); + if (mbedtls_mpi_read_binary(&d->p, prime->data, prime->len) != 0) scr_trap("scriptc: out of memory\n"); + if (generator_bytes) { + if (mbedtls_mpi_read_binary(&d->g, generator_bytes->data, generator_bytes->len) != 0) + scr_trap("scriptc: out of memory\n"); + } else if (mbedtls_mpi_lset(&d->g, (mbedtls_mpi_sint)generator) != 0) { + scr_trap("scriptc: out of memory\n"); + } + 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); +} + +/* ── 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; +} + +/* computeSecret(key, inputEncoding, outputEncoding): key^priv mod p, + * padded to the prime's length. */ +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); + if (mbedtls_mpi_read_binary(&peer, bytes->data, bytes->len) != 0 || mbedtls_mpi_sub_int(&bound, &d->p, 1) != 0) + scr_trap("scriptc: out of memory\n"); + if (mbedtls_mpi_cmp_int(&peer, 1) <= 0) { + sd_throw(SCR_ERR_RANGE, "ERR_CRYPTO_INVALID_KEYLEN", "Supplied key is too small"); + } else if (mbedtls_mpi_cmp_mpi(&peer, &bound) >= 0) { + sd_throw(SCR_ERR_RANGE, "ERR_CRYPTO_INVALID_KEYLEN", "Supplied key is too large"); + } else if (!d->has_priv || (!d->group && !sd_derives(d)) || !sd_exp(&secret, &peer, &d->priv, &d->p)) { + 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; + if (mbedtls_mpi_read_binary(value, bytes->data, bytes->len) != 0) scr_trap("scriptc: out of memory\n"); + *present = true; + scr_bytes_release(bytes); + 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,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 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, 0x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+ 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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3b, 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, 0xa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x5c, 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, 0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 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,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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, 0x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 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, 0x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3, 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, 0x3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x54, 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 37e9eacce..4b618a809 100644 --- a/packages/runtime/src/scr_dyn.h +++ b/packages/runtime/src/scr_dyn.h @@ -155,6 +155,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, 65) /* node:crypto DiffieHellman (scr_dh.c) */ \ + X(DIFFIE_HELLMAN_GROUP, 66) /* 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) */ \ 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/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_dh.c b/packages/runtime/test/test_dh.c new file mode 100644 index 000000000..aa8f175a3 --- /dev/null +++ b/packages/runtime/test/test_dh.c @@ -0,0 +1,228 @@ +/* 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); + 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); +} + +int main(void) { + test_mont_pow(); + test_is_prime(); + test_check_params(); + test_long_exponent(); + test_generate(); + fprintf(stderr, "%ld/%ld cases passed\n", total - failed, total); + return failed ? 1 : 0; +} 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..e092da727 --- /dev/null +++ b/tests/corpus/6708-dh-errors.js @@ -0,0 +1,147 @@ +// 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()); 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/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..c6a8e90b7 100644 --- a/tests/fixtures/node-types/fenced.ts +++ b/tests/fixtures/node-types/fenced.ts @@ -103,6 +103,12 @@ cipherStream.on("data", () => {}); import { createECDH } from "node:crypto"; createECDH("sect163k1"); createECDH("prime256v1").computeSecret(Buffer.alloc(65), "hex"); +/* 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 HMAC slice: @types/node declares the whole * SubtleCrypto surface, and the methods outside importKey, sign, verify * and digest fence by name. */ diff --git a/tests/harness/__snapshots__/node-types-fenced.txt b/tests/harness/__snapshots__/node-types-fenced.txt index 0bd13963d..6ac45473f 100644 --- a/tests/harness/__snapshots__/node-types-fenced.txt +++ b/tests/harness/__snapshots__/node-types-fenced.txt @@ -228,24 +228,42 @@ fenced.ts:105:1 - error SC2020: 'ECDH.computeSecret(key, encoding) with a Buffer 104 | createECDH("sect163k1"); 105 | createECDH("prime256v1").computeSecret(Buffer.alloc(65), "hex"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 106 | /* WebCrypto beyond the HMAC slice: @types/node declares the whole + 106 | /* 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:109: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)); + 108 | import { createDiffieHellman, diffieHellman, type KeyObject } from "node:crypto"; + 109 | createDiffieHellman(Buffer.from([23])).toString(); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 110 | declare const dhKey: KeyObject; + + hint: generateKeys(), computeSecret(), getPrime(), getGenerator(), getPublicKey(), getPrivateKey(), setPublicKey(), setPrivateKey() and verifyError are supported + +fenced.ts:111:1 - error SC2020: 'crypto.diffieHellman' is typed by @types/node but has no scriptc lowering yet + + 110 | declare const dhKey: KeyObject; + 111 | diffieHellman({ privateKey: dhKey, publicKey: dhKey }); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 112 | /* WebCrypto beyond the HMAC slice: @types/node declares the whole + + hint: crypto.diffieHellman takes asymmetric KeyObjects, which the static runtime does not have; the objects of createDiffieHellman, getDiffieHellman and createECDH compute shared secrets + +fenced.ts:116:9 - error SC2020: 'crypto.subtle.encrypt' is part of the standard library types but has no scriptc lowering yet + + 115 | async function encryptWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { + 116 | await crypto.subtle.encrypt({ name: "AES-GCM", iv: new Uint8Array(12) }, key, new Uint8Array(1)); | ^~~~~~~~~~~~~~~~~~~~~ - 111 | } + 117 | } 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 -fenced.ts:115:15 - error SC2020: 'navigator.hardwareConcurrency' is typed by @types/node but has no scriptc lowering yet +fenced.ts:121:15 - error SC2020: 'navigator.hardwareConcurrency' is typed by @types/node but has no scriptc lowering yet - 114 | * compile; the other members fence by name. */ - 115 | const cores = navigator.hardwareConcurrency; + 120 | * compile; the other members fence by name. */ + 121 | const cores = navigator.hardwareConcurrency; | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 116 | void cores; + 122 | 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/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/errors.test.ts b/tests/harness/errors.test.ts index 8af6998ca..87ca7b59f 100644 --- a/tests/harness/errors.test.ts +++ b/tests/harness/errors.test.ts @@ -918,6 +918,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 diff --git a/tests/harness/project-config.test.ts b/tests/harness/project-config.test.ts index dabb9b0bf..2f336a1cd 100644 --- a/tests/harness/project-config.test.ts +++ b/tests/harness/project-config.test.ts @@ -1114,6 +1114,20 @@ 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: WebCrypto HMAC matches Node under @types/node", async () => { const outDir = outDirFor("node-webcrypto-hmac"); const entry = join(nodeTypesDir, "webcrypto-hmac.ts"); diff --git a/tests/harness/self-hosting-native-toolchain.test.ts b/tests/harness/self-hosting-native-toolchain.test.ts index 6d028d597..cbab9f6c9 100644 --- a/tests/harness/self-hosting-native-toolchain.test.ts +++ b/tests/harness/self-hosting-native-toolchain.test.ts @@ -48,6 +48,7 @@ const features: NativeLinkFeatures = { tlsCa: false, cipher: false, ecdh: false, + dh: false, webcrypto: false, perfLoop: false, }; diff --git a/tests/harness/self-hosting-runtime-pack.test.ts b/tests/harness/self-hosting-runtime-pack.test.ts index f4fde795c..f170f96d1 100644 --- a/tests/harness/self-hosting-runtime-pack.test.ts +++ b/tests/harness/self-hosting-runtime-pack.test.ts @@ -49,6 +49,7 @@ const base: NativeLinkFeatures = { tlsCa: false, cipher: false, ecdh: false, + dh: false, webcrypto: false, perfLoop: false, }; From c36c414065bdf07d6fb3f7a245943a5d8f1ac4f9 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 22:23:04 -0500 Subject: [PATCH 004/102] Re-export only data shapes from package declarations, through imports and .mjs entries - A local `export { Kind }` of a name the declaration file imports (`import type { Kind } from "./kinds"`) now resolves like `export { Kind } from "./kinds"`; it was dropped. - The typedefs now reach a runtime entry outside the .js/.cjs rewrite path (an .mjs file). - Only data shapes are re-exported: an interface, type alias or enum with no method, call or construct signature, function type or other computed type, whose referenced types are data shapes too. An interface with methods describes the package's JavaScript objects and stays as the JavaScript types it (@opentelemetry/api's Counter). - NPM_STATIC_TYPES_SUFFIX moves to npm-static.ts, so that module does not import the syntax modules (the self-hosted frontend tests compile it natively). --- .../frontend/npm-static-type-exports-host.ts | 79 ++++++++--- .../frontend/npm-static-type-exports.test.ts | 53 +++++++- .../src/frontend/npm-static-type-exports.ts | 127 ++++++++++++++++-- packages/compiler/src/frontend/npm-static.ts | 29 ++-- .../main.ts.json | 6 + .../main.ts | 19 +++ .../node_modules/row-module/lib/index.d.ts | 5 + .../node_modules/row-module/lib/index.mjs | 7 + .../node_modules/row-module/package.json | 1 + .../node_modules/shape-kinds/lib/index.d.ts | 4 + .../node_modules/shape-kinds/lib/index.js | 8 ++ .../node_modules/shape-kinds/lib/kinds.d.ts | 5 + .../node_modules/shape-kinds/lib/kinds.js | 2 + .../node_modules/shape-kinds/package.json | 1 + .../main.ts.json | 1 + tests/harness/coverage.test.ts | 13 ++ 16 files changed, 320 insertions(+), 40 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7004-package-declared-type-reexports/main.ts.json create mode 100644 tests/corpus/7004-package-declared-type-reexports/main.ts create mode 100644 tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/lib/index.d.ts create mode 100644 tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/lib/index.mjs create mode 100644 tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/package.json create mode 100644 tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/index.d.ts create mode 100644 tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/index.js create mode 100644 tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/kinds.d.ts create mode 100644 tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/kinds.js create mode 100644 tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/package.json create mode 100644 tests/harness/corpus-costs/7004-package-declared-type-reexports/main.ts.json diff --git a/packages/compiler/src/frontend/npm-static-type-exports-host.ts b/packages/compiler/src/frontend/npm-static-type-exports-host.ts index 809464763..3c196e6a7 100644 --- a/packages/compiler/src/frontend/npm-static-type-exports-host.ts +++ b/packages/compiler/src/frontend/npm-static-type-exports-host.ts @@ -5,10 +5,10 @@ import { dirname, relative, resolve as resolvePath } from "node:path"; import { trackedFileExists, trackedReadFile } from "./input-tracker.js"; import { resolveBareModule } from "./resolve.js"; import { isJsSourceFileName } from "./tsc-codes.js"; +import { NPM_STATIC_TYPES_SUFFIX } from "./npm-static.js"; import type { FrontendServices } from "./services.js"; import * as ts from "./ts7/syntax.js"; import { - NPM_STATIC_TYPES_SUFFIX, npmStaticDeclarationCopy, npmStaticDeclarationExports, npmStaticDeclarationSpecifiers, @@ -106,28 +106,37 @@ export function npmStaticTypeExportPlan( ); for (const target of targets.values()) copy(target); }; - // The exported type-only declarations of `file`, through its re-exports. + const exportsOf = new Map(); + const declarationExports = (file: string): NpmStaticDeclarationExports | null => { + let ex = exportsOf.get(file); + if (ex === undefined) { + const sf = parse(file); + ex = sf === null ? null : npmStaticDeclarationExports(sf); + exportsOf.set(file, ex); + } + return ex; + }; + // The exported type-only declarations of `file`, through its re-exports, + // each with the file that declares it. + type Found = { decl: NpmStaticTypeDeclaration; file: string }; const typesOf = ( file: string, seen: Set, - ): { types: Map; values: Set } => { - const result = { - types: new Map(), - values: new Set(), - }; + ): { types: Map; values: Set } => { + const result = { types: new Map(), values: new Set() }; if (seen.has(file)) return result; seen.add(file); - const sf = parse(file); - if (sf === null) return result; - const own: NpmStaticDeclarationExports = npmStaticDeclarationExports(sf); - for (const t of own.types) result.types.set(t.name, t); + const own = declarationExports(file); + if (own === null) return result; + for (const t of own.types) result.types.set(t.name, { decl: t, file }); for (const v of own.values) result.values.add(v); for (const n of own.named) { const target = n.specifier === null ? null : declarationTargetOf(file, n.specifier); if (target === null) continue; const inner = typesOf(target, new Set(seen)); const t = inner.types.get(n.local); - if (t !== undefined) result.types.set(n.exported, { ...t, name: n.exported }); + if (t !== undefined) + result.types.set(n.exported, { ...t, decl: { ...t.decl, name: n.exported } }); else if (inner.values.has(n.local)) result.values.add(n.exported); } for (const specifier of own.stars) { @@ -139,6 +148,39 @@ export function npmStaticTypeExportPlan( } return result; }; + // Whether `name`, as `file` sees it, is a data shape: an interface, type + // alias or enum whose syntax describes no behavior (npm-static-type- + // exports.ts) and whose referenced types are data shapes too. A name the + // package's declaration files do not declare is a global (`Array`, + // `Record`, `Date`); a class, a value or an import from another package + // is not a data shape. + const dataMemo = new Map(); + const isData = (file: string, name: string, visiting: Set): boolean => { + const key = `${file}\0${name}`; + const memo = dataMemo.get(key); + if (memo !== undefined) return memo; + if (visiting.has(key)) return true; // a recursive shape + visiting.add(key); + const answer = ((): boolean => { + const ex = declarationExports(file); + if (ex === null) return false; + const local = ex.locals.get(name); + if (local !== undefined) + return !local.behavior && local.references.every((r) => isData(file, r, visiting)); + if (ex.valueNames.has(name)) return false; + const from = ex.imports.get(name); + if (from !== undefined) { + const target = declarationTargetOf(file, from.specifier); + return target !== null && isData(target, from.local, visiting); + } + const reexport = typesOf(file, new Set()).types.get(name); + if (reexport !== undefined) return isData(reexport.file, reexport.decl.declared, visiting); + return true; + })(); + visiting.delete(key); + dataMemo.set(key, answer); + return answer; + }; for (const pkg of packages) { const declared = resolveBareModule(entryPath, pkg, "types-only"); if (declared === null || declared.packageName !== pkg || !declared.typesFile.endsWith(".d.ts")) @@ -149,9 +191,16 @@ export function npmStaticTypeExportPlan( if (runtimeText === null) continue; const { types, values } = typesOf(declared.typesFile, new Set()); const declaredByRuntime = runtimeTypeNames(services, runtime.typesFile, runtimeText); - const exported = [...types.values()].filter( - (t) => !values.has(t.name) && !declaredByRuntime.has(t.name), - ); + // Only data shapes: a type with methods describes the package's + // JavaScript objects, which stay as the JavaScript types them. + const exported = [...types.values()] + .filter( + ({ decl, file }) => + !values.has(decl.name) && + !declaredByRuntime.has(decl.name) && + isData(file, decl.declared, new Set()), + ) + .map(({ decl }) => decl); if (exported.length === 0) continue; copy(declared.typesFile); const specifier = specifierFor(runtime.typesFile, copyPathOf(declared.typesFile)); diff --git a/packages/compiler/src/frontend/npm-static-type-exports.test.ts b/packages/compiler/src/frontend/npm-static-type-exports.test.ts index fa95c0fe0..89adf5bbc 100644 --- a/packages/compiler/src/frontend/npm-static-type-exports.test.ts +++ b/packages/compiler/src/frontend/npm-static-type-exports.test.ts @@ -40,6 +40,41 @@ export { helper };`), expect(exports.stars).toEqual(["./paging"]); }); +test("a local export of an imported name resolves like a re-export", () => { + const exports = npmStaticDeclarationExports( + parse(`import type { Kind } from "./kinds"; +import { type Shape as Form, helper } from "./kinds"; +export { Kind, Form as Outline, helper };`), + ); + expect(exports.types).toEqual([]); + expect(exports.named).toEqual([ + { exported: "Kind", local: "Kind", specifier: "./kinds" }, + { exported: "Outline", local: "Shape", specifier: "./kinds" }, + { exported: "helper", local: "helper", specifier: "./kinds" }, + ]); +}); + +test("each declaration records whether it describes behavior and what it references", () => { + const { locals } = npmStaticDeclarationExports( + parse(`interface Row { key: string; value: T; next?: Row; tags: Tag[] } +type Tag = "a" | "b"; +interface Counter { add(value: number): void } +type Callback = (row: Row) => void; +type Keys = keyof Row; +interface Named extends Base { label: Label }`), + ); + const shape = (name: string) => { + const d = locals.get(name)!; + return [d.behavior, [...d.references].sort()]; + }; + expect(shape("Row")).toEqual([false, ["Row", "Tag"]]); + expect(shape("Tag")).toEqual([false, []]); + expect(shape("Counter")).toEqual([true, []]); + expect(shape("Callback")[0]).toBe(true); + expect(shape("Keys")[0]).toBe(true); + expect(shape("Named")).toEqual([false, ["Base", "Label"]]); +}); + test("a copy respells the relative specifiers it is told", () => { const sf = parse(`import type { Page } from "./paging"; export * from './entries'; @@ -60,8 +95,22 @@ test("the typedef block re-exports each type with its parameters", () => { expect( npmStaticTypedefBlock( [ - { name: "Mode", params: [], templates: [] }, - { name: "Options", params: ["T", "U"], templates: ["{object} [T={}]", "[U=string]"] }, + { + name: "Mode", + declared: "Mode", + params: [], + templates: [], + behavior: false, + references: [], + }, + { + name: "Options", + declared: "Options", + params: ["T", "U"], + templates: ["{object} [T={}]", "[U=string]"], + behavior: false, + references: [], + }, ], "./index.scriptc-types", ), diff --git a/packages/compiler/src/frontend/npm-static-type-exports.ts b/packages/compiler/src/frontend/npm-static-type-exports.ts index bdea8eb03..3b74b8aef 100644 --- a/packages/compiler/src/frontend/npm-static-type-exports.ts +++ b/packages/compiler/src/frontend/npm-static-type-exports.ts @@ -19,15 +19,21 @@ import * as ts from "./ts7/syntax.js"; import { tokenStartOfNode } from "./ts7/node-functions.js"; -/** The suffix that replaces `.d.ts` in a copy's name. */ -export const NPM_STATIC_TYPES_SUFFIX = ".scriptc-types.d.ts"; - -/** A type-only declaration: its name, its type parameters' names and their - * JSDoc @template tag bodies. */ +/** A type-only declaration: its exported name, its name where it is + * declared, its type parameters' names and their JSDoc @template tag + * bodies, and what npmStaticDataShape needs to know. */ export interface NpmStaticTypeDeclaration { name: string; + declared: string; params: readonly string[]; templates: readonly string[]; + /** The declaration's own syntax describes behavior or a computed type: + * a method, call or construct signature, a function or constructor + * type, an accessor, `typeof`, `import("...")`, a conditional, mapped, + * indexed-access or `keyof` type, or a qualified type name. */ + behavior: boolean; + /** The type names it refers to, its own type parameters excepted. */ + references: readonly string[]; } /** What a declaration file declares and re-exports, by exported name. */ @@ -37,11 +43,17 @@ export interface NpmStaticDeclarationExports { /** Exported classes, functions, variables and namespaces: names the * JavaScript declares itself, or that are not type-only. */ values: readonly string[]; - /** `export { local as exported } from "specifier"` and local - * `export { a, b }` (specifier null). */ + /** `export { local as exported } from "specifier"`, including a local + * `export { a }` of an imported name. */ named: readonly { exported: string; local: string; specifier: string | null }[]; /** `export * from "specifier"`. */ stars: readonly string[]; + /** Every interface, type alias and enum the file declares, by name. */ + locals: ReadonlyMap; + /** The file's named imports: local name to imported name and specifier. */ + imports: ReadonlyMap; + /** Every class, function, namespace and variable the file declares. */ + valueNames: ReadonlySet; } function isExported(node: ts.Node): boolean { @@ -60,6 +72,49 @@ function templatesOf(sf: ts.SourceFile, params: readonly ts.TypeParameterDeclara }); } +/** Syntax kinds of a type that describes behavior or is computed. */ +const BEHAVIOR_KINDS: ReadonlySet = new Set([ + ts.SyntaxKind.MethodSignature, + ts.SyntaxKind.CallSignature, + ts.SyntaxKind.ConstructSignature, + ts.SyntaxKind.FunctionType, + ts.SyntaxKind.ConstructorType, + ts.SyntaxKind.GetAccessor, + ts.SyntaxKind.SetAccessor, + ts.SyntaxKind.TypeQuery, + ts.SyntaxKind.ImportType, + ts.SyntaxKind.ConditionalType, + ts.SyntaxKind.MappedType, + ts.SyntaxKind.InferType, + ts.SyntaxKind.IndexedAccessType, + ts.SyntaxKind.ThisType, + ts.SyntaxKind.TypePredicate, + ts.SyntaxKind.TemplateLiteralType, +]); + +/** The behavior flag and type references of an interface or type alias. */ +function shapeOf( + decl: ts.InterfaceDeclaration | ts.TypeAliasDeclaration, + params: readonly string[], +): { behavior: boolean; references: string[] } { + let behavior = false; + const references = new Set(); + const refer = (name: ts.Node): void => { + if (ts.isIdentifier(name)) { + if (!params.includes(name.text)) references.add(name.text); + } else behavior = true; // a qualified name: a namespace member + }; + ts.walkPreorder(decl, (n) => { + if (behavior) return "stop"; + if (BEHAVIOR_KINDS.has(n.kind)) behavior = true; + else if (ts.isTypeOperatorNode(n) && n.operator === ts.SyntaxKind.KeyOfKeyword) behavior = true; + else if (ts.isTypeReferenceNode(n)) refer(n.typeName); + else if (ts.isExpressionWithTypeArguments(n)) refer(n.expression); + return undefined; + }); + return { behavior, references: [...references] }; +} + /** The exports of one declaration file. */ export function npmStaticDeclarationExports(sf: ts.SourceFile): NpmStaticDeclarationExports { const types: NpmStaticTypeDeclaration[] = []; @@ -68,19 +123,44 @@ export function npmStaticDeclarationExports(sf: ts.SourceFile): NpmStaticDeclara const stars: string[] = []; const localTypes = new Map(); const localValues = new Set(); + // `import { A as B } from "./x"`: local name B is A of "./x". + const imported = new Map(); for (const stmt of sf.statements.nodes) { const exported = isExported(stmt); - if (ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)) { + if (ts.isImportDeclaration(stmt)) { + const bindings = stmt.importClause?.namedBindings; + if (ts.isStringLiteral(stmt.moduleSpecifier) && bindings && ts.isNamedImports(bindings)) { + for (const e of bindings.elements.nodes) { + imported.set(e.name.text, { + local: (e.propertyName ?? e.name).text, + specifier: stmt.moduleSpecifier.text, + }); + } + } + } else if (ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)) { const params = stmt.typeParameters?.nodes ?? []; - const decl = { + const paramNames = params.map((p) => p.name.text); + const shape = shapeOf(stmt, paramNames); + const merged = localTypes.get(stmt.name.text); // interface merging + const decl: NpmStaticTypeDeclaration = { name: stmt.name.text, - params: params.map((p) => p.name.text), + declared: stmt.name.text, + params: paramNames, templates: templatesOf(sf, params), + behavior: shape.behavior || merged?.behavior === true, + references: [...shape.references, ...(merged?.references ?? [])], }; localTypes.set(decl.name, decl); - if (exported) types.push(decl); + if (exported && merged === undefined) types.push(decl); } else if (ts.isEnumDeclaration(stmt)) { - const decl: NpmStaticTypeDeclaration = { name: stmt.name.text, params: [], templates: [] }; + const decl: NpmStaticTypeDeclaration = { + name: stmt.name.text, + declared: stmt.name.text, + params: [], + templates: [], + behavior: false, + references: [], + }; localTypes.set(decl.name, decl); if (exported) types.push(decl); } else if ( @@ -116,7 +196,9 @@ export function npmStaticDeclarationExports(sf: ts.SourceFile): NpmStaticDeclara } } } - // Local `export { a as b }` of the file's own declarations. + // Local `export { a as b }`: of the file's own declarations, or of a + // name it imports (`import type { A } from "./a"; export { A }`), which + // resolves like `export { A } from "./a"`. const resolvedNamed: typeof named = []; for (const n of named) { if (n.specifier !== null) { @@ -124,10 +206,27 @@ export function npmStaticDeclarationExports(sf: ts.SourceFile): NpmStaticDeclara continue; } const local = localTypes.get(n.local); + const from = imported.get(n.local); if (local !== undefined) types.push({ ...local, name: n.exported }); else if (localValues.has(n.local)) values.push(n.exported); + else if (from !== undefined) resolvedNamed.push({ exported: n.exported, ...from }); } - return { types, values, named: resolvedNamed, stars }; + // A merged interface's exported entry takes the merged flags. + const exportedTypes: NpmStaticTypeDeclaration[] = []; + for (const t of types) { + const local = localTypes.get(t.declared); + if (local === undefined) exportedTypes.push(t); + else exportedTypes.push({ ...local, name: t.name }); + } + return { + types: exportedTypes, + values, + named: resolvedNamed, + stars, + locals: localTypes, + imports: imported, + valueNames: localValues, + }; } /** The relative module specifiers of a declaration file's imports, exports diff --git a/packages/compiler/src/frontend/npm-static.ts b/packages/compiler/src/frontend/npm-static.ts index 33ff54cfd..800d02eff 100644 --- a/packages/compiler/src/frontend/npm-static.ts +++ b/packages/compiler/src/frontend/npm-static.ts @@ -23,7 +23,6 @@ import { trackedRealpath, } from "./input-tracker.js"; import { npmBuiltinAliasOf } from "./builtin-modules.js"; -import { NPM_STATIC_TYPES_SUFFIX } from "./npm-static-type-exports.js"; let activePackages: ReadonlySet = new Set(); let declarationOverloads: ReadonlyMap = new Map(); @@ -55,6 +54,11 @@ export function npmStaticLexerVisibleNames(path: string): readonly string[] { return lexerNames.get(path.split("\\").join("/")) ?? []; } +/** The suffix that replaces `.d.ts` in the name of a copy of an opted-in + * package's declaration file (npm-static-type-exports.ts). Defined here so + * this module does not depend on the syntax modules. */ +export const NPM_STATIC_TYPES_SUFFIX = ".scriptc-types.d.ts"; + /** Per runtime entry (forward slashes), the JSDoc typedefs that re-export * its package's type-only declarations (npm-static-type-exports.ts). */ let typeExportTypedefs = new Map(); @@ -71,6 +75,17 @@ export function setNpmStaticTypeExports( rewriteCache.clear(); } +/** `text` (or the file's own text when null) with the typedefs of a + * package runtime entry appended: the entry re-exports the type-only + * declarations of the package's .d.ts, after every respelling, so + * positions stay. Null when `path` is no runtime entry and `text` is null. */ +function withTypeExportTypedefs(path: string, text: string | null): string | null { + const typedefs = typeExportTypedefs.get(path.split("\\").join("/")); + if (typedefs === undefined) return text; + const source = text ?? trackedReadFile(path); + return source === null ? text : `${source}\n${typedefs}\n`; +} + export function setNpmStaticPackages>(packages: T): void { // npm packages served as builtins (graceful-fs as fs) never compile // their JavaScript, even when named. @@ -543,17 +558,13 @@ export function npmStaticFsShadow(services: FrontendServices): NpmStaticFsShadow } catch { rewritten = null; // unreadable/unparseable: fall through untouched } - // The runtime entry re-exports the type-only declarations of the - // package's .d.ts, after every respelling, so positions stay. - const typedefs = typeExportTypedefs.get(path.split("\\").join("/")); - if (typedefs !== undefined) { - const text = rewritten ?? trackedReadFile(path); - if (text !== null) rewritten = `${text}\n${typedefs}\n`; - } + rewritten = withTypeExportTypedefs(path, rewritten); rewriteCache.set(path, rewritten); return rewritten ?? undefined; } - return undefined; + // Other runtime entries (`.mjs`) keep their text and gain only the + // typedefs. + return withTypeExportTypedefs(path, null) ?? undefined; }, hideFile: (path) => { // The copies of the package's declaration files the typedefs name. diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7004-package-declared-type-reexports/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7004-package-declared-type-reexports/main.ts.json new file mode 100644 index 000000000..927b902d9 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7004-package-declared-type-reexports/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7004-package-declared-type-reexports/main.ts" + ], + "diags": [] +} diff --git a/tests/corpus/7004-package-declared-type-reexports/main.ts b/tests/corpus/7004-package-declared-type-reexports/main.ts new file mode 100644 index 000000000..52e45e7d4 --- /dev/null +++ b/tests/corpus/7004-package-declared-type-reexports/main.ts @@ -0,0 +1,19 @@ +// Two packages that compile from their JavaScript, with types only their +// .d.ts declares: one re-exports types its entry imports +// (`import type { Kind } from "./kinds"; export { Kind }`), the other's +// runtime entry is an ES module (`.mjs`). Declarations using those types +// keep TypeScript's types: the empty arrays the packages fill hold the +// declared rows. +import { addShapes, type Form, type Kind } from "shape-kinds"; +import { readRows, type Row } from "row-module"; + +const forms: Form[] = []; +addShapes("c2 s3", forms); +const kinds: Kind[] = forms.map((form) => form.kind); +const first = forms[0]!; +console.log(kinds.join(","), first.size + forms[1]!.size, first.kind === "circle"); + +const rows: Row[] = []; +const count = readRows("a=1;b=22", rows); +const last = rows[count - 1]!; +console.log(count, last.key, last.value.length); diff --git a/tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/lib/index.d.ts b/tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/lib/index.d.ts new file mode 100644 index 000000000..1f732f996 --- /dev/null +++ b/tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/lib/index.d.ts @@ -0,0 +1,5 @@ +export interface Row { + key: string; + value: string; +} +export declare function readRows(text: string, into: Row[]): number; diff --git a/tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/lib/index.mjs b/tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/lib/index.mjs new file mode 100644 index 000000000..33d110065 --- /dev/null +++ b/tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/lib/index.mjs @@ -0,0 +1,7 @@ +export function readRows(text, into) { + for (const part of text.split(";")) { + const at = part.indexOf("="); + into.push({ key: part.slice(0, at), value: part.slice(at + 1) }); + } + return into.length; +} diff --git a/tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/package.json b/tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/package.json new file mode 100644 index 000000000..240a3f816 --- /dev/null +++ b/tests/corpus/7004-package-declared-type-reexports/node_modules/row-module/package.json @@ -0,0 +1 @@ +{ "name": "row-module", "version": "1.0.0", "main": "./lib/index.mjs", "types": "./lib/index.d.ts" } diff --git a/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/index.d.ts b/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/index.d.ts new file mode 100644 index 000000000..ada1748d8 --- /dev/null +++ b/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/index.d.ts @@ -0,0 +1,4 @@ +import type { Kind } from "./kinds"; +import { type Shape as Form } from "./kinds"; +export { Kind, Form }; +export declare function addShapes(text: string, into: Form[]): void; diff --git a/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/index.js b/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/index.js new file mode 100644 index 000000000..d6165c4b9 --- /dev/null +++ b/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/index.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.addShapes = addShapes; +function addShapes(text, into) { + for (const part of text.split(" ")) { + into.push({ kind: part.charAt(0) === "c" ? "circle" : "square", size: Number(part.slice(1)) }); + } +} diff --git a/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/kinds.d.ts b/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/kinds.d.ts new file mode 100644 index 000000000..79c90322c --- /dev/null +++ b/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/kinds.d.ts @@ -0,0 +1,5 @@ +export type Kind = "circle" | "square"; +export interface Shape { + kind: Kind; + size: number; +} diff --git a/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/kinds.js b/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/kinds.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/lib/kinds.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/package.json b/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/package.json new file mode 100644 index 000000000..e428fc315 --- /dev/null +++ b/tests/corpus/7004-package-declared-type-reexports/node_modules/shape-kinds/package.json @@ -0,0 +1 @@ +{ "name": "shape-kinds", "version": "1.0.0", "main": "./lib/index.js", "types": "./lib/index.d.ts" } diff --git a/tests/harness/corpus-costs/7004-package-declared-type-reexports/main.ts.json b/tests/harness/corpus-costs/7004-package-declared-type-reexports/main.ts.json new file mode 100644 index 000000000..e9e0bf6d2 --- /dev/null +++ b/tests/harness/corpus-costs/7004-package-declared-type-reexports/main.ts.json @@ -0,0 +1 @@ +{ "plain": 1015, "san": 2516 } diff --git a/tests/harness/coverage.test.ts b/tests/harness/coverage.test.ts index ca62352b1..1f790c225 100644 --- a/tests/harness/coverage.test.ts +++ b/tests/harness/coverage.test.ts @@ -488,6 +488,19 @@ test("JavaScript builtin aliases keep their deferred value fence", async () => { ); }); +test("types only a package's .d.ts declares stay static through re-exports and .mjs entries", () => { + // shape-kinds re-exports types its .d.ts entry imports; row-module's + // runtime entry is an .mjs file. Without their declared types the + // program's uses of Form, Kind and Row run in the dynamic tier (12 + // statements); with them only the packages' own JavaScript and one + // arithmetic on a JavaScript return value do (4). + const { coverage } = analyze( + join(repoRoot, "tests/corpus/7004-package-declared-type-reexports/main.ts"), + ); + expect(coverage.diagnostics).toEqual([]); + expect(coverage.stats.statementsDynamic).toBe(4); +}); + test("any-typed checked-dynamic operators compile natively", () => { const file = join(repoRoot, "tests/corpus/2856-dynamic-any-local-operators.ts"); const staticCoverage = analyze(file).coverage; From ecee5fdaaffe061b715a73915aea39179f6d5803 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 23:25:33 -0500 Subject: [PATCH 005/102] Store references to ProgramLifetime instances in 4 bytes on Linux --- docs/content/docs/contracts.mdx | 2 + .../compiler/src/backend/llvm/classes.test.ts | 109 +++++++++- packages/compiler/src/backend/llvm/classes.ts | 144 ++++++++++++- .../src/backend/llvm/emit-function.ts | 1 + .../compiler/src/backend/llvm/emit-module.ts | 4 + .../src/backend/llvm/emit-statements.ts | 2 +- packages/compiler/src/backend/llvm/emitter.ts | 116 ++++++++-- .../compiler/src/backend/llvm/expr-control.ts | 10 +- .../compiler/src/backend/llvm/expr-dynamic.ts | 2 +- .../src/backend/llvm/expr-primitives.ts | 10 +- .../src/backend/llvm/expr-stream-bridges.ts | 39 +++- packages/compiler/src/backend/llvm/publish.ts | 17 +- .../compiler/src/backend/llvm/receivers.ts | 7 +- packages/compiler/src/index.ts | 8 +- packages/compiler/src/native/prepare.ts | 3 +- ...ntract-program-lifetime-references.ts.json | 6 + ...-contract-program-lifetime-workers.ts.json | 6 + packages/runtime/src/scr_alloc.c | 200 ++++++++++++++++++ packages/runtime/src/scr_rc.h | 24 +++ scripts/ci-test-costs.json | 2 + ...36-contract-program-lifetime-references.ts | 195 +++++++++++++++++ .../4637-contract-program-lifetime-workers.ts | 79 +++++++ ...ntract-program-lifetime-references.ts.json | 1 + ...-contract-program-lifetime-workers.ts.json | 1 + .../harness/program-lifetime-workers.test.ts | 48 +++++ 25 files changed, 981 insertions(+), 55 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4636-contract-program-lifetime-references.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4637-contract-program-lifetime-workers.ts.json create mode 100644 tests/corpus/4636-contract-program-lifetime-references.ts create mode 100644 tests/corpus/4637-contract-program-lifetime-workers.ts create mode 100644 tests/harness/corpus-costs/4636-contract-program-lifetime-references.ts.json create mode 100644 tests/harness/corpus-costs/4637-contract-program-lifetime-workers.ts.json create mode 100644 tests/harness/program-lifetime-workers.test.ts diff --git a/docs/content/docs/contracts.mdx b/docs/content/docs/contracts.mdx index d1bfb8cad..5af1cad2f 100644 --- a/docs/content/docs/contracts.mdx +++ b/docs/content/docs/contracts.mdx @@ -349,6 +349,8 @@ 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. + scriptc checks that the promise cannot change what the program computes (SC7008): - the class is the root of its hierarchy, so every value of any class type in the hierarchy is program-lifetime; built-in bases such as `Error`, `EventEmitter` and streams are refused because they hold runtime state that is released with the object; diff --git a/packages/compiler/src/backend/llvm/classes.test.ts b/packages/compiler/src/backend/llvm/classes.test.ts index 94da472d4..2d95e942c 100644 --- a/packages/compiler/src/backend/llvm/classes.test.ts +++ b/packages/compiler/src/backend/llvm/classes.test.ts @@ -1,13 +1,15 @@ import { expect, test } from "vitest"; import { DYN, F64, STRING, VOID, type IrModule } from "../../ir/ir.js"; import { + assignCompactLayouts, buildClassGraph, + classFieldIndex, classIdLoadLines, classMembershipIntervals, emitClassMembershipHelper, type LlClassMeta, } from "./classes.js"; -import { emitLlvmModule } from "./emitter.js"; +import { emitLlvmModule, lowRegionTarget } from "./emitter.js"; import { mangleClassNew, mangleClassReleaseDirect, @@ -196,11 +198,9 @@ test("classes whose trace visits nothing start acyclic in a traced hierarchy", ( }); test("ProgramLifetime classes pack their fields after a 32-bit header", () => { - const node = { kind: "object" as const, className: "Node" }; - const leaf = { kind: "object" as const, className: "Leaf" }; const BOOL = { kind: "bool" as const }; const nodeFields = [ - { name: "parent", type: node }, + { name: "parent", type: STRING }, { name: "flag", type: BOOL }, { name: "weight", type: F64 }, ]; @@ -214,7 +214,7 @@ test("ProgramLifetime classes pack their fields after a 32-bit header", () => { { name: "Leaf", base: "Node", - fields: [...nodeFields, { name: "next", type: leaf }, { name: "mark", type: BOOL }], + fields: [...nodeFields, { name: "next", type: STRING }, { name: "mark", type: BOOL }], methods: [], loc, }, @@ -233,6 +233,105 @@ test("ProgramLifetime classes pack their fields after a 32-bit header", () => { expect(mortal).toContain(`%${mangleClassStruct("Leaf")} = type { i64, ptr, i8, i32, ptr, i8 }`); }); +test("references between ProgramLifetime instances are 32-bit indexes into their region", () => { + const node = { kind: "object" as const, className: "Node" }; + const leaf = { kind: "object" as const, className: "Leaf" }; + const root = { localId: "root", name: "root", type: leaf }; + const nodeFields = [{ name: "parent", type: node }]; + const mod: IrModule = { + irVersion: 17, + sourceFile: loc.file, + entry: "main", + functions: [ + { + name: "main", + params: [root], + returnType: VOID, + locals: [{ id: "root", name: "root", type: leaf, mutable: false }], + body: [ + { + kind: "fieldSet", + obj: { kind: "varRef", localId: "root", type: leaf, loc }, + className: "Leaf", + field: "parent", + value: { + kind: "fieldGet", + obj: { kind: "varRef", localId: "root", type: leaf, loc }, + className: "Leaf", + field: "next", + type: leaf, + loc, + }, + loc, + }, + ], + loc, + }, + ], + classes: [ + { name: "Node", fields: nodeFields, methods: [], loc }, + { + name: "Leaf", + base: "Node", + fields: [...nodeFields, { name: "next", type: leaf }, { name: "label", type: STRING }], + methods: [], + loc, + }, + ], + contracts: { programLifetime: ["Node"] }, + }; + // Linux executables without sanitizers (lowRegionTarget). + const llvm = emitLlvmModule(mod, { pointerBits: 64, objectAudit: false, lowRegion: true }); + // parent and next take 4 bytes each; the string keeps its pointer. + expect(llvm).toContain(`%${mangleClassStruct("Node")} = type { i32, i32 }`); + expect(llvm).toContain(`%${mangleClassStruct("Leaf")} = type { i32, i32, ptr, i32 }`); + // Instances come from the region, reserved below 32 GiB before compiled + // code runs: a bump of the thread's chunk, and the runtime when it is used + // up. + const nw = + new RegExp(`^define internal ptr @${mangleClassNew("Leaf")}\\([^]*?^}`, "m").exec(llvm)?.[0] ?? + ""; + expect(nw).toContain("%plr.end = getelementptr i8, ptr %plr.next"); + expect(nw).toContain("store ptr %plr.end, ptr %plr.c"); + expect(nw).toMatch(/%plr.o = call ptr @scr_plr_alloc\(i64 /); + expect(llvm).toMatch(/call void @scr_init\(\)\n {2}call void @scr_plr_init\(\)/); + // A reference is the instance's address over 8 (0 is NULL): a read + // shifts the loaded word, a write shifts the pointer. + const main = llvm.split(/^define /m).find((fn) => fn.includes("; main\n")) ?? ""; + expect(main).toMatch(/= load i32, ptr %\S+, !tbaa/); + expect(main).toMatch(/= shl nuw nsw i64 %\S+, 3\n\s+%\S+ = inttoptr i64 %\S+ to ptr/); + expect(main).toMatch(/= ptrtoint ptr %\S+ to i64\n\s+%\S+ = lshr i64 %\S+, 3/); + expect(main).toMatch(/store i32 %\S+, ptr %\S+/); + expect(main).not.toContain("select"); + expect(lowRegionTarget("linux", false)).toBe(true); + expect(lowRegionTarget("linux", true)).toBe(false); + expect(lowRegionTarget("darwin", false)).toBe(false); + expect(lowRegionTarget("win32", false)).toBe(false); + // Other targets, 32-bit targets and mortal classes keep pointers. + const elsewhere = emitLlvmModule(mod, { pointerBits: 64, objectAudit: false }); + expect(elsewhere).toContain(`%${mangleClassStruct("Leaf")} = type { i32, ptr, ptr, ptr }`); + expect(elsewhere).not.toContain("scr_plr"); + const llvm32 = emitLlvmModule(mod, { pointerBits: 32, lowRegion: true }); + expect(llvm32).not.toContain("scr_plr"); + const mortal = emitLlvmModule({ ...mod, contracts: {} }, { pointerBits: 64, lowRegion: true }); + expect(mortal).not.toContain("scr_plr"); + // Field accessors that read the storage as a pointer are refused. + const metas = buildClassGraph(mod, new Map()); + assignCompactLayouts( + metas, + () => true, + (cls) => cls.fields.map(() => "ptr"), + (cls, i, isCompact) => { + const t = cls.fields[i]!.type; + return t.kind === "object" && isCompact(t.className); + }, + ); + const leafMeta = metas.get("Leaf")!; + expect(() => classFieldIndex(leafMeta, "next")).toThrow(/holds a 32-bit reference/); + expect(classFieldIndex(leafMeta, "next", "compressed").compressed).toBe(true); + expect(classFieldIndex(leafMeta, "label").compressed).toBe(false); +}); + 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 7ca2216d2..3073bd1bd 100644 --- a/packages/compiler/src/backend/llvm/classes.ts +++ b/packages/compiler/src/backend/llvm/classes.ts @@ -98,6 +98,10 @@ export class LlClassMeta { compactElems: { offset: number; size: number; align: number; type: string; field: number }[] = []; /** Compact classes: each field's GEP index, by its index in def.fields. */ compactSlots: number[] = []; + /** Compact classes: whether each field (by its index in def.fields) holds + * a compact class instance as a 32-bit index (COMPACT_REF) rather than a + * pointer: compactRefLoadLines decodes it, compactRefStoreLines encodes it. */ + compressed: boolean[] = []; constructor(readonly def: IrClassDef) { this.root = this; @@ -395,13 +399,24 @@ export function classEnvironmentIndex(meta: LlClassMeta): number { /** A field's GEP index inside its class struct: rc at 0, the vtable word * at 1 on hierarchy members, then the flattened field list. */ -export function classFieldIndex(meta: LlClassMeta, field: string): { index: number; type: IrType } { +export function classFieldIndex( + meta: LlClassMeta, + field: string, + refs: "pointer" | "compressed" = "pointer", +): { index: number; type: IrType; compressed: boolean } { const idx = meta.def.fields.findIndex((f) => f.name === field); if (idx < 0) throw new InternalCompilerError( `llvm emitter bug: unknown field ${field} on class ${meta.def.name}`, ); - return { index: classFieldSlot(meta, idx), type: meta.def.fields[idx]!.type }; + const compressed = meta.compressed[idx] === true; + // Callers that read or write a field's storage as a pointer must not see + // a compressed one; callers that decode and encode pass "compressed". + if (compressed && refs === "pointer") + throw new InternalCompilerError( + `llvm emitter bug: field ${field} of ${meta.def.name} holds a 32-bit reference`, + ); + return { index: classFieldSlot(meta, idx), type: meta.def.fields[idx]!.type, compressed }; } /** The GEP index of the field at `idx` in `meta.def.fields`. */ @@ -590,6 +605,75 @@ export function compactHeaderWord(meta: LlClassMeta): number { return COMPACT_HEADER_TAG | (meta.hierarchy ? meta.pre + 1 : 0); } +/** Lines that decode the 32-bit reference `idx` (an i32) of a compressed + * field into the pointer `out`. The program-lifetime region lies below + * 32 GiB (LlvmTargetOptions.lowRegion), so a reference is the instance's + * address over 8 and 0 is NULL: one shift, which x86-64 folds into the + * address of the next load. `t` names the temporaries. */ +export function compactRefLoadLines(idx: string, out: string, t: string): string[] { + return [ + ` ${t}.z = zext i32 ${idx} to i64`, + ` ${t}.o = shl nuw nsw i64 ${t}.z, 3`, + ` ${out} = inttoptr i64 ${t}.o to ptr`, + ]; +} + +/** Lines that encode the pointer `ptr` (NULL or a compact class instance) + * as the 32-bit reference `out` (an i32) a compressed field stores. */ +export function compactRefStoreLines(ptr: string, out: string, t: string): string[] { + return [ + ` ${t}.pi = ptrtoint ptr ${ptr} to i64`, + ` ${t}.s = lshr i64 ${t}.pi, 3`, + ` ${out} = trunc i64 ${t}.s to i32`, + ]; +} + +/** The storage type of a compressed field (LlClassMeta.compressed): a + * 32-bit index into the program-lifetime region. */ +export const COMPACT_REF = "i32"; + +/** Lines that allocate `%o`, `size` zeroed bytes in the program-lifetime + * region: a bump of the calling thread's chunk (scr_rc.h ScrPlrChunk, + * thread-local in worker programs), and scr_plr_alloc when the chunk is + * exhausted or the target has no inline allocation. The lines end in an + * open block. */ +function plrAllocLines(host: ClassHost, size: string): string[] { + const S = host.sizeType; + host.declare(`declare ptr @scr_plr_alloc(${S})`); + host.declare(`declare i1 @llvm.expect.i1(i1, i1)`); + if (host.inlineAlloc !== true) return [` %o = call ptr @scr_plr_alloc(${S} ${size})`]; + const chunk: string[] = []; + if (host.threadLocalAlloc === true) { + host.declare(`@scr_plr_chunk = external thread_local global { ptr, ptr }`); + host.declare(`declare nonnull ptr @llvm.threadlocal.address.p0(ptr nonnull)`); + chunk.push(` %plr.c = call ptr @llvm.threadlocal.address.p0(ptr @scr_plr_chunk)`); + } else { + host.declare(`@scr_plr_chunk = external dso_local global { ptr, ptr }`); + chunk.push(` %plr.c = getelementptr inbounds i8, ptr @scr_plr_chunk, i64 0`); + } + // A thread without a chunk has NULL for both, so nothing fits. + return [ + ...chunk, + ` %plr.lp = getelementptr inbounds i8, ptr %plr.c, i64 8`, + ` %plr.next = load ptr, ptr %plr.c`, + ` %plr.lim = load ptr, ptr %plr.lp`, + ` %plr.n7 = add ${S} ${size}, 7`, + ` %plr.n = and ${S} %plr.n7, -8`, + ` %plr.end = getelementptr i8, ptr %plr.next, ${S} %plr.n`, + ` %plr.fits = icmp ule ptr %plr.end, %plr.lim`, + ` %plr.fitsx = call i1 @llvm.expect.i1(i1 %plr.fits, i1 true)`, + ` br i1 %plr.fitsx, label %plr.bump, label %plr.slow`, + `plr.bump:`, + ` store ptr %plr.end, ptr %plr.c`, + ` br label %plr.done`, + `plr.slow:`, + ` %plr.o = call ptr @scr_plr_alloc(${S} ${size})`, + ` br label %plr.done`, + `plr.done:`, + ` %o = phi ptr [ %plr.next, %plr.bump ], [ %plr.o, %plr.slow ]`, + ]; +} + /** Byte size and alignment of a class field's LLVM storage type. */ function fieldStorage(type: string): { size: number; align: number } { switch (type) { @@ -628,7 +712,16 @@ export function assignCompactLayouts( metaMap: ReadonlyMap, compact: (root: LlClassMeta) => boolean, fieldTypes: (cls: IrClassDef) => string[], + compressedRef?: ( + cls: IrClassDef, + field: number, + isCompact: (className: string) => boolean, + ) => boolean, ): void { + const isCompact = (className: string): boolean => { + const target = metaMap.get(className); + return target !== undefined && target.def.runtime !== true && compact(target.root); + }; const byPre = [...metaMap.values()].sort((a, b) => a.pre - b.pre); for (const meta of byPre) { if (meta.def.runtime === true || !compact(meta.root)) continue; @@ -642,7 +735,22 @@ export function assignCompactLayouts( `llvm emitter bug: compact class ${meta.def.name} does not extend its base's layout`, ); const elems = inherited.map((e) => ({ ...e })); - const types = fieldTypes(meta.def); + // A reference to a compact class instance is a 32-bit index into the + // program-lifetime region (compactRefLoadLines); inherited fields keep the + // base's choice. + const compressed = meta.def.fields.map((_, i) => + i < baseCount + ? base!.compressed[i]! + : compressedRef !== undefined && compressedRef(meta.def, i, isCompact), + ); + const types = fieldTypes(meta.def).map((t, i) => { + if (!compressed[i]) return t; + if (t !== "ptr") + throw new InternalCompilerError( + `llvm emitter bug: compressed field ${meta.def.fields[i]!.name} of ${meta.def.name} is stored as ${t}`, + ); + return COMPACT_REF; + }); const own = types .map((type, field) => ({ type, field, ...fieldStorage(type) })) .slice(baseCount) @@ -679,6 +787,7 @@ export function assignCompactLayouts( meta.compact = true; meta.compactElems = elems; meta.compactSlots = slots; + meta.compressed = compressed; } } @@ -705,7 +814,10 @@ function undefFieldInits( if (f.name === "%cause") return; // A nullable-pointer field's zeroed slot already is its unit arm. if (nullable?.get(meta.def.name, f.name)) return; - const { index } = classFieldIndex(meta, f.name); + // Only union and dyn fields get a store here; a compressed field is a + // class reference, which starts NULL. + const { index, compressed } = classFieldIndex(meta, f.name, "compressed"); + if (compressed) return; if (f.type.kind === "union" && host.inlineUnions.classField(meta.def.name, f.name)) { // An inline field starts at the undefined arm's tag with zero bits. const tag = undefinedArmTag(f.type, host.unionsById); @@ -748,6 +860,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)); const typeDefs: string[] = []; const defs: string[] = []; const emitted = (mod.classes ?? []).filter((c) => !c.runtime); @@ -897,13 +1012,17 @@ export function emitClassShapes( const fieldIndex = (i: number): number => classFieldSlot(meta, i); // Teardown, trace and gcFree see each slot's storage type: a nullable // class field holds the instance pointer (NULL for the unit arm), and - // every class retain/release/visit entry point is NULL-tolerant. + // every class retain/release/visit entry point is NULL-tolerant. A + // compressed field refers to a compact instance, which nothing releases + // or traces, so they skip it. const indexedFields = [ - ...ownedFields(cls).map(({ field, i }) => ({ - name: field.name, - type: storedFieldType(cls, field), - index: fieldIndex(i), - })), + ...ownedFields(cls) + .filter(({ i }) => meta.compressed[i] !== true) + .map(({ field, i }) => ({ + name: field.name, + type: storedFieldType(cls, field), + index: fieldIndex(i), + })), ]; const refFields = indexedFields.filter((f) => isRefCounted(f.type)); const tracedFields = traced @@ -1118,6 +1237,11 @@ export function emitClassShapes( if (regions !== null) { nw.push(...regions.newAlloc(cls.name, sizeOf)); defs.push(...regions.classDefinitions(cls, sizeOf)); + } else if (meta.compact && regionRefs) { + // Compressed fields refer to compact instances by their index in the + // program-lifetime region, so every compact instance lives there: + // zeroed, 8-byte aligned and never freed. + nw.push(...plrAllocLines(host, sizeOf)); } else nw.push( ...emitObjectAlloc( diff --git a/packages/compiler/src/backend/llvm/emit-function.ts b/packages/compiler/src/backend/llvm/emit-function.ts index 7bbd3d453..0980925cb 100644 --- a/packages/compiler/src/backend/llvm/emit-function.ts +++ b/packages/compiler/src/backend/llvm/emit-function.ts @@ -153,6 +153,7 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { : new Map(); emitter.integerViews.clear(); emitter.fieldPointerTags.clear(); + emitter.compressedFieldPtrs.clear(); emitter.integerArrayBindings.clear(); emitter.loopArrayBorrows = emitter.debug === null diff --git a/packages/compiler/src/backend/llvm/emit-module.ts b/packages/compiler/src/backend/llvm/emit-module.ts index 5ccf7ccd8..3d9d41072 100644 --- a/packages/compiler/src/backend/llvm/emit-module.ts +++ b/packages/compiler/src/backend/llvm/emit-module.ts @@ -545,6 +545,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()`] : []), `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()`] : []), @@ -837,6 +838,9 @@ export function emitModuleParts(emitter: LlEmitter): string[] { ...(emitter.runtimeAbiMarker ? [` call void @${RUNTIME_ABI_MARKER}()`] : []), ...(emitter.mod.workers ? [` call void @scr_runtime_workers_v8()`] : []), ` 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()`] : []), // 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()`] : []), diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index 85f6c8dd7..d1dc6369b 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -558,7 +558,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { emitter.emitPublishedFieldGuard(obj.name, null, s.field); const { ptr, type, inline } = s.kind === "fieldSet" - ? emitter.classFieldPtr(obj.name, s.className, s.field) + ? 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 ( diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index 0bdbe23b2..0badf4000 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -266,6 +266,8 @@ import { classFieldTypes, classMembershipIntervals, classFieldIndex, + compactRefLoadLines, + compactRefStoreLines, classPreLines, classStructSym, programLifetimeClass, @@ -423,6 +425,20 @@ export interface LlvmTargetOptions { /** Translated WebAssembly memories check bounds explicitly instead of * relying on guard pages (wasm-modules.ts wasmBoundsChecks). */ wasmBoundsChecks?: boolean; + /** The executable can reserve its program-lifetime region below 32 GiB + * (lowRegionTarget): fields that refer to compact class instances then + * store the instance's address over 8 in 32 bits (classes.ts + * compactRefLoadLines). Elsewhere they keep 8-byte pointers. */ + lowRegion?: boolean; +} + +/** LlvmTargetOptions.lowRegion for an executable: Linux targets without + * sanitizers, whose address space below 32 GiB is free (ASan keeps its + * shadow memory there; other systems map their own images and libraries + * there). `platform` is a target platform (`linux`, `darwin`, `win32`, + * `wasi`). */ +export function lowRegionTarget(platform: string, sanitize: boolean): boolean { + return platform === "linux" && !sanitize; } export function emitLlvmModule(input: IrModule, options: LlvmTargetOptions = {}): string { @@ -593,6 +609,13 @@ export class LlEmitter { integerArrayBindings = new Set(); readonly fieldAliasTags = new Map(); readonly fieldPointerTags = new Map(); + /** The field pointers (classFieldPtr) of this function whose fields hold + * 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; /** Native class fields with different property names cannot occupy the * same slot of one object. Inherited views of the same property share a @@ -1507,7 +1530,32 @@ export class LlEmitter { this.classMeta, (root) => programLifetimeClass(this.shapeHost, root) && !root.threadSlot, (cls) => classFieldTypes(this.shapeHost, cls, this.int32Slots), + // Executables whose region lies below 32 GiB hold compact class + // instances there (scr_plr_alloc), so fields referring to one store + // a 32-bit reference: the field's type, the class of a + // `C | undefined` or `C | null` pointer, or the reference arm of a + // nullable pointer field, is a compact class. `C | null | undefined` + // keeps the pointer: its null is a sentinel outside the region. + mod.lib === undefined && options.lowRegion === true + ? (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); + return nullable !== null && isCompact(nullable.arm.className); + } + : undefined, ); + this.usesCompactRefs = [...this.classMeta.values()].some((m) => m.compressed.some(Boolean)); 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 @@ -3217,15 +3265,47 @@ export class LlEmitter { objName: string, className: string, field: string, - ): { ptr: string; type: IrType; inline: boolean } { + refs: "pointer" | "compressed" = "pointer", + ): { ptr: string; type: IrType; inline: boolean; compressed: boolean } { const meta = this.classMetaOf(className); - const { index, type } = classFieldIndex(meta, field); + const { index, type, compressed } = classFieldIndex(meta, field, refs); const p = this.B.tmp(); this.B.line( `${p} = getelementptr inbounds %${classStructSym(className)}, ptr ${objName}, i64 0, i32 ${index}`, ); this.markFieldPointer(p, field); - return { ptr: p, type, inline: this.inlineUnions.classField(className, field) }; + if (compressed) this.compressedFieldPtrs.add(p); + return { ptr: p, type, inline: this.inlineUnions.classField(className, field), compressed }; + } + + /** 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. */ + loadRef(ptr: string, tagged = true): string { + const B = this.B; + const v = B.tmp(); + const tags = tagged ? this.fieldAliasAttachment(ptr) : ""; + if (!this.compressedFieldPtrs.has(ptr)) { + B.line(`${v} = load ptr, ptr ${ptr}${tags}`); + return v; + } + const idx = B.tmp(); + B.line(`${idx} = load i32, ptr ${ptr}${tags}`); + for (const line of compactRefLoadLines(idx, v, `${v}.r`)) B.line(line.trimStart()); + return v; + } + + /** Stores `value` (a pointer) through a field pointer: as is, or encoded + * as the 32-bit reference of a compressed field. */ + storeRef(ptr: string, value: string): void { + const B = this.B; + if (!this.compressedFieldPtrs.has(ptr)) { + B.line(`store ptr ${value}, ptr ${ptr}${this.fieldAliasAttachment(ptr)}`); + return; + } + const idx = B.tmp(); + for (const line of compactRefStoreLines(value, idx, `${idx}.r`)) B.line(line.trimStart()); + B.line(`store i32 ${idx}, ptr ${ptr}${this.fieldAliasAttachment(ptr)}`); } /** The dynamic class's preorder number (borrowed object; the static class @@ -3357,6 +3437,7 @@ export class LlEmitter { const { tag, bits } = loadInlineUnion(B, ptr); return stackUnionBox(B, this.sizeType, tag, bits); } + if (this.compressedFieldPtrs.has(ptr)) return this.loadRef(ptr); const fieldTy = llFieldType(t, false); const raw = B.tmp(); B.line(`${raw} = load ${fieldTy}, ptr ${ptr}${this.fieldAliasAttachment(ptr)}`); @@ -3383,8 +3464,7 @@ export class LlEmitter { replaceField(ptr: string, type: IrType, inline: boolean, v: LlValue): void { if (!inline && isRefCounted(type)) { this.toHeap(v); - const old = this.B.tmp(); - this.B.line(`${old} = load ptr, ptr ${ptr}`); + const old = this.loadRef(ptr, false); this.storeField(ptr, type, v.name, false); this.releaseHeap(old, type); return; @@ -3408,6 +3488,10 @@ export class LlEmitter { storeInlineUnion(B, ptr, tag, bits); return; } + if (this.compressedFieldPtrs.has(ptr)) { + this.storeRef(ptr, value); + return; + } const fieldTy = llFieldType(t, false); if (fieldTy !== "i8") { B.line(`store ${fieldTy} ${value}, ptr ${ptr}${this.fieldAliasAttachment(ptr)}`); @@ -5182,8 +5266,9 @@ export class LlEmitter { : [ { name: f.name, - index: classFieldIndex(meta, f.name).index, + index: classFieldIndex(meta, f.name, "compressed").index, type: this.nullableFields.storageType(className, f.name, f.type), + compressed: classFieldIndex(meta, f.name, "compressed").compressed, }, ], ), @@ -5390,11 +5475,9 @@ export class LlEmitter { emitUnionProjection(e: IrExpr): LlValue { const nullable = this.nullableFieldGet(e); if (!nullable || e.kind !== "fieldGet") return this.emitReadReceiver(e); - const B = this.B; const receiver = this.emitReadReceiver(e.obj); - const { ptr } = this.classFieldPtr(receiver.name, e.className, e.field); - const p = B.tmp(); - B.line(`${p} = load ptr, ptr ${ptr}${this.fieldAliasAttachment(ptr)}`); + const { ptr } = this.classFieldPtr(receiver.name, e.className, e.field, "compressed"); + const p = this.loadRef(ptr); return { name: this.stackNullableBox(p, nullable), type: e.type }; } @@ -5407,9 +5490,8 @@ export class LlEmitter { if (!nullable || e.kind !== "fieldGet") throw new InternalCompilerError("llvm emitter bug: owned nullable stack of non-field"); const receiver = this.emitReadReceiver(e.obj); - const { ptr } = this.classFieldPtr(receiver.name, e.className, e.field); - const p = this.B.tmp(); - this.B.line(`${p} = load ptr, ptr ${ptr}${this.fieldAliasAttachment(ptr)}`); + const { ptr } = this.classFieldPtr(receiver.name, e.className, e.field, "compressed"); + const p = this.loadRef(ptr); const owner = this.own({ name: this.retainFrame(p, nullable.arm), type: nullable.arm }); return { box: this.stackNullableBox(owner.name, nullable), owner }; } @@ -5486,7 +5568,6 @@ export class LlEmitter { nullable: NullableRefField, value: IrExpr, ): void { - const B = this.B; let next: string; if ( value.kind === "unionWrap" && @@ -5509,10 +5590,9 @@ export class LlEmitter { } else { next = this.unionToNullable(this.emitUnionProjection(value).name, nullable); } - const { ptr } = this.classFieldPtr(obj, className, field); - const old = B.tmp(); - B.line(`${old} = load ptr, ptr ${ptr}`); - B.line(`store ptr ${next}, ptr ${ptr}${this.fieldAliasAttachment(ptr)}`); + const { ptr } = this.classFieldPtr(obj, className, field, "compressed"); + const old = this.loadRef(ptr, false); + this.storeRef(ptr, next); this.releaseHeap(old, nullable.arm); } diff --git a/packages/compiler/src/backend/llvm/expr-control.ts b/packages/compiler/src/backend/llvm/expr-control.ts index fd2061aae..242f9997c 100644 --- a/packages/compiler/src/backend/llvm/expr-control.ts +++ b/packages/compiler/src/backend/llvm/expr-control.ts @@ -510,9 +510,13 @@ export function emitOptionalChainReceiver( // pointer itself, through a private stack box when the union's own // representation is boxed (emitUnionProjection's form). const owner = host.emitReadReceiver(e.receiver.obj); - const { ptr } = host.classFieldPtr(owner.name, e.receiver.className, e.receiver.field); - const p = B.tmp(); - B.line(`${p} = load ptr, ptr ${ptr}${host.fieldAliasAttachment(ptr)}`); + const { ptr } = host.classFieldPtr( + owner.name, + e.receiver.className, + e.receiver.field, + "compressed", + ); + const p = host.loadRef(ptr); r = { name: host.nullableUnions.get(def.id) ? p : host.stackNullableBox(p, nullableField), type: e.receiver.type, diff --git a/packages/compiler/src/backend/llvm/expr-dynamic.ts b/packages/compiler/src/backend/llvm/expr-dynamic.ts index 554306f6e..563a900f8 100644 --- a/packages/compiler/src/backend/llvm/expr-dynamic.ts +++ b/packages/compiler/src/backend/llvm/expr-dynamic.ts @@ -344,7 +344,7 @@ export function emitDynamicExpr( const payload = host.unionPeek(u.name, def.id); const { ptr, type, inline } = arm.kind === "object" - ? host.classFieldPtr(payload, arm.className, e.field) + ? host.classFieldPtr(payload, arm.className, e.field, "compressed") : host.recordFieldPtr(payload, arm.shapeId, e.field); const nullable = arm.kind === "object" ? host.nullableFields.get(arm.className, e.field) : null; diff --git a/packages/compiler/src/backend/llvm/expr-primitives.ts b/packages/compiler/src/backend/llvm/expr-primitives.ts index d6a33ceeb..12e488b6d 100644 --- a/packages/compiler/src/backend/llvm/expr-primitives.ts +++ b/packages/compiler/src/backend/llvm/expr-primitives.ts @@ -1064,13 +1064,17 @@ export function emitRecordExpr( switch (e.kind) { case "fieldGet": { const obj = host.emitReadReceiver(e.obj); - const { ptr, type, inline } = host.classFieldPtr(obj.name, e.className, e.field); + const { ptr, type, inline } = host.classFieldPtr( + obj.name, + e.className, + e.field, + "compressed", + ); if (host.int32Slots.isField(e.className, e.field)) return host.loadInt32Field(ptr, e.type); if (inline) return host.own({ name: host.inlineFieldUnion(ptr, type), type: e.type }); const nullable = host.nullableFieldGet(e); if (nullable) { - const p = B.tmp(); - B.line(`${p} = load ptr, ptr ${ptr}${host.fieldAliasAttachment(ptr)}`); + const p = host.loadRef(ptr); return host.own({ name: host.nullableToOwnedUnion(p, nullable), type: e.type }); } const v = host.loadField(ptr, type, false); diff --git a/packages/compiler/src/backend/llvm/expr-stream-bridges.ts b/packages/compiler/src/backend/llvm/expr-stream-bridges.ts index a4f2ed749..a0a0cf24a 100644 --- a/packages/compiler/src/backend/llvm/expr-stream-bridges.ts +++ b/packages/compiler/src/backend/llvm/expr-stream-bridges.ts @@ -20,7 +20,14 @@ import { } from "../../ir/ir.js"; import { mangleFunction, mangleGlobal, mangleRecordStruct } from "../mangle.js"; import { BlockBuilder } from "./blocks.js"; -import { type LlClassMeta, classFieldIndex, classPreLines, classStructSym } from "./classes.js"; +import { + type LlClassMeta, + classFieldIndex, + classPreLines, + classStructSym, + compactRefLoadLines, + compactRefStoreLines, +} from "./classes.js"; import { SCR_ARR_FIELD, llvmCommentText } from "./common.js"; import { FN_ATTRS, @@ -280,7 +287,7 @@ export function streamTypedRefCommitAdapter( const pending = `f${index}_pending`; const store = `f${index}_store`; const after = `f${index}_after`; - const { index: fieldIndex } = classFieldIndex(meta, field.name); + const { index: fieldIndex, compressed } = classFieldIndex(meta, field.name, "compressed"); const int32 = host.int32Slots.isField(t.className, field.name); const inline = host.inlineUnions.classField(t.className, field.name); const fieldTy = int32 ? "i32" : llFieldType(field.type, inline); @@ -335,7 +342,12 @@ export function streamTypedRefCommitAdapter( ` br i1 %${pending}, label %done, label %${store}`, `${store}:`, ` %f${index}_ptr = getelementptr inbounds %${classStructSym(t.className)}, ptr %target, i64 0, i32 ${fieldIndex}`, - ` %f${index}_old = load ${fieldTy}, ptr %f${index}_ptr`, + ...(compressed + ? [ + ` %f${index}_oldidx = load i32, ptr %f${index}_ptr`, + ...compactRefLoadLines(`%f${index}_oldidx`, `%f${index}_old`, `%f${index}_od`), + ] + : [` %f${index}_old = load ${fieldTy}, ptr %f${index}_ptr`]), ); if (int32) { // int32-slots.ts keeps a field int32 only when no dynamic store in @@ -375,7 +387,12 @@ export function streamTypedRefCommitAdapter( ` %f${index}_pay = load ptr, ptr %f${index}_payp`, ` %f${index}_sel = select i1 %f${index}_isref, ptr %f${index}_pay, ptr null`, ` %f${index}_new = call ptr ${rc.retain}(ptr %f${index}_sel)`, - ` store ptr %f${index}_new, ptr %f${index}_ptr`, + ...(compressed + ? [ + ...compactRefStoreLines(`%f${index}_new`, `%f${index}_newidx`, `%f${index}_ne`), + ` store i32 %f${index}_newidx, ptr %f${index}_ptr`, + ] + : [` store ptr %f${index}_new, ptr %f${index}_ptr`]), ` call void @scr_union_release(ptr %${next})`, ` call void ${rc.release}(ptr %f${index}_old)`, ` br label %${after}`, @@ -398,6 +415,11 @@ export function streamTypedRefCommitAdapter( ` %f${index}_stored = zext i1 %${next} to i8`, ` store i8 %f${index}_stored, ptr %f${index}_ptr`, ); + } else if (compressed) { + lines.push( + ...compactRefStoreLines(`%${next}`, `%f${index}_nextidx`, `%f${index}_nx`), + ` store i32 %f${index}_nextidx, ptr %f${index}_ptr`, + ); } else { lines.push(` store ${fieldTy} %${next}, ptr %f${index}_ptr`); } @@ -832,7 +854,7 @@ export function streamTypedRefMaterializeAdapter( B.condBr(present, yes, afterField); B.startBlock(yes); } - const { index } = classFieldIndex(meta, field.name); + const { index, compressed } = classFieldIndex(meta, field.name, "compressed"); const fieldPtr = B.tmp(); let fieldValue = B.tmp(); B.line( @@ -844,7 +866,12 @@ export function streamTypedRefMaterializeAdapter( B.line(`${fieldValue} = sitofp i32 ${raw} to double`); } else if (host.inlineUnions.classField(t.className, field.name)) fieldValue = loadStructField(B, host.sizeType, fieldPtr, field.type, true); - else B.line(`${fieldValue} = load ${llFieldType(field.type, false)}, ptr ${fieldPtr}`); + else if (compressed) { + const idx = B.tmp(); + B.line(`${idx} = load i32, ptr ${fieldPtr}`); + for (const line of compactRefLoadLines(idx, fieldValue, `${fieldValue}.r`)) + B.line(line.trimStart()); + } else B.line(`${fieldValue} = load ${llFieldType(field.type, false)}, ptr ${fieldPtr}`); if (llFieldType(field.type, false) === "i8") { const boolValue = B.tmp(); B.line(`${boolValue} = trunc i8 ${fieldValue} to i1`); diff --git a/packages/compiler/src/backend/llvm/publish.ts b/packages/compiler/src/backend/llvm/publish.ts index bb7e0c8a8..2f45c3cd2 100644 --- a/packages/compiler/src/backend/llvm/publish.ts +++ b/packages/compiler/src/backend/llvm/publish.ts @@ -25,7 +25,7 @@ import type { IrClassDef, IrRecordShape, IrType, IrUnionDef, SrcLoc } from "../. import { mapOf, STRING, typeKey } from "../../ir/ir.js"; import { mangleClassStruct, mangleRecordStruct } from "../mangle.js"; import { FN_ATTRS } from "./shapes.js"; -import { COMPACT_ID_MASK } from "./classes.js"; +import { COMPACT_ID_MASK, compactRefLoadLines } from "./classes.js"; import { shapeTagFn } from "./nullable-unions.js"; import type { InlineUnionFields } from "./inline-unions.js"; import { LlvmUnsupportedError } from "./unsupported.js"; @@ -69,8 +69,10 @@ export interface PublishClassInfo { idInRc: boolean; /** Instances have the 32-bit header (classes.ts LlClassMeta.compact). */ compact: boolean; - /** The class's own and inherited fields: GEP index and storage type. */ - fields: { name: string; index: number; type: IrType }[]; + /** The class's own and inherited fields: GEP index and storage type; + * `compressed` when the field holds a 32-bit reference (classes.ts + * LlClassMeta.compressed), which the walker decodes. */ + fields: { name: string; index: number; type: IrType; compressed?: boolean }[]; } /** scr_pub_mark's object kinds (SCR_PUB_KIND_* in scr_runtime.h), for the RC audit. */ @@ -536,7 +538,7 @@ export class PublishWalkers { head: string, struct: string, traced: boolean, - members: { name: string; index: number; type: IrType }[], + members: PublishClassInfo["fields"], path: string, loc: SrcLoc, classId = false, @@ -559,7 +561,12 @@ export class PublishWalkers { } lines.push( ` %f${n} = getelementptr inbounds %${struct}, ptr %o, i64 0, i32 ${member.index} ; ${llvmComment(member.name)}`, - ` %v${n} = load ptr, ptr %f${n}`, + ...(member.compressed === true + ? [ + ` %v${n}.i = load i32, ptr %f${n}`, + ...compactRefLoadLines(`%v${n}.i`, `%v${n}`, `%v${n}.d`), + ] + : [` %v${n} = load ptr, ptr %f${n}`]), ...this.push(`%v${n}`, fn, `${n}`, this.compactRef(member.type)), ); n++; diff --git a/packages/compiler/src/backend/llvm/receivers.ts b/packages/compiler/src/backend/llvm/receivers.ts index 50b9485a1..67ca17188 100644 --- a/packages/compiler/src/backend/llvm/receivers.ts +++ b/packages/compiler/src/backend/llvm/receivers.ts @@ -118,7 +118,12 @@ export function emitReadReceiver(emitter: LlEmitter, e: IrExpr): LlValue { const { ptr, type, inline } = emitter.recordFieldPtr(receiver.name, e.shapeId, e.field); return { name: emitter.loadRecordField(ptr, type, inline), type: e.type }; } - const { ptr, type, inline } = emitter.classFieldPtr(receiver.name, e.className, e.field); + const { ptr, type, inline } = emitter.classFieldPtr( + receiver.name, + e.className, + e.field, + "compressed", + ); if (emitter.int32Slots.isField(e.className, e.field)) return emitter.loadInt32Field(ptr, e.type); return { name: emitter.loadField(ptr, type, inline), type: e.type }; diff --git a/packages/compiler/src/index.ts b/packages/compiler/src/index.ts index 92ee6b75e..2b216c77d 100644 --- a/packages/compiler/src/index.ts +++ b/packages/compiler/src/index.ts @@ -67,7 +67,11 @@ import { mobileTargetRefusal, resolveCc, } from "./backend/external-c.js"; -import { emitLlvmModuleSource, LlvmUnsupportedError } from "./backend/llvm/emitter.js"; +import { + emitLlvmModuleSource, + LlvmUnsupportedError, + lowRegionTarget, +} from "./backend/llvm/emitter.js"; import { inlineRcOption } from "./backend/llvm/shapes.js"; import { emitNativeArtifact, @@ -782,6 +786,7 @@ async function prepareExecutableInput( wasi: buildPlatform === "wasi", runtimeAbiMarker: outputKind === "obj", objectAudit: opts.sanitize === true, + lowRegion: lowRegionTarget(buildPlatform, opts.sanitize === true), ...(opts.sanitize === true ? { wasmBoundsChecks: true } : {}), ...inlineRcOption(opts.optimization, opts.sanitize === true), }); @@ -848,6 +853,7 @@ async function prepareExecutableInput( wasi: buildPlatform === "wasi", runtimeAbiMarker: useRuntimePack, objectAudit: opts.sanitize === true, + lowRegion: lowRegionTarget(buildPlatform, opts.sanitize === true), ...(opts.sanitize === true ? { wasmBoundsChecks: true } : {}), ...inlineRcOption(opts.optimization, opts.sanitize === true), ...(opts.detachedExit === true ? { detachedExit: true } : {}), diff --git a/packages/compiler/src/native/prepare.ts b/packages/compiler/src/native/prepare.ts index b90760616..6b0a2fea5 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 } from "../backend/llvm/emitter.js"; +import { emitLlvmModule, 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"; @@ -293,6 +293,7 @@ export function prepareNativeExecutable( wasi: toolchain.target.platform === "wasi", runtimeAbiMarker: outputKind === "obj" || outputKind === "exe", objectAudit: options.sanitize === true, + lowRegion: lowRegionTarget(toolchain.target.platform, options.sanitize === true), ...inlineRcOption(options.optimization, options.sanitize === true), ...(options.detachedExit === true && outputKind === "exe" ? { detachedExit: true } : {}), ...(options.optimization === "dev" && !options.strip diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4636-contract-program-lifetime-references.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4636-contract-program-lifetime-references.ts.json new file mode 100644 index 000000000..a503a5aa0 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4636-contract-program-lifetime-references.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/4636-contract-program-lifetime-references.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4637-contract-program-lifetime-workers.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4637-contract-program-lifetime-workers.ts.json new file mode 100644 index 000000000..c5d09c649 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4637-contract-program-lifetime-workers.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/4637-contract-program-lifetime-workers.ts" + ], + "diags": [] +} diff --git a/packages/runtime/src/scr_alloc.c b/packages/runtime/src/scr_alloc.c index 8cf14fb7f..4b29b4b51 100644 --- a/packages/runtime/src/scr_alloc.c +++ b/packages/runtime/src/scr_alloc.c @@ -1983,3 +1983,203 @@ void scr_heap_stats(double *total, double *used) { *total = (double)(held + sys_held); *used = (double)(held - (idle < held ? idle : held) + sys_used); } + +/* ── program-lifetime region ──────────────────────────────────────────── + * Instances of compact classes (llvm/classes.ts LlClassMeta.compact) in + * programs built for Linux without sanitizers live in one address range + * reserved for the whole process below 32 GiB, so a field that holds one + * can store its address over 8 in 32 bits (0 stays NULL). The instances + * are never freed. Each thread carves them from its own chunks of + * SCR_PLR_CHUNK bytes; a chunk is taken from the range with one atomic add. + * Pages are committed by first touch and start zeroed. Its strings are + * arrays rather than literals: programs without compact classes then link + * none of this, where literals would stay in the unit's merged strings. */ +#if defined(__linux__) && SIZE_MAX > UINT32_MAX +#include + +#define SCR_PLR_CHUNK ((size_t)1 << 20) +/* References are 32-bit addresses of 8-byte units, so the range ends by + * SCR_PLR_END. It starts at 4 GiB or above, clear of executables loaded low + * and their heaps; a refused size is halved down to SCR_PLR_MIN. */ +#define SCR_PLR_END ((size_t)32 << 30) +#define SCR_PLR_MIN ((size_t)1 << 30) +/* Past its first SCR_PLR_HUGE_AFTER bytes the range uses transparent huge + * pages, as the allocator's slices do (SCR_SA_HUGE_AFTER): a large heap of + * instances takes 512 times fewer page faults and TLB entries, and a small + * program stays on small pages. */ +#define SCR_PLR_HUGE_AFTER ((size_t)8 << 20) + +static char *scr_plr_base; /* the range's start, once reserved */ +static size_t scr_plr_size; +static size_t scr_plr_top; /* atomic */ +#if defined(SCR_WORKERS) || (defined(SCR_LIB) && defined(SCR_THREAD_INSTANCES)) +_Thread_local ScrPlrChunk scr_plr_chunk; +#else +ScrPlrChunk scr_plr_chunk; +#endif + +/* Reserves `size` bytes at `at` exactly; NULL if refused. */ +static char *scr_plr_map(void *at, size_t size) { + int flags = MAP_PRIVATE | MAP_ANON | MAP_NORESERVE; +#ifdef MAP_FIXED_NOREPLACE + flags |= MAP_FIXED_NOREPLACE; +#endif + char *p = mmap(at, size, PROT_READ | PROT_WRITE, flags, -1, 0); + if (p == MAP_FAILED) return NULL; + if (p != (char *)at) { + /* The system took `at` as a hint only (no MAP_FIXED_NOREPLACE). */ + (void)munmap(p, size); + return NULL; + } + return p; +} + +static __attribute__((noinline)) void scr_plr_reserve(void) { + static char lock; + while (__atomic_test_and_set(&lock, __ATOMIC_ACQUIRE)) { + } + if (!__atomic_load_n(&scr_plr_base, __ATOMIC_ACQUIRE)) { + char *p = NULL; + size_t size = 0; + for (size_t start = (size_t)4 << 30; !p && start <= (size_t)16 << 30; start *= 2) { + size = SCR_PLR_END - start; + while (size >= SCR_PLR_MIN && !(p = scr_plr_map((void *)start, size))) size /= 2; + } + if (p) { +#ifdef MADV_HUGEPAGE + (void)madvise(p + SCR_PLR_HUGE_AFTER, size - SCR_PLR_HUGE_AFTER, MADV_HUGEPAGE); +#endif + scr_plr_size = size; + /* The first chunk is never handed out, so every chunk is + * page-aligned. */ + __atomic_store_n(&scr_plr_top, SCR_PLR_CHUNK, __ATOMIC_RELAXED); + __atomic_store_n(&scr_plr_base, p, __ATOMIC_RELEASE); + } + } + __atomic_clear(&lock, __ATOMIC_RELEASE); + if (!scr_plr_base) { + static const char message[] = + "scriptc: cannot reserve address space below 32 GiB for program-lifetime objects\n"; + scr_trap(message); + } +} + +#ifdef SCR_SA_TRIM +/* A worker whose memory goes back when it exits (scr_sa_park_arena: it + * shared nothing) returns its chunks too, when the thread ends, and later + * chunks reuse them. A thread's chunks are linked through their first two + * words (the next chunk and the chunk's size) from scr_plr_mine; the first + * chunk a thread takes registers scr_plr_thread_end. */ +#define SCR_PLR_LINK 16 +static _Thread_local char *scr_plr_mine; +static pthread_key_t scr_plr_end_key; +static pthread_once_t scr_plr_end_once = PTHREAD_ONCE_INIT; +static pthread_mutex_t scr_plr_free_lock = PTHREAD_MUTEX_INITIALIZER; +static char **scr_plr_free; /* returned chunks of SCR_PLR_CHUNK bytes */ +static size_t scr_plr_nfree, scr_plr_free_cap; + +/* Thread exit, after scr_sa_thread_park decided whether the thread's memory + * goes back. SCR_SA_DISCARD=poison makes the chunks inaccessible instead. */ +static void scr_plr_thread_end(void *unused) { + (void)unused; + char *c = scr_plr_mine; + scr_plr_mine = NULL; + if (!scr_sa_discarded) return; + bool poison = scr_sa_discard_mode() == 2; + size_t returned = 0; + while (c) { + char *next = ((char **)c)[0]; + size_t size = ((size_t *)c)[1]; + returned += size; + if (poison) { + (void)mprotect(c, size, PROT_NONE); + } else { + (void)madvise(c, size, MADV_DONTNEED); /* reads as zero again */ + if (size == SCR_PLR_CHUNK) { + pthread_mutex_lock(&scr_plr_free_lock); + if (scr_plr_nfree == scr_plr_free_cap) { + size_t cap = scr_plr_free_cap ? 2 * scr_plr_free_cap : 64; + char **grown = realloc(scr_plr_free, cap * sizeof *grown); + if (grown) { + scr_plr_free = grown; + scr_plr_free_cap = cap; + } + } + if (scr_plr_nfree < scr_plr_free_cap) scr_plr_free[scr_plr_nfree++] = c; + pthread_mutex_unlock(&scr_plr_free_lock); + } + } + c = next; + } + static const char stats_line[] = "scr_sa: thread returned %zu MB of program-lifetime objects\n"; + const char *stats = getenv("SCR_SA_STATS"); + if (stats && stats[0] == '1') fprintf(stderr, stats_line, returned >> 20); +} + +static void scr_plr_end_key_init(void) { + (void)pthread_key_create(&scr_plr_end_key, scr_plr_thread_end); +} + +/* Records the calling thread's new chunk `p` of `size` bytes. */ +static void scr_plr_own(char *p, size_t size) { + if (!scr_plr_mine) { + (void)pthread_once(&scr_plr_end_once, scr_plr_end_key_init); + (void)pthread_setspecific(scr_plr_end_key, p); + } + ((char **)p)[0] = scr_plr_mine; + ((size_t *)p)[1] = size; + scr_plr_mine = p; +} + +static char *scr_plr_reuse(void) { + char *c = NULL; + pthread_mutex_lock(&scr_plr_free_lock); + if (scr_plr_nfree) c = scr_plr_free[--scr_plr_nfree]; + pthread_mutex_unlock(&scr_plr_free_lock); + return c; +} +#else +#define SCR_PLR_LINK 0 +#endif + +static __attribute__((noinline)) void *scr_plr_refill(size_t n) { + if (!__atomic_load_n(&scr_plr_base, __ATOMIC_ACQUIRE)) scr_plr_reserve(); + size_t need = n + SCR_PLR_LINK; + size_t chunk = + need > SCR_PLR_CHUNK ? (need + SCR_PLR_CHUNK - 1) & ~(SCR_PLR_CHUNK - 1) : SCR_PLR_CHUNK; + char *p = NULL; +#ifdef SCR_SA_TRIM + if (chunk == SCR_PLR_CHUNK) p = scr_plr_reuse(); +#endif + if (!p) { + size_t at = __atomic_fetch_add(&scr_plr_top, chunk, __ATOMIC_RELAXED); + if (at + chunk > scr_plr_size || at + chunk < at) { + static const char message[] = "scriptc: out of address space for program-lifetime objects\n"; + scr_trap(message); + } + p = scr_plr_base + at; + } +#ifdef SCR_SA_TRIM + scr_plr_own(p, chunk); +#endif + scr_plr_chunk.next = p + SCR_PLR_LINK + n; + scr_plr_chunk.limit = p + chunk; + return p + SCR_PLR_LINK; +} + +/* Called before compiled code runs (emitted main), so the region exists + * before any reference into it does. */ +void scr_plr_init(void) { + if (!__atomic_load_n(&scr_plr_base, __ATOMIC_ACQUIRE)) scr_plr_reserve(); +} + +void *scr_plr_alloc(size_t n) { + n = (n + 7) & ~(size_t)7; + char *p = scr_plr_chunk.next; + if (p && n <= (size_t)(scr_plr_chunk.limit - p)) { + scr_plr_chunk.next = p + n; + return p; + } + return scr_plr_refill(n); +} +#endif diff --git a/packages/runtime/src/scr_rc.h b/packages/runtime/src/scr_rc.h index 892531965..93fdd7946 100644 --- a/packages/runtime/src/scr_rc.h +++ b/packages/runtime/src/scr_rc.h @@ -308,6 +308,30 @@ void scr_cyc_free(void *obj); /* frees the block, header included */ void *scr_mem_realloc(void *p, size_t n); void *scr_rt_calloc(size_t n); /* emitted-code entry points */ +#if defined(__linux__) && SIZE_MAX > UINT32_MAX +/* The program-lifetime region (scr_alloc.c): compact class instances of + * programs built for Linux without sanitizers (llvm/emitter.ts + * lowRegionTarget), which are never freed, at 8-byte aligned addresses below + * 32 GiB, so their fields can hold address >> 3 in 32 bits (0 is NULL). + * scr_plr_init reserves it before compiled code runs; scr_plr_alloc returns + * zeroed memory. */ +void scr_plr_init(void); +void *scr_plr_alloc(size_t n); +/* The calling script thread's part of the region: emitted allocation fast + * paths take [next, limit) in 8-byte multiples and call scr_plr_alloc when + * it is exhausted (llvm/classes.ts addresses both fields). */ +typedef struct ScrPlrChunk { + char *next; + char *limit; +} ScrPlrChunk; +#if defined(SCR_WORKERS) || (defined(SCR_LIB) && defined(SCR_THREAD_INSTANCES)) +extern _Thread_local ScrPlrChunk scr_plr_chunk; +#else +extern ScrPlrChunk scr_plr_chunk; +#endif +_Static_assert(offsetof(ScrPlrChunk, next) == 0 && offsetof(ScrPlrChunk, limit) == 8, + "llvm/classes.ts addresses ScrPlrChunk fields at these offsets"); +#endif void scr_rt_free(void *p); /* Asks the allocator's pre-fault helper (scr_alloc.c) to fault the pages * of [lo, hi), aligned to 256 KiB, in ahead of use; builds without the diff --git a/scripts/ci-test-costs.json b/scripts/ci-test-costs.json index 949e80dc8..4c4964579 100644 --- a/scripts/ci-test-costs.json +++ b/scripts/ci-test-costs.json @@ -364,6 +364,7 @@ "tests/harness/oci-manifest.test.ts": 3, "tests/harness/opaque-class-view.test.ts": 1743, "tests/harness/process-argv.test.ts": 1923, + "tests/harness/program-lifetime-workers.test.ts": 4200, "tests/harness/project-config.test.ts": 71955, "tests/harness/provenance.test.ts": 3971, "tests/harness/regex.test.ts": 4073, @@ -781,6 +782,7 @@ "tests/harness/oci-manifest.test.ts": 3, "tests/harness/opaque-class-view.test.ts": 2545, "tests/harness/process-argv.test.ts": 2583, + "tests/harness/program-lifetime-workers.test.ts": 5, "tests/harness/project-config.test.ts": 162430, "tests/harness/provenance.test.ts": 3734, "tests/harness/publish-leaks.test.ts": 29487, diff --git a/tests/corpus/4636-contract-program-lifetime-references.ts b/tests/corpus/4636-contract-program-lifetime-references.ts new file mode 100644 index 000000000..1639f640e --- /dev/null +++ b/tests/corpus/4636-contract-program-lifetime-references.ts @@ -0,0 +1,195 @@ +import type { ProgramLifetime } from "@scriptc/types"; + +// ProgramLifetime classes that refer to each other through fields: plain, +// optional (undefined) and nullable (null) references, chains and cycles, +// references inherited from a base class and added by subclasses, beside +// fields of every other kind. Reads, writes, compound and logical +// assignment, optional chaining, identity, Map and Set keys, closures, +// inspection, JSON and unknown values see the same objects. + +abstract class Item implements ProgramLifetime { + readonly id: number; + next: Item | undefined = undefined; + owner: Group | null = null; + label: string; + constructor(id: number, label: string) { + this.id = id; + this.label = label; + } + abstract describe(): string; +} + +class Leaf extends Item { + weight = 1; + twin: Leaf | undefined = undefined; + describe(): string { + return `Leaf(${this.id}:${this.label}, w=${this.weight}, twin=${this.twin?.id ?? "-"})`; + } +} + +class Group extends Item { + first: Item | undefined = undefined; + last: Item | undefined = undefined; + readonly root: Root; + count = 0; + flagged = false; + constructor(id: number, label: string, root: Root) { + super(id, label); + this.root = root; + } + add(item: Item): void { + item.owner = this; + if (this.last === undefined) this.first = item; + else this.last.next = item; + this.last = item; + this.count++; + } + describe(): string { + const parts: string[] = []; + for (let at = this.first; at !== undefined; at = at.next) parts.push(at.describe()); + return `Group(${this.id}:${this.label} [${parts.join(", ")}])`; + } +} + +class Root implements ProgramLifetime { + readonly name: string; + top: Group | undefined = undefined; + self: Root; + readonly groups: Group[] = []; + readonly byLabel = new Map(); + constructor(name: string) { + this.name = name; + this.self = this; + } +} + +class Pair implements ProgramLifetime { + left: Pair | undefined; + right: Pair | null; + readonly tag: string; + constructor(left: Pair | undefined, right: Pair | null, tag: string) { + this.left = left; + this.right = right; + this.tag = tag; + } +} + +// A mortal class holding program-lifetime references. +class Cursor { + at: Item | undefined; + steps = 0; + constructor(at: Item | undefined) { + this.at = at; + } + advance(): boolean { + if (this.at === undefined) return false; + this.at = this.at.next; + this.steps++; + return this.at !== undefined; + } +} + +const root = new Root("root"); +let id = 0; +for (let g = 0; g < 3; g++) { + const group = new Group(id++, `g${g}`, root); + root.groups.push(group); + root.byLabel.set(group.label, group); + for (let i = 0; i < 3 + g; i++) { + const leaf = new Leaf(id++, `l${g}.${i}`); + leaf.weight = g * 10 + i; + group.add(leaf); + root.byLabel.set(leaf.label, leaf); + } +} +root.top = root.groups[0]; +root.groups[0]!.add(root.groups[1]!); +root.groups[1]!.add(root.groups[2]!); + +console.log(root.top?.describe()); +console.log(root.self === root, root.self.self.name, root.top?.root === root); + +// Reads through chains and the owner back references. +const deep = root.byLabel.get("l2.4"); +console.log(deep?.owner?.owner?.owner?.label, deep?.owner?.root.name, deep?.next?.id ?? "end"); +let hops = 0; +for (let at: Item | null = deep ?? null; at !== null; at = at.owner) hops++; +console.log("hops", hops); + +// Writes: replace, clear and relink. +const g1 = root.groups[1]!; +const firstOfG1 = g1.first!; +g1.first = firstOfG1.next; +firstOfG1.next = undefined; +firstOfG1.owner = null; +console.log(g1.describe()); +console.log(firstOfG1.owner === null, firstOfG1.next === undefined, firstOfG1.describe()); + +// Logical and conditional assignment. +const twins: Leaf[] = []; +for (const label of ["l0.0", "l0.1", "l0.2"]) { + const leaf = root.byLabel.get(label); + if (leaf instanceof Leaf) twins.push(leaf); +} +twins[0]!.twin ??= twins[1]; +twins[0]!.twin ??= twins[2]; +twins[1]!.twin ||= twins[0]; +twins[2]!.twin = twins[2]!.twin ?? twins[2]; +twins[2]!.twin &&= twins[1]; +console.log(twins.map((t) => t.describe()).join(" | ")); + +// Identity: Map and Set keys, ===, and arrays of references. +const seen = new Set(); +const visits = new Map(); +for (let round = 0; round < 3; round++) { + for (let at = root.groups[0]!.first; at !== undefined; at = at.next) { + seen.add(at); + visits.set(at, (visits.get(at) ?? 0) + 1); + } +} +console.log(seen.size, [...visits.values()].join(","), seen.has(root.groups[1]!), seen.has(firstOfG1)); +console.log(root.groups.indexOf(g1), root.groups.some((g) => g === firstOfG1)); + +// A mortal cursor and closures that capture program-lifetime objects. +const cursor = new Cursor(root.groups[2]!.first); +while (cursor.advance()) {} +console.log("steps", cursor.steps, cursor.at === undefined); +const readers: (() => string)[] = []; +for (const g of root.groups) readers.push(() => g.last?.label ?? "none"); +root.groups[2]!.last = root.groups[2]!.first; +console.log(readers.map((r) => r()).join(",")); + +// A cycle through null and undefined arms. +const a = new Pair(undefined, null, "a"); +const b = new Pair(a, null, "b"); +a.right = b; +a.left = a; +const c = new Pair(b, a, "c"); +console.log(c.left?.left?.right?.tag, c.right?.left?.tag, b.right, a.left === a); +const pairs = [a, b, c]; +pairs.sort((x, y) => (x.right?.tag ?? "").localeCompare(y.right?.tag ?? "")); +console.log(pairs.map((p) => `${p.tag}<${p.left?.tag ?? "u"},${p.right?.tag ?? "n"}>`).join(" ")); + +// Inspection, JSON and references boxed into unknown. +const solo = new Leaf(100, "solo"); +const other = new Leaf(101, "other"); +solo.twin = other; +console.log(solo); +console.log(JSON.stringify(other)); +console.log(JSON.stringify(new Pair(new Pair(undefined, null, "inner"), null, "outer"))); +console.log(Object.keys(solo).join(",")); +const boxed: unknown[] = [solo, solo.twin, solo.next, solo.owner]; +console.log(boxed.map((v) => typeof v).join(","), boxed[0] === solo, boxed[1] === other); +console.log(boxed.indexOf(other), boxed.includes(undefined), boxed.includes(null)); + +// Many objects with references to their neighbours. +let chain: Leaf | undefined = undefined; +let total = 0; +for (let i = 0; i < 20000; i++) { + const leaf: Leaf = new Leaf(i, "n"); + leaf.twin = chain; + leaf.weight = i % 7; + chain = leaf; +} +for (let at = chain; at !== undefined; at = at.twin) total += at.weight; +console.log("chain", total, chain?.twin?.twin?.id); diff --git a/tests/corpus/4637-contract-program-lifetime-workers.ts b/tests/corpus/4637-contract-program-lifetime-workers.ts new file mode 100644 index 000000000..bccdc240f --- /dev/null +++ b/tests/corpus/4637-contract-program-lifetime-workers.ts @@ -0,0 +1,79 @@ +import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads"; +import type { ProgramLifetime } from "@scriptc/types"; + +// Waves of workers that each build a graph of ProgramLifetime instances +// referring to each other, post a checksum of it and exit without sharing +// anything. scriptc never frees such instances while the worker runs; on +// Linux their memory goes back after the worker exits, like the rest of +// its memory, and later workers reuse it. + +class Item implements ProgramLifetime { + readonly id: number; + next: Item | undefined = undefined; + owner: Group | undefined = undefined; + constructor(id: number) { + this.id = id; + } +} + +class Group implements ProgramLifetime { + readonly name: string; + first: Item | undefined = undefined; + previous: Group | undefined = undefined; + count = 0; + constructor(name: string) { + this.name = name; + } + add(item: Item): void { + item.owner = this; + item.next = this.first; + this.first = item; + this.count++; + } +} + +function build(seed: number, groups: number, items: number): number { + let last: Group | undefined = undefined; + for (let g = 0; g < groups; g++) { + const group: Group = new Group(`g${seed}.${g}`); + group.previous = last; + for (let i = 0; i < items; i++) group.add(new Item(seed * 1000003 + g * items + i)); + last = group; + } + let sum = 0; + for (let group = last; group !== undefined; group = group.previous) { + for (let item = group.first; item !== undefined; item = item.next) { + if (item.owner === group) sum = (sum + item.id * (group.count % 97)) % 1000000007; + } + } + return sum; +} + +function runWorker(seed: number): Promise { + return new Promise((resolve, reject) => { + const worker = new Worker(new URL(import.meta.url), { workerData: seed }); + let sum = -1; + worker.on("message", (value: number) => { + sum = value; + }); + worker.on("error", reject); + worker.on("exit", () => resolve(sum)); + }); +} + +async function main(): Promise { + for (let wave = 0; wave < 3; wave++) { + const first = runWorker(wave * 2); + const second = runWorker(wave * 2 + 1); + console.log(`wave ${wave}: ${await first} ${await second}`); + } + // The workers' memory goes back shortly after the last one exits. + await new Promise((resolve) => setTimeout(resolve, 300)); + console.log("main", build(99, 4, 1000)); +} + +if (isMainThread) { + void main(); +} else { + parentPort!.postMessage(build(workerData as number, 50, 4000)); +} diff --git a/tests/harness/corpus-costs/4636-contract-program-lifetime-references.ts.json b/tests/harness/corpus-costs/4636-contract-program-lifetime-references.ts.json new file mode 100644 index 000000000..93afb36c0 --- /dev/null +++ b/tests/harness/corpus-costs/4636-contract-program-lifetime-references.ts.json @@ -0,0 +1 @@ +{ "plain": 4300, "san": 7900 } diff --git a/tests/harness/corpus-costs/4637-contract-program-lifetime-workers.ts.json b/tests/harness/corpus-costs/4637-contract-program-lifetime-workers.ts.json new file mode 100644 index 000000000..35b1a9df3 --- /dev/null +++ b/tests/harness/corpus-costs/4637-contract-program-lifetime-workers.ts.json @@ -0,0 +1 @@ +{ "plain": 2400, "san": 4000 } diff --git a/tests/harness/program-lifetime-workers.test.ts b/tests/harness/program-lifetime-workers.test.ts new file mode 100644 index 000000000..8172fbcde --- /dev/null +++ b/tests/harness/program-lifetime-workers.test.ts @@ -0,0 +1,48 @@ +/* ProgramLifetime instances that a worker creates are never freed while it + * runs, but on Linux they go back with the rest of its memory when it exits + * without sharing anything. The corpus program pins Node.js parity; this + * suite runs it with the allocator's statistics (SCR_SA_STATS=1) and checks + * that each discarded worker returned its program-lifetime objects. Under + * SCRIPTC_SAN=1 the runtime keeps every worker's memory, so the check does + * not apply. */ +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"; +import { compile } from "@scriptc/compiler"; + +const exec = promisify(execFile); +const program = join(import.meta.dirname, "../corpus/4637-contract-program-lifetime-workers.ts"); +const sanitize = process.env["SCRIPTC_SAN"] === "1"; + +test.skipIf(process.platform !== "linux" || sanitize)( + "workers that exit without sharing return their ProgramLifetime instances", + { timeout: 240_000 }, + async () => { + const outDir = await mkdtemp(join(tmpdir(), "scriptc-program-lifetime-workers-")); + try { + const result = await compile(program, { + backend: "llvm", + outDir, + outPath: join(outDir, "program"), + }); + expect(result.ok, JSON.stringify(result.diagnostics)).toBe(true); + if (!result.ok) return; + const { stdout, stderr } = await exec(result.binaryPath, [], { + env: { ...process.env, SCR_SA_STATS: "1", SCR_SA_DISCARD_DELAY_MS: "0" }, + timeout: 120_000, + }); + expect(stdout).toContain("wave 2: "); + // One line per discarded worker; each built 200,000 items in 50 groups. + const returned = [...stderr.matchAll(/(\d+) MB of program-lifetime objects/g)].map((m) => + Number(m[1]), + ); + expect(returned.length).toBeGreaterThan(0); + for (const mb of returned) expect(mb).toBeGreaterThanOrEqual(4); + } finally { + await rm(outDir, { recursive: true, force: true }); + } + }, +); From 5bdc3be385c8c6e222a229ce9735ab372f8842cf Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 23:25:48 -0500 Subject: [PATCH 006/102] Name function expressions by their source names in SC6101 and skip type names and generated helpers --- docs/content/docs/coverage.mdx | 2 +- .../src/frontend/lowering/dynamic-tier.ts | 57 ++++++++++++++++--- .../dynamic-tier/function-names.js | 32 +++++++++++ .../dynamic-tier/typed-hot.ts | 22 ++++++- .../coverage-fixtures/dynamic-tier/unnamed.ts | 41 +++++++++++++ tests/harness/coverage.test.ts | 24 +++++++- 6 files changed, 162 insertions(+), 16 deletions(-) create mode 100644 tests/coverage-fixtures/dynamic-tier/function-names.js create mode 100644 tests/coverage-fixtures/dynamic-tier/unnamed.ts diff --git a/docs/content/docs/coverage.mdx b/docs/content/docs/coverage.mdx index d2fc345ad..ae36f736d 100644 --- a/docs/content/docs/coverage.mdx +++ b/docs/content/docs/coverage.mdx @@ -79,7 +79,7 @@ The program compiled. Adding types to these functions lets scriptc compile them Without a profile, a dynamic-tier function counts as likely to run often when a dynamic operation runs on every iteration of one of its loops (a `for` loop's initializer and a `for...of` loop's iterable run once), when a loop calls it, or when it calls itself. A function is named only when its source says why its values are untyped: a value typed `any` (for a `for...of` variable, the value it iterates), an untyped `JSON.parse` result, or an untyped JavaScript file. Dynamic code that runs once, such as setup code that reads an `any` configuration, is not reported, and neither are functions that are dynamic for an operation with no static lowering, which more types would not change. -The warning names at most five functions, most likely to run often first, and gives the total. Dynamic-tier code in npm packages is summarized on one line with each package's function count. A build that comes from the cache repeats the warning. `--no-dynamic-tier-warning` leaves it out, and `--fail-on=dynamic` fails a coverage run on it. +The warning names at most five functions, most likely to run often first, and gives the total. A function expression is named by its own name, else by the variable, property or class field it is assigned to, else as `anonymous function`. Dynamic-tier code in npm packages is summarized on one line with each package's function count. A build that comes from the cache repeats the warning. `--no-dynamic-tier-warning` leaves it out, and `--fail-on=dynamic` fails a coverage run on it. ## Diagnostic codes diff --git a/packages/compiler/src/frontend/lowering/dynamic-tier.ts b/packages/compiler/src/frontend/lowering/dynamic-tier.ts index 72cba9942..0293f9ab7 100644 --- a/packages/compiler/src/frontend/lowering/dynamic-tier.ts +++ b/packages/compiler/src/frontend/lowering/dynamic-tier.ts @@ -172,10 +172,20 @@ function isJsonParse(node: ts.Node | undefined): boolean { ); } +/** Bindings that hold a value: variables, parameters and properties (not + * types, classes or functions, whose names an operand may also mention). */ +const VALUE_BINDING = + ts.SymbolFlags.FunctionScopedVariable | + ts.SymbolFlags.BlockScopedVariable | + ts.SymbolFlags.Property; + /** Why an identifier holds a value without a static type, or null. */ function identifierCause(lowerer: Lowerer, id: ts.Identifier, depth = 0): UntypedCause | null { - const symbol = lowerer.checker.getSymbolAtLocation(id); - const decl = symbol?.declarations?.[0]; + let symbol = lowerer.checker.getSymbolAtLocation(id); + if (symbol !== undefined && (symbol.flags & ts.SymbolFlags.Alias) !== 0) + symbol = lowerer.checker.getAliasedSymbol(symbol); + if (symbol === undefined || (symbol.flags & VALUE_BINDING) === 0) return null; + const decl = symbol.declarations?.[0]; // An unannotated `for (const item of items)` variable: name `items`. if ( depth < 4 && @@ -241,6 +251,9 @@ function causeOf(lowerer: Lowerer, sites: readonly { loc: SrcLoc }[]): UntypedCa return null; } +/** Generated functions (see scanDynamicTier), after any module prefix. */ +const GENERATED = /^%*(?:m\d+\.)?%*(?:dyn|caught|init)\./; + /** The likely-hot dynamic-tier functions of `module` (see the header). */ export function scanDynamicTier(lowerer: Lowerer, module: IrModule): DynamicTierReport { const facts = new Map(); @@ -255,9 +268,9 @@ export function scanDynamicTier(lowerer: Lowerer, module: IrModule): DynamicTier const packages = new Map(); for (const fn of module.functions) { // Generated `%dyn.*` helpers are dynamic operations lowered out of line, - // and `%init.*` is a module's top level: neither is a function to name. - if (fn.tier !== "dynamic" || fn.name.startsWith("%dyn.") || fn.name.startsWith("%init.")) - continue; + // `%caught.*` helpers test caught values, and `%init.*` is a module's top + // level: none is a function to name. + if (fn.tier !== "dynamic" || GENERATED.test(fn.name)) continue; if (isNodeModulesPath(fn.loc.file)) { const name = packageOf(fn.loc.file); packages.set(name, (packages.get(name) ?? 0) + 1); @@ -300,9 +313,35 @@ export function scanDynamicTier(lowerer: Lowerer, module: IrModule): DynamicTier }; } -/** `%%m144.Session.finish` → `Session.finish`, `m163.find` → `find`. */ -function displayName(name: string): string { - return name.replace(/^%+/, "").replace(/^m\d+\./, ""); +/** The name the source binds a function expression to (`totals` in + * `const totals = (rows) => ...`), or null. */ +function boundName(lowerer: Lowerer, loc: SrcLoc): string | null { + const sf = lowerer.program.getSourceFile(loc.file); + if (sf === undefined) return null; + const parent = nodeAt(sf, loc.start, loc.end).parent; + if ( + parent !== undefined && + (ts.isVariableDeclaration(parent) || + ts.isPropertyAssignment(parent) || + ts.isPropertyDeclaration(parent)) && + ts.isIdentifier(parent.name) + ) + return parent.name.text; + return 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 displayName(lowerer: Lowerer, f: HotDynamicFunction): string { + const plain = f.name + .replace(/^%+/, "") + .replace(/^m\d+\./, "") + .replace(/^%+/, ""); + const lambda = /^fn\d+(?:_(.+))?$/.exec(plain); + if (lambda === null) return plain; + return lambda[1] ?? boundName(lowerer, f.loc) ?? "anonymous function"; } /** SC6101 for the program lowering produced, or null (see the header). @@ -322,7 +361,7 @@ export function dynamicTierWarning( }; return dynamicTierDiag( report.hot.map((f) => ({ - name: displayName(f.name), + name: displayName(lowerer, f), where: where(f.loc), cause: f.cause, hot: f.hot, diff --git a/tests/coverage-fixtures/dynamic-tier/function-names.js b/tests/coverage-fixtures/dynamic-tier/function-names.js new file mode 100644 index 000000000..3d6ab6807 --- /dev/null +++ b/tests/coverage-fixtures/dynamic-tier/function-names.js @@ -0,0 +1,32 @@ +// Function expressions in an untyped JavaScript file: SC6101 names each one +// by its own name, else by the class field, property or variable it is +// assigned to, else as an anonymous function. +class Totals { + sum = (rows) => { + let s = 0; + for (let i = 0; i < rows.length; i++) s += rows[i].n; + return s; + }; +} + +const ops = { + count: (rows) => { + let c = 0; + for (let i = 0; i < rows.length; i++) if (rows[i].n > 1) c++; + return c; + }, +}; + +const named = function scale(rows) { + let s = 0; + for (let i = 0; i < rows.length; i++) s += rows[i].n * 2; + return s; +}; + +const rows = [{ n: 1 }, { n: 2 }]; +const results = [rows].map((list) => { + let s = 0; + for (let i = 0; i < list.length; i++) s += list[i].n; + return s; +}); +console.log(new Totals().sum(rows), ops.count(rows), named(rows), results[0]); diff --git a/tests/coverage-fixtures/dynamic-tier/typed-hot.ts b/tests/coverage-fixtures/dynamic-tier/typed-hot.ts index e72a7ca7a..804170238 100644 --- a/tests/coverage-fixtures/dynamic-tier/typed-hot.ts +++ b/tests/coverage-fixtures/dynamic-tier/typed-hot.ts @@ -1,5 +1,7 @@ -// TypeScript functions that loop over untyped values: an `any` parameter -// and an untyped JSON.parse result (SC6101 names both). +// TypeScript functions that loop over untyped values: an `any` parameter, +// an untyped JSON.parse result and an arrow function's `any` rows (SC6101 +// names all three, the arrow by the name it is bound to). A cast to an +// alias of `any` blames the untyped value it produces, not the alias. function regionTotals(items: any): Map { const out = new Map(); for (const item of items) out.set(item.region, (out.get(item.region) ?? 0) + item.amount); @@ -13,9 +15,23 @@ function countRegions(text: string): number { return n; } +const weights = (rows: any): number => { + let sum = 0; + for (let i = 0; i < rows.length; i++) sum += rows[i].amount; + return sum; +}; + +type Loose = any; + +function entryCount(value: unknown): number { + let n = 0; + for (const key of value as Loose) if (key !== "") n++; + return n; +} + const rows = [ { amount: 3, region: "eu" }, { amount: 4, region: "us" }, ]; for (const [region, total] of regionTotals(rows)) console.log(region, total); -console.log(countRegions(JSON.stringify(rows))); +console.log(countRegions(JSON.stringify(rows)), weights(rows), entryCount(["a", ""])); diff --git a/tests/coverage-fixtures/dynamic-tier/unnamed.ts b/tests/coverage-fixtures/dynamic-tier/unnamed.ts new file mode 100644 index 000000000..bdc53d81f --- /dev/null +++ b/tests/coverage-fixtures/dynamic-tier/unnamed.ts @@ -0,0 +1,41 @@ +// Dynamic loops that SC6101 does not name. `readEntries` loops over +// `unknown` values: the type name `Record` in its cast is not an untyped +// value. `readAll` catches into `Error` while a subclass of `Error` crosses +// into an `any` value, so its catch clause calls a generated check helper, +// which is not a source function. +function parse(text: string): Record | null { + const value: unknown = JSON.parse(text); + return value !== null && typeof value === "object" ? (value as Record) : null; +} + +function readEntries(text: string): Map { + const out = new Map(); + const entries = parse(text)?.["entries"]; + if (entries === null || typeof entries !== "object") return out; + for (const [name, raw] of Object.entries(entries as Record)) { + if (raw === null || typeof raw !== "object") continue; + const e = raw as { dir?: unknown; label?: unknown }; + if (typeof e.dir !== "string") continue; + out.set(name, typeof e.label === "string" ? `${e.dir}:${e.label}` : e.dir); + } + return out; +} + +class ReadError extends Error {} + +function readAll(texts: string[]): string[] { + const out: string[] = []; + for (const text of texts) { + try { + if (text === "") throw new ReadError("empty"); + out.push(text); + } catch (e) { + out.push(`cannot read: ${(e as Error).message}`); + } + } + return out; +} + +const box: any = { error: new ReadError("boxed") }; +console.log(readEntries('{"entries": {"a": {"dir": "x", "label": "y"}}}').size); +console.log(readAll(["one", ""]).join(", "), box.error.message); diff --git a/tests/harness/coverage.test.ts b/tests/harness/coverage.test.ts index ca62352b1..57ac7187c 100644 --- a/tests/harness/coverage.test.ts +++ b/tests/harness/coverage.test.ts @@ -133,9 +133,11 @@ test("likely-hot functions with untyped values report as a performance warning", test("the performance warning names the untyped value of each function", () => { const { coverage } = analyze(fixture("dynamic-tier/typed-hot.ts")); expect(coverage.performance?.[0]?.message.split("\n")).toEqual([ - "2 functions that likely run often use untyped values, which runs slower than typed code:", - " regionTotals (typed-hot.ts:3): `items` is `any`, in a loop", - " countRegions (typed-hot.ts:9): `parsed` holds an untyped `JSON.parse` result, in a loop", + "4 functions that likely run often use untyped values, which runs slower than typed code:", + " regionTotals (typed-hot.ts:5): `items` is `any`, in a loop", + " entryCount (typed-hot.ts:26): `key` is `any`, in a loop", + " countRegions (typed-hot.ts:11): `parsed` holds an untyped `JSON.parse` result, in a loop", + " weights (typed-hot.ts:18): `rows` is `any`, in a loop", ]); }); @@ -146,6 +148,22 @@ test("untyped setup code that runs once reports no performance warning", () => { expect(coveragePasses(coverage, "dynamic")).toBe(true); }); +test("the performance warning names function expressions as the source does", () => { + const { coverage } = analyze(fixture("dynamic-tier/function-names.js")); + expect(coverage.performance?.[0]?.message.split("\n").slice(1)).toEqual([ + " sum (function-names.js:5): untyped JavaScript file, in a loop", + " count (function-names.js:13): untyped JavaScript file, in a loop", + " scale (function-names.js:20): untyped JavaScript file, in a loop", + " anonymous function (function-names.js:27): untyped JavaScript file, in a loop", + ]); +}); + +test("the performance warning names neither type names nor generated helpers", () => { + const { coverage } = analyze(fixture("dynamic-tier/unnamed.ts")); + expect(coverage.diagnostics).toEqual([]); + expect(coverage.performance).toBeUndefined(); +}); + test("dynamic-tier code in npm packages is summarized by package", () => { const { coverage } = analyze(fixture("dynamic-tier/package/main.ts")); expect(coverage.performance?.[0]?.message.split("\n")).toEqual([ From 61f1329b323cefdb7849ea17c7a2292849c2f6e7 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 23:26:29 -0500 Subject: [PATCH 007/102] Name lowered helpers and closures independently of lowering order Lowering named helpers by the size of their registry at first use (%union.retag.N, %arr.map.N, ...), lifted closures and optional-chain locals by compiler-wide counters (%fnN, chain.N), generic instances by their instance count, and records and unions by creation order (rN, uN). Class expressions, mixin instances, function-local generics, non-exported namespace segments and some module globals carried the byte offset of their declaration. A name therefore depended on which unit lowered first and on the positions of unrelated code. Helpers, instances, records and unions are now named by a hash of the key they are interned by (keyedHelperName), and recursive records and unions by their printed type and declaration. Closures and optional-chain ids are named by their lowering unit, their structural position and a count per key within the unit. Offset-based names use the structural position: the chain of enclosing named declarations and the node's ordinal among same-kind nodes inside the nearest one, so an edit outside that declaration leaves the name unchanged. Two different keys with the same name throw an InternalCompilerError. The module lists its records and unions by id. The generated program is unchanged apart from these names and that order, and test:lowering-order now fails on any name difference. --- package.json | 2 +- packages/compiler/src/contracts/check.ts | 3 +- .../lowering/array-indexed-mutation.ts | 3 +- .../src/frontend/lowering/array-values.ts | 5 +- .../frontend/lowering/builtins/arguments.ts | 3 +- .../lowering/builtins/child-process-async.ts | 3 +- .../lowering/builtins/child-process-sync.ts | 3 +- .../lowering/builtins/disposable-stack.ts | 3 +- .../frontend/lowering/builtins/filesystem.ts | 3 +- .../src/frontend/lowering/builtins/json.ts | 3 +- .../lowering/builtins/operating-system.ts | 7 +- .../frontend/lowering/builtins/performance.ts | 5 +- .../src/frontend/lowering/builtins/process.ts | 5 +- .../frontend/lowering/builtins/promises.ts | 5 +- .../lowering/builtins/promisify-callback.ts | 3 +- .../frontend/lowering/builtins/text-codecs.ts | 3 +- .../src/frontend/lowering/builtins/timers.ts | 2 +- .../src/frontend/lowering/builtins/url.ts | 7 +- .../src/frontend/lowering/builtins/v8.ts | 3 +- .../src/frontend/lowering/call-arguments.ts | 3 +- .../src/frontend/lowering/call-signatures.ts | 7 +- .../src/frontend/lowering/class-assertions.ts | 5 +- .../src/frontend/lowering/class-unions.ts | 3 +- .../lowering/coercions/function-adapters.ts | 11 +- .../frontend/lowering/coercions/structural.ts | 15 +-- .../src/frontend/lowering/coercions/unions.ts | 15 +-- .../frontend/lowering/collection-ingestion.ts | 3 +- .../lowering/containers/array-callbacks.ts | 25 +++-- .../lowering/containers/array-concat.ts | 3 +- .../lowering/containers/array-construction.ts | 7 +- .../lowering/containers/array-methods.ts | 11 +- .../lowering/containers/array-pipelines.ts | 3 +- .../src/frontend/lowering/containers/bytes.ts | 5 +- .../lowering/containers/callback-arguments.ts | 3 +- .../containers/collection-grouping.ts | 5 +- .../lowering/containers/collection-methods.ts | 15 +-- .../lowering/containers/indexed-objects.ts | 15 +-- .../lowering/containers/iterator-helpers.ts | 7 +- .../lowering/containers/string-and-regexp.ts | 11 +- .../lowering/containers/string-replacement.ts | 3 +- .../frontend/lowering/expressions/binary.ts | 3 +- .../lowering/expressions/object-literals.ts | 7 +- .../lowering/expressions/optional-chains.ts | 10 +- .../lowering/expressions/property-access.ts | 3 +- .../lowering/expressions/relational.ts | 5 +- .../frontend/lowering/generic-functions.ts | 17 ++- .../src/frontend/lowering/intern-tables.ts | 7 +- .../frontend/lowering/iterator-adapters.ts | 17 +-- .../frontend/lowering/js-dynamic-objects.ts | 5 +- .../src/frontend/lowering/json-require.ts | 3 +- .../src/frontend/lowering/lifetime-regions.ts | 3 +- .../src/frontend/lowering/lower-assert.ts | 11 +- .../src/frontend/lowering/lower-calls.ts | 49 +++++---- .../src/frontend/lowering/lower-classes.ts | 9 +- .../src/frontend/lowering/lower-dgram.ts | 5 +- .../frontend/lowering/lower-event-emitter.ts | 13 ++- .../src/frontend/lowering/lower-exprs.ts | 9 +- .../src/frontend/lowering/lower-functions.ts | 2 +- .../src/frontend/lowering/lower-inspect.ts | 7 +- .../src/frontend/lowering/lower-mixins.ts | 3 +- .../src/frontend/lowering/lower-mock.ts | 3 +- .../frontend/lowering/lower-modules.test.ts | 4 +- .../src/frontend/lowering/lower-modules.ts | 15 ++- .../src/frontend/lowering/lower-namespaces.ts | 11 +- .../src/frontend/lowering/lower-server.ts | 13 ++- .../src/frontend/lowering/lower-stdlib.ts | 2 +- .../src/frontend/lowering/lower-stream.ts | 15 +-- .../src/frontend/lowering/lower-timers.ts | 7 +- .../src/frontend/lowering/lowerer.test.ts | 30 +++-- .../compiler/src/frontend/lowering/lowerer.ts | 100 ++++++++++++++--- .../src/frontend/lowering/native-ffi.ts | 2 +- .../lowering/object-enumeration-receiver.ts | 3 +- .../src/frontend/lowering/pairs-snapshot.ts | 3 +- .../lowering/promise-executor-adapter.ts | 3 +- .../lowering/require-initialization.ts | 3 +- .../src/frontend/lowering/stable-names.ts | 48 ++++++++ .../src/frontend/lowering/strict-equality.ts | 3 +- .../frontend/lowering/structural-positions.ts | 103 ++++++++++++++++++ packages/compiler/src/frontend/ts7/ast.ts | 90 ++++++++++++++- .../compiler/src/frontend/type-mapper.test.ts | 2 +- packages/compiler/src/frontend/type-mapper.ts | 46 ++++++-- .../test/array-pipeline-fusion.test.ts | 2 +- .../test/format-float-arguments.test.ts | 2 +- .../test/in-runtime-key-emission.test.ts | 2 +- .../compiler/test/type-mapper-unions.test.ts | 3 +- 85 files changed, 693 insertions(+), 256 deletions(-) create mode 100644 packages/compiler/src/frontend/lowering/stable-names.ts create mode 100644 packages/compiler/src/frontend/lowering/structural-positions.ts diff --git a/package.json b/package.json index 5cc30d9f8..d1a8e34ae 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", diff --git a/packages/compiler/src/contracts/check.ts b/packages/compiler/src/contracts/check.ts index 5934624bf..c80468961 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(/^%/, ""); } 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/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/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-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/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/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/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/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..75e527aa5 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"; @@ -55,7 +56,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; @@ -557,7 +558,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 })); 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/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..2a77fa85c 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"; @@ -292,7 +293,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 +373,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 +679,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/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/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-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.ts b/packages/compiler/src/frontend/lowering/coercions/structural.ts index 496a29607..5b5e283b3 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"; @@ -253,7 +254,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 +313,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 +342,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 +389,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 +453,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 +493,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 +518,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..7ca69d9ba 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"; @@ -506,7 +507,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 +620,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); @@ -1204,7 +1205,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 +1305,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 +1389,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, @@ -1587,7 +1588,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 +1830,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 +2122,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 +2168,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 +2309,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 +2482,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; @@ -2676,7 +2677,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); diff --git a/packages/compiler/src/frontend/lowering/containers/array-concat.ts b/packages/compiler/src/frontend/lowering/containers/array-concat.ts index 4f6e4ca43..b4e285ee9 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 }, 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..180f40435 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 }); } diff --git a/packages/compiler/src/frontend/lowering/containers/bytes.ts b/packages/compiler/src/frontend/lowering/containers/bytes.ts index bf9821d31..4b20d7bf5 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"; @@ -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), @@ -270,7 +271,7 @@ function bytesCallbackHelper( const key = `bytes.${method}:${bytesT.elem}:${typeKey(resultT)}:${typeKey(fnRet)}:${arity}:${hasInit ? "init" : ""}`; 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"; diff --git a/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts b/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts index 18754f088..f39c8e86c 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"; @@ -285,7 +286,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..d3169ec5c 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"; @@ -232,7 +233,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 +349,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 +520,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 +694,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 +746,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)); } @@ -1357,7 +1358,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 +1458,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/indexed-objects.ts b/packages/compiler/src/frontend/lowering/containers/indexed-objects.ts index efc173ffc..b3faf649e 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 }; @@ -1474,7 +1475,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); @@ -1805,7 +1806,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..48b4caabd 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 }); 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..fe4ddbc6c 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}`, @@ -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}`, 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/expressions/binary.ts b/packages/compiler/src/frontend/lowering/expressions/binary.ts index fafbbf695..7e449f12b 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({ diff --git a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts index 565db0cd8..93bf43e95 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"; @@ -406,7 +407,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 +462,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 }, }); @@ -2956,7 +2957,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); 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..6c8dfa3bf 100644 --- a/packages/compiler/src/frontend/lowering/expressions/property-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/property-access.ts @@ -1,4 +1,5 @@ /* Property reads (`a.b`): lowerExprInner's property-access branch, intrinsic and union properties, field reads and targets, and match-group reads. */ +import { keyedHelperName } from "../stable-names.js"; import { staticallySelected } from "../static-typeof.js"; import * as ts from "../../ts7/adapter.js"; import { lowerHistogramProperty } from "../builtins/performance.js"; @@ -2783,7 +2784,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 }]; diff --git a/packages/compiler/src/frontend/lowering/expressions/relational.ts b/packages/compiler/src/frontend/lowering/expressions/relational.ts index 088b45cff..836391835 100644 --- a/packages/compiler/src/frontend/lowering/expressions/relational.ts +++ b/packages/compiler/src/frontend/lowering/expressions/relational.ts @@ -1,4 +1,5 @@ /* instanceof and in, including private-name and runtime-key in. */ +import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { builtinClassInstanceOfAny, builtinClassKind } from "../builtins/builtin-class-dyn.js"; import { @@ -647,7 +648,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[] = []; @@ -1847,7 +1848,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 }; diff --git a/packages/compiler/src/frontend/lowering/generic-functions.ts b/packages/compiler/src/frontend/lowering/generic-functions.ts index abcd5a584..daf082db7 100644 --- a/packages/compiler/src/frontend/lowering/generic-functions.ts +++ b/packages/compiler/src/frontend/lowering/generic-functions.ts @@ -1,4 +1,6 @@ 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"; @@ -229,7 +231,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(), }); @@ -651,7 +656,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, @@ -2129,7 +2134,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 +2322,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 +2418,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,7 +2564,7 @@ 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, 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/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/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-calls.ts b/packages/compiler/src/frontend/lowering/lower-calls.ts index 7102f37ab..63b8781f2 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"; @@ -2094,7 +2095,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 +2204,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 +2373,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 +3235,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 +3280,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({ @@ -4706,7 +4707,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 +5394,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 +5575,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 +5672,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 +5921,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], @@ -6015,7 +6016,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 +6119,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 +6222,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 +6352,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; @@ -6588,7 +6589,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 +6835,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 +6905,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 +6990,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 +7058,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)!; @@ -8514,7 +8515,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 }; @@ -9150,7 +9151,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); @@ -10079,7 +10080,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[] => { @@ -10172,7 +10173,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. @@ -10366,7 +10367,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 }; diff --git a/packages/compiler/src/frontend/lowering/lower-classes.ts b/packages/compiler/src/frontend/lowering/lower-classes.ts index 790efe988..fcea03790 100644 --- a/packages/compiler/src/frontend/lowering/lower-classes.ts +++ b/packages/compiler/src/frontend/lowering/lower-classes.ts @@ -1,3 +1,4 @@ +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"; @@ -4663,7 +4664,7 @@ export function genericClassInstanceType( ); } const ordinal = gci.instances.size; - const name = `${gci.family.def.name}%${ordinal}`; + const name = keyedHelperName(lowerer, `${gci.family.def.name}%`, key, ""); const entry: { name: string; info: ClassInfo | null; poisoned?: boolean } = { name, info: null }; gci.instances.set(key, entry); const bindings = new Map(); @@ -7910,7 +7911,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 +8025,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 }; @@ -10532,7 +10533,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..aa90fc7c7 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({ @@ -891,7 +892,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..f105af786 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 }, @@ -2359,7 +2360,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 +2425,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..ba96bea8c 100644 --- a/packages/compiler/src/frontend/lowering/lower-exprs.ts +++ b/packages/compiler/src/frontend/lowering/lower-exprs.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { lowerWebAssemblyValue, refuseWebAssemblyUse } from "./builtins/webassembly.js"; import { dynUndefinedExpr, nodeThrowExpr, numLit, strLit, varRef } from "../../ir/build.js"; import { InternalCompilerError } from "../../errors.js"; @@ -2274,7 +2275,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 +2304,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); } diff --git a/packages/compiler/src/frontend/lowering/lower-functions.ts b/packages/compiler/src/frontend/lowering/lower-functions.ts index cd8dc31d1..653c0d837 100644 --- a/packages/compiler/src/frontend/lowering/lower-functions.ts +++ b/packages/compiler/src/frontend/lowering/lower-functions.ts @@ -270,7 +270,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 = diff --git a/packages/compiler/src/frontend/lowering/lower-inspect.ts b/packages/compiler/src/frontend/lowering/lower-inspect.ts index 4be5d0b7e..1979b43aa 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, @@ -268,7 +269,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); @@ -1145,7 +1146,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); @@ -2074,7 +2075,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..0b99e88d3 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"; @@ -1074,8 +1075,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 +1684,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 +1761,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 diff --git a/packages/compiler/src/frontend/lowering/lower-namespaces.ts b/packages/compiler/src/frontend/lowering/lower-namespaces.ts index dca835d77..19123dae3 100644 --- a/packages/compiler/src/frontend/lowering/lower-namespaces.ts +++ b/packages/compiler/src/frontend/lowering/lower-namespaces.ts @@ -36,6 +36,7 @@ * 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 type { Lowerer } from "./lowerer.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 diff --git a/packages/compiler/src/frontend/lowering/lower-server.ts b/packages/compiler/src/frontend/lowering/lower-server.ts index 058d7874a..94d49d8b3 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`; @@ -3583,7 +3584,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 +4425,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 = [ @@ -8009,7 +8010,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-stream.ts b/packages/compiler/src/frontend/lowering/lower-stream.ts index b9add95a6..a75ec43b7 100644 --- a/packages/compiler/src/frontend/lowering/lower-stream.ts +++ b/packages/compiler/src/frontend/lowering/lower-stream.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { nodeThrowExpr, boolLit, numLit, strLit } from "../../ir/build.js"; import { hashStreamOf, isHashValueType } from "./builtins/hash-stream.js"; import { InternalCompilerError } from "../../errors.js"; @@ -311,7 +312,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 { @@ -1144,7 +1145,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 { @@ -1690,7 +1691,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 +1780,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 +1941,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 = { @@ -2894,7 +2895,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, @@ -2921,7 +2922,7 @@ function pipelineAbortHelper(lowerer: Lowerer, ac: IrExpr, loc: SrcLoc): IrExpr let name = lowerer.valueHelpers.get(key); const abortT = funcOf([], 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); 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..750c27694 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..687a2fb1a 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, @@ -1004,6 +1006,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, @@ -2801,6 +2808,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,7 +2946,6 @@ 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(); @@ -3167,7 +3175,47 @@ 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. */ + readonly positions = new StructuralPositions(); + + /** 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(); @@ -3808,11 +3856,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]!; @@ -7371,7 +7419,10 @@ export class Lowerer { } 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 +7435,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 +7480,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 +7492,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; @@ -7990,7 +8049,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 +8078,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 +8111,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 +8144,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 +8172,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(); @@ -13489,7 +13557,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/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/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..cdc290b4b --- /dev/null +++ b/packages/compiler/src/frontend/lowering/structural-positions.ts @@ -0,0 +1,103 @@ +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, +]); + +/** 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 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(); + + /** 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 = anchor.fileName; + else { + const parent = anchorOf(anchor); + const name = anchorName(anchor); + path = `${this.pathOf(parent)}/${name}#${this.ordinalIn(parent, anchor, `${anchor.kind}:${name}`)}`; + } + 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/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/type-mapper.test.ts b/packages/compiler/src/frontend/type-mapper.test.ts index cf78554b4..a99eb44cc 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..ce73e8bc2 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 } 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"; @@ -252,6 +253,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 +273,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[] }`): @@ -391,10 +394,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 { + recursiveRef(t: ts.Type, description: string): string { let id = this.recIds.get(t); if (id === undefined) { - id = `r${this.shapes.length}`; + id = keyedHelperName(this, "r", `recursive:${description}`, ""); + if (this.byId.has(id)) + throw new InternalCompilerError(`two recursive types share the description ${description}`); const shape: IrRecordShape = { id, fields: [] }; this.byId.set(id, shape); this.shapes.push(shape); @@ -463,7 +468,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 +546,17 @@ export class ShapeRegistry { } } +/** A recursive checker type's printed form and first declaration, which + * name its placeholder whichever frame first reaches it. */ +function recursiveTypeName(t: ts.Type, ctx: Pick): string { + const symbol = t.getAliasSymbol() ?? t.getSymbol(); + const declaration = symbol?.declarations[0]; + const where = declaration + ? `${ts.getSourceFileOfNode(declaration).fileName}:${declaration.pos}` + : ""; + return `${ctx.checker.typeToString(t)}@${where}`; +} + /** 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 +564,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` @@ -568,10 +586,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 { + recursiveRef(t: ts.Type, description: string): string { let id = this.recIds.get(t); if (id === undefined) { - id = `u${this.unions.length}`; + id = keyedHelperName(this, "u", `recursive:${description}`, ""); + if (this.byId.has(id)) + throw new InternalCompilerError(`two recursive types share the description ${description}`); const def: IrUnionDef = { id, arms: [] }; this.byId.set(id, def); this.unions.push(def); @@ -621,7 +641,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); @@ -4651,7 +4671,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, recursiveTypeName(widened, ctx)), + }; } unions.inProgress.add(widened); const sensitivityAtEntry = contextResolutions; @@ -6995,7 +7018,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, recursiveTypeName(widened, ctx)), + }; } shapes.inProgress.add(widened); const sensitivityAtEntry = contextResolutions; 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/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/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"], ]); From 97e85bf238e4583ce3daff31577e0d20544c0541 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 23:35:02 -0500 Subject: [PATCH 008/102] Compile js-yaml and smol-toml statically and match Node --- package.json | 3 +- .../compiler/src/backend/llvm/lib-shared.ts | 9 +- .../lowering/builtins/date-classes.ts | 555 ++++++++++++++++++ .../src/frontend/lowering/builtins/dates.ts | 95 ++- .../src/frontend/lowering/builtins/errors.ts | 111 ++++ .../lowering/class-dynamic-dispatch.ts | 114 +++- .../lowering/class-method-mutations.ts | 3 + .../src/frontend/lowering/class-prototypes.ts | 27 + .../frontend/lowering/class-to-primitive.ts | 51 +- .../frontend/lowering/expressions/binary.ts | 53 +- .../lowering/expressions/element-access.ts | 18 +- .../lowering/expressions/object-literals.ts | 3 + .../lowering/expressions/property-access.ts | 70 ++- .../lowering/expressions/relational.ts | 64 +- .../frontend/lowering/expressions/updates.ts | 60 +- .../src/frontend/lowering/lower-calls.ts | 150 ++++- .../src/frontend/lowering/lower-classes.ts | 79 ++- .../src/frontend/lowering/lower-inspect.ts | 11 +- .../src/frontend/lowering/lower-modules.ts | 2 + .../src/frontend/lowering/lower-stmts.ts | 42 +- .../compiler/src/frontend/lowering/lowerer.ts | 28 +- .../src/frontend/lowering/private-brands.ts | 90 ++- .../src/frontend/lowering/surfaces.ts | 1 + packages/compiler/src/ir/builtin-effects.ts | 4 + .../compiler/src/ir/builtin-signatures.ts | 7 + packages/compiler/src/ir/int32-slots.ts | 1 + packages/compiler/src/ir/tiers.ts | 1 + .../7040-es5-error-constructor.mjs.json | 6 + .../7041-error-called-without-new.mjs.json | 6 + ...42-string-method-names-on-objects.mjs.json | 6 + .../tests/corpus/7043-date-set-time.mjs.json | 6 + .../7044-nested-empty-object-maps.mjs.json | 6 + ...045-instanceof-constructor-values.mjs.json | 6 + .../7046-parse-float-extra-arguments.mjs.json | 6 + .../corpus/7047-dynamic-string-index.mjs.json | 6 + .../7048-unary-number-coercions.mjs.json | 6 + .../7049-member-assignment-values.mjs.json | 6 + .../tests/corpus/7050-date-subclass.mjs.json | 6 + .../corpus/7051-date-subclass-typed.ts.json | 6 + .../7052-date-subclass-dynamic.mjs.json | 6 + ...-private-fields-untyped-receivers.mjs.json | 6 + ...054-let-bindings-with-null-writes.mjs.json | 6 + packages/runtime/src/scr_dyn.h | 38 ++ packages/runtime/src/scr_dyn_invoke.c | 10 + packages/runtime/src/scr_inspect.c | 35 +- packages/runtime/src/scr_json.c | 317 +++++++++- packages/runtime/src/scr_lib.c | 178 +++++- pnpm-lock.yaml | 19 +- tests/corpus/7040-es5-error-constructor.mjs | 79 +++ .../corpus/7041-error-called-without-new.mjs | 40 ++ .../7042-string-method-names-on-objects.mjs | 70 +++ tests/corpus/7043-date-set-time.mjs | 28 + .../corpus/7044-nested-empty-object-maps.mjs | 46 ++ .../7045-instanceof-constructor-values.mjs | 43 ++ .../7046-parse-float-extra-arguments.mjs | 9 + tests/corpus/7047-dynamic-string-index.mjs | 21 + tests/corpus/7048-unary-number-coercions.mjs | 34 ++ .../corpus/7049-member-assignment-values.mjs | 20 + tests/corpus/7050-date-subclass.mjs | 69 +++ tests/corpus/7051-date-subclass-typed.ts | 47 ++ tests/corpus/7052-date-subclass-dynamic.mjs | 43 ++ .../7053-private-fields-untyped-receivers.mjs | 72 +++ .../7054-let-bindings-with-null-writes.mjs | 37 ++ tests/fixtures/npm-static/js-yaml-cli.mjs | 63 ++ tests/fixtures/npm-static/smol-toml-cli.mjs | 68 +++ .../7040-es5-error-constructor.mjs.json | 1 + .../7041-error-called-without-new.mjs.json | 1 + ...42-string-method-names-on-objects.mjs.json | 1 + .../corpus-costs/7043-date-set-time.mjs.json | 1 + .../7044-nested-empty-object-maps.mjs.json | 1 + ...045-instanceof-constructor-values.mjs.json | 1 + .../7046-parse-float-extra-arguments.mjs.json | 1 + .../7047-dynamic-string-index.mjs.json | 1 + .../7048-unary-number-coercions.mjs.json | 1 + .../7049-member-assignment-values.mjs.json | 1 + .../corpus-costs/7050-date-subclass.mjs.json | 1 + .../7051-date-subclass-typed.ts.json | 1 + .../7052-date-subclass-dynamic.mjs.json | 1 + ...-private-fields-untyped-receivers.mjs.json | 1 + ...054-let-bindings-with-null-writes.mjs.json | 1 + tests/harness/npm-static-costs.json | 4 + tests/harness/npm-static.test.ts | 32 + 82 files changed, 3065 insertions(+), 114 deletions(-) create mode 100644 packages/compiler/src/frontend/lowering/builtins/date-classes.ts create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7040-es5-error-constructor.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7041-error-called-without-new.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7042-string-method-names-on-objects.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7043-date-set-time.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7044-nested-empty-object-maps.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7045-instanceof-constructor-values.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7046-parse-float-extra-arguments.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7047-dynamic-string-index.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7048-unary-number-coercions.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7049-member-assignment-values.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7050-date-subclass.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7051-date-subclass-typed.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7052-date-subclass-dynamic.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7053-private-fields-untyped-receivers.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7054-let-bindings-with-null-writes.mjs.json create mode 100644 tests/corpus/7040-es5-error-constructor.mjs create mode 100644 tests/corpus/7041-error-called-without-new.mjs create mode 100644 tests/corpus/7042-string-method-names-on-objects.mjs create mode 100644 tests/corpus/7043-date-set-time.mjs create mode 100644 tests/corpus/7044-nested-empty-object-maps.mjs create mode 100644 tests/corpus/7045-instanceof-constructor-values.mjs create mode 100644 tests/corpus/7046-parse-float-extra-arguments.mjs create mode 100644 tests/corpus/7047-dynamic-string-index.mjs create mode 100644 tests/corpus/7048-unary-number-coercions.mjs create mode 100644 tests/corpus/7049-member-assignment-values.mjs create mode 100644 tests/corpus/7050-date-subclass.mjs create mode 100644 tests/corpus/7051-date-subclass-typed.ts create mode 100644 tests/corpus/7052-date-subclass-dynamic.mjs create mode 100644 tests/corpus/7053-private-fields-untyped-receivers.mjs create mode 100644 tests/corpus/7054-let-bindings-with-null-writes.mjs create mode 100644 tests/fixtures/npm-static/js-yaml-cli.mjs create mode 100644 tests/fixtures/npm-static/smol-toml-cli.mjs create mode 100644 tests/harness/corpus-costs/7040-es5-error-constructor.mjs.json create mode 100644 tests/harness/corpus-costs/7041-error-called-without-new.mjs.json create mode 100644 tests/harness/corpus-costs/7042-string-method-names-on-objects.mjs.json create mode 100644 tests/harness/corpus-costs/7043-date-set-time.mjs.json create mode 100644 tests/harness/corpus-costs/7044-nested-empty-object-maps.mjs.json create mode 100644 tests/harness/corpus-costs/7045-instanceof-constructor-values.mjs.json create mode 100644 tests/harness/corpus-costs/7046-parse-float-extra-arguments.mjs.json create mode 100644 tests/harness/corpus-costs/7047-dynamic-string-index.mjs.json create mode 100644 tests/harness/corpus-costs/7048-unary-number-coercions.mjs.json create mode 100644 tests/harness/corpus-costs/7049-member-assignment-values.mjs.json create mode 100644 tests/harness/corpus-costs/7050-date-subclass.mjs.json create mode 100644 tests/harness/corpus-costs/7051-date-subclass-typed.ts.json create mode 100644 tests/harness/corpus-costs/7052-date-subclass-dynamic.mjs.json create mode 100644 tests/harness/corpus-costs/7053-private-fields-untyped-receivers.mjs.json create mode 100644 tests/harness/corpus-costs/7054-let-bindings-with-null-writes.mjs.json diff --git a/package.json b/package.json index 5cc30d9f8..69177e0e6 100644 --- a/package.json +++ b/package.json @@ -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/compiler/src/backend/llvm/lib-shared.ts b/packages/compiler/src/backend/llvm/lib-shared.ts index 8bb8bc3aa..5669704d0 100644 --- a/packages/compiler/src/backend/llvm/lib-shared.ts +++ b/packages/compiler/src/backend/llvm/lib-shared.ts @@ -997,12 +997,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", @@ -1478,6 +1481,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", 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..ac6fe33a9 --- /dev/null +++ b/packages/compiler/src/frontend/lowering/builtins/date-classes.ts @@ -0,0 +1,555 @@ +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 a call argument. */ +function numberArgument(lowerer: Lowerer, node: ts.Expression | undefined, loc: SrcLoc): IrExpr { + if (!node) return { kind: "numLit", value: Number.NaN, type: F64, loc }; + const value = lowerer.lowerExpr(node); + 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") { + const time = lowerer.declareHiddenLocal("%dateTime", DATE_T); + stmts.push( + { + kind: "varDecl", + localId: time.id, + init: { + kind: "libCall", + fn: "date.newMs", + args: [numberArgument(lowerer, args[0], loc)], + type: DATE_T, + loc, + }, + loc, + }, + ...args.slice(1).map((arg): IrStmt => ({ + kind: "exprStmt", + expr: lowerer.lowerExpr(arg), + loc: locOf(arg), + })), + { + 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/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/class-dynamic-dispatch.ts b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts index c90e1135b..fefe85d0c 100644 --- a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts +++ b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts @@ -2,8 +2,17 @@ import { primitiveConstructorOr } from "./lower-exprs.js"; import { dynUndefinedExpr, helperLoc, nodeThrowExpr, varRef } from "../../ir/build.js"; import { constructedValue } from "./constructor-returns.js"; import { eventTargetApiMembers, eventTargetInheritedMember } from "./lower-event-target.js"; +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, @@ -296,6 +305,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", @@ -2871,6 +2906,7 @@ export class ClassDynamicDispatch { !isClassOwnEnumerableFieldName(dispatch.name) || (!(info.builtinStream !== undefined && streamProperty(dispatch.name)) && !eventTargetInheritedMember(info, dispatch.name) && + !dateInheritedMember(lowerer, info, dispatch.name) && !findMethodOn(lowerer, info, dispatch.name) && !findGenericMethodOn(lowerer, info, dispatch.name) && dispatch.name !== "constructor" && @@ -2987,7 +3023,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 +3237,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 +3903,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 +4835,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 [ 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-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-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/expressions/binary.ts b/packages/compiler/src/frontend/lowering/expressions/binary.ts index fafbbf695..ead313a78 100644 --- a/packages/compiler/src/frontend/lowering/expressions/binary.ts +++ b/packages/compiler/src/frontend/lowering/expressions/binary.ts @@ -902,10 +902,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 +1281,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..3ca1471ae 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, ); diff --git a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts index 565db0cd8..e4f7d8675 100644 --- a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts +++ b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts @@ -797,6 +797,7 @@ export function lowerObjectLiteral( ): IrExpr { // 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 +806,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))), ) ) { diff --git a/packages/compiler/src/frontend/lowering/expressions/property-access.ts b/packages/compiler/src/frontend/lowering/expressions/property-access.ts index f0b980da0..895ff5f45 100644 --- a/packages/compiler/src/frontend/lowering/expressions/property-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/property-access.ts @@ -5,7 +5,11 @@ 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 +94,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, @@ -281,6 +285,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; @@ -1664,6 +1686,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 @@ -3533,6 +3568,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 +3611,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; diff --git a/packages/compiler/src/frontend/lowering/expressions/relational.ts b/packages/compiler/src/frontend/lowering/expressions/relational.ts index 088b45cff..37478be0d 100644 --- a/packages/compiler/src/frontend/lowering/expressions/relational.ts +++ b/packages/compiler/src/frontend/lowering/expressions/relational.ts @@ -1,4 +1,5 @@ /* instanceof and in, including private-name and runtime-key in. */ +import { dateRootOf } from "../builtins/date-classes.js"; import * as ts from "../../ts7/adapter.js"; import { builtinClassInstanceOfAny, builtinClassKind } from "../builtins/builtin-class-dyn.js"; import { @@ -265,7 +266,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, }, @@ -565,7 +571,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 +622,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 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/lower-calls.ts b/packages/compiler/src/frontend/lowering/lower-calls.ts index 7102f37ab..21b974e31 100644 --- a/packages/compiler/src/frontend/lowering/lower-calls.ts +++ b/packages/compiler/src/frontend/lowering/lower-calls.ts @@ -141,7 +141,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 { @@ -199,6 +199,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, @@ -1554,6 +1559,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) ?? @@ -3727,6 +3733,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) ?? @@ -3935,6 +3953,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 @@ -4372,6 +4482,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([ @@ -9670,6 +9803,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). @@ -10458,6 +10595,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 diff --git a/packages/compiler/src/frontend/lowering/lower-classes.ts b/packages/compiler/src/frontend/lowering/lower-classes.ts index 790efe988..9976a37e4 100644 --- a/packages/compiler/src/frontend/lowering/lower-classes.ts +++ b/packages/compiler/src/frontend/lowering/lower-classes.ts @@ -1,3 +1,11 @@ +import { + DATE_TIME_FIELD, + dateRootOf, + dateSuperCall, + isDatePrototypeMethod, + lowerDateSuperMethodCall, +} from "./builtins/date-classes.js"; +import { lowerDateStaticCall } from "./builtins/dates.js"; import { lowerValueReturningConstructorNew } from "./js-dynamic-objects.js"; import { adaptPromiseExecutor } from "./promise-executor-adapter.js"; import { dynUndefinedExpr, nodeThrowExpr, varRef } from "../../ir/build.js"; @@ -564,6 +572,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 +1964,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 +2165,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 @@ -4350,7 +4369,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 +4408,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 +4440,7 @@ export function collectClassShapeInner( base, ...(genericBase ? { genericBase } : {}), ...(callableBase ? { callableBase } : {}), + ...(extendsDate ? { extendsDate: true as const } : {}), ...(factoryBaseExpression ? { factoryBaseExpression } : {}), subclasses: [], throwingSetters, @@ -5647,6 +5669,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", @@ -6422,6 +6453,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 && @@ -7683,7 +7720,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 +7732,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 @@ -8614,12 +8651,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 +8843,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", @@ -8925,6 +8965,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 +9027,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); diff --git a/packages/compiler/src/frontend/lowering/lower-inspect.ts b/packages/compiler/src/frontend/lowering/lower-inspect.ts index 4be5d0b7e..6f90b198c 100644 --- a/packages/compiler/src/frontend/lowering/lower-inspect.ts +++ b/packages/compiler/src/frontend/lowering/lower-inspect.ts @@ -45,6 +45,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"; @@ -804,8 +805,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 +959,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", diff --git a/packages/compiler/src/frontend/lowering/lower-modules.ts b/packages/compiler/src/frontend/lowering/lower-modules.ts index d1f276d44..e12d90743 100644 --- a/packages/compiler/src/frontend/lowering/lower-modules.ts +++ b/packages/compiler/src/frontend/lowering/lower-modules.ts @@ -148,6 +148,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"; @@ -3376,6 +3377,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-stmts.ts b/packages/compiler/src/frontend/lowering/lower-stmts.ts index e3480cf9c..f1bf7c041 100644 --- a/packages/compiler/src/frontend/lowering/lower-stmts.ts +++ b/packages/compiler/src/frontend/lowering/lower-stmts.ts @@ -6110,6 +6110,18 @@ 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. + const primitive = lowerer.mapTypeOf(lowerer.typeOf(decl.name)); + if ( + (primitive?.kind === "string" || primitive?.kind === "f64" || primitive?.kind === "bool") && + candidates.some( + (node) => node.operatorToken.kind === ts.SyntaxKind.EqualsToken && mayBeNullish(node.right), + ) + ) + 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 +6152,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 +7597,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); diff --git a/packages/compiler/src/frontend/lowering/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index ee8ba7ecb..e7ea87867 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -497,7 +497,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, @@ -2944,6 +2945,10 @@ export class Lowerer { /** Named method slots observed before class collection need a callable * ABI and shared prototype descriptors instead of call-site specialization. */ readonly prototypeMethodAccesses = new Map(); + /** 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. */ @@ -8123,6 +8128,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. @@ -12758,6 +12764,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 +12802,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) ?? 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/surfaces.ts b/packages/compiler/src/frontend/lowering/surfaces.ts index c77938337..adc11e35a 100644 --- a/packages/compiler/src/frontend/lowering/surfaces.ts +++ b/packages/compiler/src/frontend/lowering/surfaces.ts @@ -2262,6 +2262,7 @@ export const AMBIENT_SURFACE_FNS: readonly AmbientSurfaceRow[] = [ "date.newLocal", "date.nativeNewFields", "date.nativeNewValue", + "date.argumentsTime", ], note: "zero arguments, one milliseconds/date-string argument, or local-time year/month fields; values are the read-only TimeClip scalar slice", }, diff --git a/packages/compiler/src/ir/builtin-effects.ts b/packages/compiler/src/ir/builtin-effects.ts index ca8c52118..b899e5277 100644 --- a/packages/compiler/src/ir/builtin-effects.ts +++ b/packages/compiler/src/ir/builtin-effects.ts @@ -534,6 +534,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 +602,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", diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index fa7876579..182d787c8 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -272,6 +272,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 +292,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 @@ -3646,6 +3649,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 }, diff --git a/packages/compiler/src/ir/int32-slots.ts b/packages/compiler/src/ir/int32-slots.ts index 6ff148c55..21223862a 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. 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/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/runtime/src/scr_dyn.h b/packages/runtime/src/scr_dyn.h index 02c4d828f..5d68b2c6d 100644 --- a/packages/runtime/src/scr_dyn.h +++ b/packages/runtime/src/scr_dyn.h @@ -662,6 +662,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); @@ -1048,6 +1082,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); diff --git a/packages/runtime/src/scr_dyn_invoke.c b/packages/runtime/src/scr_dyn_invoke.c index 2a010f213..ec49dd383 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); diff --git a/packages/runtime/src/scr_inspect.c b/packages/runtime/src/scr_inspect.c index 223517e92..a4d124ac3 100644 --- a/packages/runtime/src/scr_inspect.c +++ b/packages/runtime/src/scr_inspect.c @@ -1652,7 +1652,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_json.c b/packages/runtime/src/scr_json.c index b8f16630b..549ca9165 100644 --- a/packages/runtime/src/scr_json.c +++ b/packages/runtime/src/scr_json.c @@ -37,6 +37,19 @@ static SCR_TL ScrDyn *scr_builtin_object_prototype; +const ScrDateClassHooks *scr_date_class_hooks; + +/* 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; +} + /* 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) { @@ -1816,6 +1829,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 +2003,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 +2097,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 +2213,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 +2244,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)); @@ -3366,6 +3521,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; @@ -3457,6 +3613,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; @@ -3467,12 +3635,28 @@ ScrDyn *scr_dyn_typed_ref_string_view(const ScrDyn *d) { return out; } +/* 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); size_t index; @@ -3708,6 +3892,29 @@ ScrDyn *scr_array_buffer_constructor(void) { return scr_dyn_retain(scr_array_buffer_ctor); } +/* `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. 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; + 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}, + }; + 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; +} + bool scr_bytes_instanceof(const ScrDyn *value, const ScrDyn *callee) { if (!callee || callee->kind != SCR_DYN_FUNC) { static const char message[] = "Right-hand side of 'instanceof' is not callable"; @@ -3720,6 +3927,38 @@ 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; + } + scr_dyn_release(prototype); + } 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; @@ -6191,6 +6430,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()) { @@ -6341,6 +6581,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) { ScrDyn *view = scr_dyn_typed_ref_materialize(target); ScrDyn *defined = scr_exc_pending() ? NULL : scr_dyn_define_property(view, key, descriptor); @@ -7726,6 +7967,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 @@ -7755,7 +7999,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 @@ -7995,7 +8242,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; @@ -8098,9 +8350,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) { @@ -8161,6 +8422,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); @@ -8580,7 +8850,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; @@ -10408,7 +10678,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) || @@ -10634,6 +10904,16 @@ static bool scr_json_live_container(const ScrDyn *value, bool inspect) { * 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) { + /* 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_dyn_new_str((ScrStr *)key); + 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. */ @@ -12826,7 +13106,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)); @@ -14620,7 +14900,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); @@ -14629,7 +14912,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; @@ -14651,8 +14934,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); @@ -14663,7 +14950,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 3441e6142..d856e3000 100644 --- a/packages/runtime/src/scr_lib.c +++ b/packages/runtime/src/scr_lib.c @@ -12997,9 +12997,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 @@ -13009,13 +13116,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); @@ -13029,6 +13137,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); @@ -13059,13 +13173,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) { @@ -13092,11 +13218,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]; @@ -13111,13 +13237,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); @@ -13126,6 +13273,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/pnpm-lock.yaml b/pnpm-lock.yaml index 3974f346e..2404c3885 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 @@ -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'} @@ -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 @@ -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: {} 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..c22250fc1 --- /dev/null +++ b/tests/corpus/7050-date-subclass.mjs @@ -0,0 +1,69 @@ +// 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)); 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/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/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/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"]); From 42d4ca27f9733f3f64b3d0909bc6042d71a8351c Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 23:40:42 -0500 Subject: [PATCH 009/102] Run Promise.all of never-suspending async calls in place from stackless async bodies --- packages/compiler/src/backend/llvm/emitter.ts | 215 ++++++++++++++++++ .../compiler/src/backend/llvm/expr-async.ts | 6 + .../compiler/test/await-call-emission.test.ts | 45 ++++ .../7100-promise-all-inline-order.ts.json | 6 + ...7101-promise-all-inline-sync-throw.ts.json | 6 + .../7102-promise-all-inline-kinds.ts.json | 6 + tests/corpus/7100-promise-all-inline-order.ts | 86 +++++++ .../7101-promise-all-inline-sync-throw.ts | 21 ++ tests/corpus/7102-promise-all-inline-kinds.ts | 69 ++++++ .../7100-promise-all-inline-order.ts.json | 1 + ...7101-promise-all-inline-sync-throw.ts.json | 1 + .../7102-promise-all-inline-kinds.ts.json | 1 + 12 files changed, 463 insertions(+) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7100-promise-all-inline-order.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7101-promise-all-inline-sync-throw.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7102-promise-all-inline-kinds.ts.json create mode 100644 tests/corpus/7100-promise-all-inline-order.ts create mode 100644 tests/corpus/7101-promise-all-inline-sync-throw.ts create mode 100644 tests/corpus/7102-promise-all-inline-kinds.ts create mode 100644 tests/harness/corpus-costs/7100-promise-all-inline-order.ts.json create mode 100644 tests/harness/corpus-costs/7101-promise-all-inline-sync-throw.ts.json create mode 100644 tests/harness/corpus-costs/7102-promise-all-inline-kinds.ts.json diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index 0bdbe23b2..b306674fc 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -287,6 +287,7 @@ import { import { arrNewCall, boxAccess, + elemAccess, boxNewCall, boxReleaseSym, computeTraced, @@ -571,6 +572,33 @@ function mentionsLocal(e: IrExpr, localId: string): boolean { return found; } +/** The IR nodes in `body` that name local `id`: its declaration, reads, + * writes and closure captures. */ +function countLocalMentions(body: readonly IrStmt[], id: string): number { + let count = 0; + const visit = (node: unknown): void => { + if (node === null || typeof node !== "object") return; + if (Array.isArray(node)) { + for (const item of node) visit(item); + return; + } + const record = node as Record; + if (record["localId"] === id) count++; + const captures = record["captures"]; + if (Array.isArray(captures)) + for (const c of captures) + if ( + c === id || + (typeof c === "object" && c !== null && (c as { localId?: unknown }).localId === id) + ) + count++; + for (const [key, value] of Object.entries(record)) + if (key !== "type" && key !== "loc" && key !== "captures") visit(value); + }; + visit(body); + return count; +} + export class LlEmitter { localArrayReads = new Map(); loopArrayBorrows: ReadonlySet = new Set(); @@ -864,6 +892,9 @@ export class LlEmitter { /** The async functions whose bodies never suspend and that a direct * await may enter in place (selectStacklessAsync). */ private inlineAwaitable = new Set(); + /** Locals whose array literal emitStmts left for the `await Promise.all` + * that reads them (deferredPromiseAllLocal). */ + private readonly deferredPromiseAllEntries = new Map>(); /** The promise a `return` emitted past its finally regions already * produced for its adopting await (borrowed from the return's parked * slot); that await takes it instead of evaluating its operand. */ @@ -1945,6 +1976,185 @@ export class LlEmitter { this.emitPendingCheck(); return value; } + /** The entries of `Promise.all(arg)` that a stackless coroutine body's + * await may run in place (emitCoroInlinePromiseAll): `arg` is a non-empty + * array literal, or the local whose declaration emitStmts deferred to this + * await (deferredPromiseAllEntries), whose every entry is a call to a + * never-suspending async function, and the result is an array. Null + * otherwise. Consumes a deferred local's entries. */ + inlinePromiseAllEntries(all: ExprOf<"intrinsic">): ExprOf<"arrayLit"> | null { + if (all.name !== "promise.all" || all.type.kind !== "promise") return null; + if (all.type.inner.kind !== "array") return null; + const arg = all.args[0]; + if (arg?.kind === "varRef") { + const deferred = this.deferredPromiseAllEntries.get(arg.localId); + if (deferred === undefined) return null; + this.deferredPromiseAllEntries.delete(arg.localId); + return deferred; + } + return arg?.kind === "arrayLit" && this.promiseAllInlineable(arg) ? arg : null; + } + + /** Whether every entry of `entries` is a call an await could run in place + * (inlineAwaitEligible) that yields its promise's inner type. */ + private promiseAllInlineable(entries: ExprOf<"arrayLit">): boolean { + if (entries.elems.length === 0 || (entries.spreads?.length ?? 0) > 0) return false; + if (entries.type.kind !== "array" || entries.type.elem.kind !== "promise") return false; + const inner = entries.type.elem.inner; + return entries.elems.every((el) => { + if (el.kind !== "call" || !this.inlineAwaitEligible(el.callee)) return false; + const callee = this.fnByName.get(el.callee)!; + return typeEquals(callee.returnType, inner) && !this.callLifetimes.borrowed.has(el.callee); + }); + } + + /** Whether `stmts[i]` declares a local holding an array literal that only + * `stmts[i + 1]` reads, as the operand of `await Promise.all(local)` that + * runs first in that statement and may run its entries in place. Nothing + * runs between the literal and the await, so the await evaluates the + * literal itself (inlinePromiseAllEntries). Debug builds keep the local. */ + deferredPromiseAllLocal(stmts: readonly IrStmt[], i: number): ExprOf<"arrayLit"> | null { + const decl = stmts[i]; + const next = stmts[i + 1]; + if (this.debug !== null || decl?.kind !== "varDecl" || decl.init?.kind !== "arrayLit") + return null; + if (this.currentCoro?.kind !== "async" || next === undefined) return null; + const operand = + next.kind === "varDecl" + ? next.init + : next.kind === "exprStmt" + ? next.expr + : next.kind === "assign" + ? next.value + : null; + if (operand?.kind !== "awaitExpr" || operand.adopt === true) return null; + const all = operand.value; + if (all.kind !== "intrinsic" || all.name !== "promise.all" || all.type.kind !== "promise") + return null; + if (all.type.inner.kind !== "array") return null; + const arg = all.args[0]; + if (arg?.kind !== "varRef" || arg.localId !== decl.localId) return null; + if (!this.promiseAllInlineable(decl.init)) return null; + if (this.currentLocals.get(decl.localId)?.boxed) return null; + // The declaration and this read are the local's only mentions. + return countLocalMentions(this.currentFunctionBody, decl.localId) === 2 ? decl.init : null; + } + + /** A stackless coroutine body's `await Promise.all([f(...), ...])` of + * never-suspending calls, with Promise.all's turns and without its + * promises: the entries run in place in order and their values fill the + * result array. Promise.all queues one reaction job per entry, back to + * back, and the last of them settles the result, whose await then takes a + * turn: here one turn stands for the entries' jobs and a second for the + * await. A throwing entry becomes the rejection the await re-throws from + * its turn; the remaining entries still run, and later throws are handled + * rejections, as Promise.all's subscriptions make them. */ + emitCoroInlinePromiseAll(entries: ExprOf<"arrayLit">, type: IrType): LlValue { + if (type.kind !== "array") + throw new InternalCompilerError("llvm emitter bug: inline Promise.all result"); + const B = this.B; + const elem = type.elem; + const acc = elemAccess(elem); + const values = B.tmp(); + // Up to three values fit in the array's own block (scr_arr_new_*_small). + const small = entries.elems.length <= 3; + B.line( + `${values} = ${arrNewCall(this.shapeHost, elem, small ? "0" : String(entries.elems.length), small)}`, + ); + const out = this.own({ name: values, type }); + this.declare(`declare ptr @scr_promise_new()`); + this.declare(`declare void @scr_promise_reject_pending(ptr)`); + this.declare(`declare void @scr_promise_mark_handled(ptr)`); + const promiseType = entries.type.kind === "array" ? entries.type.elem : type; + // Each entry's rejection, owned by the frame: unobserved until the + // entries have all run, as Promise.all subscribes only then, so an + // entry argument's synchronous throw leaves them unhandled. + const rejections: string[] = []; + for (const entry of entries.elems) { + if (entry.kind !== "call") + throw new InternalCompilerError("llvm emitter bug: inline Promise.all entry"); + const slot = B.tmp(); + B.entryAllocas.push(`${slot} = alloca ptr`); + B.line(`store ptr null, ptr ${slot}`); + this.ownSlot(slot, promiseType); + rejections.push(slot); + const value = emitCallExpr(this, entry, "inline"); + const thrown = B.tmp(); + for (const line of this.pendingTestLines(thrown)) B.line(line.trim()); + const clean = B.newLabel("pa.clean"); + const rejected = B.newLabel("pa.rejected"); + const next = B.newLabel("pa.next"); + B.condBr(thrown, rejected, clean); + B.startBlock(clean); + if (acc === "ref") this.toHeap(value); + this.arrPush(values, acc, value.name); + B.br(next); + B.startBlock(rejected); + const promise = B.tmp(); + B.line(`${promise} = call ptr @scr_promise_new()`); + B.line(`call void @scr_promise_reject_pending(ptr ${promise})`); + B.line(`store ptr ${promise}, ptr ${slot}`); + B.br(next); + B.startBlock(next); + } + // Promise.all's subscriptions handle every rejection, and the first + // (in entry order) rejects the result. + let first = "null"; + for (let k = rejections.length - 1; k >= 0; k--) { + const slot = rejections[k]!; + const rejection = B.tmp(); + const present = B.tmp(); + B.line(`${rejection} = load ptr, ptr ${slot}`); + B.line(`${present} = icmp ne ptr ${rejection}, null`); + const mark = B.newLabel("pa.handled"); + const after = B.newLabel("pa.unrejected"); + B.condBr(present, mark, after); + B.startBlock(mark); + B.line(`call void @scr_promise_mark_handled(ptr ${rejection})`); + B.br(after); + B.startBlock(after); + const chosen = B.tmp(); + B.line(`${chosen} = select i1 ${present}, ptr ${rejection}, ptr ${first}`); + first = chosen; + } + // The entries' reaction jobs. + this.emitCoroAwait(null); + const failed = B.tmp(); + B.line(`${failed} = icmp ne ptr ${first}, null`); + const fulfilled = B.newLabel("pa.fulfilled"); + const rejected = B.newLabel("pa.reject"); + const join = B.newLabel("pa.join"); + B.condBr(failed, rejected, fulfilled); + B.startBlock(fulfilled); + this.emitCoroAwait(null); + B.br(join); + B.startBlock(rejected); + this.declare(`declare void @scr_coro_await_void(ptr)`); + this.emitCoroAwait(first); + B.line(`call void @scr_coro_await_void(ptr ${first})`); + B.br(join); + B.startBlock(join); + // The rejections are released here, only where an entry threw, rather + // than by the frame, which releases each slot whether or not it holds a + // promise. + this.declare(`declare void @scr_promise_release(ptr)`); + for (const slot of rejections) { + const rejection = B.tmp(); + const present = B.tmp(); + B.line(`${rejection} = load ptr, ptr ${slot}`); + B.line(`${present} = icmp ne ptr ${rejection}, null`); + const release = B.newLabel("pa.release"); + const after = B.newLabel("pa.released"); + B.condBr(present, release, after); + B.startBlock(release); + B.line(`call void @scr_promise_release(ptr ${rejection})`); + B.br(after); + B.startBlock(after); + } + this.disownSlots(rejections.map((ptr) => ({ ptr }))); + this.emitPendingCheck(); + return out; + } emitAsyncAwaitCall(fn: IrFunction, argPackLines: string[] | null, adopt = false): string[] { return emitAsyncAwaitCall(this, fn, argPackLines, adopt); } @@ -4499,6 +4709,11 @@ export class LlEmitter { if (this.B.isTerminated()) return; if (cursor) cursor.index = i; this.stmtCursor = cursor; + const deferred = this.deferredPromiseAllLocal(stmts, i); + if (deferred !== null) { + this.deferredPromiseAllEntries.set((stmts[i] as { localId: string }).localId, deferred); + continue; + } this.emitStmt(stmts[i]!); } } finally { diff --git a/packages/compiler/src/backend/llvm/expr-async.ts b/packages/compiler/src/backend/llvm/expr-async.ts index 6da63977d..4d73d0904 100644 --- a/packages/compiler/src/backend/llvm/expr-async.ts +++ b/packages/compiler/src/backend/llvm/expr-async.ts @@ -901,6 +901,12 @@ export function emitAsyncExpr( // the callee's adopting entry. Past finally regions, the return has // already produced the promise (adoptedOperand). const adopted = e.adopt === true ? host.takeAdoptedOperand() : null; + // A stackless coroutine body runs the entries of `Promise.all` of + // never-suspending calls in place and takes Promise.all's turns. + if (adopted === null && e.value.kind === "intrinsic" && host.currentCoro?.kind === "async") { + const entries = host.inlinePromiseAllEntries(e.value); + if (entries !== null) return host.emitCoroInlinePromiseAll(entries, e.type); + } // A stackless coroutine body runs a never-suspending callee in place // and takes the await's turn itself. if (adopted === null && e.value.kind === "call" && host.inlineAwaitEligible(e.value.callee)) { diff --git a/packages/compiler/test/await-call-emission.test.ts b/packages/compiler/test/await-call-emission.test.ts index b206b829b..5d2b614c3 100644 --- a/packages/compiler/test/await-call-emission.test.ts +++ b/packages/compiler/test/await-call-emission.test.ts @@ -262,3 +262,48 @@ void main(); } } }); + +const promiseAllSource = ` +async function leaf(x: number): Promise { + return x + 1; +} +async function literal(x: number): Promise { + const all: number[] = await Promise.all([leaf(x), leaf(x + 1)]); + return all[0]! + all[1]!; +} +async function local(x: number): Promise { + const ps = [leaf(x), leaf(x + 1), leaf(x + 2)]; + const all = await Promise.all(ps); + return all.length; +} +async function reused(x: number): Promise { + const ps = [leaf(x)]; + const all = await Promise.all(ps); + return all.length + ps.length; +} +async function main(): Promise { + console.log((await literal(1)) + (await local(2)) + (await reused(3))); +} +void main(); +`; + +test("a stackless body runs Promise.all of never-suspending calls in place", async () => { + const llvm = await emit(promiseAllSource); + for (const [symbol, calls] of [ + ["sc_f_literal", 2], + ["sc_f_local", 3], + ] as const) { + const body = definition(llvm, symbol); + // The entries run in place and fill the result array; one turn stands + // for Promise.all's reaction jobs and one for the await. + expect(body.match(/call double @sc_ai_leaf\(double/g)?.length, symbol).toBe(calls); + expect(body.match(/call zeroext i1 @scr_coro_hop_prepare\(ptr/g)?.length, symbol).toBe(2); + expect(body, symbol).toContain("call void @scr_promise_mark_handled(ptr"); + expect(body, symbol).not.toContain("@scr_promise_all("); + expect(body, symbol).not.toContain("@sc_as_leaf("); + } + // A local the body reads again keeps its promises. + const reused = definition(llvm, "sc_f_reused"); + expect(reused).toContain("call ptr @sc_as_leaf(double"); + expect(reused).toContain("@scr_promise_all("); +}); diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7100-promise-all-inline-order.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7100-promise-all-inline-order.ts.json new file mode 100644 index 000000000..1dd147700 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7100-promise-all-inline-order.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7100-promise-all-inline-order.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7101-promise-all-inline-sync-throw.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7101-promise-all-inline-sync-throw.ts.json new file mode 100644 index 000000000..9ee756166 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7101-promise-all-inline-sync-throw.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7101-promise-all-inline-sync-throw.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7102-promise-all-inline-kinds.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7102-promise-all-inline-kinds.ts.json new file mode 100644 index 000000000..572b90013 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7102-promise-all-inline-kinds.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7102-promise-all-inline-kinds.ts" + ], + "diags": [] +} diff --git a/tests/corpus/7100-promise-all-inline-order.ts b/tests/corpus/7100-promise-all-inline-order.ts new file mode 100644 index 000000000..b67eca014 --- /dev/null +++ b/tests/corpus/7100-promise-all-inline-order.ts @@ -0,0 +1,86 @@ +// Ordering of `await Promise.all([...])` of never-suspending async calls +// against concurrent microtasks. +const log: string[] = []; + +async function value(n: number): Promise { + log.push(`value ${n}`); + return n * 10; +} +async function fail(tag: string): Promise { + log.push(`fail ${tag}`); + throw new Error(`boom ${tag}`); +} +async function label(s: string): Promise { + log.push(`label ${s}`); + return s.toUpperCase(); +} + +function ticker(name: string, turns: number): Promise { + let p = Promise.resolve(); + for (let i = 0; i < turns; i++) p = p.then(() => void log.push(`${name} tick ${i}`)); + return p; +} + +async function literal(): Promise { + const r: number[] = await Promise.all([value(1), value(2), value(3)]); + log.push(`literal ${r.join(",")}`); +} +async function local(): Promise { + const ps = [value(4), value(5)]; + const r = await Promise.all(ps); + log.push(`local ${r.join(",")}`); +} +async function firstRejects(): Promise { + try { + await Promise.all([fail("a"), value(6), fail("b")]); + log.push("firstRejects resolved"); + } catch (e) { + log.push(`firstRejects caught ${(e as Error).message}`); + } +} +async function middleRejects(): Promise { + const ps = [value(7), fail("c"), value(8)]; + try { + const r = await Promise.all(ps); + log.push(`middleRejects resolved ${r.length}`); + } catch (e) { + log.push(`middleRejects caught ${(e as Error).message}`); + } +} +async function strings(): Promise { + const r: string[] = await Promise.all([label("x"), label("y")]); + log.push(`strings ${r.join("+")}`); +} +async function single(): Promise { + const all: number[] = await Promise.all([value(9)]); + const only = all[0]; + log.push(`single ${only}`); +} +async function reused(): Promise { + const ps = [value(11), value(12)]; + const r = await Promise.all(ps); + log.push(`reused ${r.join(",")} ${ps.length}`); +} +async function afterAssign(): Promise { + let r: number[] = []; + const ps = [value(13)]; + r = await Promise.all(ps); + log.push(`afterAssign ${r.join(",")}`); +} + +async function main(): Promise { + await Promise.all([ + ticker("t", 8), + literal(), + ticker("u", 4), + local(), + firstRejects(), + middleRejects(), + strings(), + single(), + reused(), + afterAssign(), + ]); + for (const line of log) console.log(line); +} +void main(); diff --git a/tests/corpus/7101-promise-all-inline-sync-throw.ts b/tests/corpus/7101-promise-all-inline-sync-throw.ts new file mode 100644 index 000000000..43e3b1167 --- /dev/null +++ b/tests/corpus/7101-promise-all-inline-sync-throw.ts @@ -0,0 +1,21 @@ +// An entry argument that throws synchronously leaves earlier rejections +// unhandled, since Promise.all never runs. +async function fail(tag: string): Promise { + throw new Error(`boom ${tag}`); +} +async function value(n: number): Promise { + return n; +} +function boom(): number { + throw new Error("argument"); +} +async function run(): Promise { + try { + const r: number[] = await Promise.all([fail("first"), value(boom())]); + console.log("resolved", r.length); + } catch (e) { + console.log("caught", (e as Error).message); + } +} +process.on("unhandledRejection", (reason) => console.log("unhandled", (reason as Error).message)); +void run().then(() => console.log("done")); diff --git a/tests/corpus/7102-promise-all-inline-kinds.ts b/tests/corpus/7102-promise-all-inline-kinds.ts new file mode 100644 index 000000000..6036a4d46 --- /dev/null +++ b/tests/corpus/7102-promise-all-inline-kinds.ts @@ -0,0 +1,69 @@ +// `await Promise.all([...])` of never-suspending async calls with number, +// boolean, string and record results, inside loops and larger expressions, +// and an uncaught rejection. +interface Point { + x: number; + y: number; +} +const log: string[] = []; +async function flag(n: number): Promise { + log.push(`flag ${n}`); + return n % 2 === 0; +} +async function point(n: number): Promise { + log.push(`point ${n}`); + return { x: n, y: n * n }; +} +async function count(n: number): Promise { + if (n < 0) throw new RangeError(`negative ${n}`); + return n + 1; +} +function ticker(name: string, turns: number): Promise { + let p = Promise.resolve(); + for (let i = 0; i < turns; i++) p = p.then(() => void log.push(`${name} tick ${i}`)); + return p; +} +async function flags(): Promise { + const r: boolean[] = await Promise.all([flag(1), flag(2)]); + log.push(`flags ${r.join(",")}`); +} +async function points(): Promise { + const ps = [point(1), point(2), point(3)]; + const r = await Promise.all(ps); + let sum = 0; + for (const p of r) sum += p.x + p.y; + log.push(`points ${sum}`); +} +async function loop(): Promise { + let total = 0; + for (let i = 0; i < 3; i++) { + const ps = [count(i), count(i * 2)]; + const r = await Promise.all(ps); + total += r[0]! + r[1]!; + log.push(`loop ${i} ${total}`); + } +} +function sumOf(xs: number[]): number { + let s = 0; + for (const x of xs) s += x; + return s; +} +async function nested(): Promise { + const total = 100 + sumOf(await Promise.all([count(4), count(5)])); + log.push(`nested ${total}`); +} +async function uncaught(): Promise { + const ps = [count(1), count(-2), count(-3)]; + const r = await Promise.all(ps); + log.push(`uncaught resolved ${r.length}`); +} +process.on("unhandledRejection", (reason) => { + const e = reason as Error; + console.log(`unhandled ${e.name} ${e.message}`); +}); +async function main(): Promise { + void uncaught(); + await Promise.all([ticker("t", 6), flags(), points(), loop(), nested()]); + for (const line of log) console.log(line); +} +void main(); diff --git a/tests/harness/corpus-costs/7100-promise-all-inline-order.ts.json b/tests/harness/corpus-costs/7100-promise-all-inline-order.ts.json new file mode 100644 index 000000000..054b3c2b4 --- /dev/null +++ b/tests/harness/corpus-costs/7100-promise-all-inline-order.ts.json @@ -0,0 +1 @@ +{ "plain": 3900, "san": 5000 } diff --git a/tests/harness/corpus-costs/7101-promise-all-inline-sync-throw.ts.json b/tests/harness/corpus-costs/7101-promise-all-inline-sync-throw.ts.json new file mode 100644 index 000000000..71bf780f8 --- /dev/null +++ b/tests/harness/corpus-costs/7101-promise-all-inline-sync-throw.ts.json @@ -0,0 +1 @@ +{ "plain": 2700, "san": 3500 } diff --git a/tests/harness/corpus-costs/7102-promise-all-inline-kinds.ts.json b/tests/harness/corpus-costs/7102-promise-all-inline-kinds.ts.json new file mode 100644 index 000000000..42d31979d --- /dev/null +++ b/tests/harness/corpus-costs/7102-promise-all-inline-kinds.ts.json @@ -0,0 +1 @@ +{ "plain": 3200, "san": 4000 } From 956bdf4ec0045ee6aca671dc720075409bbd7f3b Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 23:49:13 -0500 Subject: [PATCH 010/102] Bound while-loop counters that nested scans advance A while loop's counter gets an integer range when the loop only adds positive literals to it and its condition bounds it. A counter written inside a nested loop was refused, which is every hand-written scanner: `while (pos < end) { ... while (pos < end && isDigit(...)) pos++; ... }`. A nested while loop may now advance the counter when its own condition bounds it the same way and does not write it. Its passes start at most at that bound, so it leaves the counter at its entry value or at the highest value one of its passes reaches, and the outer loop's range follows from there. Other nested loops, and nested loops that do not bound the counter, still refuse it. --- .../compiler/src/ir/integer-loop-facts.ts | 74 ++++++++++++++++--- .../compiler/src/ir/integer-ranges.test.ts | 68 +++++++++++++++++ 2 files changed, 130 insertions(+), 12 deletions(-) diff --git a/packages/compiler/src/ir/integer-loop-facts.ts b/packages/compiler/src/ir/integer-loop-facts.ts index 23982aa07..b075ef29a 100644 --- a/packages/compiler/src/ir/integer-loop-facts.ts +++ b/packages/compiler/src/ir/integer-loop-facts.ts @@ -246,10 +246,15 @@ export const STRING_MAX_UNITS = 0x7fffffff; /** Bound counters of a while loop by its condition. A counter qualifies when * the loop (condition and body) changes it only by increments of positive - * integer literals outside nested loops, switch and exception regions, and a - * conjunct of the condition compares it below a literal, a binding the loop - * never writes, or the length of a string binding the loop never writes - * (`while (x * x + y * y <= 4 && it < MAX) it++`, `while (pos < text.length)`). + * integer literals outside switch and exception regions and loops other + * than nested while loops, and a conjunct of the condition compares it below + * a literal, a binding the loop never writes, or the length of a string + * binding the loop never writes (`while (x * x + y * y <= 4 && it < MAX) + * it++`, `while (pos < text.length)`). A nested while loop may advance the + * counter only when its own condition bounds it the same way and does not + * write it (a scanner's `while (pos < end && isDigit(...)) pos++`): its + * passes start at most at that bound, so it leaves the counter at its entry + * value or at the highest value one of its passes reaches. * The body runs only after that conjunct held, and the condition never * writes the counter, so every pass starts at most at the conjunct's bound. * The pass then climbs by the increments on its path; an increment inside an @@ -270,19 +275,29 @@ export function guardedLoopCounterFacts( if (opaque || delta === null || delta <= 0 || delta > 2147483647) refused.add(id); else budget.set(id, (budget.get(id) ?? 0) + delta); }; + // Nested while loops outside opaque regions, checked against their own + // conditions once the stable bounds are known. + const nested: (IrStmt & { kind: "while" })[] = []; const expr = (e: IrExpr): boolean => { if (e.kind === "assignExpr") write(e.localId, increment(e.localId, e.value)); if (e.kind === "incDec") write(e.localId, e.op === "+" ? 1 : null); return everyExprChild(e, expr, stmt); }; + const condition = new Set(); const stmt = (s: IrStmt): boolean => { + const bounded = s.kind === "while" && opaque === 0 && !s.labels?.length; const region = - s.kind === "for" || - s.kind === "while" || - s.kind === "doWhile" || - s.kind === "forOf" || - s.kind === "tryCatch" || - s.kind === "switch"; + !bounded && + (s.kind === "for" || + s.kind === "while" || + s.kind === "doWhile" || + s.kind === "forOf" || + s.kind === "tryCatch" || + s.kind === "switch"); + if (bounded) { + nested.push(s); + conditionWrites(s.cond); + } if (region) opaque++; if (s.kind === "assign") write(s.localId, increment(s.localId, s.value)); if (s.kind === "varDecl" || s.kind === "forOf") write(s.localId, null); @@ -293,7 +308,6 @@ export function guardedLoopCounterFacts( }; // The condition is evaluated before every pass; a write there would // separate the compared value from the one the body sees. - const condition = new Set(); const conditionWrites = (e: IrExpr): boolean => { if (e.kind === "assignExpr" || e.kind === "incDec") condition.add(e.localId); return everyExprChild(e, conditionWrites, (s) => { @@ -304,8 +318,9 @@ export function guardedLoopCounterFacts( }); }; conditionWrites(loop.cond); - for (const id of condition) refused.add(id); loop.body.every(stmt); + // Nested loops' conditions are collected during the walk. + for (const id of condition) refused.add(id); const stable = (id: string): boolean => { const local = locals.get(id); return local !== undefined && !local.boxed && !local.tdz && !budget.has(id) && !refused.has(id); @@ -359,6 +374,11 @@ export function guardedLoopCounterFacts( } return ceiling; }; + // A nested while loop advances only the counters its condition bounds. + for (const inner of nested) { + const caps = ceilings(inner.cond); + for (const id of writtenLocals(inner.body)) if (!caps.has(id)) refused.add(id); + } const ceiling = ceilings(loop.cond); for (const id of budget.keys()) { const local = locals.get(id), @@ -416,6 +436,21 @@ function highestCount( count = Math.max(then, else_); } else if (s.kind === "block" && !s.labels?.length) { count = walk(s.body, count); + } else if ( + s.kind === "while" && + !s.labels?.length && + increments(s.cond, true) === 0 && + ceilings(s.cond).has(id) + ) { + // Every pass starts at most at the bound; the loop ends at its entry + // value or where a pass left the counter. + const cap = ceilings(s.cond).get(id)!; + const outer = highest; + highest = cap; + walk(s.body, cap); + const inner = highest; + highest = Math.max(outer, inner); + count = Math.max(count, inner); } else { count += increments(s, false); highest = Math.max(highest, count); @@ -435,6 +470,21 @@ function highestCount( return highest; } +/** The bindings `body` assigns or increments anywhere. */ +function writtenLocals(body: readonly IrStmt[]): Set { + const ids = new Set(); + const expr = (e: IrExpr): boolean => { + if (e.kind === "assignExpr" || e.kind === "incDec") ids.add(e.localId); + return everyExprChild(e, expr, stmt); + }; + const stmt = (s: IrStmt): boolean => { + if (s.kind === "assign") ids.add(s.localId); + return everyStmtChild(s, expr, stmt); + }; + body.every(stmt); + return ids; +} + /** Recognize only exits whose target cannot be inside this statement list. * Labeled blocks, loops, switch and exception regions retain the join. */ export function integerPathFallsThrough(body: readonly IrStmt[]): boolean { diff --git a/packages/compiler/src/ir/integer-ranges.test.ts b/packages/compiler/src/ir/integer-ranges.test.ts index 32caea672..b495eb814 100644 --- a/packages/compiler/src/ir/integer-ranges.test.ts +++ b/packages/compiler/src/ir/integer-ranges.test.ts @@ -797,6 +797,74 @@ test("a while condition on a string's length bounds a counter, and guarded incre expect(run((inside) => [observe(inside), bump, rebound]).after).toBeNull(); }); +test("a nested while loop may advance a counter its own condition bounds", () => { + // while (pos < text.length) { observe(pos); while (pos < text.length && unknown === 1) pos++; pos += 2; } + const text: IrExpr = { loc, kind: "varRef", localId: "text", type: STRING }; + const length: IrExpr = { + loc, + kind: "strIntrinsic", + method: "length", + receiver: text, + args: [], + type: F64, + }; + const bump: IrStmt = { + loc, + kind: "exprStmt", + expr: { loc, kind: "incDec", op: "+", prefix: false, localId: "pos", type: F64 }, + }; + const skip: IrStmt = { loc, kind: "assign", localId: "pos", value: bin("+", ref("pos"), num(2)) }; + const and = (left: IrExpr, right: IrExpr): IrExpr => ({ + loc, + kind: "logical", + op: "&&", + left, + right, + type: BOOL, + }); + const scan = (cond: IrExpr): IrStmt => ({ loc, kind: "while", cond, body: [bump] }); + const run = (inner: IrStmt) => { + const inside = ref("pos"), + after = ref("pos"); + const f = fn([ + { loc, kind: "assign", localId: "pos", value: num(0) }, + { + loc, + kind: "while", + cond: condition("<", ref("pos"), length), + body: [observe(inside), inner, skip], + }, + observe(after), + ]); + f.locals.push( + { id: "pos", name: "pos", type: F64, mutable: true }, + { id: "text", name: "text", type: STRING, mutable: false }, + ); + const ranges = analyzeIntegerRanges(f); + return { inside: ranges.get(inside), after: ranges.get(after) }; + }; + // Each inner pass starts below the length, so the scan stops at it at the + // latest; the skip then adds 2. + const bounded = scan( + and(condition("<", ref("pos"), length), condition("===", ref("unknown"), num(1))), + ); + expect(run(bounded)).toEqual({ + inside: { min: 0, max: 2147483646 }, + after: { min: 0, max: 2147483649 }, + }); + // A nested loop that does not bound the counter, or writes it in its + // condition, leaves it unbounded. + expect(run(scan(condition("===", ref("unknown"), num(1)))).after).toBeNull(); + const writing = scan( + condition( + "<", + { loc, kind: "incDec", op: "+", prefix: true, localId: "pos", type: F64 }, + length, + ), + ); + expect(run(writing).after).toBeNull(); +}); + test("an array length bounds while and for counters even when the body resizes the array", () => { // let i = 0; while (i < items.length) { observe(i); items.push(i); i++; } observe(i); const ARR = { kind: "array", elem: F64 } as const; From 63001cbc136b3f77653750755f20796022507702 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 21 Oct 2026 23:55:37 -0500 Subject: [PATCH 011/102] Await a suspending stackless callee without its promise --- packages/cli/test/native-link-info.test.ts | 4 +- .../src/backend/llvm/emit-function.ts | 15 ++ packages/compiler/src/backend/llvm/emitter.ts | 66 +++++++++ .../compiler/src/backend/llvm/expr-async.ts | 16 +++ .../compiler/src/backend/llvm/expr-calls.ts | 11 +- packages/compiler/src/backend/mangle.ts | 5 + packages/compiler/src/backend/runtime-abi.ts | 4 +- .../src/backend/runtime-pack-targets.test.ts | 2 +- .../compiler/src/backend/runtime-pack.test.ts | 2 +- .../compiler/test/await-call-emission.test.ts | 52 ++++++- .../test/native-codegen-integration.test.ts | 4 +- .../corpus/7104-direct-await-order.ts.json | 6 + .../corpus/7105-direct-await-context.ts.json | 6 + .../runtime-darwin-arm64/scripts/build.mjs | 2 +- .../runtime-pack-common/scripts/build.mjs | 2 +- packages/runtime/src/scr_async.c | 133 +++++++++++++++++- packages/runtime/src/scr_async.h | 9 ++ packages/runtime/src/scr_console.c | 2 +- packages/runtime/src/scr_core.h | 2 +- tests/corpus/7104-direct-await-order.ts | 96 +++++++++++++ tests/corpus/7105-direct-await-context.ts | 34 +++++ .../7104-direct-await-order.ts.json | 1 + .../7105-direct-await-context.ts.json | 1 + 23 files changed, 452 insertions(+), 23 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7104-direct-await-order.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7105-direct-await-context.ts.json create mode 100644 tests/corpus/7104-direct-await-order.ts create mode 100644 tests/corpus/7105-direct-await-context.ts create mode 100644 tests/harness/corpus-costs/7104-direct-await-order.ts.json create mode 100644 tests/harness/corpus-costs/7105-direct-await-context.ts.json diff --git a/packages/cli/test/native-link-info.test.ts b/packages/cli/test/native-link-info.test.ts index 57c60b1bc..f5ff2642e 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: 23, marker: "scr_runtime_abi_v23" }, + runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, 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_v23"); + expect(error?.stderr).toContain("scr_runtime_abi_v24"); }); }); diff --git a/packages/compiler/src/backend/llvm/emit-function.ts b/packages/compiler/src/backend/llvm/emit-function.ts index 7bbd3d453..8c6264e6c 100644 --- a/packages/compiler/src/backend/llvm/emit-function.ts +++ b/packages/compiler/src/backend/llvm/emit-function.ts @@ -35,6 +35,7 @@ import { mangleArgPack, mangleAsyncAdoptCall, mangleAsyncAwaitCall, + mangleAsyncDirectSpawn, mangleAsyncSpawn, mangleBorrowedFunction, mangleClassStruct, @@ -910,6 +911,20 @@ export function emitAsyncScaffolding(emitter: LlEmitter): string[] { for (const line of emitter.emitAsyncAwaitCall(fn, argPackLines, true)) out.push(line); } const stackless = emitter.stacklessAsync.has(fn.name); + if (stackless && emitter.directAwaitCallees.has(fn.name)) { + // A coroutine's direct await: the same prefix, with the promise kept + // inside the returned fiber record. + emitter.declare(`declare ptr @scr_async_spawn_direct(ptr, ptr)`); + out.push( + `define internal ptr @${mangleAsyncDirectSpawn(fn.name)}(${spawnParams.join(", ")}) ${FN_ATTRS} { ; direct spawn ${fn.name}`, + `entry:`, + ...argPackLines, + ` %f = call ptr @scr_async_spawn_direct(ptr @${mangleTrampoline(fn.name)}, ptr %ap)`, + ` ret ptr %f`, + `}`, + ``, + ); + } const spawn = stackless ? "scr_async_spawn_stackless" : "scr_async_spawn"; emitter.declare(`declare ptr @scr_fiber_promise(ptr)`); emitter.declare(`declare ptr @${spawn}(ptr, ptr)`); diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index b306674fc..eeb89d953 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -889,6 +889,9 @@ export class LlEmitter { /** Fiberless async functions a stackless coroutine body awaits directly; * each gets an inline await entry (emitCoroInlineAwait). */ readonly inlineAwaitCallees = new Set(); + /** Stackless async functions some coroutine body awaits directly: each + * gets a direct spawn entry (emitCoroDirectAwait). */ + readonly directAwaitCallees = new Set(); /** The async functions whose bodies never suspend and that a direct * await may enter in place (selectStacklessAsync). */ private inlineAwaitable = new Set(); @@ -1913,6 +1916,69 @@ export class LlEmitter { return fn.captures === undefined; } + /** Whether a stackless coroutine body's `await f(...)` may await f's + * fiber record instead of its promise (emitCoroDirectAwait): f is a + * stackless async function whose direct call an await-call entry could + * take. The await consumes the promise, so nothing else can observe it. + * Worker programs keep the promise for their stop checkpoint. */ + directAwaitEligible(fnName: string): boolean { + if (this.wasi || this.mod.workers === true || this.currentCoro?.kind !== "async") return false; + const fn = this.fnByName.get(fnName); + if (fn === undefined || fn.async !== true || fn.generator !== undefined) return false; + if (!this.stacklessAsync.has(fnName) || fn.captures !== undefined) return false; + if (fn.returnType.kind === "dyn") return false; + return fn.asyncCacheGlobal === undefined && fn.asyncCycleCacheGlobal === undefined; + } + + /** A stackless coroutine body's `await f(...)` of a stackless f, without + * f's promise object: f's prefix runs as the spawn of a fiber record that + * keeps the promise inside. A body still running wakes this coroutine + * when it finishes, where its promise's settlement would wake its one + * waiter; a finished one takes the settled await's turn. The result (or + * the rejection, re-thrown) comes out of the record, which goes. */ + emitCoroDirectAwait(call: ExprOf<"call">, type: IrType): LlValue { + const coro = this.currentCoro; + if (coro === null) + throw new InternalCompilerError("llvm emitter bug: direct await outside a coroutine"); + const B = this.B; + const record = emitCallExpr(this, call, "direct").name; + this.declare(`declare zeroext i1 @scr_coro_direct_prepare(ptr, ptr)`); + const suspend = B.tmp(); + B.line( + `${suspend} = call zeroext i1 @scr_coro_direct_prepare(ptr ${coro.self}, ptr ${record})`, + ); + const park = B.newLabel("await.suspend"); + const ready = B.newLabel("await.ready"); + B.condBr(suspend, park, ready); + B.startBlock(park); + this.emitCoroSuspendPrepared(); + B.br(ready); + B.startBlock(ready); + if (type.kind === "void") { + this.declare(`declare void @scr_coro_direct_void(ptr)`); + B.line(`call void @scr_coro_direct_void(ptr ${record})`); + this.emitPendingCheck(); + return { name: "", type }; + } + const t = B.tmp(); + if (type.kind === "f64" || type.kind === "date") { + this.declare(`declare double @scr_coro_direct_f64(ptr)`); + B.line(`${t} = call double @scr_coro_direct_f64(ptr ${record})`); + } else if (type.kind === "bool") { + this.declare(`declare zeroext i1 @scr_coro_direct_bool(ptr)`); + B.line(`${t} = call zeroext i1 @scr_coro_direct_bool(ptr ${record})`); + } else if (type.kind === "string") { + this.declare(`declare ptr @scr_coro_direct_str(ptr)`); + B.line(`${t} = call ptr @scr_coro_direct_str(ptr ${record})`); + } else { + this.declare(`declare ptr @scr_coro_direct_ref(ptr)`); + B.line(`${t} = call ptr @scr_coro_direct_ref(ptr ${record})`); + } + const out = this.own({ name: this.adoptHeap(t, type), type }); + this.emitPendingCheck(); + return out; + } + /** The inline await entry of a fiberless async function (`sc_ai_*`): its * body on the caller's stack (between scr_async_inline_enter/exit when * fiberlessFrames), as in its spawn wrapper, returning the result and diff --git a/packages/compiler/src/backend/llvm/expr-async.ts b/packages/compiler/src/backend/llvm/expr-async.ts index 4d73d0904..b5d765b16 100644 --- a/packages/compiler/src/backend/llvm/expr-async.ts +++ b/packages/compiler/src/backend/llvm/expr-async.ts @@ -918,6 +918,22 @@ export function emitAsyncExpr( return host.emitCoroInlineAwait(e.value, e.adopt === true); } } + // A stackless coroutine body awaits a stackless callee's fiber record + // instead of its promise. + if ( + adopted === null && + e.adopt !== true && + e.value.kind === "call" && + host.directAwaitEligible(e.value.callee) + ) { + const callee = host.fnByName.get(e.value.callee)!; + if ( + typeEquals(callee.returnType, e.type) && + !host.callLifetimes.borrowed.has(e.value.callee) + ) { + return host.emitCoroDirectAwait(e.value, e.type); + } + } if (adopted === null && e.value.kind === "call" && host.awaitCallEligible(e.value.callee)) { const callee = host.fnByName.get(e.value.callee)!; if ( diff --git a/packages/compiler/src/backend/llvm/expr-calls.ts b/packages/compiler/src/backend/llvm/expr-calls.ts index 81c44d5a6..f0aa3b276 100644 --- a/packages/compiler/src/backend/llvm/expr-calls.ts +++ b/packages/compiler/src/backend/llvm/expr-calls.ts @@ -31,6 +31,7 @@ import { mangleFunction, mangleWrapper, mangleVtStruct, + mangleAsyncDirectSpawn, } from "../mangle.js"; import { classEnvironmentIndex, @@ -74,7 +75,7 @@ export function emitCallExpr( | "instanceOf" | "virtualCall" >, - awaitEntry: false | "await" | "adopt" | "inline" = false, + awaitEntry: false | "await" | "adopt" | "inline" | "direct" = false, /** A projection consumes a scalar union result (Int32Abi.union): answer * a private stack box instead of a heap box. */ stackResult = false, @@ -184,6 +185,14 @@ export function emitCallExpr( : `${host.llType(callee.params[i]!.type)} ${a.name}`, ) .join(", "); + if (awaitEntry === "direct") { + // A stackless coroutine's await of a stackless callee: the spawn + // returns the callee's fiber record (emitCoroDirectAwait). + host.directAwaitCallees.add(e.callee); + const record = B.tmp(); + B.line(`${record} = call ptr @${mangleAsyncDirectSpawn(e.callee)}(${argList})`); + return { name: record, type: callee.returnType }; + } if (awaitEntry === "inline") { // A stackless coroutine's await of a fiberless callee: the entry // runs the body in place and leaves a throw pending; the enclosing diff --git a/packages/compiler/src/backend/mangle.ts b/packages/compiler/src/backend/mangle.ts index da6cbe0f5..14736ead7 100644 --- a/packages/compiler/src/backend/mangle.ts +++ b/packages/compiler/src/backend/mangle.ts @@ -195,6 +195,11 @@ export function mangleAsyncAdoptCall(fnName: string): string { export function mangleAsyncInlineAwaitCall(fnName: string): string { return `sc_ai_${sanitize(fnName)}`; } +/** A stackless coroutine body's `await f(...)` of a stackless async f: the + * spawn of f's fiber record, which keeps its promise inside (direct await). */ +export function mangleAsyncDirectSpawn(fnName: string): string { + return `sc_dw_${sanitize(fnName)}`; +} export function mangleTrampoline(fnName: string): string { return `sc_tr_${sanitize(fnName)}`; } diff --git a/packages/compiler/src/backend/runtime-abi.ts b/packages/compiler/src/backend/runtime-abi.ts index 67be86571..5eb24482b 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 = 23 as const; -export const RUNTIME_ABI_MARKER = "scr_runtime_abi_v23" as const; +export const RUNTIME_ABI_VERSION = 24 as const; +export const RUNTIME_ABI_MARKER = "scr_runtime_abi_v24" 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 19519e1f2..fc7ed9efa 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: 23, marker: "scr_runtime_abi_v23" }, + runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, compiler: { command: "fixture", identity: "fixture", target: target.llvmTriple }, macros: { executable: [], excluded: ["SCR_LIB"], sanitizer: "external-toolchain-required" }, flavors: { diff --git a/packages/compiler/src/backend/runtime-pack.test.ts b/packages/compiler/src/backend/runtime-pack.test.ts index ee2301172..5ffb4797d 100644 --- a/packages/compiler/src/backend/runtime-pack.test.ts +++ b/packages/compiler/src/backend/runtime-pack.test.ts @@ -124,7 +124,7 @@ async function fixture(target: NativeTargetSpec = MACOS_ARM64_TARGET) { object_format: target.objectFormat, minimum_os: target.minimumOs, }, - runtime_abi: { version: 23, marker: "scr_runtime_abi_v23" }, + runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, compiler: { command: "clang", identity: "fixture clang", diff --git a/packages/compiler/test/await-call-emission.test.ts b/packages/compiler/test/await-call-emission.test.ts index 5d2b614c3..96c039155 100644 --- a/packages/compiler/test/await-call-emission.test.ts +++ b/packages/compiler/test/await-call-emission.test.ts @@ -183,10 +183,16 @@ test("bodies that suspend only at their own awaits compile to stackless coroutin const middle = definition(llvm, "sc_f_middle"); expect(middle).toMatch(/^define internal double @sc_f_middle\(double [^)]*\) #1 /); // Each await prepares its continuation and suspends the coroutine, then - // extracts the settled result; nothing parks the stack it runs on. - expect(middle).toContain("call zeroext i1 @scr_coro_await_prepare(ptr"); - expect(middle).toContain("call double @scr_coro_await_f64(ptr"); - expect(middle).toContain("call ptr @sc_as_slow(double"); + // extracts the settled result; nothing parks the stack it runs on. A + // stackless callee is awaited through its fiber record, without its + // promise (emitCoroDirectAwait). + expect(middle).toContain("call ptr @sc_dw_slow(double"); + expect(middle).toContain("call zeroext i1 @scr_coro_direct_prepare(ptr"); + expect(middle).toContain("call double @scr_coro_direct_f64(ptr"); + expect(middle).not.toContain("@sc_as_slow("); + expect(definition(llvm, "sc_dw_slow")).toContain( + "call ptr @scr_async_spawn_direct(ptr @sc_tr_slow", + ); // A callee that never suspends runs in place; the coroutine takes the // await's turn itself and awaits a rejected promise only on a throw. expect(middle).toContain("call double @sc_ai_leaf(double"); @@ -307,3 +313,41 @@ test("a stackless body runs Promise.all of never-suspending calls in place", asy expect(reused).toContain("call ptr @sc_as_leaf(double"); expect(reused).toContain("@scr_promise_all("); }); + +const directSource = ` +async function slow(x: number): Promise { + await null; + return x + 1; +} +async function direct(x: number): Promise { + return (await slow(x)) * 2; +} +async function adopting(x: number): Promise { + return slow(x); +} +async function kept(x: number): Promise { + const pending = slow(x); + await null; + return await pending; +} +async function main(): Promise { + console.log((await direct(1)) + (await adopting(2)) + (await kept(3))); +} +void main(); +`; + +test("a stackless body awaits a stackless callee's fiber record instead of its promise", async () => { + const llvm = await emit(directSource); + const direct = definition(llvm, "sc_f_direct"); + expect(direct).toContain("call ptr @sc_dw_slow(double"); + expect(direct).toContain("call zeroext i1 @scr_coro_direct_prepare(ptr"); + expect(direct).toContain("call double @scr_coro_direct_f64(ptr"); + expect(direct).not.toContain("@scr_coro_await_prepare("); + // A returned call adopts the callee's promise, and a promise held in a + // local is a value: both keep the promise. + for (const symbol of ["sc_f_adopting", "sc_f_kept"]) { + const body = definition(llvm, symbol); + expect(body, symbol).toContain("call ptr @sc_as_slow(double"); + expect(body, symbol).not.toContain("@sc_dw_slow("); + } +}); diff --git a/packages/compiler/test/native-codegen-integration.test.ts b/packages/compiler/test/native-codegen-integration.test.ts index c0f2cfe84..d8f158ebc 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_v23"); + expect(await symbols(helperObject, ["-u"])).toContain("_scr_runtime_abi_v24"); 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_v23"); + expect(undefinedSymbols).toContain("_scr_runtime_abi_v24"); }); test("helper and clang object paths retain the same outbound FFI C ABI", async () => { diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7104-direct-await-order.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7104-direct-await-order.ts.json new file mode 100644 index 000000000..238ee8fb1 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7104-direct-await-order.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7104-direct-await-order.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7105-direct-await-context.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7105-direct-await-context.ts.json new file mode 100644 index 000000000..2ed3b6aec --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7105-direct-await-context.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7105-direct-await-context.ts" + ], + "diags": [] +} diff --git a/packages/runtime-darwin-arm64/scripts/build.mjs b/packages/runtime-darwin-arm64/scripts/build.mjs index 856de4b86..85c5ffb00 100644 --- a/packages/runtime-darwin-arm64/scripts/build.mjs +++ b/packages/runtime-darwin-arm64/scripts/build.mjs @@ -337,7 +337,7 @@ async function build() { package: packageManifest.name, version: packageManifest.version, target: RUNTIME_PACK_MATRIX.target, - runtime_abi: { version: 23, marker: "scr_runtime_abi_v23" }, + runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, compiler: { command: compiler, identity: compilerVersion, diff --git a/packages/runtime-pack-common/scripts/build.mjs b/packages/runtime-pack-common/scripts/build.mjs index fa84e9c4d..b242b78aa 100644 --- a/packages/runtime-pack-common/scripts/build.mjs +++ b/packages/runtime-pack-common/scripts/build.mjs @@ -434,7 +434,7 @@ async function build() { package: packageManifest.name, version: packageManifest.version, target: matrix.target, - runtime_abi: { version: 23, marker: "scr_runtime_abi_v23" }, + runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, compiler: { command: compiler, identity: compilerVersion, diff --git a/packages/runtime/src/scr_async.c b/packages/runtime/src/scr_async.c index 12cf81f77..db1e54295 100644 --- a/packages/runtime/src/scr_async.c +++ b/packages/runtime/src/scr_async.c @@ -616,6 +616,13 @@ struct ScrFiber { struct ScrFiber *awaiter; /* This fiber was parked by such a child; set before the switch away. */ bool await_parked; + /* A stackless body spawned for a direct await (scr_async_spawn_direct): + * its promise lives in the same block (ScrDirectFiber) and nothing else + * sees it. Once the awaiting coroutine suspends it is direct_awaiter, the + * finished body wakes it in place of the promise's settlement, and the + * awaiter destroys the record when it takes the result. */ + bool direct; + struct ScrFiber *direct_awaiter; #ifdef SCR_ASAN_FIBERS void *fake_stack; /* Live stackless async fibers (scr_async_spawn_stackless) form a list @@ -2138,11 +2145,31 @@ static void scr_prefix_on_fresh_stack(ScrFiber *f, void (*entry)(ScrFiber *, voi } #endif -ScrPromise *scr_async_spawn_stackless(void (*entry)(ScrFiber *, void *), void *argpack) { - ScrFiber *f = scr_mem_calloc(sizeof *f); - if (!f) scr_oom(); +/* A directly awaited body's fiber record and its promise, one block. */ +typedef struct { + ScrFiber fiber; + ScrPromise promise; +} ScrDirectFiber; + +/* Creates a stackless body's fiber and runs its eager prefix, which + * returns at the first suspension or the end. A direct fiber's promise is + * embedded and immortal (retains and releases skip it). */ +static ScrFiber *scr_spawn_stackless_fiber(void (*entry)(ScrFiber *, void *), void *argpack, + bool direct) { + ScrFiber *f; + if (direct) { + ScrDirectFiber *block = scr_mem_calloc(sizeof *block); + if (!block) scr_oom(); + f = &block->fiber; + f->promise = &block->promise; + f->promise->rc = SIZE_MAX; + f->direct = true; + } else { + f = scr_mem_calloc(sizeof *f); + if (!f) scr_oom(); + f->promise = scr_promise_new(); + } scr_fiber_track(f); - f->promise = scr_promise_new(); f->stackless = true; f->als = scr_als_ctx_retain(*SCR_ALS_SLOT()); /* The lifetime region the eager prefix runs in, which every later step @@ -2171,6 +2198,11 @@ ScrPromise *scr_async_spawn_stackless(void (*entry)(ScrFiber *, void *), void *a scr_current = spawner; scr_exc_swap_cell(spawner ? &spawner->exc : NULL); scr_als_active = spawner ? &spawner->als : &scr_als_main_slot; + return f; +} + +ScrPromise *scr_async_spawn_stackless(void (*entry)(ScrFiber *, void *), void *argpack) { + ScrFiber *f = scr_spawn_stackless_fiber(entry, argpack, false); ScrPromise *result = scr_promise_retain(f->promise); if (f->done) { scr_promise_release(f->promise); @@ -2179,6 +2211,14 @@ ScrPromise *scr_async_spawn_stackless(void (*entry)(ScrFiber *, void *), void *a } return result; } + +/* A stackless body that a stackless coroutine awaits right away (the + * compiler's direct await): its promise never escapes, so it is embedded + * in the fiber record, which the awaiter takes the result from + * (scr_coro_direct_*) and then destroys. */ +ScrFiber *scr_async_spawn_direct(void (*entry)(ScrFiber *, void *), void *argpack) { + return scr_spawn_stackless_fiber(entry, argpack, true); +} #endif static void scr_await_park(ScrPromise *p); @@ -2447,7 +2487,28 @@ bool scr_coro_await_prepare(ScrFiber *self, ScrPromise *p) { bool scr_coro_hop_prepare(ScrFiber *self) { return scr_coro_hop_needed(self); } -void scr_coro_async_finish(ScrFiber *self) { scr_fiber_finish(self); } +/* A directly awaited body's end: its awaiter is the promise's only waiter, + * and it observes a rejection when it takes the result, so the body wakes + * it where the settlement would, without the unhandled-rejection ledger. */ +static void scr_direct_finish(ScrFiber *self) { + ScrPromise *p = self->promise; + bool stopped = false; +#ifdef SCR_WORKERS + /* A stop request rejects like the fiber epilogue does (scr_fiber_finish). */ + stopped = scr_context_checkpoint(); +#endif + if (stopped || scr_exc_pending()) scr_promise_reject_from_cell(p, &self->exc); + if (stopped) p->rejection_observed = true; + if (p->state == SCR_PROM_PENDING) + scr_trap("scriptc: internal error: directly awaited body finished unsettled\n"); + self->done = true; + if (self->direct_awaiter != NULL) scr_promise_wake_one(self->direct_awaiter); +} + +void scr_coro_async_finish(ScrFiber *self) { + if (self->direct) scr_direct_finish(self); + else scr_fiber_finish(self); +} /* Extraction after the await's suspension: the promise has settled. */ static bool scr_coro_await_settled(ScrPromise *p) { @@ -2470,6 +2531,66 @@ ScrStr *scr_coro_await_str(ScrPromise *p) { void *scr_coro_await_ref(ScrPromise *p) { return scr_coro_await_settled(p) && p->payload ? p->retain_fn(p->payload) : NULL; } + +/* A direct await of a stackless body (scr_async_spawn_direct): a body + * still running gets the coroutine as its only awaiter, which its finish + * wakes as a settlement wakes a promise's waiter; a finished body is a + * settled promise, which takes one microtask turn. */ +bool scr_coro_direct_prepare(ScrFiber *self, ScrFiber *callee) { + if (!callee->done) { + callee->direct_awaiter = self; + return true; + } + return scr_coro_hop_needed(self); +} + +/* The result of a finished direct body: its promise's settlement, read as + * scr_coro_await_* reads it (a rejection re-throws), then the record goes. */ +static inline void scr_direct_destroy(ScrFiber *f) { + /* Only a rejection reason is left: values moved out, and nothing waits + * on or shares the promise. */ + if (f->promise->payload_kind != SCR_EXC_NONE) scr_promise_release_payload(f->promise); + scr_fiber_destroy(f); + scr_fibers_live--; +} + +void scr_coro_direct_void(ScrFiber *f) { + scr_coro_await_settled(f->promise); + scr_direct_destroy(f); +} +double scr_coro_direct_f64(ScrFiber *f) { + double v = scr_coro_await_settled(f->promise) ? f->promise->f64 : 0; + scr_direct_destroy(f); + return v; +} +bool scr_coro_direct_bool(ScrFiber *f) { + bool v = scr_coro_await_settled(f->promise) ? f->promise->b : false; + scr_direct_destroy(f); + return v; +} +/* String and reference results move out of the record (+1). */ +ScrStr *scr_coro_direct_str(ScrFiber *f) { + ScrPromise *p = f->promise; + ScrStr *v = NULL; + if (scr_coro_await_settled(p)) { + v = (ScrStr *)p->payload; + p->payload = NULL; + p->payload_kind = SCR_EXC_NONE; + } + scr_direct_destroy(f); + return v; +} +void *scr_coro_direct_ref(ScrFiber *f) { + ScrPromise *p = f->promise; + void *v = NULL; + if (scr_coro_await_settled(p)) { + v = p->payload; + p->payload = NULL; + p->payload_kind = SCR_EXC_NONE; + } + scr_direct_destroy(f); + return v; +} #endif /* One microtask hop: park the current fiber on the READY queue itself and @@ -3982,7 +4103,7 @@ static void scr_resume_fiber(ScrFiber *f) { scr_loop_reap = NULL; } #endif - if (f->done) { + if (f->done && !f->direct) { scr_promise_release(f->promise); scr_fiber_destroy(f); scr_fibers_live--; diff --git a/packages/runtime/src/scr_async.h b/packages/runtime/src/scr_async.h index 041d2ea03..827c303f9 100644 --- a/packages/runtime/src/scr_async.h +++ b/packages/runtime/src/scr_async.h @@ -109,6 +109,15 @@ double scr_coro_await_f64(ScrPromise *p); bool scr_coro_await_bool(ScrPromise *p); ScrStr *scr_coro_await_str(ScrPromise *p); /* +1 */ void *scr_coro_await_ref(ScrPromise *p); /* +1 via the stored retain */ +/* A direct await of a stackless body: its promise stays inside the fiber + * record the spawn returns, and the awaiter takes the result from it. */ +ScrFiber *scr_async_spawn_direct(void (*entry)(ScrFiber *, void *), void *argpack); +bool scr_coro_direct_prepare(ScrFiber *self, ScrFiber *callee); +void scr_coro_direct_void(ScrFiber *f); +double scr_coro_direct_f64(ScrFiber *f); +bool scr_coro_direct_bool(ScrFiber *f); +ScrStr *scr_coro_direct_str(ScrFiber *f); /* +1 */ +void *scr_coro_direct_ref(ScrFiber *f); /* +1 */ double scr_await_f64(ScrPromise *p); /* rejected promises re-throw */ bool scr_await_bool(ScrPromise *p); diff --git a/packages/runtime/src/scr_console.c b/packages/runtime/src/scr_console.c index 0afb8981a..c29126a4a 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_v23(void) {} +void scr_runtime_abi_v24(void) {} void scr_init(void) { #ifdef SCR_WORKERS diff --git a/packages/runtime/src/scr_core.h b/packages/runtime/src/scr_core.h index cdf1061d9..94936a8aa 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_v23(void); +void scr_runtime_abi_v24(void); void scr_runtime_workers_v8(void); /* ── the trap funnel (scr_console.c; scr_library.c under -DSCR_LIB) ────── diff --git a/tests/corpus/7104-direct-await-order.ts b/tests/corpus/7104-direct-await-order.ts new file mode 100644 index 000000000..ab4f438c4 --- /dev/null +++ b/tests/corpus/7104-direct-await-order.ts @@ -0,0 +1,96 @@ +// A stackless async body awaiting a stackless callee that suspends: +// results of each kind, callees that finish without suspending, nested +// chains, throws before and after the first suspension, and an uncaught +// rejection, against a ticker that logs every microtask turn. +interface Point { + x: number; + y: number; +} +const log: string[] = []; + +async function slowNumber(n: number, turns: number): Promise { + for (let i = 0; i < turns; i++) await null; + log.push(`slowNumber ${n} done`); + return n * 2; +} +async function maybeSuspend(n: number): Promise { + if (n > 0) await null; + log.push(`maybeSuspend ${n}`); + return n + 100; +} +async function slowFlag(n: number): Promise { + await null; + return n % 2 === 0; +} +async function slowLabel(s: string): Promise { + await null; + return `<${s}>`; +} +async function slowPoint(n: number): Promise { + await null; + return { x: n, y: n * n }; +} +async function slowVoid(tag: string): Promise { + await null; + log.push(`slowVoid ${tag}`); +} +async function throwsEarly(n: number): Promise { + if (n > 0) throw new RangeError(`early ${n}`); + await null; + return n; +} +async function throwsLate(n: number): Promise { + await null; + await null; + throw new TypeError(`late ${n}`); +} +async function chain(depth: number): Promise { + await null; + if (depth === 0) return 1; + return 1 + (await chain(depth - 1)); +} +function ticker(name: string, turns: number): Promise { + let p = Promise.resolve(); + for (let i = 0; i < turns; i++) p = p.then(() => void log.push(`${name} tick ${i}`)); + return p; +} + +async function values(): Promise { + const a = await slowNumber(1, 2); + const b = await maybeSuspend(0); + const c = await maybeSuspend(1); + const f = await slowFlag(4); + const s = await slowLabel("x"); + const p = await slowPoint(3); + await slowVoid("v"); + log.push(`values ${a} ${b} ${c} ${f} ${s} ${p.x + p.y}`); +} +async function errors(): Promise { + try { + await throwsEarly(1); + } catch (e) { + log.push(`errors caught ${(e as Error).name} ${(e as Error).message}`); + } + try { + await throwsLate(2); + } catch (e) { + log.push(`errors caught ${(e as Error).name} ${(e as Error).message}`); + } + log.push(`errors ok ${await throwsEarly(0)}`); +} +async function nested(): Promise { + log.push(`nested ${await chain(4)}`); +} +async function uncaught(): Promise { + await slowNumber(9, 1); + await throwsLate(9); + log.push("uncaught resolved"); +} + +process.on("unhandledRejection", (reason) => console.log(`unhandled ${(reason as Error).message}`)); +async function main(): Promise { + void uncaught(); + await Promise.all([ticker("t", 10), values(), ticker("u", 3), errors(), nested()]); + for (const line of log) console.log(line); +} +void main(); diff --git a/tests/corpus/7105-direct-await-context.ts b/tests/corpus/7105-direct-await-context.ts new file mode 100644 index 000000000..c5a6bd40e --- /dev/null +++ b/tests/corpus/7105-direct-await-context.ts @@ -0,0 +1,34 @@ +// AsyncLocalStorage across a stackless body's awaits of stackless callees: +// each callee inherits its caller's store at the call, a store a callee +// enters after its first await stays inside it, and run() scopes survive +// the awaits. +import { AsyncLocalStorage } from "node:async_hooks"; + +const store = new AsyncLocalStorage(); +const log: string[] = []; + +async function read(tag: string): Promise { + await null; + return `${tag}=${store.getStore() ?? "none"}`; +} +async function enters(tag: string): Promise { + await null; + store.enterWith(`inner-${tag}`); + await null; + return `${tag}=${store.getStore() ?? "none"}`; +} +async function body(name: string): Promise { + log.push(await read(`${name}.first`)); + log.push(await enters(`${name}.enters`)); + log.push(await read(`${name}.after`)); +} + +async function main(): Promise { + await Promise.all([ + store.run("a", () => body("a")), + store.run("b", () => body("b")), + body("none"), + ]); + for (const line of log) console.log(line); +} +void main(); diff --git a/tests/harness/corpus-costs/7104-direct-await-order.ts.json b/tests/harness/corpus-costs/7104-direct-await-order.ts.json new file mode 100644 index 000000000..17c78c9c9 --- /dev/null +++ b/tests/harness/corpus-costs/7104-direct-await-order.ts.json @@ -0,0 +1 @@ +{ "plain": 3100, "san": 4100 } diff --git a/tests/harness/corpus-costs/7105-direct-await-context.ts.json b/tests/harness/corpus-costs/7105-direct-await-context.ts.json new file mode 100644 index 000000000..78ee9421a --- /dev/null +++ b/tests/harness/corpus-costs/7105-direct-await-context.ts.json @@ -0,0 +1 @@ +{ "plain": 2300, "san": 3100 } From 561f66cf5b70fdcfeed8cbf93dc8fac02cd981c9 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 00:16:11 -0500 Subject: [PATCH 012/102] Reuse deferred initializer scans while only bindings are pending --- .../deferred-module-initializers.test.ts | 20 + .../lowering/deferred-module-initializers.ts | 354 +++++++++++++----- 2 files changed, 275 insertions(+), 99 deletions(-) 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 53d6bac87..28f05bfce 100644 --- a/packages/compiler/src/frontend/lowering/deferred-module-initializers.test.ts +++ b/packages/compiler/src/frontend/lowering/deferred-module-initializers.test.ts @@ -91,6 +91,26 @@ test("finds replaced blocks and references appended to an existing body in a lat expect(functions[0]!.body).toEqual([{ kind: "block", body: [value(7)], loc }]); }); +test("reuses the scan of an unchanged body while only bindings are pending", () => { + const { initializers, pending, lowerer } = fixture(); + const placeholder = block(loc); + const functions = [fn("init", [placeholder]), fn("use", [value(1)])]; + pending.set("registry", [{ loc, lower: () => [value(7)] }]); + expect(initializers.process(lowerer, functions)).toBe(false); + const walk = vi.spyOn(traversal, "everyStmtList"); + try { + expect(initializers.process(lowerer, functions)).toBe(false); + expect(walk).not.toHaveBeenCalled(); + // A statement added to the same list is found. + functions[1]!.body.push(read("registry")); + expect(initializers.process(lowerer, functions)).toBe(true); + expect(walk.mock.calls.filter(([body]) => body === functions[0]!.body)).toHaveLength(0); + } finally { + walk.mockRestore(); + } + expect(placeholder.body).toEqual([value(7)]); +}); + test("indexes new subtrees for other demanded initializers in the same pass", () => { const { initializers, pending, lowerer } = fixture(); const nestedLoc = { ...loc, start: 10, end: 11 }; diff --git a/packages/compiler/src/frontend/lowering/deferred-module-initializers.ts b/packages/compiler/src/frontend/lowering/deferred-module-initializers.ts index b80eb7ac0..eb22b4085 100644 --- a/packages/compiler/src/frontend/lowering/deferred-module-initializers.ts +++ b/packages/compiler/src/frontend/lowering/deferred-module-initializers.ts @@ -12,6 +12,7 @@ import { } from "./lower-classes.js"; import { classPrototypeData } from "./class-prototypes.js"; import { bindingNeverReassigned } from "./binding-analysis.js"; +import { InternalCompilerError } from "../../errors.js"; /** A registry of existing class/function values allocates data, but does * not execute those bodies. Keep its initializer at its source position @@ -20,6 +21,10 @@ import { bindingNeverReassigned } from "./binding-analysis.js"; export class DeferredModuleInitializers { private readonly pending = new Map IrStmt[] }[]>(); private readonly registryGlobals = new Set(); + /** Every key ever deferred, pending or materialized. */ + private readonly deferredKeys = new Set(); + /** The last scan of each function (scanOf). */ + private readonly scans = new Map(); defer(lowerer: Lowerer, statement: ts.Statement): IrStmt | null { let key: string; @@ -126,6 +131,83 @@ export class DeferredModuleInitializers { process(lowerer: Lowerer, functions: readonly IrFunction[]): boolean { if (this.pending.size === 0) return false; + // Scans keep only the reads of deferred bindings. + for (const key of this.pending.keys()) { + if (this.deferredKeys.has(key)) continue; + this.deferredKeys.add(key); + this.scans.clear(); + } + // Class and prototype keys follow the classes IR types reach, and passes + // change those inside statements they keep (a bag initializer gains a + // prototype). While only bindings are pending, the scans of unchanged + // statement lists are reused; SCRIPTC_CHECK_DEFERRED_SCANS=1 checks each + // such pass against fresh scans. + const bindingsOnly = ![...this.pending.keys()].some( + (key) => key.startsWith("class:") || key.startsWith("prototype:"), + ); + const scans = functions.map((fn) => this.scanOf(lowerer, fn, bindingsOnly)); + const demanded = this.demanded(lowerer, functions, scans); + if (CHECK_SCANS && bindingsOnly) { + const fresh = functions.map((fn) => scanFunction(lowerer, fn, this.deferredKeys)); + const expected = this.demanded(lowerer, functions, fresh); + const blocks = (list: readonly FunctionScan[]): PlaceholderBlock[] => + list.flatMap((scan) => scan.placeholders.filter((block) => block.body.length === 0)); + const reused = blocks(scans); + const live = blocks(fresh); + if ( + [...demanded].join("\0") !== [...expected].join("\0") || + reused.length !== live.length || + reused.some((block, index) => block !== live[index]) + ) + throw new InternalCompilerError( + "reused deferred initializer scans disagree with a fresh scan", + ); + } + if (demanded.size === 0) return false; + // The placeholders come from the scans, which are fresh for every list a + // transform replaced between waves. Each is kept with the functions whose + // bodies hold it. Searching every body again for each initializer would + // make materializing large module registries quadratic in the program size. + const placeholders = new Map(); + const add = (block: PlaceholderBlock, fns: IrFunction[]): void => { + const key = locationKey(block.loc); + const blocks = placeholders.get(key) ?? []; + blocks.push({ block, fns }); + placeholders.set(key, blocks); + }; + functions.forEach((fn, index) => { + for (const block of scans[index]!.placeholders) if (block.body.length === 0) add(block, [fn]); + }); + for (const id of demanded) { + const initialize = this.pending.get(id)!; + this.pending.delete(id); + for (const action of initialize) { + const body = action.lower(); + const holders: IrFunction[] = []; + for (const { block, fns } of placeholders.get(locationKey(action.loc)) ?? []) { + if (block.body.length === 0) { + block.body.push(...body); + holders.push(...fns); + } + } + if (holders.length === 0) continue; + // These bodies changed inside unchanged statement lists. + for (const fn of holders) this.scans.delete(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); + } + } + return demanded.size !== 0; + } + + /** The pending keys the scanned functions reference, in the order the + * functions and their walks meet them. */ + private demanded( + lowerer: Lowerer, + functions: readonly IrFunction[], + scans: readonly FunctionScan[], + ): Set { const demanded = new Set(); const classHelpers = new Map(); for (const info of lowerer.classes.values()) { @@ -133,116 +215,190 @@ export class DeferredModuleInitializers { if (info.def.prototypeDataHelper) classHelpers.set(info.def.prototypeDataHelper, `prototype:${info.def.name}`); } - const seen = new Set(); - const byName = new Map(functions.map((fn) => [fn.name, fn])); - const inspectedHelpers = new Set(); + const byName = new Map(functions.map((fn, index) => [fn.name, index])); const usedHelpers: string[] = []; - const demandType = (type: IrType): void => { - if (seen.has(type)) return; - seen.add(type); - if (type.kind === "object" || type.kind === "classval") { - for (let info = lowerer.classes.get(type.className); info; info = info.base ?? undefined) { - const key = `class:${info.def.name}`; - if (this.pending.has(key)) demanded.add(key); - const prototype = `prototype:${info.def.name}`; - if (type.kind === "object" && this.pending.has(prototype)) demanded.add(prototype); + const demand = (events: readonly ScanEvent[]): void => { + for (const event of events) { + if (event.kind === "read") { + if (this.pending.has(event.id)) demanded.add(event.id); + } else if (event.kind === "call") { + const owner = classHelpers.get(event.callee); + if (owner) { + if (this.pending.has(owner)) demanded.add(owner); + usedHelpers.push(event.callee); + } + } else { + for ( + let info = lowerer.classes.get(event.className); + info; + info = info.base ?? undefined + ) { + const key = `class:${info.def.name}`; + if (this.pending.has(key)) demanded.add(key); + const prototype = `prototype:${info.def.name}`; + if (event.kind === "object" && this.pending.has(prototype)) demanded.add(prototype); + } } - } else if (type.kind === "array") demandType(type.elem); - else if (type.kind === "union") lowerer.unions.get(type.unionId)?.arms.forEach(demandType); - else if (type.kind === "record") { - const shape = lowerer.shapes.get(type.shapeId); - shape?.fields.forEach((field) => demandType(field.type)); - if (shape?.indexValue) demandType(shape.indexValue); - } else if (type.kind === "func") { - type.params.forEach(demandType); - demandType(type.ret); - } else if (type.kind === "promise") demandType(type.inner); + } }; - for (const fn of functions) { + functions.forEach((fn, index) => { // Prototype helpers are allocated eagerly while collecting metadata. // Their base-helper calls must not make unused classes reachable. - if (classHelpers.has(fn.name)) continue; - fn.params.forEach((param) => demandType(param.type)); - demandType(fn.returnType); - everyStmtList(fn.body, { - stmt: () => true, - expr: (expr) => { - demandType(expr.type); - if (readsBinding(expr) && this.pending.has(expr.localId)) demanded.add(expr.localId); - if (expr.kind === "call") { - const owner = classHelpers.get(expr.callee); - if (owner) { - if (this.pending.has(owner)) demanded.add(owner); - usedHelpers.push(expr.callee); - } - } - return true; - }, - }); - } + if (classHelpers.has(fn.name)) return; + demand(scans[index]!.signature); + demand(scans[index]!.body); + }); + const inspectedHelpers = new Set(); while (usedHelpers.length) { const name = usedHelpers.pop()!; if (inspectedHelpers.has(name)) continue; inspectedHelpers.add(name); - const fn = byName.get(name); - if (!fn) continue; - everyStmtList(fn.body, { - stmt: () => true, - expr: (expr) => { - demandType(expr.type); - if (readsBinding(expr) && this.pending.has(expr.localId)) demanded.add(expr.localId); - if (expr.kind === "call") { - const owner = classHelpers.get(expr.callee); - if (owner) { - if (this.pending.has(owner)) demanded.add(owner); - usedHelpers.push(expr.callee); - } - } - return true; - }, - }); + const index = byName.get(name); + if (index !== undefined) demand(scans[index]!.body); } - if (demanded.size === 0) return false; - // Transforms replace blocks between waves, so index the live placeholders - // anew in each pass. Searching every body again for each initializer makes - // materializing large module registries quadratic in the program size. - const placeholders = new Map[]>(); - const locationKey = (loc: IrStmt["loc"]): string => - JSON.stringify([loc.file, loc.start, loc.end]); - const indexPlaceholders = (body: IrStmt[]): void => { - everyStmtList(body, { - stmt: (statement) => { - if (statement.kind === "block" && statement.body.length === 0) { - const key = locationKey(statement.loc); - const blocks = placeholders.get(key) ?? []; - blocks.push(statement); - placeholders.set(key, blocks); - } - return true; - }, - expr: () => true, - }); - }; - for (const fn of functions) indexPlaceholders(fn.body); - for (const id of demanded) { - const initialize = this.pending.get(id)!; - this.pending.delete(id); - for (const action of initialize) { - const body = action.lower(); - let inserted = false; - for (const block of placeholders.get(locationKey(action.loc)) ?? []) { - if (block.body.length === 0) { - block.body.push(...body); - inserted = true; - } - } - // An inserted body can introduce a placeholder needed by another - // action in this pass. Unattached bodies are not part of the live IR. - if (inserted) indexPlaceholders(body); - } - } - return demanded.size !== 0; + return demanded; } + + /** What `fn` references that can demand an initializer, in the order a + * walk of it meets them. While only bindings are pending (`reuse`), a + * function's scan is reused while its statement list is the same array + * with the same length and the same first and last statements: passes that + * change a body either replace its list or add statements to it, and this + * pass forgets the scan of a function whose placeholder it fills. */ + private scanOf(lowerer: Lowerer, fn: IrFunction, reuse: boolean): FunctionScan { + const cached = this.scans.get(fn); + if ( + reuse && + cached !== undefined && + cached.statements === fn.body && + cached.length === fn.body.length && + cached.first === fn.body[0] && + cached.last === fn.body[fn.body.length - 1] + ) { + return cached; + } + const scan = scanFunction(lowerer, fn, this.deferredKeys); + this.scans.set(fn, scan); + return scan; + } +} + +type PlaceholderBlock = Extract; + +/** One reference a scan records: a class an IR type reaches (`object` also + * reaches its prototype), a binding read, or a call to a class data + * helper. */ +type ScanEvent = + | { kind: "object" | "classval"; className: string } + | { kind: "read"; id: string } + | { kind: "call"; callee: string }; + +interface FunctionScan { + statements: IrStmt[]; + length: number; + first: IrStmt | undefined; + last: IrStmt | undefined; + /** References of the parameter and return types. */ + signature: ScanEvent[]; + /** References of the body's expressions. */ + body: ScanEvent[]; + /** Empty blocks, in walk order: an initializer's position. */ + placeholders: PlaceholderBlock[]; +} + +/** Class data helpers (classStaticData, classPrototypeData). */ +const CLASS_HELPER_PREFIXES = ["%static.data.", "%prototype.data."]; + +/** SCRIPTC_CHECK_DEFERRED_SCANS=1 checks each pass that reuses scans against fresh scans. */ +const CHECK_SCANS = process.env["SCRIPTC_CHECK_DEFERRED_SCANS"] === "1"; + +function locationKey(loc: IrStmt["loc"]): string { + return JSON.stringify([loc.file, loc.start, loc.end]); +} + +/** The references of `fn` (FunctionScan). Each reference is kept at its + * first occurrence, except calls, and only reads of `deferred` keys. */ +function scanFunction( + lowerer: Lowerer, + fn: IrFunction, + deferred: ReadonlySet, +): FunctionScan { + const signature: ScanEvent[] = []; + const typeEvents = typeScanner(lowerer, signature); + for (const param of fn.params) typeEvents(param.type); + typeEvents(fn.returnType); + const { body, placeholders } = scanStatements(fn.body, lowerer, deferred); + return { + statements: fn.body, + length: fn.body.length, + first: fn.body[0], + last: fn.body[fn.body.length - 1], + signature, + body, + placeholders, + }; +} + +/** Records, once each, the classes the types it is given reach. */ +function typeScanner(lowerer: Lowerer, events: ScanEvent[]): (type: IrType) => void { + const seen = new Set(); + const classes = new Set(); + const visit = (type: IrType): void => { + if (seen.has(type)) return; + seen.add(type); + if (type.kind === "object" || type.kind === "classval") { + const key = `${type.kind}:${type.className}`; + if (!classes.has(key)) { + classes.add(key); + events.push({ kind: type.kind, className: type.className }); + } + } else if (type.kind === "array") visit(type.elem); + else if (type.kind === "union") lowerer.unions.get(type.unionId)?.arms.forEach(visit); + else if (type.kind === "record") { + const shape = lowerer.shapes.get(type.shapeId); + shape?.fields.forEach((field) => visit(field.type)); + if (shape?.indexValue) visit(shape.indexValue); + } else if (type.kind === "func") { + type.params.forEach(visit); + visit(type.ret); + } else if (type.kind === "promise") visit(type.inner); + }; + return visit; +} + +/** The references and placeholders of a statement list. Without a lowerer + * it collects only placeholders. */ +function scanStatements( + statements: IrStmt[], + lowerer?: Lowerer, + deferred?: ReadonlySet, +): { body: ScanEvent[]; placeholders: PlaceholderBlock[] } { + const body: ScanEvent[] = []; + const placeholders: PlaceholderBlock[] = []; + const typeEvents = lowerer ? typeScanner(lowerer, body) : null; + const reads = new Set(); + everyStmtList(statements, { + stmt: (statement) => { + if (statement.kind === "block" && statement.body.length === 0) placeholders.push(statement); + return true; + }, + expr: (expr) => { + if (typeEvents === null) return true; + typeEvents(expr.type); + if (readsBinding(expr) && deferred!.has(expr.localId) && !reads.has(expr.localId)) { + reads.add(expr.localId); + body.push({ kind: "read", id: expr.localId }); + } + // Every call, as the helpers are visited from a stack in call order. + if ( + expr.kind === "call" && + CLASS_HELPER_PREFIXES.some((prefix) => expr.callee.startsWith(prefix)) + ) + body.push({ kind: "call", callee: expr.callee }); + return true; + }, + }); + return { body, placeholders }; } /** A read of a binding's current value: a plain read, or an update From 321873b9576c9692d9193c2193b18a7da00d4ccc Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 00:18:36 -0500 Subject: [PATCH 013/102] Compile JavaScript-path calls that Node runs --- .../builtin-apis/streams-and-readline.mdx | 1 + .../compiler/src/backend/llvm/lib-shared.ts | 3 + .../src/frontend/lowering/builtins/atomics.ts | 16 +++-- .../src/frontend/lowering/builtins/numbers.ts | 18 ++--- .../frontend/lowering/builtins/readline.ts | 34 +++++++--- .../lowering/containers/string-and-regexp.ts | 36 ++++++++-- packages/compiler/src/ir/builtin-effects.ts | 3 + .../compiler/src/ir/builtin-signatures.ts | 3 + .../6862-readline-chained-listeners.cjs.json | 6 ++ ...6865-number-parseint-default-radix.ts.json | 6 ++ .../6866-number-parseint-untyped.js.json | 6 ++ .../6867-string-match-optional-regexp.js.json | 6 ++ ...-buffer-from-untyped-array-buffer.cjs.json | 6 ++ .../6869-atomics-untyped-arrays.cjs.json | 6 ++ packages/runtime/src/scr_bytes_io.c | 13 ++++ packages/runtime/src/scr_lib.h | 3 + packages/runtime/src/scr_shared.c | 68 +++++++++++++++++++ .../6862-readline-chained-listeners.cjs | 29 ++++++++ .../6865-number-parseint-default-radix.ts | 16 +++++ tests/corpus/6866-number-parseint-untyped.js | 9 +++ .../6867-string-match-optional-regexp.js | 20 ++++++ .../6868-buffer-from-untyped-array-buffer.cjs | 38 +++++++++++ tests/corpus/6869-atomics-untyped-arrays.cjs | 65 ++++++++++++++++++ .../6862-readline-chained-listeners.cjs.json | 1 + ...6865-number-parseint-default-radix.ts.json | 1 + .../6866-number-parseint-untyped.js.json | 1 + .../6867-string-match-optional-regexp.js.json | 1 + ...-buffer-from-untyped-array-buffer.cjs.json | 1 + .../6869-atomics-untyped-arrays.cjs.json | 1 + 29 files changed, 388 insertions(+), 29 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6862-readline-chained-listeners.cjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6865-number-parseint-default-radix.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6866-number-parseint-untyped.js.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6867-string-match-optional-regexp.js.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6869-atomics-untyped-arrays.cjs.json create mode 100644 tests/corpus/6862-readline-chained-listeners.cjs create mode 100644 tests/corpus/6865-number-parseint-default-radix.ts create mode 100644 tests/corpus/6866-number-parseint-untyped.js create mode 100644 tests/corpus/6867-string-match-optional-regexp.js create mode 100644 tests/corpus/6868-buffer-from-untyped-array-buffer.cjs create mode 100644 tests/corpus/6869-atomics-untyped-arrays.cjs create mode 100644 tests/harness/corpus-costs/6862-readline-chained-listeners.cjs.json create mode 100644 tests/harness/corpus-costs/6865-number-parseint-default-radix.ts.json create mode 100644 tests/harness/corpus-costs/6866-number-parseint-untyped.js.json create mode 100644 tests/harness/corpus-costs/6867-string-match-optional-regexp.js.json create mode 100644 tests/harness/corpus-costs/6868-buffer-from-untyped-array-buffer.cjs.json create mode 100644 tests/harness/corpus-costs/6869-atomics-untyped-arrays.cjs.json diff --git a/docs/content/limitations/builtin-apis/streams-and-readline.mdx b/docs/content/limitations/builtin-apis/streams-and-readline.mdx index a21f7a617..046f7d6b5 100644 --- a/docs/content/limitations/builtin-apis/streams-and-readline.mdx +++ b/docs/content/limitations/builtin-apis/streams-and-readline.mdx @@ -19,6 +19,7 @@ Stream constructors accept a `signal` option in an options object literal, and `stream.addAbortSignal` accepts any stream. 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/packages/compiler/src/backend/llvm/lib-shared.ts b/packages/compiler/src/backend/llvm/lib-shared.ts index 8bb8bc3aa..683211762 100644 --- a/packages/compiler/src/backend/llvm/lib-shared.ts +++ b/packages/compiler/src/backend/llvm/lib-shared.ts @@ -1037,6 +1037,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", 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/numbers.ts b/packages/compiler/src/frontend/lowering/builtins/numbers.ts index 18ca0f1f3..1ff35fbb5 100644 --- a/packages/compiler/src/frontend/lowering/builtins/numbers.ts +++ b/packages/compiler/src/frontend/lowering/builtins/numbers.ts @@ -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,7 +98,10 @@ 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 }; } const argText = 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/containers/string-and-regexp.ts b/packages/compiler/src/frontend/lowering/containers/string-and-regexp.ts index 9567ee0f6..38865093f 100644 --- a/packages/compiler/src/frontend/lowering/containers/string-and-regexp.ts +++ b/packages/compiler/src/frontend/lowering/containers/string-and-regexp.ts @@ -919,12 +919,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 +982,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")) { @@ -1920,3 +1920,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/ir/builtin-effects.ts b/packages/compiler/src/ir/builtin-effects.ts index ca8c52118..482739db5 100644 --- a/packages/compiler/src/ir/builtin-effects.ts +++ b/packages/compiler/src/ir/builtin-effects.ts @@ -97,6 +97,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", diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index fa7876579..49683550e 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -1252,6 +1252,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 }, 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/runtime/src/scr_bytes_io.c b/packages/runtime/src/scr_bytes_io.c index 5532d96da..ac8fad02e 100644 --- a/packages/runtime/src/scr_bytes_io.c +++ b/packages/runtime/src/scr_bytes_io.c @@ -1299,8 +1299,19 @@ ScrBytes *scr_buffer_concat_len_dyn(const ScrDyn *list, double total) { return scr_buffer_concat_dyn_impl(list, total, true); } +/* Buffer.from(arrayBuffer) over a checked value: a Buffer over all of the + * ArrayBuffer or SharedArrayBuffer that shares its memory, as in Node. A + * second argument would be the byte offset, and an encoding name converts + * to NaN, which is offset 0. */ +static ScrBytes *scr_buffer_from_storage(const ScrDyn *storage) { + ScrBytes *out = scr_bytes_buffer_view(storage->v.handle.ptr, SCR_BYTES_U8, 0, 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); + if (scr_buffer_storage_is(value)) return scr_buffer_from_storage(value); 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 +1355,8 @@ 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. */ + if (scr_buffer_storage_is(value)) return scr_buffer_from_storage(value); ScrBytes *out = scr_buffer_from_dyn(value, encoding); if (!out) return NULL; out->is_buffer = true; diff --git a/packages/runtime/src/scr_lib.h b/packages/runtime/src/scr_lib.h index 1b859cea1..3ce18d793 100644 --- a/packages/runtime/src/scr_lib.h +++ b/packages/runtime/src/scr_lib.h @@ -365,6 +365,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_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/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..f525f24cf --- /dev/null +++ b/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs @@ -0,0 +1,38 @@ +// Buffer.from over an untyped ArrayBuffer or SharedArrayBuffer (read from a +// Map, an untyped object field or a worker message): the Buffer covers the +// whole buffer and shares its memory, in both directions, as in Node. An +// encoding name in the second argument converts to byte offset 0. +'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 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/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 } From 71dccbb8a837820ff56fad25d367fc76d3688810 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 00:31:48 -0500 Subject: [PATCH 014/102] Declare runtime ABI 24 in the native toolchain test's runtime pack fixture The toolchain integrity test builds a runtime pack manifest by hand. It still declared ABI 23 after the runtime ABI moved to 24, so the staging check rejected the pack instead of staging it. --- tests/harness/self-hosting-native-toolchain.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/harness/self-hosting-native-toolchain.test.ts b/tests/harness/self-hosting-native-toolchain.test.ts index 6d028d597..7da7626b7 100644 --- a/tests/harness/self-hosting-native-toolchain.test.ts +++ b/tests/harness/self-hosting-native-toolchain.test.ts @@ -105,7 +105,7 @@ for (const backend of ["llvm"] as const) { object_format: target.objectFormat, minimum_os: target.minimumOs, }, - runtime_abi: { version: 23, marker: "scr_runtime_abi_v23" }, + runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, compiler: { command: "fixture", identity: "fixture", target: target.llvmTriple }, macros: { executable: [], excluded: [], sanitizer: "external-toolchain-required" }, flavors: { From 2d353e6bbe58f399e087fec007beb02138d44279 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 00:33:54 -0500 Subject: [PATCH 015/102] Compute Math.pow(2, n) for integer exponents from the result's bits --- .../src/backend/llvm/lib-filesystem.ts | 62 +++++++++++++++++++ .../corpus/6863-math-pow-base-two.ts.json | 6 ++ packages/runtime/src/scr_lib.c | 11 ++++ tests/corpus/6863-math-pow-base-two.ts | 51 +++++++++++++++ .../6863-math-pow-base-two.ts.json | 1 + 5 files changed, 131 insertions(+) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6863-math-pow-base-two.ts.json create mode 100644 tests/corpus/6863-math-pow-base-two.ts create mode 100644 tests/harness/corpus-costs/6863-math-pow-base-two.ts.json diff --git a/packages/compiler/src/backend/llvm/lib-filesystem.ts b/packages/compiler/src/backend/llvm/lib-filesystem.ts index 358b21c4f..6d5fe652d 100644 --- a/packages/compiler/src/backend/llvm/lib-filesystem.ts +++ b/packages/compiler/src/backend/llvm/lib-filesystem.ts @@ -969,6 +969,64 @@ export function emitPathUrlLibCall(host: LlvmEmitterContext, e: LibCallExpr): Ll return host.emitGenericLibCall(e); } +/** Math.pow(2, n): for an integer n from -1074 to 1023 the result is the + * power of two whose bits are its exponent field (or, below -1022, one + * mantissa bit of a subnormal), the value pow returns. Other exponents call + * scr_math_pow. */ +function emitPowerOfTwo(host: LlvmEmitterContext, n: string): string { + const B = host.B; + const check = B.newLabel("pow2.check"); + const exact = B.newLabel("pow2.exact"); + const call = B.newLabel("pow2.call"); + const join = B.newLabel("pow2.join"); + const low = B.tmp(); + const high = B.tmp(); + const inRange = B.tmp(); + B.line(`${low} = fcmp oge double ${n}, ${f64Lit(-1074)}`); + B.line(`${high} = fcmp ole double ${n}, ${f64Lit(1023)}`); + B.line(`${inRange} = and i1 ${low}, ${high}`); + B.condBr(inRange, check, call); + B.startBlock(check); + const int = B.tmp(); + const back = B.tmp(); + const integral = B.tmp(); + B.line(`${int} = fptosi double ${n} to i32`); + B.line(`${back} = sitofp i32 ${int} to double`); + B.line(`${integral} = fcmp oeq double ${back}, ${n}`); + B.condBr(integral, exact, call); + B.startBlock(exact); + const normal = B.tmp(); + const biased = B.tmp(); + const biasedWide = B.tmp(); + const normalBits = B.tmp(); + const shift = B.tmp(); + const shiftWide = B.tmp(); + const subnormalBits = B.tmp(); + const bits = B.tmp(); + const power = B.tmp(); + B.line(`${normal} = icmp sge i32 ${int}, -1022`); + B.line(`${biased} = add i32 ${int}, 1023`); + B.line(`${biasedWide} = zext i32 ${biased} to i64`); + B.line(`${normalBits} = shl i64 ${biasedWide}, 52`); + B.line(`${shift} = add i32 ${int}, 1074`); + B.line(`${shiftWide} = zext i32 ${shift} to i64`); + B.line(`${subnormalBits} = shl i64 1, ${shiftWide}`); + B.line(`${bits} = select i1 ${normal}, i64 ${normalBits}, i64 ${subnormalBits}`); + B.line(`${power} = bitcast i64 ${bits} to double`); + const exactEnd = B.currentLabel(); + B.br(join); + B.startBlock(call); + host.declare(`declare double @scr_math_pow(double, double)`); + const called = B.tmp(); + B.line(`${called} = call double @scr_math_pow(double ${f64Lit(2)}, double ${n})`); + const callEnd = B.currentLabel(); + B.br(join); + B.startBlock(join); + const out = B.tmp(); + B.line(`${out} = phi double [ ${power}, %${exactEnd} ], [ ${called}, %${callEnd} ]`); + return out; +} + export function emitPrimitiveLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlValue { const B = host.B; if (e.fn === "math.min" || e.fn === "math.max") { @@ -986,6 +1044,10 @@ export function emitPrimitiveLibCall(host: LlvmEmitterContext, e: LibCallExpr): const v = host.emitExpr(e.args[0]!); return { name: emitTruncF64(host, v.name), type: e.type }; } + if (e.fn === "math.pow" && e.args[0]!.kind === "numLit" && e.args[0]!.value === 2) { + const v = host.emitExpr(e.args[1]!); + return { name: emitPowerOfTwo(host, v.name), type: e.type }; + } if (e.fn === "math.floor" || e.fn === "math.ceil") { const intr = e.fn === "math.floor" ? "floor" : "ceil"; const v = host.emitExpr(e.args[0]!); diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6863-math-pow-base-two.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6863-math-pow-base-two.ts.json new file mode 100644 index 000000000..4e09ac362 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6863-math-pow-base-two.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6863-math-pow-base-two.ts" + ], + "diags": [] +} diff --git a/packages/runtime/src/scr_lib.c b/packages/runtime/src/scr_lib.c index 3441e6142..ee4c34592 100644 --- a/packages/runtime/src/scr_lib.c +++ b/packages/runtime/src/scr_lib.c @@ -6821,6 +6821,17 @@ double scr_math_round(double x) { * powers, follow libm. */ double scr_math_pow(double base, double exponent) { if (isnan(exponent) || (isinf(exponent) && fabs(base) == 1.0)) return NAN; + /* 2 ** n for an integer n in the double range is an exact power of two, + * the value pow returns; its bits are the exponent alone. */ + if (base == 2.0 && exponent >= -1074.0 && exponent <= 1023.0) { + int32_t n = (int32_t)exponent; + if ((double)n == exponent) { + uint64_t bits = n >= -1022 ? (uint64_t)(n + 1023) << 52 : UINT64_C(1) << (n + 1074); + double result; + memcpy(&result, &bits, sizeof result); + return result; + } + } return pow(base, exponent); } diff --git a/tests/corpus/6863-math-pow-base-two.ts b/tests/corpus/6863-math-pow-base-two.ts new file mode 100644 index 000000000..fa965382d --- /dev/null +++ b/tests/corpus/6863-math-pow-base-two.ts @@ -0,0 +1,51 @@ +// Math.pow(2, n) with a literal base of 2 and with a base of 2 in a variable, +// over every integer exponent from -1080 to 1030: subnormal results down to +// 2 ** -1074, zero below it, Infinity above 1023. Non-integer, signed-zero, +// infinite and NaN exponents, and bases next to 2, take the general path. +function bits(x: number): string { + const view = new DataView(new ArrayBuffer(8)); + view.setFloat64(0, x); + return view.getBigUint64(0).toString(16).padStart(16, "0"); +} + +function show(label: string, x: number): void { + console.log(label, bits(x), Object.is(x, -0) ? "-0" : String(x)); +} + +let base = 2; +if (process.argv.length > 99) base = 3; + +let literalDigest = 0n; +let variableDigest = 0n; +let mismatches = 0; +for (let n = -1080; n <= 1030; n++) { + const literal = Math.pow(2, n); + const variable = Math.pow(base, n); + literalDigest = (literalDigest * 31n + BigInt(`0x${bits(literal)}`)) & 0xffffffffffffffffn; + variableDigest = (variableDigest * 31n + BigInt(`0x${bits(variable)}`)) & 0xffffffffffffffffn; + if (!Object.is(literal, variable)) mismatches++; + if (n <= -1070 || (n >= -1025 && n <= -1019) || (n >= -2 && n <= 2) || (n >= 51 && n <= 54) || n >= 1021) { + show(`2 ** ${n}`, literal); + } +} +console.log("digests", literalDigest.toString(16), variableDigest.toString(16), "mismatches", mismatches); + +const exponents = [0.5, -0.5, 1.5, -0, 0, 1e-300, -1e-300, 1023.0000001, 1022.9999999, -1074.5, -1073.5, Infinity, -Infinity, NaN, 52.999999999999996, 2 ** 31, -(2 ** 31)]; +for (const e of exponents) { + show(`literal ${e}`, Math.pow(2, e)); + show(`variable ${e}`, Math.pow(base, e)); +} +for (const b of [-2, 2.0000000000000004, 1.9999999999999998, 4, 0.5]) { + show(`${b} ** 10`, Math.pow(b, 10)); + show(`${b} ** -3`, Math.pow(b, -3)); +} + +// In a loop that masks values, as a k-mer counter does. +let key = 0; +let total = 0; +for (let i = 0; i < 100000; i++) { + const length = (i % 18) + 1; + key = (key * 4 + (i % 4)) % Math.pow(2, 2 * length); + total += key - Math.floor(key / Math.pow(2, length)) * Math.pow(2, length); +} +console.log("masked total", total); diff --git a/tests/harness/corpus-costs/6863-math-pow-base-two.ts.json b/tests/harness/corpus-costs/6863-math-pow-base-two.ts.json new file mode 100644 index 000000000..3b43cd660 --- /dev/null +++ b/tests/harness/corpus-costs/6863-math-pow-base-two.ts.json @@ -0,0 +1 @@ +{ "plain": 2110, "san": 4860 } From 47ba594c3f687bee589c2137fd6995678f10eb52 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 00:34:51 -0500 Subject: [PATCH 016/102] Check every type a package type reaches before re-exporting it as a data shape The data-shape check answered a type that refers back to a type still being checked as a data shape and recorded that answer before the outer check finished. With `Branch { child: Tree; handle: Handle }` and `Tree { parent: Branch | null }`, checking Branch first recorded Tree as a data shape, and Tree was re-exported although Branch reaches an interface with a method. The check now walks every type reachable from the queried one before it records any of them as a data shape, and records the types on the path to a non-data type as non-data. --- .../npm-static-type-exports-host.test.ts | 59 +++++++++++++++ .../frontend/npm-static-type-exports-host.ts | 75 ++++++++++++------- 2 files changed, 109 insertions(+), 25 deletions(-) create mode 100644 packages/compiler/src/frontend/npm-static-type-exports-host.test.ts diff --git a/packages/compiler/src/frontend/npm-static-type-exports-host.test.ts b/packages/compiler/src/frontend/npm-static-type-exports-host.test.ts new file mode 100644 index 000000000..e37283fe6 --- /dev/null +++ b/packages/compiler/src/frontend/npm-static-type-exports-host.test.ts @@ -0,0 +1,59 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, expect, test } from "vitest"; +import { nodeFrontendServices } from "./services-node.js"; +import { npmStaticTypeExportPlan } from "./npm-static-type-exports-host.js"; + +const dirs: string[] = []; +afterAll(() => { + for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); +}); + +/** A program directory with one package whose .d.ts is `declarations`; + * returns the program's entry path. */ +function fixture(declarations: string): string { + const dir = mkdtempSync(join(tmpdir(), "scriptc-type-exports-")); + dirs.push(dir); + const lib = join(dir, "node_modules", "pkg", "lib"); + mkdirSync(lib, { recursive: true }); + writeFileSync( + join(dir, "node_modules", "pkg", "package.json"), + JSON.stringify({ name: "pkg", main: "./lib/index.js", types: "./lib/index.d.ts" }), + ); + writeFileSync(join(lib, "index.d.ts"), declarations); + writeFileSync(join(lib, "index.js"), "exports.grow = function grow(into) {};\n"); + writeFileSync(join(dir, "main.ts"), 'import { grow } from "pkg";\n'); + return join(dir, "main.ts"); +} + +/** The type names the runtime entry's typedefs re-export. */ +function reexported(entry: string): string[] { + const plan = npmStaticTypeExportPlan(nodeFrontendServices(), entry, ["pkg"]); + const block = [...plan.typedefs.values()].join("\n"); + return [...block.matchAll(/@typedef \{[^}]*\} (\w+)/g)].map((m) => m[1]!); +} + +test("only data shapes are re-exported", () => { + const entry = fixture(`export interface Point { x: number; y: number } +export interface Handle { close(): void } +export type Label = { text: string; at: Point }; +export type Callback = (point: Point) => void; +export interface Holder { handle: Handle } +export declare function grow(into: Point[]): void; +`); + expect(reexported(entry)).toEqual(["Point", "Label"]); +}); + +test("mutually recursive types are data shapes only when every type they reach is", () => { + // Branch is checked first and reaches Tree, which refers back to Branch: + // Tree is a data shape only if Branch is, and Branch holds a Handle. + const entry = fixture(`export interface Branch { child: Tree; handle: Handle } +export interface Tree { name: string; parent: Branch | null } +export interface Handle { close(): void } +export interface Node { value: number; next: List } +export interface List { head: Node | null } +export declare function grow(into: Tree[]): void; +`); + expect(reexported(entry)).toEqual(["Node", "List"]); +}); diff --git a/packages/compiler/src/frontend/npm-static-type-exports-host.ts b/packages/compiler/src/frontend/npm-static-type-exports-host.ts index 3c196e6a7..8a61ed62b 100644 --- a/packages/compiler/src/frontend/npm-static-type-exports-host.ts +++ b/packages/compiler/src/frontend/npm-static-type-exports-host.ts @@ -154,32 +154,57 @@ export function npmStaticTypeExportPlan( // package's declaration files do not declare is a global (`Array`, // `Record`, `Date`); a class, a value or an import from another package // is not a data shape. + // + // `referencesOf` answers one name: null when it is not a data shape by + // itself, otherwise the names it refers to. + type Ref = { file: string; name: string }; + const referencesOf = (file: string, name: string): Ref[] | null => { + const ex = declarationExports(file); + if (ex === null) return null; + const local = ex.locals.get(name); + if (local !== undefined) + return local.behavior ? null : local.references.map((r) => ({ file, name: r })); + if (ex.valueNames.has(name)) return null; + const from = ex.imports.get(name); + if (from !== undefined) { + const target = declarationTargetOf(file, from.specifier); + return target === null ? null : [{ file: target, name: from.local }]; + } + const reexport = typesOf(file, new Set()).types.get(name); + if (reexport !== undefined) return [{ file: reexport.file, name: reexport.decl.declared }]; + return []; + }; + // A name is a data shape when every name reachable from it is one by + // itself. `isData` walks everything reachable before it records any name + // as a data shape, so a type in a reference cycle is not recorded while + // another type in the cycle is still unchecked. const dataMemo = new Map(); - const isData = (file: string, name: string, visiting: Set): boolean => { - const key = `${file}\0${name}`; - const memo = dataMemo.get(key); - if (memo !== undefined) return memo; - if (visiting.has(key)) return true; // a recursive shape - visiting.add(key); - const answer = ((): boolean => { - const ex = declarationExports(file); - if (ex === null) return false; - const local = ex.locals.get(name); - if (local !== undefined) - return !local.behavior && local.references.every((r) => isData(file, r, visiting)); - if (ex.valueNames.has(name)) return false; - const from = ex.imports.get(name); - if (from !== undefined) { - const target = declarationTargetOf(file, from.specifier); - return target !== null && isData(target, from.local, visiting); + const isData = (file: string, name: string): boolean => { + const keyOf = (ref: Ref): string => `${ref.file}\0${ref.name}`; + // Each reached name, by key, with the key of the name it was reached from. + const reachedFrom = new Map([[keyOf({ file, name }), null]]); + const queue: Ref[] = [{ file, name }]; + for (let i = 0; i < queue.length; i++) { + const ref = queue[i]!; + const key = keyOf(ref); + const memo = dataMemo.get(key); + if (memo === true) continue; + const next = memo === false ? null : referencesOf(ref.file, ref.name); + if (next === null) { + // Every name on the path to this one reaches a non-data type. + for (let k: string | null = key; k !== null; k = reachedFrom.get(k) ?? null) + dataMemo.set(k, false); + return false; } - const reexport = typesOf(file, new Set()).types.get(name); - if (reexport !== undefined) return isData(reexport.file, reexport.decl.declared, visiting); - return true; - })(); - visiting.delete(key); - dataMemo.set(key, answer); - return answer; + for (const target of next) { + const targetKey = keyOf(target); + if (reachedFrom.has(targetKey)) continue; + reachedFrom.set(targetKey, key); + queue.push(target); + } + } + for (const key of reachedFrom.keys()) dataMemo.set(key, true); + return true; }; for (const pkg of packages) { const declared = resolveBareModule(entryPath, pkg, "types-only"); @@ -198,7 +223,7 @@ export function npmStaticTypeExportPlan( ({ decl, file }) => !values.has(decl.name) && !declaredByRuntime.has(decl.name) && - isData(file, decl.declared, new Set()), + isData(file, decl.declared), ) .map(({ decl }) => decl); if (exported.length === 0) continue; From 140b1f397fa6c293ed7d06ee9405a11e89ee0af0 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 00:35:17 -0500 Subject: [PATCH 017/102] Reject DiffieHellman secrets of 0, 1 and p - 1 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit computeSecret now fails with ERR_CRYPTO_OPERATION_FAILED ("Failed to compute shared secret") when the exponentiation yields 0, 1 or p - 1, as Node's OpenSSL derivation does: such a secret is predictable, from a peer key of small order or a composite modulus. 6708 covers a secret of 1 and of p - 1 (peer keys of order 3 and 6 modulo a 512-bit prime with p ≡ 1 mod 6) and of 0 (a peer key sharing the factor of a square modulus). --- packages/runtime/src/scr_dh.c | 7 +++++-- tests/corpus/6708-dh-errors.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/runtime/src/scr_dh.c b/packages/runtime/src/scr_dh.c index c514b45ba..351d97a0f 100644 --- a/packages/runtime/src/scr_dh.c +++ b/packages/runtime/src/scr_dh.c @@ -1058,7 +1058,9 @@ static bool sd_derives(const ScDh *d) { } /* computeSecret(key, inputEncoding, outputEncoding): key^priv mod p, - * padded to the prime's length. */ + * padded to the prime's length. 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; @@ -1073,7 +1075,8 @@ static ScrDyn *sd_compute_secret(ScDh *d, const ScrDyn *key, const ScrDyn *in_en sd_throw(SCR_ERR_RANGE, "ERR_CRYPTO_INVALID_KEYLEN", "Supplied key is too small"); } else if (mbedtls_mpi_cmp_mpi(&peer, &bound) >= 0) { sd_throw(SCR_ERR_RANGE, "ERR_CRYPTO_INVALID_KEYLEN", "Supplied key is too large"); - } else if (!d->has_priv || (!d->group && !sd_derives(d)) || !sd_exp(&secret, &peer, &d->priv, &d->p)) { + } 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); diff --git a/tests/corpus/6708-dh-errors.js b/tests/corpus/6708-dh-errors.js index e092da727..0c711c96d 100644 --- a/tests/corpus/6708-dh-errors.js +++ b/tests/corpus/6708-dh-errors.js @@ -145,3 +145,31 @@ 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")); From 8bbccee4f61efe8912096dbbf953f6b8f2853596 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 00:37:37 -0500 Subject: [PATCH 018/102] Read and write shared typed-array elements inline --- .../compiler/src/backend/llvm/expr-bytes.ts | 120 +++++++++++++----- .../test/bytes-element-emission.test.ts | 16 ++- .../6864-shared-typed-array-elements.ts.json | 6 + .../6864-shared-typed-array-elements.ts | 120 ++++++++++++++++++ .../6864-shared-typed-array-elements.ts.json | 1 + 5 files changed, 228 insertions(+), 35 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6864-shared-typed-array-elements.ts.json create mode 100644 tests/corpus/6864-shared-typed-array-elements.ts create mode 100644 tests/harness/corpus-costs/6864-shared-typed-array-elements.ts.json diff --git a/packages/compiler/src/backend/llvm/expr-bytes.ts b/packages/compiler/src/backend/llvm/expr-bytes.ts index 485b7a6b3..d36001bf6 100644 --- a/packages/compiler/src/backend/llvm/expr-bytes.ts +++ b/packages/compiler/src/backend/llvm/expr-bytes.ts @@ -176,10 +176,10 @@ export function emitBytesLength( return { name: out, type: F64 }; } -/** Worker programs: a view of a SharedArrayBuffer (`shared` is fixed before - * script code can see the view) is read and written by the runtime under - * its shared-memory lock; every other buffer belongs to this thread and - * takes the ordinary inline path. The test follows the index check: a +/** Worker programs: an element of a view of a SharedArrayBuffer (`shared` is + * fixed before script code can see the view) is read and written with one + * relaxed atomic access of its width, as the runtime's shared accessors do; + * every other buffer belongs to this thread and takes the ordinary path. The test follows the index check: a * view's length never changes, so both paths use the one checked integer * index. Branches to the returned label for a thread-owned buffer and * continues in the shared block. */ @@ -276,8 +276,9 @@ function emitBytesLoad( * shared. An integer element joins as its 32-bit value and converts to a * number after the join, as the local load does, so compares and * ToInt32/ToUint32 of the result stay integer operations. The shared read - * is an ordinary call: another thread's write must stay visible to a loop - * that reads the same element again. */ + * is a monotonic atomic load, which LLVM neither hoists nor merges: another + * thread's write stays visible to a loop that reads the same element again. + * Float16 elements read through the runtime. */ function emitSharedOrLocalLoad( host: LlvmEmitterContext, elem: IrBytesElem, @@ -286,12 +287,18 @@ function emitSharedOrLocalLoad( ): LlValue { const B = host.B; const floating = elem === "f16" || elem === "f32" || elem === "f64"; - const fn = floating ? "scr_bytes_shared_get_f64" : "scr_bytes_shared_get_int"; - const ret = floating ? "double" : "i32"; - host.declare(`declare ${ret} @${fn}(ptr, ${host.sizeType})`); const local = emitSharedBytesSplit(host, receiver); - const shared = B.tmp(); - B.line(`${shared} = call ${ret} @${fn}(ptr ${receiver}, ${host.sizeType} ${idx}) cold`); + let shared: string; + if (elem === "f16") { + host.declare(`declare double @scr_bytes_shared_get_f64(ptr, ${host.sizeType})`); + shared = B.tmp(); + B.line( + `${shared} = call double @scr_bytes_shared_get_f64(ptr ${receiver}, ${host.sizeType} ${idx}) cold`, + ); + } else { + const loaded = emitSharedLoadAt(host, elem, host.emitBytesData(receiver), idx); + shared = loaded.uint32 ?? loaded.name; + } const sharedDone = B.newLabel("bytes.shared.done"); B.br(sharedDone); B.startBlock(local); @@ -316,6 +323,43 @@ function emitSharedOrLocalLoad( return { name: out, type: F64, uint32: u32 }; } +/** The element at a checked index of a shared view, given its data pointer: + * a relaxed atomic load of the element's width, aligned as shared views + * are. Not for Float16 elements. */ +function emitSharedLoadAt( + host: LlvmEmitterContext, + elem: IrBytesElem, + data: string, + idx: string, +): LlValue { + const B = host.B; + const size = BYTES_ELEMENT_SIZE[elem]; + const p = B.tmp(); + if (elem === "f32" || elem === "f64") { + const ty = elem === "f32" ? "float" : "double"; + const raw = B.tmp(); + B.line(`${p} = getelementptr inbounds ${ty}, ptr ${data}, ${host.sizeType} ${idx}`); + B.line(`${raw} = load atomic ${ty}, ptr ${p} monotonic, align ${size}`); + if (elem === "f64") return { name: raw, type: F64 }; + const out = B.tmp(); + B.line(`${out} = fpext float ${raw} to double`); + return { name: out, type: F64 }; + } + const bits = size * 8; + const raw = B.tmp(); + B.line(`${p} = getelementptr inbounds i${bits}, ptr ${data}, ${host.sizeType} ${idx}`); + B.line(`${raw} = load atomic i${bits}, ptr ${p} monotonic, align ${size}`); + const signed = elem === "i8" || elem === "i16" || elem === "i32"; + let wide = raw; + if (bits < 32) { + wide = B.tmp(); + B.line(`${wide} = ${signed ? "sext" : "zext"} i${bits} ${raw} to i32`); + } + const out = B.tmp(); + B.line(`${out} = ${signed ? "sitofp" : "uitofp"} i32 ${wide} to double`); + return { name: out, type: F64, uint32: wide }; +} + /** The element at a checked index of a thread-owned view, given its data * pointer. */ function emitBytesLoadAt( @@ -477,7 +521,7 @@ export function emitBytesSet( const done = B.newLabel("bytes.store.done"); const data = host.emitBytesData(receiver); const idx = emitBytesIndex(host, receiver, index, indexExpr, done, inBounds); - if (host.mod.workers) { + if (host.mod.workers && elem === "f16") { host.declare(`declare void @scr_bytes_shared_set(ptr, ${host.sizeType}, double)`); const local = emitSharedBytesSplit(host, receiver); B.line( @@ -498,32 +542,48 @@ export function emitBytesSet( elem === "f16" || elem === "f32" || elem === "f64" ? null : host.emitToUint32(value.name, expr, value.uint32); - const p = B.tmp(); if (elem === "f16") { // One round-to-nearest-even step from the double, in the runtime. host.declare(`declare zeroext i16 @scr_f16_from_f64(double)`); const narrowed = B.tmp(); + const p = B.tmp(); B.line(`${narrowed} = call zeroext i16 @scr_f16_from_f64(double ${value.name})`); B.line(`${p} = getelementptr inbounds i16, ptr ${data}, ${host.sizeType} ${idx}`); B.line(`store i16 ${narrowed}, ptr ${p}, align 1${bytesElementAlias(host)}`); - } else if (BYTES_ELEMENT_SIZE[elem] < 4) { - const bits = BYTES_ELEMENT_SIZE[elem] * 8; - const byte = B.tmp(); - B.line(`${byte} = trunc i32 ${stored!} to i${bits}`); - B.line(`${p} = getelementptr inbounds i${bits}, ptr ${data}, ${host.sizeType} ${idx}`); - B.line(`store i${bits} ${byte}, ptr ${p}, align 1${bytesElementAlias(host)}`); - } else if (elem === "f32") { - const narrowed = B.tmp(); - B.line(`${narrowed} = fptrunc double ${value.name} to float`); - B.line(`${p} = getelementptr inbounds float, ptr ${data}, ${host.sizeType} ${idx}`); - B.line(`store float ${narrowed}, ptr ${p}, align 1${bytesElementAlias(host)}`); - } else if (elem === "f64") { - B.line(`${p} = getelementptr inbounds double, ptr ${data}, ${host.sizeType} ${idx}`); - B.line(`store double ${value.name}, ptr ${p}, align 1${bytesElementAlias(host)}`); - } else { - B.line(`${p} = getelementptr inbounds i32, ptr ${data}, ${host.sizeType} ${idx}`); - B.line(`store i32 ${stored!}, ptr ${p}, align 1${bytesElementAlias(host)}`); + B.br(done); + B.startBlock(done); + return; } + // The element's bits as an LLVM value of the element's width. + let ty: string; + let operand: string; + if (BYTES_ELEMENT_SIZE[elem] < 4) { + ty = `i${BYTES_ELEMENT_SIZE[elem] * 8}`; + operand = B.tmp(); + B.line(`${operand} = trunc i32 ${stored!} to ${ty}`); + } else if (elem === "f32") { + ty = "float"; + operand = B.tmp(); + B.line(`${operand} = fptrunc double ${value.name} to float`); + } else if (elem === "f64") { + ty = "double"; + operand = value.name; + } else { + ty = "i32"; + operand = stored!; + } + if (host.mod.workers) { + // A shared view's element takes a relaxed atomic store of its width. + const local = emitSharedBytesSplit(host, receiver); + const p = B.tmp(); + B.line(`${p} = getelementptr inbounds ${ty}, ptr ${data}, ${host.sizeType} ${idx}`); + B.line(`store atomic ${ty} ${operand}, ptr ${p} monotonic, align ${BYTES_ELEMENT_SIZE[elem]}`); + B.br(done); + B.startBlock(local); + } + const p = B.tmp(); + B.line(`${p} = getelementptr inbounds ${ty}, ptr ${data}, ${host.sizeType} ${idx}`); + B.line(`store ${ty} ${operand}, ptr ${p}, align 1${bytesElementAlias(host)}`); B.br(done); B.startBlock(done); } diff --git a/packages/compiler/test/bytes-element-emission.test.ts b/packages/compiler/test/bytes-element-emission.test.ts index 9a241b854..505b51963 100644 --- a/packages/compiler/test/bytes-element-emission.test.ts +++ b/packages/compiler/test/bytes-element-emission.test.ts @@ -335,11 +335,17 @@ test("a body mutation keeps the byte loop on the general f64 path", () => { test("worker programs read and write shared views at the checked integer index", () => { const ll = emitLlvmModule({ ...fixture(), workers: true }); - // The shared path receives the index the inline path checked, as an integer, - // and integer elements come back as 32-bit values. - expect(ll).toMatch(/call i32 @scr_bytes_shared_get_int\(ptr %\w+, i64 %?\w+\) cold/); - expect(ll).toMatch(/call double @scr_bytes_shared_get_f64\(ptr %\w+, i64 %?\w+\) cold/); - expect(ll).toMatch(/call void @scr_bytes_shared_set\(ptr %\w+, i64 %?\w+, double %?[\w.]+\)/); + // The shared path uses the index the inline path checked, as an integer: + // each element is one relaxed atomic access of its width, aligned to it. + expect(ll).toMatch(/load atomic i8, ptr %\w+ monotonic, align 1/); + expect(ll).toMatch(/load atomic i32, ptr %\w+ monotonic, align 4/); + expect(ll).toMatch(/load atomic float, ptr %\w+ monotonic, align 4/); + expect(ll).toMatch(/store atomic i8 [%\w.]+, ptr %\w+ monotonic, align 1/); + expect(ll).toMatch(/store atomic i32 [%\w.]+, ptr %\w+ monotonic, align 4/); + expect(ll).toMatch(/store atomic float [%\w.]+, ptr %\w+ monotonic, align 4/); + expect(ll).not.toContain("@scr_bytes_shared_get_int"); + expect(ll).not.toContain("@scr_bytes_shared_get_f64"); + expect(ll).not.toContain("@scr_bytes_shared_set"); expect(ll).not.toContain("@scr_bytes_get_or_nan"); expect(ll).not.toContain("@scr_bytes_set("); // Both paths join as one integer, which converts to a number after the join. diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6864-shared-typed-array-elements.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6864-shared-typed-array-elements.ts.json new file mode 100644 index 000000000..2a7203ef0 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6864-shared-typed-array-elements.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6864-shared-typed-array-elements.ts" + ], + "diags": [] +} diff --git a/tests/corpus/6864-shared-typed-array-elements.ts b/tests/corpus/6864-shared-typed-array-elements.ts new file mode 100644 index 000000000..ee3ecef32 --- /dev/null +++ b/tests/corpus/6864-shared-typed-array-elements.ts @@ -0,0 +1,120 @@ +// Element reads and writes of typed arrays over a SharedArrayBuffer, for every +// element kind, from the main thread and from a worker: each kind's +// conversion on write (wrapping, clamping, rounding to float32 and float16), +// NaN, -0 and the infinities, and values one thread writes and the other +// reads after a message. A worker loop that reads a flag without Atomics +// sees the main thread's write. +import { isMainThread, parentPort, Worker, workerData } from "node:worker_threads"; + +const KINDS = 10; + +const VALUES = [0, -0, 1, -1, 1.5, 2.5, -2.5, 127, 128, 255, 256, -129, 65535, 65536, 2 ** 31, -(2 ** 31) - 1, 2 ** 32 + 7, 0.1, 1e40, -1e-50, NaN, Infinity, -Infinity]; +const LENGTH = VALUES.length; + +interface Views { + i8: Int8Array; + u8: Uint8Array; + u8c: Uint8ClampedArray; + i16: Int16Array; + u16: Uint16Array; + i32: Int32Array; + u32: Uint32Array; + f16: Float16Array; + f32: Float32Array; + f64: Float64Array; +} + +/** One region of LENGTH elements per kind, each aligned to 8 bytes. */ +function viewsOf(sab: SharedArrayBuffer): Views { + const region = LENGTH * 8; + return { + i8: new Int8Array(sab, 0 * region, LENGTH), + u8: new Uint8Array(sab, 1 * region, LENGTH), + u8c: new Uint8ClampedArray(sab, 2 * region, LENGTH), + i16: new Int16Array(sab, 3 * region, LENGTH), + u16: new Uint16Array(sab, 4 * region, LENGTH), + i32: new Int32Array(sab, 5 * region, LENGTH), + u32: new Uint32Array(sab, 6 * region, LENGTH), + f16: new Float16Array(sab, 7 * region, LENGTH), + f32: new Float32Array(sab, 8 * region, LENGTH), + f64: new Float64Array(sab, 9 * region, LENGTH), + }; +} + +function show(x: number): string { + return Object.is(x, -0) ? "-0" : String(x); +} + +/** Writes VALUES (scaled by `scale`) through every view. */ +function writeAll(v: Views, scale: number): void { + for (let i = 0; i < LENGTH; i++) { + const x = VALUES[i]! * scale; + v.i8[i] = x; + v.u8[i] = x; + v.u8c[i] = x; + v.i16[i] = x; + v.u16[i] = x; + v.i32[i] = x; + v.u32[i] = x; + v.f16[i] = x; + v.f32[i] = x; + v.f64[i] = x; + } +} + +/** Every element of every view, read one at a time, and a sum per view. */ +function readAll(v: Views): string[] { + const lines: string[] = []; + const row = (kind: string, read: (i: number) => number): void => { + const cells: string[] = []; + for (let i = 0; i < LENGTH; i++) cells.push(show(read(i))); + lines.push(`${kind}: ${cells.join(" ")}`); + }; + row("Int8Array", (i) => v.i8[i]!); + row("Uint8Array", (i) => v.u8[i]!); + row("Uint8ClampedArray", (i) => v.u8c[i]!); + row("Int16Array", (i) => v.i16[i]!); + row("Uint16Array", (i) => v.u16[i]!); + row("Int32Array", (i) => v.i32[i]!); + row("Uint32Array", (i) => v.u32[i]!); + row("Float16Array", (i) => v.f16[i]!); + row("Float32Array", (i) => v.f32[i]!); + row("Float64Array", (i) => v.f64[i]!); + let total = 0; + for (let i = 0; i < LENGTH; i++) total += v.i32[i]! + v.u16[i]! + (v.u8c[i]! | 0); + lines.push(`integer total ${total}`); + return lines; +} + +if (isMainThread) { + const sab = new SharedArrayBuffer(KINDS * LENGTH * 8 + 16); + const views = viewsOf(sab); + const flag = new Int32Array(sab, KINDS * LENGTH * 8, 2); + writeAll(views, 1); + console.log("main wrote, main reads"); + for (const line of readAll(views)) console.log(line); + + const worker = new Worker(new URL(import.meta.url), { workerData: sab }); + worker.on("message", (lines: string[]) => { + if (lines.length === 1) { + console.log(lines[0]); + return; + } + console.log("main wrote, worker reads; worker wrote, main reads"); + for (const line of lines) console.log(line); + for (const line of readAll(views)) console.log(line); + flag[1] = 7; + flag[0] = 1; + }); +} else { + const sab = workerData as SharedArrayBuffer; + const views = viewsOf(sab); + const flag = new Int32Array(sab, KINDS * LENGTH * 8, 2); + const seen = readAll(views); + writeAll(views, -3); + parentPort!.postMessage(seen); + while (flag[0] === 0) { + // Spin until the main thread's write is visible. + } + parentPort!.postMessage([`worker saw the flag, then ${flag[1]}`]); +} diff --git a/tests/harness/corpus-costs/6864-shared-typed-array-elements.ts.json b/tests/harness/corpus-costs/6864-shared-typed-array-elements.ts.json new file mode 100644 index 000000000..5ec5d60dc --- /dev/null +++ b/tests/harness/corpus-costs/6864-shared-typed-array-elements.ts.json @@ -0,0 +1 @@ +{ "plain": 2290, "san": 5070 } From b59da7529e2a04baa94402c5a1ced0194623451c Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 00:44:22 -0500 Subject: [PATCH 019/102] Leave counters unbounded when a nested scan is not walked pass by pass highestCount walks a nested while loop from its bound only when the loop is a statement of the body or of its blocks and branches. A nested scan inside a labeled block or an expression reached the generic branch, which counted its increments once although the loop can repeat them. Such a loop now leaves the counter without a range. --- .../compiler/src/ir/integer-loop-facts.ts | 21 ++++++++++++++----- .../compiler/src/ir/integer-ranges.test.ts | 9 ++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/packages/compiler/src/ir/integer-loop-facts.ts b/packages/compiler/src/ir/integer-loop-facts.ts index b075ef29a..31edc2f48 100644 --- a/packages/compiler/src/ir/integer-loop-facts.ts +++ b/packages/compiler/src/ir/integer-loop-facts.ts @@ -395,11 +395,15 @@ export function guardedLoopCounterFacts( /** The largest value counter `id` takes in one pass of `body`, which starts * at most at `entry`. The caller has checked that the body changes the - * counter only by positive literal increments outside nested loops, switch, - * exception and labeled regions, so those regions leave it unchanged, and - * every exit from a straight-line path leaves the body. An `if` whose - * condition does not write the counter caps it in the then branch by the - * condition's bounds; any other statement adds the increments it holds. */ + * counter only by positive literal increments outside switch, exception and + * labeled loop regions and loops other than nested while loops whose + * conditions bound it, and every exit from a straight-line path leaves the + * body. An `if` whose condition does not write the counter caps it in the + * then branch by the condition's bounds. A nested while loop that is a + * statement of the body, or of its blocks and branches, is walked from its + * bound; any other statement adds the increments it holds, and one that + * holds a loop writing the counter (in an expression or a labeled block) + * leaves it unbounded. */ function highestCount( body: readonly IrStmt[], id: string, @@ -416,6 +420,13 @@ function highestCount( }; const stmt = (x: IrStmt): boolean => { if (x.kind === "assign" && x.localId === id) total += increment(id, x.value) ?? 0; + // A loop reached here, inside an expression or a labeled region rather + // than through `walk`, can repeat its increments: no bound. + if ( + (x.kind === "while" || x.kind === "doWhile" || x.kind === "for" || x.kind === "forOf") && + writtenLocals([x]).has(id) + ) + total = Infinity; return everyStmtChild(x, expr, stmt); }; if (expression) expr(e as IrExpr); diff --git a/packages/compiler/src/ir/integer-ranges.test.ts b/packages/compiler/src/ir/integer-ranges.test.ts index b495eb814..fcb040275 100644 --- a/packages/compiler/src/ir/integer-ranges.test.ts +++ b/packages/compiler/src/ir/integer-ranges.test.ts @@ -863,6 +863,15 @@ test("a nested while loop may advance a counter its own condition bounds", () => ), ); expect(run(writing).after).toBeNull(); + // The same scan inside a labeled block or an expression is not walked + // pass by pass; its increments could repeat, so the counter stays unbounded. + expect(run({ loc, kind: "block", labels: ["scan"], body: [bounded] }).after).toBeNull(); + const inExpression: IrStmt = { + loc, + kind: "exprStmt", + expr: { loc, kind: "seqExpr", stmts: [bounded], result: num(0), type: F64 }, + }; + expect(run(inExpression).after).toBeNull(); }); test("an array length bounds while and for counters even when the body resizes the array", () => { From 728dc6cd51cdfdd45db3a8402481c82c49bda970 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 00:47:17 -0500 Subject: [PATCH 020/102] Count program-lifetime objects in memoryUsage and fix the runtime tests - process.memoryUsage(): heapTotal counts the region's chunks that threads hold, minus the chunks discarded workers returned, and heapUsed counts them less the tails threads left unused when they moved to a new chunk. - The region builds only where it can be used: Linux runtimes with the size-class allocator, which excludes the sanitizer runtimes (scriptc keeps 8-byte references there). The standalone allocator, cycle and young-nursery tests link again: the allocator test defines the scr_trap its region needs, and checks the region (below 32 GiB, aligned, zeroed, chunks larger than one, heap statistics, threads). - scr_plr_chunk has an initializer, like the other runtime globals. --- packages/runtime/src/scr_alloc.c | 42 +++++++++++++++-- packages/runtime/src/scr_alloc.test.c | 67 +++++++++++++++++++++++++++ packages/runtime/src/scr_rc.h | 2 +- 3 files changed, 106 insertions(+), 5 deletions(-) diff --git a/packages/runtime/src/scr_alloc.c b/packages/runtime/src/scr_alloc.c index 4b29b4b51..f2304aace 100644 --- a/packages/runtime/src/scr_alloc.c +++ b/packages/runtime/src/scr_alloc.c @@ -1930,6 +1930,10 @@ void scr_mem_order_for_free(void **ptrs, size_t n, size_t offset) { * mallinfo2, the Darwin malloc zones, the Windows CRT heap, or the * sanitizer's allocator in sanitized builds). Walks the free lists, so * the cost grows with the number of free blocks. */ +#if defined(__linux__) && SCR_SMALL_ALLOC +static void scr_plr_heap_stats(size_t *held, size_t *used); +#endif + void scr_heap_stats(double *total, double *used) { size_t held = 0, idle = 0; #if SCR_SMALL_ALLOC @@ -1979,6 +1983,13 @@ void scr_heap_stats(double *total, double *used) { sys_held = s.committed; sys_used = s.allocated; } +#endif +#if defined(__linux__) && SCR_SMALL_ALLOC + /* Compact class instances (the program-lifetime region below). */ + size_t region_held, region_used; + scr_plr_heap_stats(®ion_held, ®ion_used); + sys_held += region_held; + sys_used += region_used; #endif *total = (double)(held + sys_held); *used = (double)(held - (idle < held ? idle : held) + sys_used); @@ -1986,7 +1997,8 @@ void scr_heap_stats(double *total, double *used) { /* ── program-lifetime region ──────────────────────────────────────────── * Instances of compact classes (llvm/classes.ts LlClassMeta.compact) in - * programs built for Linux without sanitizers live in one address range + * programs built for Linux without sanitizers (runtimes with the size-class + * allocator, SCR_SMALL_ALLOC) live in one address range * reserved for the whole process below 32 GiB, so a field that holds one * can store its address over 8 in 32 bits (0 stays NULL). The instances * are never freed. Each thread carves them from its own chunks of @@ -1994,7 +2006,7 @@ void scr_heap_stats(double *total, double *used) { * Pages are committed by first touch and start zeroed. Its strings are * arrays rather than literals: programs without compact classes then link * none of this, where literals would stay in the unit's merged strings. */ -#if defined(__linux__) && SIZE_MAX > UINT32_MAX +#if defined(__linux__) && SCR_SMALL_ALLOC #include #define SCR_PLR_CHUNK ((size_t)1 << 20) @@ -2012,10 +2024,13 @@ void scr_heap_stats(double *total, double *used) { static char *scr_plr_base; /* the range's start, once reserved */ static size_t scr_plr_size; static size_t scr_plr_top; /* atomic */ +/* Bytes of the chunks threads hold, and of the tails they left unused when + * they moved to a new chunk (scr_heap_stats); atomic. */ +static size_t scr_plr_held, scr_plr_waste; #if defined(SCR_WORKERS) || (defined(SCR_LIB) && defined(SCR_THREAD_INSTANCES)) -_Thread_local ScrPlrChunk scr_plr_chunk; +_Thread_local ScrPlrChunk scr_plr_chunk = {NULL, NULL}; #else -ScrPlrChunk scr_plr_chunk; +ScrPlrChunk scr_plr_chunk = {NULL, NULL}; #endif /* Reserves `size` bytes at `at` exactly; NULL if refused. */ @@ -2072,6 +2087,7 @@ static __attribute__((noinline)) void scr_plr_reserve(void) { * chunk a thread takes registers scr_plr_thread_end. */ #define SCR_PLR_LINK 16 static _Thread_local char *scr_plr_mine; +static _Thread_local size_t scr_plr_mine_waste; /* this thread's part of scr_plr_waste */ static pthread_key_t scr_plr_end_key; static pthread_once_t scr_plr_end_once = PTHREAD_ONCE_INIT; static pthread_mutex_t scr_plr_free_lock = PTHREAD_MUTEX_INITIALIZER; @@ -2112,6 +2128,9 @@ static void scr_plr_thread_end(void *unused) { c = next; } static const char stats_line[] = "scr_sa: thread returned %zu MB of program-lifetime objects\n"; + __atomic_fetch_sub(&scr_plr_held, returned, __ATOMIC_RELAXED); + __atomic_fetch_sub(&scr_plr_waste, scr_plr_mine_waste, __ATOMIC_RELAXED); + scr_plr_mine_waste = 0; const char *stats = getenv("SCR_SA_STATS"); if (stats && stats[0] == '1') fprintf(stderr, stats_line, returned >> 20); } @@ -2162,6 +2181,14 @@ static __attribute__((noinline)) void *scr_plr_refill(size_t n) { #ifdef SCR_SA_TRIM scr_plr_own(p, chunk); #endif + if (scr_plr_chunk.next) { + size_t left = (size_t)(scr_plr_chunk.limit - scr_plr_chunk.next); + __atomic_fetch_add(&scr_plr_waste, left, __ATOMIC_RELAXED); +#ifdef SCR_SA_TRIM + scr_plr_mine_waste += left; +#endif + } + __atomic_fetch_add(&scr_plr_held, chunk, __ATOMIC_RELAXED); scr_plr_chunk.next = p + SCR_PLR_LINK + n; scr_plr_chunk.limit = p + chunk; return p + SCR_PLR_LINK; @@ -2173,6 +2200,13 @@ void scr_plr_init(void) { if (!__atomic_load_n(&scr_plr_base, __ATOMIC_ACQUIRE)) scr_plr_reserve(); } +static void scr_plr_heap_stats(size_t *held, size_t *used) { + size_t h = __atomic_load_n(&scr_plr_held, __ATOMIC_RELAXED); + size_t w = __atomic_load_n(&scr_plr_waste, __ATOMIC_RELAXED); + *held = h; + *used = w < h ? h - w : 0; +} + void *scr_plr_alloc(size_t n) { n = (n + 7) & ~(size_t)7; char *p = scr_plr_chunk.next; diff --git a/packages/runtime/src/scr_alloc.test.c b/packages/runtime/src/scr_alloc.test.c index 2d8024c6d..e20c0733b 100644 --- a/packages/runtime/src/scr_alloc.test.c +++ b/packages/runtime/src/scr_alloc.test.c @@ -10,6 +10,13 @@ static bool owned(const void *p) { return (uintptr_t)p - scr_sa.base < scr_sa.span; } #endif +/* The allocator unit needs only scr_trap from the rest of the runtime: the + * program-lifetime region stops the program through it. */ +_Noreturn void scr_trap(const char *msg) { + fputs(msg, stderr); + abort(); +} + static void fill(unsigned char *p, size_t n, unsigned char seed) { for (size_t i = 0; i < n; i++) p[i] = (unsigned char)(seed + i * 7); } @@ -962,6 +969,60 @@ static void check_discard(void) { } #endif +#if defined(__linux__) && SCR_SMALL_ALLOC +/* The program-lifetime region hands out zeroed, 8-byte aligned blocks below + * 32 GiB, in order from the calling thread's chunk; a block larger than a + * chunk gets chunks of its own. Heap statistics count the chunks. Builds + * with AddressSanitizer have no region (its shadow memory takes the range), + * and scriptc builds with sanitizers keep pointers instead. */ +static void check_program_lifetime_region(void) { + double total0, used0, total1, used1; + scr_heap_stats(&total0, &used0); + scr_plr_init(); + unsigned char *a = scr_plr_alloc(20), *b = scr_plr_alloc(40); + assert(((uintptr_t)a & 7) == 0 && b == a + 24); + assert((uintptr_t)a >= ((uintptr_t)4 << 30) && (uintptr_t)b + 40 <= ((uintptr_t)32 << 30)); + for (size_t i = 0; i < 40; i++) assert(b[i] == 0); + size_t n = (size_t)3 << 20; + unsigned char *big = scr_plr_alloc(n); + assert(((uintptr_t)big & 7) == 0 && (uintptr_t)big + n <= ((uintptr_t)32 << 30)); + for (size_t i = 0; i < n; i += 4096) assert(big[i] == 0); + fill(big, n, 3); + verify(big, n, 3); + scr_heap_stats(&total1, &used1); + assert(total1 - total0 >= (double)n && used1 - used0 >= (double)n && used1 <= total1); +} + +#ifdef SCR_WORKERS +/* Threads carve the region concurrently: every block is zeroed and keeps + * what its thread wrote. */ +#define REGION_THREADS 4u +#define REGION_BLOCKS 20000u +static unsigned char *region_blocks[REGION_THREADS][REGION_BLOCKS]; + +static void *region_alloc(void *arg) { + unsigned t = (unsigned)(uintptr_t)arg; + for (unsigned i = 0; i < REGION_BLOCKS; i++) { + unsigned char *p = scr_plr_alloc(24); + for (size_t k = 0; k < 24; k++) assert(p[k] == 0); + fill(p, 24, (unsigned char)(t * 31 + i)); + region_blocks[t][i] = p; + } + return NULL; +} + +static void check_program_lifetime_region_threads(void) { + pthread_t threads[REGION_THREADS]; + for (unsigned t = 0; t < REGION_THREADS; t++) + assert(pthread_create(&threads[t], NULL, region_alloc, (void *)(uintptr_t)t) == 0); + for (unsigned t = 0; t < REGION_THREADS; t++) assert(pthread_join(threads[t], NULL) == 0); + for (unsigned t = 0; t < REGION_THREADS; t++) + for (unsigned i = 0; i < REGION_BLOCKS; i++) + verify(region_blocks[t][i], 24, (unsigned char)(t * 31 + i)); +} +#endif +#endif + int main(void) { #if SCR_SMALL_ALLOC check_slice_growth(); /* first: its class must be untouched */ @@ -975,6 +1036,12 @@ int main(void) { #if SCR_SMALL_ALLOC && defined(__linux__) && defined(__GLIBC__) check_heap_huge_pages(); #endif +#if defined(__linux__) && SCR_SMALL_ALLOC + check_program_lifetime_region(); +#ifdef SCR_WORKERS + check_program_lifetime_region_threads(); +#endif +#endif #if defined(SCR_WORKERS) && SCR_SMALL_ALLOC /* A short discard delay, which stays at its start until check_discard_delay_grows. */ setenv("SCR_SA_DISCARD_DELAY_MS", "100", 1); diff --git a/packages/runtime/src/scr_rc.h b/packages/runtime/src/scr_rc.h index 93fdd7946..7a921b451 100644 --- a/packages/runtime/src/scr_rc.h +++ b/packages/runtime/src/scr_rc.h @@ -308,7 +308,7 @@ void scr_cyc_free(void *obj); /* frees the block, header included */ void *scr_mem_realloc(void *p, size_t n); void *scr_rt_calloc(size_t n); /* emitted-code entry points */ -#if defined(__linux__) && SIZE_MAX > UINT32_MAX +#if defined(__linux__) && SCR_SMALL_ALLOC /* The program-lifetime region (scr_alloc.c): compact class instances of * programs built for Linux without sanitizers (llvm/emitter.ts * lowRegionTarget), which are never freed, at 8-byte aligned addresses below From f1e6addc819ecde9d205be4af5fd5dc2c67d830e Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 00:51:27 -0500 Subject: [PATCH 021/102] Encode messages into one block sized to their contents An encoded message allocated a node array (four nodes of 184 bytes to start, trimmed when encoding ended), a property array per object, a copy of every key and string, and the encoder's visit, identity and stack arrays. A port that queues many messages kept all of it until delivery: a {id, name} object took 15 allocations and 1.9 KB, and most of postMessage's time went into page faults on that memory. - The encoder builds nodes, properties and visits in arrays that start on the stack (8 entries), keeps borrowed references to keys and strings, and copies the result into one allocation: the header, the nodes, the properties grouped by node, the typed records and the text. A node is 40 bytes; the per-kind fields share a union. ArrayBuffer contents stay in their own allocation. - Decoding uses stack arrays for messages of up to 8 nodes and allocates the storage table only when the message has ArrayBuffer contents. - Freeing a message frees the block, and walks the nodes only when the message holds ports, native handles or ArrayBuffer contents. - The publication check reads the root before collecting the graph, so a message whose root is not frozen allocates nothing for it. The same object message now takes 4 allocations and 302 bytes, and a number 3 allocations and 129 bytes. bench/channel-messages runs in 161 ms instead of 250 ms (Node: 340 ms), with a peak RSS of 45 MB instead of 115 MB, and bench/worker-messages in 273 ms instead of 348 ms. --- packages/runtime/src/scr_message.c | 512 ++++++++++++++++-------- packages/runtime/src/scr_message.test.c | 79 ++++ 2 files changed, 414 insertions(+), 177 deletions(-) diff --git a/packages/runtime/src/scr_message.c b/packages/runtime/src/scr_message.c index cd0e92740..5e1bce37f 100644 --- a/packages/runtime/src/scr_message.c +++ b/packages/runtime/src/scr_message.c @@ -21,7 +21,7 @@ typedef enum { /* 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), the side in number. */ + /* A transferred MessagePort: its channel end (+1) and side. */ SCR_MESSAGE_PORT, /* A native handle cloned through its unit's ScrDynHandleTransfer. */ SCR_MESSAGE_HANDLE, @@ -30,67 +30,109 @@ typedef enum { const ScrMessagePortOps *scr_message_port_ops = NULL; typedef struct { - char *key; + const char *key; size_t length; size_t value; bool hidden; /* an Error's non-enumerable or inherited property */ } ScrMessageProperty; +/* SCR_MESSAGE_TYPED_REF: the capsule's process-wide adapters and type key + * (vtables, adapters and type keys are shared by every thread). */ typedef struct { - ScrMessageKind kind; - double number; - unsigned char *data; - ScrSharedBytes *shared; - size_t length; - ScrMessageProperty *properties; - size_t count; - size_t capacity; - size_t storage; - size_t offset; - ScrBytesElem element; - bool data_view; - ScrDyn *published; /* SCR_MESSAGE_PUBLISHED: immortal root, owns nothing */ - ScrChannel *channel; /* SCR_MESSAGE_PORT */ - /* SCR_MESSAGE_HANDLE: the owning unit's hooks and its payload (+1). */ - const ScrDynHandleTransfer *transfer; - void *payload; - /* SCR_MESSAGE_TYPED_REF: the capsule's process-wide adapters and type key - * (vtables, adapters and type keys are shared by every thread). */ - struct { - void *ptr; - void *(*retain)(void *); - void (*release)(void *); - const char *type_key; - size_t type_key_len; - ScrDyn *(*materialize)(void *); - void (*commit)(void *, const ScrDyn *); - bool traced; - } typed; + void *ptr; + void *(*retain)(void *); + void (*release)(void *); + const char *type_key; + size_t type_key_len; + ScrDyn *(*materialize)(void *); + void (*commit)(void *, const ScrDyn *); + bool traced; +} ScrMessageTyped; + +typedef struct { + unsigned char kind; /* ScrMessageKind */ + unsigned char element; /* SCR_MESSAGE_BYTES: ScrBytesElem */ + bool data_view; /* SCR_MESSAGE_BYTES */ + uint32_t count; /* properties */ + const ScrMessageProperty *properties; + union { + double number; /* BOOL and NUMBER; ERROR: the error kind */ + /* STRING and BIGINT: the text, in the message block. STORAGE: the + * copied bytes (owned) or the shared backing (+1). */ + struct { + char *data; + ScrSharedBytes *shared; + size_t length; + } text; + /* BYTES and ARRAY_BUFFER: the STORAGE node; BYTES: the view. */ + struct { + size_t storage; + size_t offset; + size_t length; + } view; + size_t length; /* ARRAY */ + ScrDyn *published; /* PUBLISHED: immortal root, owns nothing */ + struct { + ScrChannel *channel; /* +1 */ + int side; + } port; + /* HANDLE: the owning unit's hooks and its payload (+1). */ + struct { + const ScrDynHandleTransfer *transfer; + void *payload; + } handle; + const ScrMessageTyped *typed; /* TYPED_REF, in the message block */ + size_t typed_index; /* TYPED_REF while encoding */ + } v; } ScrMessageNode; +/* A message is one allocation: this header, then the nodes, the + * properties, the typed records and the text (keys, strings and bigints), + * sized to the message. A queued message holds nothing else, apart from + * the bytes of STORAGE nodes. */ struct ScrMessage { ScrMessageNode *nodes; size_t count; - size_t capacity; + bool storage; /* has STORAGE nodes */ + bool releases; /* has STORAGE, PORT or HANDLE nodes, which own resources */ }; typedef struct { const ScrDyn *input; ScrDyn *view; ScrDyn *keys; + ScrStr *text; /* a STRING or BIGINT node's text, until the message is packed */ size_t cursor; bool uncaught; /* an Error encoded as an uncaught exception */ } ScrMessageVisit; +typedef struct { + ScrMessageProperty property; + size_t owner; +} ScrMessagePending; + typedef struct { const void *identity; unsigned domain; size_t node; } ScrMessageIdentity; +/* The encoder's arrays start inline, so a message of up to this many nodes + * and properties allocates only its block. */ +#define SCR_MESSAGE_INLINE 8 + typedef struct { - ScrMessage *message; + ScrMessageNode *nodes; ScrMessageVisit *visits; + size_t count; + size_t capacity; + ScrMessagePending *properties; /* in the order they were reached */ + size_t property_count; + size_t property_capacity; + ScrMessageTyped *typed; + size_t typed_count; + size_t typed_capacity; + size_t text; /* bytes of text in the message block */ ScrMessageIdentity *identities; size_t identity_count; size_t identity_capacity; @@ -99,8 +141,36 @@ typedef struct { size_t stack_capacity; const ScrDyn *transfer; /* the transfer list (a dyn array), or NULL */ bool uncaught; /* the next value is an uncaught exception or its cause */ + bool storage; + bool releases; + ScrMessageNode inline_nodes[SCR_MESSAGE_INLINE]; + ScrMessageVisit inline_visits[SCR_MESSAGE_INLINE]; + ScrMessagePending inline_properties[SCR_MESSAGE_INLINE]; + ScrMessageIdentity inline_identities[2 * SCR_MESSAGE_INLINE]; + size_t inline_stack[SCR_MESSAGE_INLINE]; } ScrMessageEncoder; +static void scr_message_encoder_init(ScrMessageEncoder *encoder, const ScrDyn *transfer, bool uncaught) { + encoder->nodes = encoder->inline_nodes; + encoder->visits = encoder->inline_visits; + encoder->count = 0; + encoder->capacity = SCR_MESSAGE_INLINE; + encoder->properties = encoder->inline_properties; + encoder->property_count = 0; + encoder->property_capacity = SCR_MESSAGE_INLINE; + encoder->typed = NULL; + encoder->typed_count = encoder->typed_capacity = 0; + encoder->text = 0; + encoder->identities = NULL; + encoder->identity_count = encoder->identity_capacity = 0; + encoder->stack = encoder->inline_stack; + encoder->depth = 0; + encoder->stack_capacity = SCR_MESSAGE_INLINE; + encoder->transfer = transfer; + encoder->uncaught = uncaught; + encoder->storage = encoder->releases = false; +} + static bool scr_message_listed(const ScrMessageEncoder *encoder, const ScrDyn *value) { if (!encoder->transfer) return false; for (size_t i = 0; i < encoder->transfer->v.arr.len; i++) { @@ -122,30 +192,42 @@ static size_t scr_message_grow(size_t capacity) { return capacity ? capacity * 2 : 4; } -static unsigned char *scr_message_copy(const void *data, size_t length) { +/* Moves an encoder array of count items to a new one of capacity items, + * freeing the old one unless it is the inline array. */ +static void *scr_message_regrow(void *items, size_t count, size_t capacity, size_t size, + const void *inline_items) { + void *grown = scr_message_alloc(capacity, size); + if (count) memcpy(grown, items, count * size); + if (items != inline_items) free(items); + return grown; +} + +static char *scr_message_copy(const void *data, size_t length) { if (length == SIZE_MAX) scr_trap("scriptc: message too large\n"); - unsigned char *copy = scr_message_alloc(length + 1, 1); + char *copy = scr_message_alloc(length + 1, 1); if (length) memcpy(copy, data, length); return copy; } +/* Reserves text (and its terminator) in the message block. */ +static void scr_message_text(ScrMessageEncoder *encoder, size_t length) { + if (length >= SIZE_MAX - encoder->text) scr_trap("scriptc: message too large\n"); + encoder->text += length + 1; +} + static size_t scr_message_node(ScrMessageEncoder *encoder) { - ScrMessage *message = encoder->message; - if (message->count == message->capacity) { - size_t capacity = scr_message_grow(message->capacity); - ScrMessageNode *nodes = scr_message_alloc(capacity, sizeof(*nodes)); - ScrMessageVisit *visits = scr_message_alloc(capacity, sizeof(*visits)); - if (message->count) { - memcpy(nodes, message->nodes, message->count * sizeof(*nodes)); - memcpy(visits, encoder->visits, message->count * sizeof(*visits)); - } - free(message->nodes); - free(encoder->visits); - message->nodes = nodes; - encoder->visits = visits; - message->capacity = capacity; + if (encoder->count == encoder->capacity) { + size_t capacity = scr_message_grow(encoder->capacity); + encoder->nodes = scr_message_regrow(encoder->nodes, encoder->count, capacity, + sizeof(*encoder->nodes), encoder->inline_nodes); + encoder->visits = scr_message_regrow(encoder->visits, encoder->count, capacity, + sizeof(*encoder->visits), encoder->inline_visits); + encoder->capacity = capacity; } - return message->count++; + size_t id = encoder->count++; + memset(&encoder->nodes[id], 0, sizeof(encoder->nodes[id])); + memset(&encoder->visits[id], 0, sizeof(encoder->visits[id])); + return id; } static size_t scr_message_hash(const void *identity, unsigned domain) { @@ -171,7 +253,11 @@ static size_t scr_message_find(const ScrMessageEncoder *encoder, const void *ide static void scr_message_identify(ScrMessageEncoder *encoder, const void *identity, unsigned domain, size_t node) { if (!identity) return; - if (encoder->identity_count >= encoder->identity_capacity / 2) { + if (!encoder->identity_capacity) { + encoder->identity_capacity = sizeof encoder->inline_identities / sizeof encoder->inline_identities[0]; + encoder->identities = encoder->inline_identities; + memset(encoder->identities, 0, sizeof encoder->inline_identities); + } else if (encoder->identity_count >= encoder->identity_capacity / 2) { size_t capacity = scr_message_grow(encoder->identity_capacity); ScrMessageIdentity *entries = scr_message_alloc(capacity, sizeof(*entries)); for (size_t i = 0; i < encoder->identity_capacity; i++) { @@ -181,7 +267,7 @@ static void scr_message_identify(ScrMessageEncoder *encoder, const void *identit while (entries[slot].identity) slot = (slot + 1) & (capacity - 1); entries[slot] = entry; } - free(encoder->identities); + if (encoder->identities != encoder->inline_identities) free(encoder->identities); encoder->identities = entries; encoder->identity_capacity = capacity; } @@ -194,10 +280,8 @@ static void scr_message_identify(ScrMessageEncoder *encoder, const void *identit static void scr_message_push(ScrMessageEncoder *encoder, size_t node) { if (encoder->depth == encoder->stack_capacity) { size_t capacity = scr_message_grow(encoder->stack_capacity); - size_t *stack = scr_message_alloc(capacity, sizeof(*stack)); - if (encoder->depth) memcpy(stack, encoder->stack, encoder->depth * sizeof(*stack)); - free(encoder->stack); - encoder->stack = stack; + encoder->stack = scr_message_regrow(encoder->stack, encoder->depth, capacity, + sizeof(*encoder->stack), encoder->inline_stack); encoder->stack_capacity = capacity; } encoder->stack[encoder->depth++] = node; @@ -209,13 +293,14 @@ static size_t scr_message_storage(ScrMessageEncoder *encoder, const ScrBytes *by if (found != SIZE_MAX) return found; size_t node = scr_message_node(encoder); scr_message_identify(encoder, owner, SCR_MESSAGE_STORAGE + 1, node); - ScrMessageNode *storage = &encoder->message->nodes[node]; + ScrMessageNode *storage = &encoder->nodes[node]; storage->kind = SCR_MESSAGE_STORAGE; size_t size = scr_bytes_elem_size(owner->elem); if (owner->len > SIZE_MAX / size) scr_trap("scriptc: message too large\n"); - storage->length = owner->len * size; - if (owner->shared) storage->shared = scr_shared_retain(owner->shared); - else storage->data = scr_message_copy(owner->data, storage->length); + storage->v.text.length = owner->len * size; + if (owner->shared) storage->v.text.shared = scr_shared_retain(owner->shared); + else storage->v.text.data = scr_message_copy(owner->data, storage->v.text.length); + encoder->storage = encoder->releases = true; return node; } @@ -285,39 +370,43 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) SCR_RC_PUBLISHED(input->v.typed_ref.ptr)) { scr_sa_thread_shares(); encoder->visits[id].view = (ScrDyn *)input; - ScrMessageNode *node = &encoder->message->nodes[id]; + ScrMessageNode *node = &encoder->nodes[id]; + if (encoder->typed_count == encoder->typed_capacity) { + size_t capacity = scr_message_grow(encoder->typed_capacity); + encoder->typed = scr_message_regrow(encoder->typed, encoder->typed_count, capacity, + sizeof(*encoder->typed), NULL); + encoder->typed_capacity = capacity; + } node->kind = SCR_MESSAGE_TYPED_REF; - node->typed.ptr = input->v.typed_ref.ptr; - node->typed.retain = input->v.typed_ref.retain; - node->typed.release = input->v.typed_ref.release; - node->typed.type_key = input->v.typed_ref.type_key; - node->typed.type_key_len = input->v.typed_ref.type_key_len; - node->typed.materialize = input->v.typed_ref.materialize; - node->typed.commit = input->v.typed_ref.commit; - node->typed.traced = input->v.typed_ref.traced; + node->v.typed_index = encoder->typed_count; + encoder->typed[encoder->typed_count++] = (ScrMessageTyped){ + input->v.typed_ref.ptr, input->v.typed_ref.retain, input->v.typed_ref.release, + input->v.typed_ref.type_key, input->v.typed_ref.type_key_len, input->v.typed_ref.materialize, + input->v.typed_ref.commit, input->v.typed_ref.traced, + }; if (getenv("SCRIPTC_PUBLISH_TRACE")) - fprintf(stderr, "scriptc: published %.*s shared by reference\n", (int)node->typed.type_key_len, - node->typed.type_key); + fprintf(stderr, "scriptc: published %.*s shared by reference\n", (int)input->v.typed_ref.type_key_len, + input->v.typed_ref.type_key); return id; } if ((input->kind == SCR_DYN_OBJ || input->kind == SCR_DYN_ARR) && input->rc == SIZE_MAX) { scr_sa_thread_shares(); encoder->visits[id].view = (ScrDyn *)input; - ScrMessageNode *node = &encoder->message->nodes[id]; + ScrMessageNode *node = &encoder->nodes[id]; node->kind = SCR_MESSAGE_PUBLISHED; - node->published = (ScrDyn *)input; + node->v.published = (ScrDyn *)input; return id; } ScrDyn *value = input->kind == SCR_DYN_TYPED_REF ? scr_dyn_typed_ref_materialize(input) : (ScrDyn *)input; encoder->visits[id].view = value; if (!value || scr_exc_pending()) return SIZE_MAX; - ScrMessageNode *node = &encoder->message->nodes[id]; + ScrMessageNode *node = &encoder->nodes[id]; ScrError *error = scr_errdyn_err_of(input); if (!error && value != input) error = scr_errdyn_err_of(value); if (error && uncaught && error->vt != &scr_error_vts[SCR_ERR_DOMEX]) { node->kind = SCR_MESSAGE_ERROR; - node->number = scr_message_error_kind(error); + node->v.number = scr_message_error_kind(error); scr_error_release(error); encoder->visits[id].uncaught = true; encoder->visits[id].keys = scr_message_uncaught_keys(value); @@ -327,7 +416,7 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) } if (error) { node->kind = SCR_MESSAGE_ERROR; - node->number = SCR_ERR_ERROR; + node->v.number = SCR_ERR_ERROR; static const char *const names[] = { "Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError", }; @@ -336,7 +425,7 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) }; for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) if (error->name->len == strlen(names[i]) && !memcmp(error->name->data, names[i], error->name->len)) - node->number = kinds[i]; + node->v.number = kinds[i]; ScrDyn *keys = scr_dyn_new_arr(); static const char *const fields[] = {"message", "stack", "cause"}; for (size_t i = 0; i < sizeof fields / sizeof fields[0]; i++) { @@ -353,26 +442,28 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) switch (value->kind) { case SCR_DYN_UNDEF: node->kind = SCR_MESSAGE_UNDEFINED; break; case SCR_DYN_NULL: node->kind = SCR_MESSAGE_NULL; break; - case SCR_DYN_BOOL: node->kind = SCR_MESSAGE_BOOL; node->number = value->v.b; break; - case SCR_DYN_NUM: node->kind = SCR_MESSAGE_NUMBER; node->number = value->v.num; break; + case SCR_DYN_BOOL: node->kind = SCR_MESSAGE_BOOL; node->v.number = value->v.b; break; + case SCR_DYN_NUM: node->kind = SCR_MESSAGE_NUMBER; node->v.number = value->v.num; break; case SCR_DYN_STR: + /* The text is copied into the message block when it is packed. */ node->kind = SCR_MESSAGE_STRING; - node->length = value->v.str->len; - node->data = scr_message_copy(value->v.str->data, node->length); + encoder->visits[id].text = scr_str_retain(value->v.str); + node->v.text.length = value->v.str->len; + scr_message_text(encoder, node->v.text.length); break; case SCR_DYN_BIGINT: { ScrStr *text = scr_bigint_to_string(value->v.bigint, 10); if (!text) return SIZE_MAX; node->kind = SCR_MESSAGE_BIGINT; - node->length = text->len; - node->data = scr_message_copy(text->data, text->len); - scr_str_release(text); + encoder->visits[id].text = text; + node->v.text.length = text->len; + scr_message_text(encoder, node->v.text.length); break; } case SCR_DYN_ARR: case SCR_DYN_OBJ: node->kind = value->kind == SCR_DYN_ARR ? SCR_MESSAGE_ARRAY : SCR_MESSAGE_OBJECT; - node->length = value->kind == SCR_DYN_ARR ? value->v.arr.len : 0; + if (value->kind == SCR_DYN_ARR) node->v.length = value->v.arr.len; encoder->visits[id].keys = scr_dyn_own_keys(value); if (!encoder->visits[id].keys) return SIZE_MAX; scr_message_push(encoder, id); @@ -389,8 +480,9 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) return SIZE_MAX; } node->kind = SCR_MESSAGE_PORT; - node->channel = channel; - node->number = side; + node->v.port.channel = channel; + node->v.port.side = side; + encoder->releases = true; break; } bool buffer = scr_buffer_storage_is(value); @@ -402,21 +494,22 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) if (scr_exc_pending()) return SIZE_MAX; goto unsupported; } - node = &encoder->message->nodes[id]; + node = &encoder->nodes[id]; node->kind = SCR_MESSAGE_HANDLE; - node->transfer = transfer; - node->payload = payload; + node->v.handle.transfer = transfer; + node->v.handle.payload = payload; + encoder->releases = true; break; } const ScrBytes *bytes = buffer ? value->v.handle.ptr : value->v.bytes; size_t storage = scr_message_storage(encoder, bytes); /* Adding the storage node can reallocate the node array. */ - node = &encoder->message->nodes[id]; + node = &encoder->nodes[id]; node->kind = buffer ? SCR_MESSAGE_ARRAY_BUFFER : SCR_MESSAGE_BYTES; - node->storage = storage; - node->element = bytes->elem; - node->length = bytes->len; - node->offset = (size_t)(bytes->data - (bytes->backing ? bytes->backing : bytes)->data); + node->v.view.storage = storage; + node->element = (unsigned char)bytes->elem; + node->v.view.length = bytes->len; + node->v.view.offset = (size_t)(bytes->data - (bytes->backing ? bytes->backing : bytes)->data); node->data_view = bytes->is_data_view; break; } @@ -430,21 +523,20 @@ unsupported: static void scr_message_property(ScrMessageEncoder *encoder, size_t id, const ScrStr *key, size_t value, bool hidden) { - ScrMessageNode *node = &encoder->message->nodes[id]; - if (node->count == node->capacity) { - size_t capacity = scr_message_grow(node->capacity); - ScrMessageProperty *properties = scr_message_alloc(capacity, sizeof(*properties)); - if (node->count) memcpy(properties, node->properties, node->count * sizeof(*properties)); - free(node->properties); - node->properties = properties; - node->capacity = capacity; + if (encoder->property_count == encoder->property_capacity) { + size_t capacity = scr_message_grow(encoder->property_capacity); + encoder->properties = scr_message_regrow(encoder->properties, encoder->property_count, capacity, + sizeof(*encoder->properties), encoder->inline_properties); + encoder->property_capacity = capacity; } - node->properties[node->count++] = (ScrMessageProperty){ - (char *)scr_message_copy(key->data, key->len), key->len, value, hidden, - }; + ScrMessageNode *node = &encoder->nodes[id]; + if (node->count == UINT32_MAX) scr_trap("scriptc: message too large\n"); + node->count++; + scr_message_text(encoder, key->len); + /* The key stays alive in the owner's key list until the message is packed. */ + encoder->properties[encoder->property_count++] = (ScrMessagePending){{key->data, key->len, value, hidden}, id}; } - /* ── publication: zero-copy delivery of deeply frozen plain-data graphs ── * Structured clone of a graph that is immutable on BOTH sides is observably * a share, as long as the receiver freezes what it receives (Node's clone is @@ -558,7 +650,8 @@ static ScrMessage *scr_message_try_publish(const ScrDyn *value) { if (!scr_publish_enabled || (value->kind != SCR_DYN_OBJ && value->kind != SCR_DYN_ARR)) return NULL; ScrMessage *message = NULL; ScrPublish p = {0}; - if (value->rc == SIZE_MAX || scr_publish_collect(&p, (ScrDyn *)value)) { + /* Most messages are not frozen: check the root before collecting. */ + if (value->rc == SIZE_MAX || (scr_publish_container_ok(value) && scr_publish_collect(&p, (ScrDyn *)value))) { for (size_t i = 0; i < p.count; i++) { ScrDyn *d = p.nodes[i]; if ((uintptr_t)d & 1) { @@ -582,11 +675,11 @@ static ScrMessage *scr_message_try_publish(const ScrDyn *value) { } } scr_sa_thread_shares(); - message = scr_message_alloc(1, sizeof(*message)); - message->nodes = scr_message_alloc(1, sizeof(*message->nodes)); - message->count = message->capacity = 1; + message = scr_message_alloc(1, sizeof(*message) + sizeof(*message->nodes)); + message->nodes = (ScrMessageNode *)(message + 1); + message->count = 1; message->nodes[0].kind = SCR_MESSAGE_PUBLISHED; - message->nodes[0].published = (ScrDyn *)value; + message->nodes[0].v.published = (ScrDyn *)value; if (getenv("SCRIPTC_PUBLISH_TRACE")) fprintf(stderr, "scriptc: published %zu nodes zero-copy%s\n", p.count, value->rc == SIZE_MAX && !p.count ? " (already published)" : ""); @@ -599,13 +692,14 @@ static ScrMessage *scr_message_try_publish(const ScrDyn *value) { } static ScrMessage *scr_message_encode_with(const ScrDyn *value, const ScrDyn *transfer); -static ScrMessage *scr_message_encode_run(ScrMessageEncoder encoder, const ScrDyn *value); +static ScrMessage *scr_message_encode_run(ScrMessageEncoder *encoder, const ScrDyn *value); ScrMessage *scr_message_encode(const ScrDyn *value) { return scr_message_encode_with(value, NULL); } ScrMessage *scr_message_encode_uncaught(const ScrDyn *value) { - ScrMessage *message = scr_message_alloc(1, sizeof(*message)); - return scr_message_encode_run((ScrMessageEncoder){.message = message, .uncaught = true}, value); + ScrMessageEncoder encoder; + scr_message_encoder_init(&encoder, NULL, true); + return scr_message_encode_run(&encoder, value); } ScrMessage *scr_message_encode_transfer(const ScrDyn *value, const ScrDyn *transfer) { @@ -635,19 +729,87 @@ ScrMessage *scr_message_encode_transfer(const ScrDyn *value, const ScrDyn *trans static ScrMessage *scr_message_encode_with(const ScrDyn *value, const ScrDyn *transfer) { ScrMessage *published = transfer ? NULL : scr_message_try_publish(value); if (published) return published; - ScrMessage *message = scr_message_alloc(1, sizeof(*message)); - return scr_message_encode_run((ScrMessageEncoder){.message = message, .transfer = transfer}, value); + ScrMessageEncoder encoder; + scr_message_encoder_init(&encoder, transfer, false); + return scr_message_encode_run(&encoder, value); } -static ScrMessage *scr_message_encode_run(ScrMessageEncoder encoder, const ScrDyn *value) { - ScrMessage *message = encoder.message; - if (scr_message_value(&encoder, value) == SIZE_MAX) goto done; - while (encoder.depth && !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; } +/* Releases what a node owns: a STORAGE node's bytes, a PORT node's + * channel end and a HANDLE node's payload. */ +static void scr_message_drop(ScrMessageNode *node) { + switch (node->kind) { + case SCR_MESSAGE_STORAGE: + free(node->v.text.data); + scr_shared_release(node->v.text.shared); + break; + case SCR_MESSAGE_PORT: scr_message_port_ops->release(node->v.port.channel); break; + case SCR_MESSAGE_HANDLE: node->v.handle.transfer->drop(node->v.handle.payload); break; + default: break; + } +} + +/* Copies the encoded nodes into one block: the header, the nodes, the + * properties grouped by node (in the order they were reached), the typed + * records and the text. */ +static ScrMessage *scr_message_pack(ScrMessageEncoder *encoder) { + size_t count = encoder->count; + size_t properties = encoder->property_count; + size_t typed = encoder->typed_count; + size_t size = sizeof(ScrMessage); + size_t sizes[] = { + count, sizeof(ScrMessageNode), properties, sizeof(ScrMessageProperty), typed, sizeof(ScrMessageTyped), + }; + for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i += 2) { + if (sizes[i] > (SIZE_MAX - size) / sizes[i + 1]) scr_trap("scriptc: message too large\n"); + size += sizes[i] * sizes[i + 1]; + } + if (encoder->text > SIZE_MAX - size) scr_trap("scriptc: message too large\n"); + ScrMessage *message = malloc(size + encoder->text); + if (!message) scr_trap("scriptc: out of memory\n"); + ScrMessageNode *nodes = (ScrMessageNode *)(message + 1); + ScrMessageProperty *slots = (ScrMessageProperty *)(nodes + count); + ScrMessageTyped *records = (ScrMessageTyped *)(slots + properties); + char *text = (char *)(records + typed); + *message = (ScrMessage){nodes, count, encoder->storage, encoder->releases}; + memcpy(nodes, encoder->nodes, count * sizeof(*nodes)); + if (typed) memcpy(records, encoder->typed, typed * sizeof(*records)); + size_t first = 0; + for (size_t i = 0; i < count; i++) { + ScrMessageNode *node = &nodes[i]; + node->properties = slots + first; + first += node->count; + node->count = 0; + if (node->kind == SCR_MESSAGE_STRING || node->kind == SCR_MESSAGE_BIGINT) { + memcpy(text, encoder->visits[i].text->data, node->v.text.length); + text[node->v.text.length] = 0; + node->v.text.data = text; + text += node->v.text.length + 1; + } else if (node->kind == SCR_MESSAGE_TYPED_REF) { + node->v.typed = &records[node->v.typed_index]; + } + } + for (size_t i = 0; i < properties; i++) { + const ScrMessagePending *pending = &encoder->properties[i]; + ScrMessageNode *node = &nodes[pending->owner]; + ScrMessageProperty *slot = (ScrMessageProperty *)&node->properties[node->count++]; + *slot = pending->property; + memcpy(text, pending->property.key, pending->property.length); + text[pending->property.length] = 0; + slot->key = text; + text += pending->property.length + 1; + } + 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()) { + size_t id = encoder->stack[encoder->depth - 1]; + ScrMessageVisit *visit = &encoder->visits[id]; + if (visit->cursor == visit->keys->v.arr.len) { encoder->depth--; continue; } ScrDyn *key = visit->keys->v.arr.items[visit->cursor++]; - bool error = message->nodes[id].kind == SCR_MESSAGE_ERROR; + 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; } @@ -657,33 +819,30 @@ static ScrMessage *scr_message_encode_run(ScrMessageEncoder encoder, const ScrDy * and symbols, and serializes its cause the same way. */ if (child->kind == SCR_DYN_FUNC || child->kind == SCR_DYN_SYMBOL) { scr_dyn_release(child); continue; } hidden = !scr_dyn_has_own(visit->view, key->v.str) || !scr_dyn_property_is_enumerable(visit->view, key->v.str); - encoder.uncaught = key->v.str->len == 5 && !memcmp(key->v.str->data, "cause", 5); + encoder->uncaught = key->v.str->len == 5 && !memcmp(key->v.str->data, "cause", 5); } - size_t next = scr_message_value(&encoder, child); + size_t next = scr_message_value(encoder, child); scr_dyn_release(child); if (next == SIZE_MAX) break; - scr_message_property(&encoder, id, key->v.str, next, hidden); + scr_message_property(encoder, id, key->v.str, next, hidden); } done: - for (size_t i = 0; i < message->count; i++) { - ScrMessageVisit *visit = &encoder.visits[i]; + 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]); + for (size_t i = 0; i < encoder->count; i++) { + ScrMessageVisit *visit = &encoder->visits[i]; scr_dyn_release(visit->keys); if (visit->view != visit->input) scr_dyn_release(visit->view); scr_dyn_release((ScrDyn *)visit->input); + scr_str_release(visit->text); } - free(encoder.visits); - free(encoder.identities); - free(encoder.stack); - if (scr_exc_pending()) { scr_message_free(message); return NULL; } - /* A queued message keeps its nodes until it is received: drop the - * growth slack. */ - if (message->count && message->count < message->capacity) { - ScrMessageNode *nodes = realloc(message->nodes, message->count * sizeof(*nodes)); - if (nodes) { - message->nodes = nodes; - message->capacity = message->count; - } - } + if (encoder->nodes != encoder->inline_nodes) free(encoder->nodes); + if (encoder->visits != encoder->inline_visits) free(encoder->visits); + if (encoder->properties != encoder->inline_properties) free(encoder->properties); + if (encoder->identities != encoder->inline_identities) free(encoder->identities); + if (encoder->stack != encoder->inline_stack) free(encoder->stack); + free(encoder->typed); return message; } @@ -732,26 +891,31 @@ static void scr_message_tag_document(const ScrMessage *message, ScrDyn **values) ScrDyn *scr_message_decode(const ScrMessage *message) { if (message->count == 1 && message->nodes[0].kind == SCR_MESSAGE_PUBLISHED) - return scr_dyn_retain(message->nodes[0].published); - ScrDyn **values = scr_message_alloc(message->count, sizeof(*values)); - ScrBytes **storage = scr_message_alloc(message->count, sizeof(*storage)); - for (size_t i = 0; i < message->count; i++) { + return scr_dyn_retain(message->nodes[0].v.published); + ScrDyn *inline_values[SCR_MESSAGE_INLINE]; + ScrDyn **values = message->count <= SCR_MESSAGE_INLINE + ? inline_values : scr_message_alloc(message->count, sizeof(*values)); + memset(values, 0, message->count * sizeof(*values)); + ScrBytes **storage = message->storage ? scr_message_alloc(message->count, sizeof(*storage)) : NULL; + for (size_t i = 0; storage && i < message->count; i++) { const ScrMessageNode *node = &message->nodes[i]; if (node->kind != SCR_MESSAGE_STORAGE) continue; - storage[i] = node->shared ? scr_shared_wrap(node->shared) : scr_bytes_new(SCR_BYTES_U8, (double)node->length); + storage[i] = node->v.text.shared ? scr_shared_wrap(node->v.text.shared) + : scr_bytes_new(SCR_BYTES_U8, (double)node->v.text.length); if (!storage[i]) goto done; - if (!node->shared && node->length) memcpy(storage[i]->data, node->data, node->length); + if (!node->v.text.shared && node->v.text.length) + memcpy(storage[i]->data, node->v.text.data, node->v.text.length); } for (size_t i = 0; i < message->count; i++) { const ScrMessageNode *node = &message->nodes[i]; switch (node->kind) { case SCR_MESSAGE_UNDEFINED: values[i] = scr_dyn_retain(scr_dyn_undefined()); break; case SCR_MESSAGE_NULL: values[i] = scr_dyn_new_null(); break; - case SCR_MESSAGE_BOOL: values[i] = scr_dyn_new_bool(node->number != 0); break; - case SCR_MESSAGE_NUMBER: values[i] = scr_dyn_new_num(node->number); break; + case SCR_MESSAGE_BOOL: values[i] = scr_dyn_new_bool(node->v.number != 0); break; + case SCR_MESSAGE_NUMBER: values[i] = scr_dyn_new_num(node->v.number); break; case SCR_MESSAGE_STRING: case SCR_MESSAGE_BIGINT: { - ScrStr *text = scr_str_new((const char *)node->data, node->length); + ScrStr *text = scr_str_new(node->v.text.data, node->v.text.length); if (node->kind == SCR_MESSAGE_STRING) values[i] = scr_dyn_new_str(text); else { ScrBigInt *integer = scr_bigint_parse(text); @@ -762,19 +926,19 @@ ScrDyn *scr_message_decode(const ScrMessage *message) { } case SCR_MESSAGE_ARRAY: values[i] = scr_dyn_new_arr(); - for (size_t j = 0; j < node->length; j++) scr_dyn_arr_push_hole(values[i]); + for (size_t j = 0; j < node->v.length; j++) scr_dyn_arr_push_hole(values[i]); break; case SCR_MESSAGE_OBJECT: values[i] = scr_dyn_new_obj(); break; case SCR_MESSAGE_ERROR: { scr_error_set_traced(); - ScrError *error = scr_error_new((int)node->number, NULL); + ScrError *error = scr_error_new((int)node->v.number, NULL); values[i] = scr_dyn_from_error(error); scr_error_release(error); break; } case SCR_MESSAGE_BYTES: { - ScrBytes *bytes = scr_bytes_buffer_view(storage[node->storage], node->element, - (double)node->offset, true, (double)node->length); + ScrBytes *bytes = scr_bytes_buffer_view(storage[node->v.view.storage], (ScrBytesElem)node->element, + (double)node->v.view.offset, true, (double)node->v.view.length); if (bytes) { bytes->is_data_view = node->data_view; values[i] = scr_dyn_new_bytes(bytes); @@ -783,19 +947,21 @@ ScrDyn *scr_message_decode(const ScrMessage *message) { break; } case SCR_MESSAGE_ARRAY_BUFFER: - values[i] = scr_array_buffer_from_bytes(storage[node->storage]); + values[i] = scr_array_buffer_from_bytes(storage[node->v.view.storage]); break; case SCR_MESSAGE_STORAGE: continue; - case SCR_MESSAGE_PUBLISHED: values[i] = scr_dyn_retain(node->published); break; - case SCR_MESSAGE_TYPED_REF: - values[i] = (node->typed.traced ? scr_dyn_new_typed_ref_traced : scr_dyn_new_typed_ref)( - node->typed.ptr, node->typed.retain, node->typed.release, node->typed.type_key, - node->typed.type_key_len, node->typed.materialize, node->typed.commit); + case SCR_MESSAGE_PUBLISHED: values[i] = scr_dyn_retain(node->v.published); break; + case SCR_MESSAGE_TYPED_REF: { + const ScrMessageTyped *typed = node->v.typed; + values[i] = (typed->traced ? scr_dyn_new_typed_ref_traced : scr_dyn_new_typed_ref)( + typed->ptr, typed->retain, typed->release, typed->type_key, typed->type_key_len, + typed->materialize, typed->commit); break; + } case SCR_MESSAGE_PORT: - values[i] = scr_message_port_ops->adopt(node->channel, (int)node->number); + values[i] = scr_message_port_ops->adopt(node->v.port.channel, node->v.port.side); break; - case SCR_MESSAGE_HANDLE: values[i] = node->transfer->adopt(node->payload); break; + case SCR_MESSAGE_HANDLE: values[i] = node->v.handle.transfer->adopt(node->v.handle.payload); break; } if (!values[i] || scr_exc_pending()) goto done; } @@ -805,7 +971,7 @@ ScrDyn *scr_message_decode(const ScrMessage *message) { const ScrMessageProperty *property = &node->properties[j]; ScrDyn *value = scr_dyn_retain(values[property->value]); if (node->kind == SCR_MESSAGE_ARRAY) { - size_t index = scr_message_array_index(property->key, property->length, node->length); + size_t index = scr_message_array_index(property->key, property->length, node->v.length); if (index != SIZE_MAX) { values[i]->v.arr.items[index] = value; values[i]->v.arr.presence[index] = 1; @@ -841,24 +1007,16 @@ done:; ScrDyn *result = !scr_exc_pending() ? scr_dyn_retain(values[0]) : NULL; for (size_t i = 0; i < message->count; i++) { scr_dyn_release(values[i]); - scr_bytes_release(storage[i]); + if (storage) scr_bytes_release(storage[i]); } - free(values); + if (values != inline_values) free(values); free(storage); return result; } void scr_message_free(ScrMessage *message) { if (!message) return; - for (size_t i = 0; i < message->count; i++) { - ScrMessageNode *node = &message->nodes[i]; - for (size_t j = 0; j < node->count; j++) free(node->properties[j].key); - free(node->properties); - free(node->data); - scr_shared_release(node->shared); - if (node->kind == SCR_MESSAGE_PORT) scr_message_port_ops->release(node->channel); - if (node->kind == SCR_MESSAGE_HANDLE) node->transfer->drop(node->payload); - } - free(message->nodes); + if (message->releases) + for (size_t i = 0; i < message->count; i++) scr_message_drop(&message->nodes[i]); free(message); } diff --git a/packages/runtime/src/scr_message.test.c b/packages/runtime/src/scr_message.test.c index a6c940783..bdabc4d12 100644 --- a/packages/runtime/src/scr_message.test.c +++ b/packages/runtime/src/scr_message.test.c @@ -172,6 +172,84 @@ static void check_documents(void) { scr_message_free(message); } +/* A message larger than the encoder's inline arrays (nodes, properties, + * identities and the visit stack) keeps its key order, shared values and + * text, and an encode started from a getter during another encode + * produces its own message. */ +static SCR_TL ScrMessage *nested_message; +static ScrDyn *nested_getter(ScrClosure *closure, ScrDyn *const *args, size_t argc) { + (void)closure; (void)args; (void)argc; + ScrDyn *inner = scr_dyn_new_arr(); + scr_dyn_arr_push(inner, scr_dyn_new_num(41)); + nested_message = scr_message_encode(inner); + scr_dyn_release(inner); + return scr_dyn_new_num(42); +} + +static void check_large(void) { + ScrDyn *root = scr_dyn_new_obj(); + ScrDyn *shared = scr_dyn_new_obj(); + put_number(shared, "shared", 1); + ScrDyn *chain = root; + char key[32]; + for (int i = 0; i < 40; i++) { + ScrDyn *item = scr_dyn_new_obj(); + put_number(item, "index", i); + snprintf(key, sizeof key, "label-%d", i); + ScrStr *text = scr_str_new(key, strlen(key)); + scr_dyn_obj_set(item, "label", 5, scr_dyn_new_str(text)); + scr_str_release(text); + scr_dyn_obj_set(item, "shared", 6, scr_dyn_retain(shared)); + snprintf(key, sizeof key, "item%d", i); + scr_dyn_obj_set(root, key, strlen(key), item); + /* A chain 40 objects deep grows the visit stack. */ + ScrDyn *next = scr_dyn_new_obj(); + scr_dyn_obj_set(chain, "next", 4, next); + chain = next; + } + scr_dyn_release(shared); + ScrClosure *closure = scr_closure_new(NULL, 0); + ScrDyn *descriptor = scr_dyn_new_obj(); + scr_dyn_obj_set(descriptor, "get", 3, scr_dyn_new_func(closure, nested_getter, 0, "", "")); + scr_dyn_obj_set(descriptor, "enumerable", 10, scr_dyn_new_bool(true)); + ScrStr *name = scr_str_new("nested", 6); + ScrDyn *name_value = scr_dyn_new_str(name); + scr_dyn_release(scr_dyn_define_property(root, name_value, descriptor)); + scr_dyn_release(name_value); + scr_dyn_release(descriptor); + scr_str_release(name); + ScrMessage *message = scr_message_encode(root); + assert(message && !scr_exc_pending() && nested_message); + scr_dyn_release(root); + scr_collect_cycles(); + ScrDyn *decoded = scr_message_decode(message); + assert(decoded && !scr_exc_pending()); + assert(decoded->v.obj.len == 42); + assert(decoded->v.obj.entries[0].key_len == 5 && !memcmp(decoded->v.obj.entries[0].key, "item0", 5)); + assert(decoded->v.obj.entries[41].key_len == 6 && !memcmp(decoded->v.obj.entries[41].key, "nested", 6)); + assert(scr_dyn_obj_get(decoded, "nested", 6)->v.num == 42); + ScrDyn *first = scr_dyn_obj_get(decoded, "item0", 5); + for (int i = 0; i < 40; i++) { + snprintf(key, sizeof key, "item%d", i); + ScrDyn *item = scr_dyn_obj_get(decoded, key, strlen(key)); + assert(item && scr_dyn_obj_get(item, "index", 5)->v.num == i); + assert(scr_dyn_obj_get(item, "shared", 6) == scr_dyn_obj_get(first, "shared", 6)); + snprintf(key, sizeof key, "label-%d", i); + ScrStr *label = scr_dyn_obj_get(item, "label", 5)->v.str; + assert(label->len == strlen(key) && !memcmp(label->data, key, label->len)); + } + ScrDyn *link = decoded; + for (int i = 0; i < 40; i++) link = scr_dyn_obj_get(link, "next", 4); + assert(link && link->kind == SCR_DYN_OBJ && link->v.obj.len == 0); + scr_dyn_release(decoded); + ScrDyn *inner = scr_message_decode(nested_message); + assert(inner && inner->v.arr.len == 1 && inner->v.arr.items[0]->v.num == 41); + scr_dyn_release(inner); + scr_collect_cycles(); + scr_message_free(nested_message); + scr_message_free(message); +} + /* 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 @@ -297,6 +375,7 @@ int main(void) { check_getters(); check_rejection(); check_documents(); + check_large(); check_handle_transfer(); scr_context_cleanup(); puts("message graphs preserve identity, sparse values, byte aliases and getter order"); From 1a51223cd6f4b4899761a7ec8da3378e0f048c68 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 01:01:01 -0500 Subject: [PATCH 022/102] Say where the region's trap and memoryUsage accounting come from Comments only: scr_trap is the runtime's failure path and the standalone allocator test defines its own, and the region's chunks count in process.memoryUsage() through scr_heap_stats. --- packages/runtime/src/scr_alloc.c | 4 ++++ packages/runtime/src/scr_lib.h | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/runtime/src/scr_alloc.c b/packages/runtime/src/scr_alloc.c index f2304aace..3a36f672e 100644 --- a/packages/runtime/src/scr_alloc.c +++ b/packages/runtime/src/scr_alloc.c @@ -2072,6 +2072,8 @@ static __attribute__((noinline)) void scr_plr_reserve(void) { } } __atomic_clear(&lock, __ATOMIC_RELEASE); + /* scr_trap is the runtime's failure path (scr_exception.c); the + * allocator's standalone test defines its own (scr_alloc.test.c). */ if (!scr_plr_base) { static const char message[] = "scriptc: cannot reserve address space below 32 GiB for program-lifetime objects\n"; @@ -2188,6 +2190,8 @@ static __attribute__((noinline)) void *scr_plr_refill(size_t n) { scr_plr_mine_waste += left; #endif } + /* process.memoryUsage() counts the chunk in heapTotal and heapUsed + * (scr_heap_stats, scr_plr_heap_stats). */ __atomic_fetch_add(&scr_plr_held, chunk, __ATOMIC_RELAXED); scr_plr_chunk.next = p + SCR_PLR_LINK + n; scr_plr_chunk.limit = p + chunk; diff --git a/packages/runtime/src/scr_lib.h b/packages/runtime/src/scr_lib.h index 1b859cea1..411d1e684 100644 --- a/packages/runtime/src/scr_lib.h +++ b/packages/runtime/src/scr_lib.h @@ -238,7 +238,8 @@ double scr_process_memory_usage_field(double k); double scr_process_rss(void); /* The runtime heap's footprint (scr_alloc.c): bytes held from the system * and bytes in live allocations, for the calling thread's allocator plus - * the system allocator where it reports them. */ + * the system allocator where it reports them, plus the program-lifetime + * region's chunks (compact class instances). */ void scr_heap_stats(double *total, double *used); /* process.ppid: the parent's pid at the time of the read. */ double scr_process_ppid(void); From 93e13f49a0d0e44896769ec157bd24b153b73492 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 01:06:31 -0500 Subject: [PATCH 023/102] Keep structural names apart by declaration kind and name recursive types by position Structural positions named an enclosing declaration by its name and its ordinal among the declarations of the same kind and name, without the kind. A getter and the setter of the same property, or a class and the namespace merged with it, therefore had the same path, and local classes declared in both shared one class. The path now includes the kind, and interfaces and type aliases anchor the positions inside them. Recursive record and union placeholders were named by their printed type and the byte offset of their declaration. A comment or blank line above the type renamed them, and two instantiations that print alike (type arguments that are type parameters or classes of one name from different declarations) threw an InternalCompilerError. Placeholders are now named by the printed type and the structural position of the declaration, and the same for up to three levels of type arguments. A description that two types still share gets a numbered suffix for the later one. --- .../src/frontend/lowering/lowerer.test.ts | 16 +-- .../compiler/src/frontend/lowering/lowerer.ts | 1 + .../frontend/lowering/structural-positions.ts | 16 ++- .../compiler/src/frontend/type-mapper.test.ts | 2 +- packages/compiler/src/frontend/type-mapper.ts | 78 +++++++++--- packages/compiler/test/stable-names.test.ts | 112 ++++++++++++++++++ 6 files changed, 192 insertions(+), 33 deletions(-) create mode 100644 packages/compiler/test/stable-names.test.ts diff --git a/packages/compiler/src/frontend/lowering/lowerer.test.ts b/packages/compiler/src/frontend/lowering/lowerer.test.ts index 750c27694..7fbb9661f 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.test.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.test.ts @@ -33,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, "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(); @@ -55,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, "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]); @@ -76,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, "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(); @@ -130,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, "Recursive")); + const pendingShape = record(lowerer.shapes.recursiveRef(recursive, () => "Recursive")); const pending = lowerer.unions.intern([pendingShape], { field: "kind", cases: [{ tag: 0, values: ["a"] }], @@ -144,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, "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], { @@ -185,7 +185,7 @@ test("removing undefined reuses the discriminator transformation without hiding const recursive = {} as Type; const pending: IrType = { kind: "union", - unionId: lowerer.unions.recursiveRef(recursive, "Recursive"), + unionId: lowerer.unions.recursiveRef(recursive, () => "Recursive"), }; expect(lowerer.stripUndefinedArm(pending)).toEqual(pending); lowerer.unions.finalizeRecursive(recursive, [STRING, UNDEFINED_T]); @@ -221,7 +221,7 @@ test("adding undefined reuses semantic union transformations and sees recursive const recursive = {} as Type; const pending: IrType = { kind: "union", - unionId: lowerer.unions.recursiveRef(recursive, "Recursive"), + unionId: lowerer.unions.recursiveRef(recursive, () => "Recursive"), }; const before = lowerer.withUndefinedArmOf(pending); lowerer.unions.finalizeRecursive(recursive, [a, b], discriminant); @@ -236,7 +236,7 @@ test("optional union widening keeps refused and missing contracts current", () = const recursive = {} as Type; const pending: IrType = { kind: "union", - unionId: lowerer.unions.recursiveRef(recursive, "Recursive"), + unionId: lowerer.unions.recursiveRef(recursive, () => "Recursive"), }; expect(lowerer.withUndefinedArmOf(pending)).not.toBeNull(); lowerer.unions.finalizeRecursive(recursive, [{ kind: "date" }, STRING]); diff --git a/packages/compiler/src/frontend/lowering/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index 687a2fb1a..3f8a0a66e 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -3568,6 +3568,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, diff --git a/packages/compiler/src/frontend/lowering/structural-positions.ts b/packages/compiler/src/frontend/lowering/structural-positions.ts index cdc290b4b..ea8535d9e 100644 --- a/packages/compiler/src/frontend/lowering/structural-positions.ts +++ b/packages/compiler/src/frontend/lowering/structural-positions.ts @@ -15,6 +15,8 @@ const ANCHOR_KINDS: ReadonlySet = new Set([ 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 @@ -34,10 +36,10 @@ function anchorOf(node: ts.Node): ts.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 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 + * 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 @@ -75,8 +77,10 @@ export class StructuralPositions { if (ts.isSourceFile(anchor)) path = anchor.fileName; else { const parent = anchorOf(anchor); - const name = anchorName(anchor); - path = `${this.pathOf(parent)}/${name}#${this.ordinalIn(parent, anchor, `${anchor.kind}:${name}`)}`; + // 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; diff --git a/packages/compiler/src/frontend/type-mapper.test.ts b/packages/compiler/src/frontend/type-mapper.test.ts index a99eb44cc..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, "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 ce73e8bc2..79091cadc 100644 --- a/packages/compiler/src/frontend/type-mapper.ts +++ b/packages/compiler/src/frontend/type-mapper.ts @@ -1,5 +1,5 @@ import { InternalCompilerError } from "../errors.js"; -import { keyedHelperName } from "./lowering/stable-names.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"; @@ -393,13 +393,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, description: string): string { + * entry (empty fields) the outer frame finalizes. `describe` names a new + * placeholder (recursiveTypeName). */ + recursiveRef(t: ts.Type, describe: () => string): string { let id = this.recIds.get(t); if (id === undefined) { - id = keyedHelperName(this, "r", `recursive:${description}`, ""); - if (this.byId.has(id)) - throw new InternalCompilerError(`two recursive types share the description ${description}`); + id = recursivePlaceholderName(this, "r", describe(), (name) => this.byId.has(name)); const shape: IrRecordShape = { id, fields: [] }; this.byId.set(id, shape); this.shapes.push(shape); @@ -546,15 +545,55 @@ export class ShapeRegistry { } } -/** A recursive checker type's printed form and first declaration, which - * name its placeholder whichever frame first reaches it. */ -function recursiveTypeName(t: ts.Type, ctx: Pick): string { +/** The id of a recursive placeholder described by `description`. Two + * different types can still share a description (recursiveTypeName 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 recursiveTypeName describes. */ +const RECURSIVE_NAME_DEPTH = 3; + +/** A recursive checker type's description, which names its placeholder + * whichever frame first reaches it: 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). */ +function recursiveTypeName( + t: ts.Type, + ctx: Pick, + depth = 0, +): string { const symbol = t.getAliasSymbol() ?? t.getSymbol(); const declaration = symbol?.declarations[0]; const where = declaration - ? `${ts.getSourceFileOfNode(declaration).fileName}:${declaration.pos}` + ? (ctx.positionOf?.(declaration) ?? + `${ts.getSourceFileOfNode(declaration).fileName}:${declaration.pos}`) : ""; - return `${ctx.checker.typeToString(t)}@${where}`; + 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) => recursiveTypeName(arg, ctx, depth + 1)).join(",")}>`; + } + return description; } /** The frontend's union interner — mirrors ShapeRegistry. A union's @@ -585,13 +624,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, description: string): string { + * entry (empty arms) the outer frame finalizes. `describe` names a new + * placeholder (recursiveTypeName). */ + recursiveRef(t: ts.Type, describe: () => string): string { let id = this.recIds.get(t); if (id === undefined) { - id = keyedHelperName(this, "u", `recursive:${description}`, ""); - if (this.byId.has(id)) - throw new InternalCompilerError(`two recursive types share the description ${description}`); + id = recursivePlaceholderName(this, "u", describe(), (name) => this.byId.has(name)); const def: IrUnionDef = { id, arms: [] }; this.byId.set(id, def); this.unions.push(def); @@ -1135,6 +1173,10 @@ export interface TypeMapperCtx { * empty object type rule in the object mapping). */ emptyLiteralArm?: boolean; 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. */ @@ -4673,7 +4715,7 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { if (unions.inProgress.has(widened)) { return { kind: "union", - unionId: unions.recursiveRef(widened, recursiveTypeName(widened, ctx)), + unionId: unions.recursiveRef(widened, () => recursiveTypeName(widened, ctx)), }; } unions.inProgress.add(widened); @@ -7020,7 +7062,7 @@ function mapRecordType(widened: ts.Type, ctx: TypeMapperCtx): IrType | null { if (shapes.inProgress.has(widened)) { return { kind: "record", - shapeId: shapes.recursiveRef(widened, recursiveTypeName(widened, ctx)), + shapeId: shapes.recursiveRef(widened, () => recursiveTypeName(widened, ctx)), }; } shapes.inProgress.add(widened); diff --git a/packages/compiler/test/stable-names.test.ts b/packages/compiler/test/stable-names.test.ts new file mode 100644 index 000000000..720472556 --- /dev/null +++ b/packages/compiler/test/stable-names.test.ts @@ -0,0 +1,112 @@ +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); +}); From d68b73e3b4636308cb16fdecc21b4c5d03aa3e03 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 01:10:25 -0500 Subject: [PATCH 024/102] Extend a generic factory's local class returned through a constructor type A generic factory declared to return a constructor type (`Struct = (abstract new () => S) & { decode }`) whose every return gives back one of its own local classes (`return Base as Struct`) is now that local class's factory: each instance has its own class, the result maps to the class value while the instance lowers and at its calls, and `class X extends struct(...)` extends it like a factory returning the class directly. Before, the result type mapped to nothing (SC2008) and the extends clause refused as a computed expression. Static methods of a function-local class in a TypeScript file now lower as the class value's runtime statics, as they already do in JavaScript files: they read the enclosing function's bindings, call each other through `this`, and inherit into a subclass. Before, they refused with SC1090. Static fields and static blocks of such classes keep the fence. Fixes #1372 Co-authored-by: blurname <50226652+blurname@users.noreply.github.com> --- .../local-class-expressions.mdx | 3 +- .../frontend/lowering/generic-functions.ts | 123 ++++++++++++++++-- .../src/frontend/lowering/lower-classes.ts | 10 +- .../compiler/src/frontend/lowering/lowerer.ts | 10 ++ packages/compiler/src/frontend/type-mapper.ts | 11 ++ .../6912-extend-factory-local-class.ts.json | 6 + .../corpus/6912-extend-factory-local-class.ts | 67 ++++++++++ .../6912-extend-factory-local-class.ts.json | 1 + 8 files changed, 218 insertions(+), 13 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6912-extend-factory-local-class.ts.json create mode 100644 tests/corpus/6912-extend-factory-local-class.ts create mode 100644 tests/harness/corpus-costs/6912-extend-factory-local-class.ts.json 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..173bdc0c6 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,5 @@ -- **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, generic members, and references through the class's internal name are unsupported. + Static methods read the enclosing function's bindings and are inherited by subclasses. 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/packages/compiler/src/frontend/lowering/generic-functions.ts b/packages/compiler/src/frontend/lowering/generic-functions.ts index abcd5a584..0f549d889 100644 --- a/packages/compiler/src/frontend/lowering/generic-functions.ts +++ b/packages/compiler/src/frontend/lowering/generic-functions.ts @@ -129,6 +129,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`). */ @@ -468,7 +472,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 +488,29 @@ 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); + const classSymbol = resultClass.name + ? lowerer.checker.getSymbolAtLocation(resultClass.name) + : undefined; + return classSymbol ? lowerer.mapTypeOf(lowerer.checker.getTypeOfSymbol(classSymbol)) : 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 +585,94 @@ 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; + return declaration && + ts.isClassDeclaration(declaration) && + declaredInside(declaration, info.decl) + ? declaration + : 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 +687,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; diff --git a/packages/compiler/src/frontend/lowering/lower-classes.ts b/packages/compiler/src/frontend/lowering/lower-classes.ts index 790efe988..505b4d709 100644 --- a/packages/compiler/src/frontend/lowering/lower-classes.ts +++ b/packages/compiler/src/frontend/lowering/lower-classes.ts @@ -2404,7 +2404,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) @@ -5872,9 +5873,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), )) ) { diff --git a/packages/compiler/src/frontend/lowering/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index ee8ba7ecb..c1074f0a5 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -2171,6 +2171,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 @@ -3529,6 +3535,10 @@ export class Lowerer { genericClassInstance: (decl, ref, mapArgument) => this.genericClassInstanceType(decl, ref, mapArgument), runtimeClassValue: (type) => runtimeClassValueOfType(this, type), + localClassValue: (type) => + 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 } diff --git a/packages/compiler/src/frontend/type-mapper.ts b/packages/compiler/src/frontend/type-mapper.ts index a233f0186..25b8c45a9 100644 --- a/packages/compiler/src/frontend/type-mapper.ts +++ b/packages/compiler/src/frontend/type-mapper.ts @@ -1114,6 +1114,12 @@ 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; /** JavaScript declarations whose instance or object-literal types only * the checked-dynamic representation holds (js-dynamic-objects.ts). @@ -1653,6 +1659,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); 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/tests/corpus/6912-extend-factory-local-class.ts b/tests/corpus/6912-extend-factory-local-class.ts new file mode 100644 index 000000000..8848280e2 --- /dev/null +++ b/tests/corpus/6912-extend-factory-local-class.ts @@ -0,0 +1,67 @@ +// 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)); 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 } From 0763610e93a464943833a0ccb498bf193d2f6eb0 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 01:11:37 -0500 Subject: [PATCH 025/102] Version loops to a typed array's length on every typed array they index A loop such as `for (let i = 0; i < out.length; i++) out[i] = x[i] * y[i]` keeps its integer induction, and the version guard now also receives the loop's counted form, so it covers the accesses of `x` and `y` at the counter. Before, only counted loops (`i < n`) passed a counter to the guard, and loops to a length kept one bounds check per access of every other typed array, which kept LLVM from vectorizing them. Adds the typed-array-kernels runtime workload: element-wise loops over Float64Array, Float32Array, Uint8Array and Int32Array, and RGBA to gray. --- benchmarks/runtime/README.md | 1 + .../workloads/typed-array-kernels.json | 6 + .../runtime/workloads/typed-array-kernels.ts | 92 +++++++++++ .../backend/llvm/bytes-loop-versions.test.ts | 41 +++++ .../src/backend/llvm/emit-statements.ts | 21 ++- ...2-typed-array-length-loop-versions.ts.json | 6 + ...3-typed-array-length-loop-bindings.ts.json | 6 + .../6992-typed-array-length-loop-versions.ts | 141 +++++++++++++++++ .../6993-typed-array-length-loop-bindings.ts | 146 ++++++++++++++++++ ...2-typed-array-length-loop-versions.ts.json | 1 + ...3-typed-array-length-loop-bindings.ts.json | 1 + 11 files changed, 458 insertions(+), 4 deletions(-) create mode 100644 benchmarks/runtime/workloads/typed-array-kernels.json create mode 100644 benchmarks/runtime/workloads/typed-array-kernels.ts create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6992-typed-array-length-loop-versions.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6993-typed-array-length-loop-bindings.ts.json create mode 100644 tests/corpus/6992-typed-array-length-loop-versions.ts create mode 100644 tests/corpus/6993-typed-array-length-loop-bindings.ts create mode 100644 tests/harness/corpus-costs/6992-typed-array-length-loop-versions.ts.json create mode 100644 tests/harness/corpus-costs/6993-typed-array-length-loop-bindings.ts.json diff --git a/benchmarks/runtime/README.md b/benchmarks/runtime/README.md index d736a4ed4..1acdc9ce7 100644 --- a/benchmarks/runtime/README.md +++ b/benchmarks/runtime/README.md @@ -26,6 +26,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, RGBA to gray | | `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/typed-array-kernels.json b/benchmarks/runtime/workloads/typed-array-kernels.json new file mode 100644 index 000000000..fff290679 --- /dev/null +++ b/benchmarks/runtime/workloads/typed-array-kernels.json @@ -0,0 +1,6 @@ +{ + "entry": "workloads/typed-array-kernels.ts", + "args": [ + "1" + ] +} diff --git a/benchmarks/runtime/workloads/typed-array-kernels.ts b/benchmarks/runtime/workloads/typed-array-kernels.ts new file mode 100644 index 000000000..87c227bbc --- /dev/null +++ b/benchmarks/runtime/workloads/typed-array-kernels.ts @@ -0,0 +1,92 @@ +// 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. + +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]!; +} + +function blend(t: number, a: Float32Array, b: Float32Array, out: Float32Array): void { + for (let i = 0; i < out.length; i++) out[i] = a[i]! * (1 - t) + b[i]! * t; +} + +function mask(data: Uint8Array, key: Uint8Array, out: Uint8Array): void { + for (let i = 0; i < out.length; i++) out[i] = data[i]! ^ key[i]!; +} + +function addWrap(a: Int32Array, b: Int32Array, out: Int32Array): void { + for (let i = 0; i < out.length; i++) out[i] = (a[i]! + b[i]!) | 0; +} + +function gray(rgba: Uint8Array, out: Uint8Array): void { + for (let i = 0; i < out.length; i++) { + const j = i * 4; + out[i] = (rgba[j]! * 77 + rgba[j + 1]! * 150 + rgba[j + 2]! * 29) >> 8; + } +} + +const scale = Number(process.argv[2] ?? "1"); +const n = 1 << 16; +const x = new Float64Array(n); +const y = new Float64Array(n); +const d = new Float64Array(n); +const fa = new Float32Array(n); +const fb = new Float32Array(n); +const fo = new Float32Array(n); +const data = new Uint8Array(n); +const key = new Uint8Array(n); +const masked = new Uint8Array(n); +const ia = new Int32Array(n); +const ib = new Int32Array(n); +const io = new Int32Array(n); +const rgba = new Uint8Array(n * 4); +const luma = new Uint8Array(n); +let state = 2463534242; +const next = (): number => { + state ^= state << 13; + state ^= state >>> 17; + state ^= state << 5; + return state >>> 0; +}; +for (let i = 0; i < n; i++) { + x[i] = (next() % 20000) / 100 - 100; + y[i] = (next() % 20000) / 100; + fa[i] = (next() % 1000) / 7; + fb[i] = (next() % 1000) / 9; + data[i] = next() & 255; + key[i] = next() & 255; + ia[i] = next() | 0; + ib[i] = next() | 0; +} +for (let i = 0; i < rgba.length; i++) rgba[i] = next() & 255; + +const rounds = Math.round(1200 * scale); +let f64Sum = 0; +let f32Sum = 0; +let byteSum = 0; +let intSum = 0; +let lumaSum = 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); + x[at] = r; + fa[at] = r; + data[at] = r & 255; + ia[at] = r * 65537; + rgba[at * 4] = r & 255; + axpy(1.5, x, y, d); + blend((r & 15) / 16, fa, fb, fo); + mask(data, key, masked); + addWrap(ia, ib, io); + gray(rgba, luma); + const probe = (r * 104729) & (n - 1); + f64Sum += d[probe]!; + f32Sum += fo[probe]!; + byteSum += masked[probe]!; + intSum = (intSum + io[probe]!) | 0; + lumaSum += luma[probe]!; +} +console.log(`float64 ${f64Sum.toFixed(3)}`); +console.log(`float32 ${f32Sum.toFixed(3)}`); +console.log(`uint8 ${byteSum}`); +console.log(`int32 ${intSum}`); +console.log(`gray ${lumaSum}`); 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 ddcfd667d..ea568bc3f 100644 --- a/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts +++ b/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts @@ -209,6 +209,47 @@ test("emitted loops version the body and tag typed-array memory", () => { expect(elements).not.toBe(header); }); +test("loops to a typed array's length version the other typed arrays they index", () => { + const length = (receiver: IrExpr): IrExpr => ({ + kind: "bytesIntrinsic", + method: "length", + receiver, + args: [], + type: F64, + loc, + }); + const emit = (body: IrStmt[]): string => { + const mod: IrModule = { + irVersion: 17, + sourceFile: loc.file, + entry: "__main", + functions: [ + { name: "__main", params: [], returnType: VOID, locals: [], body: [], loc }, + fn(body), + ], + }; + return /^define internal [^\n]*@sc_bf_kernel[^]*?^}/m.exec(emitLlvmModule(mod))![0]; + }; + // for (let i = 0; i < out.length; i++) out[i] = src[i] * 2 + const scaled = set(ref("out", f64s), ref("i"), bin("*", get(ref("src", f64s), ref("i")), num(2))); + const body = emit([counted([scaled], length(ref("out", f64s)))]); + const fast = /^bytes\.version\.fast\d+:$[^]*?^bytes\.version\.done\d+:$/m.exec(body)![0]; + // The loop keeps its integer induction, and the fast copy reads `src` + // unchecked. + expect(body).toContain("integer induction i"); + expect(fast).not.toContain("bytes.index"); + expect(body.slice(0, body.indexOf(fast))).toContain("bytes.index.invalid"); + // A body that rebinds `src` keeps one checked loop. + const rebound = emit([ + counted( + [scaled, { kind: "assign", localId: "src", value: ref("out", f64s), loc }], + length(ref("out", f64s)), + ), + ]); + expect(rebound).not.toContain("bytes.version.fast"); + expect(rebound).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 => { diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index d1dc6369b..433029651 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -945,12 +945,25 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { B.startBlock(done); break; } - const version = + const versionable = emitter.bytesLoopVersionsEnabled && emitter.bytesLoopVersioning.size < MAX_BYTES_LOOP_VERSION_DEPTH && - !emitter.bytesLoopVersioning.has(s) - ? emitter.matchBytesLoopVersion(s, countedLoop) - : null; + !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 + ? matchIntegerCountedForLoop( + s, + emitter.numericLocals, + emitter.integerRanges, + 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"), diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6992-typed-array-length-loop-versions.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6992-typed-array-length-loop-versions.ts.json new file mode 100644 index 000000000..2d7025954 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6992-typed-array-length-loop-versions.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6992-typed-array-length-loop-versions.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6993-typed-array-length-loop-bindings.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6993-typed-array-length-loop-bindings.ts.json new file mode 100644 index 000000000..43b9c5f09 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6993-typed-array-length-loop-bindings.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6993-typed-array-length-loop-bindings.ts" + ], + "diags": [] +} diff --git a/tests/corpus/6992-typed-array-length-loop-versions.ts b/tests/corpus/6992-typed-array-length-loop-versions.ts new file mode 100644 index 000000000..eb08f7145 --- /dev/null +++ b/tests/corpus/6992-typed-array-length-loop-versions.ts @@ -0,0 +1,141 @@ +// Loops bounded by one typed array's length that index other typed arrays: +// equal and different lengths, offsets, mixed element types and views that +// share a buffer. Out-of-bounds reads give undefined (NaN in arithmetic) and +// out-of-bounds writes are ignored, whichever array is shorter. + +function mulInto(x: Float32Array, y: Float32Array, out: Float32Array): void { + for (let i = 0; i < out.length; i++) out[i] = x[i]! * y[i]!; +} + +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]!; +} + +function xorInto(a: Uint8Array, b: Uint8Array, out: Uint8Array): void { + for (let i = 0; i < out.length; i++) out[i] = a[i]! ^ b[i]!; +} + +function addWrap(a: Int32Array, b: Int32Array, out: Int32Array): void { + for (let i = 0; i < out.length; i++) out[i] = (a[i]! + b[i]!) | 0; +} + +function narrow(src: Float64Array, i8: Int8Array, u16: Uint16Array, u32: Uint32Array): void { + for (let i = 0; i < src.length; i++) { + i8[i] = src[i]!; + u16[i] = src[i]!; + u32[i] = src[i]!; + } +} + +function neighbors(a: Int32Array, out: Int32Array): void { + for (let i = 0; i < a.length; i++) out[i] = a[i + 1]! - a[i]!; +} + +function previous(a: Float64Array, out: Float64Array): void { + for (let i = 0; i < out.length; i++) out[i] = a[i - 1]!; +} + +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 sumPairs(a: Float64Array, b: Float64Array): number { + let s = 0; + for (let i = 0; i < a.length; i++) s += a[i]! * b[i]!; + return s; +} + +function shiftUp(view: Uint8Array, from: Uint8Array): void { + for (let i = 0; i < view.length; i++) view[i] = from[i]! + 1; +} + +const n = 37; +const fx = new Float32Array(n); +const fy = new Float32Array(n); +const dx = new Float64Array(n); +const dy = new Float64Array(n); +const ba = new Uint8Array(n); +const bb = new Uint8Array(n); +const ia = new Int32Array(n); +const ib = new Int32Array(n); +for (let i = 0; i < n; i++) { + fx[i] = i / 3; + fy[i] = 0.1 * i - 1.7; + dx[i] = i * 1.25 - 9; + dy[i] = (i * 7) % 11; + ba[i] = (i * 29) & 255; + bb[i] = (i * 113 + 7) & 255; + ia[i] = i * 0x3fffffff; + ib[i] = i * -0x2ffffff1; +} + +const fo = new Float32Array(n); +mulInto(fx, fy, fo); +console.log("f32", fo.join(",")); +const shortF = new Float32Array(5); +mulInto(fx, fy.subarray(0, 3), shortF); +console.log("f32 short input", shortF.join(",")); +const longF = new Float32Array(n + 4); +mulInto(fx, fy, longF); +console.log("f32 long output", longF.subarray(n - 2).join(",")); + +const dout = new Float64Array(n); +axpy(-2.5, dx, dy, dout); +console.log("axpy", dout.join(",")); +axpy(0.5, dx.subarray(10), dy, dout); +console.log("axpy short x", dout.subarray(20).join(",")); + +const bo = new Uint8Array(n); +xorInto(ba, bb, bo); +console.log("xor", bo.join(",")); +const io = new Int32Array(n); +addWrap(ia, ib, io); +console.log("i32", io.join(",")); + +const src = new Float64Array([0, -1, 1.5, -128.5, 255.7, 256, 65535.9, -65537, 4294967296.5, NaN, Infinity, -0]); +const i8 = new Int8Array(src.length); +const u16 = new Uint16Array(src.length - 2); +const u32 = new Uint32Array(src.length + 1); +narrow(src, i8, u16, u32); +console.log("narrow", i8.join(","), "|", u16.join(","), "|", u32.join(",")); + +const diff = new Int32Array(n); +neighbors(ia, diff); +console.log("neighbors", diff.subarray(n - 3).join(",")); +const before = new Float64Array(4); +previous(dx, before); +console.log("previous", before.join(",")); + +const px = new Uint8Array(n * 4); +for (let i = 0; i < px.length; i++) px[i] = (i * 53) & 255; +const g = new Uint8Array(n); +gray(px, g); +console.log("gray", g.join(",")); +const wide = new Uint8Array(n + 3); +gray(px, wide); +console.log("gray past input", wide.subarray(n - 1).join(",")); + +console.log("dot", sumPairs(dx, dy), sumPairs(dx, dy.subarray(0, 30))); + +// Views of one buffer: writes through one are visible to reads through the +// other on later iterations. +const buffer = new Uint8Array(24); +for (let i = 0; i < buffer.length; i++) buffer[i] = (i * 37) & 255; +shiftUp(buffer.subarray(1), buffer); +console.log("overlap forward", buffer.join(",")); +for (let i = 0; i < buffer.length; i++) buffer[i] = (i * 37) & 255; +shiftUp(buffer, buffer.subarray(1)); +console.log("overlap backward", buffer.join(",")); +const shared = new ArrayBuffer(64); +const asFloat = new Float32Array(shared); +const asBytes = new Uint8Array(shared, 4, 16); +for (let i = 0; i < asFloat.length; i++) asFloat[i] = i + 0.5; +const fromBytes = new Float32Array(16); +for (let i = 0; i < fromBytes.length; i++) { + asBytes[i] = i * 3; + fromBytes[i] = asFloat[i]!; +} +console.log("mixed views", fromBytes.join(","), asBytes.join(",")); diff --git a/tests/corpus/6993-typed-array-length-loop-bindings.ts b/tests/corpus/6993-typed-array-length-loop-bindings.ts new file mode 100644 index 000000000..e4b242b28 --- /dev/null +++ b/tests/corpus/6993-typed-array-length-loop-bindings.ts @@ -0,0 +1,146 @@ +// Loops bounded by a typed array's length whose bindings change while they +// run, that leave early, or that run at module level, in generators and in +// async functions. Each keeps the reads, writes and bounds the source names +// on every iteration. + +function swapBound(a: Float64Array, b: Float64Array, out: Float64Array): number { + let n = 0; + for (let i = 0; i < a.length; i++) { + out[i] = a[i]! + b[i]!; + n++; + if (i === 2) a = b; + } + return n; +} + +function swapOperand(a: Int16Array, b: Int16Array, out: Int16Array): void { + for (let i = 0; i < out.length; i++) { + out[i] = a[i]! * 3; + if (i === 3) a = b; + } +} + +function closureSwap(a: Uint16Array, b: Uint16Array, out: Uint16Array): void { + const swap = (): void => { + out = b; + }; + for (let i = 0; i < out.length; i++) { + out[i] = a[i]! + 1000; + if (i === 1) swap(); + } +} + +function firstAbove(values: Float32Array, limits: Float32Array): number { + for (let i = 0; i < values.length; i++) { + if (values[i]! > limits[i]!) return i; + } + return -1; +} + +function copyUntilZero(src: Uint8Array, out: Uint8Array): number { + let copied = 0; + for (let i = 0; i < src.length; i++) { + if (src[i] === 0) break; + out[i] = src[i]!; + copied++; + } + return copied; +} + +function checkedScale(src: Int32Array, out: Int32Array): void { + for (let i = 0; i < src.length; i++) { + if (src[i]! < 0) throw new RangeError(`negative at ${i}: ${src[i]}`); + out[i] = src[i]! * 2; + } +} + +function fromList(values: number[], out: Float64Array): void { + for (let i = 0; i < values.length; i++) { + out[i] = values[i]! / 2; + if (values.length < 6) values.push(i * 10); + } +} + +function rows(table: Uint32Array[], totals: Uint32Array): void { + for (let r = 0; r < table.length; r++) { + const row = table[r]!; + let sum = 0; + for (let c = 0; c < row.length; c++) sum += row[c]! * (c + 1); + totals[r] = sum; + } +} + +function* pairs(a: Int8Array, b: Int8Array): Generator { + for (let i = 0; i < a.length; i++) yield a[i]! * b[i]!; +} + +async function addLater(a: Float64Array, b: Float64Array, out: Float64Array): Promise { + for (let i = 0; i < out.length; i++) { + out[i] = a[i]! + b[i]!; + if (i % 2 === 0) await null; + } +} + +const a = new Float64Array([1, 2, 3, 4, 5, 6]); +const b = new Float64Array([10, 20, 30]); +const sum = new Float64Array(8); +console.log("swap bound", swapBound(a, b, sum), sum.join(",")); + +const s16 = new Int16Array([1, -2, 3, -4, 5, -6, 7]); +const t16 = new Int16Array([100, 200, 300, 400, 500, 600]); +const o16 = new Int16Array(7); +swapOperand(s16, t16, o16); +console.log("swap operand", o16.join(",")); + +const u = new Uint16Array([5, 6, 7, 8]); +const other = new Uint16Array(2); +const first = new Uint16Array(4); +closureSwap(u, other, first); +console.log("closure swap", first.join(","), other.join(",")); + +const values = new Float32Array([0.5, 1.5, 2.5, 3.5]); +console.log("first above", firstAbove(values, new Float32Array([1, 1, 1, 1]))); +console.log("first above short", firstAbove(values, new Float32Array([9]))); +console.log("first above none", firstAbove(values, new Float32Array([9, 9, 9, 9]))); + +const text = new Uint8Array([72, 105, 33, 0, 88]); +const copy = new Uint8Array(2); +console.log("copy", copyUntilZero(text, copy), copy.join(",")); + +const ints = new Int32Array([4, 8, -15, 16]); +const doubled = new Int32Array(4); +try { + checkedScale(ints, doubled); +} catch (error) { + console.log((error as Error).name, (error as Error).message, doubled.join(",")); +} + +const list = [3, 5]; +const halves = new Float64Array(5); +fromList(list, halves); +console.log("from list", list.join(","), halves.join(",")); + +const table = [new Uint32Array([1, 2, 3]), new Uint32Array([]), new Uint32Array([4294967295, 1])]; +const totals = new Uint32Array(4); +rows(table, totals); +console.log("rows", totals.join(",")); + +console.log("pairs", [...pairs(new Int8Array([1, -2, 3, 127]), new Int8Array([4, 5, -6]))].join(",")); + +const left = new Float64Array([0.25, 0.5, 0.75, 1]); +const right = new Float64Array([1, 2, 3, 4, 5]); +const later = new Float64Array(5); +const pending = addLater(left, right, later); +console.log("before await", later.join(",")); + +// Module-level bindings, including one a loop body reassigns. +let source = new Uint8Array([9, 8, 7, 6, 5]); +const replacement = new Uint8Array([1, 2]); +const target = new Uint8Array(5); +for (let i = 0; i < source.length; i++) { + target[i] = source[i]! + 100; + if (i === 1) source = replacement; +} +console.log("module", target.join(","), source.join(",")); + +pending.then(() => console.log("after await", later.join(","))); diff --git a/tests/harness/corpus-costs/6992-typed-array-length-loop-versions.ts.json b/tests/harness/corpus-costs/6992-typed-array-length-loop-versions.ts.json new file mode 100644 index 000000000..26208456e --- /dev/null +++ b/tests/harness/corpus-costs/6992-typed-array-length-loop-versions.ts.json @@ -0,0 +1 @@ +{ "plain": 3800, "san": 5600 } diff --git a/tests/harness/corpus-costs/6993-typed-array-length-loop-bindings.ts.json b/tests/harness/corpus-costs/6993-typed-array-length-loop-bindings.ts.json new file mode 100644 index 000000000..a6e281d1e --- /dev/null +++ b/tests/harness/corpus-costs/6993-typed-array-length-loop-bindings.ts.json @@ -0,0 +1 @@ +{ "plain": 2700, "san": 4000 } From c081d5a3a771da3b09b3c6d6ec4d90f3e311bb3e Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 01:16:55 -0500 Subject: [PATCH 026/102] Apply the byte offset in Buffer.from over untyped ArrayBuffers Buffer.from(arrayBuffer, byteOffset) with an untyped ArrayBuffer or SharedArrayBuffer now returns a Buffer from that offset to the end, as Node's fromArrayBuffer does, where the offset was dropped and the Buffer covered the whole buffer. --- .../compiler/src/backend/llvm/lib-shared.ts | 1 + .../src/frontend/lowering/containers/bytes.ts | 11 +++-- packages/compiler/src/ir/builtin-effects.ts | 1 + .../compiler/src/ir/builtin-signatures.ts | 1 + packages/runtime/src/scr_bytes.h | 1 + packages/runtime/src/scr_bytes_io.c | 43 +++++++++++++++++-- .../6868-buffer-from-untyped-array-buffer.cjs | 22 +++++++++- 7 files changed, 71 insertions(+), 9 deletions(-) diff --git a/packages/compiler/src/backend/llvm/lib-shared.ts b/packages/compiler/src/backend/llvm/lib-shared.ts index 683211762..cf2255f89 100644 --- a/packages/compiler/src/backend/llvm/lib-shared.ts +++ b/packages/compiler/src/backend/llvm/lib-shared.ts @@ -448,6 +448,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", diff --git a/packages/compiler/src/frontend/lowering/containers/bytes.ts b/packages/compiler/src/frontend/lowering/containers/bytes.ts index bf9821d31..afd108eb4 100644 --- a/packages/compiler/src/frontend/lowering/containers/bytes.ts +++ b/packages/compiler/src/frontend/lowering/containers/bytes.ts @@ -1743,8 +1743,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 +1787,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/ir/builtin-effects.ts b/packages/compiler/src/ir/builtin-effects.ts index 482739db5..ae6b663ca 100644 --- a/packages/compiler/src/ir/builtin-effects.ts +++ b/packages/compiler/src/ir/builtin-effects.ts @@ -789,6 +789,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", diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index 49683550e..c92cd40d4 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -2921,6 +2921,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 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 ac8fad02e..bd79d9089 100644 --- a/packages/runtime/src/scr_bytes_io.c +++ b/packages/runtime/src/scr_bytes_io.c @@ -1300,9 +1300,10 @@ ScrBytes *scr_buffer_concat_len_dyn(const ScrDyn *list, double total) { } /* Buffer.from(arrayBuffer) over a checked value: a Buffer over all of the - * ArrayBuffer or SharedArrayBuffer that shares its memory, as in Node. A - * second argument would be the byte offset, and an encoding name converts - * to NaN, which is offset 0. */ + * ArrayBuffer or SharedArrayBuffer that shares its memory, as in Node. The + * calls that reach it have no second argument or a literal encoding name, + * which as a byte offset converts to NaN, offset 0; other second arguments + * take scr_buffer_from_dyn_offset_pooled, which applies the offset. */ static ScrBytes *scr_buffer_from_storage(const ScrDyn *storage) { ScrBytes *out = scr_bytes_buffer_view(storage->v.handle.ptr, SCR_BYTES_U8, 0, false, 0); if (out) out->is_buffer = true; @@ -1381,6 +1382,42 @@ 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, as Node's fromArrayBuffer does (undefined and NaN are + * 0, the rest of the buffer is the length, ERR_BUFFER_OUT_OF_BOUNDS past the + * end); 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; + } + double offset = 0; + if (second->kind != SCR_DYN_UNDEF) { + if (!scr_dyn_number_coerce_js(second, &offset)) return NULL; + if (isnan(offset)) offset = 0; + } + ScrBytes *storage = value->v.handle.ptr; + ScrBytes *owner = storage->backing ? storage->backing : storage; + 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) { + char msg[96]; + int n = snprintf(msg, sizeof msg, "Start offset %.0f is outside the bounds of the buffer", start); + scr_throw_error_msg(SCR_ERR_RANGE, msg, (size_t)n); + return NULL; + } + ScrBytes *out = scr_bytes_buffer_view(storage, SCR_BYTES_U8, start, false, 0); + if (out) out->is_buffer = true; + return out; +} + /* 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/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs b/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs index f525f24cf..e30b5873e 100644 --- a/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs +++ b/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs @@ -1,7 +1,8 @@ // Buffer.from over an untyped ArrayBuffer or SharedArrayBuffer (read from a // Map, an untyped object field or a worker message): the Buffer covers the -// whole buffer and shares its memory, in both directions, as in Node. An -// encoding name in the second argument converts to byte offset 0. +// 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'); @@ -19,6 +20,23 @@ if (isMainThread) { 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]) { + 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); From 777bfb43f2e126e5d5fa0f8046eca3944d87548d Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 01:40:17 -0500 Subject: [PATCH 027/102] Revert "Name lowered helpers and closures independently of lowering order" This reverts #1750 (05e2f404d), which made main CI fail. --- package.json | 2 +- packages/compiler/src/contracts/check.ts | 3 +- .../lowering/array-indexed-mutation.ts | 3 +- .../src/frontend/lowering/array-values.ts | 5 +- .../frontend/lowering/builtins/arguments.ts | 3 +- .../lowering/builtins/child-process-async.ts | 3 +- .../lowering/builtins/child-process-sync.ts | 3 +- .../lowering/builtins/disposable-stack.ts | 3 +- .../frontend/lowering/builtins/filesystem.ts | 3 +- .../src/frontend/lowering/builtins/json.ts | 3 +- .../lowering/builtins/operating-system.ts | 7 +- .../frontend/lowering/builtins/performance.ts | 5 +- .../src/frontend/lowering/builtins/process.ts | 5 +- .../frontend/lowering/builtins/promises.ts | 5 +- .../lowering/builtins/promisify-callback.ts | 3 +- .../frontend/lowering/builtins/text-codecs.ts | 3 +- .../src/frontend/lowering/builtins/timers.ts | 2 +- .../src/frontend/lowering/builtins/url.ts | 7 +- .../src/frontend/lowering/builtins/v8.ts | 3 +- .../src/frontend/lowering/call-arguments.ts | 3 +- .../src/frontend/lowering/call-signatures.ts | 7 +- .../src/frontend/lowering/class-assertions.ts | 5 +- .../src/frontend/lowering/class-unions.ts | 3 +- .../lowering/coercions/function-adapters.ts | 11 +- .../frontend/lowering/coercions/structural.ts | 15 ++- .../src/frontend/lowering/coercions/unions.ts | 15 ++- .../frontend/lowering/collection-ingestion.ts | 3 +- .../lowering/containers/array-callbacks.ts | 25 ++-- .../lowering/containers/array-concat.ts | 3 +- .../lowering/containers/array-construction.ts | 7 +- .../lowering/containers/array-methods.ts | 11 +- .../lowering/containers/array-pipelines.ts | 3 +- .../src/frontend/lowering/containers/bytes.ts | 5 +- .../lowering/containers/callback-arguments.ts | 3 +- .../containers/collection-grouping.ts | 5 +- .../lowering/containers/collection-methods.ts | 15 ++- .../lowering/containers/indexed-objects.ts | 15 ++- .../lowering/containers/iterator-helpers.ts | 7 +- .../lowering/containers/string-and-regexp.ts | 11 +- .../lowering/containers/string-replacement.ts | 3 +- .../frontend/lowering/expressions/binary.ts | 3 +- .../lowering/expressions/object-literals.ts | 7 +- .../lowering/expressions/optional-chains.ts | 10 +- .../lowering/expressions/property-access.ts | 3 +- .../lowering/expressions/relational.ts | 5 +- .../frontend/lowering/generic-functions.ts | 17 +-- .../src/frontend/lowering/intern-tables.ts | 7 +- .../frontend/lowering/iterator-adapters.ts | 17 ++- .../frontend/lowering/js-dynamic-objects.ts | 5 +- .../src/frontend/lowering/json-require.ts | 3 +- .../src/frontend/lowering/lifetime-regions.ts | 3 +- .../src/frontend/lowering/lower-assert.ts | 11 +- .../src/frontend/lowering/lower-calls.ts | 49 ++++---- .../src/frontend/lowering/lower-classes.ts | 9 +- .../src/frontend/lowering/lower-dgram.ts | 5 +- .../frontend/lowering/lower-event-emitter.ts | 13 +- .../src/frontend/lowering/lower-exprs.ts | 9 +- .../src/frontend/lowering/lower-functions.ts | 2 +- .../src/frontend/lowering/lower-inspect.ts | 7 +- .../src/frontend/lowering/lower-mixins.ts | 3 +- .../src/frontend/lowering/lower-mock.ts | 3 +- .../frontend/lowering/lower-modules.test.ts | 4 +- .../src/frontend/lowering/lower-modules.ts | 15 +-- .../src/frontend/lowering/lower-namespaces.ts | 11 +- .../src/frontend/lowering/lower-server.ts | 13 +- .../src/frontend/lowering/lower-stdlib.ts | 2 +- .../src/frontend/lowering/lower-stream.ts | 15 ++- .../src/frontend/lowering/lower-timers.ts | 7 +- .../src/frontend/lowering/lowerer.test.ts | 30 ++--- .../compiler/src/frontend/lowering/lowerer.ts | 101 +++------------- .../src/frontend/lowering/native-ffi.ts | 2 +- .../lowering/object-enumeration-receiver.ts | 3 +- .../src/frontend/lowering/pairs-snapshot.ts | 3 +- .../lowering/promise-executor-adapter.ts | 3 +- .../lowering/require-initialization.ts | 3 +- .../src/frontend/lowering/stable-names.ts | 48 -------- .../src/frontend/lowering/strict-equality.ts | 3 +- .../frontend/lowering/structural-positions.ts | 107 ----------------- packages/compiler/src/frontend/ts7/ast.ts | 90 +------------- .../compiler/src/frontend/type-mapper.test.ts | 2 +- packages/compiler/src/frontend/type-mapper.ts | 92 ++------------ .../test/array-pipeline-fusion.test.ts | 2 +- .../test/format-float-arguments.test.ts | 2 +- .../test/in-runtime-key-emission.test.ts | 2 +- packages/compiler/test/stable-names.test.ts | 112 ------------------ .../compiler/test/type-mapper-unions.test.ts | 3 +- 86 files changed, 258 insertions(+), 854 deletions(-) delete mode 100644 packages/compiler/src/frontend/lowering/stable-names.ts delete mode 100644 packages/compiler/src/frontend/lowering/structural-positions.ts delete mode 100644 packages/compiler/test/stable-names.test.ts diff --git a/package.json b/package.json index d1a8e34ae..5cc30d9f8 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 names", + "test:lowering-order": "node scripts/lowering-order.mjs --fail-on content", "test:sandbox": "node scripts/sandbox-test.mjs", "test:sandbox:image": "node scripts/sandbox-image.mjs", "test:watch": "vitest", diff --git a/packages/compiler/src/contracts/check.ts b/packages/compiler/src/contracts/check.ts index c80468961..5934624bf 100644 --- a/packages/compiler/src/contracts/check.ts +++ b/packages/compiler/src/contracts/check.ts @@ -174,8 +174,7 @@ class ContractChecker { return `${owner}.${method[2]}`; } if (fn?.sourceName !== undefined && fn.sourceName !== "") return fn.sourceName; - if (fn !== undefined && /^%fn\.[0-9a-f]{12}$/.test(fnName)) - return `the function at ${this.where(fn.loc)}`; + if (fn !== undefined && /^%fn\d+$/.test(fnName)) return `the function at ${this.where(fn.loc)}`; return fnName.replace(/^%/, ""); } diff --git a/packages/compiler/src/frontend/lowering/array-indexed-mutation.ts b/packages/compiler/src/frontend/lowering/array-indexed-mutation.ts index 0ded460da..6d539212e 100644 --- a/packages/compiler/src/frontend/lowering/array-indexed-mutation.ts +++ b/packages/compiler/src/frontend/lowering/array-indexed-mutation.ts @@ -9,7 +9,6 @@ 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"; @@ -126,7 +125,7 @@ export function lowerArrayFill( writeNull; let name = lowerer.arrHofHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%arr.fill", key); + name = "%arr.fill." + lowerer.arrHofHelpers.size; 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 314cdfd24..0ca8503df 100644 --- a/packages/compiler/src/frontend/lowering/array-values.ts +++ b/packages/compiler/src/frontend/lowering/array-values.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { InternalCompilerError } from "../../errors.js"; import { dynUndefinedExpr, helperLoc, varRef } from "../../ir/build.js"; import { @@ -253,7 +252,7 @@ export function lowerSafeIndexRead( let name = lowerer.arrHofHelpers.get(key); if (!name) { const at = helperLoc(loc); - name = keyedHelperName(lowerer, "%arr.idxOr", key); + name = `%arr.idxOr.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); const arrT = arr.type; lowerer.liftedFns.push({ @@ -299,7 +298,7 @@ export function lowerSafeBytesRead( let name = lowerer.arrHofHelpers.get(key); if (!name) { const at = helperLoc(loc); - name = keyedHelperName(lowerer, "%bytes.idxOr", key); + name = `%bytes.idxOr.${lowerer.arrHofHelpers.size}`; 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/builtins/arguments.ts b/packages/compiler/src/frontend/lowering/builtins/arguments.ts index d2fc430dd..7f862f603 100644 --- a/packages/compiler/src/frontend/lowering/builtins/arguments.ts +++ b/packages/compiler/src/frontend/lowering/builtins/arguments.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "../stable-names.js"; import { BYTES_U8, BOOL, @@ -73,7 +72,7 @@ export function lowerOptionalNumberPredicate( const key = `number.optionalPredicate:${fn}:${typeKey(widened)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%number.optionalPredicate", key); + helper = `%number.optionalPredicate.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const input = varRef("value.0", widened, loc); lowerer.liftedFns.push({ 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 d0991dce5..5590fbe9f 100644 --- a/packages/compiler/src/frontend/lowering/builtins/child-process-async.ts +++ b/packages/compiler/src/frontend/lowering/builtins/child-process-async.ts @@ -1,4 +1,3 @@ -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"; @@ -219,7 +218,7 @@ function execFileAsyncHelper( const key = shell ? "execAsync" : "execFileAsync"; const existing = lowerer.valueHelpers.get(key); if (existing) return { name: existing, shapeId, envShapeId }; - const name = keyedHelperName(lowerer, `%${key}`, key); + const name = `%${key}.${lowerer.valueHelpers.size}`; 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-sync.ts b/packages/compiler/src/frontend/lowering/builtins/child-process-sync.ts index b9858e768..24adcc1ba 100644 --- a/packages/compiler/src/frontend/lowering/builtins/child-process-sync.ts +++ b/packages/compiler/src/frontend/lowering/builtins/child-process-sync.ts @@ -1,4 +1,3 @@ -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"; @@ -542,7 +541,7 @@ function execStdioModeHelper( const key = `cp.stdiomode:${shapeId}:${fd}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, `%cp.stdioMode.${fd}`, key); + const name = `%cp.stdioMode.${fd}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); const optsT: IrType = { kind: "record", shapeId }; diff --git a/packages/compiler/src/frontend/lowering/builtins/disposable-stack.ts b/packages/compiler/src/frontend/lowering/builtins/disposable-stack.ts index 375c3f1e7..1b9a9c03a 100644 --- a/packages/compiler/src/frontend/lowering/builtins/disposable-stack.ts +++ b/packages/compiler/src/frontend/lowering/builtins/disposable-stack.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { type Lowerer } from "../lowerer.js"; import { locOf } from "../../program.js"; @@ -85,7 +84,7 @@ export function lowerDisposableStackUseCall( const key = `disposableStack.use:${className}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%disposableStack.use", key); + helper = `%disposableStack.use.${lowerer.valueHelpers.size}`; 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/filesystem.ts b/packages/compiler/src/frontend/lowering/builtins/filesystem.ts index 6b988c491..0e1c062c5 100644 --- a/packages/compiler/src/frontend/lowering/builtins/filesystem.ts +++ b/packages/compiler/src/frontend/lowering/builtins/filesystem.ts @@ -1,4 +1,3 @@ -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"; @@ -443,7 +442,7 @@ export function lowerStringOrBytesWrite( const key = `fs.${append ? "append" : "write"}:${dataType.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%fs.writeData", key); + helper = `%fs.writeData.${lowerer.valueHelpers.size}`; 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/json.ts b/packages/compiler/src/frontend/lowering/builtins/json.ts index 64f829865..7eb8aa9b2 100644 --- a/packages/compiler/src/frontend/lowering/builtins/json.ts +++ b/packages/compiler/src/frontend/lowering/builtins/json.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "../stable-names.js"; import { isDateJsonSource } from "./dates.js"; import { dynUndefinedExpr, varRef } from "../../../ir/build.js"; import { InternalCompilerError } from "../../../errors.js"; @@ -254,7 +253,7 @@ function lowerOptionalStringifyRoot( const key = `json.optionalString:${value.type.unionId}:${JSON.stringify(indent)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%json.optionalString", key); + helper = `%json.optionalString.${lowerer.valueHelpers.size}`; 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/operating-system.ts b/packages/compiler/src/frontend/lowering/builtins/operating-system.ts index ee189a1f3..c10465039 100644 --- a/packages/compiler/src/frontend/lowering/builtins/operating-system.ts +++ b/packages/compiler/src/frontend/lowering/builtins/operating-system.ts @@ -1,4 +1,3 @@ -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"; @@ -220,7 +219,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 = keyedHelperName(lowerer, "%os.cpus", key); + helper = `%os.cpus.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const index = varRef("i.0", F64, loc); const field = (k: number): IrExpr => ({ @@ -347,7 +346,7 @@ export function lowerPathParseCall( const key = `${fn}:${typeKey(result)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%path.parse", key); + helper = `%path.parse.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const parts = varRef("parts.0", arrayOf(STRING), loc); lowerer.liftedFns.push({ @@ -449,7 +448,7 @@ export function lowerPathFormatCall( const key = `${fn}:${typeKey(recordT)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%path.format", key); + helper = `%path.format.${lowerer.valueHelpers.size}`; 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 bae525c17..72304e6a9 100644 --- a/packages/compiler/src/frontend/lowering/builtins/performance.ts +++ b/packages/compiler/src/frontend/lowering/builtins/performance.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { type Lowerer } from "../lowerer.js"; import { locOf } from "../../program.js"; @@ -331,7 +330,7 @@ function lowerPerfTimelineCall( const key = `perf.${many ? "entries" : timeline.fn}:${typeKey(result)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, `%perf.${many ? "entries" : member}`, key); + helper = `%perf.${many ? "entries" : member}.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const argsRef = varRef("a.0", DYN, loc); const whichRef = varRef("w.0", F64, loc); @@ -462,7 +461,7 @@ export function perfEntryTag( const key = `perf.tag:${entryT.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%perf.tag", key); + helper = `%perf.tag.${lowerer.valueHelpers.size}`; 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 842f42b57..25653f541 100644 --- a/packages/compiler/src/frontend/lowering/builtins/process.ts +++ b/packages/compiler/src/frontend/lowering/builtins/process.ts @@ -1,4 +1,3 @@ -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"; @@ -1562,7 +1561,7 @@ export function lowerProcessMethodCall( const key = `${prefix}usage.diff:${prevT.shapeId}:${t.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, `%${prefix}usage.diff`, key); + helper = `%${prefix}usage.diff.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const pRef: IrExpr = { kind: "varRef", localId: "p.0", type: prevT, loc }; const fieldOf = (name: string): IrExpr => ({ @@ -1637,7 +1636,7 @@ export function lowerProcessMethodCall( const key = `process.memoryUsage:${t.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%process.memoryUsage", key); + helper = `%process.memoryUsage.${lowerer.valueHelpers.size}`; 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 75e527aa5..668ef01f8 100644 --- a/packages/compiler/src/frontend/lowering/builtins/promises.ts +++ b/packages/compiler/src/frontend/lowering/builtins/promises.ts @@ -1,4 +1,3 @@ -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"; @@ -56,7 +55,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 = keyedHelperName(lowerer, "%promise.allTuple", `promise.allTuple:${key}`); + name = `%promise.allTuple.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(`promise.allTuple:${key}`, name); const ctx = newFnCtx(false, null, null, resultT.inner); ctx.isAsync = true; @@ -558,7 +557,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 = keyedHelperName(lowerer, "%promise.try", key); + helper = `%promise.try.${lowerer.arrHofHelpers.size}`; 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 })); diff --git a/packages/compiler/src/frontend/lowering/builtins/promisify-callback.ts b/packages/compiler/src/frontend/lowering/builtins/promisify-callback.ts index b4dbbf513..822a4fecc 100644 --- a/packages/compiler/src/frontend/lowering/builtins/promisify-callback.ts +++ b/packages/compiler/src/frontend/lowering/builtins/promisify-callback.ts @@ -1,4 +1,3 @@ -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"; @@ -171,7 +170,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 = keyedHelperName(lowerer, "%promisify", key); + const base = `%promisify.${lowerer.arrHofHelpers.size}`; 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/text-codecs.ts b/packages/compiler/src/frontend/lowering/builtins/text-codecs.ts index 8d47c8e3a..7229d5b84 100644 --- a/packages/compiler/src/frontend/lowering/builtins/text-codecs.ts +++ b/packages/compiler/src/frontend/lowering/builtins/text-codecs.ts @@ -1,4 +1,3 @@ -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"; @@ -130,7 +129,7 @@ function stringDecoderHelper( const key = `strdec.${op}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, `%strdec.${op}`, key); + const name = `%strdec.${op}.${lowerer.valueHelpers.size}`; 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 d7cbd63b5..2d531663f 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 = lowerer.closureName(loc, "_tpInterval"); + const fnName = `%fn${lowerer.lambdaCounter++}_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 2a77fa85c..dca8a7cc0 100644 --- a/packages/compiler/src/frontend/lowering/builtins/url.ts +++ b/packages/compiler/src/frontend/lowering/builtins/url.ts @@ -1,4 +1,3 @@ -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"; @@ -293,7 +292,7 @@ function searchParamsFromTuples( const key = `sp.fromTuples:${row.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%sp.fromTuples", key); + helper = `%sp.fromTuples.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const pairsT = init.type; const sp = (): IrExpr => varRef("sp.0", SEARCH_PARAMS_T, loc); @@ -373,7 +372,7 @@ function lowerOptionalStringSearchParams( const key = `sp.optionalString:${init.type.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%sp.optionalString", key); + helper = `%sp.optionalString.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const value = varRef("init.0", init.type, loc); lowerer.liftedFns.push({ @@ -679,7 +678,7 @@ function lowerSpForEachCall( const key = `${arity}:${typeKey(fnRet)}`; let helper = lowerer.spHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%sp.forEach", key); + helper = `%sp.forEach.${lowerer.spHofHelpers.size}`; 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 989a61a3f..3582ce8ae 100644 --- a/packages/compiler/src/frontend/lowering/builtins/v8.ts +++ b/packages/compiler/src/frontend/lowering/builtins/v8.ts @@ -5,7 +5,6 @@ * 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"; @@ -56,7 +55,7 @@ export function lowerV8HeapStatisticsCall( const key = `v8.getHeapStatistics:${t.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%v8.getHeapStatistics", key); + helper = `%v8.getHeapStatistics.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const sample = (index: number): IrExpr => ({ kind: "libCall", diff --git a/packages/compiler/src/frontend/lowering/call-arguments.ts b/packages/compiler/src/frontend/lowering/call-arguments.ts index 060ffe9d2..49f7c8ec0 100644 --- a/packages/compiler/src/frontend/lowering/call-arguments.ts +++ b/packages/compiler/src/frontend/lowering/call-arguments.ts @@ -1,4 +1,3 @@ -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"; @@ -754,7 +753,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 = keyedHelperName(lowerer, "%arr.holes", key); + const name = `%arr.holes.${lowerer.valueHelpers.size}`; 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 dacb4d324..34343ad27 100644 --- a/packages/compiler/src/frontend/lowering/call-signatures.ts +++ b/packages/compiler/src/frontend/lowering/call-signatures.ts @@ -849,10 +849,7 @@ export function collectSignatureInner(lowerer: Lowerer, decl: ts.FunctionDeclara lowerer.genericFnsBySymbol.set(symbol, { decl, baseName: nameText, - qualifiedName: lowerer.qualify( - ts.getSourceFileOfNode(decl), - nsPathPrefix(lowerer, decl) + nameText, - ), + qualifiedName: lowerer.qualify(ts.getSourceFileOfNode(decl), nsPathPrefix(decl) + nameText), typeParams: [], instances: new Map(), implicitParams: implicit, @@ -900,7 +897,7 @@ export function collectSignatureInner(lowerer: Lowerer, decl: ts.FunctionDeclara // "%default" spelling ('%' cannot appear in a user identifier). name: lowerer.qualify( ts.getSourceFileOfNode(decl), - nsPathPrefix(lowerer, decl) + (decl.name?.text ?? "%default"), + nsPathPrefix(decl) + (decl.name?.text ?? "%default"), ), params, returnType, diff --git a/packages/compiler/src/frontend/lowering/class-assertions.ts b/packages/compiler/src/frontend/lowering/class-assertions.ts index 52654fab8..900c32426 100644 --- a/packages/compiler/src/frontend/lowering/class-assertions.ts +++ b/packages/compiler/src/frontend/lowering/class-assertions.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { nodeThrowExpr, varRef } from "../../ir/build.js"; import { BOOL, @@ -123,7 +122,7 @@ export function checkedClassAssertion( const key = `classassert:${typeKey(source.type)}:${typeKey(target)}`; let name = lowerer.coercions.retags.get(key); if (!name) { - name = keyedHelperName(lowerer, "%class.assert", key); + name = `%class.assert.${lowerer.coercions.retags.size}`; lowerer.coercions.retags.set(key, name); const input = varRef("value.0", source.type, loc); const body: IrStmt[] = []; @@ -229,7 +228,7 @@ export function checkedClassUnionAssertion( const key = `classunionassert:${typeKey(value.type)}:${typeKey(target)}`; let name = lowerer.coercions.retags.get(key); if (!name) { - name = keyedHelperName(lowerer, "%class.assert", key); + name = `%class.assert.${lowerer.coercions.retags.size}`; 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-unions.ts b/packages/compiler/src/frontend/lowering/class-unions.ts index 0021b2cf8..f52026ba4 100644 --- a/packages/compiler/src/frontend/lowering/class-unions.ts +++ b/packages/compiler/src/frontend/lowering/class-unions.ts @@ -1,4 +1,3 @@ -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"; @@ -133,7 +132,7 @@ export function narrowClassUnion( const key = `classUnion:${source.className}:${target.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%class.union", key); + helper = `%class.union.${lowerer.valueHelpers.size}`; 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 fe3c14605..ffdac19f0 100644 --- a/packages/compiler/src/frontend/lowering/coercions/function-adapters.ts +++ b/packages/compiler/src/frontend/lowering/coercions/function-adapters.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "../stable-names.js"; import { dynUndefinedExpr } from "../../../ir/build.js"; import { buildFunctionAdapter } from "./builders.js"; import { InternalCompilerError } from "../../../errors.js"; @@ -34,7 +33,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 = keyedHelperName(lowerer, "%fn.width", key); + const name = `%fn.width.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); lowerer.freshClosureAdapters.add(name); // The returned closure's body: call the captured original, width-map. @@ -164,7 +163,7 @@ function restPackingAdapter( const key = `fnrestadapt:${typeKey(fromT)}:${typeKey(toT)}`; const existing = lowerer.coercions.retags.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%fn.adapt", key); + const name = `%fn.adapt.${lowerer.coercions.retags.size}`; lowerer.coercions.retags.set(key, name); lowerer.freshClosureAdapters.add(name); const fixed = fromT.params.length - 1; @@ -221,7 +220,7 @@ function funcIntoDynRestAdapter( const key = `fnadapt:${typeKey(fromT)}:${typeKey(toT)}`; const existing = lowerer.coercions.retags.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%fn.adapt", key); + const name = `%fn.adapt.${lowerer.coercions.retags.size}`; lowerer.coercions.retags.set(key, name); lowerer.freshClosureAdapters.add(name); const params: IrParam[] = [{ localId: "rest.0", name: "args", type: DYN }]; @@ -377,7 +376,7 @@ export function funcCoerceAdapter( const key = `fnadapt:${typeKey(fromT)}:${typeKey(toT)}`; const existing = lowerer.coercions.retags.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%fn.adapt", key); + const name = `%fn.adapt.${lowerer.coercions.retags.size}`; lowerer.coercions.retags.set(key, name); lowerer.freshClosureAdapters.add(name); const params: IrParam[] = toT.params.map((t, i) => ({ @@ -605,7 +604,7 @@ export function spawnResFnAdapter( const key = `fnspawn:${typeKey(fromT)}:${typeKey(toT)}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%fnval.spawnres", key); + const name = `%fnval.spawnres.${lowerer.valueHelpers.size}`; 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.ts b/packages/compiler/src/frontend/lowering/coercions/structural.ts index 5b5e283b3..496a29607 100644 --- a/packages/compiler/src/frontend/lowering/coercions/structural.ts +++ b/packages/compiler/src/frontend/lowering/coercions/structural.ts @@ -1,4 +1,3 @@ -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"; @@ -254,7 +253,7 @@ export function unionRecordWidthHelper( const key = `unionWidth:${fromId}:${target.shapeId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%union.record", key); + const name = `%union.record.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const type: IrType = { kind: "union", unionId: fromId }; const value = varRef("value.0", type, loc); @@ -313,7 +312,7 @@ export function recordWidthHelper( const key = `rec:${fromId}:${toId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%rec.width", key); + const name = `%rec.width.${lowerer.valueHelpers.size}`; // Interned BEFORE the body builds: a recursive nested-width field // (self-referential shapes) resolves to this helper itself. lowerer.valueHelpers.set(key, name); @@ -342,7 +341,7 @@ export function tupleArrayWidthHelper( const key = `tuparr:${fromId}:${typeKey(toT.elem)}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%tup.arr", key); + const name = `%tup.arr.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const fromT: IrType = { kind: "record", shapeId: fromId }; const t: IrExpr = { kind: "varRef", localId: "t.0", type: fromT, loc }; @@ -389,7 +388,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 = keyedHelperName(lowerer, "%arr.empty", key); + const name = `%arr.empty.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const a: IrExpr = { kind: "varRef", localId: "a.0", type: fromT, loc }; lowerer.liftedFns.push({ @@ -453,7 +452,7 @@ export function arrayWidthHelper( const key = `arr:${typeKey(fromElem)}:${typeKey(toElem)}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%arr.width", key); + const name = `%arr.width.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const arrT: IrType = { kind: "array", elem: fromElem }; const outT: IrType = { kind: "array", elem: toElem }; @@ -493,7 +492,7 @@ export function objRecordWidthHelper( const key = `obj:${className}:${toId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%obj.width", key); + const name = `%obj.width.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const fromT: IrType = { kind: "object", className }; lowerer.liftedFns.push(buildRecordProjection(lowerer, name, fromT, to, plan, loc)); @@ -518,7 +517,7 @@ export function recordClassWidthHelper( const key = `cls:${fromId}:${className}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%cls.width", key); + const name = `%cls.width.${lowerer.valueHelpers.size}`; 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 434e687a5..06c0af9c6 100644 --- a/packages/compiler/src/frontend/lowering/coercions/unions.ts +++ b/packages/compiler/src/frontend/lowering/coercions/unions.ts @@ -1,4 +1,3 @@ -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"; @@ -148,7 +147,7 @@ export function strandedUnitTrap( const key = `strandunit:${typeKey(expected)}:${expr.type.kind}`; let name = lowerer.coercions.retags.get(key); if (!name) { - name = keyedHelperName(lowerer, "%unit.strand", key); + name = `%unit.strand.${lowerer.coercions.retags.size}`; lowerer.coercions.retags.set(key, name); lowerer.liftedFns.push({ name, @@ -228,7 +227,7 @@ export function strandedCoercionTrap( const key = `strand:${expected.unionId}:${typeKey(src)}`; let name = lowerer.coercions.retags.get(key); if (!name) { - name = keyedHelperName(lowerer, "%union.strand", key); + name = `%union.strand.${lowerer.coercions.retags.size}`; lowerer.coercions.retags.set(key, name); const toT: IrType = { kind: "union", unionId: expected.unionId }; lowerer.liftedFns.push({ @@ -276,7 +275,7 @@ export function recordUnionWrapHelper( const key = `recordWrap:${source.shapeId}:${toId}`; const existing = lowerer.coercions.retags.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%record.wrap", key); + const name = `%record.wrap.${lowerer.coercions.retags.size}`; lowerer.coercions.retags.set(key, name); lowerer.liftedFns.push( buildRecordUnionWrap(name, source, to, plan, loc, (lift, value, dst) => @@ -308,7 +307,7 @@ export function recordUnionRouteHelper( (from, dst) => lowerer.widthLiftPlan(from, dst), ); if (!plan) return null; - const name = keyedHelperName(lowerer, "%record.route", key); + const name = `%record.route.${lowerer.coercions.retags.size}`; lowerer.coercions.retags.set(key, name); lowerer.liftedFns.push( buildRecordUnionWrap(name, source, to, plan, loc, (lift, value, dst) => @@ -353,7 +352,7 @@ export function unionRetagHelper( }); const key = `${fromId}:${toId}:${stranded.join(".")}`; const existing = lowerer.coercions.retags.get(key); - const name = existing ?? keyedHelperName(lowerer, "%union.retag", key); + const name = existing ?? `%union.retag.${lowerer.coercions.retags.size}`; if (!existing) { lowerer.coercions.retags.set(key, name); lowerer.liftedFns.push( @@ -411,7 +410,7 @@ export function narrowedArmHelper( lowerer.coercions.checkedNarrows.add(existing); return existing; } - const name = keyedHelperName(lowerer, "%union.narrow", key); + const name = `%union.narrow.${lowerer.coercions.narrows.size}`; lowerer.coercions.narrows.set(key, name); lowerer.coercions.checkedNarrows.add(name); const fn = buildUnionNarrow(name, from, target, loc, (type) => lowerer.fmt(type)); @@ -588,7 +587,7 @@ export function deferredReadHelper( const key = `deferred:${fromId}:${tag}`; const existing = lowerer.coercions.narrows.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%deferred.read", key); + const name = `%deferred.read.${lowerer.coercions.narrows.size}`; 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 8fe2a6bbb..5d14d5492 100644 --- a/packages/compiler/src/frontend/lowering/collection-ingestion.ts +++ b/packages/compiler/src/frontend/lowering/collection-ingestion.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import * as ts from "../ts7/adapter.js"; import { InternalCompilerError } from "../../errors.js"; import { typeKey } from "../type-mapper.js"; @@ -198,7 +197,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 = keyedHelperName(lowerer, "%collection.ingest", key); + name = `%collection.ingest.${lowerer.arrHofHelpers.size}`; 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 7ca69d9ba..eb99592bb 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-callbacks.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-callbacks.ts @@ -1,4 +1,3 @@ -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"; @@ -507,7 +506,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 = keyedHelperName(lowerer, `%arr.${method}`, key); + const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); lowerer.arrHofInfo.set(name, { method, elem, fnRet, arity, outElem, present, split: !!fastT }); const fn = buildArrayHofFn( @@ -620,7 +619,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 = keyedHelperName(lowerer, "%arr.union", key); + const name = `%arr.union.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); const receiver = varRef("a.0", receiverT, loc); const callback = varRef("f.0", callbackT, loc); @@ -1205,7 +1204,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 = keyedHelperName(lowerer, `%arr.${method}`, key); + const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); const arrT = arrayOf(elem); const valueT = callbackValueType(lowerer, elem, present); @@ -1305,7 +1304,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 = keyedHelperName(lowerer, `%arr.${method}`, key); + const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); if (!last) lowerer.arrHofInfo.set(name, { @@ -1389,7 +1388,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 = keyedHelperName(lowerer, `%arr.${method}`, key); + const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); lowerer.arrHofInfo.set(name, { method, @@ -1588,7 +1587,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 = keyedHelperName(lowerer, "%arr.flatMap", key); + const name = `%arr.flatMap.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); lowerer.arrHofInfo.set(name, { method: "flatMapArray", @@ -1830,7 +1829,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 = keyedHelperName(lowerer, `%arr.${method}`, key); + const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); if (method === "reduce") lowerer.arrHofInfo.set(name, { @@ -2122,7 +2121,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 = keyedHelperName(lowerer, `%arr.${method}`, key); + helper = `%arr.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const undefinedTag = elem.kind === "union" ? lowerer.armTag(elem.unionId, UNDEFINED_T) : -1; lowerer.liftedFns.push( @@ -2168,7 +2167,7 @@ function sortKeyReader( const cacheKey = `sortKey:${typeKey(elem)}:${sortKeysId(reads.map((read) => ({ order: 1, read })))}`; let reader = lowerer.arrHofHelpers.get(cacheKey); if (!reader) { - reader = keyedHelperName(lowerer, "%arr.sortKey", cacheKey); + reader = `%arr.sortKey.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(cacheKey, reader); lowerer.liftedFns.push(buildSortKeyFn(reader, elem, reads, loc)); } @@ -2309,7 +2308,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 = keyedHelperName(lowerer, "%dyn.flatmap", key); + const name = `%dyn.flatmap.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); lowerer.liftedFns.push(buildDynFlatMapFn(name, elemT, arity, loc)); return name; @@ -2482,7 +2481,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 = keyedHelperName(lowerer, "%dyn.filter", key); + const name = `%dyn.filter.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); lowerer.liftedFns.push(buildDynFilterFn(name, elemT, arity, loc)); return name; @@ -2677,7 +2676,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 = keyedHelperName(lowerer, `%tuple.${method}`, key); + helper = `%tuple.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const v = varRef("v.0", elem, loc); const out = varRef("out.0", resultT, loc); diff --git a/packages/compiler/src/frontend/lowering/containers/array-concat.ts b/packages/compiler/src/frontend/lowering/containers/array-concat.ts index b4e285ee9..4f6e4ca43 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-concat.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-concat.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "../stable-names.js"; import { identityPreservingWidening } from "../coercions/identity.js"; import { countedFor, numLit, varRef } from "../../../ir/build.js"; import { @@ -29,7 +28,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 = keyedHelperName(lowerer, "%arr.concat", key); + const name = `%arr.concat.${lowerer.arrHofHelpers.size}`; const arrT = arrayOf(elem); const params = [ { localId: "a.0", name: "a", type: arrT }, diff --git a/packages/compiler/src/frontend/lowering/containers/array-construction.ts b/packages/compiler/src/frontend/lowering/containers/array-construction.ts index 1f10640c0..40e4d6436 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-construction.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-construction.ts @@ -1,4 +1,3 @@ -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"; @@ -257,7 +256,7 @@ function appendWidenedArrayValues( const key = `insertValues:${typeKey(sourceType.elem)}:${typeKey(elem)}`; let name = lowerer.arrHofHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%arr.insertValues", key); + name = `%arr.insertValues.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); const outType = arrayOf(elem); const valueType = arrayValueType(lowerer, source.type.elem); @@ -1036,7 +1035,7 @@ export function lowerArrayFromCall( const key = `fromArray:${typeKey(arrT.elem)}:${typeKey(outElem)}:${typeKey(fnRet)}:${arity}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%arr.fromArray", key); + helper = `%arr.fromArray.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); lowerer.liftedFns.push( buildArrayFromArrayFn(lowerer, helper, arrT.elem, outElem, fnRet, arity, loc), @@ -1123,7 +1122,7 @@ export function lowerArrayFromCall( const key = `fromLen:${typeKey(fnRet)}:${arity}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%arr.fromLen", key); + helper = `%arr.fromLen.${lowerer.arrHofHelpers.size}`; 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 44182fbda..e9a130a2d 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-methods.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-methods.ts @@ -1,4 +1,3 @@ -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"; @@ -1617,7 +1616,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 = keyedHelperName(lowerer, `%arr.${method}`, key); + const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); const arrT = arrayOf(elem); const resultT = method === "includes" ? BOOL : F64; @@ -1973,7 +1972,7 @@ export function lowerTupleReadMethodCall( let helper = lowerer.arrHofHelpers.get(key); const resultType = method === "includes" ? BOOL : F64; if (!helper) { - helper = keyedHelperName(lowerer, `%tuple.${method}`, key); + helper = `%tuple.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const params = [ { localId: "a.0", name: "a", type: receiver.type }, @@ -2035,7 +2034,7 @@ export function lowerTupleReadMethodCall( const key = `tuple.slice:${typeKey(receiver.type)}:${args.length}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%tuple.slice", key); + helper = `%tuple.slice.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const params = [receiver, ...args].map((arg, i) => ({ localId: i === 0 ? "a.0" : `arg.${i}`, @@ -2126,7 +2125,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 = keyedHelperName(lowerer, `%tuple.${method}`, key); + helper = `%tuple.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const out = varRef("out.0", outType, loc); const result = varRef("r.0", ret, loc); @@ -2254,7 +2253,7 @@ function lowerArrayAtCall( const key = `at:${typeKey(elem)}:${typeKey(resultT)}:${typeKey(index.type)}`; let name = lowerer.arrHofHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%arr.at", key); + name = `%arr.at.${lowerer.arrHofHelpers.size}`; 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 180f40435..cf45a7575 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-pipelines.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-pipelines.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "../stable-names.js"; import { boolLit, countedFor, numLit, varRef } from "../../../ir/build.js"; import { BOOL, @@ -852,7 +851,7 @@ class PipelineFusion { if (!built) return null; let name = this.helpers.get(built.key); if (!name) { - name = keyedHelperName(this.lowerer, "%arr.fused", built.key); + name = `%arr.fused.${this.helpers.size}`; this.helpers.set(built.key, name); this.added.push({ ...built.fn, name }); } diff --git a/packages/compiler/src/frontend/lowering/containers/bytes.ts b/packages/compiler/src/frontend/lowering/containers/bytes.ts index 4b20d7bf5..bf9821d31 100644 --- a/packages/compiler/src/frontend/lowering/containers/bytes.ts +++ b/packages/compiler/src/frontend/lowering/containers/bytes.ts @@ -1,4 +1,3 @@ -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"; @@ -78,7 +77,7 @@ function lowerBytesSortCall( const cacheKey = `bytes.${method}:${bytesT.elem}:${key}`; let helper = lowerer.arrHofHelpers.get(cacheKey); if (!helper) { - helper = keyedHelperName(lowerer, `%bytes.${method}`, cacheKey); + helper = `%bytes.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(cacheKey, helper); lowerer.liftedFns.push( buildBytesSortFn(helper, bytesT, arity, hasComparator, copyFirst, order, loc), @@ -271,7 +270,7 @@ function bytesCallbackHelper( const key = `bytes.${method}:${bytesT.elem}:${typeKey(resultT)}:${typeKey(fnRet)}:${arity}:${hasInit ? "init" : ""}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, `%bytes.${method}`, key); + const name = `%bytes.${method}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); const reduce = method === "reduce" || method === "reduceRight"; const backward = method === "reduceRight" || method === "findLast" || method === "findLastIndex"; diff --git a/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts b/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts index f39c8e86c..18754f088 100644 --- a/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts +++ b/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts @@ -1,4 +1,3 @@ -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"; @@ -286,7 +285,7 @@ export function truthyFilterCallback( const key = `filterBoolean:${typeKey(valueT)}`; let name = lowerer.arrHofHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%arr.filterBoolean", key); + name = `%arr.filterBoolean.${lowerer.arrHofHelpers.size}`; 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 dae68d518..0bf126830 100644 --- a/packages/compiler/src/frontend/lowering/containers/collection-grouping.ts +++ b/packages/compiler/src/frontend/lowering/containers/collection-grouping.ts @@ -1,4 +1,3 @@ -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"; @@ -105,7 +104,7 @@ export function lowerGroupByStaticCall( const key = `map.groupBy:${typeKey(items.type)}:${typeKey(f.type)}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%map.groupBy", key); + helper = `%map.groupBy.${lowerer.mapHofHelpers.size}`; lowerer.mapHofHelpers.set(key, helper); lowerer.liftedFns.push(buildGroupByFn(lowerer, helper, items.type, f.type, resultT, loc)); } @@ -142,7 +141,7 @@ export function lowerGroupByStaticCall( const key = `object.groupBy:${typeKey(items.type)}:${typeKey(f.type)}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%object.groupBy", key); + helper = `%object.groupBy.${lowerer.mapHofHelpers.size}`; 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 d3169ec5c..370974c85 100644 --- a/packages/compiler/src/frontend/lowering/containers/collection-methods.ts +++ b/packages/compiler/src/frontend/lowering/containers/collection-methods.ts @@ -1,4 +1,3 @@ -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"; @@ -233,7 +232,7 @@ function lowerMapIterDrainCall( const key = `${method}:${typeKey(mapT.key)}:${typeKey(mapT.value)}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, `%map.${method}`, key); + helper = `%map.${method}.${lowerer.mapHofHelpers.size}`; lowerer.mapHofHelpers.set(key, helper); lowerer.liftedFns.push(buildMapIterDrainFn(helper, mapT, method, elemT, tupleT, loc)); } @@ -349,7 +348,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 = keyedHelperName(lowerer, "%map.entries", key); + helper = `%map.entries.${lowerer.mapHofHelpers.size}`; lowerer.mapHofHelpers.set(key, helper); lowerer.liftedFns.push( buildMapIterDrainFn(helper, mapT, "entries", tupleT, tupleT, receiver.loc), @@ -520,7 +519,7 @@ export function lowerMapForEachCall( const key = `${typeKey(mapT.key)}:${typeKey(mapT.value)}:${arity}:${typeKey(fnRet)}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%map.forEach", key); + helper = `%map.forEach.${lowerer.mapHofHelpers.size}`; lowerer.mapHofHelpers.set(key, helper); lowerer.liftedFns.push(buildCollectionForEachFn(helper, mapT, arity, fnRet, loc)); } @@ -694,7 +693,7 @@ export function lowerSetForEachCall( const key = `${typeKey(setT.elem)}:${arity}:${typeKey(fnRet)}`; let helper = lowerer.setHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%set.forEach", key); + helper = `%set.forEach.${lowerer.setHofHelpers.size}`; lowerer.setHofHelpers.set(key, helper); lowerer.liftedFns.push(buildCollectionForEachFn(helper, setT, arity, fnRet, loc)); } @@ -746,7 +745,7 @@ function lowerSetCombineCall( const key = `${name}:${typeKey(setT.elem)}:${typeKey(otherT)}`; let helper = lowerer.setHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, `%set.${name}`, key); + helper = `%set.${name}.${lowerer.setHofHelpers.size}`; lowerer.setHofHelpers.set(key, helper); lowerer.liftedFns.push(buildSetCombineFn(helper, name, setT, otherT, loc)); } @@ -1358,7 +1357,7 @@ export function mapFromSeedValue( const key = `checked-seed:${typeKey(mapT)}`; let name = lowerer.mapHofHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%map.checkedSeed", key); + name = `%map.checkedSeed.${lowerer.mapHofHelpers.size}`; lowerer.mapHofHelpers.set(key, name); const source = varRef("source.0", DYN, loc); const entries = varRef("entries.0", DYN, loc); @@ -1458,7 +1457,7 @@ export function mapFromSeedValue( const key = `seed:${typeKey(mapT.key)}:${typeKey(mapT.value)}:${elem.shapeId}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%map.seed", key); + helper = `%map.seed.${lowerer.mapHofHelpers.size}`; 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/indexed-objects.ts b/packages/compiler/src/frontend/lowering/containers/indexed-objects.ts index b3faf649e..efc173ffc 100644 --- a/packages/compiler/src/frontend/lowering/containers/indexed-objects.ts +++ b/packages/compiler/src/frontend/lowering/containers/indexed-objects.ts @@ -1,4 +1,3 @@ -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"; @@ -185,7 +184,7 @@ export function objectIterOverIndexShape( const key = `obj.${member}:ovf:${argIr.shapeId}:${typeKey(resultT)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, `%obj.${member}`, key); + helper = `%obj.${member}.${lowerer.arrHofHelpers.size}`; const outRef = varRef("out.0", resultT, loc); const rRef = varRef("r.0", argIr, loc); @@ -609,7 +608,7 @@ function lowerTypedObjectFromEntriesCall( const key = `obj.fromEntries:${argIr.elem.shapeId}:${resultT.shapeId}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%obj.fromEntries", key); + helper = `%obj.fromEntries.${lowerer.arrHofHelpers.size}`; const tupleT = argIr.elem as IrType & { kind: "record" }; const tRef = varRef("t.0", tupleT, loc); @@ -713,7 +712,7 @@ function lowerFromEntriesStringRows( const key = `obj.fromEntries:strrows:${resultT.shapeId}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%obj.fromEntries", key); + helper = `%obj.fromEntries.${lowerer.arrHofHelpers.size}`; const tRef = varRef("t.0", rowT, loc); const rowLen: IrExpr = { @@ -932,7 +931,7 @@ export function lowerRecordOvfCaptureHelper( const key = `ovf:${fromId}:${toId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%rec.capture", key); + const name = `%rec.capture.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const fromT: IrType = { kind: "record", shapeId: fromId }; const toT: IrType = { kind: "record", shapeId: toId }; @@ -1205,7 +1204,7 @@ export function lowerObjectAssignIndexShape( const key = `assign:${targetIr.shapeId}:${plan.fromId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%obj.assign", key); + const name = `%obj.assign.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const toT: IrType = { kind: "record", shapeId: targetIr.shapeId }; const fromT: IrType = { kind: "record", shapeId: plan.fromId }; @@ -1475,7 +1474,7 @@ export function lowerIndexMergeHelper( .join(","); const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%rec.merge", key); + const name = `%rec.merge.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const toT: IrType = { kind: "record", shapeId: toId }; const ksT = arrayOf(STRING); @@ -1806,7 +1805,7 @@ export function lowerEnvToPairsHelper( const key = `env.pairs:${shapeId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%env.pairs", key); + const name = `%env.pairs.${lowerer.valueHelpers.size}`; 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 48b4caabd..c23e6931c 100644 --- a/packages/compiler/src/frontend/lowering/containers/iterator-helpers.ts +++ b/packages/compiler/src/frontend/lowering/containers/iterator-helpers.ts @@ -1,4 +1,3 @@ -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"; @@ -967,7 +966,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 = keyedHelperName(lowerer, `%iter.${terminal}`, key); + helper = `%iter.${terminal}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); lowerer.liftedFns.push( buildIterChainFn( @@ -1039,7 +1038,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 = keyedHelperName(lowerer, `%iter.${stage.kind}`, key); + name = `%iter.${stage.kind}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); lowerer.liftedFns.push( buildHelperGenFn(lowerer, name, source, srcElem, stage, arg.type, outT, resultType, loc), @@ -1059,7 +1058,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" : keyedHelperName(lowerer, "%iter.budget.close", key); + name = srcT === null ? "%iter.budget" : `%iter.budget.close.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); const v = (): IrExpr => ({ kind: "varRef", localId: "v.0", type: F64, loc }); 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 fe4ddbc6c..9567ee0f6 100644 --- a/packages/compiler/src/frontend/lowering/containers/string-and-regexp.ts +++ b/packages/compiler/src/frontend/lowering/containers/string-and-regexp.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "../stable-names.js"; import { matchAllRowsReadByElements } from "./match-row-uses.js"; import { boolLit, @@ -160,7 +159,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 = keyedHelperName(lowerer, "%str.split", key); + helper = `%str.split.${lowerer.valueHelpers.size}`; const values = [receiver, separator, limit]; const params = values.map((value, index) => ({ localId: `arg.${index}`, @@ -396,7 +395,7 @@ function stringIndexHelperCall( const key = `str.index:${method}:${typeKey(receiver.type)}:${typeKey(index.type)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%str.index", key); + helper = `%str.index.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const rawReceiver = varRef("arg.0", receiver.type, loc); const rawIndex = varRef("arg.1", index.type, loc); @@ -674,7 +673,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 = keyedHelperName(lowerer, "%str.pad", key); + helper = `%str.pad.${lowerer.valueHelpers.size}`; const params = values.map((value, index) => ({ localId: `arg.${index}`, name: `arg${index}`, @@ -1310,7 +1309,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 = keyedHelperName(lowerer, "%str.positions", key); + helper = `%str.positions.${lowerer.valueHelpers.size}`; const params = [receiver, needle, position].map((arg, index) => ({ localId: `arg.${index}`, name: `arg${index}`, @@ -1412,7 +1411,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 = keyedHelperName(lowerer, "%str.positions", key); + helper = `%str.positions.${lowerer.valueHelpers.size}`; const params = [receiver, ...args].map((arg, index) => ({ localId: `arg.${index}`, name: `arg${index}`, diff --git a/packages/compiler/src/frontend/lowering/containers/string-replacement.ts b/packages/compiler/src/frontend/lowering/containers/string-replacement.ts index 780c77d0f..6856bc50b 100644 --- a/packages/compiler/src/frontend/lowering/containers/string-replacement.ts +++ b/packages/compiler/src/frontend/lowering/containers/string-replacement.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { BOOL, @@ -163,7 +162,7 @@ function lowerStringReplacementValues( const key = `str.${method}:${typeKey(replacement.type)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, `%str.${method}`, key); + helper = `%str.${method}.${lowerer.valueHelpers.size}`; 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/expressions/binary.ts b/packages/compiler/src/frontend/lowering/expressions/binary.ts index 7e449f12b..fafbbf695 100644 --- a/packages/compiler/src/frontend/lowering/expressions/binary.ts +++ b/packages/compiler/src/frontend/lowering/expressions/binary.ts @@ -1,5 +1,4 @@ /* 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"; @@ -802,7 +801,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 = keyedHelperName(lowerer, "%rec.tostr", key); + helper = `%rec.tostr.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const r = varRef("r.0", t, loc); lowerer.liftedFns.push({ diff --git a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts index 93bf43e95..565db0cd8 100644 --- a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts +++ b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts @@ -1,4 +1,3 @@ -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"; @@ -407,7 +406,7 @@ export function lowerDynObjectLiteral( if (!(err instanceof PoisonError) || !pureMember) throw err; const fence = lowerer.deferToRuntimeFence(propDiagsBefore, prop, { kind: "closure", - name: () => lowerer.closureName(loc, "_dynfence"), + name: () => `%fn${lowerer.lambdaCounter++}_dynfence`, returnType: VOID, type: { kind: "func", params: [], ret: VOID }, }); @@ -462,7 +461,7 @@ export function lowerDynObjectLiteral( if (!(err instanceof PoisonError)) throw err; const fence = lowerer.deferToRuntimeFence(convDiagsBefore, prop, { kind: "closure", - name: () => lowerer.closureName(loc, "_dynfence"), + name: () => `%fn${lowerer.lambdaCounter++}_dynfence`, returnType: VOID, type: { kind: "func", params: [], ret: VOID }, }); @@ -2957,7 +2956,7 @@ function lowerDeclaredSpreadMerge( const key = `declmerge-source:${type.shapeId}:${source.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%rec.declmerge", key); + helper = `%rec.declmerge.${lowerer.valueHelpers.size}`; const sourceType = source.value.type; const destination = varRef("out.0", type, loc); const receiver = varRef("source.0", sourceType, loc); diff --git a/packages/compiler/src/frontend/lowering/expressions/optional-chains.ts b/packages/compiler/src/frontend/lowering/expressions/optional-chains.ts index 4b8c5692a..fbcecdc32 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 = lowerer.closureName(loc, "", "chain"); + const id = `chain.${lowerer.chainCounter++}`; 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 = lowerer.closureName(loc, "", "chain"); + const id = `chain.${lowerer.chainCounter++}`; 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 = lowerer.closureName(loc, "", "chain"); + const id = `chain.${lowerer.chainCounter++}`; 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 = lowerer.closureName(loc, "", "chain"); + const id = `chain.${lowerer.chainCounter++}`; 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 = lowerer.closureName(loc, "", "chain"); + const id = `chain.${lowerer.chainCounter++}`; // 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 6c8dfa3bf..f0b980da0 100644 --- a/packages/compiler/src/frontend/lowering/expressions/property-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/property-access.ts @@ -1,5 +1,4 @@ /* 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"; @@ -2784,7 +2783,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 = keyedHelperName(lowerer, "%regex.groups", key); + helper = `%regex.groups.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const body: IrStmt[] = []; const locals: IrLocal[] = [{ id: "m.0", name: "m", type: recv.type, mutable: true }]; diff --git a/packages/compiler/src/frontend/lowering/expressions/relational.ts b/packages/compiler/src/frontend/lowering/expressions/relational.ts index 836391835..088b45cff 100644 --- a/packages/compiler/src/frontend/lowering/expressions/relational.ts +++ b/packages/compiler/src/frontend/lowering/expressions/relational.ts @@ -1,5 +1,4 @@ /* instanceof and in, including private-name and runtime-key in. */ -import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { builtinClassInstanceOfAny, builtinClassKind } from "../builtins/builtin-class-dyn.js"; import { @@ -648,7 +647,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 = keyedHelperName(lowerer, "%instanceof.union", key); + helper = `%instanceof.union.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const value: IrExpr = { kind: "varRef", localId: "value.0", type: left.type, loc }; const body: IrStmt[] = []; @@ -1848,7 +1847,7 @@ function lowerRuntimeKeyIn( const hkey = `haskey:${recvT.shapeId}`; let helper = lowerer.valueHelpers.get(hkey); if (!helper) { - helper = keyedHelperName(lowerer, "%rec.haskey", hkey); + helper = `%rec.haskey.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(hkey, helper); const recT: IrType = { kind: "record", shapeId: recvT.shapeId }; diff --git a/packages/compiler/src/frontend/lowering/generic-functions.ts b/packages/compiler/src/frontend/lowering/generic-functions.ts index daf082db7..abcd5a584 100644 --- a/packages/compiler/src/frontend/lowering/generic-functions.ts +++ b/packages/compiler/src/frontend/lowering/generic-functions.ts @@ -1,6 +1,4 @@ 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"; @@ -231,10 +229,7 @@ export function collectGenericSignature(lowerer: Lowerer, decl: ts.FunctionDecla lowerer.genericFnsBySymbol.set(symbol, { decl, baseName: nameText, - qualifiedName: lowerer.qualify( - ts.getSourceFileOfNode(decl), - nsPathPrefix(lowerer, decl) + nameText, - ), + qualifiedName: lowerer.qualify(ts.getSourceFileOfNode(decl), nsPathPrefix(decl) + nameText), typeParams, instances: new Map(), }); @@ -656,7 +651,7 @@ function internGenericInstance( const typeArgsText = `<${rendered.length > 80 ? rendered.slice(0, 77) + "..." : rendered}>`; inst = { path, - name: keyedHelperName(lowerer, `${info.qualifiedName}%`, key, ""), + name: `${info.qualifiedName}%${info.instances.size}`, ordinal: info.instances.size, params, returnType, @@ -2134,7 +2129,7 @@ function internImplicitInstance( const declared = dynamicBroadPromise ? null : implicitDeclaredReturn(lowerer, info); inst = { path, - name: keyedHelperName(lowerer, `${info.qualifiedName}%`, key, ""), + name: `${info.qualifiedName}%${info.instances.size}`, ordinal: info.instances.size, params: shapes, // The promise callers rely on before the body settles it: the @@ -2322,7 +2317,7 @@ export function implicitLocalFnInfoOf( baseName: name, qualifiedName: lowerer.qualify( ts.getSourceFileOfNode(decl), - nsPathPrefix(lowerer, stmt ?? decl, decl) + `${name}%l${positionTag(lowerer, decl)}`, + nsPathPrefix(stmt ?? decl, decl) + `${name}%l${ts.tokenStartOfNode(decl)}`, ), typeParams: [], instances: new Map(), @@ -2418,7 +2413,7 @@ export function objLitGenericFnInfoOf( baseName: name, qualifiedName: lowerer.qualify( ts.getSourceFileOfNode(fnNode), - `%ol${positionTag(lowerer, fnNode)}.${name}`, + `%ol${ts.tokenStartOfNode(fnNode)}.${name}`, ), typeParams, instances: new Map(), @@ -2564,7 +2559,7 @@ export function bindingGenericFnInfoOf( baseName: name, qualifiedName: lowerer.qualify( ts.getSourceFileOfNode(decl), - nsPathPrefix(lowerer, stmt ?? decl, decl) + + nsPathPrefix(stmt ?? decl, decl) + (topLevel ? name : `${name}%l${ts.tokenStartOfNode(decl)}`), ), typeParams, diff --git a/packages/compiler/src/frontend/lowering/intern-tables.ts b/packages/compiler/src/frontend/lowering/intern-tables.ts index e3f2b0889..fc69237db 100644 --- a/packages/compiler/src/frontend/lowering/intern-tables.ts +++ b/packages/compiler/src/frontend/lowering/intern-tables.ts @@ -23,7 +23,6 @@ * 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"; @@ -448,11 +447,7 @@ function helperName(lowerer: Lowerer, member: InternTableMember, signature: stri } function registerHelper(lowerer: Lowerer, member: InternTableMember, signature: string): string { - const name = keyedHelperName( - lowerer, - `%${INTERN_TABLE_CLASS}.${member}`, - `${member}|${signature}`, - ); + const name = `%${INTERN_TABLE_CLASS}.${member}.${lowerer.internTableHelpers.size}`; lowerer.internTableHelpers.set(`${member}|${signature}`, name); return name; } diff --git a/packages/compiler/src/frontend/lowering/iterator-adapters.ts b/packages/compiler/src/frontend/lowering/iterator-adapters.ts index e50652182..898c46f20 100644 --- a/packages/compiler/src/frontend/lowering/iterator-adapters.ts +++ b/packages/compiler/src/frontend/lowering/iterator-adapters.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { dynUndefinedExpr, varRef } from "../../ir/build.js"; import { BOOL, @@ -87,7 +86,7 @@ function dynIteratorAdapter( const key = `iterAdapt:${typeKey(expected)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%iter.adapt", key); + name = `%iter.adapt.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const locals: IrLocal[] = []; const local = (id: string, type: IrType, mutable = false): IrExpr => { @@ -314,7 +313,7 @@ export function lowerCollectionIteratorValue( loc, }; if (!typeEquals(yielded.type, type.yieldT)) return null; - name = keyedHelperName(lowerer, "%coll.iter", key); + name = `%coll.iter.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -412,7 +411,7 @@ export function lowerBytesIteratorValue( const key = `bytesIter:${method}:${typeKey(bytesT)}:${typeKey(type)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%bytes.iter", key); + name = `%bytes.iter.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const list = varRef("list.0", bytesT, loc); const index = varRef("index.0", F64, loc); @@ -518,7 +517,7 @@ export function lowerStringIteratorValue( const key = `strIter:${typeKey(type)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%str.iter", key); + name = `%str.iter.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const text = varRef("text.0", STRING, loc); const index = varRef("index.0", F64, loc); @@ -678,7 +677,7 @@ function generatorRetypeAdapter( type: resumeType(expected.nextT), loc, }; - name = keyedHelperName(lowerer, "%gen.retype", key); + name = `%gen.retype.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -795,7 +794,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 = keyedHelperName(lowerer, "%gen.drain", key); + name = `%gen.drain.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -857,7 +856,7 @@ export function generatorDrain( if (!raw) return null; const value = lowerer.coerceToExpected(raw, elem); if (!typeEquals(value.type, elem)) return null; - name = keyedHelperName(lowerer, "%gen.drain", key); + name = `%gen.drain.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -979,7 +978,7 @@ export function lowerArrayIteratorValue( }; } if (!yielded || !typeEquals(yielded.type, type.yieldT)) return null; - name = keyedHelperName(lowerer, "%arr.iter", key); + name = `%arr.iter.${lowerer.valueHelpers.size}`; 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 e27dd4183..b9bbf6216 100644 --- a/packages/compiler/src/frontend/lowering/js-dynamic-objects.ts +++ b/packages/compiler/src/frontend/lowering/js-dynamic-objects.ts @@ -21,7 +21,6 @@ * 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"; @@ -216,10 +215,10 @@ export function lowerValueReturningConstructorNew( "spread arguments when constructing a class whose constructor returns a value", ); } - const key = `ctorValue:${lowerer.positions.of(decl)}`; + const key = `ctorValue:${ts.getSourceFileOfNode(decl).fileName}:${ts.tokenStartOfNode(decl)}`; let name = lowerer.valueHelpers.get(key); if (name === undefined) { - name = keyedHelperName(lowerer, "%ctorValue", key); + name = `%ctorValue.${lowerer.valueHelpers.size}`; 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 d6c2da571..927745253 100644 --- a/packages/compiler/src/frontend/lowering/json-require.ts +++ b/packages/compiler/src/frontend/lowering/json-require.ts @@ -10,7 +10,6 @@ * 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"; @@ -85,7 +84,7 @@ export function collectJsonRequires(lowerer: Lowerer, parts: FileParts[]): void ); throw new PoisonError(); } - const id = keyedHelperName(lowerer, "%g.jsonRequire", jsonSf.fileName); + const id = `%g.jsonRequire.${lowerer.jsonRequireModules.size}`; 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/lifetime-regions.ts b/packages/compiler/src/frontend/lowering/lifetime-regions.ts index b684c0395..b212ae473 100644 --- a/packages/compiler/src/frontend/lowering/lifetime-regions.ts +++ b/packages/compiler/src/frontend/lowering/lifetime-regions.ts @@ -14,7 +14,6 @@ * 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"; @@ -153,7 +152,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 = keyedHelperName(lowerer, `%${LIFETIME_REGION_CLASS}.run`, key); + const name = `%${LIFETIME_REGION_CLASS}.run.${lowerer.regionRunHelpers.size}`; 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 bc51a9382..460f4d53a 100644 --- a/packages/compiler/src/frontend/lowering/lower-assert.ts +++ b/packages/compiler/src/frontend/lowering/lower-assert.ts @@ -1,4 +1,3 @@ -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 @@ -668,7 +667,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 = keyedHelperName(lowerer, "%assert.pdeq", key); + const name = `%assert.pdeq.${lowerer.assertHelpers.size}`; lowerer.assertHelpers.set(key, name); const a = (): IrExpr => varRef("a.0", ta, loc); const b = (): IrExpr => varRef("b.0", tb, loc); @@ -1281,7 +1280,7 @@ function deepCheckCall( const key = `assert.dcheck:${variant}:${negated}:${typeKey(a.type)}:${typeKey(b.type)}`; let name = lowerer.assertHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%assert.dcheck", key); + name = `%assert.dcheck.${lowerer.assertHelpers.size}`; lowerer.assertHelpers.set(key, name); const pa = varRef("a.0", a.type, loc); const pb = varRef("b.0", b.type, loc); @@ -1845,7 +1844,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 = keyedHelperName(lowerer, `%assert.${mode}`, key); + const name = `%assert.${mode}.${lowerer.assertHelpers.size}`; lowerer.assertHelpers.set(key, name); const caughtRef = (): IrExpr => varRef("e.0", CAUGHT, loc); @@ -2294,7 +2293,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 = keyedHelperName(lowerer, "%assert.iferr", key); + const name = `%assert.iferr.${lowerer.assertHelpers.size}`; lowerer.assertHelpers.set(key, name); const def = lowerer.unions.get(t.unionId); if (!def) throw new InternalCompilerError(`assert.ifError over unknown union ${t.unionId}`); @@ -2465,7 +2464,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 = keyedHelperName(lowerer, `%assert.${prefix}`, key); + const name = `%assert.${prefix}.${lowerer.assertHelpers.size}`; lowerer.assertHelpers.set(key, name); const a = (): IrExpr => varRef("a.0", t, loc); diff --git a/packages/compiler/src/frontend/lowering/lower-calls.ts b/packages/compiler/src/frontend/lowering/lower-calls.ts index 63b8781f2..7102f37ab 100644 --- a/packages/compiler/src/frontend/lowering/lower-calls.ts +++ b/packages/compiler/src/frontend/lowering/lower-calls.ts @@ -1,4 +1,3 @@ -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"; @@ -2095,7 +2094,7 @@ function lowerOptionalNumberDefault( const key = `number.optionalDefault:${widened.unionId}:${dflt}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%number.optionalDefault", key); + helper = `%number.optionalDefault.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const input = varRef("value.0", widened, loc); lowerer.liftedFns.push({ @@ -2204,7 +2203,7 @@ function primitiveConversionHandler( const key = `then.${name}:${typeKey(inner)}`; let fnName = lowerer.arrHofHelpers.get(key); if (fnName === undefined) { - fnName = keyedHelperName(lowerer, `%then.${name}`, key); + fnName = `%then.${name}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, fnName); const value = varRef("v.0", inner, loc); let body: IrExpr; @@ -2373,7 +2372,7 @@ function lowerBigIntConstructorValue(lowerer: Lowerer, arg: IrExpr, loc: SrcLoc) const key = `bigint.scalar:${unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%bigint.scalar", key); + helper = `%bigint.scalar.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const value = varRef("value.0", arg.type, loc); const body: IrStmt[] = []; @@ -3235,7 +3234,7 @@ function lowerScalarUnionNumber( const key = `number.scalar:${arg.type.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%number.scalar", key); + helper = `%number.scalar.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const value = varRef("value.0", arg.type, loc); const nan: IrExpr = { @@ -3280,7 +3279,7 @@ function lowerOptionalStringNumber( const key = `${label}.optionalString:${arg.type.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, `%${label}.optionalString`, key); + helper = `%${label}.optionalString.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const value = varRef("value.0", arg.type, loc); lowerer.liftedFns.push({ @@ -4707,7 +4706,7 @@ function lowerDefaultToStringCall( const key = `objToStr:${typeKey(recv.type)}${missing ? `:${missing}` : ""}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%obj.tostr", key); + helper = `%obj.tostr.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const o = varRef("o.0", recv.type, loc); lowerer.liftedFns.push({ @@ -5394,7 +5393,7 @@ function loweredTemplateStrings( const site = lowerer.globalsList.length; const globalId = `%g.templateStrings.${site}`; const readyId = `%g.templateStringsReady.${site}`; - getter = keyedHelperName(lowerer, "%templateStrings.get", key); + getter = `%templateStrings.get.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, getter); lowerer.globalsList.push( { id: globalId, name: "%templateStrings", type, mutable: true }, @@ -5575,7 +5574,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 = lowerer.closureName(loc, `_${member}pass`); + const fnName = `%fn${lowerer.lambdaCounter++}_${member}pass`; const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT], ret: promT }; const fnCtx = newFnCtx(true, null, funcType, inner); fnCtx.isAsync = true; @@ -5672,7 +5671,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 = lowerer.closureName(loc, "_then2"); + const fnName = `%fn${lowerer.lambdaCounter++}_then2`; const paramTypes: IrType[] = [ promT, ...(fulfilled ? [fulfilled.value.type] : []), @@ -5921,7 +5920,7 @@ export function lowerPromiseMethodCall( ); }; const resultT: IrType & { kind: "promise" } = { kind: "promise", inner: DYN }; - const fnName = lowerer.closureName(loc, "_then"); + const fnName = `%fn${lowerer.lambdaCounter++}_then`; const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT, DYN], @@ -6016,7 +6015,7 @@ export function lowerPromiseMethodCall( ); } const R = resultT.inner; - const fnName = lowerer.closureName(loc, "_then"); + const fnName = `%fn${lowerer.lambdaCounter++}_then`; const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT, cb.type], @@ -6119,7 +6118,7 @@ export function lowerPromiseMethodCall( "finally callbacks with parameters or a return value (use () => { ... })", ); } - const fnName = lowerer.closureName(loc, "_finally"); + const fnName = `%fn${lowerer.lambdaCounter++}_finally`; const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT, cb.type], @@ -6222,7 +6221,7 @@ export function lowerPromiseMethodCall( } if (cb.type.kind === "dyn") { const resultT: IrType & { kind: "promise" } = { kind: "promise", inner: DYN }; - const fnName = lowerer.closureName(loc, "_catchdyn"); + const fnName = `%fn${lowerer.lambdaCounter++}_catchdyn`; const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT, DYN], @@ -6352,7 +6351,7 @@ export function lowerPromiseMethodCall( ); } const R = resultT.inner; - const fnName = lowerer.closureName(loc, "_catch"); + const fnName = `%fn${lowerer.lambdaCounter++}_catch`; const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT], ret: resultT }; const fnCtx = newFnCtx(true, null, funcType, R); fnCtx.isAsync = true; @@ -6589,7 +6588,7 @@ function filterNarrowHelper( const key = `filterNarrow:${test}:${typeKey(elem)}:${typeKey(outElem)}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%arr.filterNarrow", key); + const name = `%arr.filterNarrow.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, name); const arrT = arrayOf(elem); @@ -6835,7 +6834,7 @@ export function recordKeysArrayCall( const key = `obj.keys:${argIr.shapeId}:${typeKey(resultT)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%obj.keys", key); + helper = `%obj.keys.${lowerer.arrHofHelpers.size}`; 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); @@ -6905,7 +6904,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 = keyedHelperName(lowerer, "%obj.hasOwn", key); + const helper = `%obj.hasOwn.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const shape = lowerer.shapes.get(shapeId)!; const recT: IrType = { kind: "record", shapeId }; @@ -6990,7 +6989,7 @@ function classAssignHelper( const key = `obj.assignClass:${className}:${srcShapeId}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const helper = keyedHelperName(lowerer, "%obj.assignClass", key); + const helper = `%obj.assignClass.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const sShape = lowerer.shapes.get(srcShapeId)!; const oT: IrType = { kind: "object", className }; @@ -7058,7 +7057,7 @@ function recordAssignHelper( const key = `obj.assign:${targetShapeId}:${srcShapeId}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const helper = keyedHelperName(lowerer, "%obj.assign", key); + const helper = `%obj.assign.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const sShape = lowerer.shapes.get(srcShapeId)!; const tShape = lowerer.shapes.get(targetShapeId)!; @@ -8515,7 +8514,7 @@ function lowerObjectStaticCall( const key = `obj.${member}:${argIr.shapeId}:${typeKey(resultT)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, `%obj.${member}`, key); + helper = `%obj.${member}.${lowerer.arrHofHelpers.size}`; 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 }; @@ -9151,7 +9150,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 ?? keyedHelperName(lowerer, "%arrow.bind", key); + const name = existing ?? `%arrow.bind.${lowerer.arrHofHelpers.size}`; if (!existing) { lowerer.arrHofHelpers.set(key, name); lowerer.freshClosureAdapters.add(name); @@ -10080,7 +10079,7 @@ function lowerUnionObjectDynFieldCall( const receiverRef = varRef(receiverLocal.id, receiverT, loc); let helper = lowerer.unionCallHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%union.call", key); + helper = `%union.call.${lowerer.unionCallHelpers.size}`; lowerer.unionCallHelpers.set(key, helper); const receiverRef = varRef("this.0", receiverT, loc); const branch = (plan: (typeof plans)[number]): IrStmt[] => { @@ -10173,7 +10172,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 = keyedHelperName(lowerer, "%union.call", key); + const name = `%union.call.${lowerer.unionCallHelpers.size}`; 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. @@ -10367,7 +10366,7 @@ export function lowerStaticNumberGlobal( const key = `parseInt.optional:${unionT.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%parseInt.optional", key); + helper = `%parseInt.optional.${lowerer.valueHelpers.size}`; 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 }; diff --git a/packages/compiler/src/frontend/lowering/lower-classes.ts b/packages/compiler/src/frontend/lowering/lower-classes.ts index fcea03790..790efe988 100644 --- a/packages/compiler/src/frontend/lowering/lower-classes.ts +++ b/packages/compiler/src/frontend/lowering/lower-classes.ts @@ -1,4 +1,3 @@ -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"; @@ -4664,7 +4663,7 @@ export function genericClassInstanceType( ); } const ordinal = gci.instances.size; - const name = keyedHelperName(lowerer, `${gci.family.def.name}%`, key, ""); + const name = `${gci.family.def.name}%${ordinal}`; const entry: { name: string; info: ClassInfo | null; poisoned?: boolean } = { name, info: null }; gci.instances.set(key, entry); const bindings = new Map(); @@ -7911,7 +7910,7 @@ export function classIteratorDrainCall( const key = `${cit.className}:${typeKey(outElem)}`; let name = lowerer.iterDrainHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%iter.drain", key); + name = `%iter.drain.${lowerer.iterDrainHelpers.size}`; lowerer.iterDrainHelpers.set(key, name); const recvT: IrType = { kind: "object", className: cit.className }; const recvRef: IrExpr = { kind: "varRef", localId: "r.0", type: recvT, loc }; @@ -8025,7 +8024,7 @@ export function classIteratorRestDrainCall( const key = `it:${cit.iterT.className}`; let name = lowerer.iterDrainHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%iter.drain", key); + name = `%iter.drain.${lowerer.iterDrainHelpers.size}`; 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 }; @@ -10533,7 +10532,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 = keyedHelperName(lowerer, "%x509.record", key); + helper = `%x509.record.${lowerer.valueHelpers.size}`; 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 aa90fc7c7..5c99ebc82 100644 --- a/packages/compiler/src/frontend/lowering/lower-dgram.ts +++ b/packages/compiler/src/frontend/lowering/lower-dgram.ts @@ -1,4 +1,3 @@ -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 @@ -358,7 +357,7 @@ function checkedDynPromise( const key = `dns.promise:${typeKey(declared)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%dns.promise", key); + helper = `%dns.promise.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, helper); const promiseT: IrType = { kind: "promise", inner: DYN }; lowerer.liftedFns.push({ @@ -892,7 +891,7 @@ export function lowerPromisifiedDnsCall( const key = `dnsPromise:${JSON.stringify(value)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%dnsPromise", key); + name = `%dnsPromise.${lowerer.valueHelpers.size}`; 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 f105af786..f472672b2 100644 --- a/packages/compiler/src/frontend/lowering/lower-event-emitter.ts +++ b/packages/compiler/src/frontend/lowering/lower-event-emitter.ts @@ -42,7 +42,6 @@ * 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"; @@ -632,7 +631,7 @@ function lowerFlexListenerCall( const key = `emitter.${registering ? "onFlex" : "offDyn"}:${typeKey(recvT)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, `%emitter.${registering ? "onFlex" : "offFlex"}`, key); + helper = `%emitter.${registering ? "onFlex" : "offFlex"}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const params: IrParam[] = [ { localId: "r.0", name: "r", type: recvT }, @@ -851,7 +850,7 @@ function lowerDynListenerCall( const existing = lowerer.arrHofHelpers.get(key); let helper = existing; if (!helper) { - helper = keyedHelperName(lowerer, `%emitter.${registering ? "onDyn" : "offDyn"}`, key); + helper = `%emitter.${registering ? "onDyn" : "offDyn"}.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const check: IrStmt = { kind: "exprStmt", @@ -1001,7 +1000,7 @@ export function lowerDynamicEmitterEmit( const key = `emitter.dynEmit:${typeKey(recvT)}:${k}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%emitter.dynEmit", key); + helper = `%emitter.dynEmit.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const params: IrParam[] = [ { localId: "r.0", name: "r", type: recvT }, @@ -1093,7 +1092,7 @@ export function lowerDynamicEmitterOn( const key = `emitter.dynOn:${typeKey(recvT)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%emitter.dynOn", key); + helper = `%emitter.dynOn.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const params: IrParam[] = [ { localId: "r.0", name: "r", type: recvT }, @@ -2360,7 +2359,7 @@ function emitDispatchExpr( const key = `emitter.emitDispatch:${typeKey(recvT)}:${name}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = keyedHelperName(lowerer, "%emitter.emitDispatch", key); + helper = `%emitter.emitDispatch.${lowerer.arrHofHelpers.size}`; lowerer.arrHofHelpers.set(key, helper); const params: IrParam[] = [ { localId: "r.0", name: "r", type: recvT }, @@ -2425,7 +2424,7 @@ function eventsOnceBoxer( const key = `eventsOnce:${typeKey(fnType)}`; let name = lowerer.valueHelpers.get(key); if (name === undefined) { - name = keyedHelperName(lowerer, "%events.onceArgs", key); + name = `%events.onceArgs.${lowerer.valueHelpers.size}`; 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 ba96bea8c..e7a1b79a8 100644 --- a/packages/compiler/src/frontend/lowering/lower-exprs.ts +++ b/packages/compiler/src/frontend/lowering/lower-exprs.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { lowerWebAssemblyValue, refuseWebAssemblyUse } from "./builtins/webassembly.js"; import { dynUndefinedExpr, nodeThrowExpr, numLit, strLit, varRef } from "../../ir/build.js"; import { InternalCompilerError } from "../../errors.js"; @@ -2275,11 +2274,7 @@ 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 at = locOf(getter); - const snapshot = { - id: keyedHelperName(lowerer, "%g.cjsSnapshot", `${at.file}:${at.start}:${at.end}`), - type: call.type, - }; + const snapshot = { id: `%g.cjsSnapshot.${lowerer.cjsAccessorSnapshots.size}`, type: call.type }; lowerer.globalsList.push({ id: snapshot.id, name: "%cjsSnapshot", @@ -2304,7 +2299,7 @@ export function cjsAccessorSnapshotStores( if (getters.length === 0) return []; let readyId = lowerer.cjsSnapshotReady.get(dep); if (readyId === undefined) { - readyId = keyedHelperName(lowerer, "%g.cjsSnapshotReady", dep.fileName); + readyId = `%g.cjsSnapshotReady.${lowerer.cjsSnapshotReady.size}`; lowerer.globalsList.push({ id: readyId, name: "%cjsSnapshotReady", type: BOOL, mutable: true }); lowerer.cjsSnapshotReady.set(dep, readyId); } diff --git a/packages/compiler/src/frontend/lowering/lower-functions.ts b/packages/compiler/src/frontend/lowering/lower-functions.ts index 653c0d837..cd8dc31d1 100644 --- a/packages/compiler/src/frontend/lowering/lower-functions.ts +++ b/packages/compiler/src/frontend/lowering/lower-functions.ts @@ -270,7 +270,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 = lowerer.closureName(locOf(node), baseName ? `_${baseName}` : ""); + const fnName = `%fn${lowerer.lambdaCounter++}${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 = diff --git a/packages/compiler/src/frontend/lowering/lower-inspect.ts b/packages/compiler/src/frontend/lowering/lower-inspect.ts index 1979b43aa..4be5d0b7e 100644 --- a/packages/compiler/src/frontend/lowering/lower-inspect.ts +++ b/packages/compiler/src/frontend/lowering/lower-inspect.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { dynUndefinedExpr, boolLit, @@ -269,7 +268,7 @@ function errorInspectHelper( const key = `insp.userError:${typeKey(t)}`; const existing = lowerer.inspectHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, "%util.insp", key); + const name = `%util.insp.${lowerer.inspectHelpers.size}`; lowerer.inspectHelpers.set(key, name); const v = (): IrExpr => varRef("v.0", t, loc); const r = (): IrExpr => varRef("r.0", F64, loc); @@ -1146,7 +1145,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 = keyedHelperName(lowerer, "%util.insp", key); + const name = `%util.insp.${lowerer.inspectHelpers.size}`; lowerer.inspectHelpers.set(key, name); const v = (): IrExpr => varRef("v.0", t, loc); @@ -2075,7 +2074,7 @@ function formatUnionHelper( const existing = lowerer.inspectHelpers.get(key); if (existing) return existing; const loc = helperLoc(site); - const name = keyedHelperName(lowerer, "%util.fmtv", key); + const name = `%util.fmtv.${lowerer.inspectHelpers.size}`; 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 9de027563..766059dfb 100644 --- a/packages/compiler/src/frontend/lowering/lower-mixins.ts +++ b/packages/compiler/src/frontend/lowering/lower-mixins.ts @@ -34,7 +34,6 @@ * 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"; @@ -453,7 +452,7 @@ function instantiateMixinCall( const base = mixinBaseClassOf(lowerer, call.arguments.nodes[0]!); const instName = lowerer.qualify( ts.getSourceFileOfNode(call), - `%mx${positionTag(lowerer, call)}.${shape.classNode.name?.text ?? ""}`, + `%mx${ts.tokenStartOfNode(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 8c50dee46..fcc68c787 100644 --- a/packages/compiler/src/frontend/lowering/lower-mock.ts +++ b/packages/compiler/src/frontend/lowering/lower-mock.ts @@ -17,7 +17,6 @@ * 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, @@ -137,7 +136,7 @@ function liftOnce( const key = `mock.${role}:${owner}`; const existing = lowerer.assertHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, `%mock.${role}`, key); + const name = `%mock.${role}.${lowerer.assertHelpers.size}`; 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 f1021e4da..84cc96e7d 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).sort(); + const wanted = lowerer.shapes.shapes.map((shape) => shape.id); 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).sort(); + const wanted = lowerer.shapes.shapes.map((shape) => shape.id); 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 0b99e88d3..d1f276d44 100644 --- a/packages/compiler/src/frontend/lowering/lower-modules.ts +++ b/packages/compiler/src/frontend/lowering/lower-modules.ts @@ -1,5 +1,4 @@ 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"; @@ -1075,14 +1074,8 @@ export function moduleArtifacts( else delete rest.abstractMethods; return rest; }), - // 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)), + records: lowerer.shapes.shapes.filter((r) => shapeIds.has(r.id)), + unions: lowerer.unions.unions.filter((u) => unionIds.has(u.id)), }; } @@ -1684,7 +1677,7 @@ export function collectGlobals( } if (type.kind === "void") lowerer.badType(stmt.name, lowerer.typeOf(stmt.name)); const g: IrGlobal = { - id: `%g.${tag}${nsPathPrefix(lowerer, stmt)}%alias.${stmt.name.text}%${positionTag(lowerer, stmt)}`, + id: `%g.${tag}${nsPathPrefix(stmt)}%alias.${stmt.name.text}%${ts.tokenStartOfNode(stmt)}`, name: stmt.name.text, type, mutable: false, @@ -1761,7 +1754,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(lowerer, stmt, list.declarations.nodes[0]); + const nsPrefix = nsPathPrefix(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 diff --git a/packages/compiler/src/frontend/lowering/lower-namespaces.ts b/packages/compiler/src/frontend/lowering/lower-namespaces.ts index 19123dae3..dca835d77 100644 --- a/packages/compiler/src/frontend/lowering/lower-namespaces.ts +++ b/packages/compiler/src/frontend/lowering/lower-namespaces.ts @@ -36,7 +36,6 @@ * 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 type { Lowerer } from "./lowerer.js"; @@ -165,11 +164,7 @@ 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( - owner: PositionTagOwner, - node: ts.Node, - modifierDecl?: ts.Node, -): string { +export function nsPathPrefix(node: ts.Node, modifierDecl?: ts.Node): string { const parent = node.parent; if (parent === undefined || !ts.isModuleBlock(parent)) return ""; const flagsHost = modifierDecl ?? node; @@ -184,10 +179,10 @@ export function nsPathPrefix( 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 ? `%${positionTag(owner, p)}` : "")); + segs.unshift(p.name.text + (nonExported ? `%${ts.tokenStartOfNode(p)}` : "")); } } - return `${segs.join("%")}${exported ? "" : `%${positionTag(owner, parent)}`}.`; + return `${segs.join("%")}${exported ? "" : `%${ts.tokenStartOfNode(parent)}`}.`; } /** The registered namespace-block kind a symbol's declaration sits in diff --git a/packages/compiler/src/frontend/lowering/lower-server.ts b/packages/compiler/src/frontend/lowering/lower-server.ts index 94d49d8b3..058d7874a 100644 --- a/packages/compiler/src/frontend/lowering/lower-server.ts +++ b/packages/compiler/src/frontend/lowering/lower-server.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { dynUndefinedExpr, nodeThrowExpr, @@ -184,7 +183,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 ?? keyedHelperName(lowerer, "%server.voidcb", key); + const name = existing ?? `%server.voidcb.${lowerer.arrHofHelpers.size}`; if (!existing) { lowerer.arrHofHelpers.set(key, name); const impl = `${name}.impl`; @@ -280,7 +279,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 ?? keyedHelperName(lowerer, "%server.recvret", key); + const name = existing ?? `%server.recvret.${lowerer.arrHofHelpers.size}`; if (!existing) { lowerer.arrHofHelpers.set(key, name); const params = callArgs.map((a, i) => ({ localId: `p${i}.0`, name: `p${i}`, type: a.type })); @@ -591,7 +590,7 @@ function h2HeadersCallbackAdapter( ); const key = `h2.hdrcb:${handleKind}:${withStatus}:${typeKey(fromT)}:${shapeId ?? ""}`; const existing = lowerer.arrHofHelpers.get(key); - const name = existing ?? keyedHelperName(lowerer, "%h2.hdrcb", key); + const name = existing ?? `%h2.hdrcb.${lowerer.arrHofHelpers.size}`; if (!existing) { lowerer.arrHofHelpers.set(key, name); const impl = `${name}.impl`; @@ -3584,7 +3583,7 @@ export function lowerCompatReqStreamOptionalCall( type: unionT, loc, }; - const id = lowerer.closureName(loc, "", "chain"); + const id = `chain.${lowerer.chainCounter++}`; const body = lowerH2StreamMethodCall(lowerer, call, call.expression, { kind: "chainRecv", id, @@ -4425,7 +4424,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 ?? keyedHelperName(lowerer, "%server.opts", key); + const name = existing ?? `%server.opts.${lowerer.arrHofHelpers.size}`; if (!existing) { lowerer.arrHofHelpers.set(key, name); const params = [ @@ -8010,7 +8009,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 ?? keyedHelperName(lowerer, "%server.endcb", key); + const helper = existing ?? `%server.endcb.${lowerer.arrHofHelpers.size}`; 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 0beb24a0e..2ad3657c7 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 = lowerer.closureName(loc, "_staticImport"); + const fnName = `%fn${lowerer.lambdaCounter++}_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-stream.ts b/packages/compiler/src/frontend/lowering/lower-stream.ts index a75ec43b7..b9add95a6 100644 --- a/packages/compiler/src/frontend/lowering/lower-stream.ts +++ b/packages/compiler/src/frontend/lowering/lower-stream.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { nodeThrowExpr, boolLit, numLit, strLit } from "../../ir/build.js"; import { hashStreamOf, isHashValueType } from "./builtins/hash-stream.js"; import { InternalCompilerError } from "../../errors.js"; @@ -312,7 +311,7 @@ function lowerStreamCallback( ); } } - const fnName = lowerer.closureName(loc, `_${which}cb`); + const fnName = `%fn${lowerer.lambdaCounter++}_${which}cb`; const fnCtx = newFnCtx(true, null, funcType, funcType.ret); lowerer.fnStack.push(fnCtx); try { @@ -1145,7 +1144,7 @@ function streamMethodWrapper( paramTypes.push(got.type); } const ret = found.sig.ret; - const fnName = lowerer.closureName(loc, `_${which}vt`); + const fnName = `%fn${lowerer.lambdaCounter++}_${which}vt`; const funcType = funcOf([thisType, ...paramTypes], ret); lowerer.fnStack.push(newFnCtx(true, null, funcType, ret)); try { @@ -1691,7 +1690,7 @@ function fromGenHelpers( const key = `streamFromGen:${role}:${typeKey(gen)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, `%stream.fromGen.${role}`, key); + name = `%stream.fromGen.${role}.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -1780,7 +1779,7 @@ function classIteratorObject( const key = `streamFromIter:${cit.iterT.className}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%stream.fromIter", key); + name = `%stream.fromIter.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const nextName = `${name}.next`; const nextT = funcOf([], DYN); @@ -1941,7 +1940,7 @@ function classAsyncIteratorObject( const key = `streamFromAsyncIter:${cit.className}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%stream.fromAsyncIter", key); + name = `%stream.fromAsyncIter.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const it: IrLocal = { id: "it.0", name: "it", type: cit.iterT, mutable: false, boxed: true }; const src: IrLocal = { @@ -2895,7 +2894,7 @@ function pipelineBoxHelper( const key = `pipelineBox:${typeKey(promiseT)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = keyedHelperName(lowerer, "%stream.pipelineBox", key); + name = `%stream.pipelineBox.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -2922,7 +2921,7 @@ function pipelineAbortHelper(lowerer: Lowerer, ac: IrExpr, loc: SrcLoc): IrExpr let name = lowerer.valueHelpers.get(key); const abortT = funcOf([], VOID); if (!name) { - name = keyedHelperName(lowerer, "%stream.pipelineAbort", key); + name = `%stream.pipelineAbort.${lowerer.valueHelpers.size}`; 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); diff --git a/packages/compiler/src/frontend/lowering/lower-timers.ts b/packages/compiler/src/frontend/lowering/lower-timers.ts index 03c9c5c1f..7d4bba34b 100644 --- a/packages/compiler/src/frontend/lowering/lower-timers.ts +++ b/packages/compiler/src/frontend/lowering/lower-timers.ts @@ -1,4 +1,3 @@ -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"; @@ -56,7 +55,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 ?? keyedHelperName(lowerer, "%timer.dropret", key); + const name = existing ?? `%timer.dropret.${lowerer.arrHofHelpers.size}`; if (!existing) { lowerer.arrHofHelpers.set(key, name); lowerer.liftedFns.push( @@ -118,7 +117,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 ?? keyedHelperName(lowerer, "%timer.droparg", key); + const name = existing ?? `%timer.droparg.${lowerer.arrHofHelpers.size}`; if (!existing) { lowerer.arrHofHelpers.set(key, name); lowerer.liftedFns.push( @@ -204,7 +203,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 ?? keyedHelperName(lowerer, "%timer.argsthunk", key); + const name = existing ?? `%timer.argsthunk.${lowerer.arrHofHelpers.size}`; 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 7fbb9661f..bacdc7941 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.test.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.test.ts @@ -10,7 +10,6 @@ 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 }; @@ -33,7 +32,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, () => "Recursive"); + lowerer.shapes.recursiveRef(recursive); lowerer.shapes.finalizeRecursive(recursive, [{ name: "kind", type: STRING }]); expect(lowerer.unionRetagHelper(from, to, loc)).toBe(helper); expect(plan).toHaveBeenCalled(); @@ -55,7 +54,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, () => "Recursive"); + const to = lowerer.unions.recursiveRef(recursive); const trapped = lowerer.unionRetagHelper(from, to, loc); expect(trapped).not.toBeNull(); lowerer.unions.finalizeRecursive(recursive, [UNDEFINED_T]); @@ -76,7 +75,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, () => "Recursive")); + const target = record(lowerer.shapes.recursiveRef(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(); @@ -130,7 +129,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, () => "Recursive")); + const pendingShape = record(lowerer.shapes.recursiveRef(recursive)); const pending = lowerer.unions.intern([pendingShape], { field: "kind", cases: [{ tag: 0, values: ["a"] }], @@ -144,7 +143,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, () => "Recursive"); + const union = lowerer.unions.recursiveRef(recursive); const shape = record(lowerer.shapes.intern([{ name: "kind", type: STRING }])); expect(lowerer.literalUnionArm(union, ["ready"])).toBeNull(); lowerer.unions.finalizeRecursive(recursive, [shape], { @@ -183,10 +182,7 @@ test("removing undefined reuses the discriminator transformation without hiding ); const recursive = {} as Type; - const pending: IrType = { - kind: "union", - unionId: lowerer.unions.recursiveRef(recursive, () => "Recursive"), - }; + const pending: IrType = { kind: "union", unionId: lowerer.unions.recursiveRef(recursive) }; expect(lowerer.stripUndefinedArm(pending)).toEqual(pending); lowerer.unions.finalizeRecursive(recursive, [STRING, UNDEFINED_T]); expect(lowerer.stripUndefinedArm(pending)).toEqual(STRING); @@ -219,10 +215,7 @@ 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, () => "Recursive"), - }; + const pending: IrType = { kind: "union", unionId: lowerer.unions.recursiveRef(recursive) }; const before = lowerer.withUndefinedArmOf(pending); lowerer.unions.finalizeRecursive(recursive, [a, b], discriminant); expect(lowerer.withUndefinedArmOf(pending)).toEqual(added); @@ -234,18 +227,13 @@ 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, () => "Recursive"), - }; + const pending: IrType = { kind: "union", unionId: lowerer.unions.recursiveRef(recursive) }; expect(lowerer.withUndefinedArmOf(pending)).not.toBeNull(); lowerer.unions.finalizeRecursive(recursive, [{ kind: "date" }, STRING]); expect(lowerer.withUndefinedArmOf(pending)).toBeNull(); expect(lowerer.withUndefinedArmOf(pending)).toBeNull(); - // 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]) }; + const missing: IrType = { kind: "union", unionId: `u${lowerer.unions.unions.length}` }; 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 3f8a0a66e..ee8ba7ecb 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -1,6 +1,4 @@ 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, @@ -1006,11 +1004,6 @@ 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, @@ -2808,8 +2801,6 @@ 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(); @@ -2946,6 +2937,7 @@ 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(); @@ -3175,47 +3167,7 @@ export class Lowerer { * dispatch revision needs no weak-key identity or process-global state. */ errorMethodDispatchRevision: string | null = null; errorPropertyDispatchRevision: string | null = null; - /** Structural source positions (structural-positions.ts) for names that - * stay the same when unrelated code moves. */ - readonly positions = new StructuralPositions(); - - /** 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; - } - + lambdaCounter = 0; readonly preparedClassFactories = new Map(); readonly preparingClassFactories = new Set(); @@ -3568,7 +3520,6 @@ 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, @@ -3857,11 +3808,11 @@ export class Lowerer { })() ? this.qualify( ts.getSourceFileOfNode(decl), - `%cx${positionTag(this, decl)}.${decl.name?.text ?? ""}`, + `%cx${ts.tokenStartOfNode(decl)}.${decl.name?.text ?? ""}`, ) : this.qualify( ts.getSourceFileOfNode(decl), - nsPathPrefix(this, decl) + (decl.name ? decl.name.text : "%anon"), + nsPathPrefix(decl) + (decl.name ? decl.name.text : "%anon"), ); for (let index = this.localClassInstantiations.length - 1; index >= 0; index--) { const entry = this.localClassInstantiations[index]!; @@ -7420,10 +7371,7 @@ export class Lowerer { } for (const decl of fp.classDecls) { const info = this.classes.get(this.classNamer(decl)); - if (info) - functions.push( - ...this.withClosureRoot(info.def.name, () => this.lowerClassMembers(info)), - ); + if (info) functions.push(...this.lowerClassMembers(info)); else if (this.countsSkips()) this.countSkippedBody(decl); } } @@ -7436,10 +7384,7 @@ export class Lowerer { // are reachable by definition, already counted by reachable emit. if (!this.remainder) { for (const fp of parts) { - const initName = this.initNameOf.get(fp.sf)!; - functions.push( - this.withClosureRoot(initName, () => this.lowerFileInit(fp.sf, fp.topStmts, initName)), - ); + functions.push(this.lowerFileInit(fp.sf, fp.topStmts, this.initNameOf.get(fp.sf)!)); } functions.push(this.buildMain()); } @@ -7481,9 +7426,7 @@ export class Lowerer { // default): the diagnostic is recorded — the instance skips // like a signature-blocked function (lowerFunction's rule). try { - functions.push( - this.withClosureRoot(inst.name, () => this.lowerGenericInstance(info, inst)), - ); + functions.push(this.lowerGenericInstance(info, inst)); } catch (e) { if (!(e instanceof PoisonError)) throw e; } @@ -7493,10 +7436,7 @@ export class Lowerer { // instances of its own; the joint fixpoint covers both). while (es < this.emitSpecQueue.length) { try { - const spec = this.emitSpecQueue[es++]!; - const fn = this.withClosureRoot(emitSpecRoot(spec), () => - lowerEmitOverrideSpec(this, spec), - ); + const fn = lowerEmitOverrideSpec(this, this.emitSpecQueue[es++]!); if (fn) functions.push(fn); } catch (e) { if (!(e instanceof PoisonError)) throw e; @@ -8050,9 +7990,7 @@ export class Lowerer { this.genericClassDemandPriority.set(info, ref); instanceFunctions.push( ...this.withGenericDemandOwner(owner, () => - this.shapes.withDeclaredOrderPriority(ref, () => - this.withClosureRoot(info.def.name, () => this.lowerClassMembers(info)), - ), + this.shapes.withDeclaredOrderPriority(ref, () => this.lowerClassMembers(info)), ), ); relieveHeapPressure(); @@ -8079,7 +8017,7 @@ export class Lowerer { instanceFunctions.push( this.withGenericDemandOwner(owner, () => this.shapes.withDeclaredOrderPriority(ref, () => - this.withClosureRoot(inst.name, () => this.lowerGenericInstance(info, inst)), + this.lowerGenericInstance(info, inst), ), ), ); @@ -8112,12 +8050,9 @@ export class Lowerer { ); while (specLowered < waveEnd) { try { - const fn = this.shapes.withDeclaredOrderPriority([4, instanceMetadataOrder++], () => { - const spec = this.emitSpecQueue[specLowered++]!; - return this.withClosureRoot(emitSpecRoot(spec), () => - lowerEmitOverrideSpec(this, spec), - ); - }); + const fn = this.shapes.withDeclaredOrderPriority([4, instanceMetadataOrder++], () => + lowerEmitOverrideSpec(this, this.emitSpecQueue[specLowered++]!), + ); if (fn) instanceFunctions.push(fn); } catch (e) { if (!(e instanceof PoisonError)) throw e; @@ -8145,9 +8080,7 @@ export class Lowerer { initFunctions.push( this.withGenericDemandOwner(owner, () => this.shapes.withDeclaredOrderPriority(priority, () => - this.withClosureRoot(this.initNameOf.get(fp.sf)!, () => - this.lowerFileInit(fp.sf, fp.topStmts, this.initNameOf.get(fp.sf)!), - ), + this.lowerFileInit(fp.sf, fp.topStmts, this.initNameOf.get(fp.sf)!), ), ), ); @@ -8173,9 +8106,7 @@ export class Lowerer { const priority = metadataPriority.get(name) ?? [3, expressionMetadataOrder++]; const owner = demandOwner(priority); const fn = this.withGenericDemandOwner(owner, () => - this.shapes.withDeclaredOrderPriority(priority, () => - this.withClosureRoot(name, unit.lower), - ), + this.shapes.withDeclaredOrderPriority(priority, unit.lower), ); if (fn) loweredUnits.set(name, fn); relieveHeapPressure(); @@ -13558,7 +13489,7 @@ export class Lowerer { const key = `${fn.valueFn ?? fn.fn}:${typeKey(funcType)}:${adapterShape}`; let fnName = this.builtinCallableValueFns.get(key); if (!fnName) { - fnName = keyedHelperName(this, `%builtin.value.${fn.valueFn ?? fn.fn}`, key); + fnName = `%builtin.value.${fn.valueFn ?? fn.fn}.${this.builtinCallableValueFns.size}`; 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/native-ffi.ts b/packages/compiler/src/frontend/lowering/native-ffi.ts index 62f2be9f1..0f932ba93 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 = lowerer.closureName(loc, "", "%ffi.module"); + const name = `%ffi.module.${lowerer.lambdaCounter++}`; 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 388ac3904..855da3bda 100644 --- a/packages/compiler/src/frontend/lowering/object-enumeration-receiver.ts +++ b/packages/compiler/src/frontend/lowering/object-enumeration-receiver.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { BOOL, STRING, @@ -28,7 +27,7 @@ export function objectEnumerationReceiver( const key = `obj.receiver:${source.unionId}:${expected.shapeId}`; let name = lowerer.arrHofHelpers.get(key); if (name === undefined) { - name = keyedHelperName(lowerer, "%obj.receiver", key); + name = `%obj.receiver.${lowerer.arrHofHelpers.size}`; 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 acf7b3bf9..3b33fb0cd 100644 --- a/packages/compiler/src/frontend/lowering/pairs-snapshot.ts +++ b/packages/compiler/src/frontend/lowering/pairs-snapshot.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { arrayOf, BOOL, @@ -50,7 +49,7 @@ export function pairsSnapshotHelper( const key = `${options.keyPrefix}.snapshot:${shapeId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = keyedHelperName(lowerer, `%${options.keyPrefix}.snapshot`, key); + const name = `%${options.keyPrefix}.snapshot.${lowerer.valueHelpers.size}`; lowerer.valueHelpers.set(key, name); const recordType: IrType = { kind: "record", shapeId }; const pairsType = arrayOf(STRING); diff --git a/packages/compiler/src/frontend/lowering/promise-executor-adapter.ts b/packages/compiler/src/frontend/lowering/promise-executor-adapter.ts index 84aa8dac0..09d228b05 100644 --- a/packages/compiler/src/frontend/lowering/promise-executor-adapter.ts +++ b/packages/compiler/src/frontend/lowering/promise-executor-adapter.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { varRef } from "../../ir/build.js"; import { type IrExpr, @@ -41,7 +40,7 @@ export function adaptPromiseExecutor( const key = `promise.executor:${typeKey(execT)}:${typeKey(inner)}`; let name = lowerer.arrHofHelpers.get(key); if (name === undefined) { - name = keyedHelperName(lowerer, "%promise.executor", key); + name = `%promise.executor.${lowerer.arrHofHelpers.size}`; 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 c8fc9c730..d979423b0 100644 --- a/packages/compiler/src/frontend/lowering/require-initialization.ts +++ b/packages/compiler/src/frontend/lowering/require-initialization.ts @@ -9,7 +9,6 @@ * 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 { @@ -120,7 +119,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.${positionTag(lowerer, decl)}`; + const flagId = `%g.${tag}%required.${ts.tokenStartOfNode(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 deleted file mode 100644 index 8f7d0967e..000000000 --- a/packages/compiler/src/frontend/lowering/stable-names.ts +++ /dev/null @@ -1,48 +0,0 @@ -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 8a87c8111..7b9b6902b 100644 --- a/packages/compiler/src/frontend/lowering/strict-equality.ts +++ b/packages/compiler/src/frontend/lowering/strict-equality.ts @@ -1,4 +1,3 @@ -import { keyedHelperName } from "./stable-names.js"; import { boolLit, varRef } from "../../ir/build.js"; import { BOOL, @@ -136,7 +135,7 @@ export function lowerUnionEquality( loc, ); if (!result) return null; - name = keyedHelperName(lowerer, "%value.eq", key); + name = `%value.eq.${lowerer.equalityHelpers.size}`; 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 deleted file mode 100644 index ea8535d9e..000000000 --- a/packages/compiler/src/frontend/lowering/structural-positions.ts +++ /dev/null @@ -1,107 +0,0 @@ -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(); - - /** 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 = 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/ts7/ast.ts b/packages/compiler/src/frontend/ts7/ast.ts index 0bddd1a80..369213d89 100644 --- a/packages/compiler/src/frontend/ts7/ast.ts +++ b/packages/compiler/src/frontend/ts7/ast.ts @@ -47,9 +47,8 @@ import { } from "./ast-guards.generated.js"; import type { Ts7DiagnosticData as Diagnostic } from "./session-schema.generated.js"; import { ModifierFlags, SyntaxKind } from "./enums.js"; -import { AstKind, KIND_NODE_LIST } from "./ast-schema.generated.js"; +import { AstKind } 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 ---- */ @@ -197,93 +196,6 @@ 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/type-mapper.test.ts b/packages/compiler/src/frontend/type-mapper.test.ts index 163ba7b9e..cf78554b4 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, () => "Recursive"); + const union = unions.recursiveRef(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 79091cadc..a233f0186 100644 --- a/packages/compiler/src/frontend/type-mapper.ts +++ b/packages/compiler/src/frontend/type-mapper.ts @@ -1,5 +1,4 @@ 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"; @@ -253,8 +252,6 @@ 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 @@ -273,7 +270,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 order. */ + /** All interned shapes in first-seen (`r0`, `r1`, ...) order. */ readonly shapes: IrRecordShape[] = []; /** ts.Types currently being mapped — a BACK-REFERENCE to one of these is * the recursive knot (`interface TreeNode { children: TreeNode[] }`): @@ -393,12 +390,11 @@ 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. `describe` names a new - * placeholder (recursiveTypeName). */ - recursiveRef(t: ts.Type, describe: () => string): string { + * entry (empty fields) the outer frame finalizes. */ + recursiveRef(t: ts.Type): string { let id = this.recIds.get(t); if (id === undefined) { - id = recursivePlaceholderName(this, "r", describe(), (name) => this.byId.has(name)); + id = `r${this.shapes.length}`; const shape: IrRecordShape = { id, fields: [] }; this.byId.set(id, shape); this.shapes.push(shape); @@ -467,7 +463,7 @@ export class ShapeRegistry { const key = this.keyOf(fields, tuple, indexValue); let id = this.byKey.get(key); if (id === undefined) { - id = keyedHelperName(this, "r", key, ""); + id = `r${this.shapes.length}`; const shape: IrRecordShape = { id, fields, @@ -545,57 +541,6 @@ export class ShapeRegistry { } } -/** The id of a recursive placeholder described by `description`. Two - * different types can still share a description (recursiveTypeName 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 recursiveTypeName describes. */ -const RECURSIVE_NAME_DEPTH = 3; - -/** A recursive checker type's description, which names its placeholder - * whichever frame first reaches it: 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). */ -function recursiveTypeName( - 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) => recursiveTypeName(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. @@ -603,12 +548,10 @@ function recursiveTypeName( 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 order. */ + /** All interned unions in first-seen (`u0`, `u1`, ...) 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` @@ -624,12 +567,11 @@ 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. `describe` names a new - * placeholder (recursiveTypeName). */ - recursiveRef(t: ts.Type, describe: () => string): string { + * entry (empty arms) the outer frame finalizes. */ + recursiveRef(t: ts.Type): string { let id = this.recIds.get(t); if (id === undefined) { - id = recursivePlaceholderName(this, "u", describe(), (name) => this.byId.has(name)); + id = `u${this.unions.length}`; const def: IrUnionDef = { id, arms: [] }; this.byId.set(id, def); this.unions.push(def); @@ -679,7 +621,7 @@ export class UnionRegistry { const key = JSON.stringify([arms.map(typeKey), discriminant]); let id = this.byKey.get(key); if (id === undefined) { - id = keyedHelperName(this, "u", key, ""); + id = `u${this.unions.length}`; const def: IrUnionDef = { id, arms, ...(discriminant ? { discriminant } : {}) }; this.byKey.set(key, id); this.byId.set(id, def); @@ -1173,10 +1115,6 @@ export interface TypeMapperCtx { * empty object type rule in the object mapping). */ emptyLiteralArm?: boolean; 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. */ @@ -4713,10 +4651,7 @@ 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, () => recursiveTypeName(widened, ctx)), - }; + return { kind: "union", unionId: unions.recursiveRef(widened) }; } unions.inProgress.add(widened); const sensitivityAtEntry = contextResolutions; @@ -7060,10 +6995,7 @@ 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, () => recursiveTypeName(widened, ctx)), - }; + return { kind: "record", shapeId: shapes.recursiveRef(widened) }; } shapes.inProgress.add(widened); const sensitivityAtEntry = contextResolutions; diff --git a/packages/compiler/test/array-pipeline-fusion.test.ts b/packages/compiler/test/array-pipeline-fusion.test.ts index 55cd0025e..f5d743265 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(/\.[0-9a-f]+$/, "")); + calls.push(e.callee.replace(/\.\d+$/, "")); return true; }, stmt: () => true, diff --git a/packages/compiler/test/format-float-arguments.test.ts b/packages/compiler/test/format-float-arguments.test.ts index 6ce9c4bc0..e59e023ca 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(/\.[0-9a-f]+$/, "")) + .map((name) => name.replace(/\.\d+$/, "")) .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 589685a7a..aebbb2ea4 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_[0-9a-f]+/); + const helper = body(llvm, /sc_b?f__x25_rec_haskey_\d+/); 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/stable-names.test.ts b/packages/compiler/test/stable-names.test.ts deleted file mode 100644 index 720472556..000000000 --- a/packages/compiler/test/stable-names.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -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); -}); diff --git a/packages/compiler/test/type-mapper-unions.test.ts b/packages/compiler/test/type-mapper-unions.test.ts index 684960002..c714df4d7 100644 --- a/packages/compiler/test/type-mapper-unions.test.ts +++ b/packages/compiler/test/type-mapper-unions.test.ts @@ -139,8 +139,7 @@ describe("checker and synthesized optional union identity", () => { nullable.arms.filter((arm) => arm.kind !== "nullT" && arm.kind !== "undefinedT"), ), ).toBe(required.unionId); - // Cases follow the arms, which are ordered by their type keys. - expect(nullable.discriminant!.cases.map((entry) => entry.values).sort()).toEqual([ + expect(nullable.discriminant!.cases.map((entry) => entry.values)).toEqual([ ["a", "alias"], ["b"], ]); From d426960f454e86bc8f53226e59b5a4db256f317c Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 01:55:38 -0500 Subject: [PATCH 028/102] Make Cipheriv and Decipheriv Transforms and accept function stages anywhere in pipeline() Cipheriv and Decipheriv values are Transforms, as in Node: they can be written and ended, piped into, used as pipeline() and stream/promises pipeline stages, composed, read, iterated with for await, read by stream/consumers, passed to finished(), and listened to, and their stream properties read as in Node. Each chunk goes through the cipher's update(), and the end pushes final() or reports its error through 'error'; writing after final() throws out of write(). The stream unit builds a cipher's Transform on its first stream use from operations the cipher's handle provides (ScrDynHandleOps.transform), so programs that use ciphers without streams link as before. The cipher is a collector-headered object behind a traced handle: its Transform's steps hold it, and the pair is reclaimed as a cycle. Through untyped values, in a program that uses streams, a cipher's stream properties and its on, once, off, pipe, unpipe, read, pause, resume, setEncoding, write, end, destroy, cork and uncork members run on its Transform; other stream members throw a coded SC2020 error. A Transform holds a write's callback while its readable side is at the high-water mark and runs it at the next read, and runs it on a tick once the readable side has ended, as Transform._write does. write() on a PassThrough, a Transform, a Hash or a cipher used to return true however much the readable side buffered. zlib streams applied the rule already and keep their timing. pipeline() accepts function stages anywhere among its streams, so runs of async generator stages can sit on both sides of a stream. A stage can be named by a function declaration, or a const bound to a function expression, that nothing reassigns; its body lowers again at the pipeline with its source typed by the pipeline. The source can also be an array, a string, a synchronous generator object, or a synchronous generator function without parameters: an async generator steps the source's iterator and yields each element, and the next stage receives each element on the same tick as with Node's for await over the source. The runtime's function-stage entry points take a bitmask of the function positions and one (next, read, return) helper triple for each generator pumped into a stream, so RUNTIME_ABI_VERSION is now 25. In JavaScript, the chunks a stage receives from the previous stage's generator read as the strings or Buffers it yields, so their string and Buffer methods compile. Corpus 7055-7059 cover cipher streams in TypeScript and JavaScript, their errors, close order and backpressure, the pipeline stages and sources with their tick order, and Transform backpressure. --- .../limitations/builtin-apis/crypto.mdx | 5 +- .../builtin-apis/streams-and-readline.mdx | 8 +- .../src/generated/node-v24-compatibility.json | 24 +- .../generated/node-v24-internal.json | 45 ++ internal/compatibility/src/generate.mjs | 2 +- internal/compatibility/static-support.json | 6 +- packages/cli/test/native-link-info.test.ts | 4 +- .../ambient/scriptc-node-fallback.d.ts | 7 +- .../compiler/src/backend/llvm/lib-shared.ts | 1 + .../compiler/src/backend/llvm/lib-stream.ts | 29 +- packages/compiler/src/backend/runtime-abi.ts | 4 +- .../src/backend/runtime-pack-targets.test.ts | 2 +- .../compiler/src/backend/runtime-pack.test.ts | 2 +- .../src/frontend/lowering/binding-analysis.ts | 10 +- .../src/frontend/lowering/builtins/crypto.ts | 5 +- .../frontend/lowering/builtins/hash-stream.ts | 133 +++++- .../src/frontend/lowering/containers/bytes.ts | 11 +- .../lowering/containers/iterator-helpers.ts | 4 +- .../src/frontend/lowering/dyn-streams.ts | 2 +- .../lowering/expressions/property-access.ts | 3 + .../src/frontend/lowering/lower-stmts.ts | 10 +- .../src/frontend/lowering/lower-stream.ts | 424 ++++++++++++++---- .../compiler/src/frontend/lowering/lowerer.ts | 15 +- packages/compiler/src/ir/builtin-effects.ts | 1 + .../compiler/src/ir/builtin-signatures.ts | 35 +- packages/compiler/src/ir/runtime-features.ts | 1 + packages/compiler/src/ir/validate.ts | 33 +- .../test/native-codegen-integration.test.ts | 4 +- .../tests/corpus/7055-cipher-streams.ts.json | 6 + .../corpus/7056-cipher-stream-errors.ts.json | 6 + .../tests/corpus/7057-cipher-streams.mjs.json | 6 + .../7058-pipeline-function-stages.mjs.json | 6 + .../7059-transform-backpressure.ts.json | 6 + .../runtime-darwin-arm64/scripts/build.mjs | 2 +- .../runtime-pack-common/scripts/build.mjs | 2 +- packages/runtime/src/scr_cipher.c | 132 +++++- packages/runtime/src/scr_console.c | 2 +- packages/runtime/src/scr_core.h | 2 +- packages/runtime/src/scr_dyn.h | 29 ++ packages/runtime/src/scr_json.c | 3 + packages/runtime/src/scr_stream.c | 386 ++++++++++++---- packages/runtime/src/scr_stream.h | 64 +-- packages/runtime/src/scr_stream_dyn.c | 5 +- packages/runtime/src/scr_zlib_stream.c | 3 +- tests/corpus/7055-cipher-streams.ts | 182 ++++++++ tests/corpus/7056-cipher-stream-errors.ts | 111 +++++ tests/corpus/7057-cipher-streams.mjs | 85 ++++ .../corpus/7058-pipeline-function-stages.mjs | 180 ++++++++ tests/corpus/7059-transform-backpressure.ts | 90 ++++ .../corpus-costs/7055-cipher-streams.ts.json | 1 + .../7056-cipher-stream-errors.ts.json | 1 + .../corpus-costs/7057-cipher-streams.mjs.json | 1 + .../7058-pipeline-function-stages.mjs.json | 1 + .../7059-transform-backpressure.ts.json | 1 + .../self-hosting-native-toolchain.test.ts | 2 +- 55 files changed, 1803 insertions(+), 342 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7055-cipher-streams.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7056-cipher-stream-errors.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7057-cipher-streams.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7058-pipeline-function-stages.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7059-transform-backpressure.ts.json create mode 100644 tests/corpus/7055-cipher-streams.ts create mode 100644 tests/corpus/7056-cipher-stream-errors.ts create mode 100644 tests/corpus/7057-cipher-streams.mjs create mode 100644 tests/corpus/7058-pipeline-function-stages.mjs create mode 100644 tests/corpus/7059-transform-backpressure.ts create mode 100644 tests/harness/corpus-costs/7055-cipher-streams.ts.json create mode 100644 tests/harness/corpus-costs/7056-cipher-stream-errors.ts.json create mode 100644 tests/harness/corpus-costs/7057-cipher-streams.mjs.json create mode 100644 tests/harness/corpus-costs/7058-pipeline-function-stages.mjs.json create mode 100644 tests/harness/corpus-costs/7059-transform-backpressure.ts.json diff --git a/docs/content/limitations/builtin-apis/crypto.mdx b/docs/content/limitations/builtin-apis/crypto.mdx index 3c830c63d..9ca6bfff4 100644 --- a/docs/content/limitations/builtin-apis/crypto.mdx +++ b/docs/content/limitations/builtin-apis/crypto.mdx @@ -8,7 +8,10 @@ `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, and GCM modes 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. diff --git a/docs/content/limitations/builtin-apis/streams-and-readline.mdx b/docs/content/limitations/builtin-apis/streams-and-readline.mdx index a21f7a617..b7c2e062e 100644 --- a/docs/content/limitations/builtin-apis/streams-and-readline.mdx +++ b/docs/content/limitations/builtin-apis/streams-and-readline.mdx @@ -3,14 +3,16 @@ `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. 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. + `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 })`), 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. + An async generator function as the destination, using the PassThrough that `pipeline()` returns for a function destination, and function stages or iterable sources together with pipeline options are unsupported. `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. diff --git a/docs/src/generated/node-v24-compatibility.json b/docs/src/generated/node-v24-compatibility.json index 66b0ba3dd..d77322eb5 100644 --- a/docs/src/generated/node-v24-compatibility.json +++ b/docs/src/generated/node-v24-compatibility.json @@ -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" } }, diff --git a/internal/compatibility/generated/node-v24-internal.json b/internal/compatibility/generated/node-v24-internal.json index c6a7a102c..537b8f05a 100644 --- a/internal/compatibility/generated/node-v24-internal.json +++ b/internal/compatibility/generated/node-v24-internal.json @@ -19313,6 +19313,9 @@ "tests/corpus/6703-ecdh-private-keys.ts", "tests/corpus/6704-ecdh-set-public-key.cjs", "tests/corpus/6705-ecdh-handles.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/corpus/node24-crypto-kdf-errors.ts", "tests/corpus/node24-crypto-kdf-options.ts", "tests/corpus/node24-crypto-kdf.ts", @@ -19700,6 +19703,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" ] }, @@ -19736,6 +19742,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" ] }, @@ -21734,6 +21743,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 +21782,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 +21821,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 +21860,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 +21899,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 +21938,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 +21977,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 +22016,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 +22055,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 +22094,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 +22133,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 +22172,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" ] }, diff --git a/internal/compatibility/src/generate.mjs b/internal/compatibility/src/generate.mjs index 9bd3927b8..cf77c1f84 100644 --- a/internal/compatibility/src/generate.mjs +++ b/internal/compatibility/src/generate.mjs @@ -594,7 +594,7 @@ function publicDetail(tier) { 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:(?: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..0e608148f 100644 --- a/internal/compatibility/static-support.json +++ b/internal/compatibility/static-support.json @@ -42,8 +42,8 @@ "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.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/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/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.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"], @@ -412,7 +412,7 @@ { "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": ["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": "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"] }, diff --git a/packages/cli/test/native-link-info.test.ts b/packages/cli/test/native-link-info.test.ts index f5ff2642e..56ca46878 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: 25, marker: "scr_runtime_abi_v25" }, 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_v25"); }); }); diff --git a/packages/compiler/ambient/scriptc-node-fallback.d.ts b/packages/compiler/ambient/scriptc-node-fallback.d.ts index dbb3cd8fd..16d7b9845 100644 --- a/packages/compiler/ambient/scriptc-node-fallback.d.ts +++ b/packages/compiler/ambient/scriptc-node-fallback.d.ts @@ -2852,7 +2852,8 @@ declare module "crypto" { ): 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. */ + * 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 +2863,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 +2884,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; diff --git a/packages/compiler/src/backend/llvm/lib-shared.ts b/packages/compiler/src/backend/llvm/lib-shared.ts index 8bb8bc3aa..524d5939d 100644 --- a/packages/compiler/src/backend/llvm/lib-shared.ts +++ b/packages/compiler/src/backend/llvm/lib-shared.ts @@ -754,6 +754,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", diff --git a/packages/compiler/src/backend/llvm/lib-stream.ts b/packages/compiler/src/backend/llvm/lib-stream.ts index d3b4b1f5b..5d198d306 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"], @@ -662,14 +663,14 @@ export function emitStreamLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlV e.fn === "stream.pipelineStages" || e.fn === "stream.pipelineStagesDyn" ) { - // (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]): 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 +678,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); const args = e.args.map((a) => host.emitExpr(a)); const packed = (from: number, count: number): string => { if (count === 0) return "null"; @@ -691,20 +693,17 @@ 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})`); diff --git a/packages/compiler/src/backend/runtime-abi.ts b/packages/compiler/src/backend/runtime-abi.ts index 5eb24482b..f02510338 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 = 25 as const; +export const RUNTIME_ABI_MARKER = "scr_runtime_abi_v25" 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..8bdbc8492 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: 25, marker: "scr_runtime_abi_v25" }, compiler: { command: "fixture", identity: "fixture", target: target.llvmTriple }, macros: { executable: [], excluded: ["SCR_LIB"], sanitizer: "external-toolchain-required" }, flavors: { diff --git a/packages/compiler/src/backend/runtime-pack.test.ts b/packages/compiler/src/backend/runtime-pack.test.ts index 5ffb4797d..a3ac9fe5d 100644 --- a/packages/compiler/src/backend/runtime-pack.test.ts +++ b/packages/compiler/src/backend/runtime-pack.test.ts @@ -124,7 +124,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: 25, marker: "scr_runtime_abi_v25" }, compiler: { command: "clang", identity: "fixture clang", 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/crypto.ts b/packages/compiler/src/frontend/lowering/builtins/crypto.ts index f4270dbe8..3dd3a4278 100644 --- a/packages/compiler/src/frontend/lowering/builtins/crypto.ts +++ b/packages/compiler/src/frontend/lowering/builtins/crypto.ts @@ -907,7 +907,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 +921,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)) diff --git a/packages/compiler/src/frontend/lowering/builtins/hash-stream.ts b/packages/compiler/src/frontend/lowering/builtins/hash-stream.ts index 382d15eaf..f2f3625dd 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,21 +79,48 @@ 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 }); + return withValueStreamReceiver(lowerer, access.expression, locOf(call), () => + 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), () => + 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. A result + * typed as the Transform (a member that answers `this`) answers the value + * itself. */ +function withValueStreamReceiver( + lowerer: Lowerer, + receiver: ts.Expression, + loc: SrcLoc, + 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 = @@ -68,16 +129,42 @@ export function lowerHashStreamCall( ? { 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/containers/bytes.ts b/packages/compiler/src/frontend/lowering/containers/bytes.ts index 4b20d7bf5..32fb03644 100644 --- a/packages/compiler/src/frontend/lowering/containers/bytes.ts +++ b/packages/compiler/src/frontend/lowering/containers/bytes.ts @@ -1078,11 +1078,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) { diff --git a/packages/compiler/src/frontend/lowering/containers/iterator-helpers.ts b/packages/compiler/src/frontend/lowering/containers/iterator-helpers.ts index 48b4caabd..ba5d0684d 100644 --- a/packages/compiler/src/frontend/lowering/containers/iterator-helpers.ts +++ b/packages/compiler/src/frontend/lowering/containers/iterator-helpers.ts @@ -1223,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; @@ -1253,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/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/expressions/property-access.ts b/packages/compiler/src/frontend/lowering/expressions/property-access.ts index 6c8dfa3bf..4d8e4d52c 100644 --- a/packages/compiler/src/frontend/lowering/expressions/property-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/property-access.ts @@ -132,6 +132,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"; @@ -3995,6 +3996,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); diff --git a/packages/compiler/src/frontend/lowering/lower-stmts.ts b/packages/compiler/src/frontend/lowering/lower-stmts.ts index e3480cf9c..bc3d2e869 100644 --- a/packages/compiler/src/frontend/lowering/lower-stmts.ts +++ b/packages/compiler/src/frontend/lowering/lower-stmts.ts @@ -3,6 +3,7 @@ import { declaredMemberOf, isPromisePrototypeRead } from "./expressions/property import { hostsAll } from "./expressions/hosted-narrowing.js"; import { requestGeneralStreamSurface } from "./general-streams.js"; import { lowerForAwaitDynStream } from "./dyn-streams.js"; +import { lowerForAwaitValueStream } from "./builtins/hash-stream.js"; import { lowerChildPropertyWrite } from "./handle-properties.js"; import { matchAllRowsReadByElements, @@ -9390,10 +9391,11 @@ 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), - ); + // 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; diff --git a/packages/compiler/src/frontend/lowering/lower-stream.ts b/packages/compiler/src/frontend/lowering/lower-stream.ts index a75ec43b7..ab21b8a7e 100644 --- a/packages/compiler/src/frontend/lowering/lower-stream.ts +++ b/packages/compiler/src/frontend/lowering/lower-stream.ts @@ -1,6 +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 @@ -52,7 +52,10 @@ 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 { BOOL, DYN, @@ -74,6 +77,7 @@ import { funcOf, typeEquals, typeKey, + UNDEFINED_T, } from "../../ir/ir.js"; const BYTES = BYTES_U8; @@ -2084,10 +2088,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, @@ -2429,10 +2433,10 @@ export function lowerStreamModuleCall( ? pipelineOptions(lowerer, lastArg) : null; const stageArgs = opts ? args.slice(0, -1) : args; - if (stageArgs.some(isPipelineFunctionStage)) { + if (hasPipelineFunctionStage(lowerer, stageArgs)) { if (opts) { lowerer.noLowering( - "pipeline with function stages and options", + "pipeline with function stages or iterable sources and options", lastArg, "pipeline(source, async function* (source) { ... }, destination) without options is supported", ); @@ -2503,7 +2507,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)) { @@ -2621,7 +2628,7 @@ 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 @@ -2680,19 +2687,215 @@ export function lowerStreamModuleCall( 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; + 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. */ +function lowerIterableSource( + lowerer: Lowerer, + node: ts.Expression, + fn: StageFunction | null, + loc: SrcLoc, +): { closure: IrExpr; out: SyncGenType } | null { + 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; @@ -2701,56 +2904,89 @@ interface PipelineStagesLowering { 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), 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. 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, ): 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 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; + // 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; + for (let j = 0; j < stageArgs.length; j++) { + const arg = stageArgs[j]!; + const fn = 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 && (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; + 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 = lowerStreamArg(lowerer, arg, "pipeline"); + } catch (e) { + if (e instanceof StreamArgTypeThrow) lowerer.noLowering("pipeline over this value", arg); + throw e; + } + 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.isFunctionExpression(fn) && fn.asteriskToken !== undefined; + const isGen = !ts.isArrowFunction(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, + arg, "end the pipeline with a stream or an async function (source) { for await (const chunk of source) ... }", ); } @@ -2761,7 +2997,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) ... }", ); } @@ -2783,8 +3019,9 @@ function lowerPipelineStages( "type it as { signal: AbortSignal }", ); } - mask |= 1 << (i - first); + mask |= 1 << stages.length; } + positions += 2 ** j; stages.push(lowered.closure); if (lowered.out.kind === "promise") { dest = 2; @@ -2794,29 +3031,7 @@ function lowerPipelineStages( 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" && @@ -2828,28 +3043,25 @@ 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); + // SCR_PIPE_* flags: bits 1-2 the destination, bit 5 the signal and abort. + 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; + const last: IrType = + dest === 2 ? { kind: "object", className: "%PassThrough" } : streams[streams.length - 1]!.type; if (mask === 0) return { args: head, last, dest, destPromise, wrap: (call) => call }; // const ac = new AbortController(): its signal goes to the stages, and // finishImpl's ac.abort() runs through the abort closure. @@ -2980,7 +3192,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]; @@ -2995,6 +3207,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 ( @@ -3017,14 +3231,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); @@ -3032,9 +3268,19 @@ function lowerStageFunction( return { closure, out: out as IrType & ({ kind: "generator" } | { kind: "promise" }) }; } finally { if (symbol) lowerer.stageSourceTypes.delete(symbol); + lowerer.implicitParamTypes = previousImplicit; } } +/** 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 @@ -3806,9 +4052,10 @@ 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]!)))) { + // 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 = lowerer.lowerExpr(access.expression); const source = lowerer.declareHiddenLocal("%pipeSource", receiverValue.type); const hashValue = lowerer.lowerExpr(args[0]!); @@ -3826,7 +4073,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" }, diff --git a/packages/compiler/src/frontend/lowering/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index 3f8a0a66e..f55498599 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -62,7 +62,7 @@ import { resolveRequireRuntime } from "../runtime-resolve.js"; import { lowerKeyObjectCall } from "./builtins/key-object.js"; import { isEcdhType, lowerEcdhCall } from "./builtins/ecdh.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"; @@ -3030,10 +3030,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. */ @@ -12486,8 +12486,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); } diff --git a/packages/compiler/src/ir/builtin-effects.ts b/packages/compiler/src/ir/builtin-effects.ts index ca8c52118..89aa5b001 100644 --- a/packages/compiler/src/ir/builtin-effects.ts +++ b/packages/compiler/src/ir/builtin-effects.ts @@ -80,6 +80,7 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "procStream.write", "child.stdioStream", "stream.unboxDyn", + "stream.handleStream", "stream.pipeDyn", "stream.unpipeDyn", "weakMap.new", diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index fa7876579..9490ed78c 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -2712,6 +2712,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; @@ -3936,14 +3942,15 @@ 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 }, @@ -4734,3 +4741,15 @@ 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): each pumps its last + * generator into that stream through one (next, read, return) triple. */ +export function pipelinePumpedRuns(total: number, positions: number): number { + let runs = 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/runtime-features.ts b/packages/compiler/src/ir/runtime-features.ts index 4142b6efe..7d8626e4b 100644 --- a/packages/compiler/src/ir/runtime-features.ts +++ b/packages/compiler/src/ir/runtime-features.ts @@ -237,6 +237,7 @@ const STREAM_LIB_FNS: ReadonlySet = new Set([ "stream.prop", "stream.stdioWritable", "stream.unboxDyn", + "stream.handleStream", "stream.unpipeDyn", "stream.workerStdio", ]); diff --git a/packages/compiler/src/ir/validate.ts b/packages/compiler/src/ir/validate.ts index 88ccbbc33..9de1b5b62 100644 --- a/packages/compiler/src/ir/validate.ts +++ b/packages/compiler/src/ir/validate.ts @@ -60,7 +60,7 @@ 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"; /** The promisified crypto calls' value kinds besides checked-dynamic. */ const CRYPTO_PROMISE_VALUES: Readonly> = { @@ -5614,23 +5614,34 @@ function validateFunction( e.fn === "stream.pipelineStagesDyn" || e.fn === "sp.pipelineStages" ) { - // (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]): positions bit j marks + // stage j a function, flags bits 1-2 the destination, bit 5 the + // signal group; helpers are three per function run a stream + // follows. + 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); + 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!); + const groups = helperCount + (destKind === 2 ? 1 : 0) + (flags! & 32 ? 2 : 0); const cbArgs = e.fn === "sp.pipelineStages" ? 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 === 2) !== lastIsFunction || + total < 2 || e.args.length !== 5 + n! + k! + groups + cbArgs ) { err(`libCall ${e.fn} count/arity mismatch`, e.loc); @@ -5647,7 +5658,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); diff --git a/packages/compiler/test/native-codegen-integration.test.ts b/packages/compiler/test/native-codegen-integration.test.ts index d8f158ebc..c05e7f994 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_v25"); 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_v25"); }); test("helper and clang object paths retain the same outbound FFI C ABI", async () => { 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/runtime-darwin-arm64/scripts/build.mjs b/packages/runtime-darwin-arm64/scripts/build.mjs index 85c5ffb00..c18a1d080 100644 --- a/packages/runtime-darwin-arm64/scripts/build.mjs +++ b/packages/runtime-darwin-arm64/scripts/build.mjs @@ -337,7 +337,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: 25, marker: "scr_runtime_abi_v25" }, compiler: { command: compiler, identity: compilerVersion, diff --git a/packages/runtime-pack-common/scripts/build.mjs b/packages/runtime-pack-common/scripts/build.mjs index b242b78aa..f0eab2cb5 100644 --- a/packages/runtime-pack-common/scripts/build.mjs +++ b/packages/runtime-pack-common/scripts/build.mjs @@ -434,7 +434,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: 25, marker: "scr_runtime_abi_v25" }, compiler: { command: compiler, identity: compilerVersion, diff --git a/packages/runtime/src/scr_cipher.c b/packages/runtime/src/scr_cipher.c index df62a79a3..c8a10a731 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 @@ -103,6 +105,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 +118,38 @@ 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_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 ───────────────────────────────────────────────────────────── */ @@ -532,9 +562,10 @@ 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; @@ -883,7 +914,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; @@ -953,7 +985,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 +1092,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 +1156,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 +1175,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 +1207,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 +1230,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..c8fa40b38 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_v25(void) {} void scr_init(void) { #ifdef SCR_WORKERS diff --git a/packages/runtime/src/scr_core.h b/packages/runtime/src/scr_core.h index 94936a8aa..5e5278588 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_v25(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_dyn.h b/packages/runtime/src/scr_dyn.h index 02c4d828f..cafc8d07e 100644 --- a/packages/runtime/src/scr_dyn.h +++ b/packages/runtime/src/scr_dyn.h @@ -1388,8 +1388,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_json.c b/packages/runtime/src/scr_json.c index b8f16630b..194ade887 100644 --- a/packages/runtime/src/scr_json.c +++ b/packages/runtime/src/scr_json.c @@ -37,6 +37,8 @@ static SCR_TL ScrDyn *scr_builtin_object_prototype; +SCR_TL const ScrHandleStreamHooks *scr_handle_stream_hooks; + /* 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) { @@ -4309,6 +4311,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; diff --git a/packages/runtime/src/scr_stream.c b/packages/runtime/src/scr_stream.c index f7330b615..271937f2e 100644 --- a/packages/runtime/src/scr_stream.c +++ b/packages/runtime/src/scr_stream.c @@ -175,6 +175,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; @@ -412,6 +417,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 { @@ -688,8 +694,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; @@ -1706,17 +1717,20 @@ static void scr_stream_wq_push(ScrStreamState *st, ScrBytes *chunk /*moves*/, Sc st->w.n++; } +static void scr_stream_transform_callback(ScrStream *s); + static void scr_stream_do_write(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_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 (!scr_exc_pending()) scr_stream_transform_callback(s); st->w.wsync = false; return; } @@ -3294,13 +3308,13 @@ 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 *); @@ -3309,20 +3323,25 @@ typedef ScrDyn *(*ScrPipeBoxFn)(ScrClosure *, ScrPromise *); enum { SCR_PIPE_DEST_STREAM, SCR_PIPE_DEST_PROMISE = 2 }; 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, 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 +3350,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 +3599,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); @@ -3721,27 +3740,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); @@ -3776,7 +3795,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 +3822,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,12 +3860,12 @@ 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; } @@ -3864,25 +3883,25 @@ 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); +/* 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; @@ -4263,12 +4282,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); @@ -5800,6 +5819,19 @@ 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) { @@ -5820,7 +5852,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*/, @@ -6171,6 +6204,9 @@ 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; ScrClosure *cb = t->cb; @@ -6369,8 +6405,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 +6448,138 @@ 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; +} + +/* The pending exception as a stream error (+1). */ +static ScrError *scr_handle_step_caught(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 Transform handle threw a value that is not an Error"); +} + +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_handle_step_caught(), 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; +} + +/* 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 +6655,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 +6729,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 +6910,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..1e5b789e7 100644 --- a/packages/runtime/src/scr_stream.h +++ b/packages/runtime/src/scr_stream.h @@ -143,6 +143,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 +204,34 @@ 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_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 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_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/tests/corpus/7055-cipher-streams.ts b/tests/corpus/7055-cipher-streams.ts new file mode 100644 index 000000000..8befd2339 --- /dev/null +++ b/tests/corpus/7055-cipher-streams.ts @@ -0,0 +1,182 @@ +// 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, + 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 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 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..f0a61e7c2 --- /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(); + }, + ); +}); +{ + 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(); + }), + ); + 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(); + }, + ), + ); + 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/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/self-hosting-native-toolchain.test.ts b/tests/harness/self-hosting-native-toolchain.test.ts index 7da7626b7..c01b52595 100644 --- a/tests/harness/self-hosting-native-toolchain.test.ts +++ b/tests/harness/self-hosting-native-toolchain.test.ts @@ -105,7 +105,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: 25, marker: "scr_runtime_abi_v25" }, compiler: { command: "fixture", identity: "fixture", target: target.llvmTriple }, macros: { executable: [], excluded: [], sanitizer: "external-toolchain-required" }, flavors: { From e7e943a1d3ffd4a8e44fc40ffcd19b217ba8ad4c Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 02:00:06 -0500 Subject: [PATCH 029/102] Accept only nested scans that highestCount walks pass by pass The first pass of guardedLoopCounterFacts accepted a nested while loop anywhere outside an opaque region, and highestCount then left counters unbounded where it does not walk such a loop. The first pass now accepts the same loops highestCount walks: statements of the body, its blocks and its branches. A loop in a labeled block or among an expression's statements is an ordinary loop region, whose counter writes are refused. --- packages/compiler/src/ir/integer-loop-facts.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/compiler/src/ir/integer-loop-facts.ts b/packages/compiler/src/ir/integer-loop-facts.ts index 31edc2f48..8807212dc 100644 --- a/packages/compiler/src/ir/integer-loop-facts.ts +++ b/packages/compiler/src/ir/integer-loop-facts.ts @@ -276,16 +276,26 @@ export function guardedLoopCounterFacts( else budget.set(id, (budget.get(id) ?? 0) + delta); }; // Nested while loops outside opaque regions, checked against their own - // conditions once the stable bounds are known. + // conditions once the stable bounds are known. Only loops that highestCount + // walks pass by pass qualify: statements of the body, its blocks and its + // branches. One in a labeled block or among an expression's statements + // (`indirect`) is an ordinary loop region. const nested: (IrStmt & { kind: "while" })[] = []; + let indirect = 0; const expr = (e: IrExpr): boolean => { if (e.kind === "assignExpr") write(e.localId, increment(e.localId, e.value)); if (e.kind === "incDec") write(e.localId, e.op === "+" ? 1 : null); - return everyExprChild(e, expr, stmt); + return everyExprChild(e, expr, (x) => { + indirect++; + const completed = stmt(x); + indirect--; + return completed; + }); }; const condition = new Set(); const stmt = (s: IrStmt): boolean => { - const bounded = s.kind === "while" && opaque === 0 && !s.labels?.length; + const bounded = s.kind === "while" && opaque === 0 && indirect === 0 && !s.labels?.length; + const labeled = s.kind === "block" && !!s.labels?.length; const region = !bounded && (s.kind === "for" || @@ -299,10 +309,12 @@ export function guardedLoopCounterFacts( conditionWrites(s.cond); } if (region) opaque++; + if (labeled) indirect++; if (s.kind === "assign") write(s.localId, increment(s.localId, s.value)); if (s.kind === "varDecl" || s.kind === "forOf") write(s.localId, null); if (s.kind === "tryCatch" && s.catchLocalId) write(s.catchLocalId, null); const completed = everyStmtChild(s, expr, stmt); + if (labeled) indirect--; if (region) opaque--; return completed; }; From 2fbfc1b270d2a48485464ceeb50ac75b28d514c5 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 02:00:30 -0500 Subject: [PATCH 030/102] Keep each build's translation unit private until the build ends The kept LLVM text and IR are named after the entry (`.ll`, `.ir.json`) in the output directory, so two programs whose entries share a name and are built into one directory share those files. The executable cache published the translation unit by copying the shared `.ll` after the native build, so when the other program wrote it in between, the stamp recorded the other program's text, and a later cache hit relinked the wrong program without any error. A build now writes, compiles and caches private copies beside the shared names and renames them into place when it ends. A cache hit that relinks compiles a private copy of the cached translation unit, and leaves a shared file that already holds those bytes as it is. The native build reads the private copy and keeps the shared name as the spelling clang sees, so native cache keys and debug names do not change. --- .../compiler/src/backend/native/contracts.ts | 4 + .../compiler/src/backend/native/executable.ts | 15 +- .../src/executable/executable-cache.test.ts | 11 +- .../src/executable/executable-cache.ts | 48 ++++- packages/compiler/src/index.ts | 176 ++++++++++++------ .../executable-cache-shared-output.test.ts | 102 ++++++++++ 6 files changed, 289 insertions(+), 67 deletions(-) create mode 100644 tests/harness/executable-cache-shared-output.test.ts diff --git a/packages/compiler/src/backend/native/contracts.ts b/packages/compiler/src/backend/native/contracts.ts index 06a41c9b2..36f804fb2 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 diff --git a/packages/compiler/src/backend/native/executable.ts b/packages/compiler/src/backend/native/executable.ts index a551ad600..9dab1c783 100644 --- a/packages/compiler/src/backend/native/executable.ts +++ b/packages/compiler/src/backend/native/executable.ts @@ -481,7 +481,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 = @@ -861,7 +861,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 +901,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 +972,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/executable/executable-cache.test.ts b/packages/compiler/src/executable/executable-cache.test.ts index 94b136c90..e7c57d1b0 100644 --- a/packages/compiler/src/executable/executable-cache.test.ts +++ b/packages/compiler/src/executable/executable-cache.test.ts @@ -133,8 +133,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-/); + 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..941a7acdc 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, @@ -179,6 +180,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; @@ -575,15 +585,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 +599,31 @@ 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 { + llvmSourcePath = privateSiblingPath(paths.llvmPath, "llvm"); + 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 +645,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/index.ts b/packages/compiler/src/index.ts index 2b216c77d..db1b0b3e3 100644 --- a/packages/compiler/src/index.ts +++ b/packages/compiler/src/index.ts @@ -524,6 +524,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 +566,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), @@ -729,8 +734,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 +850,7 @@ async function prepareExecutableInput( await mkdir(opts.outDir, { recursive: true }); const llvmPath = defaultSourcePaths.llvm; + const llvmSourcePath = privateSiblingPath(llvmPath, "llvm"); const backend = "llvm" as const; const useRuntimePack = opts.nativeProgramObject === true || usesPrecompiledRuntimePack(opts, backend); @@ -863,12 +873,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 +894,51 @@ 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. + */ +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), + ]); } /** @@ -976,10 +1032,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 +1104,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 +1144,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 +1506,46 @@ 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, + }; + 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(), + }; + } + } await compileExecutableNative( earlyHit.native, nativeInputPath, @@ -1496,6 +1561,10 @@ async function compileTracked( : async ({ dependencies }) => { await publishEarlyExecutableCache(cacheRoot, executableCacheOptions, { ...earlyHit, + llvmPath: hitSources.llvmSourcePath, + ...(hitSources.irSourcePath === undefined + ? {} + : { irPath: hitSources.irSourcePath }), executableRestored: true, nativeDependencies: dependencies, frontend: earlyHit.frontend, @@ -1503,6 +1572,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 +1602,7 @@ async function compileTracked( nativeProgramObject.partitionPaths, ); } + await installBuildSources(hitSources); } await pruneBuildCache(cacheRoot); return { @@ -1564,7 +1635,8 @@ 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 { llvmSource, llvmPath, llvmSourcePath, irPath, irSourcePath } = prepared; + const { nativeFeatures, programSplit, sourceTexts } = prepared; const backend = "llvm" as const; await mkdir(dirname(opts.outPath), { recursive: true }); if (earlyCacheOptions === null) { @@ -1599,7 +1671,7 @@ async function compileTracked( } await compileExecutableNative( nativeFeatures, - nativeProgramObject?.linkPath ?? llvmPath, + nativeProgramObject?.linkPath ?? llvmSourcePath, opts.outPath, opts.sanitize ?? false, ffi, @@ -1611,23 +1683,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 +1732,7 @@ 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); + await installBuildSources({ llvmPath, llvmSourcePath, irPath, irSourcePath }); } await pruneBuildCache(cacheRoot); timing("complete"); 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"); + } + }, + ); +}); From 491480e1ad3990c5d6f834e6afbd910420a34ee3 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 02:09:43 -0500 Subject: [PATCH 031/102] Convert clamped stores inline and test thread-owned views once in typed-array loops A Uint8ClampedArray store called scr_bytes_to_u8_clamp for every element, which kept loops of clamped stores scalar. The store now computes ToUint8Clamp in line: NaN and values at most 0 store 0, values at least 255 store 255, and values between round through (v + 2^52) - 2^52, which rounds a value in (0, 255) to the nearest integer, ties to even, as the runtime function does. In worker-enabled programs, every typed-array element access tests the view's shared storage and branches between a relaxed atomic access and the ordinary one, so loops over thread-owned views kept one branch per access. A view's shared storage is fixed at construction, like its length, so the typed-array loop version guard now tests it once for each invariant receiver, and the fast copy reads and writes those views directly. In worker programs a loop is versioned for this even when no bound needs a guard. When any receiver is shared, the checked copy runs unchanged. Programs without workers emit the same code as before. Adds a Uint8ClampedArray brighten kernel to the typed-array-kernels workload. --- benchmarks/runtime/README.md | 2 +- .../runtime/workloads/typed-array-kernels.ts | 12 +++ .../backend/llvm/bytes-loop-versions.test.ts | 31 ++++++++ .../src/backend/llvm/bytes-loop-versions.ts | 46 ++++++++++- .../src/backend/llvm/emit-function.ts | 1 + .../src/backend/llvm/emit-statements.ts | 5 ++ packages/compiler/src/backend/llvm/emitter.ts | 11 ++- .../compiler/src/backend/llvm/expr-bytes.ts | 52 ++++++++++--- .../test/bytes-element-emission.test.ts | 42 ++++++++++ .../6994-uint8-clamped-store-rounding.ts.json | 6 ++ ...5-worker-typed-array-loop-versions.ts.json | 6 ++ .../6994-uint8-clamped-store-rounding.ts | 77 +++++++++++++++++++ .../6995-worker-typed-array-loop-versions.ts | 74 ++++++++++++++++++ .../6994-uint8-clamped-store-rounding.ts.json | 1 + ...5-worker-typed-array-loop-versions.ts.json | 1 + 15 files changed, 348 insertions(+), 19 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6994-uint8-clamped-store-rounding.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6995-worker-typed-array-loop-versions.ts.json create mode 100644 tests/corpus/6994-uint8-clamped-store-rounding.ts create mode 100644 tests/corpus/6995-worker-typed-array-loop-versions.ts create mode 100644 tests/harness/corpus-costs/6994-uint8-clamped-store-rounding.ts.json create mode 100644 tests/harness/corpus-costs/6995-worker-typed-array-loop-versions.ts.json diff --git a/benchmarks/runtime/README.md b/benchmarks/runtime/README.md index 1acdc9ce7..cbf47675a 100644 --- a/benchmarks/runtime/README.md +++ b/benchmarks/runtime/README.md @@ -26,7 +26,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, 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 | | `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/typed-array-kernels.ts b/benchmarks/runtime/workloads/typed-array-kernels.ts index 87c227bbc..ba68f7241 100644 --- a/benchmarks/runtime/workloads/typed-array-kernels.ts +++ b/benchmarks/runtime/workloads/typed-array-kernels.ts @@ -17,6 +17,10 @@ function addWrap(a: Int32Array, b: Int32Array, out: Int32Array): void { for (let i = 0; i < out.length; i++) out[i] = (a[i]! + b[i]!) | 0; } +function brighten(src: Uint8ClampedArray, gain: number, out: Uint8ClampedArray): void { + for (let i = 0; i < out.length; i++) out[i] = src[i]! * gain + 8; +} + function gray(rgba: Uint8Array, out: Uint8Array): void { for (let i = 0; i < out.length; i++) { const j = i * 4; @@ -38,6 +42,8 @@ const masked = new Uint8Array(n); const ia = new Int32Array(n); const ib = new Int32Array(n); const io = new Int32Array(n); +const pixels = new Uint8ClampedArray(n); +const bright = new Uint8ClampedArray(n); const rgba = new Uint8Array(n * 4); const luma = new Uint8Array(n); let state = 2463534242; @@ -56,6 +62,7 @@ for (let i = 0; i < n; i++) { key[i] = next() & 255; ia[i] = next() | 0; ib[i] = next() | 0; + pixels[i] = next() & 255; } for (let i = 0; i < rgba.length; i++) rgba[i] = next() & 255; @@ -64,6 +71,7 @@ let f64Sum = 0; let f32Sum = 0; let byteSum = 0; let intSum = 0; +let brightSum = 0; let lumaSum = 0; for (let r = 0; r < rounds; r++) { // Change one input element per round so no round repeats the last. @@ -72,21 +80,25 @@ for (let r = 0; r < rounds; r++) { fa[at] = r; data[at] = r & 255; ia[at] = r * 65537; + pixels[at] = r & 255; rgba[at * 4] = r & 255; 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); const probe = (r * 104729) & (n - 1); f64Sum += d[probe]!; f32Sum += fo[probe]!; byteSum += masked[probe]!; intSum = (intSum + io[probe]!) | 0; + brightSum += bright[probe]!; lumaSum += luma[probe]!; } console.log(`float64 ${f64Sum.toFixed(3)}`); console.log(`float32 ${f32Sum.toFixed(3)}`); console.log(`uint8 ${byteSum}`); console.log(`int32 ${intSum}`); +console.log(`clamped ${brightSum}`); console.log(`gray ${lumaSum}`); 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 ea568bc3f..3fbc01cc5 100644 --- a/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts +++ b/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts @@ -109,6 +109,8 @@ function match( ranges, initialized: findInitializedByteLoopBindings(f).get(loop) ?? new Set(), proven: new Set(), + workers: false, + owned: new Set(), }); } @@ -250,6 +252,35 @@ test("loops to a typed array's length version the other typed arrays they index" expect(rebound).toContain("bytes.index.invalid"); }); +test("worker programs test each receiver's shared storage once in the guard", () => { + // for (let i = 0; i < n; i++) out[i] = src[i] * 2, where either view may + // be shared. + const loop = counted([ + set(ref("out", f64s), ref("i"), bin("*", get(ref("src", f64s), ref("i")), num(2))), + ]); + const kernel = fn([loop]); + const mod: IrModule = { + irVersion: 17, + sourceFile: loc.file, + entry: "__main", + workers: true, + 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)); + expect(guard.match(/icmp eq ptr %\S+, null/g)).toHaveLength(2); + const fast = /^bytes\.version\.fast\d+:$[^]*?^bytes\.version\.done\d+:$/m.exec(body)![0]; + expect(fast).not.toContain("bytes.shared"); + expect(fast).not.toMatch(/(load|store) atomic double/); + // The checked copy keeps the shared-memory path for each access. + const slow = body.slice(body.search(/^bytes\.version\.slow\d+:$/m), body.indexOf(fast)); + expect(slow).toContain("load atomic double"); + expect(slow).toContain("store atomic double"); +}); + test("Float16Array accesses version in elements and share the element tag", () => { const f16s: IrType = { kind: "bytes", elem: "f16" }; const withHalves = (body: IrStmt[]): IrFunction => { diff --git a/packages/compiler/src/backend/llvm/bytes-loop-versions.ts b/packages/compiler/src/backend/llvm/bytes-loop-versions.ts index df8977426..dcb735e61 100644 --- a/packages/compiler/src/backend/llvm/bytes-loop-versions.ts +++ b/packages/compiler/src/backend/llvm/bytes-loop-versions.ts @@ -6,7 +6,7 @@ import { byteNumberAccess } from "../../ir/byte-numbers.js"; import { everyExprChild, everyStmtChild } from "../../ir/traverse.js"; import { exactInteger, widenInteger } from "./integer-values.js"; import { emitCountedLoopLimit, emitCountedLoopSafety } from "./counted-loops.js"; -import { emitBytesHeaderLength } from "./expr-bytes.js"; +import { emitBytesHeaderLength, emitBytesSharedStorage } from "./expr-bytes.js"; type Node = IrExpr | IrStmt; type VarRef = IrExpr & { kind: "varRef" }; @@ -41,8 +41,13 @@ interface AffineCheck { export interface BytesLoopVersion { /** Typed-array accesses that are in bounds whenever the guard holds. */ bounds: ReadonlySet; + /** 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 }[]; + /** Receivers the guard requires to have no shared storage. */ + ownedReceivers: number[]; fixed: FixedCheck[]; affine: AffineCheck[]; /** The counted loop whose iteration space the affine checks cover. */ @@ -66,6 +71,11 @@ export interface BytesLoopFacts { initialized: ReadonlySet; /** Accesses already proved in bounds without a guard. */ proven: ReadonlySet; + /** Worker programs: an access of a view that may be shared tests the + * view's shared storage first. */ + workers: boolean; + /** Accesses already proved thread-owned by an enclosing version. */ + owned: ReadonlySet; } const MAX_COST = 400; @@ -87,6 +97,11 @@ const INVARIANT_OPS = new Set(["+", "-", "*", "&", "|", "^", "<<", ">>", ">>>"]) * and last values in bounds, such as `out[base + i]` for `i < n` or * `view.getUint32(i * 4)`. * + * 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 + * same guard tests each invariant receiver once, and the fast copy reads + * and writes thread-owned views directly. + * * Only small synchronous loops are versioned (nested loops included), and * the emitter bounds how deeply versions nest. The checked loop runs * whenever the guard fails, and keeps every out-of-bounds read, ignored @@ -314,10 +329,19 @@ export function matchBytesLoopVersion( } 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(); const access = (node: Node, array: IrExpr, index: IrExpr, width: number): void => { - if (facts.proven.has(node)) return; const ref = root(array); if (!ref) return; + if (facts.workers && !facts.owned.has(node)) { + const receiver = receiverOf(ref); + const nodes = owned.get(receiver); + if (nodes) nodes.push(node); + else owned.set(receiver, [node]); + } + if (facts.proven.has(node)) return; const shape = counter !== null ? affine(index) : null; if (shape && shape.counter !== 0) { const operands = new Set(); @@ -383,9 +407,15 @@ export function matchBytesLoopVersion( }); const fixedKept = [...fixed.values()].slice(0, MAX_CHECKS); const affineKept = affineGroups.slice(0, MAX_CHECKS - fixedKept.length); - if (fixedKept.length === 0 && affineKept.length === 0) return null; + const ownedKept = [...owned.entries()].slice(0, MAX_CHECKS); + if (fixedKept.length === 0 && affineKept.length === 0 && ownedKept.length === 0) return null; const bounds = new Set(); + const ownedNodes = new Set(); const used = new Set(); + for (const [receiver, nodes] of ownedKept) { + used.add(receiver); + for (const node of nodes) ownedNodes.add(node); + } const ranges = new Map(); const counterLow = Math.max(counted?.range.min ?? 0, -bound), counterHigh = Math.min(counted?.range.max ?? 0, bound); @@ -420,7 +450,9 @@ export function matchBytesLoopVersion( (counted.range.min < -bound || counted.range.max > bound); return { bounds, + owned: ownedNodes, receivers: order.map((index) => receivers[index]!), + ownedReceivers: ownedKept.map(([receiver]) => renumber.get(receiver)!), fixed: fixedKept.map((g) => ({ receiver: renumber.get(g.check.receiver)!, end: g.check.end, @@ -439,7 +471,8 @@ export function matchBytesLoopVersion( } /** Branches to `fast` when every access the version proves is in bounds for - * every iteration, and to `slow` otherwise (including a counted loop whose + * every iteration and every view it proves thread-owned has no shared + * storage, and to `slow` otherwise (including a counted loop whose * integer form is not established, or a module receiver not yet set). */ export function emitBytesLoopVersionGuard( host: LlvmEmitterContext, @@ -473,6 +506,11 @@ export function emitBytesLoopVersionGuard( return wide; }); const conditions: string[] = []; + for (const index of version.ownedReceivers) { + const owned = B.tmp(); + B.line(`${owned} = icmp eq ptr ${emitBytesSharedStorage(host, receivers[index]!)}, null`); + conditions.push(owned); + } for (const check of version.fixed) { const ok = B.tmp(); B.line(`${ok} = icmp ugt i64 ${lengths[check.receiver]}, ${check.end}`); diff --git a/packages/compiler/src/backend/llvm/emit-function.ts b/packages/compiler/src/backend/llvm/emit-function.ts index d83b9ff64..5053c1b54 100644 --- a/packages/compiler/src/backend/llvm/emit-function.ts +++ b/packages/compiler/src/backend/llvm/emit-function.ts @@ -228,6 +228,7 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { emitter.integerLoopRanges = rangeFacts.loopRanges; emitter.int32Elements = slotFacts.elements ?? null; emitter.bytesBounds = findBytesBounds(numericFn, emitter.integerRanges); + emitter.bytesOwned = new Set(); // Debug builds keep every number local a double for the debugger's // variable view. Lazily boxed captured parameters keep their double, // which the box is created from, and so do plain copies of a capture or diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index 433029651..d2e96994b 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -517,6 +517,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { s.index, s.value, emitter.bytesBounds.has(s), + emitter.bytesOwned.has(s), ); break; } @@ -970,6 +971,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { 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 { @@ -978,6 +980,8 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { 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); @@ -985,6 +989,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { B.br(done); } finally { emitter.bytesBounds = originalBounds; + emitter.bytesOwned = originalOwned; emitter.integerRanges = originalRanges; emitter.provenCountedGuards.delete(s); emitter.bytesLoopVersioning.delete(s); diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index 1f2be4439..c254d0907 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -1125,6 +1125,9 @@ export class LlEmitter { * guard already passed. */ readonly provenCountedGuards = new Set(); bytesBounds: ReadonlySet = new Set(); + /** Worker programs: typed-array accesses whose views an enclosing version + * guard proved thread-owned. */ + bytesOwned: ReadonlySet = new Set(); integerViews = new Map(); /** Module globals the current function owns outright (initializer * bindings): their function-local slot, which stands in for the global. */ @@ -3836,6 +3839,8 @@ export class LlEmitter { ranges: this.integerRanges, initialized, proven: this.bytesBounds, + workers: this.mod.workers === true, + owned: this.bytesOwned, }); } @@ -6196,8 +6201,9 @@ export class LlEmitter { expr?: IrExpr, inBounds = false, invalidNaN = false, + owned = false, ): LlValue { - return emitBytesGet(this, elem, receiver, index, expr, inBounds, invalidNaN); + return emitBytesGet(this, elem, receiver, index, expr, inBounds, invalidNaN, owned); } emitToUint32(value: string, expr?: IrExpr, uint32?: string): string { @@ -6260,8 +6266,9 @@ export class LlEmitter { indexExpr?: IrExpr, expr?: IrExpr, inBounds = false, + owned = false, ): void { - return emitBytesSet(this, elem, receiver, index, value, indexExpr, expr, inBounds); + return emitBytesSet(this, elem, receiver, index, value, indexExpr, expr, inBounds, owned); } emitBytesIntrinsic(e: IrExpr & { kind: "bytesIntrinsic" }): LlValue { diff --git a/packages/compiler/src/backend/llvm/expr-bytes.ts b/packages/compiler/src/backend/llvm/expr-bytes.ts index d36001bf6..062bfdfbe 100644 --- a/packages/compiler/src/backend/llvm/expr-bytes.ts +++ b/packages/compiler/src/backend/llvm/expr-bytes.ts @@ -176,6 +176,17 @@ export function emitBytesLength( return { name: out, type: F64 }; } +/** A view's shared backing (null for a buffer this thread owns). It is + * set at construction, before script code can see the view. */ +export function emitBytesSharedStorage(host: LlvmEmitterContext, receiver: string): string { + const B = host.B; + const slot = B.tmp(), + storage = B.tmp(); + B.line(`${slot} = getelementptr inbounds %ScrBytes, ptr ${receiver}, i64 0, i32 9`); + B.line(`${storage} = load ptr, ptr ${slot}${bytesHeaderAlias(host)}`); + return storage; +} + /** Worker programs: an element of a view of a SharedArrayBuffer (`shared` is * fixed before script code can see the view) is read and written with one * relaxed atomic access of its width, as the runtime's shared accessors do; @@ -186,12 +197,9 @@ export function emitBytesLength( function emitSharedBytesSplit(host: LlvmEmitterContext, receiver: string): string { const B = host.B; host.declare(`declare i1 @llvm.expect.i1(i1, i1)`); - const slot = B.tmp(), - storage = B.tmp(), + const storage = emitBytesSharedStorage(host, receiver), isShared = B.tmp(), expected = B.tmp(); - B.line(`${slot} = getelementptr inbounds %ScrBytes, ptr ${receiver}, i64 0, i32 9`); - B.line(`${storage} = load ptr, ptr ${slot}${bytesHeaderAlias(host)}`); B.line(`${isShared} = icmp ne ptr ${storage}, null`); B.line(`${expected} = call i1 @llvm.expect.i1(i1 ${isShared}, i1 false)`); const shared = B.newLabel("bytes.shared"), @@ -209,15 +217,17 @@ export function emitBytesGet( expr?: IrExpr, inBounds = false, invalidNaN = false, + owned = false, ): LlValue { const B = host.B; // Any invalid index traps (the array runtime's discipline). - if (!invalidNaN) return emitBytesLoad(host, elem, receiver, index, expr, inBounds, undefined); + if (!invalidNaN) + return emitBytesLoad(host, elem, receiver, index, expr, inBounds, undefined, owned); // The numeric view of an ordinary read: an invalid index never touches // storage and reads as NaN — ToNumber of Node's undefined. const invalid = B.newLabel("bytes.read.invalid"); const done = B.newLabel("bytes.read.done"); - const loaded = emitBytesLoad(host, elem, receiver, index, expr, inBounds, invalid); + const loaded = emitBytesLoad(host, elem, receiver, index, expr, inBounds, invalid, owned); const ok = B.newLabel("bytes.read.ok"); B.br(ok); B.startBlock(ok); @@ -260,8 +270,10 @@ function emitBytesLoad( expr: IrExpr | undefined, inBounds: boolean, invalid: string | undefined, + owned: boolean, ): LlValue { - if (host.mod.workers) { + // `owned`: an enclosing version guard proved the view thread-owned. + if (host.mod.workers && !owned) { const idx = emitBytesIndex(host, receiver, index, expr, invalid, inBounds); return emitSharedOrLocalLoad(host, elem, receiver, idx); } @@ -515,13 +527,14 @@ export function emitBytesSet( indexExpr?: IrExpr, expr?: IrExpr, inBounds = false, + owned = false, ): void { const B = host.B; // Invalid integer-indexed writes are ignored after evaluating the RHS. const done = B.newLabel("bytes.store.done"); const data = host.emitBytesData(receiver); const idx = emitBytesIndex(host, receiver, index, indexExpr, done, inBounds); - if (host.mod.workers && elem === "f16") { + if (host.mod.workers && !owned && elem === "f16") { host.declare(`declare void @scr_bytes_shared_set(ptr, ${host.sizeType}, double)`); const local = emitSharedBytesSplit(host, receiver); B.line( @@ -532,10 +545,24 @@ export function emitBytesSet( } let stored: string | null; if (elem === "u8c") { - host.declare(`declare double @scr_bytes_to_u8_clamp(double)`); - const clamped = B.tmp(); + // ToUint8Clamp, as scr_bytes_to_u8_clamp computes it: NaN and values + // at most 0 store 0, values at least 255 store 255, and values between + // round to the nearest integer, ties to even. Adding and subtracting + // 2^52 rounds a value in (0, 255) that way in the default rounding mode, + // with no call or branch, so loops of clamped stores can vectorize. + const positive = B.tmp(), + high = B.tmp(), + shifted = B.tmp(), + rounded = B.tmp(), + upper = B.tmp(), + clamped = B.tmp(); stored = B.tmp(); - B.line(`${clamped} = call double @scr_bytes_to_u8_clamp(double ${value.name})`); + B.line(`${positive} = fcmp ogt double ${value.name}, 0.0`); + B.line(`${high} = fcmp oge double ${value.name}, 255.0`); + B.line(`${shifted} = fadd double ${value.name}, 0x4330000000000000`); + B.line(`${rounded} = fsub double ${shifted}, 0x4330000000000000`); + B.line(`${upper} = select i1 ${high}, double 255.0, double ${rounded}`); + B.line(`${clamped} = select i1 ${positive}, double ${upper}, double 0.0`); B.line(`${stored} = fptoui double ${clamped} to i32`); } else stored = @@ -572,7 +599,7 @@ export function emitBytesSet( ty = "i32"; operand = stored!; } - if (host.mod.workers) { + if (host.mod.workers && !owned) { // A shared view's element takes a relaxed atomic store of its width. const local = emitSharedBytesSplit(host, receiver); const p = B.tmp(); @@ -721,6 +748,7 @@ export function emitBytesIntrinsic( e.args[0], host.bytesBounds.has(e), e.invalidNaN === true, + host.bytesOwned.has(e), ); case "slice": return call( diff --git a/packages/compiler/test/bytes-element-emission.test.ts b/packages/compiler/test/bytes-element-emission.test.ts index 505b51963..c0a78a898 100644 --- a/packages/compiler/test/bytes-element-emission.test.ts +++ b/packages/compiler/test/bytes-element-emission.test.ts @@ -406,3 +406,45 @@ test("large record clones stay outlined while small clones remain inlineable", ( expect(large).toContain("define internal ptr @sc_rclone_large(ptr %src) #2"); expect(large).toContain("attributes #2 = { noinline sanitize_address }"); }); + +test("Uint8ClampedArray stores clamp and round without a runtime call", () => { + const type = bytesOf("u8c"); + const mod: IrModule = { + irVersion: 17, + sourceFile: loc.file, + entry: "__main", + functions: [ + { name: "__main", params: [], returnType: VOID, locals: [], body: [], loc }, + { + name: "store", + params: [ + { localId: "px", name: "px", type }, + { localId: "v", name: "v", type: F64 }, + ], + returnType: VOID, + locals: [ + { id: "px", name: "px", type, mutable: false }, + { id: "v", name: "v", type: F64, mutable: false }, + ], + body: [ + { + kind: "bytesSet", + arr: { kind: "varRef", localId: "px", type, loc }, + index: { kind: "numLit", value: 0, type: F64, loc }, + value: { kind: "varRef", localId: "v", type: F64, loc }, + loc, + }, + ], + loc, + }, + ], + }; + expect(validateModule(mod)).toEqual([]); + const body = /^define internal [^\n]*@sc_bf_store[^]*?^}/m.exec(emitLlvmModule(mod))![0]; + expect(body).not.toContain("scr_bytes_to_u8_clamp"); + expect(body).toMatch(/fcmp ogt double %\S+, 0\.0/); + expect(body).toMatch(/fcmp oge double %\S+, 255\.0/); + expect(body).toMatch(/fadd double %\S+, 0x4330000000000000/); + expect(body).toMatch(/fsub double %\S+, 0x4330000000000000/); + expect(body).toMatch(/store i8 [^\n]*, align 1/); +}); diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6994-uint8-clamped-store-rounding.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6994-uint8-clamped-store-rounding.ts.json new file mode 100644 index 000000000..f5a6b8742 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6994-uint8-clamped-store-rounding.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6994-uint8-clamped-store-rounding.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6995-worker-typed-array-loop-versions.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6995-worker-typed-array-loop-versions.ts.json new file mode 100644 index 000000000..8078248f5 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6995-worker-typed-array-loop-versions.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6995-worker-typed-array-loop-versions.ts" + ], + "diags": [] +} diff --git a/tests/corpus/6994-uint8-clamped-store-rounding.ts b/tests/corpus/6994-uint8-clamped-store-rounding.ts new file mode 100644 index 000000000..5fc3295da --- /dev/null +++ b/tests/corpus/6994-uint8-clamped-store-rounding.ts @@ -0,0 +1,77 @@ +// Uint8ClampedArray stores: NaN and values at most 0 store 0, values at +// least 255 store 255, and values between round to the nearest integer, +// ties to even. Covers single stores and loops, every tie between 0 and +// 255 with the doubles on either side of it, and values far outside. + +/** The largest power of two at most `x` (x > 0). */ +function floorPower(x: number): number { + let p = 1; + while (p * 2 <= x) p *= 2; + while (p > x) p /= 2; + return p; +} + +/** The doubles just above and below `x` (x >= 0). */ +function nextUp(x: number): number { + return x === 0 ? 5e-324 : x + floorPower(x) * 2 ** -52; +} + +function nextDown(x: number): number { + if (x === 0) return -5e-324; + const p = floorPower(x); + return x - (p === x ? p * 2 ** -53 : p * 2 ** -52); +} + +function storeAll(values: Float64Array, out: Uint8ClampedArray): void { + const n = out.length; + for (let i = 0; i < n; i++) out[i] = values[i]!; +} + +function scale(px: Uint8ClampedArray, k: number): void { + const n = px.length; + for (let i = 0; i < n; i++) px[i] = px[i]! * k; +} + +const special = [ + NaN, -NaN, Infinity, -Infinity, 0, -0, 5e-324, -5e-324, 2.2250738585072014e-308, 0.49999999999999994, + 0.5, 0.5000000000000001, 1, 1.5, 2.5, 3.5, 127.5, 128.5, 253.5, 254.49999999999997, 254.5, + 254.50000000000003, 254.99999999999997, 255, 255.00000000000003, 255.5, 256, -1, -0.5, -0.4, + 1e300, -1e300, 2 ** 31, 2 ** 32 + 0.5, 2 ** 52, 2 ** 52 + 1, 2 ** 53, -(2 ** 52), +]; +const one = new Uint8ClampedArray(1); +const singles: number[] = []; +for (const v of special) { + one[0] = v; + singles.push(one[0]!); +} +console.log("single", singles.join(",")); + +const ties: number[] = []; +for (let k = 0; k <= 255; k++) { + ties.push(k + 0.5, nextDown(k + 0.5), nextUp(k + 0.5), k, nextDown(k), nextUp(k)); +} +const values = new Float64Array(ties.length + special.length); +values.set(ties); +values.set(special, ties.length); +const stored = new Uint8ClampedArray(values.length); +storeAll(values, stored); +const expected = new Uint8ClampedArray(values.length); +for (let i = 0; i < values.length; i++) expected[i] = values[i]!; +let mismatches = 0; +for (let i = 0; i < values.length; i++) if (stored[i] !== expected[i]) mismatches++; +console.log("loop", values.length, "mismatches", mismatches); +let digest = 0; +for (let i = 0; i < stored.length; i++) digest = (Math.imul(digest, 31) + stored[i]!) | 0; +console.log("digest", digest, stored.subarray(0, 24).join(",")); +console.log("tail", stored.subarray(ties.length).join(",")); + +const px = new Uint8ClampedArray(64); +for (let i = 0; i < px.length; i++) px[i] = i * 4.25; +scale(px, 1.37); +console.log("scaled", px.join(",")); +scale(px, -1); +console.log("negated", px.join(",")); +const fromInts = new Uint8ClampedArray(8); +const ints = new Int32Array([-300, -1, 0, 1, 254, 255, 256, 2147483647]); +for (let i = 0; i < fromInts.length; i++) fromInts[i] = ints[i]!; +console.log("ints", fromInts.join(",")); diff --git a/tests/corpus/6995-worker-typed-array-loop-versions.ts b/tests/corpus/6995-worker-typed-array-loop-versions.ts new file mode 100644 index 000000000..5b85271b9 --- /dev/null +++ b/tests/corpus/6995-worker-typed-array-loop-versions.ts @@ -0,0 +1,74 @@ +import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads"; + +// Typed-array loops in a worker-enabled program, over views of a thread's +// own ArrayBuffer, views of a SharedArrayBuffer, and both in one loop. Each +// loop gives the same results whichever kind of buffer its views use, and +// writes through shared views are visible to the other thread. + +function scale(src: Float64Array, dst: Float32Array, k: number): void { + for (let i = 0; i < dst.length; i++) dst[i] = src[i]! * k; +} + +function countAbove(view: Int16Array, limit: number): number { + let n = 0; + for (let i = 0; i < view.length; i++) if (view[i]! > limit) n++; + return n; +} + +function mix(a: Uint8Array, b: Uint8Array, out: Uint8ClampedArray): void { + const n = out.length; + for (let i = 0; i < n; i++) out[i] = a[i]! * 2 - b[i]!; +} + +function bump(view: Int32Array, by: number): void { + for (let i = 0; i < view.length; i++) view[i] = (view[i]! + by) | 0; +} + +function report(label: string, src: Float64Array, dst: Float32Array, ints: Int16Array, a: Uint8Array, b: Uint8Array, out: Uint8ClampedArray): string { + for (let i = 0; i < src.length; i++) src[i] = i * 1.5 - 4; + for (let i = 0; i < ints.length; i++) ints[i] = (i * 7919) % 2001 - 1000; + for (let i = 0; i < a.length; i++) { + a[i] = i * 37; + b[i] = 255 - i * 11; + } + scale(src, dst, 0.1); + mix(a, b, out); + return `${label}: ${dst.join(",")} | ${countAbove(ints, 250)} ${countAbove(ints.subarray(3), -1)} | ${out.join(",")}`; +} + +function views(buffer: ArrayBuffer | SharedArrayBuffer, other: ArrayBuffer | SharedArrayBuffer): string { + const src = new Float64Array(buffer, 0, 12); + const dst = new Float32Array(other, 0, 10); + const ints = new Int16Array(buffer, 96, 40); + const a = new Uint8Array(other, 40, 16); + const b = new Uint8Array(buffer, 176, 16); + const out = new Uint8ClampedArray(other, 56, 16); + return report("pair", src, dst, ints, a, b, out); +} + +if (isMainThread) { + // Bytes 224-255 of the shared buffer hold counters the views never use. + const shared = new SharedArrayBuffer(256); + console.log(views(new ArrayBuffer(256), new ArrayBuffer(256))); + console.log(views(shared, new ArrayBuffer(256))); + console.log(views(new ArrayBuffer(256), shared)); + console.log(views(shared, new SharedArrayBuffer(256))); + const own = new Int32Array(8); + bump(own, 5); + bump(new Int32Array(shared, 224, 8), 1); + const worker = new Worker(new URL(import.meta.url), { workerData: shared }); + worker.on("message", (line: string) => console.log(line)); + worker.on("exit", (code: number) => { + const seen = new Int32Array(shared, 224, 8); + bump(seen, 1000); + console.log(`exit ${code}: ${seen.join(",")} own ${own.join(",")}`); + console.log(`dst after worker: ${new Float32Array(shared, 0, 10).join(",")}`); + }); +} else { + const shared = workerData as SharedArrayBuffer; + const counters = new Int32Array(shared, 224, 8); + bump(counters, 10); + bump(counters.subarray(2, 5), -3); + parentPort!.postMessage(`worker: ${counters.join(",")}`); + parentPort!.postMessage(views(new ArrayBuffer(256), shared)); +} diff --git a/tests/harness/corpus-costs/6994-uint8-clamped-store-rounding.ts.json b/tests/harness/corpus-costs/6994-uint8-clamped-store-rounding.ts.json new file mode 100644 index 000000000..a52f2c454 --- /dev/null +++ b/tests/harness/corpus-costs/6994-uint8-clamped-store-rounding.ts.json @@ -0,0 +1 @@ +{ "plain": 2400, "san": 3300 } diff --git a/tests/harness/corpus-costs/6995-worker-typed-array-loop-versions.ts.json b/tests/harness/corpus-costs/6995-worker-typed-array-loop-versions.ts.json new file mode 100644 index 000000000..c0aef3bb7 --- /dev/null +++ b/tests/harness/corpus-costs/6995-worker-typed-array-loop-versions.ts.json @@ -0,0 +1 @@ +{ "plain": 2700, "san": 3900 } From 16cf12c20d66aa23a18308446871e7d55dc18d01 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 02:11:54 -0500 Subject: [PATCH 032/102] Run two-counter for loops on integer counters `for (let lo = a, hi = b; lo < hi; lo++, hi--)` kept both counters as doubles: the counted-loop match takes a single counter, so every `a[lo]`/`a[hi]` converted and tested its index. A loop whose two counters close in on each other by positive literal steps, are not written by the body and index something now stores both as i64: on every body entry both lie between the first start and the second. A start without a proven integer range is tested at run time on a versioned loop, as a counted loop's is. --- .../src/backend/llvm/counted-loops.ts | 81 ++++++++----- .../src/backend/llvm/emit-statements.ts | 58 ++++++++- .../compiler/src/ir/integer-loops.test.ts | 73 ++++++++++- packages/compiler/src/ir/integer-loops.ts | 114 ++++++++++++++++++ .../corpus/7140-paired-loop-counters.ts.json | 6 + tests/corpus/7140-paired-loop-counters.ts | 81 +++++++++++++ .../7140-paired-loop-counters.ts.json | 1 + 7 files changed, 377 insertions(+), 37 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json create mode 100644 tests/corpus/7140-paired-loop-counters.ts create mode 100644 tests/harness/corpus-costs/7140-paired-loop-counters.ts.json diff --git a/packages/compiler/src/backend/llvm/counted-loops.ts b/packages/compiler/src/backend/llvm/counted-loops.ts index 36fc63e1f..02943b852 100644 --- a/packages/compiler/src/backend/llvm/counted-loops.ts +++ b/packages/compiler/src/backend/llvm/counted-loops.ts @@ -1,4 +1,5 @@ -import type { IntegerCountedForLoop } from "../../ir/integer-loops.js"; +import type { IntegerCountedForLoop, IntegerPairedForLoop } from "../../ir/integer-loops.js"; +import type { IrExpr } from "../../ir/ir.js"; import type { LlvmEmitterContext } from "./expr-context.js"; import { f64Lit } from "./common.js"; @@ -59,37 +60,51 @@ export function emitCountedLoopSafety( `${safe} = fcmp ${loop.step > 0 ? "ole" : "oge"} double ${bound.name}, ${f64Lit(loop.guardLimit)}`, ); } - if (loop.startGuarded) { - // An exact integer of at most 2^53 - 1 in magnitude, and not -0 - // (the bit patterns of the value and its round trip agree). - // NaN and infinities fail the ordered range tests. - const start = host.emitExpr(loop.start); - const low = B.tmp(), - high = B.tmp(), - raw = B.tmp(), - wide = B.tmp(), - back = B.tmp(), - bits = B.tmp(), - backBits = B.tmp(), - exact = B.tmp(), - inRange = B.tmp(), - ok = B.tmp(); - B.line(`${low} = fcmp oge double ${start.name}, ${f64Lit(-Number.MAX_SAFE_INTEGER)}`); - B.line(`${high} = fcmp ole double ${start.name}, ${f64Lit(Number.MAX_SAFE_INTEGER)}`); - B.line(`${inRange} = and i1 ${low}, ${high}`); - B.line(`${raw} = fptosi double ${start.name} to i64`); - B.line(`${wide} = freeze i64 ${raw}`); - B.line(`${back} = sitofp i64 ${wide} to double`); - B.line(`${bits} = bitcast double ${start.name} 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}`); - if (safe === "true") safe = ok; - else { - const both = B.tmp(); - B.line(`${both} = and i1 ${safe}, ${ok}`); - safe = both; - } - } + if (loop.startGuarded) safe = andSafe(host, safe, emitExactStart(host, loop.start)); return safe; } + +/** 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 { + let safe = "true"; + for (const counter of [loop.low, loop.high]) + if (counter.startGuarded) safe = andSafe(host, safe, emitExactStart(host, counter.start)); + return safe; +} + +function andSafe(host: LlvmEmitterContext, safe: string, ok: string): string { + if (safe === "true") return ok; + const both = host.B.tmp(); + host.B.line(`${both} = and i1 ${safe}, ${ok}`); + return both; +} + +/** An exact integer of at most 2^53 - 1 in magnitude, and not -0 (the bit + * patterns of the value and its round trip agree). NaN and infinities fail + * the ordered range tests. */ +function emitExactStart(host: LlvmEmitterContext, expr: IrExpr): string { + const B = host.B; + const start = host.emitExpr(expr); + const low = B.tmp(), + high = B.tmp(), + raw = B.tmp(), + wide = B.tmp(), + back = B.tmp(), + bits = B.tmp(), + backBits = B.tmp(), + exact = B.tmp(), + inRange = B.tmp(), + ok = B.tmp(); + B.line(`${low} = fcmp oge double ${start.name}, ${f64Lit(-Number.MAX_SAFE_INTEGER)}`); + B.line(`${high} = fcmp ole double ${start.name}, ${f64Lit(Number.MAX_SAFE_INTEGER)}`); + B.line(`${inRange} = and i1 ${low}, ${high}`); + B.line(`${raw} = fptosi double ${start.name} to i64`); + B.line(`${wide} = freeze i64 ${raw}`); + B.line(`${back} = sitofp i64 ${wide} to double`); + B.line(`${bits} = bitcast double ${start.name} 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; +} diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index 433029651..cf83fc945 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -42,10 +42,15 @@ import { matchIntegerArrayForLoop, matchIntegerBytesForLoop, matchIntegerCountedForLoop, + matchIntegerPairedForLoop, } from "../../ir/integer-loops.js"; import { emitByteWindowGuard, matchByteWindow } from "./byte-windows.js"; import { countedDenseShape, emitDenseLoopGuard, matchDenseArrayLoop } from "./dense-array-loops.js"; -import { emitCountedLoopLimit, emitCountedLoopSafety } from "./counted-loops.js"; +import { + emitCountedLoopLimit, + emitCountedLoopSafety, + emitPairedLoopSafety, +} from "./counted-loops.js"; import { emitBytesLoopVersionGuard } from "./bytes-loop-versions.js"; import { mangleLocal } from "../mangle.js"; import { LlvmUnsupportedError } from "./unsupported.js"; @@ -865,6 +870,12 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { 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 + ? matchIntegerPairedForLoop(s, emitter.numericLocals, emitter.integerRanges) + : null; const window = countedLoop && emitter.byteWindowsEnabled ? matchByteWindow( @@ -993,8 +1004,10 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { break; } let countedJoin: string | null = null; - if (countedLoop?.guarded && !emitter.provenCountedGuards.has(s)) { - const safe = emitCountedLoopSafety(emitter, countedLoop); + if ((countedLoop?.guarded && !emitter.provenCountedGuards.has(s)) || pairedLoop?.guarded) { + const safe = countedLoop + ? emitCountedLoopSafety(emitter, countedLoop) + : emitPairedLoopSafety(emitter, pairedLoop!); const fast = B.newLabel("counted.fast"); const slow = B.newLabel("counted.slow"); countedJoin = B.newLabel("counted.done"); @@ -1009,6 +1022,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { emitter.scopes.push([]); let integerSlot: string | null = null; let countedLimit: string | null = null; + const pairedSlots: string[] = []; if (integerLoop) { integerSlot = B.slot(); B.entryAllocas.push( @@ -1053,6 +1067,24 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { : countedLoop.range, }); countedLimit = emitCountedLoopLimit(emitter, countedLoop); + } else if (pairedLoop) { + for (const counter of [pairedLoop.low, pairedLoop.high]) { + const slot = B.slot(); + B.entryAllocas.push( + `${slot} = alloca i64 ; integer induction ${emitter.currentLocals.get(counter.localId)!.name}`, + ); + const value = emitter.emitExpr(counter.start); + const start = B.tmp(); + B.line(`${start} = fptosi double ${value.name} to i64`); + B.line(`store i64 ${start}, ptr ${slot}`); + pairedSlots.push(slot); + emitter.integerLoopBindings.set(counter.localId, { + slot, + type: "i64", + signed: true, + range: pairedLoop.range, + }); + } } else if (s.init) { // A multi-declarator head shares the loop's scope. Emitting its // IR block as an ordinary block would release captured/ref locals @@ -1134,6 +1166,14 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { `${inBounds} = icmp ${countedLoop.step > 0 ? "slt" : "sgt"} i64 ${index}, ${countedLimit}`, ); B.condBr(inBounds, lb, exit); + } else if (pairedLoop) { + const low = B.tmp(), + high = B.tmp(), + open = B.tmp(); + B.line(`${low} = load i64, ptr ${pairedSlots[0]}`); + B.line(`${high} = load i64, ptr ${pairedSlots[1]}`); + B.line(`${open} = icmp ${pairedLoop.inclusive ? "sle" : "slt"} i64 ${low}, ${high}`); + B.condBr(open, lb, exit); } else if (s.cond) B.condBr(emitter.emitCondition(s.cond), lb, exit); else B.br(lb); B.startBlock(lb); @@ -1165,6 +1205,14 @@ 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}`); + } else if (pairedLoop) { + [pairedLoop.low, pairedLoop.high].forEach((counter, i) => { + const old = B.tmp(); + const next = B.tmp(); + B.line(`${old} = load i64, ptr ${pairedSlots[i]}`); + B.line(`${next} = add nsw i64 ${old}, ${counter.step}`); + B.line(`store i64 ${next}, ptr ${pairedSlots[i]}`); + }); } else if (s.update) emitter.emitStmt(s.update); B.br(lc); } @@ -1173,6 +1221,10 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { emitter.releaseScope(emitter.scopes.pop()!); if (integerLoop) emitter.integerLoopBindings.delete(integerLoop.localId); if (countedLoop) emitter.integerLoopBindings.delete(countedLoop.localId); + if (pairedLoop) { + emitter.integerLoopBindings.delete(pairedLoop.low.localId); + emitter.integerLoopBindings.delete(pairedLoop.high.localId); + } if (integerArrayLoop) emitter.integerArrayBindings.delete(integerArrayLoop.localId); if (countedJoin) { B.br(countedJoin); diff --git a/packages/compiler/src/ir/integer-loops.test.ts b/packages/compiler/src/ir/integer-loops.test.ts index aada3b053..24bbf5be0 100644 --- a/packages/compiler/src/ir/integer-loops.test.ts +++ b/packages/compiler/src/ir/integer-loops.test.ts @@ -1,6 +1,10 @@ import { expect, test } from "vitest"; import { BOOL, F64, STRING, arrayOf, type IrExpr, type IrLocal, type IrStmt } from "./ir.js"; -import { matchIntegerArrayForLoop, matchIntegerCountedForLoop } from "./integer-loops.js"; +import { + matchIntegerArrayForLoop, + matchIntegerCountedForLoop, + matchIntegerPairedForLoop, +} from "./integer-loops.js"; const loc = { file: "integer-array-loop.ts", start: 0, end: 0 }; const number = (value: number): IrExpr => ({ kind: "numLit", value, type: F64, loc }); @@ -355,3 +359,70 @@ test("a descending loop from an array's last index takes an integer counter for range: { min: 0, max: 4294967294 }, }); }); + +test("paired counters closing in on each other run as integers", () => { + const vars = new Map(locals); + for (const id of ["lo", "hi", "head"]) vars.set(id, { id, name: id, type: F64, mutable: true }); + 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 element = (index: IrExpr): IrExpr => ({ + kind: "arrayGet", + arr: { kind: "varRef", localId: "a", type: arrayOf(F64), loc }, + index, + type: F64, + loc, + }); + const paired = ( + lowStart: IrExpr, + highStart: IrExpr, + update = [step("lo", "+"), step("hi", "-")], + ) => + ({ + kind: "for", + loc, + init: { + kind: "block", + body: [ + { kind: "varDecl", localId: "lo", init: lowStart, loc }, + { kind: "varDecl", localId: "hi", init: highStart, loc }, + ], + loc, + }, + cond: { kind: "bin", op: "<", left: ref("lo"), right: ref("hi"), type: BOOL, loc }, + update: { kind: "block", body: update, loc }, + body: [{ kind: "exprStmt", expr: element(ref("hi")), loc }], + }) as IrStmt & { kind: "for" }; + expect(matchIntegerPairedForLoop(paired(number(0), number(9)), vars)).toMatchObject({ + low: { localId: "lo", step: 1, startGuarded: false }, + high: { localId: "hi", step: -1, startGuarded: false }, + guarded: false, + range: { min: 0, max: 9 }, + }); + // A start without a known range is tested at run time. + expect(matchIntegerPairedForLoop(paired(number(0), ref("head")), vars)).toMatchObject({ + high: { startGuarded: true }, + guarded: true, + }); + // Counters moving the same way, written by the body, captured, started + // from each other, or never used as an index are refused. + expect( + matchIntegerPairedForLoop( + paired(number(0), number(9), [step("lo", "+"), step("hi", "+")]), + vars, + ), + ).toBeNull(); + const writing = paired(number(0), number(9)); + writing.body.push(step("hi", "-", 2)); + expect(matchIntegerPairedForLoop(writing, vars)).toBeNull(); + const boxed = new Map(vars); + boxed.set("hi", { ...vars.get("hi")!, boxed: true }); + expect(matchIntegerPairedForLoop(paired(number(0), number(9)), boxed)).toBeNull(); + expect(matchIntegerPairedForLoop(paired(number(0), ref("lo")), vars)).toBeNull(); + const unused = paired(number(0), number(9)); + unused.body = []; + expect(matchIntegerPairedForLoop(unused, vars)).toBeNull(); +}); diff --git a/packages/compiler/src/ir/integer-loops.ts b/packages/compiler/src/ir/integer-loops.ts index 9b4675685..e80680d6e 100644 --- a/packages/compiler/src/ir/integer-loops.ts +++ b/packages/compiler/src/ir/integer-loops.ts @@ -281,6 +281,120 @@ export function matchIntegerCountedForLoop( }; } +/** A for loop whose two counters close in on each other: + * + * for (let lo = a, hi = b; lo < hi; lo++, hi--) { ... } + * + * The first counter only grows and the second only shrinks, by positive + * literal steps, the body writes neither, and the loop runs while the first + * is below (or at most) the second. Every body entry therefore holds both + * between the first start and the second start: exact integers when the + * starts are. A start without a proven integer range is tested at run time + * on a versioned loop, as a counted loop's is. */ +export interface IntegerPairedCounter { + localId: string; + start: IrExpr; + /** The signed step of each update. */ + step: number; + startGuarded: boolean; +} +export interface IntegerPairedForLoop { + low: IntegerPairedCounter; + high: IntegerPairedCounter; + inclusive: boolean; + guarded: boolean; + /** Both counters' values on every body entry. */ + range: IntegerRange; +} + +export function matchIntegerPairedForLoop( + stmt: IrStmt & { kind: "for" }, + locals: ReadonlyMap, + ranges: IntegerRanges = new Map(), +): IntegerPairedForLoop | null { + const init = stmt.init, + update = stmt.update, + cond = stmt.cond; + if (init?.kind !== "block" || init.body.length !== 2) return null; + if (update?.kind !== "block" || update.body.length !== 2) return null; + if (cond?.kind !== "bin" || (cond.op !== "<" && cond.op !== "<=")) return null; + if (cond.left.kind !== "varRef" || cond.right.kind !== "varRef") return null; + const lowId = cond.left.localId, + highId = cond.right.localId; + if (lowId === highId) return null; + const counter = (id: string): IntegerPairedCounter | null => { + const decl = init.body.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; + // Each start is evaluated once in the head and again on a fallback path. + if ( + !stableLoopValue(start, locals, stmt.body, false, lowId) || + !stableLoopValue(start, locals, stmt.body, false, highId) + ) + return null; + const steps = update.body.map((u) => constantStep(u, id)).filter((v) => v !== null); + if (steps.length !== 1 || writesLocal(stmt.body, id)) return null; + const known = + start.kind === "numLit" && Number.isSafeInteger(start.value) && !Object.is(start.value, -0) + ? { min: start.value, max: start.value } + : ranges.get(start); + const startGuarded = !known && start.kind !== "numLit" && start.type.kind === "f64"; + if (!known && !startGuarded) return null; + if (known && (known.min < -Number.MAX_SAFE_INTEGER || known.max > Number.MAX_SAFE_INTEGER)) + return null; + return { localId: id, start, step: steps[0]!, startGuarded }; + }; + const low = counter(lowId), + high = counter(highId); + if (!low || !high || low.step <= 0 || high.step >= 0) return null; + const startRange = (c: IntegerPairedCounter): IntegerRange => + c.startGuarded + ? { min: -Number.MAX_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER } + : c.start.kind === "numLit" + ? { min: c.start.value, max: c.start.value } + : ranges.get(c.start)!; + const guarded = low.startGuarded || high.startGuarded; + // Only a loop whose counters index something gains from integer storage. + let useful = false, + cost = 0; + const isCounter = (e: IrExpr): boolean => + (e.kind === "varRef" && (e.localId === lowId || e.localId === highId)) || + (e.kind === "bin" && + (e.op === "+" || e.op === "-") && + (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])) + useful = true; + if (e.kind === "bytesIntrinsic" && e.method === "get" && e.args[0] && isCounter(e.args[0])) + useful = true; + return (!guarded || ++cost <= 80) && everyExprChild(e, expr, bodyStmt); + }; + const bodyStmt = (s: IrStmt): boolean => { + if ((s.kind === "arraySet" || s.kind === "bytesSet") && isCounter(s.index)) useful = true; + if ( + guarded && + (s.kind === "for" || s.kind === "forOf" || s.kind === "while" || s.kind === "doWhile") + ) + return false; + return (!guarded || ++cost <= 80) && everyStmtChild(s, expr, bodyStmt); + }; + if (!stmt.body.every(bodyStmt) || !useful) return null; + return { + low, + high, + inclusive: cond.op === "<=", + guarded, + // A loop whose starts already fail the condition never enters the body. + range: { + min: startRange(low).min, + max: Math.max(startRange(low).min, startRange(high).max), + }, + }; +} + /** True when a lowered subtree writes `localId`. Local ids are unique per * function, so typed traversal includes writes * nested in expressions, branches, nested loops, and try/finally bodies. */ diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json new file mode 100644 index 000000000..122d64bb6 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7140-paired-loop-counters.ts" + ], + "diags": [] +} diff --git a/tests/corpus/7140-paired-loop-counters.ts b/tests/corpus/7140-paired-loop-counters.ts new file mode 100644 index 000000000..ec1610d1a --- /dev/null +++ b/tests/corpus/7140-paired-loop-counters.ts @@ -0,0 +1,81 @@ +// For loops with two counters closing in on each other (`lo++, hi--`): +// in-place reversals, inclusive bounds, larger steps, early exits, starts +// that are fractions, negative zero, NaN, huge or already crossed, nested +// reversals, and counters a closure captures or the body writes. +function reverse(a: number[], from: number, to: number): number[] { + for (let lo = from, hi = to; lo < hi; lo++, hi--) { + const t = a[lo]!; + a[lo] = a[hi]!; + a[hi] = t; + } + return a; +} +const base = (): number[] => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; +console.log(reverse(base(), 0, 9).join(",")); +console.log(reverse(base(), 2, 6).join(",")); +console.log(reverse(base(), 6, 2).join(",")); +console.log(reverse(base(), 3, 3).join(",")); +// Unproven starts: fractions, negative zero, NaN and huge values keep JS +// semantics (charCodeAt truncates its index; out-of-range reads are NaN). +function codes(s: string, from: number, to: number): string { + const out: number[] = []; + for (let lo = from, hi = to; lo < hi; lo++, hi--) out.push(s.charCodeAt(lo), s.charCodeAt(hi), lo, hi); + return out.join(","); +} +const word = "abcdefgh"; +console.log(codes(word, 0.5, 4.5)); +console.log(codes(word, -0, 3), Object.is(-0 + 0, 0)); +console.log(codes(word, NaN, 4), "|", codes(word, 0, NaN)); +console.log(codes(word, 2 ** 53 - 3, 2 ** 53)); +console.log(codes(word, -3, 2)); + +function pairs(n: number): string { + const out: string[] = []; + for (let i = 0, j = n; i <= j; i += 2, j -= 3) out.push(`${i}:${j}`); + return out.join(" "); +} +console.log(pairs(20), "|", pairs(0), "|", pairs(-1)); + +function firstGap(a: number[]): number { + let found = -1; + for (let lo = 0, hi = a.length - 1; lo < hi; lo++, hi--) { + if (a[lo] === a[hi]) continue; + found = lo; + break; + } + return found; +} +console.log(firstGap([1, 2, 3, 2, 1]), firstGap([1, 2, 3, 4, 2, 1]), firstGap([])); + +// The flip loop of a permutation puzzle: the next index comes from the array. +function flips(perm: number[]): number { + const work = perm.slice(); + let count = 0; + let head = work[0]!; + while (head !== 0) { + for (let lo = 0, hi = head; lo < hi; lo++, hi--) { + const t = work[lo]!; + work[lo] = work[hi]!; + work[hi] = t; + } + count++; + head = work[0]!; + } + return count; +} +console.log(flips([3, 1, 0, 2]), flips([4, 3, 2, 1, 0]), flips([0, 1, 2])); + +// Counters a closure reads, or the body writes, stay ordinary bindings. +const readers: (() => number)[] = []; +for (let lo = 0, hi = 4; lo < hi; lo++, hi--) readers.push(() => lo * 10 + hi); +console.log(readers.map((f) => f()).join(",")); +const seen: number[] = []; +for (let lo = 0, hi = 10; lo < hi; lo++, hi--) { + seen.push(lo, hi); + if (lo === 2) hi -= 3; +} +console.log(seen.join(",")); +const text = "abcdefgh"; +let mirrored = ""; +for (let lo = 0, hi = text.length - 1; lo <= hi; lo++, hi--) mirrored += text.charAt(hi) + text.charCodeAt(lo); +console.log(mirrored); diff --git a/tests/harness/corpus-costs/7140-paired-loop-counters.ts.json b/tests/harness/corpus-costs/7140-paired-loop-counters.ts.json new file mode 100644 index 000000000..549fd6a4a --- /dev/null +++ b/tests/harness/corpus-costs/7140-paired-loop-counters.ts.json @@ -0,0 +1 @@ +{ "plain": 3880, "san": 6000 } From d1ff061833279865ddff6cba84b4f2d5dd362ebc Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 02:48:13 -0500 Subject: [PATCH 033/102] Revert "Run two-counter for loops on integer counters" This reverts #1768 (8fec4484d), which made main CI fail. --- .../src/backend/llvm/counted-loops.ts | 81 +++++-------- .../src/backend/llvm/emit-statements.ts | 58 +-------- .../compiler/src/ir/integer-loops.test.ts | 73 +---------- packages/compiler/src/ir/integer-loops.ts | 114 ------------------ .../corpus/7140-paired-loop-counters.ts.json | 6 - tests/corpus/7140-paired-loop-counters.ts | 81 ------------- .../7140-paired-loop-counters.ts.json | 1 - 7 files changed, 37 insertions(+), 377 deletions(-) delete mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json delete mode 100644 tests/corpus/7140-paired-loop-counters.ts delete mode 100644 tests/harness/corpus-costs/7140-paired-loop-counters.ts.json diff --git a/packages/compiler/src/backend/llvm/counted-loops.ts b/packages/compiler/src/backend/llvm/counted-loops.ts index 02943b852..36fc63e1f 100644 --- a/packages/compiler/src/backend/llvm/counted-loops.ts +++ b/packages/compiler/src/backend/llvm/counted-loops.ts @@ -1,5 +1,4 @@ -import type { IntegerCountedForLoop, IntegerPairedForLoop } from "../../ir/integer-loops.js"; -import type { IrExpr } from "../../ir/ir.js"; +import type { IntegerCountedForLoop } from "../../ir/integer-loops.js"; import type { LlvmEmitterContext } from "./expr-context.js"; import { f64Lit } from "./common.js"; @@ -60,51 +59,37 @@ export function emitCountedLoopSafety( `${safe} = fcmp ${loop.step > 0 ? "ole" : "oge"} double ${bound.name}, ${f64Lit(loop.guardLimit)}`, ); } - if (loop.startGuarded) safe = andSafe(host, safe, emitExactStart(host, loop.start)); + if (loop.startGuarded) { + // An exact integer of at most 2^53 - 1 in magnitude, and not -0 + // (the bit patterns of the value and its round trip agree). + // NaN and infinities fail the ordered range tests. + const start = host.emitExpr(loop.start); + const low = B.tmp(), + high = B.tmp(), + raw = B.tmp(), + wide = B.tmp(), + back = B.tmp(), + bits = B.tmp(), + backBits = B.tmp(), + exact = B.tmp(), + inRange = B.tmp(), + ok = B.tmp(); + B.line(`${low} = fcmp oge double ${start.name}, ${f64Lit(-Number.MAX_SAFE_INTEGER)}`); + B.line(`${high} = fcmp ole double ${start.name}, ${f64Lit(Number.MAX_SAFE_INTEGER)}`); + B.line(`${inRange} = and i1 ${low}, ${high}`); + B.line(`${raw} = fptosi double ${start.name} to i64`); + B.line(`${wide} = freeze i64 ${raw}`); + B.line(`${back} = sitofp i64 ${wide} to double`); + B.line(`${bits} = bitcast double ${start.name} 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}`); + if (safe === "true") safe = ok; + else { + const both = B.tmp(); + B.line(`${both} = and i1 ${safe}, ${ok}`); + safe = both; + } + } return safe; } - -/** 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 { - let safe = "true"; - for (const counter of [loop.low, loop.high]) - if (counter.startGuarded) safe = andSafe(host, safe, emitExactStart(host, counter.start)); - return safe; -} - -function andSafe(host: LlvmEmitterContext, safe: string, ok: string): string { - if (safe === "true") return ok; - const both = host.B.tmp(); - host.B.line(`${both} = and i1 ${safe}, ${ok}`); - return both; -} - -/** An exact integer of at most 2^53 - 1 in magnitude, and not -0 (the bit - * patterns of the value and its round trip agree). NaN and infinities fail - * the ordered range tests. */ -function emitExactStart(host: LlvmEmitterContext, expr: IrExpr): string { - const B = host.B; - const start = host.emitExpr(expr); - const low = B.tmp(), - high = B.tmp(), - raw = B.tmp(), - wide = B.tmp(), - back = B.tmp(), - bits = B.tmp(), - backBits = B.tmp(), - exact = B.tmp(), - inRange = B.tmp(), - ok = B.tmp(); - B.line(`${low} = fcmp oge double ${start.name}, ${f64Lit(-Number.MAX_SAFE_INTEGER)}`); - B.line(`${high} = fcmp ole double ${start.name}, ${f64Lit(Number.MAX_SAFE_INTEGER)}`); - B.line(`${inRange} = and i1 ${low}, ${high}`); - B.line(`${raw} = fptosi double ${start.name} to i64`); - B.line(`${wide} = freeze i64 ${raw}`); - B.line(`${back} = sitofp i64 ${wide} to double`); - B.line(`${bits} = bitcast double ${start.name} 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; -} diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index e15de353a..d2e96994b 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -42,15 +42,10 @@ import { matchIntegerArrayForLoop, matchIntegerBytesForLoop, matchIntegerCountedForLoop, - matchIntegerPairedForLoop, } from "../../ir/integer-loops.js"; import { emitByteWindowGuard, matchByteWindow } from "./byte-windows.js"; import { countedDenseShape, emitDenseLoopGuard, matchDenseArrayLoop } from "./dense-array-loops.js"; -import { - emitCountedLoopLimit, - emitCountedLoopSafety, - emitPairedLoopSafety, -} from "./counted-loops.js"; +import { emitCountedLoopLimit, emitCountedLoopSafety } from "./counted-loops.js"; import { emitBytesLoopVersionGuard } from "./bytes-loop-versions.js"; import { mangleLocal } from "../mangle.js"; import { LlvmUnsupportedError } from "./unsupported.js"; @@ -871,12 +866,6 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { 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 - ? matchIntegerPairedForLoop(s, emitter.numericLocals, emitter.integerRanges) - : null; const window = countedLoop && emitter.byteWindowsEnabled ? matchByteWindow( @@ -1009,10 +998,8 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { break; } let countedJoin: string | null = null; - if ((countedLoop?.guarded && !emitter.provenCountedGuards.has(s)) || pairedLoop?.guarded) { - const safe = countedLoop - ? emitCountedLoopSafety(emitter, countedLoop) - : emitPairedLoopSafety(emitter, pairedLoop!); + if (countedLoop?.guarded && !emitter.provenCountedGuards.has(s)) { + const safe = emitCountedLoopSafety(emitter, countedLoop); const fast = B.newLabel("counted.fast"); const slow = B.newLabel("counted.slow"); countedJoin = B.newLabel("counted.done"); @@ -1027,7 +1014,6 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { emitter.scopes.push([]); let integerSlot: string | null = null; let countedLimit: string | null = null; - const pairedSlots: string[] = []; if (integerLoop) { integerSlot = B.slot(); B.entryAllocas.push( @@ -1072,24 +1058,6 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { : countedLoop.range, }); countedLimit = emitCountedLoopLimit(emitter, countedLoop); - } else if (pairedLoop) { - for (const counter of [pairedLoop.low, pairedLoop.high]) { - const slot = B.slot(); - B.entryAllocas.push( - `${slot} = alloca i64 ; integer induction ${emitter.currentLocals.get(counter.localId)!.name}`, - ); - const value = emitter.emitExpr(counter.start); - const start = B.tmp(); - B.line(`${start} = fptosi double ${value.name} to i64`); - B.line(`store i64 ${start}, ptr ${slot}`); - pairedSlots.push(slot); - emitter.integerLoopBindings.set(counter.localId, { - slot, - type: "i64", - signed: true, - range: pairedLoop.range, - }); - } } else if (s.init) { // A multi-declarator head shares the loop's scope. Emitting its // IR block as an ordinary block would release captured/ref locals @@ -1171,14 +1139,6 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { `${inBounds} = icmp ${countedLoop.step > 0 ? "slt" : "sgt"} i64 ${index}, ${countedLimit}`, ); B.condBr(inBounds, lb, exit); - } else if (pairedLoop) { - const low = B.tmp(), - high = B.tmp(), - open = B.tmp(); - B.line(`${low} = load i64, ptr ${pairedSlots[0]}`); - B.line(`${high} = load i64, ptr ${pairedSlots[1]}`); - B.line(`${open} = icmp ${pairedLoop.inclusive ? "sle" : "slt"} i64 ${low}, ${high}`); - B.condBr(open, lb, exit); } else if (s.cond) B.condBr(emitter.emitCondition(s.cond), lb, exit); else B.br(lb); B.startBlock(lb); @@ -1210,14 +1170,6 @@ 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}`); - } else if (pairedLoop) { - [pairedLoop.low, pairedLoop.high].forEach((counter, i) => { - const old = B.tmp(); - const next = B.tmp(); - B.line(`${old} = load i64, ptr ${pairedSlots[i]}`); - B.line(`${next} = add nsw i64 ${old}, ${counter.step}`); - B.line(`store i64 ${next}, ptr ${pairedSlots[i]}`); - }); } else if (s.update) emitter.emitStmt(s.update); B.br(lc); } @@ -1226,10 +1178,6 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { emitter.releaseScope(emitter.scopes.pop()!); if (integerLoop) emitter.integerLoopBindings.delete(integerLoop.localId); if (countedLoop) emitter.integerLoopBindings.delete(countedLoop.localId); - if (pairedLoop) { - emitter.integerLoopBindings.delete(pairedLoop.low.localId); - emitter.integerLoopBindings.delete(pairedLoop.high.localId); - } if (integerArrayLoop) emitter.integerArrayBindings.delete(integerArrayLoop.localId); if (countedJoin) { B.br(countedJoin); diff --git a/packages/compiler/src/ir/integer-loops.test.ts b/packages/compiler/src/ir/integer-loops.test.ts index 24bbf5be0..aada3b053 100644 --- a/packages/compiler/src/ir/integer-loops.test.ts +++ b/packages/compiler/src/ir/integer-loops.test.ts @@ -1,10 +1,6 @@ import { expect, test } from "vitest"; import { BOOL, F64, STRING, arrayOf, type IrExpr, type IrLocal, type IrStmt } from "./ir.js"; -import { - matchIntegerArrayForLoop, - matchIntegerCountedForLoop, - matchIntegerPairedForLoop, -} from "./integer-loops.js"; +import { matchIntegerArrayForLoop, matchIntegerCountedForLoop } from "./integer-loops.js"; const loc = { file: "integer-array-loop.ts", start: 0, end: 0 }; const number = (value: number): IrExpr => ({ kind: "numLit", value, type: F64, loc }); @@ -359,70 +355,3 @@ test("a descending loop from an array's last index takes an integer counter for range: { min: 0, max: 4294967294 }, }); }); - -test("paired counters closing in on each other run as integers", () => { - const vars = new Map(locals); - for (const id of ["lo", "hi", "head"]) vars.set(id, { id, name: id, type: F64, mutable: true }); - 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 element = (index: IrExpr): IrExpr => ({ - kind: "arrayGet", - arr: { kind: "varRef", localId: "a", type: arrayOf(F64), loc }, - index, - type: F64, - loc, - }); - const paired = ( - lowStart: IrExpr, - highStart: IrExpr, - update = [step("lo", "+"), step("hi", "-")], - ) => - ({ - kind: "for", - loc, - init: { - kind: "block", - body: [ - { kind: "varDecl", localId: "lo", init: lowStart, loc }, - { kind: "varDecl", localId: "hi", init: highStart, loc }, - ], - loc, - }, - cond: { kind: "bin", op: "<", left: ref("lo"), right: ref("hi"), type: BOOL, loc }, - update: { kind: "block", body: update, loc }, - body: [{ kind: "exprStmt", expr: element(ref("hi")), loc }], - }) as IrStmt & { kind: "for" }; - expect(matchIntegerPairedForLoop(paired(number(0), number(9)), vars)).toMatchObject({ - low: { localId: "lo", step: 1, startGuarded: false }, - high: { localId: "hi", step: -1, startGuarded: false }, - guarded: false, - range: { min: 0, max: 9 }, - }); - // A start without a known range is tested at run time. - expect(matchIntegerPairedForLoop(paired(number(0), ref("head")), vars)).toMatchObject({ - high: { startGuarded: true }, - guarded: true, - }); - // Counters moving the same way, written by the body, captured, started - // from each other, or never used as an index are refused. - expect( - matchIntegerPairedForLoop( - paired(number(0), number(9), [step("lo", "+"), step("hi", "+")]), - vars, - ), - ).toBeNull(); - const writing = paired(number(0), number(9)); - writing.body.push(step("hi", "-", 2)); - expect(matchIntegerPairedForLoop(writing, vars)).toBeNull(); - const boxed = new Map(vars); - boxed.set("hi", { ...vars.get("hi")!, boxed: true }); - expect(matchIntegerPairedForLoop(paired(number(0), number(9)), boxed)).toBeNull(); - expect(matchIntegerPairedForLoop(paired(number(0), ref("lo")), vars)).toBeNull(); - const unused = paired(number(0), number(9)); - unused.body = []; - expect(matchIntegerPairedForLoop(unused, vars)).toBeNull(); -}); diff --git a/packages/compiler/src/ir/integer-loops.ts b/packages/compiler/src/ir/integer-loops.ts index e80680d6e..9b4675685 100644 --- a/packages/compiler/src/ir/integer-loops.ts +++ b/packages/compiler/src/ir/integer-loops.ts @@ -281,120 +281,6 @@ export function matchIntegerCountedForLoop( }; } -/** A for loop whose two counters close in on each other: - * - * for (let lo = a, hi = b; lo < hi; lo++, hi--) { ... } - * - * The first counter only grows and the second only shrinks, by positive - * literal steps, the body writes neither, and the loop runs while the first - * is below (or at most) the second. Every body entry therefore holds both - * between the first start and the second start: exact integers when the - * starts are. A start without a proven integer range is tested at run time - * on a versioned loop, as a counted loop's is. */ -export interface IntegerPairedCounter { - localId: string; - start: IrExpr; - /** The signed step of each update. */ - step: number; - startGuarded: boolean; -} -export interface IntegerPairedForLoop { - low: IntegerPairedCounter; - high: IntegerPairedCounter; - inclusive: boolean; - guarded: boolean; - /** Both counters' values on every body entry. */ - range: IntegerRange; -} - -export function matchIntegerPairedForLoop( - stmt: IrStmt & { kind: "for" }, - locals: ReadonlyMap, - ranges: IntegerRanges = new Map(), -): IntegerPairedForLoop | null { - const init = stmt.init, - update = stmt.update, - cond = stmt.cond; - if (init?.kind !== "block" || init.body.length !== 2) return null; - if (update?.kind !== "block" || update.body.length !== 2) return null; - if (cond?.kind !== "bin" || (cond.op !== "<" && cond.op !== "<=")) return null; - if (cond.left.kind !== "varRef" || cond.right.kind !== "varRef") return null; - const lowId = cond.left.localId, - highId = cond.right.localId; - if (lowId === highId) return null; - const counter = (id: string): IntegerPairedCounter | null => { - const decl = init.body.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; - // Each start is evaluated once in the head and again on a fallback path. - if ( - !stableLoopValue(start, locals, stmt.body, false, lowId) || - !stableLoopValue(start, locals, stmt.body, false, highId) - ) - return null; - const steps = update.body.map((u) => constantStep(u, id)).filter((v) => v !== null); - if (steps.length !== 1 || writesLocal(stmt.body, id)) return null; - const known = - start.kind === "numLit" && Number.isSafeInteger(start.value) && !Object.is(start.value, -0) - ? { min: start.value, max: start.value } - : ranges.get(start); - const startGuarded = !known && start.kind !== "numLit" && start.type.kind === "f64"; - if (!known && !startGuarded) return null; - if (known && (known.min < -Number.MAX_SAFE_INTEGER || known.max > Number.MAX_SAFE_INTEGER)) - return null; - return { localId: id, start, step: steps[0]!, startGuarded }; - }; - const low = counter(lowId), - high = counter(highId); - if (!low || !high || low.step <= 0 || high.step >= 0) return null; - const startRange = (c: IntegerPairedCounter): IntegerRange => - c.startGuarded - ? { min: -Number.MAX_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER } - : c.start.kind === "numLit" - ? { min: c.start.value, max: c.start.value } - : ranges.get(c.start)!; - const guarded = low.startGuarded || high.startGuarded; - // Only a loop whose counters index something gains from integer storage. - let useful = false, - cost = 0; - const isCounter = (e: IrExpr): boolean => - (e.kind === "varRef" && (e.localId === lowId || e.localId === highId)) || - (e.kind === "bin" && - (e.op === "+" || e.op === "-") && - (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])) - useful = true; - if (e.kind === "bytesIntrinsic" && e.method === "get" && e.args[0] && isCounter(e.args[0])) - useful = true; - return (!guarded || ++cost <= 80) && everyExprChild(e, expr, bodyStmt); - }; - const bodyStmt = (s: IrStmt): boolean => { - if ((s.kind === "arraySet" || s.kind === "bytesSet") && isCounter(s.index)) useful = true; - if ( - guarded && - (s.kind === "for" || s.kind === "forOf" || s.kind === "while" || s.kind === "doWhile") - ) - return false; - return (!guarded || ++cost <= 80) && everyStmtChild(s, expr, bodyStmt); - }; - if (!stmt.body.every(bodyStmt) || !useful) return null; - return { - low, - high, - inclusive: cond.op === "<=", - guarded, - // A loop whose starts already fail the condition never enters the body. - range: { - min: startRange(low).min, - max: Math.max(startRange(low).min, startRange(high).max), - }, - }; -} - /** True when a lowered subtree writes `localId`. Local ids are unique per * function, so typed traversal includes writes * nested in expressions, branches, nested loops, and try/finally bodies. */ diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json deleted file mode 100644 index 122d64bb6..000000000 --- a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "order": [ - "/tests/corpus/7140-paired-loop-counters.ts" - ], - "diags": [] -} diff --git a/tests/corpus/7140-paired-loop-counters.ts b/tests/corpus/7140-paired-loop-counters.ts deleted file mode 100644 index ec1610d1a..000000000 --- a/tests/corpus/7140-paired-loop-counters.ts +++ /dev/null @@ -1,81 +0,0 @@ -// For loops with two counters closing in on each other (`lo++, hi--`): -// in-place reversals, inclusive bounds, larger steps, early exits, starts -// that are fractions, negative zero, NaN, huge or already crossed, nested -// reversals, and counters a closure captures or the body writes. -function reverse(a: number[], from: number, to: number): number[] { - for (let lo = from, hi = to; lo < hi; lo++, hi--) { - const t = a[lo]!; - a[lo] = a[hi]!; - a[hi] = t; - } - return a; -} -const base = (): number[] => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; -console.log(reverse(base(), 0, 9).join(",")); -console.log(reverse(base(), 2, 6).join(",")); -console.log(reverse(base(), 6, 2).join(",")); -console.log(reverse(base(), 3, 3).join(",")); -// Unproven starts: fractions, negative zero, NaN and huge values keep JS -// semantics (charCodeAt truncates its index; out-of-range reads are NaN). -function codes(s: string, from: number, to: number): string { - const out: number[] = []; - for (let lo = from, hi = to; lo < hi; lo++, hi--) out.push(s.charCodeAt(lo), s.charCodeAt(hi), lo, hi); - return out.join(","); -} -const word = "abcdefgh"; -console.log(codes(word, 0.5, 4.5)); -console.log(codes(word, -0, 3), Object.is(-0 + 0, 0)); -console.log(codes(word, NaN, 4), "|", codes(word, 0, NaN)); -console.log(codes(word, 2 ** 53 - 3, 2 ** 53)); -console.log(codes(word, -3, 2)); - -function pairs(n: number): string { - const out: string[] = []; - for (let i = 0, j = n; i <= j; i += 2, j -= 3) out.push(`${i}:${j}`); - return out.join(" "); -} -console.log(pairs(20), "|", pairs(0), "|", pairs(-1)); - -function firstGap(a: number[]): number { - let found = -1; - for (let lo = 0, hi = a.length - 1; lo < hi; lo++, hi--) { - if (a[lo] === a[hi]) continue; - found = lo; - break; - } - return found; -} -console.log(firstGap([1, 2, 3, 2, 1]), firstGap([1, 2, 3, 4, 2, 1]), firstGap([])); - -// The flip loop of a permutation puzzle: the next index comes from the array. -function flips(perm: number[]): number { - const work = perm.slice(); - let count = 0; - let head = work[0]!; - while (head !== 0) { - for (let lo = 0, hi = head; lo < hi; lo++, hi--) { - const t = work[lo]!; - work[lo] = work[hi]!; - work[hi] = t; - } - count++; - head = work[0]!; - } - return count; -} -console.log(flips([3, 1, 0, 2]), flips([4, 3, 2, 1, 0]), flips([0, 1, 2])); - -// Counters a closure reads, or the body writes, stay ordinary bindings. -const readers: (() => number)[] = []; -for (let lo = 0, hi = 4; lo < hi; lo++, hi--) readers.push(() => lo * 10 + hi); -console.log(readers.map((f) => f()).join(",")); -const seen: number[] = []; -for (let lo = 0, hi = 10; lo < hi; lo++, hi--) { - seen.push(lo, hi); - if (lo === 2) hi -= 3; -} -console.log(seen.join(",")); -const text = "abcdefgh"; -let mirrored = ""; -for (let lo = 0, hi = text.length - 1; lo <= hi; lo++, hi--) mirrored += text.charAt(hi) + text.charCodeAt(lo); -console.log(mirrored); diff --git a/tests/harness/corpus-costs/7140-paired-loop-counters.ts.json b/tests/harness/corpus-costs/7140-paired-loop-counters.ts.json deleted file mode 100644 index 549fd6a4a..000000000 --- a/tests/harness/corpus-costs/7140-paired-loop-counters.ts.json +++ /dev/null @@ -1 +0,0 @@ -{ "plain": 3880, "san": 6000 } From 1a240fbf107766e102c7c027b02ea5f78b62d6d7 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 02:49:33 -0500 Subject: [PATCH 034/102] Support asymmetric keys, signatures and Ed25519 in node:crypto and WebCrypto Co-authored-by: saboursepideh <25549001+saboursepideh@users.noreply.github.com> --- .../limitations/builtin-apis/crypto.mdx | 16 +- .../src/generated/node-v24-compatibility.json | 108 +- .../generated/node-v24-internal.json | 226 +- internal/compatibility/static-support.json | 3 +- .../ambient/scriptc-node-fallback.d.ts | 249 +- .../src/backend/executable-features.ts | 2 + packages/compiler/src/backend/library-pack.ts | 2 + .../compiler/src/backend/llvm/lib-shared.ts | 12 + .../src/backend/native-link-info-core.ts | 6 + .../compiler/src/backend/native/contracts.ts | 6 + .../compiler/src/backend/native/executable.ts | 8 +- .../src/backend/runtime-pack-targets.test.ts | 2 + .../compiler/src/backend/runtime-pack.test.ts | 2 + .../src/backend/target-diagnostics.ts | 21 +- packages/compiler/src/backend/warm-cache.ts | 2 + .../src/executable/executable-cache.test.ts | 2 + .../src/executable/executable-cache.ts | 4 + .../src/frontend/lowering/builtins/crypto.ts | 54 + .../frontend/lowering/builtins/key-object.ts | 31 +- .../frontend/lowering/builtins/webcrypto.ts | 31 +- .../src/frontend/lowering/surfaces.ts | 35 +- packages/compiler/src/frontend/type-mapper.ts | 102 +- packages/compiler/src/index.ts | 2 + packages/compiler/src/ir/builtin-effects.ts | 8 + .../compiler/src/ir/builtin-signatures.ts | 15 + packages/compiler/src/ir/runtime-features.ts | 65 + packages/compiler/src/library/ir-policy.ts | 8 + packages/compiler/src/native/cli.ts | 2 + packages/compiler/src/native/prepare.ts | 2 + .../compiler/src/native/sanitizer.test.ts | 2 + packages/compiler/surface-manifest.json | 50 +- .../tests/corpus/7080-crypto-ed25519.mjs.json | 6 + .../corpus/7081-webcrypto-ed25519.mjs.json | 6 + .../corpus/7082-crypto-key-objects.ts.json | 6 + .../corpus/7083-crypto-sign-verify.ts.json | 6 + .../corpus/7084-crypto-key-pairs.cjs.json | 6 + .../corpus/7085-webcrypto-ecdsa-rsa.ts.json | 6 + .../7086-webcrypto-ecdsa-rsa-errors.mjs.json | 6 + .../tests/fixtures/node-types/keys.ts.json | 6 + .../node-types/webcrypto-ecdsa.ts.json | 6 + .../runtime-pack-matrix.mjs | 2 +- .../runtime-darwin-arm64/scripts/build.mjs | 3 +- .../runtime-pack-matrix.mjs | 5 +- .../runtime-pack-common/scripts/build.mjs | 3 +- .../runtime-wasm32-wasi/scripts/build.mjs | 3 + packages/runtime/src/scr_crypto.h | 18 + packages/runtime/src/scr_dyn.h | 5 + packages/runtime/src/scr_ed25519.c | 76 + packages/runtime/src/scr_lib.c | 12 +- packages/runtime/src/scr_pki.c | 2118 ++++++++++++ packages/runtime/src/scr_pki.h | 75 + packages/runtime/src/scr_webcrypto.c | 164 +- packages/runtime/src/scr_webcrypto.h | 58 + packages/runtime/src/scr_webcrypto_pki.c | 845 +++++ packages/runtime/vendor/README.md | 12 + packages/runtime/vendor/libsodium/LICENSE | 18 + packages/runtime/vendor/libsodium/README.md | 7 + packages/runtime/vendor/libsodium/common.h | 285 ++ .../vendor/libsodium/crypto_hash_sha512.h | 60 + .../libsodium/crypto_scalarmult_curve25519.h | 42 + .../vendor/libsodium/crypto_sign_ed25519.h | 124 + .../vendor/libsodium/crypto_verify_16.h | 23 + .../vendor/libsodium/crypto_verify_32.h | 23 + .../vendor/libsodium/crypto_verify_64.h | 23 + .../runtime/vendor/libsodium/ed25519_ref10.c | 2858 +++++++++++++++++ .../runtime/vendor/libsodium/ed25519_ref10.h | 142 + .../vendor/libsodium/ed25519_ref10_fe_25_5.h | 1030 ++++++ packages/runtime/vendor/libsodium/export.h | 57 + .../runtime/vendor/libsodium/fe_25_5/base.h | 1344 ++++++++ .../runtime/vendor/libsodium/fe_25_5/base2.h | 40 + .../vendor/libsodium/fe_25_5/constants.h | 40 + .../runtime/vendor/libsodium/fe_25_5/fe.h | 220 ++ .../runtime/vendor/libsodium/hash_sha512_cp.c | 284 ++ packages/runtime/vendor/libsodium/keypair.c | 84 + packages/runtime/vendor/libsodium/open.c | 98 + .../runtime/vendor/libsodium/randombytes.h | 72 + packages/runtime/vendor/libsodium/sign.c | 128 + .../vendor/libsodium/sign_ed25519_ref10.h | 18 + packages/runtime/vendor/libsodium/utils.h | 179 ++ packages/runtime/vendor/libsodium/verify.c | 95 + tests/corpus/7080-crypto-ed25519.mjs | 34 + tests/corpus/7081-webcrypto-ed25519.mjs | 39 + tests/corpus/7082-crypto-key-objects.ts | 132 + tests/corpus/7083-crypto-sign-verify.ts | 85 + tests/corpus/7084-crypto-key-pairs.cjs | 64 + tests/corpus/7085-webcrypto-ecdsa-rsa.ts | 66 + .../7086-webcrypto-ecdsa-rsa-errors.mjs | 58 + tests/diagnostics/webcrypto-refusals.ts | 16 +- tests/fixtures/node-types/fenced.ts | 16 +- tests/fixtures/node-types/keys.ts | 43 + tests/fixtures/node-types/webcrypto-ecdsa.ts | 34 + .../__snapshots__/node-types-fenced.txt | 16 +- .../__snapshots__/webcrypto-refusals.ts.txt | 33 +- .../corpus-costs/7080-crypto-ed25519.mjs.json | 1 + .../7081-webcrypto-ed25519.mjs.json | 1 + .../7082-crypto-key-objects.ts.json | 1 + .../7083-crypto-sign-verify.ts.json | 1 + .../7084-crypto-key-pairs.cjs.json | 1 + .../7085-webcrypto-ecdsa-rsa.ts.json | 1 + .../7086-webcrypto-ecdsa-rsa-errors.mjs.json | 1 + tests/harness/errors.test.ts | 71 +- tests/harness/library-asyncfree.test.ts | 9 + tests/harness/project-config.test.ts | 32 + .../self-hosting-native-toolchain.test.ts | 2 + .../harness/self-hosting-runtime-pack.test.ts | 2 + 105 files changed, 12304 insertions(+), 280 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7080-crypto-ed25519.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7081-webcrypto-ed25519.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7082-crypto-key-objects.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7083-crypto-sign-verify.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7084-crypto-key-pairs.cjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7085-webcrypto-ecdsa-rsa.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/keys.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/webcrypto-ecdsa.ts.json create mode 100644 packages/runtime/src/scr_ed25519.c create mode 100644 packages/runtime/src/scr_pki.c create mode 100644 packages/runtime/src/scr_pki.h create mode 100644 packages/runtime/src/scr_webcrypto.h create mode 100644 packages/runtime/src/scr_webcrypto_pki.c create mode 100644 packages/runtime/vendor/libsodium/LICENSE create mode 100644 packages/runtime/vendor/libsodium/README.md create mode 100644 packages/runtime/vendor/libsodium/common.h create mode 100644 packages/runtime/vendor/libsodium/crypto_hash_sha512.h create mode 100644 packages/runtime/vendor/libsodium/crypto_scalarmult_curve25519.h create mode 100644 packages/runtime/vendor/libsodium/crypto_sign_ed25519.h create mode 100644 packages/runtime/vendor/libsodium/crypto_verify_16.h create mode 100644 packages/runtime/vendor/libsodium/crypto_verify_32.h create mode 100644 packages/runtime/vendor/libsodium/crypto_verify_64.h create mode 100644 packages/runtime/vendor/libsodium/ed25519_ref10.c create mode 100644 packages/runtime/vendor/libsodium/ed25519_ref10.h create mode 100644 packages/runtime/vendor/libsodium/ed25519_ref10_fe_25_5.h create mode 100644 packages/runtime/vendor/libsodium/export.h create mode 100644 packages/runtime/vendor/libsodium/fe_25_5/base.h create mode 100644 packages/runtime/vendor/libsodium/fe_25_5/base2.h create mode 100644 packages/runtime/vendor/libsodium/fe_25_5/constants.h create mode 100644 packages/runtime/vendor/libsodium/fe_25_5/fe.h create mode 100644 packages/runtime/vendor/libsodium/hash_sha512_cp.c create mode 100644 packages/runtime/vendor/libsodium/keypair.c create mode 100644 packages/runtime/vendor/libsodium/open.c create mode 100644 packages/runtime/vendor/libsodium/randombytes.h create mode 100644 packages/runtime/vendor/libsodium/sign.c create mode 100644 packages/runtime/vendor/libsodium/sign_ed25519_ref10.h create mode 100644 packages/runtime/vendor/libsodium/utils.h create mode 100644 packages/runtime/vendor/libsodium/verify.c create mode 100644 tests/corpus/7080-crypto-ed25519.mjs create mode 100644 tests/corpus/7081-webcrypto-ed25519.mjs create mode 100644 tests/corpus/7082-crypto-key-objects.ts create mode 100644 tests/corpus/7083-crypto-sign-verify.ts create mode 100644 tests/corpus/7084-crypto-key-pairs.cjs create mode 100644 tests/corpus/7085-webcrypto-ecdsa-rsa.ts create mode 100644 tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs create mode 100644 tests/fixtures/node-types/keys.ts create mode 100644 tests/fixtures/node-types/webcrypto-ecdsa.ts create mode 100644 tests/harness/corpus-costs/7080-crypto-ed25519.mjs.json create mode 100644 tests/harness/corpus-costs/7081-webcrypto-ed25519.mjs.json create mode 100644 tests/harness/corpus-costs/7082-crypto-key-objects.ts.json create mode 100644 tests/harness/corpus-costs/7083-crypto-sign-verify.ts.json create mode 100644 tests/harness/corpus-costs/7084-crypto-key-pairs.cjs.json create mode 100644 tests/harness/corpus-costs/7085-webcrypto-ecdsa-rsa.ts.json create mode 100644 tests/harness/corpus-costs/7086-webcrypto-ecdsa-rsa-errors.mjs.json diff --git a/docs/content/limitations/builtin-apis/crypto.mdx b/docs/content/limitations/builtin-apis/crypto.mdx index 3c830c63d..855968219 100644 --- a/docs/content/limitations/builtin-apis/crypto.mdx +++ b/docs/content/limitations/builtin-apis/crypto.mdx @@ -4,7 +4,7 @@ `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. @@ -15,5 +15,17 @@ `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. + 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. + Diffie-Hellman and `publicEncrypt`/`privateDecrypt` remain unsupported. + WebCrypto's `crypto.subtle` supports HMAC keys imported from `raw` with `sign` and `verify`, SHA-1 and SHA-2 `digest`, and `generateKey`, `importKey`, `exportKey`, `sign`, and `verify` for 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. + The methods are called on `crypto.subtle` directly; other methods, algorithms, and SHA-3 digests throw a coded SC2020 error, and 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. Native derivations finish before their deferred callbacks, so computation blocks the caller. diff --git a/docs/src/generated/node-v24-compatibility.json b/docs/src/generated/node-v24-compatibility.json index 66b0ba3dd..4898fe218 100644 --- a/docs/src/generated/node-v24-compatibility.json +++ b/docs/src/generated/node-v24-compatibility.json @@ -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" } }, { @@ -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" } }, { @@ -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" } }, { @@ -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" } }, { diff --git a/internal/compatibility/generated/node-v24-internal.json b/internal/compatibility/generated/node-v24-internal.json index c6a7a102c..c886cccf9 100644 --- a/internal/compatibility/generated/node-v24-internal.json +++ b/internal/compatibility/generated/node-v24-internal.json @@ -19313,12 +19313,17 @@ "tests/corpus/6703-ecdh-private-keys.ts", "tests/corpus/6704-ecdh-set-public-key.cjs", "tests/corpus/6705-ecdh-handles.ts", + "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/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/ecdh.ts", + "tests/fixtures/node-types/keys.ts", "tests/harness/npm-static.test.ts" ] }, @@ -19961,8 +19966,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 +20019,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 +20076,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 +20106,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 +20232,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 +20262,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" }, @@ -21096,8 +21143,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 +21200,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" }, @@ -23007,8 +23068,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 +23098,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 +23243,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 +23273,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 +23303,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 +23333,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 +23363,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 +23393,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" }, @@ -106616,6 +106733,9 @@ "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/node24-crypto-kdf-errors.ts", "tests/corpus/node24-crypto-kdf-options.ts", "tests/corpus/node24-crypto-kdf.ts", @@ -110543,6 +110663,9 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.digest", "tests": [ + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", @@ -110640,8 +110763,19 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.exportKey", + "tests": [ + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-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", + "tests/fixtures/node-types/webcrypto-hmac.ts" + ] }, "anchorSource": "exact" }, @@ -110686,8 +110820,19 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.generateKey", + "tests": [ + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-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", + "tests/fixtures/node-types/webcrypto-hmac.ts" + ] }, "anchorSource": "exact" }, @@ -110712,6 +110857,9 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.importKey", "tests": [ + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", @@ -110743,6 +110891,9 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.sign", "tests": [ + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", @@ -110797,6 +110948,9 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.verify", "tests": [ + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", diff --git a/internal/compatibility/static-support.json b/internal/compatibility/static-support.json index 23c7a159b..d799d4887 100644 --- a/internal/compatibility/static-support.json +++ b/internal/compatibility/static-support.json @@ -194,7 +194,7 @@ "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.generateKey", "subtle.importKey", "subtle.exportKey", "subtle.sign", "subtle.verify", "subtle.digest"], "status": "partial", "evidence": ["tests/corpus/7081-webcrypto-ed25519.mjs", "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", "tests/corpus/7086-webcrypto-ecdsa-rsa-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", "tests/fixtures/node-types/webcrypto-hmac.ts"] }, { "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": "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"] }, @@ -418,6 +418,7 @@ { "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/packages/compiler/ambient/scriptc-node-fallback.d.ts b/packages/compiler/ambient/scriptc-node-fallback.d.ts index dbb3cd8fd..ca1913cd7 100644 --- a/packages/compiler/ambient/scriptc-node-fallback.d.ts +++ b/packages/compiler/ambient/scriptc-node-fallback.d.ts @@ -544,11 +544,12 @@ 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 +/* WebCrypto (scr_webcrypto.c): crypto.subtle's importKey for raw HMAC + * keys, HMAC sign/verify, generateKey, importKey, exportKey, sign and + * verify for ECDSA, 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). 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 @@ -623,27 +624,70 @@ 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 keys import from 'raw'; ECDSA and RSA keys generate, import and + * export as 'spki', 'pkcs8' and 'jwk', and ECDSA public keys as 'raw'. */ interface SubtleCrypto { digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + generateKey( + algorithm: EcKeyGenParams | RsaHashedKeyGenParams | "Ed25519" | { name: "Ed25519" }, + 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, key: CryptoKey, data: BufferSource): Promise; + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + sign( + algorithm: AlgorithmIdentifier | EcdsaParams | RsaPssParams, + key: CryptoKey, + data: BufferSource, + ): Promise; verify( - algorithm: AlgorithmIdentifier, + algorithm: AlgorithmIdentifier | EcdsaParams | RsaPssParams, key: CryptoKey, signature: BufferSource, data: BufferSource, @@ -2693,8 +2737,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 +2758,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; diff --git a/packages/compiler/src/backend/executable-features.ts b/packages/compiler/src/backend/executable-features.ts index f7cae8508..f22607384 100644 --- a/packages/compiler/src/backend/executable-features.ts +++ b/packages/compiler/src/backend/executable-features.ts @@ -56,6 +56,8 @@ export function executableLinkFeatures(mod: IrModule): NativeLinkFeatures { tlsCa: features.tlsCa, cipher: features.cipher, ecdh: features.ecdh, + pki: features.pki, + ed25519: features.ed25519, webcrypto: features.webcrypto, perfLoop: features.perfLoop, }; diff --git a/packages/compiler/src/backend/library-pack.ts b/packages/compiler/src/backend/library-pack.ts index 805198df1..3867d255a 100644 --- a/packages/compiler/src/backend/library-pack.ts +++ b/packages/compiler/src/backend/library-pack.ts @@ -60,6 +60,8 @@ export async function compilePackedLibrary( tls: false, cipher: false, ecdh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, tlsCa: false, diff --git a/packages/compiler/src/backend/llvm/lib-shared.ts b/packages/compiler/src/backend/llvm/lib-shared.ts index 8bb8bc3aa..c1a8a33b1 100644 --- a/packages/compiler/src/backend/llvm/lib-shared.ts +++ b/packages/compiler/src/backend/llvm/lib-shared.ts @@ -614,7 +614,9 @@ 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.sign": "scr_webcrypto_sign", "webcrypto.verify": "scr_webcrypto_verify", "webcrypto.digest": "scr_webcrypto_digest", @@ -1027,6 +1029,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", @@ -1565,6 +1575,7 @@ export function mockTimerSym( } export const USES_TIMERS_LIB_FNS = new Set([ + "crypto.generateKeyPairCb", "process.emitWarning", // Constructor-function streams defer their events on the stream ticks. "dyn.builtinStreamClass", @@ -1573,6 +1584,7 @@ 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.sign", "webcrypto.verify", "webcrypto.digest", diff --git a/packages/compiler/src/backend/native-link-info-core.ts b/packages/compiler/src/backend/native-link-info-core.ts index a476e1f7f..484ce03cd 100644 --- a/packages/compiler/src/backend/native-link-info-core.ts +++ b/packages/compiler/src/backend/native-link-info-core.ts @@ -90,6 +90,12 @@ export interface NativeLinkFeatures { /** crypto.createECDH and ECDH.convertKey: scr_ecdh.c plus the mbedTLS * archive. */ ecdh: 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..a4d5dc3dd 100644 --- a/packages/compiler/src/backend/native/contracts.ts +++ b/packages/compiler/src/backend/native/contracts.ts @@ -249,6 +249,12 @@ export interface CcOptions { /** crypto.createECDH and ECDH.convertKey: compiles scr_ecdh.c and links * the mbedTLS archive (shared with tls). */ ecdh?: 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..cae6d9499 100644 --- a/packages/compiler/src/backend/native/executable.ts +++ b/packages/compiler/src/backend/native/executable.ts @@ -114,6 +114,7 @@ interface RuntimeUnitContext { tlsCa: boolean; cipher: boolean; ecdh: boolean; + pki: boolean; lreObjects: readonly string[]; zlibObjects: readonly string[]; tlsArchive: string | null; @@ -297,6 +298,8 @@ 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 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 +311,7 @@ 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.pki ? [u.rt(join(u.rtDir, "scr_pki.c"))] : []), u.tlsArchive, // mbedTLS's win32 entropy poll is BCryptGenRandom (bcrypt.h). // The unconditional win32 libs above do not carry it. @@ -375,7 +379,8 @@ export async function compileCInternal( // Symmetric ciphers and ECDH link the same mbedTLS archive as TLS. const cipher = opts.cipher ?? false; const ecdh = opts.ecdh ?? false; - const mbedtls = tls || cipher || ecdh; + const pki = opts.pki ?? false; + const mbedtls = tls || cipher || ecdh || pki; const driver = resolveCc(); const darwinDebugSymbols = needsDarwinDebugSymbols( targetPlatform(driver), @@ -733,6 +738,7 @@ export async function compileCInternal( tlsCa, cipher, ecdh, + pki, lreObjects, zlibObjects, tlsArchive, diff --git a/packages/compiler/src/backend/runtime-pack-targets.test.ts b/packages/compiler/src/backend/runtime-pack-targets.test.ts index fc7ed9efa..0a6868aa0 100644 --- a/packages/compiler/src/backend/runtime-pack-targets.test.ts +++ b/packages/compiler/src/backend/runtime-pack-targets.test.ts @@ -125,6 +125,8 @@ const features = { tlsCa: false, cipher: false, ecdh: 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..d0515a8ef 100644 --- a/packages/compiler/src/backend/runtime-pack.test.ts +++ b/packages/compiler/src/backend/runtime-pack.test.ts @@ -61,6 +61,8 @@ const BASE: NativeLinkFeatures = { tlsCa: false, cipher: false, ecdh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, }; diff --git a/packages/compiler/src/backend/target-diagnostics.ts b/packages/compiler/src/backend/target-diagnostics.ts index b7049f6fe..c9aecc170 100644 --- a/packages/compiler/src/backend/target-diagnostics.ts +++ b/packages/compiler/src/backend/target-diagnostics.ts @@ -2,7 +2,11 @@ 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 { + 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 @@ -215,6 +219,14 @@ export function moduleWasiUnavailableSurface( }; 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 +253,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..2f98fd920 100644 --- a/packages/compiler/src/backend/warm-cache.ts +++ b/packages/compiler/src/backend/warm-cache.ts @@ -67,6 +67,8 @@ export async function warmNativeCaches( tls: false, cipher: false, ecdh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, tlsCa: false, diff --git a/packages/compiler/src/executable/executable-cache.test.ts b/packages/compiler/src/executable/executable-cache.test.ts index 94b136c90..0d786e208 100644 --- a/packages/compiler/src/executable/executable-cache.test.ts +++ b/packages/compiler/src/executable/executable-cache.test.ts @@ -65,6 +65,8 @@ const native: EarlyExecutableNativeFeatures = { tlsCa: false, cipher: false, ecdh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, }; diff --git a/packages/compiler/src/executable/executable-cache.ts b/packages/compiler/src/executable/executable-cache.ts index 2312f5e85..975f67cf8 100644 --- a/packages/compiler/src/executable/executable-cache.ts +++ b/packages/compiler/src/executable/executable-cache.ts @@ -96,6 +96,8 @@ export interface EarlyExecutableNativeFeatures { tls: boolean; cipher: boolean; ecdh: boolean; + pki: boolean; + ed25519: boolean; perfLoop: boolean; tlsCa: boolean; webcrypto: boolean; @@ -228,6 +230,8 @@ const BOOLEAN_NATIVE_KEYS = [ "tlsCa", "cipher", "ecdh", + "pki", + "ed25519", "webcrypto", "perfLoop", ] as const satisfies readonly (keyof EarlyExecutableNativeFeatures)[]; diff --git a/packages/compiler/src/frontend/lowering/builtins/crypto.ts b/packages/compiler/src/frontend/lowering/builtins/crypto.ts index f4270dbe8..8b42a218d 100644 --- a/packages/compiler/src/frontend/lowering/builtins/crypto.ts +++ b/packages/compiler/src/frontend/lowering/builtins/crypto.ts @@ -695,6 +695,8 @@ export function lowerCryptoModuleCall( loc, }; } + const pki = lowerPkiCall(lowerer, expr, bi.member, args, loc); + if (pki) return pki; if (bi.member === "createSecretKey") { if (args.length < 1 || args.length > 2 || args.some(ts.isSpreadElement)) lowerer.noLowering( @@ -1335,3 +1337,55 @@ export function isWebCryptoReceiver(lowerer: Lowerer, receiver: ts.Expression): } return false; } + +/** 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/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/webcrypto.ts b/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts index 93cba84c5..ef04e8761 100644 --- a/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts +++ b/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts @@ -6,23 +6,27 @@ import { lowerDynObjectLiteral } from "../expressions/object-literals.js"; import { stdlibGlobalNameOf } from "../surfaces.js"; import { WEBCRYPTO_DYN_TYPES } from "../../type-mapper.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 - * values are native handles; their type maps to dyn and their members - * are handle reads. Other SubtleCrypto methods are refused by name. */ +/* WebCrypto (scr_webcrypto.c, and scr_webcrypto_pki.c for ECDSA, Ed25519, + * RSASSA-PKCS1-v1_5 and RSA-PSS): `crypto.subtle.generateKey`, + * `importKey`, `exportKey`, `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 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"], ["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.importKey('raw', ...) for HMAC keys, 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. */ function isSubtleReceiver(lowerer: Lowerer, node: ts.Expression): boolean { @@ -51,17 +55,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/surfaces.ts b/packages/compiler/src/frontend/lowering/surfaces.ts index c77938337..bc5834533 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], @@ -2210,8 +2220,15 @@ 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.sign", + "webcrypto.verify", + "webcrypto.digest", + ], + note: "importKey('raw') for HMAC keys, 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", @@ -3055,14 +3072,6 @@ export const BUILTIN_MODULE_FENCE_HINTS: Record< crypto: { ...Object.fromEntries( [ - "generateKeyPair", - "generateKeyPairSync", - "createPrivateKey", - "createPublicKey", - "createSign", - "createVerify", - "sign", - "verify", "createDiffieHellman", "createDiffieHellmanGroup", "getDiffieHellman", @@ -3073,9 +3082,9 @@ export const BUILTIN_MODULE_FENCE_HINTS: Record< "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", + "Diffie-Hellman and RSA encryption have no lowering — the asymmetric crypto surface is " + + "RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, " + + "createSign, createVerify, and createECDH", ]), ), ...Object.fromEntries( diff --git a/packages/compiler/src/frontend/type-mapper.ts b/packages/compiler/src/frontend/type-mapper.ts index a233f0186..50b809007 100644 --- a/packages/compiler/src/frontend/type-mapper.ts +++ b/packages/compiler/src/frontend/type-mapper.ts @@ -146,6 +146,37 @@ export const WEBCRYPTO_DYN_TYPES: ReadonlySet = new Set([ "KeyAlgorithm", "HmacImportParams", "HmacKeyAlgorithm", + "CryptoKeyPair", + "EcKeyAlgorithm", + "RsaHashedKeyAlgorithm", + "EcKeyGenParams", + "EcKeyImportParams", + "EcdsaParams", + "RsaHashedKeyGenParams", + "RsaHashedImportParams", + "RsaPssParams", +]); + +/** 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 = [ @@ -2903,9 +2934,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 +2949,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)) && @@ -4183,6 +4244,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- diff --git a/packages/compiler/src/index.ts b/packages/compiler/src/index.ts index 2b216c77d..458930616 100644 --- a/packages/compiler/src/index.ts +++ b/packages/compiler/src/index.ts @@ -624,6 +624,8 @@ async function compileExecutableNative( tlsCa: features.tlsCa, cipher: features.cipher, ecdh: features.ecdh, + pki: features.pki, + ed25519: features.ed25519, webcrypto: features.webcrypto, perfLoop: features.perfLoop, ...(onArtifactReady === undefined ? {} : { onArtifactReady }), diff --git a/packages/compiler/src/ir/builtin-effects.ts b/packages/compiler/src/ir/builtin-effects.ts index ca8c52118..3d9fb3f50 100644 --- a/packages/compiler/src/ir/builtin-effects.ts +++ b/packages/compiler/src/ir/builtin-effects.ts @@ -976,4 +976,12 @@ 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", ]); diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index fa7876579..95de752ec 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -2845,7 +2845,9 @@ 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.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 } }, @@ -4638,6 +4640,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 }, diff --git a/packages/compiler/src/ir/runtime-features.ts b/packages/compiler/src/ir/runtime-features.ts index 4142b6efe..2e828c027 100644 --- a/packages/compiler/src/ir/runtime-features.ts +++ b/packages/compiler/src/ir/runtime-features.ts @@ -621,6 +621,63 @@ 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_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. */ +export function moduleNamesEd25519(mod: IrModule): boolean { + let named = false; + everyModuleNode(mod, { + expr: (node) => { + if (node.kind === "strLit" && node.value.toLowerCase() === "ed25519") named = true; + return !named; + }, + stmt: () => !named, + type: () => true, + }); + return 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 @@ -819,6 +876,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({ initial: moduleUsesWebCryptoAsymmetric, fns: [...PKI_LIB_FNS] }), + /** scr_ed25519.c (the vendored libsodium Ed25519), linked with pki: a + * string literal in the module names Ed25519. */ + ed25519: rule({ initial: moduleNamesEd25519 }), 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] }), @@ -926,6 +989,8 @@ function noRuntimeFeatures(): RuntimeFeatures { nodeTest: false, parseArgs: false, perfLoop: false, + pki: false, + ed25519: false, processEvents: false, qs: false, regex: false, diff --git a/packages/compiler/src/library/ir-policy.ts b/packages/compiler/src/library/ir-policy.ts index 51aeb6146..f16ae3d0c 100644 --- a/packages/compiler/src/library/ir-policy.ts +++ b/packages/compiler/src/library/ir-policy.ts @@ -52,6 +52,13 @@ 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.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 +166,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/cli.ts b/packages/compiler/src/native/cli.ts index ed8d52293..7679338bb 100644 --- a/packages/compiler/src/native/cli.ts +++ b/packages/compiler/src/native/cli.ts @@ -110,6 +110,8 @@ async function main(): Promise { tls: false, cipher: false, ecdh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, tlsCa: false, diff --git a/packages/compiler/src/native/prepare.ts b/packages/compiler/src/native/prepare.ts index 6b0a2fea5..f470b614e 100644 --- a/packages/compiler/src/native/prepare.ts +++ b/packages/compiler/src/native/prepare.ts @@ -161,6 +161,8 @@ function validFeatures(value: unknown): value is NativeLinkFeatures { "tlsCa", "cipher", "ecdh", + "pki", + "ed25519", "webcrypto", "perfLoop", ].every((name) => typeof features[name] === "boolean"); diff --git a/packages/compiler/src/native/sanitizer.test.ts b/packages/compiler/src/native/sanitizer.test.ts index e6beb24cc..a626cd78c 100644 --- a/packages/compiler/src/native/sanitizer.test.ts +++ b/packages/compiler/src/native/sanitizer.test.ts @@ -120,6 +120,8 @@ test.skipIf(process.platform !== "linux" && process.platform !== "darwin")( tlsCa: false, cipher: false, ecdh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, nativeFetch: false, diff --git a/packages/compiler/surface-manifest.json b/packages/compiler/surface-manifest.json index c05e994a8..a1f252814 100644 --- a/packages/compiler/surface-manifest.json +++ b/packages/compiler/surface-manifest.json @@ -498,7 +498,7 @@ "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" + "note": "Diffie-Hellman and RSA encryption have no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, and createECDH" }, { "id": "node-builtin.crypto.createDiffieHellmanGroup", @@ -506,7 +506,7 @@ "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" + "note": "Diffie-Hellman and RSA encryption have no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, and createECDH" }, { "id": "node-builtin.crypto.createECDH", @@ -530,17 +530,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 +548,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 +562,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": "Diffie-Hellman and RSA encryption have no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, and createECDH" }, { "id": "node-builtin.crypto.generateKey", @@ -582,17 +574,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", @@ -614,7 +602,7 @@ "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" + "note": "Diffie-Hellman and RSA encryption have no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, and createECDH" }, { "id": "node-builtin.crypto.getRandomValues", @@ -658,7 +646,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": "Diffie-Hellman and RSA encryption have no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, and createECDH" }, { "id": "node-builtin.crypto.privateEncrypt", @@ -666,7 +654,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": "Diffie-Hellman and RSA encryption have no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, and createECDH" }, { "id": "node-builtin.crypto.publicDecrypt", @@ -674,7 +662,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": "Diffie-Hellman and RSA encryption have no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, and createECDH" }, { "id": "node-builtin.crypto.publicEncrypt", @@ -682,7 +670,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": "Diffie-Hellman and RSA encryption have no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, and createECDH" }, { "id": "node-builtin.crypto.randomBytes", @@ -744,9 +732,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,9 +744,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" + "status": "static" }, { "id": "node-builtin.crypto.webcrypto", @@ -5726,7 +5710,7 @@ "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('raw') for HMAC keys, 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/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/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/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/runtime-darwin-arm64/runtime-pack-matrix.mjs b/packages/runtime-darwin-arm64/runtime-pack-matrix.mjs index db72284f6..5549b0db9 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", "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..9e74b48c6 100644 --- a/packages/runtime-darwin-arm64/scripts/build.mjs +++ b/packages/runtime-darwin-arm64/scripts/build.mjs @@ -172,7 +172,8 @@ 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_pki.c" ? ["-I", join(mbedtls, "include")] : []), ...(unit.source === "scr_zlib.c" || unit.source === "scr_fetch.c" diff --git a/packages/runtime-pack-common/runtime-pack-matrix.mjs b/packages/runtime-pack-common/runtime-pack-matrix.mjs index 0f40218a1..0039662bf 100644 --- a/packages/runtime-pack-common/runtime-pack-matrix.mjs +++ b/packages/runtime-pack-common/runtime-pack-matrix.mjs @@ -149,8 +149,11 @@ export const OPTIONAL_RUNTIME_SOURCES = [ ["scr_tls.c", "tlsEffective"], ["scr_cipher.c", "cipher"], ["scr_ecdh.c", "ecdh"], + ["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")], ["scr_fetch.c", "nativeFetch"], ]; @@ -212,7 +215,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", "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..3b43f3b83 100644 --- a/packages/runtime-pack-common/scripts/build.mjs +++ b/packages/runtime-pack-common/scripts/build.mjs @@ -223,7 +223,8 @@ 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_pki.c" ? ["-I", join(mbedtls, "include")] : []), ...(unit.source === "scr_zlib.c" || unit.source === "scr_fetch.c" diff --git a/packages/runtime-wasm32-wasi/scripts/build.mjs b/packages/runtime-wasm32-wasi/scripts/build.mjs index 2dd983973..7c8bc4652 100644 --- a/packages/runtime-wasm32-wasi/scripts/build.mjs +++ b/packages/runtime-wasm32-wasi/scripts/build.mjs @@ -22,6 +22,9 @@ process.env.SCRIPTC_RUNTIME_PACK_CONFIG = JSON.stringify({ "scr_tls.c", "scr_cipher.c", "scr_ecdh.c", + "scr_pki.c", + "scr_webcrypto_pki.c", + "scr_ed25519.c", "scr_wasm.c", "scr_fetch.c", ], diff --git a/packages/runtime/src/scr_crypto.h b/packages/runtime/src/scr_crypto.h index d12858abf..29695e5cc 100644 --- a/packages/runtime/src/scr_crypto.h +++ b/packages/runtime/src/scr_crypto.h @@ -82,6 +82,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 @@ -212,6 +216,8 @@ size_t scr_crypto_hmac_raw(const char *alg, const unsigned char *key, size_t key * 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); @@ -229,5 +235,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_dyn.h b/packages/runtime/src/scr_dyn.h index 02c4d828f..b2615b57e 100644 --- a/packages/runtime/src/scr_dyn.h +++ b/packages/runtime/src/scr_dyn.h @@ -158,6 +158,11 @@ typedef enum { 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) */ \ + X(PRIVATE_KEY, 65) /* node:crypto PrivateKeyObject (scr_pki.c) */ \ + X(PUBLIC_KEY, 66) /* node:crypto PublicKeyObject (scr_pki.c) */ \ + X(SIGN, 67) /* node:crypto Sign (scr_pki.c) */ \ + X(VERIFY, 68) /* node:crypto Verify (scr_pki.c) */ \ + X(ASYMMETRIC_CRYPTO_KEY, 69) /* WebCrypto ECDSA and RSA CryptoKey (scr_webcrypto_pki.c) */ \ X(EVENT, 14) /* ScrEvent — new Event() and AbortSignal's abort events */ \ X(EVENT_TARGET, 39) /* ScrEventTarget — new EventTarget() */ \ X(FETCH_HEADERS, 13) /* native static-fetch response Headers */ \ 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_lib.c b/packages/runtime/src/scr_lib.c index ee4c34592..094ec36af 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; } diff --git a/packages/runtime/src/scr_pki.c b/packages/runtime/src/scr_pki.c new file mode 100644 index 000000000..1b102fd22 --- /dev/null +++ b/packages/runtime/src/scr_pki.c @@ -0,0 +1,2118 @@ +/* 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 "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); +} + +/* 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) { + char lite[96]; + char message[256]; + int n = snprintf(message, sizeof message, "The property '%s' is invalid. Received %s", name, + scr_dyn_inspect_lite(got, lite, sizeof lite)); + scr_throw_error_msg_code(SCR_ERR_TYPE, message, (size_t)n, "ERR_INVALID_ARG_VALUE"); +} + +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) { + char message[256]; + int n = snprintf(message, sizeof message, + "'%s' is part of the standard library types but has no scriptc lowering yet", what); + scr_throw_error_msg_code(SCR_ERR_ERROR, message, (size_t)n, "SC2020"); +} + +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; + } + char message[160]; + int n = snprintf(message, sizeof message, "%s is not a function", what); + scr_throw_error_msg(SCR_ERR_TYPE, message, (size_t)n); + 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; + char message[160]; + int n = snprintf(message, sizeof message, "Cannot set property %.*s of #<%s> which has only a getter", + (int)len, name, holder); + scr_throw_error_msg(SCR_ERR_TYPE, message, (size_t)n); + 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) { + char lite[96]; + char message[200]; + int n = snprintf(message, sizeof message, + "The argument 'type' must be a supported key type. Received %s", + scr_dyn_inspect_lite(type, lite, sizeof lite)); + scr_throw_error_msg_code(SCR_ERR_TYPE, message, (size_t)n, "ERR_INVALID_ARG_VALUE"); + 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; + if (b != b || b < 0 || b > 4294967295.0 || b != (double)(uint64_t)b) { + sp_key_release(k); + char message[160]; + char lite[64]; + int n = snprintf(message, sizeof message, + "The value of \"options.modulusLength\" is out of range. It must be >= 0 && <= 4294967295. Received %s", + scr_dyn_inspect_lite(bits, lite, sizeof lite)); + scr_throw_error_msg_code(SCR_ERR_RANGE, message, (size_t)n, "ERR_OUT_OF_RANGE"); + 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)) { + char message[160]; + int n = snprintf(message, sizeof message, "Invalid digest: %.*s", (int)alg->v.str->len, + alg->v.str->data); + scr_throw_error_msg_code(SCR_ERR_TYPE, message, (size_t)n, "ERR_CRYPTO_INVALID_DIGEST"); + 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); + } + char message[160]; + int n = snprintf(message, sizeof message, "%s is not a function", what); + scr_throw_error_msg(SCR_ERR_TYPE, message, (size_t)n); + 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..e299806f7 --- /dev/null +++ b/packages/runtime/src/scr_pki.h @@ -0,0 +1,75 @@ +/* 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; + +/* 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_webcrypto.c b/packages/runtime/src/scr_webcrypto.c index 546b24151..a11b22fe4 100644 --- a/packages/runtime/src/scr_webcrypto.c +++ b/packages/runtime/src/scr_webcrypto.c @@ -18,6 +18,7 @@ * 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 @@ -43,13 +44,12 @@ 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[] = { +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 +75,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 +89,9 @@ 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, ...) { +void scr_wc_type_error(const char *code, const char *fmt, ...) { char message[512]; va_list ap; va_start(ap, fmt); @@ -105,7 +103,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 +111,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 +121,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 +137,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; @@ -163,14 +161,14 @@ static ScrBytes *scr_wc_buffer_source(const char *prefix, size_t index, ScrDyn * } /* 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,15 +186,14 @@ 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 }; /* 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) { @@ -245,9 +242,9 @@ typedef struct { 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,7 +252,7 @@ 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()); @@ -264,7 +261,7 @@ static ScrDyn *scr_wc_member(const ScrDyn *dict, const char *key) { /* 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 +276,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); @@ -436,10 +433,10 @@ 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); @@ -567,7 +564,43 @@ static ScrDyn *scr_crypto_key_new(const unsigned char *data, size_t len, const c * 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; +} + +/* 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; @@ -575,7 +608,7 @@ static ScrPromise *scr_wc_rejected(void) { /* 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,15 +616,12 @@ 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]); } @@ -681,6 +711,11 @@ done: } 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); @@ -706,7 +741,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; } @@ -724,6 +760,10 @@ static bool scr_wc_sign_verify(const ScrDyn *args, bool verify, unsigned char ma scr_wc_unsupported_algorithm(method, algorithm.name); goto done; } + if (asymmetric_key) { + 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 +784,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 +811,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 +877,53 @@ done: scr_crypto_promise_settle_array_buffer); return p; } + +/* generateKey(algorithm, extractable, keyUsages): ECDSA, + * RSASSA-PKCS1-v1_5 and RSA-PSS key pairs (scr_webcrypto_pki.c); other + * recognized algorithms are refused after Node's argument conversions. */ +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); + bool converted = true; + if (!scr_wc_is_object(a.v[0])) { + ScrStr *str = scr_wc_dom_string(a.v[0]); + if (str) scr_str_release(str); + else converted = false; + } + if (converted && scr_wc_key_usages(prefix, 2, a.v[2]) >= 0) { + ScrStr *name = scr_wc_algorithm_name(a.v[0], "Algorithm"); + if (name) { + const char *known = scr_wc_lookup(scr_wc_import_names, SCR_WC_COUNT(scr_wc_import_names), name); + scr_str_release(name); + if (!known) scr_throw_domex("NotSupportedError", "Unrecognized algorithm name"); + else scr_wc_unsupported_algorithm("generateKey", known); + } + } + scr_wc_args_drop(&a, 3); + return scr_wc_rejected(); +} + +/* exportKey(format, key): ECDSA and RSA keys (scr_webcrypto_pki.c); HMAC + * keys are refused after Node's argument conversions. */ +ScrPromise *scr_webcrypto_export_key(ScrDyn *args) { + static const char prefix[] = "Failed to execute 'exportKey' on 'SubtleCrypto'"; + if (!scr_wc_required(prefix, args, 2)) return scr_wc_rejected(); + ScrWcArgs a; + scr_wc_args_take(&a, args, 2); + ScrPromise *result = NULL; + if (scr_wc_key_format(prefix, a.v[0])) { + if (scr_wc_asymmetric && scr_wc_asymmetric->is_key(a.v[1])) result = scr_wc_asymmetric->export_key(args); + else if (scr_crypto_key_of(a.v[1])) scr_wc_unsupported("exportKey", "HMAC keys"); + else + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type CryptoKey.", prefix); + } + scr_wc_args_drop(&a, 2); + 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..c8d7d83bc --- /dev/null +++ b/packages/runtime/src/scr_webcrypto.h @@ -0,0 +1,58 @@ +/* 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_SIGN = 1u << 2, SCR_WC_USAGE_VERIFY = 1u << 3 }; + +/* 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_pki.c b/packages/runtime/src/scr_webcrypto_pki.c new file mode 100644 index 000000000..e913b1dc6 --- /dev/null +++ b/packages/runtime/src/scr_webcrypto_pki.c @@ -0,0 +1,845 @@ +/* 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; + char message[128]; + int n = snprintf(message, sizeof message, "Cannot set property %.*s of # which has only a getter", + (int)len, name); + scr_throw_error_msg(SCR_ERR_TYPE, message, (size_t)n); + 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]"); + char message[160]; + int n = snprintf(message, sizeof message, "%s is not a function", what); + scr_throw_error_msg(SCR_ERR_TYPE, message, (size_t)n); + 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/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/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----- +MIGkAgEBBDDer7W8pQD96zdS8UWxg34nMTxqREszwP6niYYOdw75LHPmHF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FgQUdKIx6ULFLPNP/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..437dc1640 --- /dev/null +++ b/tests/corpus/7083-crypto-sign-verify.ts @@ -0,0 +1,85 @@ +// 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)); +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..ed4db0310 --- /dev/null +++ b/tests/corpus/7084-crypto-key-pairs.cjs @@ -0,0 +1,64 @@ +// 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" })); + +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/diagnostics/webcrypto-refusals.ts b/tests/diagnostics/webcrypto-refusals.ts index d162872fb..1d68813e8 100644 --- a/tests/diagnostics/webcrypto-refusals.ts +++ b/tests/diagnostics/webcrypto-refusals.ts @@ -1,17 +1,7 @@ -// 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 methods are 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/fenced.ts b/tests/fixtures/node-types/fenced.ts index 16a74081f..622f9cad3 100644 --- a/tests/fixtures/node-types/fenced.ts +++ b/tests/fixtures/node-types/fenced.ts @@ -69,11 +69,11 @@ 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): Diffie-Hellman names the lowered + * asymmetric surface, symmetric ciphers the missing cipher stack, prime + * checks theirs, and setFips the FIPS truth (getFips() lowers to 0). */ +import { checkPrimeSync, createCipheriv, createDiffieHellman, setFips } from "node:crypto"; +createDiffieHellman(512); createCipheriv("aes-128-ccm", Buffer.alloc(16), Buffer.alloc(12), { authTagLength: 16 }); checkPrimeSync(7n); setFips(false); @@ -103,9 +103,9 @@ cipherStream.on("data", () => {}); 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. */ +/* WebCrypto beyond the lowered methods: @types/node declares the whole + * SubtleCrypto surface, and the methods outside generateKey, importKey, + * exportKey, 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)); } 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/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/harness/__snapshots__/node-types-fenced.txt b/tests/harness/__snapshots__/node-types-fenced.txt index 0bd13963d..93a687267 100644 --- a/tests/harness/__snapshots__/node-types-fenced.txt +++ b/tests/harness/__snapshots__/node-types-fenced.txt @@ -115,18 +115,18 @@ 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.createDiffieHellman' 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 { checkPrimeSync, createCipheriv, createDiffieHellman, setFips } from "node:crypto"; + 76 | createDiffieHellman(512); + | ^~~~~~~~~~~~~~~~~~~~~~~~ 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: Diffie-Hellman and RSA encryption have no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, and createECDH 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 | createDiffieHellman(512); 77 | createCipheriv("aes-128-ccm", Buffer.alloc(16), Buffer.alloc(12), { authTagLength: 16 }); | ^~~~~~~~~~~~~ 78 | checkPrimeSync(7n); @@ -228,7 +228,7 @@ fenced.ts:105:1 - error SC2020: 'ECDH.computeSecret(key, encoding) with a Buffer 104 | createECDH("sect163k1"); 105 | createECDH("prime256v1").computeSecret(Buffer.alloc(65), "hex"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 106 | /* WebCrypto beyond the HMAC slice: @types/node declares the whole + 106 | /* WebCrypto beyond the lowered methods: @types/node declares the whole 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) @@ -239,7 +239,7 @@ fenced.ts:110:9 - error SC2020: 'crypto.subtle.encrypt' is part of the standard | ^~~~~~~~~~~~~~~~~~~~~ 111 | } - 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.importKey('raw', ...) for HMAC keys, 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:115:15 - error SC2020: 'navigator.hardwareConcurrency' is typed by @types/node but has no scriptc lowering yet diff --git a/tests/harness/__snapshots__/webcrypto-refusals.ts.txt b/tests/harness/__snapshots__/webcrypto-refusals.ts.txt index 521edff3c..2821d8306 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:5: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" }, + 4 | // (node-types/fenced.ts pins their fence under @types/node). + 5 | const subtle = crypto.subtle; + | ^~~~~~~~~~~~~ + 6 | 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.importKey('raw', ...) for HMAC keys, 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:8: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); + 7 | + 8 | console.log(typeof crypto.subtle.sign); + | ^~~~~~~~~~~~~~~~~~ + 9 | - 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); - | ^~~~~~~~~~~~~~~~~~ - 19 | - - 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.importKey('raw', ...) for HMAC keys, 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/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/errors.test.ts b/tests/harness/errors.test.ts index 8af6998ca..de73c6289 100644 --- a/tests/harness/errors.test.ts +++ b/tests/harness/errors.test.ts @@ -1641,7 +1641,7 @@ console.log(typeof promisePrototype, typeof promisePrototype.then, promiseProtot // 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,11 +1653,10 @@ 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"]), -); +await attempt("aes", () => crypto.subtle.importKey("raw", bytes, { name: "AES-GCM" }, false, ["encrypt"])); 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"]), @@ -1672,15 +1671,16 @@ 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" + + "aes Error SC2020 crypto.subtle.importKey with the AES-GCM 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", ); }); - test("a literal 'jwk' import is a named fence where it runs", async () => { + test("a literal 'jwk' HMAC import rejects with SC2020", async () => { const r = await compileAndRun( "webcrypto-jwk-literal", `console.log("before"); @@ -1690,8 +1690,59 @@ await crypto.subtle.importKey("jwk", { kty: "oct", k: "c2VjcmV0" }, { name: "HMA ); 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$/, + expect(r.stderr).toBe( + "Uncaught Error: crypto.subtle.importKey with the 'jwk' key format is not supported yet [SC2020]\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/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/project-config.test.ts b/tests/harness/project-config.test.ts index dabb9b0bf..186ded475 100644 --- a/tests/harness/project-config.test.ts +++ b/tests/harness/project-config.test.ts @@ -1114,6 +1114,38 @@ test("node-types: ECDH matches Node under @types/node", async () => { 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"); diff --git a/tests/harness/self-hosting-native-toolchain.test.ts b/tests/harness/self-hosting-native-toolchain.test.ts index 7da7626b7..d1dc52c7a 100644 --- a/tests/harness/self-hosting-native-toolchain.test.ts +++ b/tests/harness/self-hosting-native-toolchain.test.ts @@ -48,6 +48,8 @@ const features: NativeLinkFeatures = { tlsCa: false, cipher: false, ecdh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, }; diff --git a/tests/harness/self-hosting-runtime-pack.test.ts b/tests/harness/self-hosting-runtime-pack.test.ts index f4fde795c..908bdc5bb 100644 --- a/tests/harness/self-hosting-runtime-pack.test.ts +++ b/tests/harness/self-hosting-runtime-pack.test.ts @@ -49,6 +49,8 @@ const base: NativeLinkFeatures = { tlsCa: false, cipher: false, ecdh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, }; From 1773ffbef35e8ffb2cdfb060278ac316df85116d Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 02:52:01 -0500 Subject: [PATCH 035/102] WebCrypto: the crypto global, node:crypto's webcrypto, and secret-key SubtleCrypto --- .../limitations/builtin-apis/crypto.mdx | 3 + .../src/generated/node-v24-compatibility.json | 58 +- .../generated/node-v24-internal.json | 198 ++- internal/compatibility/static-support.json | 11 +- .../ambient/scriptc-node-fallback.d.ts | 103 +- .../compiler/src/backend/llvm/lib-shared.ts | 12 + .../src/backend/native-link-info-core.ts | 5 +- .../compiler/src/backend/native/contracts.ts | 5 +- .../compiler/src/backend/native/executable.ts | 3 + .../src/backend/target-diagnostics.ts | 8 + .../src/frontend/lowering/builtins/crypto.ts | 5 +- .../frontend/lowering/builtins/webcrypto.ts | 60 +- .../lowering/expressions/identifiers.ts | 5 +- .../lowering/expressions/property-access.ts | 14 +- .../src/frontend/lowering/lower-calls.ts | 35 +- .../src/frontend/lowering/lower-stmts.ts | 10 +- .../compiler/src/frontend/lowering/lowerer.ts | 4 + .../src/frontend/lowering/surfaces.ts | 20 +- packages/compiler/src/frontend/type-mapper.ts | 10 + .../compiler/src/ir/builtin-signatures.ts | 7 + packages/compiler/src/ir/runtime-features.ts | 14 +- packages/compiler/surface-manifest.json | 12 +- .../corpus/7120-webcrypto-random-uuid.ts.json | 6 + .../7121-webcrypto-crypto-object.mjs.json | 6 + .../corpus/7122-webcrypto-node-crypto.ts.json | 6 + .../7123-webcrypto-node-crypto.cjs.json | 6 + .../corpus/7124-webcrypto-secret-keys.ts.json | 6 + .../corpus/7125-webcrypto-key-errors.mjs.json | 6 + .../tests/corpus/7126-webcrypto-aes.ts.json | 6 + .../corpus/7127-webcrypto-aes-errors.mjs.json | 6 + .../corpus/7128-webcrypto-derive.ts.json | 6 + .../7129-webcrypto-derive-errors.mjs.json | 6 + .../node-types/webcrypto-keys.ts.json | 6 + .../runtime-darwin-arm64/scripts/build.mjs | 3 +- .../runtime-pack-matrix.mjs | 4 + .../runtime-pack-common/scripts/build.mjs | 3 +- .../runtime-wasm32-wasi/scripts/build.mjs | 1 + packages/runtime/src/scr_crypto.h | 44 +- packages/runtime/src/scr_webcrypto.c | 1372 +++++++++++++++-- packages/runtime/src/scr_webcrypto_aes.c | 137 ++ packages/runtime/src/scr_webcrypto_object.c | 53 + tests/corpus/7120-webcrypto-random-uuid.ts | 22 + tests/corpus/7121-webcrypto-crypto-object.mjs | 35 + tests/corpus/7122-webcrypto-node-crypto.ts | 38 + tests/corpus/7123-webcrypto-node-crypto.cjs | 31 + tests/corpus/7124-webcrypto-secret-keys.ts | 91 ++ tests/corpus/7125-webcrypto-key-errors.mjs | 95 ++ tests/corpus/7126-webcrypto-aes.ts | 77 + tests/corpus/7127-webcrypto-aes-errors.mjs | 71 + tests/corpus/7128-webcrypto-derive.ts | 45 + tests/corpus/7129-webcrypto-derive-errors.mjs | 72 + tests/diagnostics/webcrypto-refusals.ts | 19 +- tests/fixtures/node-types/fenced.ts | 12 +- tests/fixtures/node-types/webcrypto-keys.ts | 32 + .../__snapshots__/node-types-fenced.txt | 10 +- .../__snapshots__/webcrypto-refusals.ts.txt | 31 +- .../7120-webcrypto-random-uuid.ts.json | 1 + .../7121-webcrypto-crypto-object.mjs.json | 1 + .../7122-webcrypto-node-crypto.ts.json | 1 + .../7123-webcrypto-node-crypto.cjs.json | 1 + .../7124-webcrypto-secret-keys.ts.json | 1 + .../7125-webcrypto-key-errors.mjs.json | 1 + .../corpus-costs/7126-webcrypto-aes.ts.json | 1 + .../7127-webcrypto-aes-errors.mjs.json | 1 + .../7128-webcrypto-derive.ts.json | 1 + .../7129-webcrypto-derive-errors.mjs.json | 1 + tests/harness/errors.test.ts | 31 +- tests/harness/project-config.test.ts | 18 + 68 files changed, 2688 insertions(+), 337 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7120-webcrypto-random-uuid.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7121-webcrypto-crypto-object.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7122-webcrypto-node-crypto.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7123-webcrypto-node-crypto.cjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7124-webcrypto-secret-keys.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7125-webcrypto-key-errors.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7126-webcrypto-aes.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7127-webcrypto-aes-errors.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7128-webcrypto-derive.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7129-webcrypto-derive-errors.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/webcrypto-keys.ts.json create mode 100644 packages/runtime/src/scr_webcrypto_aes.c create mode 100644 packages/runtime/src/scr_webcrypto_object.c create mode 100644 tests/corpus/7120-webcrypto-random-uuid.ts create mode 100644 tests/corpus/7121-webcrypto-crypto-object.mjs create mode 100644 tests/corpus/7122-webcrypto-node-crypto.ts create mode 100644 tests/corpus/7123-webcrypto-node-crypto.cjs create mode 100644 tests/corpus/7124-webcrypto-secret-keys.ts create mode 100644 tests/corpus/7125-webcrypto-key-errors.mjs create mode 100644 tests/corpus/7126-webcrypto-aes.ts create mode 100644 tests/corpus/7127-webcrypto-aes-errors.mjs create mode 100644 tests/corpus/7128-webcrypto-derive.ts create mode 100644 tests/corpus/7129-webcrypto-derive-errors.mjs create mode 100644 tests/fixtures/node-types/webcrypto-keys.ts create mode 100644 tests/harness/corpus-costs/7120-webcrypto-random-uuid.ts.json create mode 100644 tests/harness/corpus-costs/7121-webcrypto-crypto-object.mjs.json create mode 100644 tests/harness/corpus-costs/7122-webcrypto-node-crypto.ts.json create mode 100644 tests/harness/corpus-costs/7123-webcrypto-node-crypto.cjs.json create mode 100644 tests/harness/corpus-costs/7124-webcrypto-secret-keys.ts.json create mode 100644 tests/harness/corpus-costs/7125-webcrypto-key-errors.mjs.json create mode 100644 tests/harness/corpus-costs/7126-webcrypto-aes.ts.json create mode 100644 tests/harness/corpus-costs/7127-webcrypto-aes-errors.mjs.json create mode 100644 tests/harness/corpus-costs/7128-webcrypto-derive.ts.json create mode 100644 tests/harness/corpus-costs/7129-webcrypto-derive-errors.mjs.json diff --git a/docs/content/limitations/builtin-apis/crypto.mdx b/docs/content/limitations/builtin-apis/crypto.mdx index 3c830c63d..b00ea438e 100644 --- a/docs/content/limitations/builtin-apis/crypto.mdx +++ b/docs/content/limitations/builtin-apis/crypto.mdx @@ -16,4 +16,7 @@ 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. + 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 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; other SubtleCrypto methods, algorithms, and key formats are refused. Native derivations finish before their deferred callbacks, so computation blocks the caller. diff --git a/docs/src/generated/node-v24-compatibility.json b/docs/src/generated/node-v24-compatibility.json index 66b0ba3dd..2c09eb9be 100644 --- a/docs/src/generated/node-v24-compatibility.json +++ b/docs/src/generated/node-v24-compatibility.json @@ -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" } }, { @@ -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" } }, { diff --git a/internal/compatibility/generated/node-v24-internal.json b/internal/compatibility/generated/node-v24-internal.json index c6a7a102c..c9f6dc6be 100644 --- a/internal/compatibility/generated/node-v24-internal.json +++ b/internal/compatibility/generated/node-v24-internal.json @@ -19313,6 +19313,8 @@ "tests/corpus/6703-ecdh-private-keys.ts", "tests/corpus/6704-ecdh-set-public-key.cjs", "tests/corpus/6705-ecdh-handles.ts", + "tests/corpus/7122-webcrypto-node-crypto.ts", + "tests/corpus/7123-webcrypto-node-crypto.cjs", "tests/corpus/node24-crypto-kdf-errors.ts", "tests/corpus/node24-crypto-kdf-options.ts", "tests/corpus/node24-crypto-kdf.ts", @@ -21215,8 +21217,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 +21244,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" }, @@ -106607,8 +106617,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 +106624,20 @@ "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.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/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 +110095,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 +110124,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 +110153,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 +110214,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 +110243,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 +110272,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 +110301,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 +110330,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 +110501,23 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.decrypt", + "tests": [ + "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" + ] }, "anchorSource": "exact" }, @@ -110494,8 +110539,23 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.deriveBits", + "tests": [ + "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" + ] }, "anchorSource": "exact" }, @@ -110517,8 +110577,23 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.deriveKey", + "tests": [ + "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" + ] }, "anchorSource": "exact" }, @@ -110543,6 +110618,13 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.digest", "tests": [ + "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", @@ -110617,8 +110699,23 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.encrypt", + "tests": [ + "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" + ] }, "anchorSource": "exact" }, @@ -110640,8 +110737,23 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.exportKey", + "tests": [ + "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" + ] }, "anchorSource": "exact" }, @@ -110686,8 +110798,23 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.generateKey", + "tests": [ + "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" + ] }, "anchorSource": "exact" }, @@ -110712,6 +110839,13 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.importKey", "tests": [ + "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", @@ -110743,6 +110877,13 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.sign", "tests": [ + "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", @@ -110797,6 +110938,13 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.verify", "tests": [ + "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", diff --git a/internal/compatibility/static-support.json b/internal/compatibility/static-support.json index 23c7a159b..e7b3486c4 100644 --- a/internal/compatibility/static-support.json +++ b/internal/compatibility/static-support.json @@ -187,16 +187,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/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.deriveBits", "subtle.deriveKey", "subtle.sign", "subtle.verify", "subtle.digest"], "status": "partial", "evidence": ["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"] }, { "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"] }, @@ -413,6 +415,7 @@ { "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": ["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": "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"] }, diff --git a/packages/compiler/ambient/scriptc-node-fallback.d.ts b/packages/compiler/ambient/scriptc-node-fallback.d.ts index dbb3cd8fd..489af1700 100644 --- a/packages/compiler/ambient/scriptc-node-fallback.d.ts +++ b/packages/compiler/ambient/scriptc-node-fallback.d.ts @@ -544,12 +544,15 @@ 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 +/* WebCrypto's secret-key slice (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, + * PBKDF2 and HKDF deriveBits and deriveKey, 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. */ + * 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 +585,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,10 +661,37 @@ 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 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: AesKeyGenParams | HmacKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; importKey( format: "jwk", keyData: JsonWebKey, @@ -651,6 +716,21 @@ interface SubtleCrypto { } 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 @@ -2784,8 +2864,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 +2876,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, diff --git a/packages/compiler/src/backend/llvm/lib-shared.ts b/packages/compiler/src/backend/llvm/lib-shared.ts index 8bb8bc3aa..507624652 100644 --- a/packages/compiler/src/backend/llvm/lib-shared.ts +++ b/packages/compiler/src/backend/llvm/lib-shared.ts @@ -615,10 +615,17 @@ export const LIB_FN_SYMS: Record = { "crypto.keyObjectInput": "scr_crypto_key_object_input", "crypto.isKeyObject": "scr_crypto_is_key_object", "webcrypto.importKey": "scr_webcrypto_import_key", + "webcrypto.generateKey": "scr_webcrypto_generate_key", + "webcrypto.exportKey": "scr_webcrypto_export_key", + "webcrypto.encrypt": "scr_webcrypto_encrypt", + "webcrypto.decrypt": "scr_webcrypto_decrypt", + "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", @@ -1573,6 +1580,11 @@ 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.deriveBits", + "webcrypto.deriveKey", "webcrypto.sign", "webcrypto.verify", "webcrypto.digest", diff --git a/packages/compiler/src/backend/native-link-info-core.ts b/packages/compiler/src/backend/native-link-info-core.ts index a476e1f7f..55301948b 100644 --- a/packages/compiler/src/backend/native-link-info-core.ts +++ b/packages/compiler/src/backend/native-link-info-core.ts @@ -84,8 +84,9 @@ 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. */ diff --git a/packages/compiler/src/backend/native/contracts.ts b/packages/compiler/src/backend/native/contracts.ts index 06a41c9b2..8df233585 100644 --- a/packages/compiler/src/backend/native/contracts.ts +++ b/packages/compiler/src/backend/native/contracts.ts @@ -243,8 +243,9 @@ 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). */ diff --git a/packages/compiler/src/backend/native/executable.ts b/packages/compiler/src/backend/native/executable.ts index a551ad600..229b2f967 100644 --- a/packages/compiler/src/backend/native/executable.ts +++ b/packages/compiler/src/backend/native/executable.ts @@ -297,6 +297,8 @@ 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"), + // 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 +310,7 @@ 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.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. diff --git a/packages/compiler/src/backend/target-diagnostics.ts b/packages/compiler/src/backend/target-diagnostics.ts index b7049f6fe..eb70a0d2c 100644 --- a/packages/compiler/src/backend/target-diagnostics.ts +++ b/packages/compiler/src/backend/target-diagnostics.ts @@ -208,6 +208,14 @@ export function moduleWasiUnavailableSurface( }; return false; } + if (node.fn === "webcrypto.encrypt" || node.fn === "webcrypto.decrypt") { + found = { + surface: + "WebCrypto encrypt and decrypt (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)", diff --git a/packages/compiler/src/frontend/lowering/builtins/crypto.ts b/packages/compiler/src/frontend/lowering/builtins/crypto.ts index f4270dbe8..fc1502958 100644 --- a/packages/compiler/src/frontend/lowering/builtins/crypto.ts +++ b/packages/compiler/src/frontend/lowering/builtins/crypto.ts @@ -7,6 +7,7 @@ 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, @@ -1316,8 +1317,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); diff --git a/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts b/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts index 93cba84c5..fe310294c 100644 --- a/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts +++ b/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts @@ -5,34 +5,57 @@ 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's secret-key slice (scr_webcrypto.c, with encrypt and + * decrypt in scr_webcrypto_aes.c): `crypto.subtle`'s `importKey`, + * `generateKey`, `exportKey`, `encrypt`, `decrypt`, `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([ ["importKey", "webcrypto.importKey"], + ["generateKey", "webcrypto.generateKey"], + ["exportKey", "webcrypto.exportKey"], + ["encrypt", "webcrypto.encrypt"], + ["decrypt", "webcrypto.decrypt"], + ["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, deriveBits and deriveKey with PBKDF2 or HKDF, sign and verify with HMAC, 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 +74,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/expressions/identifiers.ts b/packages/compiler/src/frontend/lowering/expressions/identifiers.ts index b5f99d682..16cca3b13 100644 --- a/packages/compiler/src/frontend/lowering/expressions/identifiers.ts +++ b/packages/compiler/src/frontend/lowering/expressions/identifiers.ts @@ -549,6 +549,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 +724,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 }; diff --git a/packages/compiler/src/frontend/lowering/expressions/property-access.ts b/packages/compiler/src/frontend/lowering/expressions/property-access.ts index f0b980da0..5cd70d2a5 100644 --- a/packages/compiler/src/frontend/lowering/expressions/property-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/property-access.ts @@ -162,6 +162,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"; @@ -842,8 +843,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 @@ -2959,6 +2968,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). diff --git a/packages/compiler/src/frontend/lowering/lower-calls.ts b/packages/compiler/src/frontend/lowering/lower-calls.ts index 7102f37ab..c503f0c9c 100644 --- a/packages/compiler/src/frontend/lowering/lower-calls.ts +++ b/packages/compiler/src/frontend/lowering/lower-calls.ts @@ -1542,9 +1542,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) ?? @@ -10492,20 +10493,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())` diff --git a/packages/compiler/src/frontend/lowering/lower-stmts.ts b/packages/compiler/src/frontend/lowering/lower-stmts.ts index e3480cf9c..7f0854523 100644 --- a/packages/compiler/src/frontend/lowering/lower-stmts.ts +++ b/packages/compiler/src/frontend/lowering/lower-stmts.ts @@ -3964,9 +3964,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)) { diff --git a/packages/compiler/src/frontend/lowering/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index ee8ba7ecb..3fbb110ed 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -13410,6 +13410,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`). diff --git a/packages/compiler/src/frontend/lowering/surfaces.ts b/packages/compiler/src/frontend/lowering/surfaces.ts index c77938337..67950a53f 100644 --- a/packages/compiler/src/frontend/lowering/surfaces.ts +++ b/packages/compiler/src/frontend/lowering/surfaces.ts @@ -2210,15 +2210,26 @@ 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.importKey", + "webcrypto.generateKey", + "webcrypto.exportKey", + "webcrypto.encrypt", + "webcrypto.decrypt", + "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, PBKDF2 and HKDF deriveBits and deriveKey, HMAC sign and verify, 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", @@ -3088,9 +3099,6 @@ export const BUILTIN_MODULE_FENCE_HINTS: Record< 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, diff --git a/packages/compiler/src/frontend/type-mapper.ts b/packages/compiler/src/frontend/type-mapper.ts index a233f0186..a491edf95 100644 --- a/packages/compiler/src/frontend/type-mapper.ts +++ b/packages/compiler/src/frontend/type-mapper.ts @@ -146,6 +146,16 @@ export const WEBCRYPTO_DYN_TYPES: ReadonlySet = new Set([ "KeyAlgorithm", "HmacImportParams", "HmacKeyAlgorithm", + "HmacKeyGenParams", + "AesKeyGenParams", + "AesKeyAlgorithm", + "JsonWebKey", + "AesGcmParams", + "AesCbcParams", + "AesCtrParams", + "Pbkdf2Params", + "HkdfParams", + "AesDerivedKeyParams", ]); export const FETCH_AMBIENT_TYPES = [ diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index fa7876579..416d5f18e 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -2846,10 +2846,17 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ * one dyn array and answers a promise that argument and validation * failures reject. CryptoKey values are native handles. */ "webcrypto.importKey": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, + "webcrypto.generateKey": { 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.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 }, diff --git a/packages/compiler/src/ir/runtime-features.ts b/packages/compiler/src/ir/runtime-features.ts index 4142b6efe..61e04177b 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", @@ -647,8 +649,9 @@ 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 and decrypt (scr_webcrypto_aes.c) + * link the same archive. */ + cipher: rule({ fns: ["crypto.cipherNew", "webcrypto.encrypt", "webcrypto.decrypt"] }), copying: rule({ expr: (node, _tables) => (node.kind === "arrIntrinsic" && COPYING_ARR_METHODS.has(node.method)) || @@ -675,12 +678,15 @@ 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", "crypto.ecdhNew", ], prefixes: [...READABLE_DYN_ASYNC_PREFIXES, "wasm."], @@ -787,6 +793,8 @@ const RUNTIME_FEATURE_RULES = { "global.native", "util.styleText", "crypto.cipherNew", + "webcrypto.encrypt", + "webcrypto.decrypt", "crypto.ecdhNew", "crypto.ecdhConvertKey", ...BUILTIN_CLASS_LIB_FNS, diff --git a/packages/compiler/surface-manifest.json b/packages/compiler/surface-manifest.json index c05e994a8..3e8b9df73 100644 --- a/packages/compiler/surface-manifest.json +++ b/packages/compiler/surface-manifest.json @@ -762,14 +762,6 @@ "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" - }, { "id": "node-builtin.dgram", "kind": "node-builtin", @@ -5719,14 +5711,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, PBKDF2 and HKDF deriveBits and deriveKey, HMAC sign and verify, and SHA-1/SHA-2 digest; other methods, algorithms and key formats are refused" }, { "id": "syntax.async-generators", 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/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/runtime-darwin-arm64/scripts/build.mjs b/packages/runtime-darwin-arm64/scripts/build.mjs index 85c5ffb00..3944b023c 100644 --- a/packages/runtime-darwin-arm64/scripts/build.mjs +++ b/packages/runtime-darwin-arm64/scripts/build.mjs @@ -172,7 +172,8 @@ 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_webcrypto_aes.c" ? ["-I", join(mbedtls, "include")] : []), ...(unit.source === "scr_zlib.c" || unit.source === "scr_fetch.c" diff --git a/packages/runtime-pack-common/runtime-pack-matrix.mjs b/packages/runtime-pack-common/runtime-pack-matrix.mjs index 0f40218a1..3529df137 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. @@ -151,6 +153,8 @@ export const OPTIONAL_RUNTIME_SOURCES = [ ["scr_ecdh.c", "ecdh"], ["scr_wasm.c", "wasm"], ["scr_webcrypto.c", "webcrypto"], + // WebCrypto's AES ciphers run over the cipher feature's mbedTLS archive. + ["scr_webcrypto_aes.c", all("cipher", "webcrypto")], ["scr_fetch.c", "nativeFetch"], ]; diff --git a/packages/runtime-pack-common/scripts/build.mjs b/packages/runtime-pack-common/scripts/build.mjs index b242b78aa..f59a2431f 100644 --- a/packages/runtime-pack-common/scripts/build.mjs +++ b/packages/runtime-pack-common/scripts/build.mjs @@ -223,7 +223,8 @@ 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_webcrypto_aes.c" ? ["-I", join(mbedtls, "include")] : []), ...(unit.source === "scr_zlib.c" || unit.source === "scr_fetch.c" diff --git a/packages/runtime-wasm32-wasi/scripts/build.mjs b/packages/runtime-wasm32-wasi/scripts/build.mjs index 2dd983973..0a8699b23 100644 --- a/packages/runtime-wasm32-wasi/scripts/build.mjs +++ b/packages/runtime-wasm32-wasi/scripts/build.mjs @@ -22,6 +22,7 @@ process.env.SCRIPTC_RUNTIME_PACK_CONFIG = JSON.stringify({ "scr_tls.c", "scr_cipher.c", "scr_ecdh.c", + "scr_webcrypto_aes.c", "scr_wasm.c", "scr_fetch.c", ], diff --git a/packages/runtime/src/scr_crypto.h b/packages/runtime/src/scr_crypto.h index d12858abf..ddc306598 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); @@ -202,19 +205,48 @@ 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); +/* 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 diff --git a/packages/runtime/src/scr_webcrypto.c b/packages/runtime/src/scr_webcrypto.c index 546b24151..4d2c27be4 100644 --- a/packages/runtime/src/scr_webcrypto.c +++ b/packages/runtime/src/scr_webcrypto.c @@ -1,22 +1,27 @@ -/* 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 @@ -28,8 +33,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,6 +49,15 @@ 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", }; +/* 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", +}; static 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", @@ -193,7 +208,24 @@ static const char *const scr_wc_usages[] = { "deriveKey", "deriveBits", "wrapKey", "unwrapKey", "encapsulateKey", "encapsulateBits", "decapsulateKey", "decapsulateBits", }; -enum { SCR_WC_USAGE_SIGN = 1u << 2, SCR_WC_USAGE_VERIFY = 1u << 3 }; +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, +}; + +/* 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) { @@ -215,11 +247,8 @@ 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), @@ -237,10 +266,10 @@ 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; @@ -261,6 +290,28 @@ static ScrDyn *scr_wc_member(const ScrDyn *dict, const char *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. */ @@ -295,11 +346,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 +360,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 +388,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 +398,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 +423,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 +477,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 */ @@ -446,26 +538,34 @@ static ScrDyn *scr_wc_cstr(const char *s) { 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 +640,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 +651,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,6 +665,208 @@ 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. */ @@ -573,6 +877,19 @@ static ScrPromise *scr_wc_rejected(void) { 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) { @@ -595,9 +912,158 @@ static 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,77 +1071,28 @@ 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; } @@ -683,7 +1100,118 @@ done: ScrPromise *scr_webcrypto_import_key(ScrDyn *args) { 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). */ +ScrPromise *scr_webcrypto_generate_key(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 *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 for secret keys: raw and raw-secret answer an ArrayBuffer + * of the key bytes, jwk an object { key_ops, ext, alg, kty, k }. */ +static ScrDyn *scr_wc_export(const ScrDyn *args) { + 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_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type CryptoKey.", prefix); + goto done; + } + 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); + goto done; + } + if (!key->extractable) { + scr_throw_domex("InvalidAccessError", "key is not extractable"); + goto done; + } + if (strcmp(format, "raw") == 0 || strcmp(format, "raw-secret") == 0) { + ScrBytes *bytes = scr_bytes_new(SCR_BYTES_U8, (double)key->len); + if (key->len) memcpy(bytes->data, key->data, key->len); + result = scr_array_buffer_from_bytes(bytes); + scr_bytes_release(bytes); + } else if (strcmp(format, "jwk") == 0) { + char buf[16]; + const char *alg = scr_wc_jwk_alg(key->name, key->hash, key->length, buf, sizeof buf); + ScrBytes *bytes = scr_bytes_new(SCR_BYTES_U8, (double)key->len); + if (key->len) memcpy(bytes->data, key->data, key->len); + ScrStr *encoding = scr_str_new("base64url", 9); + ScrStr *k = scr_bytes_to_str(bytes, encoding); + scr_str_release(encoding); + scr_bytes_release(bytes); + 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 { + char message[96]; + snprintf(message, sizeof message, "Unable to export %s secret key using %s format", key->name, + format); + scr_throw_domex("NotSupportedError", message); + } +done: + scr_wc_args_drop(&a, 2); + return result; +} + +ScrPromise *scr_webcrypto_export_key(ScrDyn *args) { + ScrDyn *result = scr_wc_export(args); + if (!result) return scr_wc_rejected(); + return scr_wc_resolved(result); } /* sign(algorithm, key, data) / verify(algorithm, key, signature, data): @@ -717,13 +1245,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 (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); @@ -827,3 +1359,563 @@ 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; +} + +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]); + if (!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 (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; + { + ScrBytes *view = data; + SCR_BYTES_SNAPSHOT(view); + ScrBytes *iv = params.iv; + SCR_BYTES_SNAPSHOT(iv); + if (!params.aad) params.aad = scr_bytes_new(SCR_BYTES_U8, 0); + 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) { + result = scr_wc_deferred_buffer(out); + } else { + scr_throw_domex("OperationError", "The operation failed for an operation-specific reason"); + result = scr_wc_deferred_rejection(); + } + } +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(); +} + +/* ── 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) { + if (!(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]); + if (!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(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]); + if (!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(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_aes.c b/packages/runtime/src/scr_webcrypto_aes.c new file mode 100644 index 000000000..7cb63f561 --- /dev/null +++ b/packages/runtime/src/scr_webcrypto_aes.c @@ -0,0 +1,137 @@ +/* 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; +} + +/* 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-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); } 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/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/diagnostics/webcrypto-refusals.ts b/tests/diagnostics/webcrypto-refusals.ts index d162872fb..309e70c4e 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 -// (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); - +// The native WebCrypto surface is crypto.subtle's secret-key slice, 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 subtle = crypto.subtle; console.log(typeof subtle); diff --git a/tests/fixtures/node-types/fenced.ts b/tests/fixtures/node-types/fenced.ts index 16a74081f..dfd07d446 100644 --- a/tests/fixtures/node-types/fenced.ts +++ b/tests/fixtures/node-types/fenced.ts @@ -103,13 +103,13 @@ cipherStream.on("data", () => {}); 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)); +/* WebCrypto beyond the secret-key slice: @types/node declares the whole + * SubtleCrypto surface, and the methods outside the slice, such as + * wrapKey, fence by name. */ +async function wrapWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { + await crypto.subtle.wrapKey("raw", key, key, "AES-KW"); } -void encryptWithWebCrypto; +void wrapWithWebCrypto; /* 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/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/harness/__snapshots__/node-types-fenced.txt b/tests/harness/__snapshots__/node-types-fenced.txt index 0bd13963d..2f1f8cb2e 100644 --- a/tests/harness/__snapshots__/node-types-fenced.txt +++ b/tests/harness/__snapshots__/node-types-fenced.txt @@ -228,18 +228,18 @@ fenced.ts:105:1 - error SC2020: 'ECDH.computeSecret(key, encoding) with a Buffer 104 | createECDH("sect163k1"); 105 | createECDH("prime256v1").computeSecret(Buffer.alloc(65), "hex"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 106 | /* WebCrypto beyond the HMAC slice: @types/node declares the whole + 106 | /* WebCrypto beyond the secret-key slice: @types/node declares the whole 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:110:9 - error SC2020: 'crypto.subtle.wrapKey' 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)); + 109 | async function wrapWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { + 110 | await crypto.subtle.wrapKey("raw", key, key, "AES-KW"); | ^~~~~~~~~~~~~~~~~~~~~ 111 | } - 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, deriveBits and deriveKey with PBKDF2 or HKDF, sign and verify with HMAC, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle fenced.ts:115:15 - error SC2020: 'navigator.hardwareConcurrency' is typed by @types/node but has no scriptc lowering yet diff --git a/tests/harness/__snapshots__/webcrypto-refusals.ts.txt b/tests/harness/__snapshots__/webcrypto-refusals.ts.txt index 521edff3c..e46099f69 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 | // @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, deriveBits and deriveKey with PBKDF2 or HKDF, 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: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, deriveBits and deriveKey with PBKDF2 or HKDF, 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 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/errors.test.ts b/tests/harness/errors.test.ts index 8af6998ca..00ee40043 100644 --- a/tests/harness/errors.test.ts +++ b/tests/harness/errors.test.ts @@ -1634,14 +1634,14 @@ 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. +// 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 secret-key slice reject with SC2020", async () => { const r = await compileAndRun( "webcrypto-unsupported-algorithms", `const bytes = new TextEncoder().encode("secret"); @@ -1662,10 +1662,10 @@ 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"]), -); +await attempt("ed25519 key", () => crypto.subtle.generateKey({ name: "Ed25519" }, 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)); `, "mjs", ); @@ -1676,22 +1676,25 @@ await attempt("computed jwk", () => "ecdsa Error SC2020 crypto.subtle.sign with the ECDSA algorithm is not supported yet\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", + "ed25519 key Error SC2020 crypto.subtle.generateKey with the Ed25519 algorithm 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", ); }); - 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-wrap-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: "AES-KW", length: 128 }, true, ["wrapKey"]); +await crypto.subtle.wrapKey("raw", key, key, "AES-KW"); `, "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\.wrapKey' is part of the standard library types but has no scriptc lowering yet.*\n$/, ); }); }); diff --git a/tests/harness/project-config.test.ts b/tests/harness/project-config.test.ts index dabb9b0bf..8532ad6e9 100644 --- a/tests/harness/project-config.test.ts +++ b/tests/harness/project-config.test.ts @@ -1132,6 +1132,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"); From f00428ccb1aa6a7e0b3a384cb71b53bd4fe28217 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 02:53:03 -0500 Subject: [PATCH 036/102] Keep pipe() answering its destination and evaluate pipeline() arguments in source order --- .../frontend/lowering/builtins/hash-stream.ts | 16 +++--- .../src/frontend/lowering/lower-stream.ts | 52 +++++++++++++------ tests/corpus/7055-cipher-streams.ts | 40 ++++++++++++++ 3 files changed, 87 insertions(+), 21 deletions(-) diff --git a/packages/compiler/src/frontend/lowering/builtins/hash-stream.ts b/packages/compiler/src/frontend/lowering/builtins/hash-stream.ts index f2f3625dd..88f6c2d95 100644 --- a/packages/compiler/src/frontend/lowering/builtins/hash-stream.ts +++ b/packages/compiler/src/frontend/lowering/builtins/hash-stream.ts @@ -82,7 +82,10 @@ export function lowerHashStreamCall( if (!isValueStream(lowerer, access.expression)) return null; const info = lowerer.classes.get(TRANSFORM_CLASS); if (!info) return null; - return withValueStreamReceiver(lowerer, access.expression, locOf(call), () => + // 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), @@ -98,19 +101,20 @@ export function lowerValueStreamProperty( 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), () => + 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. A result - * typed as the Transform (a member that answers `this`) answers the value - * itself. */ + * `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); @@ -124,7 +128,7 @@ function withValueStreamReceiver( } 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", diff --git a/packages/compiler/src/frontend/lowering/lower-stream.ts b/packages/compiler/src/frontend/lowering/lower-stream.ts index ab21b8a7e..d6f89dc11 100644 --- a/packages/compiler/src/frontend/lowering/lower-stream.ts +++ b/packages/compiler/src/frontend/lowering/lower-stream.ts @@ -2935,6 +2935,10 @@ function lowerPipelineStages( // 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]!; const fn = pipelineStageFunction(lowerer, arg); @@ -2948,6 +2952,7 @@ function lowerPipelineStages( 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; @@ -2974,6 +2979,7 @@ function lowerPipelineStages( 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; @@ -3022,6 +3028,7 @@ function lowerPipelineStages( 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; @@ -3048,6 +3055,20 @@ function lowerPipelineStages( } helperArgs.push(pipelineBoxHelper(lowerer, destPromise!, loc)); } + 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. const flags = (dest << 1) | (mask !== 0 ? 32 : 0); const head: IrExpr[] = [ @@ -3062,7 +3083,7 @@ function lowerPipelineStages( ]; const last: IrType = dest === 2 ? { kind: "object", className: "%PassThrough" } : streams[streams.length - 1]!.type; - if (mask === 0) return { args: head, last, dest, destPromise, wrap: (call) => call }; + 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); @@ -3079,20 +3100,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, + }), }; } diff --git a/tests/corpus/7055-cipher-streams.ts b/tests/corpus/7055-cipher-streams.ts index 8befd2339..8f9e0d1ea 100644 --- a/tests/corpus/7055-cipher-streams.ts +++ b/tests/corpus/7055-cipher-streams.ts @@ -8,6 +8,7 @@ import * as crypto from "node:crypto"; import { PassThrough, Readable, + Transform, Writable, addAbortSignal, compose, @@ -65,6 +66,43 @@ async function viaPipeAndForAwait(): Promise { 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"); @@ -176,6 +214,8 @@ async function main(): Promise { await viaCallbackPipeline(); await viaPromisePipeline(); await viaPipeAndForAwait(); + await viaPipeIntoTransform(); + await viaPipelineArgumentOrder(); await viaEvents(); await gcm(); } From 70697b45c327c515559e65cd8e4a8602bc98941b Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 02:56:39 -0500 Subject: [PATCH 037/102] Give generic arrow bindings Node's behavior before their declarations run Generic arrow and function-expression bindings compile to shared instances, and their declarations emit no store. Code that can run before the declaration then diverged from Node. - Inside a function, a nested function lowered before the declaration reads the binding through a TDZ box that nothing initialized. That covers closures above the declaration and hoisted function declarations. Such a read threw a ReferenceError even after the declaration ran. The declaration now stores the instance its declared signature pins into that box. - At module scope, calls and pinned value reads went straight to the instances even when a hoisted function or an earlier closure ran them before the declaration. A binding with such a use now has a flag that its declaration sets. - Uses that can run first check the flag. - A let or const throws Node's ReferenceError before the arguments run. - A var runs the arguments and then throws "is not a function". - Uses that follow the declaration stay direct calls: later statements, closures created after it, its own initializer, and function declarations that only such code calls. A var binding inside a function that is called from a place that can run before its declaration would need a per-call flag shared with its closures. That shape now fails with SC1090 instead of calling the instance. --- .../frontend/lowering/generic-functions.ts | 330 +++++++++++++++++- .../src/frontend/lowering/lower-stmts.ts | 17 +- .../compiler/src/frontend/lowering/lowerer.ts | 3 + ...0-generic-local-binding-early-uses.ts.json | 6 + .../7181-generic-module-binding-tdz.ts.json | 6 + .../7182-generic-binding-direct-calls.ts.json | 6 + .../7180-generic-local-binding-early-uses.ts | 53 +++ .../corpus/7181-generic-module-binding-tdz.ts | 49 +++ .../7182-generic-binding-direct-calls.ts | 42 +++ tests/diagnostics/generic-value-bindings.ts | 12 + .../generic-value-bindings.ts.txt | 9 +- ...0-generic-local-binding-early-uses.ts.json | 1 + .../7181-generic-module-binding-tdz.ts.json | 1 + .../7182-generic-binding-direct-calls.ts.json | 1 + 14 files changed, 531 insertions(+), 5 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7180-generic-local-binding-early-uses.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7181-generic-module-binding-tdz.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7182-generic-binding-direct-calls.ts.json create mode 100644 tests/corpus/7180-generic-local-binding-early-uses.ts create mode 100644 tests/corpus/7181-generic-module-binding-tdz.ts create mode 100644 tests/corpus/7182-generic-binding-direct-calls.ts create mode 100644 tests/harness/corpus-costs/7180-generic-local-binding-early-uses.ts.json create mode 100644 tests/harness/corpus-costs/7181-generic-module-binding-tdz.ts.json create mode 100644 tests/harness/corpus-costs/7182-generic-binding-direct-calls.ts.json diff --git a/packages/compiler/src/frontend/lowering/generic-functions.ts b/packages/compiler/src/frontend/lowering/generic-functions.ts index abcd5a584..d0e07582c 100644 --- a/packages/compiler/src/frontend/lowering/generic-functions.ts +++ b/packages/compiler/src/frontend/lowering/generic-functions.ts @@ -3,15 +3,20 @@ 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 { 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 +27,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 +96,15 @@ 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 }; + /** 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 @@ -257,7 +271,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 @@ -1233,6 +1254,47 @@ 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. */ +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(); + return pinnedGenericClosure(lowerer, name, info, sigs[0]!, fenceUnpinned); +} + +/** 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); @@ -2565,9 +2627,18 @@ export function bindingGenericFnInfoOf( 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 +2646,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/lower-stmts.ts b/packages/compiler/src/frontend/lowering/lower-stmts.ts index e3480cf9c..7d9425a28 100644 --- a/packages/compiler/src/frontend/lowering/lower-stmts.ts +++ b/packages/compiler/src/frontend/lowering/lower-stmts.ts @@ -138,6 +138,8 @@ import { bindingGenericFnAliasInfoOf, bindingGenericFnInfoOf, bindingGenericFnNodeOf, + genericBindingPresenceStore, + genericBindingStoredValue, implicitLocalFnInfoOf, implicitLocalFnNodeOf, implicitMethodCallInfersReturn, @@ -5108,8 +5110,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); } } diff --git a/packages/compiler/src/frontend/lowering/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index ee8ba7ecb..751aca523 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -1906,6 +1906,9 @@ 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-symbol result of the never-reassigned file scan * (bindingNeverReassigned — object-literal generic-method receivers). */ readonly neverReassignedCache = new Map(); 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/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..85458d973 --- /dev/null +++ b/tests/corpus/7180-generic-local-binding-early-uses.ts @@ -0,0 +1,53 @@ +// 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()()); 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/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/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/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 } From 32da078c118daa1400cad25e5d46bbe9b07f366a Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:00:21 -0500 Subject: [PATCH 038/102] Match Node's AsyncLocalStorage context in async prefixes and generator steps --- packages/compiler/src/backend/llvm/emitter.ts | 14 +-- .../compiler/test/await-call-emission.test.ts | 14 +-- .../7106-async-prefix-enter-with.ts.json | 6 ++ .../corpus/7107-for-await-context.ts.json | 6 ++ .../7108-generator-step-context.ts.json | 6 ++ packages/runtime/src/scr_async.c | 83 +++++++++++++---- packages/runtime/src/scr_async.h | 10 ++- tests/corpus/7106-async-prefix-enter-with.ts | 88 +++++++++++++++++++ tests/corpus/7107-for-await-context.ts | 37 ++++++++ tests/corpus/7108-generator-step-context.ts | 49 +++++++++++ .../7106-async-prefix-enter-with.ts.json | 1 + .../7107-for-await-context.ts.json | 1 + .../7108-generator-step-context.ts.json | 1 + 13 files changed, 281 insertions(+), 35 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7106-async-prefix-enter-with.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7107-for-await-context.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7108-generator-step-context.ts.json create mode 100644 tests/corpus/7106-async-prefix-enter-with.ts create mode 100644 tests/corpus/7107-for-await-context.ts create mode 100644 tests/corpus/7108-generator-step-context.ts create mode 100644 tests/harness/corpus-costs/7106-async-prefix-enter-with.ts.json create mode 100644 tests/harness/corpus-costs/7107-for-await-context.ts.json create mode 100644 tests/harness/corpus-costs/7108-generator-step-context.ts.json diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index c254d0907..4ab2a42fa 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -1885,14 +1885,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 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/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/runtime/src/scr_async.c b/packages/runtime/src/scr_async.c index db1e54295..9d3a25469 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,34 @@ void scr_als_ctx_release(ScrAlsCtx *c) { free(c); } +/* 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); + } +} + +/* 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); @@ -1889,6 +1921,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 +2043,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 +2057,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 +2093,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 +2103,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 +2209,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 +2221,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 +2234,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 +2343,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 +2363,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 +2412,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 +5711,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 +5726,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 +5748,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 +5758,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 +5767,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/tests/corpus/7106-async-prefix-enter-with.ts b/tests/corpus/7106-async-prefix-enter-with.ts new file mode 100644 index 000000000..27dff250b --- /dev/null +++ b/tests/corpus/7106-async-prefix-enter-with.ts @@ -0,0 +1,88 @@ +// 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. +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; +} + +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()}`); + }); + 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/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 } From b2b216c3df6184fd964ad3aee3ee69c07e7ecd07 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:10:12 -0500 Subject: [PATCH 039/102] Extend a generic factory's anonymous local class returned through a constructor type A generic factory declared to return a constructor type now also extends when it returns an anonymous class expression (`return class { ... } as Struct`) or a `const` bound to one (`const Hold = class { ... }; return Hold`). The result's class value is the class expression's own constructor type; before, it was read through the class's name, so an anonymous class refused with SC1090 and SC2008. --- .../frontend/lowering/generic-functions.ts | 34 ++++++++++++++----- .../corpus/6912-extend-factory-local-class.ts | 32 +++++++++++++++++ 2 files changed, 57 insertions(+), 9 deletions(-) diff --git a/packages/compiler/src/frontend/lowering/generic-functions.ts b/packages/compiler/src/frontend/lowering/generic-functions.ts index 0f549d889..e843b6909 100644 --- a/packages/compiler/src/frontend/lowering/generic-functions.ts +++ b/packages/compiler/src/frontend/lowering/generic-functions.ts @@ -496,10 +496,18 @@ function localClassResultInstance( const viaConstructorType = retTs.getSymbol()?.valueDeclaration !== resultClass; const returnType = withInstanceScope(lowerer, info, inst, () => { if (!viaConstructorType) return lowerer.mapTypeOf(retTs); - const classSymbol = resultClass.name - ? lowerer.checker.getSymbolAtLocation(resultClass.name) - : undefined; - return classSymbol ? lowerer.mapTypeOf(lowerer.checker.getTypeOfSymbol(classSymbol)) : null; + // 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); @@ -646,11 +654,19 @@ function returnedLocalClass(lowerer: Lowerer, info: GenericFnInfo): ts.ClassLike if (ts.isClassExpression(expr)) return declaredInside(expr, info.decl) ? expr : null; if (!ts.isIdentifier(expr)) return null; const declaration = lowerer.checker.getSymbolAtLocation(expr)?.valueDeclaration; - return declaration && - ts.isClassDeclaration(declaration) && - declaredInside(declaration, info.decl) - ? declaration - : null; + 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; diff --git a/tests/corpus/6912-extend-factory-local-class.ts b/tests/corpus/6912-extend-factory-local-class.ts index 8848280e2..e33a59c77 100644 --- a/tests/corpus/6912-extend-factory-local-class.ts +++ b/tests/corpus/6912-extend-factory-local-class.ts @@ -65,3 +65,35 @@ function twice(n: number): number { 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()); From 42dd9390c13551dd40383e3a1decbeeaa5de33af Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:10:30 -0500 Subject: [PATCH 040/102] Compute index temps of a typed-array loop counter as integers In `for (let i = 0; i < out.length; i++) { const j = i * 4; ... px[j + 1] }` the fast copy of the typed-array loop version computed `j` as a double and converted every index back. The version gives each affine index operand its range under the guard's bound on the counter, but kept the range an operand already had, and the counter of a loop to a length is only known to be below 2^53, so `i * 4` stayed a double multiply. The version now narrows the existing range to the guard's. A constant number local whose initializer has an exact integer form now keeps that integer in an i64 slot beside the double, and its reads carry both, so `px[j + 1]` indexes with integer arithmetic. Only optimized synchronous functions keep these integers, and every other declaration of the local drops its integer, since one declaration is emitted once per loop copy. --- .../backend/llvm/bytes-loop-versions.test.ts | 44 ++++++ .../src/backend/llvm/bytes-loop-versions.ts | 10 +- .../src/backend/llvm/emit-function.ts | 2 + .../src/backend/llvm/emit-statements.ts | 44 ++++++ packages/compiler/src/backend/llvm/emitter.ts | 11 ++ .../src/backend/llvm/expr-primitives.ts | 3 +- .../6996-typed-array-index-temps.ts.json | 6 + tests/corpus/6996-typed-array-index-temps.ts | 134 ++++++++++++++++++ .../6996-typed-array-index-temps.ts.json | 1 + 9 files changed, 252 insertions(+), 3 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6996-typed-array-index-temps.ts.json create mode 100644 tests/corpus/6996-typed-array-index-temps.ts create mode 100644 tests/harness/corpus-costs/6996-typed-array-index-temps.ts.json 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..28194c7b3 100644 --- a/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts +++ b/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts @@ -281,6 +281,50 @@ 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("Float16Array accesses version in elements and share the element tag", () => { const f16s: IrType = { kind: "bytes", elem: "f16" }; const withHalves = (body: IrStmt[]): IrFunction => { diff --git a/packages/compiler/src/backend/llvm/bytes-loop-versions.ts b/packages/compiler/src/backend/llvm/bytes-loop-versions.ts index dcb735e61..8c7f668a0 100644 --- a/packages/compiler/src/backend/llvm/bytes-loop-versions.ts +++ b/packages/compiler/src/backend/llvm/bytes-loop-versions.ts @@ -427,7 +427,6 @@ 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; @@ -438,7 +437,14 @@ export function matchBytesLoopVersion( 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) }); } } // Renumber the receivers the kept checks use. diff --git a/packages/compiler/src/backend/llvm/emit-function.ts b/packages/compiler/src/backend/llvm/emit-function.ts index 5053c1b54..09e6551c3 100644 --- a/packages/compiler/src/backend/llvm/emit-function.ts +++ b/packages/compiler/src/backend/llvm/emit-function.ts @@ -128,6 +128,8 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { emitter.stableCaptureIds = fn.captures !== undefined ? emitter.lazyCaptures.stableCaptures(fn.name) : new Set(); emitter.integerLoopBindings.clear(); + emitter.integerTemps.clear(); + emitter.integerTempsEnabled = emitter.debug === null && !fn.async && !fn.generator; emitter.countedLoopsEnabled = emitter.debug === null && !fn.async && !fn.generator; emitter.speculativeLoopsEnabled = emitter.countedLoopsEnabled; emitter.speculativeFunction = fn.name; diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index d2e96994b..7f189c066 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -50,6 +50,7 @@ import { emitBytesLoopVersionGuard } from "./bytes-loop-versions.js"; import { mangleLocal } from "../mangle.js"; import { LlvmUnsupportedError } from "./unsupported.js"; import type { LlValue } from "./expr-context.js"; +import { widenInteger } from "./integer-values.js"; import { SCALAR_UNION_RESULT } from "./int32-abi.js"; import { emitLiteralSwitch } from "./switch-dispatch.js"; import { @@ -267,6 +268,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); @@ -1544,6 +1546,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; diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index c254d0907..e11622b9b 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -1081,6 +1081,17 @@ export class LlEmitter { string, { slot: string; type: "i32" | "i64"; signed?: boolean; range?: { min: number; max: number } } >(); + /** 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; countedLoopsEnabled = false; /** Speculative integer loops (speculative-integers.ts) run in this function. */ speculativeLoopsEnabled = false; diff --git a/packages/compiler/src/backend/llvm/expr-primitives.ts b/packages/compiler/src/backend/llvm/expr-primitives.ts index 12e488b6d..354004e9e 100644 --- a/packages/compiler/src/backend/llvm/expr-primitives.ts +++ b/packages/compiler/src/backend/llvm/expr-primitives.ts @@ -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(); 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/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/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 } From ec0574f44b2feb927745961916974b647121297e Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:13:24 -0500 Subject: [PATCH 041/102] Read the byte offset of every untyped ArrayBuffer Buffer.from in one place All Buffer.from paths over an untyped ArrayBuffer or SharedArrayBuffer now go through one function that takes the byte offset explicitly, as Node's fromArrayBuffer does. The start-offset RangeError prints the offset as JavaScript does (-1.5, -1e+21, -Infinity) and builds its message without a fixed-size buffer, which a large negative offset overran. --- packages/runtime/src/scr_bytes_io.c | 77 ++++++++++--------- .../6868-buffer-from-untyped-array-buffer.cjs | 2 +- 2 files changed, 43 insertions(+), 36 deletions(-) diff --git a/packages/runtime/src/scr_bytes_io.c b/packages/runtime/src/scr_bytes_io.c index bd79d9089..137208938 100644 --- a/packages/runtime/src/scr_bytes_io.c +++ b/packages/runtime/src/scr_bytes_io.c @@ -1299,20 +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) over a checked value: a Buffer over all of the - * ArrayBuffer or SharedArrayBuffer that shares its memory, as in Node. The - * calls that reach it have no second argument or a literal encoding name, - * which as a byte offset converts to NaN, offset 0; other second arguments - * take scr_buffer_from_dyn_offset_pooled, which applies the offset. */ -static ScrBytes *scr_buffer_from_storage(const ScrDyn *storage) { - ScrBytes *out = scr_bytes_buffer_view(storage->v.handle.ptr, SCR_BYTES_U8, 0, false, 0); +/* 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); - if (scr_buffer_storage_is(value)) return scr_buffer_from_storage(value); + /* 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); @@ -1356,8 +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. */ - if (scr_buffer_storage_is(value)) return scr_buffer_from_storage(value); + /* 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; @@ -1384,9 +1413,8 @@ ScrBytes *scr_buffer_from_dyn_ref_pooled(const ScrDyn *value, const ScrStr *enco /* 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, as Node's fromArrayBuffer does (undefined and NaN are - * 0, the rest of the buffer is the length, ERR_BUFFER_OUT_OF_BOUNDS past the - * end); other values convert as scr_buffer_from_dyn_ref_pooled with utf8. */ + * 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); @@ -1394,28 +1422,7 @@ ScrBytes *scr_buffer_from_dyn_offset_pooled(const ScrDyn *value, const ScrDyn *s scr_str_release(utf8); return out; } - double offset = 0; - if (second->kind != SCR_DYN_UNDEF) { - if (!scr_dyn_number_coerce_js(second, &offset)) return NULL; - if (isnan(offset)) offset = 0; - } - ScrBytes *storage = value->v.handle.ptr; - ScrBytes *owner = storage->backing ? storage->backing : storage; - 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) { - char msg[96]; - int n = snprintf(msg, sizeof msg, "Start offset %.0f is outside the bounds of the buffer", start); - scr_throw_error_msg(SCR_ERR_RANGE, msg, (size_t)n); - return NULL; - } - ScrBytes *out = scr_bytes_buffer_view(storage, SCR_BYTES_U8, start, false, 0); - if (out) out->is_buffer = true; - return out; + return scr_buffer_from_storage(value, second); } /* new Buffer(number, encoding) — the deprecated ctor's string arm with a diff --git a/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs b/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs index e30b5873e..ff2c59a46 100644 --- a/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs +++ b/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs @@ -23,7 +23,7 @@ if (isMainThread) { 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]) { + 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); From c4d91bf2d9a65e65579fbc87c588beb2eadeb101 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:18:35 -0500 Subject: [PATCH 042/102] Give runtime globals definitions, export only the declared library symbols, and fence the new libFn spellings --- packages/compiler/src/frontend/lowering/surfaces.ts | 1 + packages/runtime/src/scr_json.c | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/compiler/src/frontend/lowering/surfaces.ts b/packages/compiler/src/frontend/lowering/surfaces.ts index adc11e35a..64227ed08 100644 --- a/packages/compiler/src/frontend/lowering/surfaces.ts +++ b/packages/compiler/src/frontend/lowering/surfaces.ts @@ -2263,6 +2263,7 @@ export const AMBIENT_SURFACE_FNS: readonly AmbientSurfaceRow[] = [ "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", }, diff --git a/packages/runtime/src/scr_json.c b/packages/runtime/src/scr_json.c index 549ca9165..cab709bf6 100644 --- a/packages/runtime/src/scr_json.c +++ b/packages/runtime/src/scr_json.c @@ -37,7 +37,7 @@ static SCR_TL ScrDyn *scr_builtin_object_prototype; -const ScrDateClassHooks *scr_date_class_hooks; +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 From 3a879f4f05489d5915a7d49ecdf2501c7643fe6e Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:24:50 -0500 Subject: [PATCH 043/102] Read error constructors as values and destructure workerData in JavaScript --- .../lowering/expressions/object-literals.ts | 25 +++++- .../lowering/expressions/property-access.ts | 20 ++++- .../src/frontend/lowering/lower-stmts.ts | 3 + .../6870-error-constructor-values.js.json | 6 ++ .../6871-worker-data-destructuring.cjs.json | 6 ++ packages/runtime/src/scr_dyn.h | 3 + packages/runtime/src/scr_dyn_invoke.c | 2 + packages/runtime/src/scr_json.c | 79 ++++++++++++++++--- tests/corpus/6870-error-constructor-values.js | 55 +++++++++++++ .../corpus/6871-worker-data-destructuring.cjs | 30 +++++++ .../6870-error-constructor-values.js.json | 1 + .../6871-worker-data-destructuring.cjs.json | 1 + 12 files changed, 216 insertions(+), 15 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6870-error-constructor-values.js.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6871-worker-data-destructuring.cjs.json create mode 100644 tests/corpus/6870-error-constructor-values.js create mode 100644 tests/corpus/6871-worker-data-destructuring.cjs create mode 100644 tests/harness/corpus-costs/6870-error-constructor-values.js.json create mode 100644 tests/harness/corpus-costs/6871-worker-data-destructuring.cjs.json diff --git a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts index 565db0cd8..a17af9b83 100644 --- a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts +++ b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts @@ -35,6 +35,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 +394,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 @@ -3153,6 +3156,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 +3186,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 }; diff --git a/packages/compiler/src/frontend/lowering/expressions/property-access.ts b/packages/compiler/src/frontend/lowering/expressions/property-access.ts index 5cd70d2a5..c55ec29bb 100644 --- a/packages/compiler/src/frontend/lowering/expressions/property-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/property-access.ts @@ -4020,10 +4020,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", @@ -4034,6 +4050,7 @@ const GLOBAL_CONSTRUCTOR_VALUES: ReadonlySet = new Set([ "Promise", "WeakMap", "WeakSet", + ...ERROR_CONSTRUCTOR_VALUES, ]); /** The builtin global functions JavaScript sources read as interned @@ -4176,6 +4193,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); diff --git a/packages/compiler/src/frontend/lowering/lower-stmts.ts b/packages/compiler/src/frontend/lowering/lower-stmts.ts index 7f0854523..31c0e4565 100644 --- a/packages/compiler/src/frontend/lowering/lower-stmts.ts +++ b/packages/compiler/src/frontend/lowering/lower-stmts.ts @@ -3888,6 +3888,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", 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/runtime/src/scr_dyn.h b/packages/runtime/src/scr_dyn.h index 02c4d828f..1310d5fd8 100644 --- a/packages/runtime/src/scr_dyn.h +++ b/packages/runtime/src/scr_dyn.h @@ -725,6 +725,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); diff --git a/packages/runtime/src/scr_dyn_invoke.c b/packages/runtime/src/scr_dyn_invoke.c index 2a010f213..7b375018b 100644 --- a/packages/runtime/src/scr_dyn_invoke.c +++ b/packages/runtime/src/scr_dyn_invoke.c @@ -1913,6 +1913,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_json.c b/packages/runtime/src/scr_json.c index b8f16630b..e308958d7 100644 --- a/packages/runtime/src/scr_json.c +++ b/packages/runtime/src/scr_json.c @@ -1799,6 +1799,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); @@ -7704,6 +7753,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); } @@ -11657,21 +11717,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()); diff --git a/tests/corpus/6870-error-constructor-values.js b/tests/corpus/6870-error-constructor-values.js new file mode 100644 index 000000000..81f5086d2 --- /dev/null +++ b/tests/corpus/6870-error-constructor-values.js @@ -0,0 +1,55 @@ +// 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); 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/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 } From e37b94cc94c673743d9e4eead55a6968b0a145fe Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:29:38 -0500 Subject: [PATCH 044/102] Serialize the self-hosted emitter's IR compactly in its test The pretty-printed IR of the self-hosted LLVM emitter is close to the JavaScript string length limit on CI checkouts, so any growth of the emitter fails the test with "Invalid string length". --- tests/harness/self-hosting-llvm-emitter.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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]; From 931f6d48b5952b71485b20501ead419797ffe9f3 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:35:33 -0500 Subject: [PATCH 045/102] Evaluate the extends expression of classes defined inside functions A class defined inside a function whose base resolves to a known class lowered to its class value alone, so the `extends` expression never ran. Node evaluates it each time the definition runs, so its calls and other effects were missing (`class Local extends select(2) {}` never called select). The class value now follows the heritage expression's evaluation when that expression can have effects: a call, construction, assignment, update, delete, await or yield outside nested functions. Module-scope classes already evaluated it. --- .../src/frontend/lowering/lower-classes.ts | 56 ++++++++++++++++--- .../7183-local-class-heritage-effects.ts.json | 6 ++ .../7183-local-class-heritage-effects.ts | 54 ++++++++++++++++++ .../7183-local-class-heritage-effects.ts.json | 1 + 4 files changed, 110 insertions(+), 7 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7183-local-class-heritage-effects.ts.json create mode 100644 tests/corpus/7183-local-class-heritage-effects.ts create mode 100644 tests/harness/corpus-costs/7183-local-class-heritage-effects.ts.json diff --git a/packages/compiler/src/frontend/lowering/lower-classes.ts b/packages/compiler/src/frontend/lowering/lower-classes.ts index 505b4d709..7e6f80f2c 100644 --- a/packages/compiler/src/frontend/lowering/lower-classes.ts +++ b/packages/compiler/src/frontend/lowering/lower-classes.ts @@ -6142,13 +6142,55 @@ export function lowerClassExpression(lowerer: Lowerer, expr: ts.ClassLikeDeclara loc, }); } - 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, + ); + // 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 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/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/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 } From 144bfb27242bb2fc5c50f6363511f25ea895e94e Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:41:43 -0500 Subject: [PATCH 046/102] Store assignment expressions into module lets declared without an initializer A module `let` declared without an initializer whose type uses its null pointer as the TDZ sentinel (a function, for example) is initialized when its declaration runs, while its slot is still empty. markUninitializedWrites marked the assignment statements that run after the declaration as initializing, but not assignments in expression position. Those ran the pointer check and threw "ReferenceError: Cannot access 'g' before initialization" where Node stores the value, so the deferred-resolver pattern `let resolve!: ...; new Promise((r) => (resolve = r))` failed, as did `(h) => (g = h)` and `const r = (g = h)`. An assignment expression to such a binding now becomes an initializing `assign` whose value a temp holds and yields. Writes that can run before the declaration keep the flag check, so they still throw Node's ReferenceError. --- .../frontend/lowering/cycle-initialization.ts | 30 +++++++-- ...ialized-let-assignment-expressions.ts.json | 6 ++ ...ninitialized-let-assignment-expressions.ts | 63 +++++++++++++++++++ ...ialized-let-assignment-expressions.ts.json | 1 + 4 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7109-uninitialized-let-assignment-expressions.ts.json create mode 100644 tests/corpus/7109-uninitialized-let-assignment-expressions.ts create mode 100644 tests/harness/corpus-costs/7109-uninitialized-let-assignment-expressions.ts.json 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/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/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/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 } From 79684d0ef491b6213c9b80bdba3a673e29650214 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:44:38 -0500 Subject: [PATCH 047/102] Name lowered helpers and closures independently of lowering order Lowering named helpers by the size of their registry at first use (%union.retag.N, %arr.map.N, ...), lifted closures and optional-chain locals by compiler-wide counters (%fnN, chain.N), generic instances by their instance count, and records and unions by creation order (rN, uN). Class expressions, mixin instances, function-local generics, non-exported namespace segments and some module globals carried the byte offset of their declaration. A name therefore depended on which unit lowered first and on the positions of unrelated code. Helpers, instances, records and unions are now named by a hash of the key they are interned by (keyedHelperName). Closures and optional-chain ids are named by their lowering unit, their structural position and a count per key within the unit. Offset-based names use the structural position: the chain of enclosing named declarations (each with its kind, name and ordinal) and the node's ordinal among same-kind nodes inside the nearest one, so an edit outside that declaration leaves the name unchanged. Interfaces and type aliases anchor the positions inside them, and default library files are named by their base name, so tsgo and tsc-ts, which install them in different directories, give the same positions. Recursive record and union placeholders are named by the printed type, the structural position of the declaration and the same for up to three levels of type arguments; a description that two types still share gets a numbered suffix for the later one. A generic class instance keyed by a literal type argument is named by the literal's text or the argument's description instead of its checker type id. Two different keys with the same name throw an InternalCompilerError. The SC6101 performance warning recognizes the new closure names (fn., with _ for a named function expression) and lists the functions that rank alike in source order. The module lists its records and unions by id. The generated program is unchanged apart from these names and that order, and test:lowering-order now fails on any name difference. --- package.json | 2 +- packages/compiler/src/contracts/check.ts | 3 +- .../lowering/array-indexed-mutation.ts | 3 +- .../src/frontend/lowering/array-values.ts | 5 +- .../frontend/lowering/builtins/arguments.ts | 3 +- .../lowering/builtins/child-process-async.ts | 3 +- .../lowering/builtins/child-process-sync.ts | 3 +- .../lowering/builtins/disposable-stack.ts | 3 +- .../frontend/lowering/builtins/filesystem.ts | 3 +- .../src/frontend/lowering/builtins/json.ts | 3 +- .../lowering/builtins/operating-system.ts | 7 +- .../frontend/lowering/builtins/performance.ts | 5 +- .../src/frontend/lowering/builtins/process.ts | 5 +- .../frontend/lowering/builtins/promises.ts | 5 +- .../lowering/builtins/promisify-callback.ts | 3 +- .../frontend/lowering/builtins/text-codecs.ts | 3 +- .../src/frontend/lowering/builtins/timers.ts | 2 +- .../src/frontend/lowering/builtins/url.ts | 7 +- .../src/frontend/lowering/builtins/v8.ts | 3 +- .../src/frontend/lowering/call-arguments.ts | 3 +- .../src/frontend/lowering/call-signatures.ts | 7 +- .../src/frontend/lowering/class-assertions.ts | 5 +- .../src/frontend/lowering/class-unions.ts | 3 +- .../lowering/coercions/function-adapters.ts | 11 +- .../frontend/lowering/coercions/structural.ts | 15 +-- .../src/frontend/lowering/coercions/unions.ts | 15 +-- .../frontend/lowering/collection-ingestion.ts | 3 +- .../lowering/containers/array-callbacks.ts | 25 ++-- .../lowering/containers/array-concat.ts | 3 +- .../lowering/containers/array-construction.ts | 7 +- .../lowering/containers/array-methods.ts | 11 +- .../lowering/containers/array-pipelines.ts | 3 +- .../src/frontend/lowering/containers/bytes.ts | 5 +- .../lowering/containers/callback-arguments.ts | 3 +- .../containers/collection-grouping.ts | 5 +- .../lowering/containers/collection-methods.ts | 15 +-- .../lowering/containers/indexed-objects.ts | 15 +-- .../lowering/containers/iterator-helpers.ts | 7 +- .../lowering/containers/string-and-regexp.ts | 11 +- .../lowering/containers/string-replacement.ts | 3 +- .../src/frontend/lowering/dynamic-tier.ts | 20 +++- .../frontend/lowering/expressions/binary.ts | 3 +- .../lowering/expressions/object-literals.ts | 7 +- .../lowering/expressions/optional-chains.ts | 10 +- .../lowering/expressions/property-access.ts | 3 +- .../lowering/expressions/relational.ts | 5 +- .../frontend/lowering/generic-functions.ts | 17 ++- .../src/frontend/lowering/intern-tables.ts | 7 +- .../frontend/lowering/iterator-adapters.ts | 17 +-- .../frontend/lowering/js-dynamic-objects.ts | 5 +- .../src/frontend/lowering/json-require.ts | 3 +- .../src/frontend/lowering/lifetime-regions.ts | 3 +- .../src/frontend/lowering/lower-assert.ts | 11 +- .../src/frontend/lowering/lower-calls.ts | 49 ++++---- .../src/frontend/lowering/lower-classes.ts | 28 ++++- .../src/frontend/lowering/lower-dgram.ts | 5 +- .../frontend/lowering/lower-event-emitter.ts | 13 +- .../src/frontend/lowering/lower-exprs.ts | 9 +- .../src/frontend/lowering/lower-functions.ts | 2 +- .../src/frontend/lowering/lower-inspect.ts | 7 +- .../src/frontend/lowering/lower-mixins.ts | 3 +- .../src/frontend/lowering/lower-mock.ts | 3 +- .../frontend/lowering/lower-modules.test.ts | 4 +- .../src/frontend/lowering/lower-modules.ts | 15 ++- .../src/frontend/lowering/lower-namespaces.ts | 11 +- .../src/frontend/lowering/lower-server.ts | 13 +- .../src/frontend/lowering/lower-stdlib.ts | 2 +- .../src/frontend/lowering/lower-stream.ts | 15 +-- .../src/frontend/lowering/lower-timers.ts | 7 +- .../src/frontend/lowering/lowerer.test.ts | 30 +++-- .../compiler/src/frontend/lowering/lowerer.ts | 107 ++++++++++++++--- .../src/frontend/lowering/native-ffi.ts | 2 +- .../lowering/object-enumeration-receiver.ts | 3 +- .../src/frontend/lowering/pairs-snapshot.ts | 3 +- .../lowering/promise-executor-adapter.ts | 3 +- .../lowering/require-initialization.ts | 3 +- .../src/frontend/lowering/stable-names.ts | 48 ++++++++ .../src/frontend/lowering/strict-equality.ts | 3 +- .../frontend/lowering/structural-positions.ts | 111 +++++++++++++++++ packages/compiler/src/frontend/ts7/ast.ts | 90 +++++++++++++- .../compiler/src/frontend/type-mapper.test.ts | 2 +- packages/compiler/src/frontend/type-mapper.ts | 93 +++++++++++++-- .../test/array-pipeline-fusion.test.ts | 2 +- .../test/format-float-arguments.test.ts | 2 +- .../test/in-runtime-key-emission.test.ts | 2 +- packages/compiler/test/stable-names.test.ts | 112 ++++++++++++++++++ .../compiler/test/type-mapper-unions.test.ts | 3 +- 87 files changed, 900 insertions(+), 262 deletions(-) create mode 100644 packages/compiler/src/frontend/lowering/stable-names.ts create mode 100644 packages/compiler/src/frontend/lowering/structural-positions.ts create mode 100644 packages/compiler/test/stable-names.test.ts diff --git a/package.json b/package.json index 5cc30d9f8..d1a8e34ae 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", diff --git a/packages/compiler/src/contracts/check.ts b/packages/compiler/src/contracts/check.ts index 5934624bf..c80468961 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(/^%/, ""); } 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/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/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-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/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/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/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/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..75e527aa5 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"; @@ -55,7 +56,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; @@ -557,7 +558,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 })); 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/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..2a77fa85c 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"; @@ -292,7 +293,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 +373,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 +679,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/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/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-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.ts b/packages/compiler/src/frontend/lowering/coercions/structural.ts index 496a29607..5b5e283b3 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"; @@ -253,7 +254,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 +313,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 +342,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 +389,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 +453,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 +493,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 +518,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..7ca69d9ba 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"; @@ -506,7 +507,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 +620,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); @@ -1204,7 +1205,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 +1305,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 +1389,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, @@ -1587,7 +1588,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 +1830,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 +2122,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 +2168,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 +2309,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 +2482,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; @@ -2676,7 +2677,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); diff --git a/packages/compiler/src/frontend/lowering/containers/array-concat.ts b/packages/compiler/src/frontend/lowering/containers/array-concat.ts index 4f6e4ca43..b4e285ee9 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 }, 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..180f40435 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 }); } diff --git a/packages/compiler/src/frontend/lowering/containers/bytes.ts b/packages/compiler/src/frontend/lowering/containers/bytes.ts index 9d8def80e..8a4364754 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"; @@ -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), @@ -270,7 +271,7 @@ function bytesCallbackHelper( const key = `bytes.${method}:${bytesT.elem}:${typeKey(resultT)}:${typeKey(fnRet)}:${arity}:${hasInit ? "init" : ""}`; 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"; diff --git a/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts b/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts index 18754f088..f39c8e86c 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"; @@ -285,7 +286,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..d3169ec5c 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"; @@ -232,7 +233,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 +349,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 +520,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 +694,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 +746,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)); } @@ -1357,7 +1358,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 +1458,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/indexed-objects.ts b/packages/compiler/src/frontend/lowering/containers/indexed-objects.ts index efc173ffc..b3faf649e 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 }; @@ -1474,7 +1475,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); @@ -1805,7 +1806,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 540518284..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 }); 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 38865093f..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}`, @@ -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}`, 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/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/binary.ts b/packages/compiler/src/frontend/lowering/expressions/binary.ts index fafbbf695..7e449f12b 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({ diff --git a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts index a17af9b83..a2f399e34 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"; @@ -409,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 }, }); @@ -464,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 }, }); @@ -2959,7 +2960,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); 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 ea075c528..d66110950 100644 --- a/packages/compiler/src/frontend/lowering/expressions/property-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/property-access.ts @@ -1,4 +1,5 @@ /* Property reads (`a.b`): lowerExprInner's property-access branch, intrinsic and union properties, field reads and targets, and match-group reads. */ +import { keyedHelperName } from "../stable-names.js"; import { staticallySelected } from "../static-typeof.js"; import * as ts from "../../ts7/adapter.js"; import { lowerHistogramProperty } from "../builtins/performance.js"; @@ -2793,7 +2794,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 }]; diff --git a/packages/compiler/src/frontend/lowering/expressions/relational.ts b/packages/compiler/src/frontend/lowering/expressions/relational.ts index 088b45cff..836391835 100644 --- a/packages/compiler/src/frontend/lowering/expressions/relational.ts +++ b/packages/compiler/src/frontend/lowering/expressions/relational.ts @@ -1,4 +1,5 @@ /* instanceof and in, including private-name and runtime-key in. */ +import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { builtinClassInstanceOfAny, builtinClassKind } from "../builtins/builtin-class-dyn.js"; import { @@ -647,7 +648,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[] = []; @@ -1847,7 +1848,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 }; diff --git a/packages/compiler/src/frontend/lowering/generic-functions.ts b/packages/compiler/src/frontend/lowering/generic-functions.ts index e843b6909..1fff26585 100644 --- a/packages/compiler/src/frontend/lowering/generic-functions.ts +++ b/packages/compiler/src/frontend/lowering/generic-functions.ts @@ -1,4 +1,6 @@ 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"; @@ -233,7 +235,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(), }); @@ -774,7 +779,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, @@ -2252,7 +2257,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 @@ -2440,7 +2445,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(), @@ -2536,7 +2541,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(), @@ -2682,7 +2687,7 @@ 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, 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/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/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-calls.ts b/packages/compiler/src/frontend/lowering/lower-calls.ts index c503f0c9c..c5e34306c 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"; @@ -2095,7 +2096,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({ @@ -2204,7 +2205,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; @@ -2373,7 +2374,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[] = []; @@ -3235,7 +3236,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 = { @@ -3280,7 +3281,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({ @@ -4707,7 +4708,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({ @@ -5394,7 +5395,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 }, @@ -5575,7 +5576,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; @@ -5672,7 +5673,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] : []), @@ -5921,7 +5922,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], @@ -6016,7 +6017,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], @@ -6119,7 +6120,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], @@ -6222,7 +6223,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], @@ -6352,7 +6353,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; @@ -6589,7 +6590,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); @@ -6835,7 +6836,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); @@ -6905,7 +6906,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 }; @@ -6990,7 +6991,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 }; @@ -7058,7 +7059,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)!; @@ -8515,7 +8516,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 }; @@ -9151,7 +9152,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); @@ -10080,7 +10081,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[] => { @@ -10173,7 +10174,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. @@ -10367,7 +10368,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 }; diff --git a/packages/compiler/src/frontend/lowering/lower-classes.ts b/packages/compiler/src/frontend/lowering/lower-classes.ts index 7e6f80f2c..4ea4583f6 100644 --- a/packages/compiler/src/frontend/lowering/lower-classes.ts +++ b/packages/compiler/src/frontend/lowering/lower-classes.ts @@ -1,3 +1,4 @@ +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 +85,7 @@ import { } from "./call-signatures.js"; import { omittedArgFor } from "./call-arguments.js"; import { + checkerTypeDescription, isGenericCallableMemberType, jsOpenObjectType, typeKey, @@ -4664,7 +4666,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(); @@ -7954,7 +7974,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 }; @@ -8068,7 +8088,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 }; @@ -10576,7 +10596,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..aa90fc7c7 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({ @@ -891,7 +892,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..f105af786 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 }, @@ -2359,7 +2360,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 +2425,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..ba96bea8c 100644 --- a/packages/compiler/src/frontend/lowering/lower-exprs.ts +++ b/packages/compiler/src/frontend/lowering/lower-exprs.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { lowerWebAssemblyValue, refuseWebAssemblyUse } from "./builtins/webassembly.js"; import { dynUndefinedExpr, nodeThrowExpr, numLit, strLit, varRef } from "../../ir/build.js"; import { InternalCompilerError } from "../../errors.js"; @@ -2274,7 +2275,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 +2304,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); } diff --git a/packages/compiler/src/frontend/lowering/lower-functions.ts b/packages/compiler/src/frontend/lowering/lower-functions.ts index cd8dc31d1..653c0d837 100644 --- a/packages/compiler/src/frontend/lowering/lower-functions.ts +++ b/packages/compiler/src/frontend/lowering/lower-functions.ts @@ -270,7 +270,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 = diff --git a/packages/compiler/src/frontend/lowering/lower-inspect.ts b/packages/compiler/src/frontend/lowering/lower-inspect.ts index 4be5d0b7e..1979b43aa 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, @@ -268,7 +269,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); @@ -1145,7 +1146,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); @@ -2074,7 +2075,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..0b99e88d3 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"; @@ -1074,8 +1075,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 +1684,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 +1761,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 diff --git a/packages/compiler/src/frontend/lowering/lower-namespaces.ts b/packages/compiler/src/frontend/lowering/lower-namespaces.ts index dca835d77..19123dae3 100644 --- a/packages/compiler/src/frontend/lowering/lower-namespaces.ts +++ b/packages/compiler/src/frontend/lowering/lower-namespaces.ts @@ -36,6 +36,7 @@ * 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 type { Lowerer } from "./lowerer.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 diff --git a/packages/compiler/src/frontend/lowering/lower-server.ts b/packages/compiler/src/frontend/lowering/lower-server.ts index 058d7874a..94d49d8b3 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`; @@ -3583,7 +3584,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 +4425,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 = [ @@ -8009,7 +8010,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-stream.ts b/packages/compiler/src/frontend/lowering/lower-stream.ts index 33c842f6d..d6f89dc11 100644 --- a/packages/compiler/src/frontend/lowering/lower-stream.ts +++ b/packages/compiler/src/frontend/lowering/lower-stream.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { nodeThrowExpr, boolLit, numLit, strLit } from "../../ir/build.js"; import { isValueStream, valueStreamOf } from "./builtins/hash-stream.js"; import { InternalCompilerError } from "../../errors.js"; @@ -315,7 +316,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 { @@ -1148,7 +1149,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 { @@ -1694,7 +1695,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, @@ -1783,7 +1784,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); @@ -1944,7 +1945,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 = { @@ -3128,7 +3129,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, @@ -3155,7 +3156,7 @@ function pipelineAbortHelper(lowerer: Lowerer, ac: IrExpr, loc: SrcLoc): IrExpr let name = lowerer.valueHelpers.get(key); const abortT = funcOf([], 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); 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 ac68fc972..d8b86b59a 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, @@ -1004,6 +1006,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, @@ -2807,6 +2814,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(); @@ -2943,7 +2952,6 @@ 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(); @@ -3173,7 +3181,53 @@ 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. */ + /** Default library files are named 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)}` + : 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(); @@ -3526,6 +3580,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, @@ -3818,11 +3873,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]!; @@ -7381,7 +7436,10 @@ export class Lowerer { } 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); } } @@ -7394,7 +7452,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()); } @@ -7436,7 +7497,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; } @@ -7446,7 +7509,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; @@ -8000,7 +8066,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(); @@ -8027,7 +8095,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)), ), ), ); @@ -8060,9 +8128,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; @@ -8090,7 +8161,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)!), + ), ), ), ); @@ -8116,7 +8189,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(); @@ -13504,7 +13579,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/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/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/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/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 af88a7448..9abd5a0b0 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"; @@ -262,6 +263,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 @@ -280,7 +283,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[] }`): @@ -400,11 +403,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); @@ -473,7 +477,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, @@ -551,6 +555,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. @@ -558,10 +614,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` @@ -577,11 +635,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); @@ -631,7 +690,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); @@ -1131,6 +1190,10 @@ export interface TypeMapperCtx { * 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. */ @@ -4672,7 +4735,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; @@ -7016,7 +7082,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; 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/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/stable-names.test.ts b/packages/compiler/test/stable-names.test.ts new file mode 100644 index 000000000..720472556 --- /dev/null +++ b/packages/compiler/test/stable-names.test.ts @@ -0,0 +1,112 @@ +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); +}); 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"], ]); From ebbc6c1831827649525ff5b3aff5b875a6062a80 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 03:56:15 -0500 Subject: [PATCH 048/102] Fix recursive JSON unions and primitive constructors as array callbacks --- .../lowering/containers/callback-arguments.ts | 59 +++++++++++++ .../lowering/expressions/array-literals.ts | 15 ++++ .../lowering/expressions/identifiers.ts | 51 ++++++++++-- .../src/frontend/lowering/lower-calls.ts | 34 ++++++++ .../src/frontend/lowering/lower-exprs.ts | 8 +- .../6826-map-primitive-constructors.ts.json | 6 ++ ...27-recursive-union-nested-literals.ts.json | 6 ++ ...828-recursive-union-object-walkers.ts.json | 6 ++ .../corpus/6826-map-primitive-constructors.ts | 25 ++++++ .../6827-recursive-union-nested-literals.ts | 29 +++++++ .../6828-recursive-union-object-walkers.ts | 83 +++++++++++++++++++ .../6826-map-primitive-constructors.ts.json | 1 + ...27-recursive-union-nested-literals.ts.json | 1 + ...828-recursive-union-object-walkers.ts.json | 1 + 14 files changed, 316 insertions(+), 9 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6826-map-primitive-constructors.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6827-recursive-union-nested-literals.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6828-recursive-union-object-walkers.ts.json create mode 100644 tests/corpus/6826-map-primitive-constructors.ts create mode 100644 tests/corpus/6827-recursive-union-nested-literals.ts create mode 100644 tests/corpus/6828-recursive-union-object-walkers.ts create mode 100644 tests/harness/corpus-costs/6826-map-primitive-constructors.ts.json create mode 100644 tests/harness/corpus-costs/6827-recursive-union-nested-literals.ts.json create mode 100644 tests/harness/corpus-costs/6828-recursive-union-object-walkers.ts.json diff --git a/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts b/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts index f39c8e86c..9db04e95b 100644 --- a/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts +++ b/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts @@ -6,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, @@ -69,6 +71,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 @@ -274,6 +290,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. */ diff --git a/packages/compiler/src/frontend/lowering/expressions/array-literals.ts b/packages/compiler/src/frontend/lowering/expressions/array-literals.ts index 00eae1041..8f119504c 100644 --- a/packages/compiler/src/frontend/lowering/expressions/array-literals.ts +++ b/packages/compiler/src/frontend/lowering/expressions/array-literals.ts @@ -184,6 +184,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/identifiers.ts b/packages/compiler/src/frontend/lowering/expressions/identifiers.ts index 16cca3b13..1f74cea42 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, @@ -226,7 +227,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); } @@ -938,10 +942,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 ( @@ -962,7 +999,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/lower-calls.ts b/packages/compiler/src/frontend/lowering/lower-calls.ts index c5e34306c..46f98871e 100644 --- a/packages/compiler/src/frontend/lowering/lower-calls.ts +++ b/packages/compiler/src/frontend/lowering/lower-calls.ts @@ -173,6 +173,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"; @@ -4343,7 +4344,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 @@ -4361,6 +4380,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 { diff --git a/packages/compiler/src/frontend/lowering/lower-exprs.ts b/packages/compiler/src/frontend/lowering/lower-exprs.ts index ba96bea8c..b5acaf9e6 100644 --- a/packages/compiler/src/frontend/lowering/lower-exprs.ts +++ b/packages/compiler/src/frontend/lowering/lower-exprs.ts @@ -3057,8 +3057,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( @@ -3081,7 +3083,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/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/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/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 } From b99094543f67f874867a3eece221c8b2fde463e7 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 04:04:16 -0500 Subject: [PATCH 049/102] Revert "Read error constructors as values and destructure workerData in JavaScript" This reverts #1776, which made main CI fail. --- .../lowering/expressions/object-literals.ts | 25 +----- .../lowering/expressions/property-access.ts | 20 +---- .../src/frontend/lowering/lower-stmts.ts | 3 - .../6870-error-constructor-values.js.json | 6 -- .../6871-worker-data-destructuring.cjs.json | 6 -- packages/runtime/src/scr_dyn.h | 3 - packages/runtime/src/scr_dyn_invoke.c | 2 - packages/runtime/src/scr_json.c | 79 +++---------------- tests/corpus/6870-error-constructor-values.js | 55 ------------- .../corpus/6871-worker-data-destructuring.cjs | 30 ------- .../6870-error-constructor-values.js.json | 1 - .../6871-worker-data-destructuring.cjs.json | 1 - 12 files changed, 15 insertions(+), 216 deletions(-) delete mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6870-error-constructor-values.js.json delete mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6871-worker-data-destructuring.cjs.json delete mode 100644 tests/corpus/6870-error-constructor-values.js delete mode 100644 tests/corpus/6871-worker-data-destructuring.cjs delete mode 100644 tests/harness/corpus-costs/6870-error-constructor-values.js.json delete mode 100644 tests/harness/corpus-costs/6871-worker-data-destructuring.cjs.json diff --git a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts index a2f399e34..93bf43e95 100644 --- a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts +++ b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts @@ -36,7 +36,6 @@ 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, @@ -395,11 +394,9 @@ export function lowerDynObjectLiteral( const lowerValue = (): IrExpr => ts.isMethodDeclaration(prop) ? lowerer.lowerLambda(prop, true) - : ts.isShorthandPropertyAssignment(prop) && shorthandBuiltinValue(lowerer, prop) - ? shorthandBuiltinValue(lowerer, prop)! - : !boxValue && ts.isObjectLiteralExpression(valueExpr) - ? lowerer.lowerExprExpecting(valueExpr, DYN) - : lowerer.lowerExpr(valueExpr as ts.Expression); + : !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 @@ -3157,20 +3154,6 @@ 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, @@ -3187,8 +3170,6 @@ 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 }; diff --git a/packages/compiler/src/frontend/lowering/expressions/property-access.ts b/packages/compiler/src/frontend/lowering/expressions/property-access.ts index d66110950..06186c4dc 100644 --- a/packages/compiler/src/frontend/lowering/expressions/property-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/property-access.ts @@ -4024,26 +4024,10 @@ 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` and `err.constructor === TypeError` are - * exact identity tests, and `err.constructor.name` is the constructor's - * name. */ + * so `o.constructor === Object` is an exact identity test. */ const GLOBAL_CONSTRUCTOR_VALUES: ReadonlySet = new Set([ "Object", "Function", @@ -4054,7 +4038,6 @@ const GLOBAL_CONSTRUCTOR_VALUES: ReadonlySet = new Set([ "Promise", "WeakMap", "WeakSet", - ...ERROR_CONSTRUCTOR_VALUES, ]); /** The builtin global functions JavaScript sources read as interned @@ -4197,7 +4180,6 @@ 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); diff --git a/packages/compiler/src/frontend/lowering/lower-stmts.ts b/packages/compiler/src/frontend/lowering/lower-stmts.ts index 7dc0b87cc..84c54307a 100644 --- a/packages/compiler/src/frontend/lowering/lower-stmts.ts +++ b/packages/compiler/src/frontend/lowering/lower-stmts.ts @@ -3889,9 +3889,6 @@ 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", 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 deleted file mode 100644 index a2f0e02ea..000000000 --- a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6870-error-constructor-values.js.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "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 deleted file mode 100644 index b610a5878..000000000 --- a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6871-worker-data-destructuring.cjs.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "order": [ - "/tests/corpus/6871-worker-data-destructuring.cjs" - ], - "diags": [] -} diff --git a/packages/runtime/src/scr_dyn.h b/packages/runtime/src/scr_dyn.h index 1d8a7f1d4..cafc8d07e 100644 --- a/packages/runtime/src/scr_dyn.h +++ b/packages/runtime/src/scr_dyn.h @@ -725,9 +725,6 @@ 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); diff --git a/packages/runtime/src/scr_dyn_invoke.c b/packages/runtime/src/scr_dyn_invoke.c index 7b375018b..2a010f213 100644 --- a/packages/runtime/src/scr_dyn_invoke.c +++ b/packages/runtime/src/scr_dyn_invoke.c @@ -1913,8 +1913,6 @@ 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_json.c b/packages/runtime/src/scr_json.c index 57846b041..194ade887 100644 --- a/packages/runtime/src/scr_json.c +++ b/packages/runtime/src/scr_json.c @@ -1801,55 +1801,6 @@ 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); @@ -7756,17 +7707,6 @@ 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); } @@ -11720,18 +11660,21 @@ 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) { - /* 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", + static const char *const tokens[] = { + "[builtin Error]", "[builtin TypeError]", + "[builtin RangeError]", "[builtin SyntaxError]", + NULL, "[builtin ReferenceError]", "[builtin EvalError]", "[builtin URIError]", + "[builtin 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 names / sizeof names[0]; kind++) { - if (!names[kind]) continue; + for (size_t kind = 0; vt && kind < sizeof tokens / sizeof tokens[0]; kind++) { + if (!tokens[kind]) continue; if (vt != &scr_error_vts[kind]) continue; - return scr_dyn_error_constructor(names[kind]); + 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_retain(scr_dyn_undefined()); diff --git a/tests/corpus/6870-error-constructor-values.js b/tests/corpus/6870-error-constructor-values.js deleted file mode 100644 index 81f5086d2..000000000 --- a/tests/corpus/6870-error-constructor-values.js +++ /dev/null @@ -1,55 +0,0 @@ -// 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); diff --git a/tests/corpus/6871-worker-data-destructuring.cjs b/tests/corpus/6871-worker-data-destructuring.cjs deleted file mode 100644 index 63ae789bd..000000000 --- a/tests/corpus/6871-worker-data-destructuring.cjs +++ /dev/null @@ -1,30 +0,0 @@ -// 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/harness/corpus-costs/6870-error-constructor-values.js.json b/tests/harness/corpus-costs/6870-error-constructor-values.js.json deleted file mode 100644 index c608ce33a..000000000 --- a/tests/harness/corpus-costs/6870-error-constructor-values.js.json +++ /dev/null @@ -1 +0,0 @@ -{ "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 deleted file mode 100644 index d6c0cb9ee..000000000 --- a/tests/harness/corpus-costs/6871-worker-data-destructuring.cjs.json +++ /dev/null @@ -1 +0,0 @@ -{ "plain": 1300, "san": 3490 } From 4919576d097984a23f6005cf52d9fb33bda2b6a3 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 04:16:06 -0500 Subject: [PATCH 050/102] Filter regex start positions by their leading character sets --- .../src/backend/llvm/regex-matchers.test.ts | 19 ++ .../src/backend/llvm/regex-matchers.ts | 163 +++++++++++++++++- .../corpus/6872-regex-start-filter.ts.json | 6 + tests/corpus/6872-regex-start-filter.ts | 79 +++++++++ .../6872-regex-start-filter.ts.json | 1 + 5 files changed, 262 insertions(+), 6 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6872-regex-start-filter.ts.json create mode 100644 tests/corpus/6872-regex-start-filter.ts create mode 100644 tests/harness/corpus-costs/6872-regex-start-filter.ts.json 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..77f8a06eb 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"), @@ -743,10 +885,16 @@ class RxGen { 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`); + if (reach === 0) { + this.line(`${fits} = icmp sle i32 ${i16}, %len`); + } else { + const last = this.tmp(); + this.line(`${last} = add i32 ${i16}, ${reach}`); + this.line(`${fits} = icmp sle i32 ${last}, %len`); + } 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}`); @@ -1769,7 +1917,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/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/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/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 } From 67247dd26bb8af65349e69c73ffa80603254632c Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 04:21:55 -0500 Subject: [PATCH 051/102] Support objectMode streams with any value as a chunk Readable, Writable, Duplex, Transform and PassThrough take the objectMode option, and a Duplex, Transform or PassThrough the readableObjectMode and writableObjectMode options, as true or false literals in an options object literal or in an options value. An object-mode side holds any value that converts to a checked-dynamic value: push, unshift, write, end, pipe, pipeline, for await, 'data' listeners, Readable.from and the transform callback carry values in TypeScript and JavaScript, and constructor-function streams and options held in variables do the same. The object-mode high-water mark counts values and defaults to 16. A readable buffer that mixes strings, Buffers and other values holds them all, and push(undefined) and other values on a byte-mode stream report ERR_INVALID_ARG_TYPE through 'error', as in Node. In typed code a write or transform callback, or a _write or _transform method, may declare its chunk with any such type, which converts when the callback runs. Writes pass the encoding argument to _write and _transform as Node does: undefined when absent, null when a callback took its place, otherwise the value unchanged. A parameter declared string | null | undefined receives that value and one declared string receives "" for undefined and null. write(chunk, encoding) on a byte-mode stream encodes a string chunk with any known encoding and throws ERR_UNKNOWN_ENCODING for an unknown one. Readable.from takes typed Maps and Sets of any such value, and arrays that mix strings and Buffers. for await over a readable-only stream that will emit 'close' now ends after 'close', as Node's eos does. Buffered writes that complete inside clearBuffer run their callbacks in order, and 'finish' waits for a deferred afterWrite that carries a callback, as Node's pendingcb does, unless a _final callback schedules it. The 'data' listener adapters take three slots and write and transform callbacks read their chunk and encoding through runtime accessors, so RUNTIME_ABI_VERSION is now 26. --- .../builtin-apis/streams-and-readline.mdx | 10 +- .../limitations/builtin-function-values.mdx | 2 +- packages/cli/test/native-link-info.test.ts | 4 +- .../ambient/scriptc-node-fallback.d.ts | 85 +- .../src/backend/llvm/expr-stream-callbacks.ts | 217 +++- .../compiler/src/backend/llvm/lib-process.ts | 37 +- .../compiler/src/backend/llvm/lib-shared.ts | 5 + .../compiler/src/backend/llvm/lib-stream.ts | 52 +- packages/compiler/src/backend/runtime-abi.ts | 4 +- .../src/backend/runtime-pack-targets.test.ts | 2 +- .../compiler/src/backend/runtime-pack.test.ts | 2 +- .../lowering/lower-async-iteration.ts | 4 +- .../frontend/lowering/lower-event-emitter.ts | 51 +- .../src/frontend/lowering/lower-stream.ts | 323 ++++-- packages/compiler/src/ir/builtin-effects.ts | 2 + .../compiler/src/ir/builtin-signatures.ts | 14 +- packages/compiler/src/ir/runtime-features.ts | 2 + packages/compiler/src/ir/validate.ts | 9 +- .../test/native-codegen-integration.test.ts | 4 +- .../corpus/7240-objectmode-streams.ts.json | 6 + .../corpus/7241-objectmode-streams.mjs.json | 6 + .../corpus/7242-objectmode-dynamic.cjs.json | 6 + .../7243-for-await-close-order.mjs.json | 6 + .../corpus/7244-objectmode-subclasses.ts.json | 6 + .../7245-writable-callback-order.mjs.json | 6 + .../runtime-darwin-arm64/scripts/build.mjs | 2 +- .../runtime-pack-common/scripts/build.mjs | 2 +- packages/runtime/src/scr_console.c | 2 +- packages/runtime/src/scr_core.h | 2 +- packages/runtime/src/scr_dyn_builtin_stream.c | 58 +- packages/runtime/src/scr_stream.c | 951 +++++++++++++----- packages/runtime/src/scr_stream.h | 25 + packages/runtime/src/scr_stream_ops.c | 12 +- tests/corpus/7240-objectmode-streams.ts | 130 +++ tests/corpus/7241-objectmode-streams.mjs | 148 +++ tests/corpus/7242-objectmode-dynamic.cjs | 93 ++ tests/corpus/7243-for-await-close-order.mjs | 58 ++ tests/corpus/7244-objectmode-subclasses.ts | 79 ++ tests/corpus/7245-writable-callback-order.mjs | 71 ++ .../7240-objectmode-streams.ts.json | 1 + .../7241-objectmode-streams.mjs.json | 1 + .../7242-objectmode-dynamic.cjs.json | 1 + .../7243-for-await-close-order.mjs.json | 1 + .../7244-objectmode-subclasses.ts.json | 1 + .../7245-writable-callback-order.mjs.json | 1 + .../self-hosting-native-toolchain.test.ts | 2 +- 46 files changed, 2064 insertions(+), 442 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7240-objectmode-streams.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7241-objectmode-streams.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7242-objectmode-dynamic.cjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7243-for-await-close-order.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7244-objectmode-subclasses.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7245-writable-callback-order.mjs.json create mode 100644 tests/corpus/7240-objectmode-streams.ts create mode 100644 tests/corpus/7241-objectmode-streams.mjs create mode 100644 tests/corpus/7242-objectmode-dynamic.cjs create mode 100644 tests/corpus/7243-for-await-close-order.mjs create mode 100644 tests/corpus/7244-objectmode-subclasses.ts create mode 100644 tests/corpus/7245-writable-callback-order.mjs create mode 100644 tests/harness/corpus-costs/7240-objectmode-streams.ts.json create mode 100644 tests/harness/corpus-costs/7241-objectmode-streams.mjs.json create mode 100644 tests/harness/corpus-costs/7242-objectmode-dynamic.cjs.json create mode 100644 tests/harness/corpus-costs/7243-for-await-close-order.mjs.json create mode 100644 tests/harness/corpus-costs/7244-objectmode-subclasses.ts.json create mode 100644 tests/harness/corpus-costs/7245-writable-callback-order.mjs.json diff --git a/docs/content/limitations/builtin-apis/streams-and-readline.mdx b/docs/content/limitations/builtin-apis/streams-and-readline.mdx index 4e0832c26..8461cc71c 100644 --- a/docs/content/limitations/builtin-apis/streams-and-readline.mdx +++ b/docs/content/limitations/builtin-apis/streams-and-readline.mdx @@ -1,13 +1,17 @@ -- **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, 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. + 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 its Buffers; another value throws a not-supported error (read such values with `'data'` listeners, `for await`, or `pipe`). + `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 })`), 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. diff --git a/docs/content/limitations/builtin-function-values.mdx b/docs/content/limitations/builtin-function-values.mdx index 37ed8eb48..c1bab6680 100644 --- a/docs/content/limitations/builtin-function-values.mdx +++ b/docs/content/limitations/builtin-function-values.mdx @@ -28,7 +28,7 @@ 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 (`decodeStrings: false`, `signal`, and others) are refused here too, as are `_writev`, `_construct`, symbol event names, `listeners()`, `rawListeners()`, `wrap()`, strings written to a byte-mode stream in encodings other than UTF-8, and pipes into a destination that overrides `write()` or `end()`. 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/packages/cli/test/native-link-info.test.ts b/packages/cli/test/native-link-info.test.ts index 56ca46878..630ef7173 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: 25, marker: "scr_runtime_abi_v25" }, + runtime_abi: { version: 26, marker: "scr_runtime_abi_v26" }, 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_v25"); + expect(error?.stderr).toContain("scr_runtime_abi_v26"); }); }); diff --git a/packages/compiler/ambient/scriptc-node-fallback.d.ts b/packages/compiler/ambient/scriptc-node-fallback.d.ts index 936283d40..0d6c3eb1e 100644 --- a/packages/compiler/ambient/scriptc-node-fallback.d.ts +++ b/packages/compiler/ambient/scriptc-node-fallback.d.ts @@ -6710,11 +6710,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. */ @@ -6820,6 +6819,51 @@ 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; + /* The operators' options: concurrency and highWaterMark bound map's * in-flight callbacks and queued results. */ interface ArrayOptions { @@ -6839,7 +6883,10 @@ declare module "stream" { [Symbol.asyncIterator](): AsyncIterableIterator; iterator(options?: { destroyOnReturn?: boolean }): AsyncIterableIterator; 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; + unshift(chunk: any, encoding?: string): void; read(size?: number): Buffer | null; pause(): this; resume(): this; @@ -6946,6 +6993,7 @@ declare module "stream" { } class Writable extends EventEmitter { + constructor(opts: ObjectWritableOptions); constructor(opts?: WritableOptions); /* The underscore-method surface (see Readable). */ _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; @@ -6961,9 +7009,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; @@ -7013,6 +7071,7 @@ 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 { + constructor(opts: ObjectDuplexOptions); constructor(opts?: DuplexOptions); /* The underscore-method surface (see Readable). */ _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; @@ -7027,9 +7086,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; @@ -7101,16 +7170,18 @@ declare module "stream" { } class Transform extends Duplex { + constructor(opts: ObjectTransformOptions); 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?: TransformOptions); } diff --git a/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts b/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts index 9be757a20..17507e128 100644 --- a/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts +++ b/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts @@ -15,23 +15,55 @@ export function streamDataAdapter( sym = `sc_ee_dad_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); 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 +89,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 +105,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); @@ -114,11 +146,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,7 +173,25 @@ 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); @@ -164,12 +223,25 @@ 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" @@ -179,10 +251,16 @@ export function streamDoneFnFor( : 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" : ""})`); + ? 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 +268,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 +312,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,7 +331,8 @@ 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); return sym; @@ -611,18 +698,14 @@ export function streamCbThunkFor( : 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 @@ -673,15 +756,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 | 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 c08d7b720..032d44d50 100644 --- a/packages/compiler/src/backend/llvm/lib-shared.ts +++ b/packages/compiler/src/backend/llvm/lib-shared.ts @@ -1113,10 +1113,13 @@ export const LIB_FN_SYMS: Record = { "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.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", @@ -1667,6 +1670,7 @@ export const USES_TIMERS_LIB_FNS = new Set([ "readable.pushDyn", "readable.unshift", "readable.unshiftStr", + "readable.unshiftDyn", "readable.read", "readable.readDyn", "readable.setEncoding", @@ -1698,6 +1702,7 @@ export const USES_TIMERS_LIB_FNS = new Set([ "console.write", "writable.writeU", "writable.writeDyn", + "writable.writeEnc", "writable.end", "writable.uncork", "stream.destroy", diff --git a/packages/compiler/src/backend/llvm/lib-stream.ts b/packages/compiler/src/backend/llvm/lib-stream.ts index 5d198d306..6d6c6f99c 100644 --- a/packages/compiler/src/backend/llvm/lib-stream.ts +++ b/packages/compiler/src/backend/llvm/lib-stream.ts @@ -419,10 +419,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"); @@ -432,19 +456,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(); @@ -771,3 +803,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/runtime-abi.ts b/packages/compiler/src/backend/runtime-abi.ts index f02510338..703e8fe48 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 = 25 as const; -export const RUNTIME_ABI_MARKER = "scr_runtime_abi_v25" as const; +export const RUNTIME_ABI_VERSION = 26 as const; +export const RUNTIME_ABI_MARKER = "scr_runtime_abi_v26" 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 8bdbc8492..a49c36ac3 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: 25, marker: "scr_runtime_abi_v25" }, + runtime_abi: { version: 26, marker: "scr_runtime_abi_v26" }, compiler: { command: "fixture", identity: "fixture", target: target.llvmTriple }, macros: { executable: [], excluded: ["SCR_LIB"], sanitizer: "external-toolchain-required" }, flavors: { diff --git a/packages/compiler/src/backend/runtime-pack.test.ts b/packages/compiler/src/backend/runtime-pack.test.ts index a3ac9fe5d..53afafe16 100644 --- a/packages/compiler/src/backend/runtime-pack.test.ts +++ b/packages/compiler/src/backend/runtime-pack.test.ts @@ -124,7 +124,7 @@ async function fixture(target: NativeTargetSpec = MACOS_ARM64_TARGET) { object_format: target.objectFormat, minimum_os: target.minimumOs, }, - runtime_abi: { version: 25, marker: "scr_runtime_abi_v25" }, + runtime_abi: { version: 26, marker: "scr_runtime_abi_v26" }, compiler: { command: "clang", identity: "fixture clang", diff --git a/packages/compiler/src/frontend/lowering/lower-async-iteration.ts b/packages/compiler/src/frontend/lowering/lower-async-iteration.ts index 0e48f2040..5b427a750 100644 --- a/packages/compiler/src/frontend/lowering/lower-async-iteration.ts +++ b/packages/compiler/src/frontend/lowering/lower-async-iteration.ts @@ -428,7 +428,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-event-emitter.ts b/packages/compiler/src/frontend/lowering/lower-event-emitter.ts index f105af786..f44a3d6d8 100644 --- a/packages/compiler/src/frontend/lowering/lower-event-emitter.ts +++ b/packages/compiler/src/frontend/lowering/lower-event-emitter.ts @@ -1458,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]!); @@ -1500,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) { @@ -1654,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) { @@ -1665,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", diff --git a/packages/compiler/src/frontend/lowering/lower-stream.ts b/packages/compiler/src/frontend/lowering/lower-stream.ts index d6f89dc11..14062051f 100644 --- a/packages/compiler/src/frontend/lowering/lower-stream.ts +++ b/packages/compiler/src/frontend/lowering/lower-stream.ts @@ -308,6 +308,21 @@ 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 the Buffer), or throws a TypeError there; an encoding of another + // type (`string | null | undefined`) from the encoding argument's. + if ( + (i === 0 || i === 1) && + (which === "write" || which === "transform") && + 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]!)}'`, @@ -404,11 +419,52 @@ 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; /** 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; +} + /** 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 @@ -657,6 +713,8 @@ function parseStreamOptions( badEncoding: null, pushEncoding: null, signal: null, + readableObject: false, + writableObject: false, flags: 0, cbs: [], }; @@ -669,6 +727,18 @@ 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; + 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 ?? []) { @@ -715,7 +785,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 @@ -776,16 +846,9 @@ 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": { if (value.kind === ts.SyntaxKind.TrueKeyword) break; // Node's default lowerer.noLowering( @@ -942,6 +1005,8 @@ function streamCtorArgs( badEncoding: string | null; pushEncoding: string | null; signal: IrExpr | null; + readableObject: boolean; + writableObject: boolean; } { const shape = streamCtorShape(cls); const o = parseStreamOptions( @@ -971,6 +1036,8 @@ function streamCtorArgs( badEncoding: o.badEncoding, pushEncoding: o.pushEncoding, signal: o.signal, + readableObject: o.readableObject, + writableObject: o.writableObject, }; } @@ -1015,6 +1082,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). @@ -1133,6 +1211,22 @@ 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. + if ( + i === 1 && + (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; + } // 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. @@ -1140,6 +1234,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 the Buffer), or throws a TypeError there. + if ( + i === 0 && + (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, @@ -1301,6 +1411,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", @@ -1602,7 +1725,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); @@ -1623,20 +1756,24 @@ export function lowerStreamStaticCall( lowerer.noLowering( `Readable.from 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 @@ -3587,14 +3724,6 @@ function lowerStreamOperator( 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 { @@ -3925,10 +4054,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", ); }; @@ -3973,11 +4116,17 @@ 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 = lowerer.lowerExpr(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); if (kind === "null") { @@ -4237,9 +4386,54 @@ 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 = lowerer.lowerExpr(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); + 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 = lowerer.lowerExpr(access.expression); const chunk = lowerer.lowerExprExpecting(args[0]!, DYN); return { kind: "libCall", fn: "writable.writeDyn", args: [receiver, chunk], type: BOOL, loc }; @@ -4263,19 +4457,15 @@ 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 chunk = @@ -4284,16 +4474,7 @@ export function lowerStreamMethodCall( : 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 }; @@ -4305,34 +4486,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); 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( @@ -4342,6 +4518,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) @@ -4604,8 +4784,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/ir/builtin-effects.ts b/packages/compiler/src/ir/builtin-effects.ts index dd82d06c2..8a4e1848d 100644 --- a/packages/compiler/src/ir/builtin-effects.ts +++ b/packages/compiler/src/ir/builtin-effects.ts @@ -358,6 +358,7 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "readable.pushU", "readable.pushDyn", "readable.unshift", + "readable.unshiftDyn", "readable.unshiftStr", "readable.read", "readable.readDyn", @@ -370,6 +371,7 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "writable.writeStr", "writable.writeU", "writable.writeDyn", + "writable.writeEnc", "writable.end", "writable.uncork", "stream.destroy", diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index 8f5928d12..8104c7392 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -3875,7 +3875,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 → @@ -4014,6 +4018,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 }, @@ -4025,6 +4030,12 @@ 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 }, + /** 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 @@ -4078,6 +4089,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 }, diff --git a/packages/compiler/src/ir/runtime-features.ts b/packages/compiler/src/ir/runtime-features.ts index 9531d7845..1528242c4 100644 --- a/packages/compiler/src/ir/runtime-features.ts +++ b/packages/compiler/src/ir/runtime-features.ts @@ -216,6 +216,8 @@ 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", "console.bind", "crypto.hashStream", "crypto.hashStreamPiped", diff --git a/packages/compiler/src/ir/validate.ts b/packages/compiler/src/ir/validate.ts index 9de1b5b62..bb36c7007 100644 --- a/packages/compiler/src/ir/validate.ts +++ b/packages/compiler/src/ir/validate.ts @@ -4109,6 +4109,7 @@ function validateFunction( 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" || @@ -5492,6 +5493,7 @@ function validateFunction( e.fn.startsWith("passthrough.") || e.fn === "stream.destroy" || e.fn === "stream.destroyErr" || + e.fn === "stream.objectMode" || e.fn === "stream.iteratorClose" || e.fn === "stream.prop" || e.fn === "stream.errored" || @@ -5782,6 +5784,7 @@ function validateFunction( e.fn === "writable.end" || e.fn === "readable.setEncoding" || e.fn === "readable.pushEncoding" || + e.fn === "stream.objectMode" || e.fn === "stream.destroy" || e.fn === "stream.destroyErr" || e.fn === "stream.iteratorClose" @@ -5898,8 +5901,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/test/native-codegen-integration.test.ts b/packages/compiler/test/native-codegen-integration.test.ts index c05e7f994..af8d9b724 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_v25"); + expect(await symbols(helperObject, ["-u"])).toContain("_scr_runtime_abi_v26"); 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_v25"); + expect(undefinedSymbols).toContain("_scr_runtime_abi_v26"); }); test("helper and clang object paths retain the same outbound FFI C ABI", async () => { 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/runtime-darwin-arm64/scripts/build.mjs b/packages/runtime-darwin-arm64/scripts/build.mjs index 6cc32d7fa..edfaa7519 100644 --- a/packages/runtime-darwin-arm64/scripts/build.mjs +++ b/packages/runtime-darwin-arm64/scripts/build.mjs @@ -338,7 +338,7 @@ async function build() { package: packageManifest.name, version: packageManifest.version, target: RUNTIME_PACK_MATRIX.target, - runtime_abi: { version: 25, marker: "scr_runtime_abi_v25" }, + runtime_abi: { version: 26, marker: "scr_runtime_abi_v26" }, compiler: { command: compiler, identity: compilerVersion, diff --git a/packages/runtime-pack-common/scripts/build.mjs b/packages/runtime-pack-common/scripts/build.mjs index a2c987b97..542e7d48e 100644 --- a/packages/runtime-pack-common/scripts/build.mjs +++ b/packages/runtime-pack-common/scripts/build.mjs @@ -435,7 +435,7 @@ async function build() { package: packageManifest.name, version: packageManifest.version, target: matrix.target, - runtime_abi: { version: 25, marker: "scr_runtime_abi_v25" }, + runtime_abi: { version: 26, marker: "scr_runtime_abi_v26" }, compiler: { command: compiler, identity: compilerVersion, diff --git a/packages/runtime/src/scr_console.c b/packages/runtime/src/scr_console.c index c8fa40b38..24cd8093b 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_v25(void) {} +void scr_runtime_abi_v26(void) {} void scr_init(void) { #ifdef SCR_WORKERS diff --git a/packages/runtime/src/scr_core.h b/packages/runtime/src/scr_core.h index 5e5278588..791c600c7 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_v25(void); +void scr_runtime_abi_v26(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_dyn_builtin_stream.c b/packages/runtime/src/scr_dyn_builtin_stream.c index 209c8c39a..cdd815642 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" @@ -275,11 +274,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 +360,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]); @@ -488,8 +487,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 +582,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 +624,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: @@ -1037,10 +1037,16 @@ static ScrDyn *bcs_write(ScrStream *s, ScrDyn *self, ScrDyn *const *args, size_t 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(); + } + bool below; + if (scr_stream_writes_values(s)) { + /* an object-mode side hands the encoding argument to _write */ + below = scr_stream_write_enc(s, chunk, encoding, bcs_callback(cb, self, s)); + } else { + if (chunk->kind == SCR_DYN_STR && !bcs_utf8_only(encoding)) return NULL; + below = scr_stream_write_dyn(s, chunk, bcs_callback(cb, self, s)); } - 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)); if (scr_exc_pending()) return NULL; return scr_dyn_new_bool(below); } @@ -1055,11 +1061,17 @@ 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)) { + if (!bcs_nullish(chunk) && scr_stream_writes_values(s)) { + /* end(chunk) writes the value with the encoding argument */ + 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)); + } else if (chunk->kind == SCR_DYN_STR && !bcs_utf8_only(encoding)) { + return NULL; + } else 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)); @@ -1376,8 +1388,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_stream.c b/packages/runtime/src/scr_stream.c index 271937f2e..0c17c8840 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,6 +135,14 @@ 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. */ @@ -146,6 +157,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 +173,23 @@ 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; 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; @@ -267,31 +297,79 @@ 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 on an object-mode side. */ +static size_t scr_stream_wchunk_len(const ScrStreamState *st, ScrBytes *chunk) { + return st->w.object_mode ? 1 : chunk->len; +} + +static ScrBytes *scr_stream_wchunk_retain(const ScrStreamState *st, ScrBytes *chunk) { + if (st->w.object_mode) 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.object_mode) 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); @@ -312,8 +390,11 @@ 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.object_mode && 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); free(st->w.end_cbs); @@ -335,6 +416,11 @@ 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); @@ -348,6 +434,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.object_mode && 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); @@ -425,6 +514,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; @@ -486,10 +576,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); @@ -498,7 +598,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, @@ -523,10 +623,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(); } @@ -549,7 +649,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) { @@ -610,17 +711,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 @@ -637,7 +750,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) { @@ -681,7 +796,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; @@ -716,8 +831,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); @@ -753,12 +881,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); @@ -781,8 +909,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 @@ -790,9 +918,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) { @@ -852,7 +980,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; @@ -865,9 +993,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; } } @@ -877,10 +1005,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); } } @@ -950,43 +1078,33 @@ 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); @@ -998,15 +1116,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); @@ -1051,14 +1180,28 @@ 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); @@ -1066,17 +1209,7 @@ static void scr_stream_next_fulfill(ScrStreamState *st, ScrPromise *w /*moves*/, 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; + 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); } @@ -1108,11 +1241,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) { @@ -1124,7 +1257,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; } } @@ -1175,13 +1308,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 @@ -1192,7 +1330,7 @@ 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); } } @@ -1201,7 +1339,7 @@ static ScrPromise *scr_stream_next_chunk_impl(ScrStream *s, bool dyn) { 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); + scr_stream_next_fulfill(st, scr_promise_retain(p), NULL, SCR_ENTRY_BYTES); return p; } if (st->r.next_waiter) { @@ -1214,6 +1352,11 @@ static ScrPromise *scr_stream_next_chunk_impl(ScrStream *s, bool dyn) { st->r.next_dyn = dyn; 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); @@ -1268,25 +1411,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); @@ -1447,10 +1576,10 @@ ScrStream *scr_stream_from_arr(ScrArr *arr, double flags, double hwm) { } /* 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) { @@ -1460,14 +1589,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 { @@ -1598,61 +1720,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); @@ -1660,12 +1793,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) ────── */ @@ -1706,7 +1849,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); @@ -1714,29 +1858,49 @@ 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_transform_callback(ScrStream *s); -static void scr_stream_do_write(ScrStream *s, ScrBytes *chunk /*moves*/, ScrClosure *cb /*moves*/) { +static void scr_stream_do_write_inner(ScrStream *s, ScrBytes *chunk /*moves*/, ScrClosure *cb /*moves*/); + +/* 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 (st->w.object_mode) 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); @@ -1744,12 +1908,12 @@ 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) { - 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); @@ -1757,7 +1921,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; } @@ -1770,8 +1934,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); @@ -1863,12 +2028,14 @@ 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); } /* 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; 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++]; @@ -1876,8 +2043,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 @@ -1947,6 +2115,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); } @@ -2327,10 +2500,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); @@ -2345,10 +2518,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"); @@ -2398,6 +2569,7 @@ 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 */ ScrStr *enc; /* owned canonical name, or NULL */ /* BORROWED callable fields (owned by the options record). */ ScrDyn *read, *write, *final_fn, *destroy, *transform, *flush; @@ -2474,17 +2646,17 @@ 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->read = out->write = out->final_fn = out->destroy = out->transform = out->flush = 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); + { + 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)); } 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)"; @@ -2527,7 +2699,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; @@ -2538,6 +2710,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) { @@ -2578,6 +2752,10 @@ static ScrClosure *scr_stream_dynopt_pick(ScrDyn *opt, void *dyn_inv, ScrClosure return fb; } +static void scr_stream_dynopt_apply_object(ScrStream *s, const ScrStreamDynOpts *o) { + if (s != NULL && s->st != NULL) scr_stream_set_object_mode(s, o->readable_object, o->writable_object); +} + static void scr_stream_dynopt_apply_enc(ScrStream *s, ScrStr *enc) { if (enc == NULL) return; ScrStream *chain = scr_stream_set_encoding(s, enc); @@ -2593,6 +2771,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; } @@ -2604,8 +2783,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) { @@ -2620,6 +2801,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; } @@ -2640,6 +2822,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; } @@ -2666,6 +2849,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); } @@ -2686,6 +2870,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, @@ -2710,6 +2895,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); } @@ -2739,6 +2925,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); } @@ -3299,6 +3486,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(); @@ -4067,25 +4260,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 { @@ -4206,7 +4394,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; @@ -4379,7 +4567,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)); @@ -4452,7 +4654,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. */ @@ -4643,7 +4845,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); } @@ -4797,7 +5003,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; @@ -5323,6 +5529,85 @@ 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 = true; +} + +/* 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.object_mode; +} + +/* 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) { @@ -5330,6 +5615,9 @@ bool scr_stream_push(ScrStream *s, ScrBytes *chunk) { } 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) { @@ -5374,11 +5662,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); @@ -5408,7 +5696,7 @@ 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); } @@ -5422,6 +5710,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); @@ -5431,9 +5759,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); @@ -5444,7 +5772,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) || @@ -5468,13 +5796,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 @@ -5491,13 +5821,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 */ @@ -5515,11 +5860,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); @@ -5575,7 +5928,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); @@ -5647,7 +6000,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 @@ -5658,12 +6012,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. */ @@ -5672,7 +6026,28 @@ 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)); +} + bool scr_stream_write(ScrStream *s, ScrBytes *chunk, ScrClosure *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; + } return scr_stream_write_chunk(s, chunk, cb); } @@ -5686,6 +6061,13 @@ bool scr_stream_write_null(ScrStream *s) { } bool scr_stream_write_str(ScrStream *s, ScrStr *str, ScrClosure *cb) { + 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; + } 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); @@ -5695,10 +6077,65 @@ bool scr_stream_write_str(ScrStream *s, ScrStr *str, ScrClosure *cb) { return ret; } +/* 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); + scr_str_release(name); + if (canonical == NULL) { + if (cb) scr_closure_release(cb); + return false; + } + if (chunk->kind != SCR_DYN_STR) { + scr_str_release(canonical); + return scr_stream_write_dyn(s, chunk, cb); + } + ScrBytes *b = scr_bytes_from_str(chunk->v.str, canonical); + scr_str_release(canonical); + scr_stream_buffer(b); + bool ret = scr_stream_write_chunk(s, b, cb); + scr_bytes_release(b); + 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); @@ -5778,7 +6215,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); } @@ -5837,6 +6279,8 @@ void scr_stream_transform_done(ScrStream *s, ScrError *err /*moves*/, ScrBytes * 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); @@ -5870,6 +6314,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); @@ -5885,6 +6332,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. */ @@ -5970,6 +6449,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; } @@ -6011,7 +6491,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; @@ -6209,6 +6689,7 @@ static void scr_stream_run_tick(ScrStreamTick *t) { 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) { @@ -6272,6 +6753,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); @@ -6318,9 +6806,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; } @@ -6347,10 +6835,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 */ } @@ -6475,16 +6966,6 @@ static const ScrDynHandleTransform *scr_handle_step_ops(ScrClosure *cb) { return scr_handle_step_handle_ops(cb)->transform; } -/* The pending exception as a stream error (+1). */ -static ScrError *scr_handle_step_caught(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 Transform handle threw a value that is not an Error"); -} - 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. */ @@ -6494,7 +6975,7 @@ static void scr_handle_step_transform(ScrClosure *cb, ScrStream *s, ScrBytes *ch 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_handle_step_caught(), out, NULL); + 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) { diff --git a/packages/runtime/src/scr_stream.h b/packages/runtime/src/scr_stream.h index 1e5b789e7..8b8a72406 100644 --- a/packages/runtime/src/scr_stream.h +++ b/packages/runtime/src/scr_stream.h @@ -272,6 +272,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) */ @@ -291,6 +292,8 @@ 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); /* node:stream/promises — the promise forms over the finished/pipeline @@ -475,6 +478,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 diff --git a/packages/runtime/src/scr_stream_ops.c b/packages/runtime/src/scr_stream_ops.c index d32dd5d67..8fd220168 100644 --- a/packages/runtime/src/scr_stream_ops.c +++ b/packages/runtime/src/scr_stream_ops.c @@ -305,7 +305,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 @@ -1492,16 +1492,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; diff --git a/tests/corpus/7240-objectmode-streams.ts b/tests/corpus/7240-objectmode-streams.ts new file mode 100644 index 000000000..9316ff480 --- /dev/null +++ b/tests/corpus/7240-objectmode-streams.ts @@ -0,0 +1,130 @@ +// 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. +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)); +} + +async function main(): Promise { + await records(); + await collections(); + counters(); + sided(); + duplex(); + passthrough(); +} +main(); diff --git a/tests/corpus/7241-objectmode-streams.mjs b/tests/corpus/7241-objectmode-streams.mjs new file mode 100644 index 000000000..334273c00 --- /dev/null +++ b/tests/corpus/7241-objectmode-streams.mjs @@ -0,0 +1,148 @@ +// 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")); +} + +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/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/self-hosting-native-toolchain.test.ts b/tests/harness/self-hosting-native-toolchain.test.ts index c01b52595..d7187c50b 100644 --- a/tests/harness/self-hosting-native-toolchain.test.ts +++ b/tests/harness/self-hosting-native-toolchain.test.ts @@ -105,7 +105,7 @@ for (const backend of ["llvm"] as const) { object_format: target.objectFormat, minimum_os: target.minimumOs, }, - runtime_abi: { version: 25, marker: "scr_runtime_abi_v25" }, + runtime_abi: { version: 26, marker: "scr_runtime_abi_v26" }, compiler: { command: "fixture", identity: "fixture", target: target.llvmTriple }, macros: { executable: [], excluded: [], sanitizer: "external-toolchain-required" }, flavors: { From c47a0e90aee3d3a7e75c8b6c1cb16b9b3c570f4b Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 04:27:35 -0500 Subject: [PATCH 052/102] Compile JSX with the classic runtime Fixes #889 Co-authored-by: papack <33105506+papack@users.noreply.github.com> --- .oxlintrc.jsonc | 1 + docs/content/docs/limitations.mdx | 2 + .../limitations/language-features/jsx.mdx | 5 + .../compiler/src/frontend/jsx-entities.ts | 258 ++++++ .../compiler/src/frontend/jsx-source.test.ts | 244 +++++ packages/compiler/src/frontend/jsx-source.ts | 856 ++++++++++++++++++ packages/compiler/src/frontend/program.ts | 124 ++- .../src/frontend/ts7/enums.generated.ts | 22 + packages/compiler/src/frontend/ts7/enums.ts | 21 + .../compiler/src/frontend/ts7/program-host.ts | 4 + packages/compiler/src/frontend/tsc-codes.ts | 7 + .../6822-jsx-classic-runtime/main.ts.json | 11 + .../6824-jsx-automatic-runtime/main.ts.json | 12 + .../main.ts.json | 8 + .../jsx-factory-mismatch/main.ts.json | 17 + .../diagnostics/jsx-preserve/main.ts.json | 18 + .../diagnostics/jsx-type-errors/main.ts.json | 26 + scripts/generate-ts7-ast-schema.mjs | 2 + .../6822-jsx-classic-runtime/factory.ts | 7 + tests/corpus/6822-jsx-classic-runtime/html.ts | 45 + .../corpus/6822-jsx-classic-runtime/list.jsx | 22 + tests/corpus/6822-jsx-classic-runtime/main.ts | 15 + .../corpus/6822-jsx-classic-runtime/page.tsx | 40 + .../6822-jsx-classic-runtime/pragma.tsx | 11 + .../6822-jsx-classic-runtime/tsconfig.json | 9 + .../corpus/6824-jsx-automatic-runtime/alt.tsx | 3 + .../alt/jsx-runtime.ts | 17 + .../corpus/6824-jsx-automatic-runtime/main.ts | 10 + .../6824-jsx-automatic-runtime/package.json | 8 + .../6824-jsx-automatic-runtime/page.tsx | 33 + .../6824-jsx-automatic-runtime/render.ts | 15 + .../runtime/index.ts | 12 + .../runtime/jsx-runtime.ts | 33 + .../6824-jsx-automatic-runtime/tsconfig.json | 8 + .../6825-jsx-automatic-development/main.ts | 5 + .../package.json | 6 + .../runtime/jsx-dev-runtime.ts | 31 + .../tsconfig.json | 8 + .../6825-jsx-automatic-development/view.tsx | 21 + .../diagnostics/jsx-factory-mismatch/main.ts | 3 + .../jsx-factory-mismatch/tsconfig.json | 1 + .../diagnostics/jsx-factory-mismatch/view.tsx | 13 + tests/diagnostics/jsx-preserve/main.ts | 3 + tests/diagnostics/jsx-preserve/tsconfig.json | 1 + tests/diagnostics/jsx-preserve/view.tsx | 9 + tests/diagnostics/jsx-type-errors/main.ts | 3 + .../diagnostics/jsx-type-errors/tsconfig.json | 1 + tests/diagnostics/jsx-type-errors/view.tsx | 15 + .../jsx-factory-mismatch/main.ts.txt | 6 + .../__snapshots__/jsx-preserve/main.ts.txt | 8 + .../__snapshots__/jsx-type-errors/main.ts.txt | 13 + .../6822-jsx-classic-runtime/main.ts.json | 1 + .../6824-jsx-automatic-runtime/main.ts.json | 1 + .../main.ts.json | 1 + tests/harness/differential.test.ts | 4 +- tests/harness/jsx-oracle.ts | 120 +++ tests/harness/linux-differential.test.ts | 4 +- tests/harness/llvm-differential.test.ts | 4 +- tests/harness/windows-differential.test.ts | 23 +- 59 files changed, 2216 insertions(+), 15 deletions(-) create mode 100644 docs/content/limitations/language-features/jsx.mdx create mode 100644 packages/compiler/src/frontend/jsx-entities.ts create mode 100644 packages/compiler/src/frontend/jsx-source.test.ts create mode 100644 packages/compiler/src/frontend/jsx-source.ts create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6822-jsx-classic-runtime/main.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6824-jsx-automatic-runtime/main.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6825-jsx-automatic-development/main.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-factory-mismatch/main.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-preserve/main.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-type-errors/main.ts.json create mode 100644 tests/corpus/6822-jsx-classic-runtime/factory.ts create mode 100644 tests/corpus/6822-jsx-classic-runtime/html.ts create mode 100644 tests/corpus/6822-jsx-classic-runtime/list.jsx create mode 100644 tests/corpus/6822-jsx-classic-runtime/main.ts create mode 100644 tests/corpus/6822-jsx-classic-runtime/page.tsx create mode 100644 tests/corpus/6822-jsx-classic-runtime/pragma.tsx create mode 100644 tests/corpus/6822-jsx-classic-runtime/tsconfig.json create mode 100644 tests/corpus/6824-jsx-automatic-runtime/alt.tsx create mode 100644 tests/corpus/6824-jsx-automatic-runtime/alt/jsx-runtime.ts create mode 100644 tests/corpus/6824-jsx-automatic-runtime/main.ts create mode 100644 tests/corpus/6824-jsx-automatic-runtime/package.json create mode 100644 tests/corpus/6824-jsx-automatic-runtime/page.tsx create mode 100644 tests/corpus/6824-jsx-automatic-runtime/render.ts create mode 100644 tests/corpus/6824-jsx-automatic-runtime/runtime/index.ts create mode 100644 tests/corpus/6824-jsx-automatic-runtime/runtime/jsx-runtime.ts create mode 100644 tests/corpus/6824-jsx-automatic-runtime/tsconfig.json create mode 100644 tests/corpus/6825-jsx-automatic-development/main.ts create mode 100644 tests/corpus/6825-jsx-automatic-development/package.json create mode 100644 tests/corpus/6825-jsx-automatic-development/runtime/jsx-dev-runtime.ts create mode 100644 tests/corpus/6825-jsx-automatic-development/tsconfig.json create mode 100644 tests/corpus/6825-jsx-automatic-development/view.tsx create mode 100644 tests/diagnostics/jsx-factory-mismatch/main.ts create mode 100644 tests/diagnostics/jsx-factory-mismatch/tsconfig.json create mode 100644 tests/diagnostics/jsx-factory-mismatch/view.tsx create mode 100644 tests/diagnostics/jsx-preserve/main.ts create mode 100644 tests/diagnostics/jsx-preserve/tsconfig.json create mode 100644 tests/diagnostics/jsx-preserve/view.tsx create mode 100644 tests/diagnostics/jsx-type-errors/main.ts create mode 100644 tests/diagnostics/jsx-type-errors/tsconfig.json create mode 100644 tests/diagnostics/jsx-type-errors/view.tsx create mode 100644 tests/harness/__snapshots__/jsx-factory-mismatch/main.ts.txt create mode 100644 tests/harness/__snapshots__/jsx-preserve/main.ts.txt create mode 100644 tests/harness/__snapshots__/jsx-type-errors/main.ts.txt create mode 100644 tests/harness/corpus-costs/6822-jsx-classic-runtime/main.ts.json create mode 100644 tests/harness/corpus-costs/6824-jsx-automatic-runtime/main.ts.json create mode 100644 tests/harness/corpus-costs/6825-jsx-automatic-development/main.ts.json create mode 100644 tests/harness/jsx-oracle.ts 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/docs/content/docs/limitations.mdx b/docs/content/docs/limitations.mdx index 5be38a924..e132f27da 100644 --- a/docs/content/docs/limitations.mdx +++ b/docs/content/docs/limitations.mdx @@ -34,6 +34,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/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/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/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/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..c87da0bfe 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) => 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/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/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/scripts/generate-ts7-ast-schema.mjs b/scripts/generate-ts7-ast-schema.mjs index a1bc80117..07af474de 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]; 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/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/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/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/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/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/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/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]); } From cab2db4f96f3205f35326e069a68bfc6df589953 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 04:27:50 -0500 Subject: [PATCH 053/102] Drop the Cipheriv stream fence from the node-types fixture --- tests/fixtures/node-types/fenced.ts | 4 -- .../__snapshots__/node-types-fenced.txt | 41 ++++++++----------- 2 files changed, 16 insertions(+), 29 deletions(-) diff --git a/tests/fixtures/node-types/fenced.ts b/tests/fixtures/node-types/fenced.ts index dfd07d446..274d57272 100644 --- a/tests/fixtures/node-types/fenced.ts +++ b/tests/fixtures/node-types/fenced.ts @@ -93,10 +93,6 @@ 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. */ diff --git a/tests/harness/__snapshots__/node-types-fenced.txt b/tests/harness/__snapshots__/node-types-fenced.txt index 2f1f8cb2e..3198db366 100644 --- a/tests/harness/__snapshots__/node-types-fenced.txt +++ b/tests/harness/__snapshots__/node-types-fenced.txt @@ -205,47 +205,38 @@ 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 secret-key slice: @types/node declares the whole + 102 | /* WebCrypto beyond the secret-key slice: @types/node declares the whole 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.wrapKey' is part of the standard library types but has no scriptc lowering yet +fenced.ts:106:9 - error SC2020: 'crypto.subtle.wrapKey' is part of the standard library types but has no scriptc lowering yet - 109 | async function wrapWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { - 110 | await crypto.subtle.wrapKey("raw", key, key, "AES-KW"); + 105 | async function wrapWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { + 106 | await crypto.subtle.wrapKey("raw", key, key, "AES-KW"); | ^~~~~~~~~~~~~~~~~~~~~ - 111 | } + 107 | } 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, deriveBits and deriveKey with PBKDF2 or HKDF, sign and verify with HMAC, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle -fenced.ts:115:15 - error SC2020: 'navigator.hardwareConcurrency' is typed by @types/node but has no scriptc lowering yet +fenced.ts:111:15 - error SC2020: 'navigator.hardwareConcurrency' is typed by @types/node but has no scriptc lowering yet - 114 | * compile; the other members fence by name. */ - 115 | const cores = navigator.hardwareConcurrency; + 110 | * compile; the other members fence by name. */ + 111 | const cores = navigator.hardwareConcurrency; | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 116 | void cores; + 112 | void cores; hint: of Node's navigator global only typeof navigator and navigator.userAgent compile \ No newline at end of file From b03e965bf99716c4f353053526fa6ab67182ceda Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 04:35:27 -0500 Subject: [PATCH 054/102] Resolve 7058's promises with undefined so both checkers agree --- tests/corpus/7058-pipeline-function-stages.mjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/corpus/7058-pipeline-function-stages.mjs b/tests/corpus/7058-pipeline-function-stages.mjs index f0a61e7c2..f75abac39 100644 --- a/tests/corpus/7058-pipeline-function-stages.mjs +++ b/tests/corpus/7058-pipeline-function-stages.mjs @@ -60,7 +60,7 @@ await new Promise((resolve) => { }, (err, value) => { console.log("array source:", err ?? null, value); - resolve(); + resolve(undefined); }, ); }); @@ -114,7 +114,7 @@ function ticker(log) { await new Promise((resolve) => pipeline(["a", "b"], new PassThrough(), sink(log), () => { stop(); - resolve(); + resolve(undefined); }), ); console.log("array ticks:", log.join(" ")); @@ -134,7 +134,7 @@ function ticker(log) { sink(log), () => { stop(); - resolve(); + resolve(undefined); }, ), ); From feec4bf4df9734d23aa0c919429e5de42d902802 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 04:44:34 -0500 Subject: [PATCH 055/102] Call typed-array callbacks directly and visit on an integer counter The helpers of the typed-array callback methods (forEach, map, filter, some, every, find, findIndex, findLast, findLastIndex, reduce, reduceRight) called their callback through the closure's code pointer on every element, and one helper served every call with the same signature, so the callback was never inlined. A literal callback now gets a helper of its own, as for the array methods, and the constant-callback census accepts the typed-array helpers, so the helper calls that function directly. The visit is now a loop on its own counter, `for (let i = 0; i < a.length; i++)` or down from the last index, instead of a loop on a counter declared before it, so the counter is an integer and element reads need no index test. reduce and reduceRight without an initial value read their seed at the first visited index and start one past it. Adds reduce, some and map callbacks to the typed-array-kernels workload. --- benchmarks/runtime/README.md | 2 +- .../runtime/workloads/typed-array-kernels.ts | 11 +++ .../backend/llvm/constant-callbacks.test.ts | 23 +++-- .../src/backend/llvm/constant-callbacks.ts | 12 ++- .../lowering/containers/array-callbacks.ts | 2 +- .../src/frontend/lowering/containers/bytes.ts | 84 +++++++++++++---- .../test/bytes-callback-helpers.test.ts | 68 ++++++++++++++ .../6999-typed-array-callback-loops.ts.json | 6 ++ .../corpus/6999-typed-array-callback-loops.ts | 93 +++++++++++++++++++ .../6999-typed-array-callback-loops.ts.json | 1 + 10 files changed, 269 insertions(+), 33 deletions(-) create mode 100644 packages/compiler/test/bytes-callback-helpers.test.ts create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6999-typed-array-callback-loops.ts.json create mode 100644 tests/corpus/6999-typed-array-callback-loops.ts create mode 100644 tests/harness/corpus-costs/6999-typed-array-callback-loops.ts.json diff --git a/benchmarks/runtime/README.md b/benchmarks/runtime/README.md index cbf47675a..34baccf5b 100644 --- a/benchmarks/runtime/README.md +++ b/benchmarks/runtime/README.md @@ -26,7 +26,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, 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/typed-array-kernels.ts b/benchmarks/runtime/workloads/typed-array-kernels.ts index ba68f7241..d865ec914 100644 --- a/benchmarks/runtime/workloads/typed-array-kernels.ts +++ b/benchmarks/runtime/workloads/typed-array-kernels.ts @@ -21,6 +21,14 @@ function brighten(src: Uint8ClampedArray, gain: number, out: Uint8ClampedArray): for (let i = 0; i < out.length; i++) out[i] = src[i]! * gain + 8; } +// 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; @@ -73,6 +81,7 @@ let byteSum = 0; let intSum = 0; let brightSum = 0; let lumaSum = 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); @@ -88,6 +97,7 @@ for (let r = 0; r < rounds; r++) { addWrap(ia, ib, io); brighten(pixels, 0.75 + (r & 7) / 8, bright); gray(rgba, luma); + if ((r & 3) === 0) callbackSum += callbacks(fo, 140 + (r & 12), masked); const probe = (r * 104729) & (n - 1); f64Sum += d[probe]!; f32Sum += fo[probe]!; @@ -102,3 +112,4 @@ console.log(`uint8 ${byteSum}`); console.log(`int32 ${intSum}`); console.log(`clamped ${brightSum}`); console.log(`gray ${lumaSum}`); +console.log(`callbacks ${callbackSum.toFixed(3)}`); 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..8a898d6a0 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 && diff --git a/packages/compiler/src/frontend/lowering/containers/array-callbacks.ts b/packages/compiler/src/frontend/lowering/containers/array-callbacks.ts index 7ca69d9ba..612c47ea0 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-callbacks.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-callbacks.ts @@ -452,7 +452,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}` : ""; } diff --git a/packages/compiler/src/frontend/lowering/containers/bytes.ts b/packages/compiler/src/frontend/lowering/containers/bytes.ts index 8a4364754..fd4420b69 100644 --- a/packages/compiler/src/frontend/lowering/containers/bytes.ts +++ b/packages/compiler/src/frontend/lowering/containers/bytes.ts @@ -43,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 @@ -251,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, @@ -267,8 +282,9 @@ 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 = keyedHelperName(lowerer, `%bytes.${method}`, key); @@ -300,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", @@ -344,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) { @@ -459,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", @@ -486,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({ @@ -506,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 }); 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/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/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/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 } From 883f22ddd62005a26bb0fff3e9b83991e3cf6b7e Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 04:50:13 -0500 Subject: [PATCH 056/102] Run two-counter for loops on integer counters `for (let lo = a, hi = b; lo < hi; lo++, hi--)` kept both counters as doubles: the counted-loop match takes a single counter, so every `a[lo]`/`a[hi]` converted and tested its index. A loop whose two counters close in on each other by positive literal steps, are not written by the body and index something now stores both as i64: on every body entry both lie between the first start and the second. A start without a proven integer range is tested at run time on a versioned loop, as a counted loop's is. --- .../src/backend/llvm/counted-loops.ts | 81 ++++++++----- .../src/backend/llvm/emit-statements.ts | 58 ++++++++- .../compiler/src/ir/integer-loops.test.ts | 73 ++++++++++- packages/compiler/src/ir/integer-loops.ts | 114 ++++++++++++++++++ .../corpus/7140-paired-loop-counters.ts.json | 6 + tests/corpus/7140-paired-loop-counters.ts | 81 +++++++++++++ .../7140-paired-loop-counters.ts.json | 1 + 7 files changed, 377 insertions(+), 37 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json create mode 100644 tests/corpus/7140-paired-loop-counters.ts create mode 100644 tests/harness/corpus-costs/7140-paired-loop-counters.ts.json diff --git a/packages/compiler/src/backend/llvm/counted-loops.ts b/packages/compiler/src/backend/llvm/counted-loops.ts index 36fc63e1f..02943b852 100644 --- a/packages/compiler/src/backend/llvm/counted-loops.ts +++ b/packages/compiler/src/backend/llvm/counted-loops.ts @@ -1,4 +1,5 @@ -import type { IntegerCountedForLoop } from "../../ir/integer-loops.js"; +import type { IntegerCountedForLoop, IntegerPairedForLoop } from "../../ir/integer-loops.js"; +import type { IrExpr } from "../../ir/ir.js"; import type { LlvmEmitterContext } from "./expr-context.js"; import { f64Lit } from "./common.js"; @@ -59,37 +60,51 @@ export function emitCountedLoopSafety( `${safe} = fcmp ${loop.step > 0 ? "ole" : "oge"} double ${bound.name}, ${f64Lit(loop.guardLimit)}`, ); } - if (loop.startGuarded) { - // An exact integer of at most 2^53 - 1 in magnitude, and not -0 - // (the bit patterns of the value and its round trip agree). - // NaN and infinities fail the ordered range tests. - const start = host.emitExpr(loop.start); - const low = B.tmp(), - high = B.tmp(), - raw = B.tmp(), - wide = B.tmp(), - back = B.tmp(), - bits = B.tmp(), - backBits = B.tmp(), - exact = B.tmp(), - inRange = B.tmp(), - ok = B.tmp(); - B.line(`${low} = fcmp oge double ${start.name}, ${f64Lit(-Number.MAX_SAFE_INTEGER)}`); - B.line(`${high} = fcmp ole double ${start.name}, ${f64Lit(Number.MAX_SAFE_INTEGER)}`); - B.line(`${inRange} = and i1 ${low}, ${high}`); - B.line(`${raw} = fptosi double ${start.name} to i64`); - B.line(`${wide} = freeze i64 ${raw}`); - B.line(`${back} = sitofp i64 ${wide} to double`); - B.line(`${bits} = bitcast double ${start.name} 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}`); - if (safe === "true") safe = ok; - else { - const both = B.tmp(); - B.line(`${both} = and i1 ${safe}, ${ok}`); - safe = both; - } - } + if (loop.startGuarded) safe = andSafe(host, safe, emitExactStart(host, loop.start)); return safe; } + +/** 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 { + let safe = "true"; + for (const counter of [loop.low, loop.high]) + if (counter.startGuarded) safe = andSafe(host, safe, emitExactStart(host, counter.start)); + return safe; +} + +function andSafe(host: LlvmEmitterContext, safe: string, ok: string): string { + if (safe === "true") return ok; + const both = host.B.tmp(); + host.B.line(`${both} = and i1 ${safe}, ${ok}`); + return both; +} + +/** An exact integer of at most 2^53 - 1 in magnitude, and not -0 (the bit + * patterns of the value and its round trip agree). NaN and infinities fail + * the ordered range tests. */ +function emitExactStart(host: LlvmEmitterContext, expr: IrExpr): string { + const B = host.B; + const start = host.emitExpr(expr); + const low = B.tmp(), + high = B.tmp(), + raw = B.tmp(), + wide = B.tmp(), + back = B.tmp(), + bits = B.tmp(), + backBits = B.tmp(), + exact = B.tmp(), + inRange = B.tmp(), + ok = B.tmp(); + B.line(`${low} = fcmp oge double ${start.name}, ${f64Lit(-Number.MAX_SAFE_INTEGER)}`); + B.line(`${high} = fcmp ole double ${start.name}, ${f64Lit(Number.MAX_SAFE_INTEGER)}`); + B.line(`${inRange} = and i1 ${low}, ${high}`); + B.line(`${raw} = fptosi double ${start.name} to i64`); + B.line(`${wide} = freeze i64 ${raw}`); + B.line(`${back} = sitofp i64 ${wide} to double`); + B.line(`${bits} = bitcast double ${start.name} 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; +} diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index 7f189c066..7239db7d8 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -42,10 +42,15 @@ import { matchIntegerArrayForLoop, matchIntegerBytesForLoop, matchIntegerCountedForLoop, + matchIntegerPairedForLoop, } from "../../ir/integer-loops.js"; import { emitByteWindowGuard, matchByteWindow } from "./byte-windows.js"; import { countedDenseShape, emitDenseLoopGuard, matchDenseArrayLoop } from "./dense-array-loops.js"; -import { emitCountedLoopLimit, emitCountedLoopSafety } from "./counted-loops.js"; +import { + emitCountedLoopLimit, + emitCountedLoopSafety, + emitPairedLoopSafety, +} from "./counted-loops.js"; import { emitBytesLoopVersionGuard } from "./bytes-loop-versions.js"; import { mangleLocal } from "../mangle.js"; import { LlvmUnsupportedError } from "./unsupported.js"; @@ -868,6 +873,12 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { 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 + ? matchIntegerPairedForLoop(s, emitter.numericLocals, emitter.integerRanges) + : null; const window = countedLoop && emitter.byteWindowsEnabled ? matchByteWindow( @@ -1000,8 +1011,10 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { break; } let countedJoin: string | null = null; - if (countedLoop?.guarded && !emitter.provenCountedGuards.has(s)) { - const safe = emitCountedLoopSafety(emitter, countedLoop); + if ((countedLoop?.guarded && !emitter.provenCountedGuards.has(s)) || pairedLoop?.guarded) { + const safe = countedLoop + ? emitCountedLoopSafety(emitter, countedLoop) + : emitPairedLoopSafety(emitter, pairedLoop!); const fast = B.newLabel("counted.fast"); const slow = B.newLabel("counted.slow"); countedJoin = B.newLabel("counted.done"); @@ -1016,6 +1029,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { emitter.scopes.push([]); let integerSlot: string | null = null; let countedLimit: string | null = null; + const pairedSlots: string[] = []; if (integerLoop) { integerSlot = B.slot(); B.entryAllocas.push( @@ -1060,6 +1074,24 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { : countedLoop.range, }); countedLimit = emitCountedLoopLimit(emitter, countedLoop); + } else if (pairedLoop) { + for (const counter of [pairedLoop.low, pairedLoop.high]) { + const slot = B.slot(); + B.entryAllocas.push( + `${slot} = alloca i64 ; integer induction ${emitter.currentLocals.get(counter.localId)!.name}`, + ); + const value = emitter.emitExpr(counter.start); + const start = B.tmp(); + B.line(`${start} = fptosi double ${value.name} to i64`); + B.line(`store i64 ${start}, ptr ${slot}`); + pairedSlots.push(slot); + emitter.integerLoopBindings.set(counter.localId, { + slot, + type: "i64", + signed: true, + range: pairedLoop.range, + }); + } } else if (s.init) { // A multi-declarator head shares the loop's scope. Emitting its // IR block as an ordinary block would release captured/ref locals @@ -1141,6 +1173,14 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { `${inBounds} = icmp ${countedLoop.step > 0 ? "slt" : "sgt"} i64 ${index}, ${countedLimit}`, ); B.condBr(inBounds, lb, exit); + } else if (pairedLoop) { + const low = B.tmp(), + high = B.tmp(), + open = B.tmp(); + B.line(`${low} = load i64, ptr ${pairedSlots[0]}`); + B.line(`${high} = load i64, ptr ${pairedSlots[1]}`); + B.line(`${open} = icmp ${pairedLoop.inclusive ? "sle" : "slt"} i64 ${low}, ${high}`); + B.condBr(open, lb, exit); } else if (s.cond) B.condBr(emitter.emitCondition(s.cond), lb, exit); else B.br(lb); B.startBlock(lb); @@ -1172,6 +1212,14 @@ 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}`); + } else if (pairedLoop) { + [pairedLoop.low, pairedLoop.high].forEach((counter, i) => { + const old = B.tmp(); + const next = B.tmp(); + B.line(`${old} = load i64, ptr ${pairedSlots[i]}`); + B.line(`${next} = add nsw i64 ${old}, ${counter.step}`); + B.line(`store i64 ${next}, ptr ${pairedSlots[i]}`); + }); } else if (s.update) emitter.emitStmt(s.update); B.br(lc); } @@ -1180,6 +1228,10 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { emitter.releaseScope(emitter.scopes.pop()!); if (integerLoop) emitter.integerLoopBindings.delete(integerLoop.localId); if (countedLoop) emitter.integerLoopBindings.delete(countedLoop.localId); + if (pairedLoop) { + emitter.integerLoopBindings.delete(pairedLoop.low.localId); + emitter.integerLoopBindings.delete(pairedLoop.high.localId); + } if (integerArrayLoop) emitter.integerArrayBindings.delete(integerArrayLoop.localId); if (countedJoin) { B.br(countedJoin); diff --git a/packages/compiler/src/ir/integer-loops.test.ts b/packages/compiler/src/ir/integer-loops.test.ts index aada3b053..24bbf5be0 100644 --- a/packages/compiler/src/ir/integer-loops.test.ts +++ b/packages/compiler/src/ir/integer-loops.test.ts @@ -1,6 +1,10 @@ import { expect, test } from "vitest"; import { BOOL, F64, STRING, arrayOf, type IrExpr, type IrLocal, type IrStmt } from "./ir.js"; -import { matchIntegerArrayForLoop, matchIntegerCountedForLoop } from "./integer-loops.js"; +import { + matchIntegerArrayForLoop, + matchIntegerCountedForLoop, + matchIntegerPairedForLoop, +} from "./integer-loops.js"; const loc = { file: "integer-array-loop.ts", start: 0, end: 0 }; const number = (value: number): IrExpr => ({ kind: "numLit", value, type: F64, loc }); @@ -355,3 +359,70 @@ test("a descending loop from an array's last index takes an integer counter for range: { min: 0, max: 4294967294 }, }); }); + +test("paired counters closing in on each other run as integers", () => { + const vars = new Map(locals); + for (const id of ["lo", "hi", "head"]) vars.set(id, { id, name: id, type: F64, mutable: true }); + 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 element = (index: IrExpr): IrExpr => ({ + kind: "arrayGet", + arr: { kind: "varRef", localId: "a", type: arrayOf(F64), loc }, + index, + type: F64, + loc, + }); + const paired = ( + lowStart: IrExpr, + highStart: IrExpr, + update = [step("lo", "+"), step("hi", "-")], + ) => + ({ + kind: "for", + loc, + init: { + kind: "block", + body: [ + { kind: "varDecl", localId: "lo", init: lowStart, loc }, + { kind: "varDecl", localId: "hi", init: highStart, loc }, + ], + loc, + }, + cond: { kind: "bin", op: "<", left: ref("lo"), right: ref("hi"), type: BOOL, loc }, + update: { kind: "block", body: update, loc }, + body: [{ kind: "exprStmt", expr: element(ref("hi")), loc }], + }) as IrStmt & { kind: "for" }; + expect(matchIntegerPairedForLoop(paired(number(0), number(9)), vars)).toMatchObject({ + low: { localId: "lo", step: 1, startGuarded: false }, + high: { localId: "hi", step: -1, startGuarded: false }, + guarded: false, + range: { min: 0, max: 9 }, + }); + // A start without a known range is tested at run time. + expect(matchIntegerPairedForLoop(paired(number(0), ref("head")), vars)).toMatchObject({ + high: { startGuarded: true }, + guarded: true, + }); + // Counters moving the same way, written by the body, captured, started + // from each other, or never used as an index are refused. + expect( + matchIntegerPairedForLoop( + paired(number(0), number(9), [step("lo", "+"), step("hi", "+")]), + vars, + ), + ).toBeNull(); + const writing = paired(number(0), number(9)); + writing.body.push(step("hi", "-", 2)); + expect(matchIntegerPairedForLoop(writing, vars)).toBeNull(); + const boxed = new Map(vars); + boxed.set("hi", { ...vars.get("hi")!, boxed: true }); + expect(matchIntegerPairedForLoop(paired(number(0), number(9)), boxed)).toBeNull(); + expect(matchIntegerPairedForLoop(paired(number(0), ref("lo")), vars)).toBeNull(); + const unused = paired(number(0), number(9)); + unused.body = []; + expect(matchIntegerPairedForLoop(unused, vars)).toBeNull(); +}); diff --git a/packages/compiler/src/ir/integer-loops.ts b/packages/compiler/src/ir/integer-loops.ts index 9b4675685..e80680d6e 100644 --- a/packages/compiler/src/ir/integer-loops.ts +++ b/packages/compiler/src/ir/integer-loops.ts @@ -281,6 +281,120 @@ export function matchIntegerCountedForLoop( }; } +/** A for loop whose two counters close in on each other: + * + * for (let lo = a, hi = b; lo < hi; lo++, hi--) { ... } + * + * The first counter only grows and the second only shrinks, by positive + * literal steps, the body writes neither, and the loop runs while the first + * is below (or at most) the second. Every body entry therefore holds both + * between the first start and the second start: exact integers when the + * starts are. A start without a proven integer range is tested at run time + * on a versioned loop, as a counted loop's is. */ +export interface IntegerPairedCounter { + localId: string; + start: IrExpr; + /** The signed step of each update. */ + step: number; + startGuarded: boolean; +} +export interface IntegerPairedForLoop { + low: IntegerPairedCounter; + high: IntegerPairedCounter; + inclusive: boolean; + guarded: boolean; + /** Both counters' values on every body entry. */ + range: IntegerRange; +} + +export function matchIntegerPairedForLoop( + stmt: IrStmt & { kind: "for" }, + locals: ReadonlyMap, + ranges: IntegerRanges = new Map(), +): IntegerPairedForLoop | null { + const init = stmt.init, + update = stmt.update, + cond = stmt.cond; + if (init?.kind !== "block" || init.body.length !== 2) return null; + if (update?.kind !== "block" || update.body.length !== 2) return null; + if (cond?.kind !== "bin" || (cond.op !== "<" && cond.op !== "<=")) return null; + if (cond.left.kind !== "varRef" || cond.right.kind !== "varRef") return null; + const lowId = cond.left.localId, + highId = cond.right.localId; + if (lowId === highId) return null; + const counter = (id: string): IntegerPairedCounter | null => { + const decl = init.body.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; + // Each start is evaluated once in the head and again on a fallback path. + if ( + !stableLoopValue(start, locals, stmt.body, false, lowId) || + !stableLoopValue(start, locals, stmt.body, false, highId) + ) + return null; + const steps = update.body.map((u) => constantStep(u, id)).filter((v) => v !== null); + if (steps.length !== 1 || writesLocal(stmt.body, id)) return null; + const known = + start.kind === "numLit" && Number.isSafeInteger(start.value) && !Object.is(start.value, -0) + ? { min: start.value, max: start.value } + : ranges.get(start); + const startGuarded = !known && start.kind !== "numLit" && start.type.kind === "f64"; + if (!known && !startGuarded) return null; + if (known && (known.min < -Number.MAX_SAFE_INTEGER || known.max > Number.MAX_SAFE_INTEGER)) + return null; + return { localId: id, start, step: steps[0]!, startGuarded }; + }; + const low = counter(lowId), + high = counter(highId); + if (!low || !high || low.step <= 0 || high.step >= 0) return null; + const startRange = (c: IntegerPairedCounter): IntegerRange => + c.startGuarded + ? { min: -Number.MAX_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER } + : c.start.kind === "numLit" + ? { min: c.start.value, max: c.start.value } + : ranges.get(c.start)!; + const guarded = low.startGuarded || high.startGuarded; + // Only a loop whose counters index something gains from integer storage. + let useful = false, + cost = 0; + const isCounter = (e: IrExpr): boolean => + (e.kind === "varRef" && (e.localId === lowId || e.localId === highId)) || + (e.kind === "bin" && + (e.op === "+" || e.op === "-") && + (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])) + useful = true; + if (e.kind === "bytesIntrinsic" && e.method === "get" && e.args[0] && isCounter(e.args[0])) + useful = true; + return (!guarded || ++cost <= 80) && everyExprChild(e, expr, bodyStmt); + }; + const bodyStmt = (s: IrStmt): boolean => { + if ((s.kind === "arraySet" || s.kind === "bytesSet") && isCounter(s.index)) useful = true; + if ( + guarded && + (s.kind === "for" || s.kind === "forOf" || s.kind === "while" || s.kind === "doWhile") + ) + return false; + return (!guarded || ++cost <= 80) && everyStmtChild(s, expr, bodyStmt); + }; + if (!stmt.body.every(bodyStmt) || !useful) return null; + return { + low, + high, + inclusive: cond.op === "<=", + guarded, + // A loop whose starts already fail the condition never enters the body. + range: { + min: startRange(low).min, + max: Math.max(startRange(low).min, startRange(high).max), + }, + }; +} + /** True when a lowered subtree writes `localId`. Local ids are unique per * function, so typed traversal includes writes * nested in expressions, branches, nested loops, and try/finally bodies. */ diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json new file mode 100644 index 000000000..122d64bb6 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7140-paired-loop-counters.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7140-paired-loop-counters.ts" + ], + "diags": [] +} diff --git a/tests/corpus/7140-paired-loop-counters.ts b/tests/corpus/7140-paired-loop-counters.ts new file mode 100644 index 000000000..ec1610d1a --- /dev/null +++ b/tests/corpus/7140-paired-loop-counters.ts @@ -0,0 +1,81 @@ +// For loops with two counters closing in on each other (`lo++, hi--`): +// in-place reversals, inclusive bounds, larger steps, early exits, starts +// that are fractions, negative zero, NaN, huge or already crossed, nested +// reversals, and counters a closure captures or the body writes. +function reverse(a: number[], from: number, to: number): number[] { + for (let lo = from, hi = to; lo < hi; lo++, hi--) { + const t = a[lo]!; + a[lo] = a[hi]!; + a[hi] = t; + } + return a; +} +const base = (): number[] => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; +console.log(reverse(base(), 0, 9).join(",")); +console.log(reverse(base(), 2, 6).join(",")); +console.log(reverse(base(), 6, 2).join(",")); +console.log(reverse(base(), 3, 3).join(",")); +// Unproven starts: fractions, negative zero, NaN and huge values keep JS +// semantics (charCodeAt truncates its index; out-of-range reads are NaN). +function codes(s: string, from: number, to: number): string { + const out: number[] = []; + for (let lo = from, hi = to; lo < hi; lo++, hi--) out.push(s.charCodeAt(lo), s.charCodeAt(hi), lo, hi); + return out.join(","); +} +const word = "abcdefgh"; +console.log(codes(word, 0.5, 4.5)); +console.log(codes(word, -0, 3), Object.is(-0 + 0, 0)); +console.log(codes(word, NaN, 4), "|", codes(word, 0, NaN)); +console.log(codes(word, 2 ** 53 - 3, 2 ** 53)); +console.log(codes(word, -3, 2)); + +function pairs(n: number): string { + const out: string[] = []; + for (let i = 0, j = n; i <= j; i += 2, j -= 3) out.push(`${i}:${j}`); + return out.join(" "); +} +console.log(pairs(20), "|", pairs(0), "|", pairs(-1)); + +function firstGap(a: number[]): number { + let found = -1; + for (let lo = 0, hi = a.length - 1; lo < hi; lo++, hi--) { + if (a[lo] === a[hi]) continue; + found = lo; + break; + } + return found; +} +console.log(firstGap([1, 2, 3, 2, 1]), firstGap([1, 2, 3, 4, 2, 1]), firstGap([])); + +// The flip loop of a permutation puzzle: the next index comes from the array. +function flips(perm: number[]): number { + const work = perm.slice(); + let count = 0; + let head = work[0]!; + while (head !== 0) { + for (let lo = 0, hi = head; lo < hi; lo++, hi--) { + const t = work[lo]!; + work[lo] = work[hi]!; + work[hi] = t; + } + count++; + head = work[0]!; + } + return count; +} +console.log(flips([3, 1, 0, 2]), flips([4, 3, 2, 1, 0]), flips([0, 1, 2])); + +// Counters a closure reads, or the body writes, stay ordinary bindings. +const readers: (() => number)[] = []; +for (let lo = 0, hi = 4; lo < hi; lo++, hi--) readers.push(() => lo * 10 + hi); +console.log(readers.map((f) => f()).join(",")); +const seen: number[] = []; +for (let lo = 0, hi = 10; lo < hi; lo++, hi--) { + seen.push(lo, hi); + if (lo === 2) hi -= 3; +} +console.log(seen.join(",")); +const text = "abcdefgh"; +let mirrored = ""; +for (let lo = 0, hi = text.length - 1; lo <= hi; lo++, hi--) mirrored += text.charAt(hi) + text.charCodeAt(lo); +console.log(mirrored); diff --git a/tests/harness/corpus-costs/7140-paired-loop-counters.ts.json b/tests/harness/corpus-costs/7140-paired-loop-counters.ts.json new file mode 100644 index 000000000..549fd6a4a --- /dev/null +++ b/tests/harness/corpus-costs/7140-paired-loop-counters.ts.json @@ -0,0 +1 @@ +{ "plain": 3880, "san": 6000 } From 13608301496f6a1980b63bb08f6ac3391d6d957e Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 04:52:44 -0500 Subject: [PATCH 057/102] Support new tls.TLSSocket and tls.connect({ socket }) --- .../src/generated/node-v24-compatibility.json | 12 +- .../generated/node-v24-internal.json | 23 +- internal/compatibility/static-support.json | 1 + .../ambient/scriptc-node-fallback.d.ts | 63 +++- packages/compiler/src/backend/llvm/lib-tls.ts | 7 + .../src/frontend/lowering/lower-classes.ts | 8 +- .../src/frontend/lowering/lower-server.ts | 162 ++++++++- packages/compiler/src/ir/builtin-effects.ts | 2 + .../compiler/src/ir/builtin-signatures.ts | 14 + .../tests/corpus/7087-tls-socket-wrap.ts.json | 6 + .../7088-tls-socket-connect-tunnel.ts.json | 6 + .../7089-http-host-header-tunnels.ts.json | 6 + .../diagnostics/tls-socket-fences.ts.json | 6 + .../node-types/tls-socket-wrap.ts.json | 6 + packages/runtime/src/scr_http.c | 39 ++- packages/runtime/src/scr_net.c | 313 ++++++++++++++---- packages/runtime/src/scr_net.h | 24 ++ packages/runtime/src/scr_tls.c | 282 +++++++++++++++- packages/runtime/src/scr_tls.h | 9 + tests/corpus/7087-tls-socket-wrap.ts | 104 ++++++ .../corpus/7088-tls-socket-connect-tunnel.ts | 64 ++++ tests/corpus/7089-http-host-header-tunnels.ts | 31 ++ tests/diagnostics/tls-socket-fences.ts | 20 ++ tests/fixtures/node-types/tls-socket-wrap.ts | 31 ++ .../__snapshots__/tls-socket-fences.ts.txt | 26 ++ .../corpus-costs/7087-tls-socket-wrap.ts.json | 1 + .../7088-tls-socket-connect-tunnel.ts.json | 1 + .../7089-http-host-header-tunnels.ts.json | 1 + tests/harness/errors.test.ts | 50 +++ tests/harness/project-config.test.ts | 18 + 30 files changed, 1223 insertions(+), 113 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7087-tls-socket-wrap.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7088-tls-socket-connect-tunnel.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7089-http-host-header-tunnels.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/tls-socket-fences.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/tls-socket-wrap.ts.json create mode 100644 tests/corpus/7087-tls-socket-wrap.ts create mode 100644 tests/corpus/7088-tls-socket-connect-tunnel.ts create mode 100644 tests/corpus/7089-http-host-header-tunnels.ts create mode 100644 tests/diagnostics/tls-socket-fences.ts create mode 100644 tests/fixtures/node-types/tls-socket-wrap.ts create mode 100644 tests/harness/__snapshots__/tls-socket-fences.ts.txt create mode 100644 tests/harness/corpus-costs/7087-tls-socket-wrap.ts.json create mode 100644 tests/harness/corpus-costs/7088-tls-socket-connect-tunnel.ts.json create mode 100644 tests/harness/corpus-costs/7089-http-host-header-tunnels.ts.json diff --git a/docs/src/generated/node-v24-compatibility.json b/docs/src/generated/node-v24-compatibility.json index 682e68f99..1d9190afe 100644 --- a/docs/src/generated/node-v24-compatibility.json +++ b/docs/src/generated/node-v24-compatibility.json @@ -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" } }, { diff --git a/internal/compatibility/generated/node-v24-internal.json b/internal/compatibility/generated/node-v24-internal.json index a86967ff3..58deb8944 100644 --- a/internal/compatibility/generated/node-v24-internal.json +++ b/internal/compatibility/generated/node-v24-internal.json @@ -95421,7 +95421,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" @@ -96123,8 +96126,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" }, @@ -96911,8 +96919,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" }, diff --git a/internal/compatibility/static-support.json b/internal/compatibility/static-support.json index 6b3eaab4c..6a9a1dbad 100644 --- a/internal/compatibility/static-support.json +++ b/internal/compatibility/static-support.json @@ -369,6 +369,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"] }, diff --git a/packages/compiler/ambient/scriptc-node-fallback.d.ts b/packages/compiler/ambient/scriptc-node-fallback.d.ts index 936283d40..4e8fbde15 100644 --- a/packages/compiler/ambient/scriptc-node-fallback.d.ts +++ b/packages/compiler/ambient/scriptc-node-fallback.d.ts @@ -4858,8 +4858,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). */ @@ -4867,7 +4867,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; @@ -4883,7 +4891,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; @@ -4898,7 +4914,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; @@ -4949,9 +4973,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 @@ -4967,7 +4992,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( @@ -4980,7 +5005,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( @@ -5451,6 +5476,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 */ @@ -5462,6 +5488,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; @@ -5470,12 +5511,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; 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/frontend/lowering/lower-classes.ts b/packages/compiler/src/frontend/lowering/lower-classes.ts index 2a772ae25..d8ccc15b7 100644 --- a/packages/compiler/src/frontend/lowering/lower-classes.ts +++ b/packages/compiler/src/frontend/lowering/lower-classes.ts @@ -158,7 +158,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, @@ -9836,6 +9836,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. diff --git a/packages/compiler/src/frontend/lowering/lower-server.ts b/packages/compiler/src/frontend/lowering/lower-server.ts index 94d49d8b3..d9746e1f6 100644 --- a/packages/compiler/src/frontend/lowering/lower-server.ts +++ b/packages/compiler/src/frontend/lowering/lower-server.ts @@ -2939,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. @@ -2962,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( @@ -4676,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 @@ -4985,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); } @@ -5043,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; diff --git a/packages/compiler/src/ir/builtin-effects.ts b/packages/compiler/src/ir/builtin-effects.ts index dd82d06c2..9f604e408 100644 --- a/packages/compiler/src/ir/builtin-effects.ts +++ b/packages/compiler/src/ir/builtin-effects.ts @@ -230,6 +230,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 diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index 8f5928d12..bcf467111 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -2182,6 +2182,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 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/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/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/runtime/src/scr_http.c b/packages/runtime/src/scr_http.c index d9876c30b..a5847e59b 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)) { diff --git a/packages/runtime/src/scr_net.c b/packages/runtime/src/scr_net.c index f091daede..8f9a68424 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,71 @@ 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->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 +5425,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 +5445,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 +5690,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..8f26bbf4d 100644 --- a/packages/runtime/src/scr_net.h +++ b/packages/runtime/src/scr_net.h @@ -351,8 +351,19 @@ 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); } 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 +377,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 +399,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_tls.c b/packages/runtime/src/scr_tls.c index b4d125cb2..6fa1f169d 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,14 @@ 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; } ScrTlsSock; /* checkServerIdentity for an IP literal: the address must be one of the @@ -703,6 +738,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 +755,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 +1075,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 +1132,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 +1223,20 @@ 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); +} + static const ScrNetTransportOps SCR_TLS_OPS = { .xread = scr_tls_xread, .xwrite = scr_tls_xwrite, @@ -1146,6 +1245,7 @@ static const ScrNetTransportOps SCR_TLS_OPS = { .pending = scr_tls_pending, .shutdown_write = scr_tls_shutdown_write, .free = scr_tls_free, + .after_established = scr_tls_after_established, }; /* ── the server surface ──────────────────────────────────────────────── */ @@ -2088,6 +2188,101 @@ 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, +}; + +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 */ + 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; + } + 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 +2434,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 +2450,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 +2518,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 +2538,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 +2566,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 +2582,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 +2592,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 +2621,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 +2839,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) { + 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) { @@ -2660,9 +2916,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/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/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/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/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/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/errors.test.ts b/tests/harness/errors.test.ts index 00ee40043..96949201d 100644 --- a/tests/harness/errors.test.ts +++ b/tests/harness/errors.test.ts @@ -855,6 +855,56 @@ try { }); }); +// 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", + ); + }); +}); + // 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). diff --git a/tests/harness/project-config.test.ts b/tests/harness/project-config.test.ts index 8532ad6e9..7a916b4dd 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"); From c09801c06402160567da0632419460a038ae1546 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 05:08:24 -0500 Subject: [PATCH 058/102] Map a JS binding's declared type only for a nullish write --- packages/compiler/src/frontend/lowering/lower-stmts.ts | 10 ++++++---- packages/compiler/src/frontend/lowering/lowerer.ts | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/compiler/src/frontend/lowering/lower-stmts.ts b/packages/compiler/src/frontend/lowering/lower-stmts.ts index 2840b0b45..687420baf 100644 --- a/packages/compiler/src/frontend/lowering/lower-stmts.ts +++ b/packages/compiler/src/frontend/lowering/lower-stmts.ts @@ -6119,14 +6119,16 @@ export function jsBindingHasOpenWrites(lowerer: Lowerer, decl: ts.VariableDeclar // types as a primitive (`offset = match[3] || null`): JavaScript files // are checked without strict null checks, so the declared type does not // admit them. - const primitive = lowerer.mapTypeOf(lowerer.typeOf(decl.name)); + // The declared type is mapped only when such a write exists. if ( - (primitive?.kind === "string" || primitive?.kind === "f64" || primitive?.kind === "bool") && candidates.some( (node) => node.operatorToken.kind === ts.SyntaxKind.EqualsToken && mayBeNullish(node.right), ) - ) - return true; + ) { + 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; diff --git a/packages/compiler/src/frontend/lowering/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index f3ab173f8..edf0a694b 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -3596,7 +3596,7 @@ export class Lowerer { this.genericClassInstanceType(decl, ref, mapArgument), runtimeClassValue: (type) => runtimeClassValueOfType(this, type), localClassValue: (type) => - this.instanceResultClass?.declared === type.id + this.instanceResultClass !== null && this.instanceResultClass.declared === type.id ? this.instanceResultClass.value : (this.localClassValueTypes.get(type.id) ?? null), mixinClassInstance: (decl) => From 1917d1aa003b40808bc5fe2001e8174f2356f62a Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 05:25:02 -0500 Subject: [PATCH 059/102] Test an array read's hole-free prefix before its capacity The dense path of an element read that may be undefined (the `%arr.idxOr` reads behind `a[i]` as `T | undefined`, the store `a[x] = a[y]!`, and the element reads of the lowered array methods) tested the index against the capacity, then against the hole-free prefix (`filled`), and only above the prefix against the length and the slot's state. `filled` is at most the length and the capacity (scr_array.h), so an index below it needs no other test: the read now tests `filled` first and takes the value path on that test alone. Above the prefix it tests the capacity, the length and the state as before. A double index first branches to the runtime lookup when it is not an exact integer, then takes the same tests on its i64 value, which a 32-bit target compares before truncating it. --- .../backend/llvm/local-array-reads.test.ts | 15 +++ .../src/backend/llvm/local-array-reads.ts | 115 +++++++++--------- .../7142-array-read-filled-prefix.ts.json | 6 + tests/corpus/7142-array-read-filled-prefix.ts | 72 +++++++++++ .../7142-array-read-filled-prefix.ts.json | 1 + 5 files changed, 153 insertions(+), 56 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7142-array-read-filled-prefix.ts.json create mode 100644 tests/corpus/7142-array-read-filled-prefix.ts create mode 100644 tests/harness/corpus-costs/7142-array-read-filled-prefix.ts.json 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..b09029865 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,18 @@ 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); + } +}); diff --git a/packages/compiler/src/backend/llvm/local-array-reads.ts b/packages/compiler/src/backend/llvm/local-array-reads.ts index b9fd0f54b..45d046e1f 100644 --- a/packages/compiler/src/backend/llvm/local-array-reads.ts +++ b/packages/compiler/src/backend/llvm/local-array-reads.ts @@ -12,7 +12,7 @@ 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"; @@ -472,78 +472,81 @@ function emitDenseReferenceArrayRead( loadType: "ptr" | "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"); 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/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/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 } From 9893630810a26ae8f5ed817108027153a8d74ca3 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 05:26:43 -0500 Subject: [PATCH 060/102] Skip declaration files when looking for writes to a narrowed binding Narrowing stability looked for writes to a binding by walking the whole file that declares it. For globals such as `console` and `JSON` that file is a declaration file (scriptc-node-fallback.d.ts, lib.es5.d.ts), so every build that read one of them materialized about 46,000 AST nodes and kept them until the end of the build. A declaration file holds no code that runs, so none of its writes happen: the walk now returns no writes for it. --- .../compiler/src/frontend/lowering/narrowing-stability.ts | 4 ++++ 1 file changed, 4 insertions(+) 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; From 999fef551e00eb746f3b1a84745ccafb89e0aaf9 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 05:27:07 -0500 Subject: [PATCH 061/102] Resolve repeated checker objects from their ids without decoding them Checker replies name every type, symbol and signature they reach in full, and most of them are objects the client already holds: building tsc-ts, 96% of the types, 79% of the symbols and 80% of the signatures in replies are cached by id. Object replies are now read as bytes, each element's extent is found by a scan that skips strings, and an element whose leading "id" is cached resolves to the cached object without its text being decoded. The other elements are parsed as before. --- .../compiler/src/frontend/ts7/checker.test.ts | 15 +- .../src/frontend/ts7/semantic-checker.ts | 33 ++-- .../src/frontend/ts7/semantic-json.test.ts | 79 ++++++++- .../src/frontend/ts7/semantic-json.ts | 153 ++++++++++++++++++ .../src/frontend/ts7/semantic-model.test.ts | 5 +- .../src/frontend/ts7/semantic-model.ts | 90 ++++++++--- 6 files changed, 326 insertions(+), 49 deletions(-) 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/semantic-checker.ts b/packages/compiler/src/frontend/ts7/semantic-checker.ts index 92aa77333..5e7f8339a 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"; @@ -106,32 +105,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; @@ -375,11 +367,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); From 6bf3b7d9df9b0a9c506392570f2fb8bece333ffb Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 05:44:28 -0500 Subject: [PATCH 062/102] Install driver-built translation units before the native build The private copy of the LLVM text had no extension. Builds that compile it with the C driver (sanitize builds, targets without the LLVM helper) passed it to clang directly when the native cache was off, and clang read it as a linker input, so the build failed. The copy is now named with `.ll`. Those builds also record the output directory in their native cache proof. Renaming the private copies to the shared names after the native build changed that directory, so every unchanged repeat missed the proof and relinked the executable. The shared names are now installed before the native build, which compiles and caches copies in a private directory outside the output directory. --- packages/cli/test/executable-cache.test.ts | 56 +++++++++++++- .../src/executable/executable-cache.test.ts | 2 +- .../src/executable/executable-cache.ts | 3 +- packages/compiler/src/index.ts | 77 +++++++++++++++++-- 4 files changed, 127 insertions(+), 11 deletions(-) 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/compiler/src/executable/executable-cache.test.ts b/packages/compiler/src/executable/executable-cache.test.ts index e7c57d1b0..2de688531 100644 --- a/packages/compiler/src/executable/executable-cache.test.ts +++ b/packages/compiler/src/executable/executable-cache.test.ts @@ -137,7 +137,7 @@ test("early executable cache restores the emitted TU, IR, and native feature gat // them there when it is done. expect(hit?.llvmPath).toBe(f.llvmPath); expect(hit?.irPath).toBe(f.irPath); - expect(hit?.llvmSourcePath).toMatch(/[/\\]\.scriptc-llvm-/); + 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"); diff --git a/packages/compiler/src/executable/executable-cache.ts b/packages/compiler/src/executable/executable-cache.ts index 941a7acdc..be94efb0b 100644 --- a/packages/compiler/src/executable/executable-cache.ts +++ b/packages/compiler/src/executable/executable-cache.ts @@ -615,7 +615,8 @@ async function readExecutableCache( ) await installBytes(ir, paths.irPath); } else { - llvmSourcePath = privateSiblingPath(paths.llvmPath, "llvm"); + // 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) { diff --git a/packages/compiler/src/index.ts b/packages/compiler/src/index.ts index db1b0b3e3..7d6ab9b6d 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 { @@ -850,7 +851,8 @@ async function prepareExecutableInput( await mkdir(opts.outDir, { recursive: true }); const llvmPath = defaultSourcePaths.llvm; - const llvmSourcePath = privateSiblingPath(llvmPath, "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); @@ -912,6 +914,8 @@ async function prepareExecutableInput( * 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; @@ -941,6 +945,40 @@ async function installBuildSources(sources: BuildSources): Promise { ]); } +/** + * 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 }, + }; +} + /** * The child process that prepares an executable build's input: frontend, lowering and LLVM emission * (`runFrontendProcess`). Node's heap keeps the pages a build's frontend used for the life of the @@ -1515,6 +1553,9 @@ async function compileTracked( 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 = @@ -1545,6 +1586,11 @@ async function compileTracked( sourceTexts: new Map(), }; } + } else { + const staged = await stageDriverBuildSources(hitSources); + stagedDir = staged.dir; + nativeSources = staged.sources; + nativeInputPath = nativeSources.llvmSourcePath; } await compileExecutableNative( earlyHit.native, @@ -1561,10 +1607,10 @@ async function compileTracked( : async ({ dependencies }) => { await publishEarlyExecutableCache(cacheRoot, executableCacheOptions, { ...earlyHit, - llvmPath: hitSources.llvmSourcePath, - ...(hitSources.irSourcePath === undefined + llvmPath: nativeSources.llvmSourcePath, + ...(nativeSources.irSourcePath === undefined ? {} - : { irPath: hitSources.irSourcePath }), + : { irPath: nativeSources.irSourcePath }), executableRestored: true, nativeDependencies: dependencies, frontend: earlyHit.frontend, @@ -1602,7 +1648,8 @@ async function compileTracked( nativeProgramObject.partitionPaths, ); } - await installBuildSources(hitSources); + if (stagedDir === null) await installBuildSources(hitSources); + else await rm(stagedDir, { recursive: true, force: true }); } await pruneBuildCache(cacheRoot); return { @@ -1635,8 +1682,17 @@ async function compileTracked( ) : await prepareExecutableInput(entryPath, opts, ffi, buildPlatform, timing, warningSink); if ("ok" in prepared) return prepared; - const { llvmSource, llvmPath, llvmSourcePath, irPath, irSourcePath } = 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) { @@ -1668,6 +1724,10 @@ async function compileTracked( sourceTexts, }; } + } else { + const staged = await stageDriverBuildSources(buildSources); + stagedDir = staged.dir; + ({ llvmSourcePath, irSourcePath } = staged.sources); } await compileExecutableNative( nativeFeatures, @@ -1732,7 +1792,8 @@ async function compileTracked( nativeProgramObject.partitionPaths, ); } - await installBuildSources({ llvmPath, llvmSourcePath, irPath, irSourcePath }); + if (stagedDir === null) await installBuildSources(buildSources); + else await rm(stagedDir, { recursive: true, force: true }); } await pruneBuildCache(cacheRoot); timing("complete"); From 6f11afa09e85010c6b15c3e515b93d160d3379a5 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 05:46:53 -0500 Subject: [PATCH 063/102] Size crypto error messages to their whole text The key and signature errors formatted into fixed stack buffers and passed snprintf's return value on as the message length. A message longer than the buffer, such as "Invalid digest: " with a long algorithm name from crypto.sign or crypto.verify, then copied bytes past the end of the buffer into the error. The messages are now sized to their whole text, so a long name appears in full, as in Node. The received values in these messages also follow Node: strings as util.inspect quotes them, cut at 128 characters, and large integers with ERR_OUT_OF_RANGE's separators. A fractional, NaN or infinite modulusLength reports "It must be an integer", as validateUint32 does. --- packages/runtime/src/scr_pki.c | 98 +++++++++++++++--------- packages/runtime/src/scr_pki.h | 4 + packages/runtime/src/scr_webcrypto_pki.c | 10 +-- tests/corpus/7083-crypto-sign-verify.ts | 3 + tests/corpus/7084-crypto-key-pairs.cjs | 14 ++++ 5 files changed, 86 insertions(+), 43 deletions(-) diff --git a/packages/runtime/src/scr_pki.c b/packages/runtime/src/scr_pki.c index 1b102fd22..54aadc06b 100644 --- a/packages/runtime/src/scr_pki.c +++ b/packages/runtime/src/scr_pki.c @@ -12,6 +12,8 @@ * All arguments are borrowed. */ #include "scr_runtime.h" +#include +#include #include #include #include @@ -37,14 +39,41 @@ 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) { - char lite[96]; - char message[256]; - int n = snprintf(message, sizeof message, "The property '%s' is invalid. Received %s", name, - scr_dyn_inspect_lite(got, lite, sizeof lite)); - scr_throw_error_msg_code(SCR_ERR_TYPE, message, (size_t)n, "ERR_INVALID_ARG_VALUE"); + 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) { @@ -53,10 +82,8 @@ static void sp_unsupported_input(void) { /* The coded refusal for a form this runtime does not implement. */ static void sp_not_supported(const char *what) { - char message[256]; - int n = snprintf(message, sizeof message, - "'%s' is part of the standard library types but has no scriptc lowering yet", what); - scr_throw_error_msg_code(SCR_ERR_ERROR, message, (size_t)n, "SC2020"); + 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) { @@ -1066,9 +1093,7 @@ static ScrDyn *sp_key_invoke(void *h, ScrDyn *self, const char *method, ScrDyn * sp_not_supported("KeyObject.toCryptoKey"); return NULL; } - char message[160]; - int n = snprintf(message, sizeof message, "%s is not a function", what); - scr_throw_error_msg(SCR_ERR_TYPE, message, (size_t)n); + scr_pki_throw_fmt(SCR_ERR_TYPE, NULL, "%s is not a function", what); return NULL; } @@ -1093,10 +1118,8 @@ static bool sp_key_set(void *h, const char *name, size_t len, const ScrDyn *valu ? "AsymmetricKeyObject" : NULL; if (!holder) return false; - char message[160]; - int n = snprintf(message, sizeof message, "Cannot set property %.*s of #<%s> which has only a getter", - (int)len, name, holder); - scr_throw_error_msg(SCR_ERR_TYPE, message, (size_t)n); + 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; } @@ -1210,12 +1233,11 @@ static SpKey *sp_generate(const ScrDyn *type, const ScrDyn *options) { 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) { - char lite[96]; - char message[200]; - int n = snprintf(message, sizeof message, - "The argument 'type' must be a supported key type. Received %s", - scr_dyn_inspect_lite(type, lite, sizeof lite)); - scr_throw_error_msg_code(SCR_ERR_TYPE, message, (size_t)n, "ERR_INVALID_ARG_VALUE"); + 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. */ @@ -1252,14 +1274,15 @@ static SpKey *sp_generate(const ScrDyn *type, const ScrDyn *options) { return NULL; } double b = bits->v.num; - if (b != b || b < 0 || b > 4294967295.0 || b != (double)(uint64_t)b) { + /* 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); - char message[160]; - char lite[64]; - int n = snprintf(message, sizeof message, - "The value of \"options.modulusLength\" is out of range. It must be >= 0 && <= 4294967295. Received %s", - scr_dyn_inspect_lite(bits, lite, sizeof lite)); - scr_throw_error_msg_code(SCR_ERR_RANGE, message, (size_t)n, "ERR_OUT_OF_RANGE"); + 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"); @@ -1404,10 +1427,15 @@ static bool sp_algorithm(const ScrDyn *alg, mbedtls_md_type_t *md) { return false; } if (!sp_digest_of(alg->v.str, md)) { - char message[160]; - int n = snprintf(message, sizeof message, "Invalid digest: %.*s", (int)alg->v.str->len, - alg->v.str->data); - scr_throw_error_msg_code(SCR_ERR_TYPE, message, (size_t)n, "ERR_CRYPTO_INVALID_DIGEST"); + /* 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; @@ -1799,9 +1827,7 @@ static ScrDyn *sp_signer_invoke(void *h, ScrDyn *self, const char *method, ScrDy sp_key_release(k.key); return scr_dyn_new_bool(ok); } - char message[160]; - int n = snprintf(message, sizeof message, "%s is not a function", what); - scr_throw_error_msg(SCR_ERR_TYPE, message, (size_t)n); + scr_pki_throw_fmt(SCR_ERR_TYPE, NULL, "%s is not a function", what); return NULL; } diff --git a/packages/runtime/src/scr_pki.h b/packages/runtime/src/scr_pki.h index e299806f7..71be3c1df 100644 --- a/packages/runtime/src/scr_pki.h +++ b/packages/runtime/src/scr_pki.h @@ -12,6 +12,10 @@ 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. */ diff --git a/packages/runtime/src/scr_webcrypto_pki.c b/packages/runtime/src/scr_webcrypto_pki.c index e913b1dc6..7439a12db 100644 --- a/packages/runtime/src/scr_webcrypto_pki.c +++ b/packages/runtime/src/scr_webcrypto_pki.c @@ -115,10 +115,8 @@ static bool sw_key_set(void *h, const char *name, size_t len, const ScrDyn *valu 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; - char message[128]; - int n = snprintf(message, sizeof message, "Cannot set property %.*s of # which has only a getter", - (int)len, name); - scr_throw_error_msg(SCR_ERR_TYPE, message, (size_t)n); + scr_pki_throw_fmt(SCR_ERR_TYPE, NULL, "Cannot set property %.*s of # which has only a getter", (int)len, + name); return true; } @@ -129,9 +127,7 @@ static ScrDyn *sw_key_invoke(void *h, ScrDyn *self, const char *method, ScrDyn * (void)args; (void)argc; if (strcmp(method, "toString") == 0) return scr_wc_cstr("[object CryptoKey]"); - char message[160]; - int n = snprintf(message, sizeof message, "%s is not a function", what); - scr_throw_error_msg(SCR_ERR_TYPE, message, (size_t)n); + scr_pki_throw_fmt(SCR_ERR_TYPE, NULL, "%s is not a function", what); return NULL; } diff --git a/tests/corpus/7083-crypto-sign-verify.ts b/tests/corpus/7083-crypto-sign-verify.ts index 437dc1640..4f6b86e72 100644 --- a/tests/corpus/7083-crypto-sign-verify.ts +++ b/tests/corpus/7083-crypto-sign-verify.ts @@ -80,6 +80,9 @@ 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 index ed4db0310..ca267d89f 100644 --- a/tests/corpus/7084-crypto-key-pairs.cjs +++ b/tests/corpus/7084-crypto-key-pairs.cjs @@ -50,6 +50,20 @@ attempt("unknown curve", () => crypto.generateKeyPairSync("ec", { namedCurve: "n 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) => { From 01a467060b1ee76dac71a6fc0e77bc599150ecc3 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 05:48:30 -0500 Subject: [PATCH 064/102] Support WebCrypto wrapKey and unwrapKey crypto.subtle.wrapKey exports a secret key (raw, raw-secret or jwk) and encrypts it, and unwrapKey decrypts and imports one, as Node's webcrypto.js does: the wrap algorithm normalizes through the wrapKey registry (AES-KW) and then the encrypt registry (AES-GCM, AES-CBC and AES-CTR with their dictionaries), the wrapping key's algorithm and usages are checked, and a JWK payload is its JSON text, padded with spaces to a multiple of 8 bytes for AES-KW. A wrapped JWK that is not UTF-8 JSON with a kty member rejects with Node's DataError. AES-KW is RFC 3394 key wrap over the vendored mbedTLS block cipher, in scr_webcrypto_aes.c beside the other AES modes: wrapping takes a multiple of 8 bytes and at least 16, unwrapping a multiple of 8 and at least 24, and the integrity check value is compared in constant time. The cipher's failures, and unwrapKey's import errors, reject on a later loop turn as Node's job promises do. This completes jose's symmetric key management: 7132 runs the real jose 6.2.12 PBES2-HS256+A128KW, PBES2-HS384+A192KW, PBES2-HS512+A256KW, A128KW and A256KW paths (EncryptJWT and jwtDecrypt) against Node. getPublicKey replaces wrapKey as the refused method in the fenced fixture and the JavaScript refusal test. --- .../limitations/builtin-apis/crypto.mdx | 2 +- .../src/generated/node-v24-compatibility.json | 12 +- .../generated/node-v24-internal.json | 77 +- internal/compatibility/static-support.json | 4 +- .../ambient/scriptc-node-fallback.d.ts | 18 +- .../compiler/src/backend/llvm/lib-shared.ts | 4 + .../src/backend/target-diagnostics.ts | 9 +- .../frontend/lowering/builtins/webcrypto.ts | 8 +- .../src/frontend/lowering/surfaces.ts | 4 +- .../compiler/src/ir/builtin-signatures.ts | 2 + packages/compiler/src/ir/runtime-features.ts | 18 +- packages/compiler/surface-manifest.json | 2 +- .../corpus/7130-webcrypto-wrap-key.ts.json | 6 + .../7131-webcrypto-wrap-key-errors.mjs.json | 6 + .../corpus/7132-jose-pbes2/main.mjs.json | 6 + packages/runtime/src/scr_crypto.h | 7 + packages/runtime/src/scr_webcrypto.c | 317 ++++++-- packages/runtime/src/scr_webcrypto_aes.c | 67 ++ tests/corpus/7130-webcrypto-wrap-key.ts | 69 ++ .../corpus/7131-webcrypto-wrap-key-errors.mjs | 65 ++ tests/corpus/7132-jose-pbes2/main.mjs | 50 ++ .../node_modules/jose/LICENSE.md | 21 + .../jose/dist/types/jwt/decrypt.d.ts | 34 + .../jose/dist/types/jwt/encrypt.d.ts | 57 ++ .../node_modules/jose/dist/types/types.d.ts | 736 ++++++++++++++++++ .../jose/dist/types/util/errors.d.ts | 182 +++++ .../jose/dist/webapi/jwt/decrypt.js | 13 + .../jose/dist/webapi/jwt/encrypt.js | 45 ++ .../jose/dist/webapi/lib/buffer_utils.js | 75 ++ .../dist/webapi/lib/content_encryption.js | 90 +++ .../jose/dist/webapi/lib/deflate.js | 40 + .../jose/dist/webapi/lib/jwe_algorithms.js | 116 +++ .../jose/dist/webapi/lib/jwe_decrypt.js | 187 +++++ .../jose/dist/webapi/lib/jwe_encrypt.js | 75 ++ .../jose/dist/webapi/lib/jwt_claims_set.js | 146 ++++ .../node_modules/jose/dist/webapi/lib/key.js | 155 ++++ .../jose/dist/webapi/lib/key_descriptor.js | 9 + .../jose/dist/webapi/lib/key_management.js | 196 +++++ .../jose/dist/webapi/lib/validate.js | 122 +++ .../jose/dist/webapi/util/base64url.js | 16 + .../jose/dist/webapi/util/errors.js | 109 +++ .../node_modules/jose/package.json | 17 + tests/fixtures/node-types/fenced.ts | 8 +- .../__snapshots__/node-types-fenced.txt | 10 +- .../__snapshots__/webcrypto-refusals.ts.txt | 4 +- .../7130-webcrypto-wrap-key.ts.json | 1 + .../7131-webcrypto-wrap-key-errors.mjs.json | 1 + .../7132-jose-pbes2/main.mjs.json | 1 + tests/harness/errors.test.ts | 12 +- 49 files changed, 3139 insertions(+), 92 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7130-webcrypto-wrap-key.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7131-webcrypto-wrap-key-errors.mjs.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7132-jose-pbes2/main.mjs.json create mode 100644 tests/corpus/7130-webcrypto-wrap-key.ts create mode 100644 tests/corpus/7131-webcrypto-wrap-key-errors.mjs create mode 100644 tests/corpus/7132-jose-pbes2/main.mjs create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/LICENSE.md create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/jwt/decrypt.d.ts create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/jwt/encrypt.d.ts create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/types.d.ts create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/util/errors.d.ts create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/jwt/decrypt.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/jwt/encrypt.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/buffer_utils.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/content_encryption.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/deflate.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_algorithms.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_decrypt.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_encrypt.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key_descriptor.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key_management.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/validate.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/util/base64url.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/util/errors.js create mode 100644 tests/corpus/7132-jose-pbes2/node_modules/jose/package.json create mode 100644 tests/harness/corpus-costs/7130-webcrypto-wrap-key.ts.json create mode 100644 tests/harness/corpus-costs/7131-webcrypto-wrap-key-errors.mjs.json create mode 100644 tests/harness/corpus-costs/7132-jose-pbes2/main.mjs.json diff --git a/docs/content/limitations/builtin-apis/crypto.mdx b/docs/content/limitations/builtin-apis/crypto.mdx index 641d0d8f9..2cb0db5f0 100644 --- a/docs/content/limitations/builtin-apis/crypto.mdx +++ b/docs/content/limitations/builtin-apis/crypto.mdx @@ -20,6 +20,6 @@ ECDH property reads and writes throw a coded SC2020 error. Other public-key operations 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 on native targets, `deriveBits()` and `deriveKey()` with PBKDF2 and HKDF, HMAC `sign()` and `verify()`, and SHA-1 and SHA-2 `digest()`. + 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()` 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; other SubtleCrypto methods, algorithms, and key formats are refused. Native derivations finish before their deferred callbacks, so computation blocks the caller. diff --git a/docs/src/generated/node-v24-compatibility.json b/docs/src/generated/node-v24-compatibility.json index 682e68f99..628c267be 100644 --- a/docs/src/generated/node-v24-compatibility.json +++ b/docs/src/generated/node-v24-compatibility.json @@ -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 a86967ff3..83b4c5691 100644 --- a/internal/compatibility/generated/node-v24-internal.json +++ b/internal/compatibility/generated/node-v24-internal.json @@ -106677,6 +106677,9 @@ "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", @@ -110549,6 +110552,9 @@ "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", @@ -110587,6 +110593,9 @@ "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", @@ -110625,6 +110634,9 @@ "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", @@ -110663,6 +110675,9 @@ "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", @@ -110747,6 +110762,9 @@ "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", @@ -110785,6 +110803,9 @@ "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", @@ -110846,6 +110867,9 @@ "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", @@ -110884,6 +110908,9 @@ "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", @@ -110922,6 +110949,9 @@ "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", @@ -110957,8 +110987,26 @@ "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" + ] }, "anchorSource": "exact" }, @@ -110983,6 +111031,9 @@ "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", @@ -111018,8 +111069,26 @@ "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" + ] }, "anchorSource": "exact" }, diff --git a/internal/compatibility/static-support.json b/internal/compatibility/static-support.json index 6b3eaab4c..568dbbf0d 100644 --- a/internal/compatibility/static-support.json +++ b/internal/compatibility/static-support.json @@ -187,14 +187,14 @@ "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/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.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.generateKey", "subtle.exportKey", "subtle.encrypt", "subtle.decrypt", "subtle.deriveBits", "subtle.deriveKey", "subtle.sign", "subtle.verify", "subtle.digest"], "status": "partial", "evidence": ["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"] }, + { "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"] }, { "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/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"] }, diff --git a/packages/compiler/ambient/scriptc-node-fallback.d.ts b/packages/compiler/ambient/scriptc-node-fallback.d.ts index 936283d40..1e40b6f6f 100644 --- a/packages/compiler/ambient/scriptc-node-fallback.d.ts +++ b/packages/compiler/ambient/scriptc-node-fallback.d.ts @@ -547,7 +547,8 @@ declare var DOMException: { /* WebCrypto's secret-key slice (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, - * PBKDF2 and HKDF deriveBits and deriveKey, HMAC sign/verify and the SHA-1/SHA-2 digests, typed as + * wrapKey and unwrapKey (AES-KW or those ciphers), PBKDF2 and HKDF + * deriveBits and deriveKey, HMAC sign/verify 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 @@ -707,12 +708,27 @@ interface SubtleCrypto { keyUsages: readonly KeyUsage[], ): Promise; sign(algorithm: AlgorithmIdentifier, 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; verify( algorithm: AlgorithmIdentifier, 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; diff --git a/packages/compiler/src/backend/llvm/lib-shared.ts b/packages/compiler/src/backend/llvm/lib-shared.ts index c08d7b720..8805d7e0c 100644 --- a/packages/compiler/src/backend/llvm/lib-shared.ts +++ b/packages/compiler/src/backend/llvm/lib-shared.ts @@ -620,6 +620,8 @@ export const LIB_FN_SYMS: Record = { "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", @@ -1595,6 +1597,8 @@ export const USES_TIMERS_LIB_FNS = new Set([ "webcrypto.generateKey", "webcrypto.encrypt", "webcrypto.decrypt", + "webcrypto.wrapKey", + "webcrypto.unwrapKey", "webcrypto.deriveBits", "webcrypto.deriveKey", "webcrypto.sign", diff --git a/packages/compiler/src/backend/target-diagnostics.ts b/packages/compiler/src/backend/target-diagnostics.ts index eb70a0d2c..bd901341e 100644 --- a/packages/compiler/src/backend/target-diagnostics.ts +++ b/packages/compiler/src/backend/target-diagnostics.ts @@ -208,10 +208,15 @@ export function moduleWasiUnavailableSurface( }; return false; } - if (node.fn === "webcrypto.encrypt" || node.fn === "webcrypto.decrypt") { + if ( + node.fn === "webcrypto.encrypt" || + node.fn === "webcrypto.decrypt" || + node.fn === "webcrypto.wrapKey" || + node.fn === "webcrypto.unwrapKey" + ) { found = { surface: - "WebCrypto encrypt and decrypt (the wasm32-wasi runtime does not include the mbedTLS library)", + "WebCrypto encrypt, decrypt, wrapKey and unwrapKey (the wasm32-wasi runtime does not include the mbedTLS library)", loc, }; return false; diff --git a/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts b/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts index fe310294c..e4f1f0955 100644 --- a/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts +++ b/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts @@ -9,8 +9,8 @@ import { isWebCryptoReceiver } from "./crypto.js"; /* WebCrypto's secret-key slice (scr_webcrypto.c, with encrypt and * decrypt in scr_webcrypto_aes.c): `crypto.subtle`'s `importKey`, - * `generateKey`, `exportKey`, `encrypt`, `decrypt`, `deriveBits`, - * `deriveKey`, `sign`, `verify` and `digest` + * `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 @@ -25,6 +25,8 @@ const SUBTLE_LOWERED: ReadonlyMap = new Map([ ["exportKey", "webcrypto.exportKey"], ["encrypt", "webcrypto.encrypt"], ["decrypt", "webcrypto.decrypt"], + ["wrapKey", "webcrypto.wrapKey"], + ["unwrapKey", "webcrypto.unwrapKey"], ["deriveBits", "webcrypto.deriveBits"], ["deriveKey", "webcrypto.deriveKey"], ["sign", "webcrypto.sign"], @@ -33,7 +35,7 @@ const SUBTLE_LOWERED: ReadonlyMap = new Map([ ]); const 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, deriveBits and deriveKey with PBKDF2 or HKDF, 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 with AES-KW or those ciphers, deriveBits and deriveKey with PBKDF2 or HKDF, sign and verify with HMAC, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle"; /** Whether `node` is a SubtleCrypto object: `subtle` on a WebCrypto * Crypto object (the global, globalThis.crypto or node:crypto's diff --git a/packages/compiler/src/frontend/lowering/surfaces.ts b/packages/compiler/src/frontend/lowering/surfaces.ts index bb9a6c062..6179f8c78 100644 --- a/packages/compiler/src/frontend/lowering/surfaces.ts +++ b/packages/compiler/src/frontend/lowering/surfaces.ts @@ -2216,13 +2216,15 @@ export const AMBIENT_SURFACE_FNS: readonly AmbientSurfaceRow[] = [ "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, PBKDF2 and HKDF deriveBits and deriveKey, 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 with AES-KW or those ciphers, PBKDF2 and HKDF deriveBits and deriveKey, HMAC sign and verify, and SHA-1/SHA-2 digest; other methods, algorithms and key formats are refused", }, { id: "stdlib.webcrypto.CryptoKey", diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index 8f5928d12..380c7cb7c 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -2862,6 +2862,8 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "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 } }, diff --git a/packages/compiler/src/ir/runtime-features.ts b/packages/compiler/src/ir/runtime-features.ts index 9531d7845..5c60eb54f 100644 --- a/packages/compiler/src/ir/runtime-features.ts +++ b/packages/compiler/src/ir/runtime-features.ts @@ -650,9 +650,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. WebCrypto's encrypt and decrypt (scr_webcrypto_aes.c) - * link the same archive. */ - cipher: rule({ fns: ["crypto.cipherNew", "webcrypto.encrypt", "webcrypto.decrypt"] }), + * 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)) || @@ -688,6 +696,8 @@ const RUNTIME_FEATURE_RULES = { "crypto.cipherNew", "webcrypto.encrypt", "webcrypto.decrypt", + "webcrypto.wrapKey", + "webcrypto.unwrapKey", "crypto.ecdhNew", ], prefixes: [...READABLE_DYN_ASYNC_PREFIXES, "wasm."], @@ -796,6 +806,8 @@ const RUNTIME_FEATURE_RULES = { "crypto.cipherNew", "webcrypto.encrypt", "webcrypto.decrypt", + "webcrypto.wrapKey", + "webcrypto.unwrapKey", "crypto.ecdhNew", "crypto.ecdhConvertKey", ...BUILTIN_CLASS_LIB_FNS, diff --git a/packages/compiler/surface-manifest.json b/packages/compiler/surface-manifest.json index 3e8b9df73..02b1181b5 100644 --- a/packages/compiler/surface-manifest.json +++ b/packages/compiler/surface-manifest.json @@ -5718,7 +5718,7 @@ "kind": "stdlib", "name": "globalThis.crypto.subtle", "status": "static", - "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, PBKDF2 and HKDF deriveBits and deriveKey, 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 with AES-KW or those ciphers, PBKDF2 and HKDF deriveBits and deriveKey, HMAC sign and verify, and SHA-1/SHA-2 digest; other methods, algorithms and key formats are refused" }, { "id": "syntax.async-generators", 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-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/runtime/src/scr_crypto.h b/packages/runtime/src/scr_crypto.h index ddc306598..99d8b85bc 100644 --- a/packages/runtime/src/scr_crypto.h +++ b/packages/runtime/src/scr_crypto.h @@ -241,6 +241,13 @@ typedef ScrBytes *(*ScrWebCryptoAesFn)(const char *name, bool decrypt, const uns 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 diff --git a/packages/runtime/src/scr_webcrypto.c b/packages/runtime/src/scr_webcrypto.c index 4d2c27be4..fc6941e36 100644 --- a/packages/runtime/src/scr_webcrypto.c +++ b/packages/runtime/src/scr_webcrypto.c @@ -104,7 +104,7 @@ static const char *scr_wc_native_hash(const char *name) { /* ── errors ────────────────────────────────────────────────────────── */ -static const char *const scr_wc_ordinals[] = {"1st", "2nd", "3rd", "4th", "5th"}; +static const char *const scr_wc_ordinals[] = {"1st", "2nd", "3rd", "4th", "5th", "6th", "7th"}; static void scr_wc_type_error(const char *code, const char *fmt, ...) __attribute__((format(printf, 2, 3))); @@ -1151,6 +1151,47 @@ done: 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 }. */ static ScrDyn *scr_wc_export(const ScrDyn *args) { @@ -1166,30 +1207,11 @@ static ScrDyn *scr_wc_export(const ScrDyn *args) { scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type CryptoKey.", prefix); goto done; } - 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); - goto done; - } - if (!key->extractable) { - scr_throw_domex("InvalidAccessError", "key is not extractable"); - goto done; - } - if (strcmp(format, "raw") == 0 || strcmp(format, "raw-secret") == 0) { - ScrBytes *bytes = scr_bytes_new(SCR_BYTES_U8, (double)key->len); - if (key->len) memcpy(bytes->data, key->data, key->len); - result = scr_array_buffer_from_bytes(bytes); - scr_bytes_release(bytes); - } else if (strcmp(format, "jwk") == 0) { + 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); - ScrBytes *bytes = scr_bytes_new(SCR_BYTES_U8, (double)key->len); - if (key->len) memcpy(bytes->data, key->data, key->len); - ScrStr *encoding = scr_str_new("base64url", 9); - ScrStr *k = scr_bytes_to_str(bytes, encoding); - scr_str_release(encoding); - scr_bytes_release(bytes); + 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)); @@ -1198,10 +1220,9 @@ static ScrDyn *scr_wc_export(const ScrDyn *args) { scr_dyn_obj_set(result, "k", 1, scr_dyn_new_str(k)); scr_str_release(k); } else { - char message[96]; - snprintf(message, sizeof message, "Unable to export %s secret key using %s format", key->name, - format); - scr_throw_domex("NotSupportedError", message); + 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); @@ -1548,6 +1569,43 @@ static ScrPromise *scr_wc_deferred_buffer(ScrBytes *bytes) { 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'" @@ -1580,31 +1638,7 @@ ScrPromise *scr_webcrypto_cipher(ScrDyn *args, bool decrypt, ScrWebCryptoAesFn a goto done; } if (!scr_wc_max_length(data, "data")) goto done; - { - ScrBytes *view = data; - SCR_BYTES_SNAPSHOT(view); - ScrBytes *iv = params.iv; - SCR_BYTES_SNAPSHOT(iv); - if (!params.aad) params.aad = scr_bytes_new(SCR_BYTES_U8, 0); - 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) { - result = scr_wc_deferred_buffer(out); - } else { - scr_throw_domex("OperationError", "The operation failed for an operation-specific reason"); - result = scr_wc_deferred_rejection(); - } - } + result = scr_wc_run_cipher(aes, name, decrypt, key, ¶ms, data); done: if (data) scr_bytes_release(data); scr_wc_cipher_params_drop(¶ms); @@ -1612,6 +1646,185 @@ done: 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_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_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; + if (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 (!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_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 (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_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 diff --git a/packages/runtime/src/scr_webcrypto_aes.c b/packages/runtime/src/scr_webcrypto_aes.c index 7cb63f561..016ac57af 100644 --- a/packages/runtime/src/scr_webcrypto_aes.c +++ b/packages/runtime/src/scr_webcrypto_aes.c @@ -122,11 +122,74 @@ static ScrBytes *scr_wc_aes_ctr(const unsigned char *key, size_t key_len, 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); @@ -135,3 +198,7 @@ static ScrBytes *scr_wc_aes(const char *name, bool decrypt, const unsigned char 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/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-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/fixtures/node-types/fenced.ts b/tests/fixtures/node-types/fenced.ts index 274d57272..27c212daa 100644 --- a/tests/fixtures/node-types/fenced.ts +++ b/tests/fixtures/node-types/fenced.ts @@ -101,11 +101,11 @@ createECDH("sect163k1"); createECDH("prime256v1").computeSecret(Buffer.alloc(65), "hex"); /* WebCrypto beyond the secret-key slice: @types/node declares the whole * SubtleCrypto surface, and the methods outside the slice, such as - * wrapKey, fence by name. */ -async function wrapWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { - await crypto.subtle.wrapKey("raw", key, key, "AES-KW"); + * getPublicKey, fence by name. */ +async function publicKeyWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { + await crypto.subtle.getPublicKey(key, ["verify"]); } -void wrapWithWebCrypto; +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/harness/__snapshots__/node-types-fenced.txt b/tests/harness/__snapshots__/node-types-fenced.txt index 3198db366..ce43c5085 100644 --- a/tests/harness/__snapshots__/node-types-fenced.txt +++ b/tests/harness/__snapshots__/node-types-fenced.txt @@ -223,14 +223,14 @@ fenced.ts:101:1 - error SC2020: 'ECDH.computeSecret(key, encoding) with a Buffer 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:106:9 - error SC2020: 'crypto.subtle.wrapKey' is part of the standard library types but has no scriptc lowering yet +fenced.ts:106:9 - error SC2020: 'crypto.subtle.getPublicKey' is part of the standard library types but has no scriptc lowering yet - 105 | async function wrapWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { - 106 | await crypto.subtle.wrapKey("raw", key, key, "AES-KW"); - | ^~~~~~~~~~~~~~~~~~~~~ + 105 | async function publicKeyWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { + 106 | await crypto.subtle.getPublicKey(key, ["verify"]); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~ 107 | } - 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, deriveBits and deriveKey with PBKDF2 or HKDF, 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 with AES-KW or those ciphers, deriveBits and deriveKey with PBKDF2 or HKDF, sign and verify with HMAC, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle fenced.ts:111:15 - error SC2020: 'navigator.hardwareConcurrency' is typed by @types/node but has no scriptc lowering yet diff --git a/tests/harness/__snapshots__/webcrypto-refusals.ts.txt b/tests/harness/__snapshots__/webcrypto-refusals.ts.txt index e46099f69..147afb0d3 100644 --- a/tests/harness/__snapshots__/webcrypto-refusals.ts.txt +++ b/tests/harness/__snapshots__/webcrypto-refusals.ts.txt @@ -5,7 +5,7 @@ webcrypto-refusals.ts:6:16 - error SC2020: 'crypto.subtle as a value' is part of | ^~~~~~~~~~~~~ 7 | console.log(typeof 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, deriveBits and deriveKey with PBKDF2 or HKDF, 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 with AES-KW or those ciphers, deriveBits and deriveKey with PBKDF2 or HKDF, 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:9:20 - error SC2020: 'crypto.subtle.sign as a value' is part of the standard library types but has no scriptc lowering yet @@ -14,4 +14,4 @@ webcrypto-refusals.ts:9:20 - error SC2020: 'crypto.subtle.sign as a value' is pa | ^~~~~~~~~~~~~~~~~~ 10 | - 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, deriveBits and deriveKey with PBKDF2 or HKDF, 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 with AES-KW or those ciphers, deriveBits and deriveKey with PBKDF2 or HKDF, 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 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-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/errors.test.ts b/tests/harness/errors.test.ts index 00ee40043..d321b9a00 100644 --- a/tests/harness/errors.test.ts +++ b/tests/harness/errors.test.ts @@ -1666,6 +1666,7 @@ await attempt("ed25519 key", () => crypto.subtle.generateKey({ name: "Ed25519" } 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" })); `, "mjs", ); @@ -1678,23 +1679,24 @@ await attempt("ecdh bits", () => crypto.subtle.deriveBits({ name: "ECDH" }, key, "sha3 hmac Error SC2020 crypto.subtle.importKey with the SHA3-256 algorithm is not supported yet\n" + "ed25519 key Error SC2020 crypto.subtle.generateKey with the Ed25519 algorithm 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", + "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", ); }); test("a method outside the slice is a named fence where it runs", async () => { const r = await compileAndRun( - "webcrypto-wrap-key", + "webcrypto-get-public-key", `console.log("before"); -const key = await crypto.subtle.generateKey({ name: "AES-KW", length: 128 }, true, ["wrapKey"]); -await crypto.subtle.wrapKey("raw", key, key, "AES-KW"); +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\.wrapKey' 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$/, ); }); }); From c14e2607c55bafdc05e3ff7f961fb8a57778ad20 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 05:52:31 -0500 Subject: [PATCH 065/102] Address #1785 review: Buffer|string data adapter and objectMode chunk handling --- .../src/backend/llvm/expr-stream-callbacks.ts | 12 ++++++++++++ packages/runtime/src/scr_stream.c | 9 +++++++++ tests/corpus/7241-objectmode-streams.mjs | 7 +++++++ 3 files changed, 28 insertions(+) diff --git a/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts b/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts index 17507e128..0570d0ea7 100644 --- a/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts +++ b/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts @@ -126,6 +126,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`, @@ -136,6 +139,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`, diff --git a/packages/runtime/src/scr_stream.c b/packages/runtime/src/scr_stream.c index 0c17c8840..be5ccb910 100644 --- a/packages/runtime/src/scr_stream.c +++ b/packages/runtime/src/scr_stream.c @@ -5637,6 +5637,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); @@ -5702,6 +5704,13 @@ void scr_stream_unshift(ScrStream *s, ScrBytes *chunk) { } 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); diff --git a/tests/corpus/7241-objectmode-streams.mjs b/tests/corpus/7241-objectmode-streams.mjs index 334273c00..6101930df 100644 --- a/tests/corpus/7241-objectmode-streams.mjs +++ b/tests/corpus/7241-objectmode-streams.mjs @@ -100,6 +100,13 @@ function unshiftFront() { 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() { From 3cefd421a132f1d1502e45405bf7e11981fb4286 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 05:58:32 -0500 Subject: [PATCH 066/102] Fence requestCert beside a secureContext and free failed TLSSockets new tls.TLSSocket(socket, { isServer: true, secureContext, requestCert: true }) skipped the options walk that refuses requestCert, so the server asked for no client certificate and accepted every client, even with rejectUnauthorized: true. With a secureContext, Node still reads the socket's own options, so a truthy requestCert, SNICallback and ALPNCallback now throw the fence there too. A TLS socket's transport kept its 'secure' and 'session' listeners until the socket was freed. A handshake that fails never fires 'secure', so a listener that captures the socket kept the socket and its TLS state alive after it closed. The transport now drops those listeners when the socket settles, and ignores listeners added after that. --- .../7094-tls-socket-failed-handshakes.ts.json | 6 ++ packages/runtime/src/scr_net.c | 1 + packages/runtime/src/scr_net.h | 3 + packages/runtime/src/scr_tls.c | 49 ++++++++++++- .../7094-tls-socket-failed-handshakes.ts | 49 +++++++++++++ .../7094-tls-socket-failed-handshakes.ts.json | 1 + tests/harness/errors.test.ts | 45 ++++++++++++ tests/harness/tls-socket-leaks.test.ts | 68 +++++++++++++++++++ 8 files changed, 220 insertions(+), 2 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7094-tls-socket-failed-handshakes.ts.json create mode 100644 tests/corpus/7094-tls-socket-failed-handshakes.ts create mode 100644 tests/harness/corpus-costs/7094-tls-socket-failed-handshakes.ts.json create mode 100644 tests/harness/tls-socket-leaks.test.ts 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/runtime/src/scr_net.c b/packages/runtime/src/scr_net.c index 8f9a68424..29a4af393 100644 --- a/packages/runtime/src/scr_net.c +++ b/packages/runtime/src/scr_net.c @@ -5354,6 +5354,7 @@ static bool scr_net_sock_settle(ScrNetSocket *sock) { 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; diff --git a/packages/runtime/src/scr_net.h b/packages/runtime/src/scr_net.h index 8f26bbf4d..ffa9b2f72 100644 --- a/packages/runtime/src/scr_net.h +++ b/packages/runtime/src/scr_net.h @@ -354,6 +354,9 @@ typedef struct ScrNetTransportOps { /* 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 diff --git a/packages/runtime/src/scr_tls.c b/packages/runtime/src/scr_tls.c index 6fa1f169d..e7436ab69 100644 --- a/packages/runtime/src/scr_tls.c +++ b/packages/runtime/src/scr_tls.c @@ -664,6 +664,7 @@ typedef struct ScrTlsSock { 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 @@ -1237,6 +1238,17 @@ static void scr_tls_after_established(void *tctx) { 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, @@ -1245,6 +1257,7 @@ 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, }; @@ -2202,6 +2215,29 @@ 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"; @@ -2233,12 +2269,17 @@ ScrNetSocket *scr_tls_wrap_socket(ScrNetSocket *raw, const ScrDyn *opts /*borrow return NULL; } /* Node serves a secureContext as it is: the record's cert, key and - * other context options are not read then */ + * 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; @@ -2867,7 +2908,7 @@ void scr_tls_sock_on_secure_connect(ScrNetSocket *s, ScrClosure *cb /*moves*/, b * 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) { + if (t == NULL || t->established || t->settled) { scr_closure_release(cb); return; } @@ -2880,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 */ } 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/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/errors.test.ts b/tests/harness/errors.test.ts index 96949201d..31f2b6fd9 100644 --- a/tests/harness/errors.test.ts +++ b/tests/harness/errors.test.ts @@ -905,6 +905,51 @@ listener.listen(0, () => { }); }); +// 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). 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); + }); + }, +); From 4e834f8eed49b694be5fb5c1b14ba4f827342a68 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 06:00:28 -0500 Subject: [PATCH 067/102] Read error constructors as values and destructure workerData in JavaScript (reland) --- .../lowering/expressions/object-literals.ts | 25 +++++- .../lowering/expressions/property-access.ts | 34 +++++++- .../src/frontend/lowering/lower-calls.ts | 29 +++++++ .../src/frontend/lowering/lower-stmts.ts | 3 + .../6870-error-constructor-values.js.json | 6 ++ .../6871-worker-data-destructuring.cjs.json | 6 ++ packages/runtime/src/scr_dyn.h | 3 + packages/runtime/src/scr_dyn_invoke.c | 2 + packages/runtime/src/scr_json.c | 79 ++++++++++++++++--- tests/corpus/6870-error-constructor-values.js | 65 +++++++++++++++ .../corpus/6871-worker-data-destructuring.cjs | 30 +++++++ .../6870-error-constructor-values.js.json | 1 + .../6871-worker-data-destructuring.cjs.json | 1 + 13 files changed, 267 insertions(+), 17 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6870-error-constructor-values.js.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6871-worker-data-destructuring.cjs.json create mode 100644 tests/corpus/6870-error-constructor-values.js create mode 100644 tests/corpus/6871-worker-data-destructuring.cjs create mode 100644 tests/harness/corpus-costs/6870-error-constructor-values.js.json create mode 100644 tests/harness/corpus-costs/6871-worker-data-destructuring.cjs.json diff --git a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts index 015be7914..678b375fe 100644 --- a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts +++ b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts @@ -36,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, @@ -394,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 @@ -3157,6 +3160,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, @@ -3173,6 +3190,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 }; diff --git a/packages/compiler/src/frontend/lowering/expressions/property-access.ts b/packages/compiler/src/frontend/lowering/expressions/property-access.ts index 957dd1ddf..7f3910c15 100644 --- a/packages/compiler/src/frontend/lowering/expressions/property-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/property-access.ts @@ -4090,10 +4090,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", @@ -4104,6 +4120,7 @@ const GLOBAL_CONSTRUCTOR_VALUES: ReadonlySet = new Set([ "Promise", "WeakMap", "WeakSet", + ...ERROR_CONSTRUCTOR_VALUES, ]); /** The builtin global functions JavaScript sources read as interned @@ -4154,8 +4171,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 @@ -4246,6 +4273,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); diff --git a/packages/compiler/src/frontend/lowering/lower-calls.ts b/packages/compiler/src/frontend/lowering/lower-calls.ts index bd5068d05..39b7207c0 100644 --- a/packages/compiler/src/frontend/lowering/lower-calls.ts +++ b/packages/compiler/src/frontend/lowering/lower-calls.ts @@ -7439,6 +7439,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" || diff --git a/packages/compiler/src/frontend/lowering/lower-stmts.ts b/packages/compiler/src/frontend/lowering/lower-stmts.ts index 687420baf..7c0b4f7ff 100644 --- a/packages/compiler/src/frontend/lowering/lower-stmts.ts +++ b/packages/compiler/src/frontend/lowering/lower-stmts.ts @@ -3889,6 +3889,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", 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/runtime/src/scr_dyn.h b/packages/runtime/src/scr_dyn.h index 9220dd843..facf9f2ff 100644 --- a/packages/runtime/src/scr_dyn.h +++ b/packages/runtime/src/scr_dyn.h @@ -764,6 +764,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); diff --git a/packages/runtime/src/scr_dyn_invoke.c b/packages/runtime/src/scr_dyn_invoke.c index ec49dd383..80e01b08c 100644 --- a/packages/runtime/src/scr_dyn_invoke.c +++ b/packages/runtime/src/scr_dyn_invoke.c @@ -1923,6 +1923,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_json.c b/packages/runtime/src/scr_json.c index 4e21fa397..f610ffdbb 100644 --- a/packages/runtime/src/scr_json.c +++ b/packages/runtime/src/scr_json.c @@ -1814,6 +1814,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); @@ -7951,6 +8000,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); } @@ -11943,21 +12003,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()); 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/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 } From fb403d5755dfb737815419cd02960755ab4018a4 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 06:06:45 -0500 Subject: [PATCH 068/102] Clear a store that an async prefix enters in a loop callback When an event-loop callback calls an async function or steps a generator that enters a store before its first await, the store becomes the callback's at the end of the prefix. On the main slot it now ends with that callback, as an enterWith there does: the copy schedules the tick that clears the main slot, so the store does not reach later callbacks. --- packages/runtime/src/scr_async.c | 47 +++++++++++--------- tests/corpus/7106-async-prefix-enter-with.ts | 33 +++++++++++++- 2 files changed, 59 insertions(+), 21 deletions(-) diff --git a/packages/runtime/src/scr_async.c b/packages/runtime/src/scr_async.c index 9d3a25469..9e3365fbe 100644 --- a/packages/runtime/src/scr_async.c +++ b/packages/runtime/src/scr_async.c @@ -674,6 +674,32 @@ 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 @@ -685,6 +711,7 @@ static void scr_als_prefix_end(ScrFiber *f) { 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(); } } @@ -758,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). */ diff --git a/tests/corpus/7106-async-prefix-enter-with.ts b/tests/corpus/7106-async-prefix-enter-with.ts index 27dff250b..d70822171 100644 --- a/tests/corpus/7106-async-prefix-enter-with.ts +++ b/tests/corpus/7106-async-prefix-enter-with.ts @@ -3,7 +3,9 @@ // 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. +// 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(); @@ -45,6 +47,33 @@ async function fibered(tag: string): Promise { 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"); @@ -83,6 +112,8 @@ async function main(): Promise { 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(); From fb544eb98e40024a1ed8122dc8ab41501c0484b9 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 06:07:58 -0500 Subject: [PATCH 069/102] Validate DiffieHellman peer keys like Node: oversized keys and RFC 5114 subgroups Keys, primes and generators drop their leading zero bytes before import, as BN_bin2bn does, and a value still past mbedTLS's 80000-byte limit throws Node's error or a coded SC2020 error instead of aborting the process: computeSecret rejects a key longer than the prime as too large, a long generator is a bad generator, and setPublicKey/setPrivateKey refuse with SC2020. Under the RFC 5114 groups, computeSecret rejects a peer key with key^q mod p != 1 with ERR_CRYPTO_INVALID_KEYTYPE, as OpenSSL's public key check does, closing small-subgroup confinement of the private key. The safe-prime groups keep the range check only, as in Node. Exponents past 8192 bits are split into digits bit by bit, so generateKeys with a long private key takes linear time. --- .../limitations/builtin-apis/crypto.mdx | 1 + .../tests/corpus/6712-dh-peer-keys.js.json | 6 + packages/runtime/src/scr_dh.c | 117 +++++++++++++++--- tests/corpus/6712-dh-peer-keys.js | 117 ++++++++++++++++++ .../corpus-costs/6712-dh-peer-keys.js.json | 1 + 5 files changed, 223 insertions(+), 19 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6712-dh-peer-keys.js.json create mode 100644 tests/corpus/6712-dh-peer-keys.js create mode 100644 tests/harness/corpus-costs/6712-dh-peer-keys.js.json diff --git a/docs/content/limitations/builtin-apis/crypto.mdx b/docs/content/limitations/builtin-apis/crypto.mdx index 6eb42c8b1..f1c06eb72 100644 --- a/docs/content/limitations/builtin-apis/crypto.mdx +++ b/docs/content/limitations/builtin-apis/crypto.mdx @@ -20,6 +20,7 @@ ECDH property reads and writes throw a coded SC2020 error. `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. 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/runtime/src/scr_dh.c b/packages/runtime/src/scr_dh.c index 351d97a0f..cf44338f5 100644 --- a/packages/runtime/src/scr_dh.c +++ b/packages/runtime/src/scr_dh.c @@ -17,7 +17,8 @@ * 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. All arguments are borrowed. */ + * 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 @@ -39,6 +40,9 @@ #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, @@ -171,6 +175,14 @@ static void sd_too_long(void) { 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). */ static bool sd_validate_int32(const char *name, double value) { bool integer = isfinite(value) && trunc(value) == value; @@ -215,10 +227,10 @@ static bool sd_exp(mbedtls_mpi *out, const mbedtls_mpi *base, const mbedtls_mpi 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) { - MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&digit, e)); - MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&digit, offset)); - for (size_t bit = SD_DIGIT_BITS; bit < mbedtls_mpi_bitlen(&digit); bit++) - MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&digit, bit, 0)); + /* 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)); @@ -234,6 +246,36 @@ cleanup: 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) { @@ -872,12 +914,21 @@ static ScrDyn *sd_generate(double bits, const ScrBytes *generator_bytes, double /* 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(); - if (mbedtls_mpi_read_binary(&d->p, prime->data, prime->len) != 0) scr_trap("scriptc: out of memory\n"); - if (generator_bytes) { - if (mbedtls_mpi_read_binary(&d->g, generator_bytes->data, generator_bytes->len) != 0) - scr_trap("scriptc: out of memory\n"); - } else if (mbedtls_mpi_lset(&d->g, (mbedtls_mpi_sint)generator) != 0) { - scr_trap("scriptc: out of memory\n"); + 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)) { @@ -1057,10 +1108,27 @@ static bool sd_derives(const ScDh *d) { 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 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. */ + * 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; @@ -1069,12 +1137,19 @@ static ScrDyn *sd_compute_secret(ScDh *d, const ScrDyn *key, const ScrDyn *in_en mbedtls_mpi_init(&peer); mbedtls_mpi_init(&bound); mbedtls_mpi_init(&secret); - if (mbedtls_mpi_read_binary(&peer, bytes->data, bytes->len) != 0 || mbedtls_mpi_sub_int(&bound, &d->p, 1) != 0) + /* 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 (mbedtls_mpi_cmp_int(&peer, 1) <= 0) { + 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 (mbedtls_mpi_cmp_mpi(&peer, &bound) >= 0) { + } 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"); @@ -1103,9 +1178,13 @@ static ScrDyn *sd_get_value(const mbedtls_mpi *value, bool present, const char * 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; - if (mbedtls_mpi_read_binary(value, bytes->data, bytes->len) != 0) scr_trap("scriptc: out of memory\n"); - *present = true; + 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); } 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/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 } From d01117fa517daca56dbb8d87d3c6267d028a81b5 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 06:13:45 -0500 Subject: [PATCH 070/102] Batch the contextual types and signatures that lowering asks per node ClassProtocols' identity-flow fixpoint asks the contextual type of each site whose source carries identity, one round trip at a time, and lowering asks the resolved signature of each call and the contextual type of each array literal and conditional it lowers the same way. The checker facade can now batch them: prefetchContextualTypes for the fixpoint's sites before it runs, and, for each prefetched wave of reachable roots, the resolved signatures of its calls and the contextual types of its array literals and conditionals. A batched query that fails is left out of the memo, so a direct query still throws where it is made. The batches use the checker's getContextualTypes and getResolvedSignatures requests. NODE_BATCH_QUERIES keeps them off until scriptc depends on a tsc-ts release that answers them; while it is off the prefetches do nothing. --- .../src/frontend/lowering/class-protocols.ts | 30 +++++++- packages/compiler/src/frontend/ts7/checker.ts | 72 ++++++++++++++++++- .../src/frontend/ts7/semantic-checker.ts | 18 +++++ 3 files changed, 115 insertions(+), 5 deletions(-) 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/ts7/checker.ts b/packages/compiler/src/frontend/ts7/checker.ts index 4f2d60294..cd43636af 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,30 @@ 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, +): void { + const answer = (chunk: readonly I[]): void => { + let answers: readonly (O | undefined)[]; + try { + answers = fetch(chunk); + } catch { + 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)); +} + 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) { @@ -322,7 +346,51 @@ 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)); + batchAnswers( + 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)); + batchAnswers( + missing, + (chunk) => this.raw.getResolvedSignatures(chunk), + (node, signature) => this.cache.resolvedSignature.set(node, signature), + ); } /** Batches symbol queries for every identifier under roots without the diff --git a/packages/compiler/src/frontend/ts7/semantic-checker.ts b/packages/compiler/src/frontend/ts7/semantic-checker.ts index 5e7f8339a..1e5f46b4d 100644 --- a/packages/compiler/src/frontend/ts7/semantic-checker.ts +++ b/packages/compiler/src/frontend/ts7/semantic-checker.ts @@ -96,6 +96,13 @@ export interface SemanticCompletion { symbol: SemanticSymbol | undefined; } +/** Whether lowering asks the checker for contextual types and resolved + * signatures in batches (`getContextualTypes`, `getResolvedSignatures`). + * Off until scriptc depends on a tsc-ts release that answers them: the + * batch prefetches (checker.ts) then do nothing and lowering asks node by + * node. */ +export const NODE_BATCH_QUERIES = false; + /** 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. */ @@ -201,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 }); } @@ -213,6 +224,13 @@ 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)[] { + const data = this.project.request<(SignatureResponse | null)[]>("getResolvedSignatures", { + locations: nodes.map((node) => node.id), + }); + return data.map((item) => (item === null ? undefined : this.project.signature(item))); + } getSignatureFromDeclaration(node: AstNode): SemanticSignature | undefined { return this.signature("getSignatureFromDeclaration", { location: node.id }); } From 0f6ea63f21f8a0f044177ebb6f36fc3cf96fac16 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 06:17:05 -0500 Subject: [PATCH 071/102] Give each evaluation of a forward-read generic binding its own function A generic binding inside a function that a nested function read before the declaration lowered stores its instance into a TDZ box when the declaration runs. That value was the instance's closure, which the backend interns for module functions, so every evaluation of the declaration stored the same function object. JavaScript makes a new one each time. The stored value is now a closure over a lifted forwarder that calls the instance, so each evaluation allocates a new closure; the forwarder is created once per instance. Async and rest-parameter bindings read this way report SC1090. Corpus 7180 checks the identities. --- .../frontend/lowering/generic-functions.ts | 71 ++++++++++++++++++- .../7180-generic-local-binding-early-uses.ts | 16 +++++ 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/packages/compiler/src/frontend/lowering/generic-functions.ts b/packages/compiler/src/frontend/lowering/generic-functions.ts index d0e07582c..e8d3241c0 100644 --- a/packages/compiler/src/frontend/lowering/generic-functions.ts +++ b/packages/compiler/src/frontend/lowering/generic-functions.ts @@ -16,7 +16,7 @@ import { isUnitType, typeEquals, } from "../../ir/ir.js"; -import { nodeThrowExpr } from "../../ir/build.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"; @@ -102,6 +102,8 @@ export interface GenericFnInfo { * 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; @@ -1266,7 +1268,10 @@ export function lowerGenericFnValue( * 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. */ + * 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, @@ -1281,7 +1286,67 @@ export function genericBindingStoredValue( ); const sigs = lowerer.checker.getCallSignatures(lowerer.typeOf(name)); if (sigs.length !== 1) fenceUnpinned(); - return pinnedGenericClosure(lowerer, name, info, sigs[0]!, 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 diff --git a/tests/corpus/7180-generic-local-binding-early-uses.ts b/tests/corpus/7180-generic-local-binding-early-uses.ts index 85458d973..f3f7816b5 100644 --- a/tests/corpus/7180-generic-local-binding-early-uses.ts +++ b/tests/corpus/7180-generic-local-binding-early-uses.ts @@ -51,3 +51,19 @@ function counter(): () => number { 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()); From 3fecf687f542143adbb381bf6f182383b7baa7e8 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 06:31:30 -0500 Subject: [PATCH 072/102] Throw Node's TypeError for member reads of holes in wide unions A binding that may hold a value its declared type omits (a function parameter fed array elements, which can be holes) and that the checker narrowed to one record or class arm of a union with more than two arms was read through a checked extraction of that arm. When the binding held a hole, a member read or method call threw "undefined is not representable in the target union ..." for a record arm and "Value is not an instance of 'Shape'" for a class arm, where Node throws "Cannot read properties of undefined (reading 'a')". The read now tests for undefined first and throws Node's TypeError, as the two-arm path already does. --- .../lowering/expressions/narrowing.ts | 49 +++++++++++++++--- .../7280-named-reads-hole-receivers.ts.json | 6 +++ .../corpus/7280-named-reads-hole-receivers.ts | 50 +++++++++++++++++++ .../7280-named-reads-hole-receivers.ts.json | 1 + 4 files changed, 100 insertions(+), 6 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7280-named-reads-hole-receivers.ts.json create mode 100644 tests/corpus/7280-named-reads-hole-receivers.ts create mode 100644 tests/harness/corpus-costs/7280-named-reads-hole-receivers.ts.json diff --git a/packages/compiler/src/frontend/lowering/expressions/narrowing.ts b/packages/compiler/src/frontend/lowering/expressions/narrowing.ts index 2e3dd6140..786f3a337 100644 --- a/packages/compiler/src/frontend/lowering/expressions/narrowing.ts +++ b/packages/compiler/src/frontend/lowering/expressions/narrowing.ts @@ -985,11 +985,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 +1044,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 +1061,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 +1090,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); } 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/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/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 } From 9b317ba97da174cc7949a8c849dd6c0fb5e56879 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 06:48:13 -0500 Subject: [PATCH 073/102] Allow the JSX lowering tests' TypeScript 5 import jsx-source.test.ts compares the JSX rewrite with TypeScript 5's transpileModule output, so it imports typescript5 as the other test oracles on the TypeScript 5 island allowlist do. scripts/test-ts7.mjs did not list it, and the TypeScript 7 parity job failed since #1786. --- scripts/test-ts7.mjs | 1 + 1 file changed, 1 insertion(+) 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", From 1f357b3091288cf7aafa51d988580fa0b66c6420 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 07:01:51 -0500 Subject: [PATCH 074/102] Fence non-Buffer chunk parameters on byte-mode stream callbacks again --- .../src/frontend/lowering/lower-stream.ts | 48 +++++++++++++++---- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/packages/compiler/src/frontend/lowering/lower-stream.ts b/packages/compiler/src/frontend/lowering/lower-stream.ts index 14062051f..cb81348eb 100644 --- a/packages/compiler/src/frontend/lowering/lower-stream.ts +++ b/packages/compiler/src/frontend/lowering/lower-stream.ts @@ -289,6 +289,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); @@ -309,11 +310,13 @@ function lowerStreamCallback( // 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 the Buffer), or throws a TypeError there; an encoding of another - // type (`string | null | undefined`) from the encoding argument's. + // 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 is the fence's; an encoding + // of another type (`string | null | undefined`) converts from the + // encoding argument's value. if ( - (i === 0 || i === 1) && + ((i === 0 && chunkValues) || i === 1) && (which === "write" || which === "transform") && funcType.params[i]!.kind !== "func" && canConvertToDyn( @@ -465,6 +468,20 @@ function streamObjectModes( return out; } +/** Whether an options literal sets the writable side's object mode with a + * `true` literal (objectMode, or writableObjectMode on a duplex stream). + * Reports nothing: streamObjectModes 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 !== "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 @@ -802,7 +819,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, out.writableObject), + ); } finally { if (pinned) lowerer.stageSourceTypes.delete(pinned); } @@ -1151,6 +1171,7 @@ function streamMethodWrapper( thisType: IrType, loc: SrcLoc, blame: ts.Node, + chunkValues = true, ): IrExpr | null { const found = lowerer.findMethodOn(info, methodName); if (!found) { @@ -1235,10 +1256,11 @@ function streamMethodWrapper( 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 the Buffer), or throws a TypeError there. + // 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 && + chunkValues && (which === "write" || which === "transform") && got.type.kind !== "func" && canConvertToDyn( @@ -1343,10 +1365,20 @@ 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. + const optsNode = argNodes[0] !== undefined ? followOptionsArg(lowerer, argNodes[0]) : null; + const chunkValues = + argNodes[0] !== undefined && + (optsNode === null || + !ts.isObjectLiteralExpression(optsNode) || + literalWritesValues(optsNode, cls !== "%Readable" && cls !== "%Writable")); const fallback = (name: string): IrExpr | null => { const methodName = UNDERSCORE_METHODS.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 }); From 01dd4f6796c2deed78f330822c861e4cb73321e3 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 07:05:30 -0500 Subject: [PATCH 075/102] Keep the handle tags in name order and update two tests for current main --- packages/runtime/src/scr_dyn.h | 10 +++++----- tests/harness/library-profile.test.ts | 9 ++++++--- tests/harness/stream-entry-kinds.test.ts | 6 ++---- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/packages/runtime/src/scr_dyn.h b/packages/runtime/src/scr_dyn.h index c9d090370..9607274e3 100644 --- a/packages/runtime/src/scr_dyn.h +++ b/packages/runtime/src/scr_dyn.h @@ -143,6 +143,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 */ \ @@ -160,11 +161,6 @@ typedef enum { 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) */ \ - X(PRIVATE_KEY, 65) /* node:crypto PrivateKeyObject (scr_pki.c) */ \ - X(PUBLIC_KEY, 66) /* node:crypto PublicKeyObject (scr_pki.c) */ \ - X(SIGN, 67) /* node:crypto Sign (scr_pki.c) */ \ - X(VERIFY, 68) /* node:crypto Verify (scr_pki.c) */ \ - X(ASYMMETRIC_CRYPTO_KEY, 69) /* WebCrypto ECDSA and RSA CryptoKey (scr_webcrypto_pki.c) */ \ X(EVENT, 14) /* ScrEvent — new Event() and AbortSignal's abort events */ \ X(EVENT_TARGET, 39) /* ScrEventTarget — new EventTarget() */ \ X(FETCH_HEADERS, 13) /* native static-fetch response Headers */ \ @@ -192,14 +188,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 */ \ diff --git a/tests/harness/library-profile.test.ts b/tests/harness/library-profile.test.ts index 2b28a6cd0..f327f8372 100644 --- a/tests/harness/library-profile.test.ts +++ b/tests/harness/library-profile.test.ts @@ -482,7 +482,10 @@ 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: "node-builtin.crypto.createDiffieHellman", + remediation: "key agreement comes from the host", + }, ], }, }), @@ -492,9 +495,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 + // (crypto.createDiffieHellman 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"); + expect(profileRemediation(r.profile, "SC2020")).toBe("key agreement comes from the host"); expect(profileRemediation(r.profile, "SC4014")).toBeUndefined(); }); diff --git a/tests/harness/stream-entry-kinds.test.ts b/tests/harness/stream-entry-kinds.test.ts index f7333b298..ec89c5914 100644 --- a/tests/harness/stream-entry-kinds.test.ts +++ b/tests/harness/stream-entry-kinds.test.ts @@ -138,7 +138,7 @@ r.once('readable', () => { 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 +151,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"); }); }); From f87a04fa06b0e2e9b547b435542220a59d2761ae Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 07:08:26 -0500 Subject: [PATCH 076/102] Build typed 'message' listener parameters from the message A 'message' listener with a typed parameter received each message as a checked-dynamic value: the port decoded the message into dyn objects, the listener's thunk matched the value against each union arm, read every field again to build the record, and the dyn objects were then released. For bench/channel-messages that was about a third of the delivery time. - A closure registered with on, once, addListener, prependListener or prependOnceListener for 'message' gets a typed message entry when its parameter is a number, boolean, string, a record of those without union fields, or a boxed union of those arms with null or undefined. The entry builds the parameter from the message's nodes and calls the closure. - The entry handles a message only when it has the parameter's exact layout: the union arm the checked conversion picks, and a record's declared keys in declaration order with no others. Any other message runs through the thunk on the decoded value, as before, so undeclared keys, other orders and mismatches behave as they did. - Ports, workers and parentPort deliver a message through the entries when no value in it is reached twice and it holds no ports or native handles. Listeners without an entry share one decoded value, made when the first of them runs. - The message readers are runtime entry points, so the runtime ABI is now 27. Corpus 7130 and 7131 check typed listeners on MessageChannel ports, a worker and parentPort against Node: exact layouts, extra keys, shared values, nested records, untyped listeners beside typed ones, once listeners and a transferred port. --- packages/cli/test/native-link-info.test.ts | 4 +- packages/compiler/src/backend/llvm/dyn.ts | 300 ++++++++++++++++++ .../compiler/src/backend/llvm/expr-dynamic.ts | 35 ++ packages/compiler/src/backend/runtime-abi.ts | 4 +- .../src/backend/runtime-pack-targets.test.ts | 2 +- .../compiler/src/backend/runtime-pack.test.ts | 2 +- .../test/native-codegen-integration.test.ts | 4 +- .../7130-typed-message-listeners.ts.json | 6 + .../corpus/7131-typed-worker-messages.ts.json | 6 + .../runtime-darwin-arm64/scripts/build.mjs | 2 +- .../runtime-pack-common/scripts/build.mjs | 2 +- packages/runtime/src/scr_console.c | 2 +- packages/runtime/src/scr_core.h | 2 +- packages/runtime/src/scr_dyn.h | 57 +++- packages/runtime/src/scr_events_emitter.c | 54 +++- packages/runtime/src/scr_events_emitter.h | 6 + packages/runtime/src/scr_json.c | 7 + packages/runtime/src/scr_message.c | 69 ++-- packages/runtime/src/scr_message.test.c | 47 +++ packages/runtime/src/scr_worker_events.c | 24 ++ tests/corpus/7130-typed-message-listeners.ts | 80 +++++ tests/corpus/7131-typed-worker-messages.ts | 54 ++++ .../7130-typed-message-listeners.ts.json | 1 + .../7131-typed-worker-messages.ts.json | 1 + .../self-hosting-native-toolchain.test.ts | 2 +- 25 files changed, 718 insertions(+), 55 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7130-typed-message-listeners.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7131-typed-worker-messages.ts.json create mode 100644 tests/corpus/7130-typed-message-listeners.ts create mode 100644 tests/corpus/7131-typed-worker-messages.ts create mode 100644 tests/harness/corpus-costs/7130-typed-message-listeners.ts.json create mode 100644 tests/harness/corpus-costs/7131-typed-worker-messages.ts.json diff --git a/packages/cli/test/native-link-info.test.ts b/packages/cli/test/native-link-info.test.ts index 630ef7173..a7a5e718a 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: 26, marker: "scr_runtime_abi_v26" }, + runtime_abi: { version: 27, marker: "scr_runtime_abi_v27" }, 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_v26"); + expect(error?.stderr).toContain("scr_runtime_abi_v27"); }); }); diff --git a/packages/compiler/src/backend/llvm/dyn.ts b/packages/compiler/src/backend/llvm/dyn.ts index 6911ef98b..ac01a9209 100644 --- a/packages/compiler/src/backend/llvm/dyn.ts +++ b/packages/compiler/src/backend/llvm/dyn.ts @@ -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; @@ -4610,6 +4621,295 @@ export class LlDyn { 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) { + this.messageListeners.set(key, null); + return null; + } + const name = `sc_dml_${this.messageListeners.size}`; + this.messageListeners.set(key, name); + 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(), + `}`, + ``, + ); + 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, 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); + if (!def || 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); + 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(), + `}`, + ``, + ); + return name; + } + /** The adapter closure body for one TARGET signature: caps[0] is an * untraced obj-box owning the dyn function value. */ dynFuncAdapterHelper(t: IrType & { kind: "func" }): string { diff --git a/packages/compiler/src/backend/llvm/expr-dynamic.ts b/packages/compiler/src/backend/llvm/expr-dynamic.ts index 563a900f8..58bb90569 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(); @@ -1323,3 +1337,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/runtime-abi.ts b/packages/compiler/src/backend/runtime-abi.ts index 703e8fe48..3a41d9176 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 = 26 as const; -export const RUNTIME_ABI_MARKER = "scr_runtime_abi_v26" as const; +export const RUNTIME_ABI_VERSION = 27 as const; +export const RUNTIME_ABI_MARKER = "scr_runtime_abi_v27" 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 c884f1132..af61e5229 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: 26, marker: "scr_runtime_abi_v26" }, + runtime_abi: { version: 27, marker: "scr_runtime_abi_v27" }, compiler: { command: "fixture", identity: "fixture", target: target.llvmTriple }, macros: { executable: [], excluded: ["SCR_LIB"], sanitizer: "external-toolchain-required" }, flavors: { diff --git a/packages/compiler/src/backend/runtime-pack.test.ts b/packages/compiler/src/backend/runtime-pack.test.ts index 3a0b7870a..d09509911 100644 --- a/packages/compiler/src/backend/runtime-pack.test.ts +++ b/packages/compiler/src/backend/runtime-pack.test.ts @@ -127,7 +127,7 @@ async function fixture(target: NativeTargetSpec = MACOS_ARM64_TARGET) { object_format: target.objectFormat, minimum_os: target.minimumOs, }, - runtime_abi: { version: 26, marker: "scr_runtime_abi_v26" }, + runtime_abi: { version: 27, marker: "scr_runtime_abi_v27" }, compiler: { command: "clang", identity: "fixture clang", diff --git a/packages/compiler/test/native-codegen-integration.test.ts b/packages/compiler/test/native-codegen-integration.test.ts index af8d9b724..35a747d60 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_v26"); + expect(await symbols(helperObject, ["-u"])).toContain("_scr_runtime_abi_v27"); 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_v26"); + expect(undefinedSymbols).toContain("_scr_runtime_abi_v27"); }); test("helper and clang object paths retain the same outbound FFI C ABI", async () => { 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/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/runtime-darwin-arm64/scripts/build.mjs b/packages/runtime-darwin-arm64/scripts/build.mjs index 012b86013..631750cdf 100644 --- a/packages/runtime-darwin-arm64/scripts/build.mjs +++ b/packages/runtime-darwin-arm64/scripts/build.mjs @@ -340,7 +340,7 @@ async function build() { package: packageManifest.name, version: packageManifest.version, target: RUNTIME_PACK_MATRIX.target, - runtime_abi: { version: 26, marker: "scr_runtime_abi_v26" }, + runtime_abi: { version: 27, marker: "scr_runtime_abi_v27" }, compiler: { command: compiler, identity: compilerVersion, diff --git a/packages/runtime-pack-common/scripts/build.mjs b/packages/runtime-pack-common/scripts/build.mjs index 5b8f3563f..0e81033ad 100644 --- a/packages/runtime-pack-common/scripts/build.mjs +++ b/packages/runtime-pack-common/scripts/build.mjs @@ -437,7 +437,7 @@ async function build() { package: packageManifest.name, version: packageManifest.version, target: matrix.target, - runtime_abi: { version: 26, marker: "scr_runtime_abi_v26" }, + runtime_abi: { version: 27, marker: "scr_runtime_abi_v27" }, compiler: { command: compiler, identity: compilerVersion, diff --git a/packages/runtime/src/scr_console.c b/packages/runtime/src/scr_console.c index 24cd8093b..a3ac43cc0 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_v26(void) {} +void scr_runtime_abi_v27(void) {} void scr_init(void) { #ifdef SCR_WORKERS diff --git a/packages/runtime/src/scr_core.h b/packages/runtime/src/scr_core.h index 791c600c7..fea020d16 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_v26(void); +void scr_runtime_abi_v27(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_dyn.h b/packages/runtime/src/scr_dyn.h index c9d090370..2602e0341 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 @@ -254,6 +255,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). */ @@ -391,7 +441,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 @@ -1246,6 +1296,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 diff --git a/packages/runtime/src/scr_events_emitter.c b/packages/runtime/src/scr_events_emitter.c index 901e2d114..5e03c0d6c 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; the others share one decoded argument, made when + * the first of them runs. */ +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,19 @@ static bool scr_ee_emit_core(ScrEmitter *em, ScrStr *name, va_list *ap_template, continue; } } + if (message && 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 +1134,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 +1145,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 +1157,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 +1169,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 +1267,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 +1289,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 +1302,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..6e1ef536a 100644 --- a/packages/runtime/src/scr_events_emitter.h +++ b/packages/runtime/src/scr_events_emitter.h @@ -154,6 +154,12 @@ 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; the other listeners get 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_json.c b/packages/runtime/src/scr_json.c index f610ffdbb..355a34aee 100644 --- a/packages/runtime/src/scr_json.c +++ b/packages/runtime/src/scr_json.c @@ -4122,9 +4122,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) { diff --git a/packages/runtime/src/scr_message.c b/packages/runtime/src/scr_message.c index 5e1bce37f..508266103 100644 --- a/packages/runtime/src/scr_message.c +++ b/packages/runtime/src/scr_message.c @@ -3,30 +3,6 @@ #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 +71,7 @@ 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 */ }; typedef struct { @@ -143,6 +120,8 @@ 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 */ + 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 +147,7 @@ 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; } static bool scr_message_listed(const ScrMessageEncoder *encoder, const ScrDyn *value) { @@ -290,7 +269,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]; @@ -360,7 +342,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); @@ -482,7 +467,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 +483,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 +663,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 +756,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, count, encoder->storage, encoder->releases, + !encoder->shared && !encoder->adopts}; memcpy(nodes, encoder->nodes, count * sizeof(*nodes)); if (typed) memcpy(records, encoder->typed, typed * sizeof(*records)); size_t first = 0; @@ -1014,6 +1001,28 @@ done:; return result; } +bool scr_message_readable(const ScrMessage *message) { return message->readable; } + +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_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/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/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/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/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/self-hosting-native-toolchain.test.ts b/tests/harness/self-hosting-native-toolchain.test.ts index 176caa516..c0176eb93 100644 --- a/tests/harness/self-hosting-native-toolchain.test.ts +++ b/tests/harness/self-hosting-native-toolchain.test.ts @@ -108,7 +108,7 @@ for (const backend of ["llvm"] as const) { object_format: target.objectFormat, minimum_os: target.minimumOs, }, - runtime_abi: { version: 26, marker: "scr_runtime_abi_v26" }, + runtime_abi: { version: 27, marker: "scr_runtime_abi_v27" }, compiler: { command: "fixture", identity: "fixture", target: target.llvmTriple }, macros: { executable: [], excluded: [], sanitizer: "external-toolchain-required" }, flavors: { From 87162a491d4b0f4819bc6577f0045f02a3774912 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 07:20:14 -0500 Subject: [PATCH 077/102] Index dispatch receivers by name instead of testing each one ClassDynamicDispatch.process tested every property receiver for every property dispatch and for every method name a dynamic call names, in every pass: on the flat tsc-ts bundle, 9.2 million receiver tests per build. It now indexes each receiver list once by the method, generic method, accessor and field names along each receiver's base chain, and tests only the receivers listed under a name, plus the ones whose emitter, stream or EventTarget root answers names of its own, in list order. Names that the test decides on every receiver (compiler names, constructor, stack) and emit-override specializations still test every receiver. SCRIPTC_CHECK_DISPATCH_CANDIDATES=1 checks each selection against a test of every receiver. --- .../lowering/class-dynamic-dispatch.ts | 149 ++++++++++++++++-- 1 file changed, 132 insertions(+), 17 deletions(-) diff --git a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts index fefe85d0c..79edae433 100644 --- a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts +++ b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts @@ -1,4 +1,5 @@ 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"; @@ -467,6 +468,77 @@ 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 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); + add( + members, + name.startsWith("get:") || name.startsWith("set:") ? name.slice(4) : name, + position, + ); + } + 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); @@ -1342,10 +1414,31 @@ 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); + return mergePositions(found[table].get(name) ?? [], 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 ( @@ -1364,7 +1457,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; }; @@ -2898,24 +2997,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) && - !dateInheritedMember(lowerer, 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); From 930ee4e63a5f79d3d9414f596cae814e8e6b6c06 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 07:20:38 -0500 Subject: [PATCH 078/102] Answer binary requests in the literal-values test transport Object replies are read through binary() since the checker objects are resolved from their ids, so the test transport answers both forms. --- .../src/frontend/literal-values.test.ts | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) 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; From 3800a7d31158b3ff72559b53d779b281da1917ac Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 07:37:58 -0500 Subject: [PATCH 079/102] Version dense array loops bounded by an invariant limit A counted loop whose limit is an invariant value other than the array's length, such as `j < n` after `const n = a.length`, gets the same fast copy as a loop to `a.length`: one test before the loop bounds the limit by 2^31 - 1 and by each indexed array's hole-free prefix, for every array the loop provably never resizes, and the fast copy reads those slots directly. The length proof accepts number and boolean writes to class fields, which run no user code, and borrowed element reads in a fast copy load the slot without the prefix test or the runtime call. The fast copy's loop body may hold up to 160 IR nodes. --- .../backend/llvm/dense-array-loops.test.ts | 85 +++++++++++---- .../src/backend/llvm/dense-array-loops.ts | 85 +++++++++++---- .../src/backend/llvm/local-array-reads.ts | 18 ++++ .../src/ir/array-length-stability.test.ts | 26 +++++ .../compiler/src/ir/array-length-stability.ts | 9 ++ ...-array-dense-loop-invariant-limits.ts.json | 6 ++ .../7320-array-dense-loop-invariant-limits.ts | 101 ++++++++++++++++++ ...-array-dense-loop-invariant-limits.ts.json | 1 + 8 files changed, 291 insertions(+), 40 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7320-array-dense-loop-invariant-limits.ts.json create mode 100644 tests/corpus/7320-array-dense-loop-invariant-limits.ts create mode 100644 tests/harness/corpus-costs/7320-array-dense-loop-invariant-limits.ts.json 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..32c9cccab 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,23 @@ 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, + ...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 +137,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/local-array-reads.ts b/packages/compiler/src/backend/llvm/local-array-reads.ts index 45d046e1f..cdd00c4e7 100644 --- a/packages/compiler/src/backend/llvm/local-array-reads.ts +++ b/packages/compiler/src/backend/llvm/local-array-reads.ts @@ -586,6 +586,24 @@ 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)}`); + 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. 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/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/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/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 } From c297971f130d183cb0f39fa1a8991d0728e96340 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 07:41:13 -0500 Subject: [PATCH 080/102] Report JSX-lowered files to the checker server as changed The program the lowering compiles serves each file that has JSX at its own path, with the JSX rewritten to calls (host.addVirtualFile). The host reported such a path to the checker server as created whenever it was not virtual yet. The files exist on disk and the server had already read them for the program that checks them as written, so tsgo kept their original text, and lowering met the JSX syntax: SC1090 "syntax 'JsxFragment' is not supported yet" in 6822, 6824 and 6825 under SCRIPTC_CHECKER=tsgo, while tsc-ts reread the files. A virtual file that replaces a file on disk is now reported as changed, and both checkers give the same LLVM IR and diagnostics for the JSX corpus programs. --- packages/compiler/src/frontend/ts7/program-host.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/compiler/src/frontend/ts7/program-host.ts b/packages/compiler/src/frontend/ts7/program-host.ts index c87da0bfe..639086e94 100644 --- a/packages/compiler/src/frontend/ts7/program-host.ts +++ b/packages/compiler/src/frontend/ts7/program-host.ts @@ -192,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); } From 906f9911a148b4e1f54c0b4e195bafa92b629824 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 07:45:48 -0500 Subject: [PATCH 081/102] Keep a callback's captured scalars in registers in loops that call it A call through a binding that the constant-callback census resolves keeps a fallback through the closure's code pointer. In a loop that fallback is an unknown call that takes the closure, so the closure's code pointer, its captures and a captured `let` were reloaded, and the `let` stored back, on every iteration of `let s = 0; a.forEach((v) => { s = (s + v) | 0; })`. A for, while or do-while loop that calls such a binding now tests once, before the loop, that the binding's closure has the known code pointer. The copy where the test holds calls the function directly with no fallback, and the other copy is the ordinary loop. A closure's code pointer is set only when the closure is built and the census resolves only bindings the function never rebinds, so one test covers the loop. Only bindings declared before the loop qualify, and loops are versioned up to a size bound. Number and boolean box payloads get an alias category of their own, so a store to a captured `let` no longer aliases element loads and other memory in the loop. With the closure built in the caller, the test folds after inlining and the captured `let` stays in a register. --- .../src/backend/llvm/emit-function.ts | 2 + .../src/backend/llvm/emit-statements.ts | 117 ++++++++++++++ packages/compiler/src/backend/llvm/emitter.ts | 45 +++++- .../compiler/src/backend/llvm/expr-calls.ts | 27 ++-- .../test/callback-loop-versions.test.ts | 83 ++++++++++ .../7300-callback-captured-scalars.ts.json | 6 + .../corpus/7300-callback-captured-scalars.ts | 147 ++++++++++++++++++ .../7300-callback-captured-scalars.ts.json | 1 + 8 files changed, 406 insertions(+), 22 deletions(-) create mode 100644 packages/compiler/test/callback-loop-versions.test.ts create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7300-callback-captured-scalars.ts.json create mode 100644 tests/corpus/7300-callback-captured-scalars.ts create mode 100644 tests/harness/corpus-costs/7300-callback-captured-scalars.ts.json diff --git a/packages/compiler/src/backend/llvm/emit-function.ts b/packages/compiler/src/backend/llvm/emit-function.ts index 09e6551c3..9e8f7d701 100644 --- a/packages/compiler/src/backend/llvm/emit-function.ts +++ b/packages/compiler/src/backend/llvm/emit-function.ts @@ -83,6 +83,8 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { } 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; diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index 7239db7d8..618464e88 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -55,6 +55,7 @@ import { emitBytesLoopVersionGuard } 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"; @@ -76,6 +77,9 @@ import { } from "./string-construction.js"; import { emitStringInputs } from "./string-lifetimes.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; emitter.frames.push([]); @@ -795,6 +799,11 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { break; } case "while": { + const callbacks = callbackVersionBindings(emitter, s); + if (callbacks) { + emitCallbackVersionedLoop(emitter, s, callbacks); + break; + } const workerBudget = emitter.workerLoopBudget(s); const le = B.newLabel("loop.e"); emitter.emitLoopCopies(s, true, le, (exit) => { @@ -827,6 +836,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"); @@ -855,6 +869,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 = @@ -1885,6 +1904,104 @@ 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 that + * an enclosing version has not already proved, qualify: the guard reads + * each binding before the loop runs. */ +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.has(s) + ) + 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" && + !emitter.knownCallbacks.has(e.callee.localId) && + !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); +} + /** 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 diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index ed1785912..9170db7d2 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -831,6 +831,12 @@ export class LlEmitter { readonly callLifetimes: CallLifetimes; readonly constantCallbacks: Map>; currentConstantCallbacks: ReadonlyMap = new Map(); + /** 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; @@ -3901,6 +3907,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(); @@ -3914,12 +3939,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)`); @@ -3933,11 +3964,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})`); diff --git a/packages/compiler/src/backend/llvm/expr-calls.ts b/packages/compiler/src/backend/llvm/expr-calls.ts index f0aa3b276..4bcf2a3d5 100644 --- a/packages/compiler/src/backend/llvm/expr-calls.ts +++ b/packages/compiler/src/backend/llvm/expr-calls.ts @@ -29,7 +29,6 @@ import { mangleClassStruct, mangleFnClosure, mangleFunction, - mangleWrapper, mangleVtStruct, mangleAsyncDirectSpawn, } from "../mangle.js"; @@ -839,21 +838,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 +926,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 { 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..c26abe1c4 --- /dev/null +++ b/packages/compiler/test/callback-loop-versions.test.ts @@ -0,0 +1,83 @@ +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"); +}); 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/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/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 } From f0c48e1b399cb7aa44ddfad988b678f9c6c3154d Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 08:03:32 -0500 Subject: [PATCH 082/102] Bound compiled regex reads by the characters left in the subject The 16-character searches (the first-character search, the start filter and greedy class loops) and literal runs checked `i + n <= len` in 32-bit arithmetic. Subjects may be up to 2^31 - 2 characters, so near that length the sum wrapped negative, passed the check and read past the subject. Each check now compares the characters left (`len - i`, which cannot wrap) with the characters it reads, and advances the position only after it passes. --- .../src/backend/llvm/regex-matchers.ts | 28 +++--- .../test/regex-matcher-bounds.test.ts | 91 +++++++++++++++++++ 2 files changed, 106 insertions(+), 13 deletions(-) create mode 100644 packages/compiler/test/regex-matcher-bounds.test.ts diff --git a/packages/compiler/src/backend/llvm/regex-matchers.ts b/packages/compiler/src/backend/llvm/regex-matchers.ts index 77f8a06eb..d83d6bae5 100644 --- a/packages/compiler/src/backend/llvm/regex-matchers.ts +++ b/packages/compiler/src/backend/llvm/regex-matchers.ts @@ -882,16 +882,13 @@ 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`); - if (reach === 0) { - this.line(`${fits} = icmp sle i32 ${i16}, %len`); - } else { - const last = this.tmp(); - this.line(`${last} = add i32 ${i16}, ${reach}`); - this.line(`${fits} = icmp sle i32 ${last}, %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 = filter !== null ? this.testPrefix(filter, i) : this.testVector(plan!, i), @@ -899,6 +896,7 @@ class RxGen { 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), @@ -1149,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 = ""; @@ -1171,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`); @@ -1377,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(); @@ -1390,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(); 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 }); + } + }, +); From 866c0bfea5a22bff19537bf33f8c375fc7d8823c Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 08:05:45 -0500 Subject: [PATCH 083/102] Version typed-array loops whose index adds an unranged invariant term A row-major dot product, `const base = r * cols; for (let j = 0; j < cols; j++) s += w[base + j] * v[j]`, kept one index test per `w` read: the typed-array loop version guard covered an index `k * counter + terms + c` only when every loop-invariant term had a proven integer range, and `base` has none when `cols` is a parameter. The guard now also accepts a pure loop-invariant term without a proven range. It evaluates the term once and requires an exact integer (not -0) between -2^32 and 2^32, then checks the first and last index as for any affine index. In the fast copy the term has that range, so the index is integer arithmetic and the reads take no index test. Any other value runs the checked copy. Adds a Float32Array matrix-vector product with four accumulators per row to the typed-array-kernels workload. --- benchmarks/runtime/README.md | 2 +- .../runtime/workloads/typed-array-kernels.ts | 31 ++++++- .../backend/llvm/bytes-loop-versions.test.ts | 33 +++++++ .../src/backend/llvm/bytes-loop-versions.ts | 89 ++++++++++++++++--- ...-typed-array-invariant-index-terms.ts.json | 6 ++ .../6997-typed-array-invariant-index-terms.ts | 78 ++++++++++++++++ ...-typed-array-invariant-index-terms.ts.json | 1 + 7 files changed, 227 insertions(+), 13 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6997-typed-array-invariant-index-terms.ts.json create mode 100644 tests/corpus/6997-typed-array-invariant-index-terms.ts create mode 100644 tests/harness/corpus-costs/6997-typed-array-invariant-index-terms.ts.json diff --git a/benchmarks/runtime/README.md b/benchmarks/runtime/README.md index cbf47675a..1e01aa3a7 100644 --- a/benchmarks/runtime/README.md +++ b/benchmarks/runtime/README.md @@ -26,7 +26,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, and a row-major `Float32Array` matrix-vector product | | `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/typed-array-kernels.ts b/benchmarks/runtime/workloads/typed-array-kernels.ts index ba68f7241..4fd2e7cd7 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,23 @@ 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; + } +} + function gray(rgba: Uint8Array, out: Uint8Array): void { for (let i = 0; i < out.length; i++) { const j = i * 4; @@ -45,6 +63,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 +87,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 +97,7 @@ let byteSum = 0; let intSum = 0; let brightSum = 0; let lumaSum = 0; +let productSum = 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 +107,14 @@ 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); const probe = (r * 104729) & (n - 1); f64Sum += d[probe]!; f32Sum += fo[probe]!; @@ -95,6 +122,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 +130,4 @@ console.log(`uint8 ${byteSum}`); console.log(`int32 ${intSum}`); console.log(`clamped ${brightSum}`); console.log(`gray ${lumaSum}`); +console.log(`matvec ${productSum.toFixed(3)}`); 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 28194c7b3..ace8f294c 100644 --- a/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts +++ b/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts @@ -134,6 +134,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))]); diff --git a/packages/compiler/src/backend/llvm/bytes-loop-versions.ts b/packages/compiler/src/backend/llvm/bytes-loop-versions.ts index 8c7f668a0..c3cee3feb 100644 --- a/packages/compiler/src/backend/llvm/bytes-loop-versions.ts +++ b/packages/compiler/src/backend/llvm/bytes-loop-versions.ts @@ -7,6 +7,7 @@ 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"; type Node = IrExpr | IrStmt; type VarRef = IrExpr & { kind: "varRef" }; @@ -50,6 +51,9 @@ export interface BytesLoopVersion { ownedReceivers: number[]; fixed: FixedCheck[]; affine: AffineCheck[]; + /** 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]. */ @@ -83,6 +87,9 @@ const MAX_FIXED_END = 2 ** 32; 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 +102,9 @@ 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. * * 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 @@ -198,9 +207,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 +218,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 +246,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,7 +333,7 @@ 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); @@ -433,7 +457,7 @@ export function matchBytesLoopVersion( 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; } @@ -447,6 +471,12 @@ export function matchBytesLoopVersion( 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); // 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])); @@ -470,6 +500,7 @@ export function matchBytesLoopVersion( minOffset: g.check.minOffset, maxEnd: g.check.maxEnd, })), + guarded, counted: affineKept.length > 0 ? counted : null, counterBound: needsBound ? bound : null, ranges, @@ -567,6 +598,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 = emitGuardedTerm(host, value.name); + 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. @@ -614,6 +653,34 @@ export function emitBytesLoopVersionGuard( else B.condBr(valid, fast, slow); } +/** Tests that a guarded term is an exact integer within GUARDED_TERM (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 emitGuardedTerm(host: LlvmEmitterContext, value: string): { 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(GUARDED_TERM.min)}`); + B.line(`${high} = fcmp ole double ${value}, ${f64Lit(GUARDED_TERM.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/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/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/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 } From e4a9940e5b4d45170992c3094cd7888dbf064fdb Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 08:07:12 -0500 Subject: [PATCH 084/102] Finish bailed speculative iterations outside the ordinary loop copy A speculative integer loop's failed check used to continue at the failed statement inside the ordinary copy. That gave the ordinary copy a second entry, so LLVM saw an irreducible cycle and did not hoist its invariant loads or keep its values in registers. A loop whose check fails on every entry, such as an inner loop over fractional fields, then ran every iteration in that unoptimized copy. A failed check now continues in a third copy that is entered only from the fast copy: it re-executes the failed statement, the rest of the body and the update, then jumps to the ordinary copy's header. The ordinary copy has a single entry and stays a natural loop. Each loop site also counts its entries in a row whose fast copy bailed. A fast copy that completes a speculated write and leaves the loop clears the count, and after 8 bailing entries in a row the site runs the ordinary copy only. The count is a hint, read and written with unordered atomics: both copies give the same results. --- .../src/backend/llvm/emit-statements.ts | 100 ++++++++++++++-- packages/compiler/src/backend/llvm/emitter.ts | 11 ++ .../test/speculative-loop-emission.test.ts | 85 ++++++++++++++ .../7321-speculative-loop-bail-sites.ts.json | 6 + .../7321-speculative-loop-bail-sites.ts | 111 ++++++++++++++++++ .../7321-speculative-loop-bail-sites.ts.json | 1 + 6 files changed, 304 insertions(+), 10 deletions(-) create mode 100644 packages/compiler/test/speculative-loop-emission.test.ts create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7321-speculative-loop-bail-sites.ts.json create mode 100644 tests/corpus/7321-speculative-loop-bail-sites.ts create mode 100644 tests/harness/corpus-costs/7321-speculative-loop-bail-sites.ts.json diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index 7239db7d8..a22de3445 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -803,6 +803,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({ @@ -835,6 +836,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, @@ -1135,6 +1137,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(); @@ -1885,6 +1888,10 @@ export function emitSwitch(emitter: LlEmitter, s: IrStmt & { kind: "switch" }): B.startBlock(end); } +/** 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 @@ -1939,23 +1946,66 @@ 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 = `@scr.spec.bails.${emitter.speculativeLoopSites++}`; + emitter.declare(`${bails} = internal global i8 0`); + 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( @@ -1992,22 +2042,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 @@ -2134,7 +2205,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`); @@ -2145,6 +2217,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); } diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index ed1785912..c1cf66af4 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -1102,9 +1102,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). */ 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..78a7de295 --- /dev/null +++ b/packages/compiler/test/speculative-loop-emission.test.ts @@ -0,0 +1,85 @@ +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); + const slow = order.findIndex((l) => l.startsWith("spec.slow")); + const tail = order.findIndex((l) => l.startsWith("spec.tail")); + const fast = order.findIndex((l) => l.startsWith("spec.fast")); + expect(slow).toBeGreaterThanOrEqual(0); + expect(tail).toBeGreaterThan(slow); + expect(fast).toBeGreaterThan(tail); + // Every resume point is in the third copy, between its start and the + // fast copy, so the ordinary copy has one entry. + const resumes = order.flatMap((l, i) => (l.startsWith("spec.resume") ? [i] : [])); + expect(resumes.length).toBeGreaterThan(0); + for (const i of resumes) { + expect(i).toBeGreaterThan(tail); + expect(i).toBeLessThan(fast); + } + // 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}`); +}); + +test("a loop site stops entering its fast copy after repeated bails", async () => { + const llvm = await emitLlvm(source); + const site = /^(@scr\.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] ?? ""; + const escaped = site!.replace(/\./g, "\\."); + // 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 ${escaped} 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/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/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/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 } From fbb4fbc5b0c59c91bbb6f2e3fc15f97c7fa203dc Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 08:07:37 -0500 Subject: [PATCH 085/102] Encode posted records from their fields, and queue a message in one block postMessage of a typed record boxes it as a live record capsule, and the message encoder materialized the capsule's checked-dynamic view to read it: it built the view object, listed its own keys, tested each one for enumerability and read it back, then released the view and the key list. On an object-only run of bench/channel-messages that was about half of the encode time. - A live record capsule whose view was never created (no undeclared properties, no writes through an untyped view) now encodes from the record's field hooks (ScrDynTypedRecordOps), which answer exactly the view's keys, order and boxed values. Nested records encode the same way to a depth of 32, then through their views as before. Capsules with a view, published values, and every other value encode as before. - The mail event that carries a message lives in the message's block, so a queued message is one allocation instead of two. Corpus 7139 and 7360 post typed records on a MessageChannel and between a worker and the main thread: optional fields, nested records, a record reached twice, a chain deeper than the recursion limit, a parsed record with undeclared keys, and a function-valued field. --- .../corpus/7139-message-typed-records.ts.json | 6 ++ .../corpus/7360-worker-typed-records.ts.json | 6 ++ packages/runtime/src/scr_dyn.h | 3 + packages/runtime/src/scr_json.c | 4 ++ packages/runtime/src/scr_mailbox.c | 8 ++- packages/runtime/src/scr_mailbox.h | 5 ++ packages/runtime/src/scr_message.c | 53 +++++++++++++++++- packages/runtime/src/scr_worker.c | 5 +- tests/corpus/7139-message-typed-records.ts | 55 +++++++++++++++++++ tests/corpus/7360-worker-typed-records.ts | 37 +++++++++++++ .../7139-message-typed-records.ts.json | 1 + .../7360-worker-typed-records.ts.json | 1 + 12 files changed, 177 insertions(+), 7 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7139-message-typed-records.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7360-worker-typed-records.ts.json create mode 100644 tests/corpus/7139-message-typed-records.ts create mode 100644 tests/corpus/7360-worker-typed-records.ts create mode 100644 tests/harness/corpus-costs/7139-message-typed-records.ts.json create mode 100644 tests/harness/corpus-costs/7360-worker-typed-records.ts.json 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/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/runtime/src/scr_dyn.h b/packages/runtime/src/scr_dyn.h index 2602e0341..62987708a 100644 --- a/packages/runtime/src/scr_dyn.h +++ b/packages/runtime/src/scr_dyn.h @@ -364,6 +364,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 diff --git a/packages/runtime/src/scr_json.c b/packages/runtime/src/scr_json.c index 355a34aee..1c85a928a 100644 --- a/packages/runtime/src/scr_json.c +++ b/packages/runtime/src/scr_json.c @@ -3591,6 +3591,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. */ 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_message.c b/packages/runtime/src/scr_message.c index 508266103..29cbb1be0 100644 --- a/packages/runtime/src/scr_message.c +++ b/packages/runtime/src/scr_message.c @@ -1,4 +1,5 @@ #include "scr_message.h" +#include "scr_mailbox.h" #include #include @@ -72,6 +73,7 @@ struct ScrMessage { 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 { @@ -98,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; @@ -121,6 +127,7 @@ typedef struct { 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]; @@ -148,6 +155,7 @@ static void scr_message_encoder_init(ScrMessageEncoder *encoder, const ScrDyn *t encoder->transfer = transfer; encoder->uncaught = uncaught; encoder->storage = encoder->releases = encoder->shared = encoder->adopts = false; + encoder->record_depth = 0; } static bool scr_message_listed(const ScrMessageEncoder *encoder, const ScrDyn *value) { @@ -321,6 +329,9 @@ 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 size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) { bool uncaught = encoder->uncaught; encoder->uncaught = false; @@ -382,6 +393,39 @@ 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; + 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); + } + 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; @@ -756,8 +800,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, - !encoder->shared && !encoder->adopts}; + *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; @@ -1003,6 +1047,11 @@ done:; 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; } 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/tests/corpus/7139-message-typed-records.ts b/tests/corpus/7139-message-typed-records.ts new file mode 100644 index 000000000..678b9cc48 --- /dev/null +++ b/tests/corpus/7139-message-typed-records.ts @@ -0,0 +1,55 @@ +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); +} 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/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/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 } From d406f633bdb2d609e8c9a85a107ff275fe46bf28 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 08:18:18 -0500 Subject: [PATCH 086/102] Keep the receiver index within what the native frontend lowers The receiver index read its methods or members table by a computed key and iterated generic method names through `?.keys() ?? []`. The native frontend refuses dynamic keyed reads of records and cannot convert the iterator-or-array union, so the complete frontend no longer lowered. The table is now selected with a conditional and the generic method names are iterated under a check. --- .../frontend/lowering/class-dynamic-dispatch.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts index 79edae433..79deb2aeb 100644 --- a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts +++ b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts @@ -510,10 +510,11 @@ function receiverIndex(lowerer: Lowerer, plans: readonly PropertyReceiver[]): Re position, ); } - for (const name of c.genericMethods?.keys() ?? []) { - add(methods, name, position); - add(members, name, 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); }); @@ -1430,9 +1431,8 @@ export class ClassDynamicDispatch { ): readonly PropertyReceiver[] => { if (name.startsWith("emit:")) return plans; const found = indexOf(plans); - return mergePositions(found[table].get(name) ?? [], found.rooted).map( - (position) => plans[position]!, - ); + 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); From 2f3e25b431fc13f0f8a08fdb0505b0c277dc734a Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 08:35:56 -0500 Subject: [PATCH 087/102] Accept Buffer-compatible chunk annotations and keep super(undefined) in byte mode --- .../src/frontend/lowering/lower-stream.ts | 18 ++++++---- tests/corpus/7240-objectmode-streams.ts | 33 ++++++++++++++++- .../stream-byte-mode-chunk-fences.ts | 36 +++++++++++++++++++ .../stream-byte-mode-chunk-fences.ts.txt | 8 +++++ 4 files changed, 87 insertions(+), 8 deletions(-) create mode 100644 tests/diagnostics/stream-byte-mode-chunk-fences.ts create mode 100644 tests/harness/__snapshots__/stream-byte-mode-chunk-fences.ts.txt diff --git a/packages/compiler/src/frontend/lowering/lower-stream.ts b/packages/compiler/src/frontend/lowering/lower-stream.ts index cb81348eb..6540b3a99 100644 --- a/packages/compiler/src/frontend/lowering/lower-stream.ts +++ b/packages/compiler/src/frontend/lowering/lower-stream.ts @@ -312,11 +312,13 @@ function lowerStreamCallback( // 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 is the fence's; an encoding - // of another type (`string | null | undefined`) converts from the - // encoding argument's value. + // 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) || i === 1) && + ((i === 0 && (chunkValues || widensInto(lowerer, fullTuple[0]!, funcType.params[0]!, loc))) || + i === 1) && (which === "write" || which === "transform") && funcType.params[i]!.kind !== "func" && canConvertToDyn( @@ -1369,11 +1371,13 @@ export function lowerStreamSuperCall( // 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 = - argNodes[0] !== undefined && - (optsNode === null || - !ts.isObjectLiteralExpression(optsNode) || + 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); diff --git a/tests/corpus/7240-objectmode-streams.ts b/tests/corpus/7240-objectmode-streams.ts index 9316ff480..47f799eee 100644 --- a/tests/corpus/7240-objectmode-streams.ts +++ b/tests/corpus/7240-objectmode-streams.ts @@ -2,7 +2,8 @@ // 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. +// 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"; @@ -119,6 +120,34 @@ async function collections(): Promise { 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(); @@ -126,5 +155,7 @@ async function main(): Promise { sided(); duplex(); passthrough(); + await new Promise((resolve) => setTimeout(resolve, 5)); + await byteChunks(); } main(); 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/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 From 6e75e59f753e9dd25ba5b915220f036d2421bc10 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 08:52:18 -0500 Subject: [PATCH 088/102] Check each speculative site of a loop in the third-copy emission test Since dense-array loops bounded by an invariant limit are versioned, the test's loop has a speculative site in each dense copy. The test paired every resume point with the first site's labels; it now checks each site's resume points against that site's third and fast copies. --- .../test/speculative-loop-emission.test.ts | 43 +++++++++++-------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/packages/compiler/test/speculative-loop-emission.test.ts b/packages/compiler/test/speculative-loop-emission.test.ts index 78a7de295..a691d856d 100644 --- a/packages/compiler/test/speculative-loop-emission.test.ts +++ b/packages/compiler/test/speculative-loop-emission.test.ts @@ -47,24 +47,33 @@ 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); - const slow = order.findIndex((l) => l.startsWith("spec.slow")); - const tail = order.findIndex((l) => l.startsWith("spec.tail")); - const fast = order.findIndex((l) => l.startsWith("spec.fast")); - expect(slow).toBeGreaterThanOrEqual(0); - expect(tail).toBeGreaterThan(slow); - expect(fast).toBeGreaterThan(tail); - // Every resume point is in the third copy, between its start and the - // fast copy, so the ordinary copy has one entry. - const resumes = order.flatMap((l, i) => (l.startsWith("spec.resume") ? [i] : [])); - expect(resumes.length).toBeGreaterThan(0); - for (const i of resumes) { - expect(i).toBeGreaterThan(tail); - expect(i).toBeLessThan(fast); + // 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}`); } - // 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 () => { From 142e10a0c428065a37eac0228b3a2b83fef5694f Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 08:55:08 -0500 Subject: [PATCH 089/102] Run counters that step beside a counted loop's counter as integers `for (let i = 0, p = 0; i < count; i++, p += 4)` kept both counters as doubles: the counted-loop match takes a single declaration and a single update. A counted loop now also accepts further counters declared in its head and stepped by a constant in its update, when the condition does not read them and the body does not write them. On body entry k such a counter holds `start + step * k`, so its range follows from the driver's: k is at most the driver's span over its step. When that range can pass 2^53, the versioned loop tests `|start| + |step| * span / |driver step| <= 2^52` at run time, and an unproven start is tested for an exact safe integer, as the driver's is. Nested update blocks (`i++, j += 2, k--`) are flattened. Byte windows and dense loops still take only single-counter loops. --- .../src/backend/llvm/counted-loops.ts | 45 ++++- .../backend/llvm/dense-array-loops.test.ts | 1 + .../src/backend/llvm/emit-statements.ts | 36 +++- .../compiler/src/ir/integer-loops.test.ts | 100 ++++++++++ packages/compiler/src/ir/integer-loops.ts | 188 +++++++++++++----- .../7141-comoving-loop-counters.ts.json | 6 + tests/corpus/7141-comoving-loop-counters.ts | 144 ++++++++++++++ .../7141-comoving-loop-counters.ts.json | 1 + 8 files changed, 467 insertions(+), 54 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7141-comoving-loop-counters.ts.json create mode 100644 tests/corpus/7141-comoving-loop-counters.ts create mode 100644 tests/harness/corpus-costs/7141-comoving-loop-counters.ts.json 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-loops.test.ts b/packages/compiler/src/backend/llvm/dense-array-loops.test.ts index 32c9cccab..f7a4bc892 100644 --- a/packages/compiler/src/backend/llvm/dense-array-loops.test.ts +++ b/packages/compiler/src/backend/llvm/dense-array-loops.test.ts @@ -120,6 +120,7 @@ const counted = ( limitGuarded: false, startGuarded: false, guardLimit: 0, + followers: [], ...fields, }); diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index 7239db7d8..c493f6c9c 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -879,8 +879,9 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { !integerLoop && !countedLoop && 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 && emitter.byteWindowsEnabled ? matchByteWindow( s, countedLoop, @@ -898,7 +899,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 = @@ -1030,6 +1031,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( @@ -1073,6 +1075,23 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { ? 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]) { @@ -1212,6 +1231,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(); @@ -1227,7 +1253,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); diff --git a/packages/compiler/src/ir/integer-loops.test.ts b/packages/compiler/src/ir/integer-loops.test.ts index 24bbf5be0..e1453abad 100644 --- a/packages/compiler/src/ir/integer-loops.test.ts +++ b/packages/compiler/src/ir/integer-loops.test.ts @@ -426,3 +426,103 @@ 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(); +}); diff --git a/packages/compiler/src/ir/integer-loops.ts b/packages/compiler/src/ir/integer-loops.ts index e80680d6e..c4cdc327c 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,68 @@ 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. + const trips = Math.floor( + (step > 0 ? range.max - startRange.min : startRange.max - range.min) / Math.abs(step), + ); + 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))); @@ -241,32 +354,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 +365,7 @@ export function matchIntegerCountedForLoop( startGuarded, guardLimit, range, + followers, }; } 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/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/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 } From 0318671352edbc3d699dc9beeaca53316af149d6 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 09:17:49 -0500 Subject: [PATCH 090/102] Reuse the class dispatch passes' per-function scans while bodies are unchanged --- .../lowering/caught-value-dispatch.ts | 24 +- .../frontend/lowering/class-construction.ts | 20 +- .../lowering/class-dynamic-dispatch.ts | 118 ++------ .../deferred-module-initializers.test.ts | 9 + .../lowering/deferred-module-initializers.ts | 14 +- .../frontend/lowering/dispatch-sites.test.ts | 60 ++++ .../src/frontend/lowering/dispatch-sites.ts | 272 ++++++++++++++++++ .../lowering/generator-dynamic-dispatch.ts | 50 ++-- .../compiler/src/frontend/lowering/lowerer.ts | 18 +- 9 files changed, 417 insertions(+), 168 deletions(-) create mode 100644 packages/compiler/src/frontend/lowering/dispatch-sites.test.ts create mode 100644 packages/compiler/src/frontend/lowering/dispatch-sites.ts 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-construction.ts b/packages/compiler/src/frontend/lowering/class-construction.ts index 30f504b4a..66ec547bc 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"; @@ -254,22 +255,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 fefe85d0c..f2ccb0ec6 100644 --- a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts +++ b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts @@ -77,6 +77,7 @@ 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, @@ -226,7 +227,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; @@ -780,6 +781,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; @@ -862,12 +865,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(); @@ -891,100 +895,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); 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..2618dacf9 --- /dev/null +++ b/packages/compiler/src/frontend/lowering/dispatch-sites.ts @@ -0,0 +1,272 @@ +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"; + +/** 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" && expr.fn === "dyn.destructureRest") + ) + 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/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/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index b02a0a843..7a2bfd9e7 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -8231,13 +8231,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, From ed66338cb6a2e47c7dfd409487b4fd22853973d5 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 09:25:44 -0500 Subject: [PATCH 091/102] Record the order-parity baseline for the byte-mode chunk fence fixture --- .../tests/diagnostics/stream-byte-mode-chunk-fences.ts.json | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/stream-byte-mode-chunk-fences.ts.json 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": [] +} From 279cdcffae822a41934914bd1f2f71ff4966659f Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 09:39:07 -0500 Subject: [PATCH 092/102] Name source files relative to the entry's directory in structural positions Structural positions started with a file's absolute path, so lowered names (closures, recursive records and unions, and every name keyed by a type that holds one) changed with the directory the program was compiled in. Union arms are ordered by their types' keys, so a program compiled in a new temporary directory could also get its union arms in another order. union-retype.test.ts compiles each program in a fresh temporary directory, and in about one run in ten the arms of the visitor's unions came out in an order where no retag keeps its tags, which failed "lowered identity retags share the box". Positions now name a file by its path relative to the entry's directory (default library files keep their base name), so the same program gets the same names wherever it sits. --- packages/compiler/src/frontend/lowering/lowerer.ts | 10 ++++++---- packages/compiler/test/stable-names.test.ts | 7 +++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/compiler/src/frontend/lowering/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index 7a2bfd9e7..747e396af 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -181,7 +181,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"; @@ -3192,12 +3192,14 @@ export class Lowerer { errorPropertyDispatchRevision: string | null = null; /** Structural source positions (structural-positions.ts) for names that * stay the same when unrelated code moves. */ - /** Default library files are named by their base name: two checkers - * install them in different directories. */ + /** 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)}` - : sf.fileName, + : relative(dirname(this.entry.fileName), sf.fileName), ); /** The outermost node whose token span is exactly `loc`, or null. */ diff --git a/packages/compiler/test/stable-names.test.ts b/packages/compiler/test/stable-names.test.ts index 720472556..c82db039d 100644 --- a/packages/compiler/test/stable-names.test.ts +++ b/packages/compiler/test/stable-names.test.ts @@ -110,3 +110,10 @@ console.log(box.value); 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!)); +}); From 8487742019e824472ad29a96135c2e3553147ca6 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 09:48:41 -0500 Subject: [PATCH 093/102] Read the shared decoded value after an untyped listener, and skip discriminated unions - Once a 'message' listener without a typed entry has decoded the message, the listeners after it read that decoded value, so a typed listener sees what an earlier untyped listener changed, as in Node. - A union with a literal discriminator gets no typed message entry: its checked conversion also tests the discriminator, which the message readers do not. Corpus 7361 checks a typed listener after an untyped one that changes the message, and a listener on a discriminated union. --- packages/compiler/src/backend/llvm/dyn.ts | 8 ++-- ...7361-message-listeners-share-value.ts.json | 6 +++ packages/runtime/src/scr_events_emitter.c | 9 ++-- packages/runtime/src/scr_events_emitter.h | 4 +- .../7361-message-listeners-share-value.ts | 45 +++++++++++++++++++ ...7361-message-listeners-share-value.ts.json | 1 + 6 files changed, 66 insertions(+), 7 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7361-message-listeners-share-value.ts.json create mode 100644 tests/corpus/7361-message-listeners-share-value.ts create mode 100644 tests/harness/corpus-costs/7361-message-listeners-share-value.ts.json diff --git a/packages/compiler/src/backend/llvm/dyn.ts b/packages/compiler/src/backend/llvm/dyn.ts index ac01a9209..5c9d8e60f 100644 --- a/packages/compiler/src/backend/llvm/dyn.ts +++ b/packages/compiler/src/backend/llvm/dyn.ts @@ -4681,8 +4681,8 @@ export class LlDyn { /** 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, with at most one - * number, boolean and string arm. */ + * 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": @@ -4706,7 +4706,9 @@ export class LlDyn { } case "union": { const def = this.host.unionsById.get(t.unionId); - if (!def || this.host.nullableUnions.has(t.unionId)) return false; + // 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; 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/runtime/src/scr_events_emitter.c b/packages/runtime/src/scr_events_emitter.c index 5e03c0d6c..93a724ecb 100644 --- a/packages/runtime/src/scr_events_emitter.c +++ b/packages/runtime/src/scr_events_emitter.c @@ -1049,8 +1049,8 @@ SCR_COLD static void scr_ee_listener_mismatch(const ScrStr *name, bool typed_emi } /* A message emit (scr_emitter_emit_message): listeners with a typed message - * entry read the message; the others share one decoded argument, made when - * the first of them runs. */ + * 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 *); @@ -1101,7 +1101,10 @@ static bool scr_ee_emit_core(ScrEmitter *em, ScrStr *name, va_list *ap_template, continue; } } - if (message && e->flex_message && e->flex_message(e->flex_cb, message->message)) { + /* 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; } diff --git a/packages/runtime/src/scr_events_emitter.h b/packages/runtime/src/scr_events_emitter.h index 6e1ef536a..29d4c397f 100644 --- a/packages/runtime/src/scr_events_emitter.h +++ b/packages/runtime/src/scr_events_emitter.h @@ -156,7 +156,9 @@ 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; the other listeners get decode(message), made once. */ + * 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 *)); 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/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 } From ddf7eb8a2bc226e215a9795f51cf3ac747c57572 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 09:50:32 -0500 Subject: [PATCH 094/102] Check with tsc-ts 0.0.7 and batch contextual types and signatures tsc-ts 0.0.7 answers getContextualTypes and getResolvedSignatures, so NODE_BATCH_QUERIES is on: lowering asks the checker for the contextual types of identity-flow sites, array literals and conditionals, and the resolved signatures of calls, in batches instead of node by node. The release-age exclusions move to tsc-ts 0.0.7 and its platform packages, and add @scriptc/threads 0.4.1, which tsc-ts 0.0.7 depends on. --- packages/compiler/package.json | 2 +- .../src/frontend/ts7/semantic-checker.ts | 9 +- pnpm-lock.yaml | 138 +++++++++--------- pnpm-workspace.yaml | 17 ++- 4 files changed, 83 insertions(+), 83 deletions(-) diff --git a/packages/compiler/package.json b/packages/compiler/package.json index 98d984d4f..a283f821a 100644 --- a/packages/compiler/package.json +++ b/packages/compiler/package.json @@ -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/src/frontend/ts7/semantic-checker.ts b/packages/compiler/src/frontend/ts7/semantic-checker.ts index d1d42c6e1..e7e6b408d 100644 --- a/packages/compiler/src/frontend/ts7/semantic-checker.ts +++ b/packages/compiler/src/frontend/ts7/semantic-checker.ts @@ -97,11 +97,10 @@ export interface SemanticCompletion { } /** Whether lowering asks the checker for contextual types and resolved - * signatures in batches (`getContextualTypes`, `getResolvedSignatures`). - * Off until scriptc depends on a tsc-ts release that answers them: the - * batch prefetches (checker.ts) then do nothing and lowering asks node by - * node. */ -export const NODE_BATCH_QUERIES = false; + * 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. */ +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 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2404c3885..589de2a51 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -55,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) @@ -110,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 @@ -271,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==} @@ -1360,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': @@ -1377,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] @@ -2577,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 @@ -2840,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 @@ -3090,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 @@ -3159,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' @@ -3340,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' @@ -3439,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': {} @@ -3454,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': @@ -3563,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) @@ -3571,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 @@ -3600,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' @@ -3638,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 @@ -4442,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 @@ -4460,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 @@ -4604,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 @@ -4619,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: @@ -4813,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 @@ -4894,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 @@ -4904,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: From cd2b1e2574ca8fde0f8516d7b8800a861246c312 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 09:55:01 -0500 Subject: [PATCH 095/102] Keep callback loop versions from nesting A callback loop version emits its loop twice. A loop inside either copy could be versioned again, so a nest of loops that each call a callback built just before them (`const g = adder(i)`) doubled at every level: a three-deep nest was emitted seven times per function. A loop inside a callback version, or the versioned loop itself emitted again for each copy, is no longer versioned, so a loop nest is emitted at most twice. The outer loop keeps its version; inner loops keep their calls as they are. --- .../src/backend/llvm/emit-statements.ts | 17 +++++----- .../test/callback-loop-versions.test.ts | 31 +++++++++++++++++++ 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index ffd47c467..4fe1a27bd 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -1910,9 +1910,11 @@ export function emitSwitch(emitter: LlEmitter, s: IrStmt & { kind: "switch" }): /** 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 that - * an enclosing version has not already proved, qualify: the guard reads - * each binding before the loop runs. */ + * 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" }, @@ -1920,7 +1922,7 @@ function callbackVersionBindings( if ( !emitter.callbackVersionsEnabled || emitter.currentConstantCallbacks.size === 0 || - emitter.callbackVersioning.has(s) + emitter.callbackVersioning.size > 0 ) return null; const found = new Map(); @@ -1930,12 +1932,7 @@ function callbackVersionBindings( 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" && - !emitter.knownCallbacks.has(e.callee.localId) && - !found.has(e.callee.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; diff --git a/packages/compiler/test/callback-loop-versions.test.ts b/packages/compiler/test/callback-loop-versions.test.ts index c26abe1c4..63a669fd4 100644 --- a/packages/compiler/test/callback-loop-versions.test.ts +++ b/packages/compiler/test/callback-loop-versions.test.ts @@ -81,3 +81,34 @@ test("a callback declared in the loop body is not read before the loop", async ( `); 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); +}); From b82c70d5de2853a368f13edb96ced5f14061fe2e Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 09:56:19 -0500 Subject: [PATCH 096/102] Bound a follower's trip count only by a safe-integer span The trip count that bounds a follower's range was the driver's span over its step, computed in doubles. A span above 2^53 - 1 can round down: from -(2^53 - 1) to below 2^52 - 1 the span 3 * 2^52 - 3 becomes 3 * 2^52 - 4, so a follower that reaches 2^53 got the range limit 2^53 - 1 and ran as an unchecked integer. Such a span now bounds no trip count, and the follower is tested at run time (or the loop is refused when every value is known). Below it the quotient rounds to at least its floor, and the follower's products and sums are exact within the safe range. --- packages/compiler/src/ir/integer-loops.test.ts | 16 ++++++++++++++++ packages/compiler/src/ir/integer-loops.ts | 10 ++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/compiler/src/ir/integer-loops.test.ts b/packages/compiler/src/ir/integer-loops.test.ts index e1453abad..b6ac27e3a 100644 --- a/packages/compiler/src/ir/integer-loops.test.ts +++ b/packages/compiler/src/ir/integer-loops.test.ts @@ -525,4 +525,20 @@ test("counters stepped beside the tested one run as integers", () => { 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 c4cdc327c..c451c0852 100644 --- a/packages/compiler/src/ir/integer-loops.ts +++ b/packages/compiler/src/ir/integer-loops.ts @@ -269,10 +269,12 @@ export function matchIntegerCountedForLoop( }; // 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. - const trips = Math.floor( - (step > 0 ? range.max - startRange.min : startRange.max - range.min) / Math.abs(step), - ); + // 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; From ca579641a45bebcd629b2081b101233613375596 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 10:04:30 -0500 Subject: [PATCH 097/102] Index quoted get: and set: method names under their own keys --- .../lowering/class-dynamic-dispatch.ts | 13 +++++----- .../class-quoted-accessor-keys.mjs.json | 6 +++++ tests/corpus/class-quoted-accessor-keys.mjs | 26 +++++++++++++++++++ .../class-quoted-accessor-keys.mjs.json | 1 + 4 files changed, 40 insertions(+), 6 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/class-quoted-accessor-keys.mjs.json create mode 100644 tests/corpus/class-quoted-accessor-keys.mjs create mode 100644 tests/harness/corpus-costs/class-quoted-accessor-keys.mjs.json diff --git a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts index 79deb2aeb..e792de957 100644 --- a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts +++ b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts @@ -477,7 +477,7 @@ interface ReceiverIndex { /** 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 property name), or a field it has. */ + * accessor under its key and under its property name), or a field it has. */ members: Map; rooted: number[]; } @@ -504,11 +504,12 @@ function receiverIndex(lowerer: Lowerer, plans: readonly PropertyReceiver[]): Re for (let c: ClassInfo | null = info; c; c = c.base) { for (const name of c.methods.keys()) { add(methods, name, position); - add( - members, - name.startsWith("get:") || name.startsWith("set:") ? name.slice(4) : 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()) { 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/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/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 } From 08081ca1a2185a824a4fe8068447ec39e8e924f7 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 10:22:22 -0500 Subject: [PATCH 098/102] Encode each field of a posted record completely before the next A typed record encoded from its field hooks queued a plain-object field on the visit stack and went on to the next field, so getters on later fields ran before the properties of earlier ones were read. Node's serializer finishes each field, nested properties included, before the next. The record path now drains the visit stack down to where it started after each field, so properties are read in Node's order. Corpus 7139 posts a record whose fields hold getter-bearing objects and prints the read order. --- packages/runtime/src/scr_message.c | 28 +++++++++++++++----- tests/corpus/7139-message-typed-records.ts | 30 ++++++++++++++++++++++ 2 files changed, 51 insertions(+), 7 deletions(-) diff --git a/packages/runtime/src/scr_message.c b/packages/runtime/src/scr_message.c index 29cbb1be0..d4eb263cf 100644 --- a/packages/runtime/src/scr_message.c +++ b/packages/runtime/src/scr_message.c @@ -331,6 +331,7 @@ static ScrDyn *scr_message_uncaught_keys(const ScrDyn *view) { 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; @@ -407,6 +408,9 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) 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); @@ -422,6 +426,10 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) 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; @@ -832,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; } @@ -843,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 @@ -854,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]); diff --git a/tests/corpus/7139-message-typed-records.ts b/tests/corpus/7139-message-typed-records.ts index 678b9cc48..35d0d1588 100644 --- a/tests/corpus/7139-message-typed-records.ts +++ b/tests/corpus/7139-message-typed-records.ts @@ -53,3 +53,33 @@ try { } 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(); From eef347115963cbe0723b0a53017b696b6f5f242e Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 10:46:38 -0500 Subject: [PATCH 099/102] Stop asking batch methods the checker server answers as unknown tsgo has no getContextualTypes or getResolvedSignatures. Each prefetch asked for them anyway, and a failed chunk was split and retried down to single nodes, so a tsgo build paid about two failed requests per prefetched node. The checker facade now remembers a batch method the server answers with "unknown API method" and asks those queries node by node from then on. --- packages/compiler/src/frontend/ts7/checker.ts | 40 +++++++++++++++++-- .../src/frontend/ts7/semantic-checker.ts | 3 +- packages/compiler/test/ts7/facade.test.ts | 31 ++++++++++++++ 3 files changed, 69 insertions(+), 5 deletions(-) diff --git a/packages/compiler/src/frontend/ts7/checker.ts b/packages/compiler/src/frontend/ts7/checker.ts index cd43636af..9550d1dc2 100644 --- a/packages/compiler/src/frontend/ts7/checker.ts +++ b/packages/compiler/src/frontend/ts7/checker.ts @@ -86,12 +86,19 @@ function batchAnswers( items: readonly I[], fetch: (chunk: readonly I[]) => readonly (O | undefined)[], store: (item: I, answer: O | undefined) => void, -): 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 { + } catch (error) { + if (unknown(error)) { + known = false; + return; + } if (chunk.length === 1) return; const mid = chunk.length >> 1; answer(chunk.slice(0, mid)); @@ -101,6 +108,13 @@ function batchAnswers( 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[] { @@ -239,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 @@ -374,7 +391,8 @@ export class CheckerFacade { if (!NODE_BATCH_QUERIES) return; this.ensureActive(); const missing = [...new Set(nodes)].filter((node) => !this.cache.contextualType.has(node)); - batchAnswers( + this.batchNodes( + "getContextualTypes", missing, (chunk) => this.raw.getContextualTypes(chunk), (node, type) => this.cache.contextualType.set(node, type), @@ -386,13 +404,27 @@ export class CheckerFacade { if (!NODE_BATCH_QUERIES) return; this.ensureActive(); const missing = [...new Set(nodes)].filter((node) => !this.cache.resolvedSignature.has(node)); - batchAnswers( + 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 * usual companion getTypeOfSymbol batch. Preflight uses this for AST * analyses that themselves inspect deferred bodies for binding identity: diff --git a/packages/compiler/src/frontend/ts7/semantic-checker.ts b/packages/compiler/src/frontend/ts7/semantic-checker.ts index e7e6b408d..c19f93598 100644 --- a/packages/compiler/src/frontend/ts7/semantic-checker.ts +++ b/packages/compiler/src/frontend/ts7/semantic-checker.ts @@ -99,7 +99,8 @@ export interface SemanticCompletion { /** 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. */ + * 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 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); From 9aaebbab254ac0ee6359e10eca248fefab0c3559 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 11:14:27 -0500 Subject: [PATCH 100/102] Prepare v0.4.2 release --- CHANGELOG.md | 156 +++++++++++++++++- packages/cli-darwin-arm64/package.json | 2 +- packages/cli-darwin-x64/package.json | 2 +- packages/cli-linux-arm64-gnu/package.json | 2 +- packages/cli-linux-arm64-musl/package.json | 2 +- packages/cli-linux-x64-gnu/package.json | 2 +- packages/cli-linux-x64-musl/package.json | 2 +- packages/cli-win32-x64-msvc/package.json | 2 +- packages/cli/package.json | 2 +- packages/compiler/package.json | 2 +- packages/compiler/surface-manifest.json | 2 +- packages/experimental/package.json | 2 +- packages/llvm-darwin-arm64/package.json | 2 +- packages/llvm-darwin-x64/package.json | 2 +- packages/llvm-linux-arm64-gnu/package.json | 2 +- packages/llvm-linux-arm64-musl/package.json | 2 +- packages/llvm-linux-x64-gnu/package.json | 2 +- packages/llvm-linux-x64-musl/package.json | 2 +- packages/llvm-win32-x64-msvc/package.json | 2 +- packages/runtime-android-arm64/package.json | 2 +- packages/runtime-darwin-arm64/package.json | 2 +- packages/runtime-darwin-x64/package.json | 2 +- packages/runtime-ios-arm64/package.json | 2 +- .../runtime-ios-simulator-arm64/package.json | 2 +- packages/runtime-linux-arm64-gnu/package.json | 2 +- .../runtime-linux-arm64-musl/package.json | 2 +- packages/runtime-linux-x64-gnu/package.json | 2 +- packages/runtime-linux-x64-musl/package.json | 2 +- packages/runtime-wasm32-wasi/package.json | 2 +- packages/runtime-win32-x64-msvc/package.json | 2 +- packages/runtime/package.json | 2 +- packages/threads/package.json | 2 +- packages/types/package.json | 2 +- 33 files changed, 186 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31d34e8db..2bdd47363 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,160 @@ 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 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 +231,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/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/compiler/package.json b/packages/compiler/package.json index a283f821a..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", diff --git a/packages/compiler/surface-manifest.json b/packages/compiler/surface-manifest.json index 45b3edbaa..637a5f831 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.", 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-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-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-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/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", From e39ddf3d00e0b1305f4ceff4534547adace32f5c Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 22 Oct 2026 13:18:04 -0500 Subject: [PATCH 101/102] Refresh the native compiler's optimization profile --- packages/compiler/native/cli.profdata.gz | Bin 1452782 -> 1634955 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/packages/compiler/native/cli.profdata.gz b/packages/compiler/native/cli.profdata.gz index 55523e76548ae821bbce8762876d84a3b3ccd182..e2f344a4d7f73f6e5b70e119a45c1e9db5fdf6d3 100644 GIT binary patch literal 1634955 zcmV);K!(2`iwFP!000021MD4loD)TNcXOTIj*fIt+V%oS@6tS~AcifocY$1TBst&& zDHe)~pjc2qu`8gWf`Vc}u>gvQilC@`B8s9YidX>oej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