Files
scriptc/packages/threads/index.js
T
Malte Ubl bf508eb70f Publish typed object graphs to workers by reference (@scriptc/threads)
The new @scriptc/threads package exports publish(value) and
sharesPublishedGraphs. Node.js runs its JavaScript: publish validates
the whole graph (plain objects, arrays, class instances, Maps, Sets and
primitives other than symbols), then deep-freezes it, and published Maps
and Sets reject mutation. scriptc builds lower both exports to
intrinsics and never compile the package body.

In scriptc, publish makes the graph immutable and immortal: a
compiler-emitted walker per static type (llvm/publish.ts) marks every
object rc == SIZE_MAX through a runtime worklist (scr_publish.c), so
retains, releases and the collector skip it and nothing frees it, and
the objects leave the collector's buffers. Hierarchy members dispatch on
the concrete class; arrays, maps, sets, strings and dyn subgraphs have
runtime walkers. Static types over-approximate a graph, so an
unpublishable type gets a refusing walker that fails only when a value
is present, and every mark is logged so a refusal restores the whole
graph, exactly like the Node implementation's validate-first order.

A typed-ref capsule over a published object travels through postMessage
and workerData as a pointer (a fresh capsule in the receiver; vtables,
adapters and type keys are process-wide); immortal dyn graphs inside a
message are shared the same way. Iterating a published map no longer
writes its iteration depth.

Stores into the static types a program publishes (computed by
backend/publication.ts, a class with its whole hierarchy) carry a guard
that throws Node's frozen-object TypeErrors, and may-throw counts them.
The corpus program pins the contract against Node: shared and cyclic
class graphs with arrays, maps, sets and records read identically on
both threads, every write form fails with Node's message, unpublished
instances of the same classes stay writable, a refused publish leaves
its graph unchanged, and a worker-published graph reaches the main
thread. packages/threads/README.md documents the contract and the
differences (prototypes and identity across messages).

Each mark records its object kind, so a successful publish takes the
objects out of the RC audit's live counts (immortal objects are never
freed).

Dates (time values) and process streams (descriptors) are scalars in
scriptc, so their walkers refuse a date field or root directly instead
of pushing its bits as a pointer; the refusal corpus program pins the
statically typed refusals (date, function, RegExp, typed array and Error
values in class and record fields, and a date root) against Node.

Main lowers a discarded or union-typed `xs.pop()` to a length
truncation; those stores now carry a `pop` marker so a published array
fails with pop's own TypeError ("Cannot delete property 'N'", or the
length message for an empty array, whose `length = 0` store the emitter
drops unless the array type can be published).
2026-10-10 01:00:36 -05:00

81 lines
3.0 KiB
JavaScript

// @scriptc/threads — the Node.js implementation.
//
// scriptc builds lower these exports to compiler intrinsics: publish() makes
// a graph immortal and immutable so postMessage and workerData share it with
// other threads by reference. Under Node.js, publish() gives the same graph
// the same immutability: it validates the whole graph first, then deep-freezes
// it, and Maps and Sets reject mutation. Node.js still clones what it posts,
// so receivers should publish() what they receive (a no-op in scriptc) and
// must not compare identity across messages.
/** True when postMessage and workerData deliver published graphs by reference
* (scriptc builds); false under Node.js, which clones them. */
export const sharesPublishedGraphs = false;
const published = new WeakSet();
function refuseMutation(kind) {
return function () {
throw new TypeError(`Cannot modify a published ${kind}`);
};
}
function describe(value) {
if (typeof value === "function") return "function";
if (typeof value === "symbol") return "symbol";
return Object.prototype.toString.call(value).slice(8, -1) + " object";
}
function refuse(value) {
throw new TypeError(`Cannot publish a ${describe(value)}`);
}
/** Publishes `value` and everything it reaches: plain objects, arrays, class
* instances, Maps, Sets and primitives other than symbols. Throws a TypeError,
* leaving the graph unchanged, when it reaches anything else (functions,
* symbols, accessor properties, Dates, RegExps, Errors, Promises, typed arrays
* and other built-in objects). Returns `value`. */
export function publish(value) {
const order = [];
const seen = new Set();
const stack = [value];
while (stack.length > 0) {
const v = stack.pop();
if (typeof v === "symbol") refuse(v);
if (v === null || (typeof v !== "object" && typeof v !== "function")) continue;
if (published.has(v) || seen.has(v)) continue;
if (typeof v === "function") refuse(v);
seen.add(v);
order.push(v);
if (v instanceof Map) {
for (const [key, item] of v) stack.push(key, item);
continue;
}
if (v instanceof Set) {
for (const item of v) stack.push(item);
continue;
}
const tag = Object.prototype.toString.call(v);
if (tag !== "[object Object]" && tag !== "[object Array]") refuse(v);
for (const key of Reflect.ownKeys(v)) {
if (typeof key === "symbol") refuse(key);
const descriptor = Object.getOwnPropertyDescriptor(v, key);
if (descriptor.get !== undefined || descriptor.set !== undefined)
throw new TypeError("Cannot publish an accessor property");
stack.push(descriptor.value);
}
}
for (const v of order) {
if (v instanceof Map) {
for (const name of ["set", "delete", "clear"])
Object.defineProperty(v, name, { value: refuseMutation("Map") });
} else if (v instanceof Set) {
for (const name of ["add", "delete", "clear"])
Object.defineProperty(v, name, { value: refuseMutation("Set") });
}
Object.freeze(v);
published.add(v);
}
return value;
}