@mica-js/simulator 2.7.1 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2132,2019 +2132,2448 @@ function standalone(code, cause, phase) {
2132
2132
  }));
2133
2133
  }
2134
2134
  //#endregion
2135
- //#region src/runtime/instance.ts
2136
- var EMPTY_MESSAGES = Object.freeze([]);
2137
- var jitModels = /* @__PURE__ */ new WeakMap();
2138
- /** Retain the binding identity when adapters reuse the same immutable function table. */
2139
- function bindJitFunctions(base, functions) {
2140
- if (functions.length === 0) return base;
2141
- let models = jitModels.get(base);
2142
- const cached = models?.get(functions);
2143
- if (cached !== void 0) return cached;
2144
- const model = validateDeviceIR({
2145
- ...base,
2146
- declarations: base.declarations.concat(functions)
2135
+ //#region src/polling.ts
2136
+ function isPollingInstruction(body, pc, pcName) {
2137
+ const definitions = /* @__PURE__ */ new Map();
2138
+ const redirects = [];
2139
+ const visit = (region) => {
2140
+ for (const operation of region.operations) {
2141
+ if ("result" in operation) definitions.set(operation.result, operation);
2142
+ switch (operation.kind) {
2143
+ case "constant":
2144
+ case "unary":
2145
+ case "binary":
2146
+ case "numeric":
2147
+ case "field":
2148
+ case "length":
2149
+ case "index":
2150
+ case "isNone":
2151
+ case "nonNull":
2152
+ case "optional":
2153
+ case "local":
2154
+ case "localRead":
2155
+ case "localWrite":
2156
+ case "memoryLength":
2157
+ case "load8":
2158
+ case "load16le":
2159
+ case "load16be":
2160
+ case "load32le":
2161
+ case "load32be":
2162
+ case "readSample":
2163
+ case "yield": break;
2164
+ case "read":
2165
+ if (operation.resource === "derived" || operation.name === pcName) return false;
2166
+ break;
2167
+ case "if":
2168
+ if (!visit(operation.yes) || operation.no && !visit(operation.no)) return false;
2169
+ break;
2170
+ case "select":
2171
+ if (!visit(operation.yes.body) || !visit(operation.no.body)) return false;
2172
+ break;
2173
+ case "and":
2174
+ case "or":
2175
+ if (!visit(operation.right.body)) return false;
2176
+ break;
2177
+ case "match":
2178
+ if (operation.arms.some((arm) => !visit(arm.body)) || operation.otherwise && !visit(operation.otherwise)) return false;
2179
+ break;
2180
+ case "redirect":
2181
+ redirects.push(operation.target);
2182
+ break;
2183
+ default: return false;
2184
+ }
2185
+ }
2186
+ return true;
2187
+ };
2188
+ if (!visit(body)) return false;
2189
+ return redirects.some((target) => {
2190
+ const definition = definitions.get(target);
2191
+ return definition?.kind !== "constant" || definition.constant.kind === "number" && definition.constant.value === pc;
2147
2192
  });
2148
- for (const declaration of model.declarations.slice(base.declarations.length)) if (declaration.kind !== "function") throw new TypeError("Expected JIT function declaration");
2149
- if (models === void 0) {
2150
- models = /* @__PURE__ */ new WeakMap();
2151
- jitModels.set(base, models);
2193
+ }
2194
+ //#endregion
2195
+ //#region src/runtime/jit.ts
2196
+ /** Large programs dispatch through shards; small ones stay on the faster monolithic form. */
2197
+ var DIRECT_SHARD_SIZE = 32;
2198
+ function syncJitCall(jit, name) {
2199
+ const step = jit.host.call(name, []).next();
2200
+ if (!step.done) throw new TypeError("Unexpected suspension in synchronous function");
2201
+ return step.value;
2202
+ }
2203
+ var checkpointStatsByJit = /* @__PURE__ */ new WeakMap();
2204
+ /** Create the opt-in checkpoint counters once, on the first instrumented Direct frame. */
2205
+ function directCheckpointStats(jit) {
2206
+ let stats = checkpointStatsByJit.get(jit);
2207
+ if (stats === void 0) {
2208
+ stats = {
2209
+ publications: 0,
2210
+ finishes: 0,
2211
+ emptySuffixes: 0,
2212
+ boundaryCalls: 0,
2213
+ continues: 0,
2214
+ exits: 0
2215
+ };
2216
+ checkpointStatsByJit.set(jit, stats);
2152
2217
  }
2153
- models.set(functions, model);
2154
- return model;
2218
+ return stats;
2155
2219
  }
2156
- /** Membership test without allocating: every key of `next` is already in `previous`. */
2157
- function hasEvery(previous, next) {
2158
- for (const slot of next.keys()) if (!previous.has(slot)) return false;
2159
- return true;
2220
+ /** Read counters without creating them; undefined means diagnostics stayed off. */
2221
+ function readDirectCheckpointStats(jit) {
2222
+ return checkpointStatsByJit.get(jit);
2160
2223
  }
2161
- function createContext(owner, board) {
2162
- return Object.freeze({
2163
- get props() {
2164
- board.assertReadAllowed(owner);
2165
- return Object.freeze(Object.fromEntries([...owner.props].map(([key, value]) => [key, externalValue(value)])));
2166
- },
2167
- get inputs() {
2168
- owner.assertCallAllowed();
2169
- return owner.inputs();
2170
- },
2171
- get memory() {
2172
- board.assertReadAllowed(owner);
2173
- return owner.publicMemory();
2224
+ var barriers = /* @__PURE__ */ new WeakMap();
2225
+ function directBarriers(jit) {
2226
+ let entry = barriers.get(jit);
2227
+ if (entry === void 0) {
2228
+ entry = {
2229
+ stateMask: /* @__PURE__ */ new Int32Array(0),
2230
+ memoryMask: /* @__PURE__ */ new Int32Array(0)
2231
+ };
2232
+ barriers.set(jit, entry);
2233
+ }
2234
+ return entry;
2235
+ }
2236
+ function directStats(jit) {
2237
+ const counted = jit;
2238
+ return counted.directStats ??= {
2239
+ directCompiles: 0,
2240
+ directShards: 0,
2241
+ directCalls: 0,
2242
+ directFallbacks: 0,
2243
+ directDeadlines: 0,
2244
+ directStopped: 0,
2245
+ directSessions: 0,
2246
+ directShardCompiles: 0,
2247
+ directRouteInstalls: 0,
2248
+ directRouteRemovals: 0,
2249
+ directRoutes: 0,
2250
+ directDispatchMisses: 0,
2251
+ directGenericInstructions: 0,
2252
+ directBodyBytes: 0,
2253
+ directShardBytes: 0,
2254
+ directDispatcherBytes: 0,
2255
+ directHelperBytes: 0,
2256
+ directShareCallbacks: 0,
2257
+ directShareCandidates: 0,
2258
+ directShareGroups: 0,
2259
+ directSharedRoutes: 0,
2260
+ directSharedBodies: 0,
2261
+ directSharedBytes: 0,
2262
+ directShareReusedBodies: 0,
2263
+ directShareReusedRoutes: 0,
2264
+ directShareRejected: {
2265
+ missing: 0,
2266
+ invalid: 0,
2267
+ single: 0,
2268
+ ir: 0,
2269
+ delay: 0,
2270
+ isolated: 0,
2271
+ context: 0
2174
2272
  },
2175
- topics: board.topicBridge(owner),
2176
- reportError: (error) => board.report(owner, error),
2177
- attachJit: (options) => owner.attach(options),
2178
- loadBytes: (name, bytes, ...offset) => owner.loadBytes(name, bytes, offset.length ? offset[0] : 0)
2179
- });
2273
+ directShareMarkRejected: {
2274
+ unknownPc: 0,
2275
+ duplicate: 0,
2276
+ invalidPc: 0,
2277
+ invalidLength: 0,
2278
+ outsideRegion: 0,
2279
+ crossView: 0,
2280
+ service: 0,
2281
+ notAdmitted: 0
2282
+ }
2283
+ };
2180
2284
  }
2285
+ /** Direct execution counters of one JIT; absent until it first attempted an instruction. */
2286
+ function directJitStats(jit) {
2287
+ return jit.directStats;
2288
+ }
2289
+ var directSessionSnapshots = /* @__PURE__ */ new WeakMap();
2181
2290
  /**
2182
- * State map whose scalar direct-bank writes are synced lazily on read.
2183
- *
2184
- * Direct JIT writes update `stateValues` and invalidate `stateSlots` at every boundary,
2185
- * while no observer or host reads `instance.states` until a reaction, observation,
2186
- * fallback or external query accesses it. Deferring the string-keyed `Map.set` calls
2187
- * until an actual read removes redundant map updates across resident GPIO edges while
2188
- * keeping `instance.states` an exact `Map<string, unknown>` at every read site.
2291
+ * Fold monotonic session counters into the per-JIT totals and publish the current route and
2292
+ * shard counts. Called after every commit so the benchmark never inspects session internals.
2189
2293
  */
2190
- var StateMirrorMap = class extends Map {
2191
- names = [];
2192
- bankValues = [];
2193
- dirty = /* @__PURE__ */ new Int32Array(0);
2194
- pending = false;
2195
- bindDirectBank(names, values) {
2196
- this.names = names;
2197
- this.bankValues = values;
2198
- this.dirty = new Int32Array(Math.ceil(names.length / 32));
2294
+ function syncDirectSessionStats(jit, session) {
2295
+ const next = session.stats();
2296
+ const stats = directStats(jit);
2297
+ const previous = directSessionSnapshots.get(jit);
2298
+ const base = previous?.session === session ? previous.stats : void 0;
2299
+ stats.directShardCompiles += next.compiledShards - (base?.compiledShards ?? 0);
2300
+ stats.directRouteInstalls += next.routeInstalls - (base?.routeInstalls ?? 0);
2301
+ stats.directRouteRemovals += next.routeRemovals - (base?.routeRemovals ?? 0);
2302
+ stats.directBodyBytes += next.bodyBytes - (base?.bodyBytes ?? 0);
2303
+ stats.directShardBytes += next.shardBytes - (base?.shardBytes ?? 0);
2304
+ stats.directDispatcherBytes += next.dispatcherBytes - (base?.dispatcherBytes ?? 0);
2305
+ stats.directHelperBytes += next.helperBytes - (base?.helperBytes ?? 0);
2306
+ stats.directShareGroups = next.shareGroups;
2307
+ stats.directSharedRoutes = next.sharedRoutes;
2308
+ stats.directSharedBodies += next.sharedBodies - (base?.sharedBodies ?? 0);
2309
+ stats.directSharedBytes += next.sharedBytes - (base?.sharedBytes ?? 0);
2310
+ stats.directShareReusedBodies += next.shareReusedBodies - (base?.shareReusedBodies ?? 0);
2311
+ stats.directShareReusedRoutes += next.shareReusedRoutes - (base?.shareReusedRoutes ?? 0);
2312
+ stats.directShareRejected.missing += next.shareRejected.missing - (base?.shareRejected.missing ?? 0);
2313
+ stats.directShareRejected.invalid += next.shareRejected.invalid - (base?.shareRejected.invalid ?? 0);
2314
+ stats.directShareRejected.single += next.shareRejected.single - (base?.shareRejected.single ?? 0);
2315
+ stats.directShareRejected.ir += next.shareRejected.ir - (base?.shareRejected.ir ?? 0);
2316
+ stats.directShareRejected.delay += next.shareRejected.delay - (base?.shareRejected.delay ?? 0);
2317
+ stats.directShareRejected.isolated += next.shareRejected.isolated - (base?.shareRejected.isolated ?? 0);
2318
+ stats.directShareRejected.context += next.shareRejected.context - (base?.shareRejected.context ?? 0);
2319
+ stats.directShards = next.shards;
2320
+ stats.directRoutes = next.routes;
2321
+ directSessionSnapshots.set(jit, {
2322
+ session,
2323
+ stats: next
2324
+ });
2325
+ }
2326
+ /** Drop the active session and publish zero current counts; cumulative totals stay. */
2327
+ function releaseDirectSession(jit) {
2328
+ const direct = jit.direct;
2329
+ if (direct !== void 0) {
2330
+ syncDirectSessionStats(jit, direct.session);
2331
+ jit.direct = void 0;
2332
+ direct.session.dispose();
2333
+ directSessionSnapshots.delete(jit);
2334
+ jit.directMemories.clear();
2335
+ }
2336
+ const stats = directJitStats(jit);
2337
+ if (stats !== void 0) {
2338
+ stats.directShards = 0;
2339
+ stats.directRoutes = 0;
2340
+ stats.directShareGroups = 0;
2341
+ stats.directSharedRoutes = 0;
2199
2342
  }
2200
- markDirectDirty(word, bits) {
2201
- this.dirty[word] |= bits;
2202
- this.pending = true;
2343
+ }
2344
+ /** Mark the active session stale; an idle session is released immediately. */
2345
+ function staleDirectSession(jit, running) {
2346
+ const direct = jit.direct;
2347
+ if (direct === void 0) {
2348
+ jit.directStale = false;
2349
+ return false;
2203
2350
  }
2204
- flush() {
2205
- if (!this.pending) return;
2206
- this.pending = false;
2207
- const { names, bankValues, dirty } = this;
2208
- for (let word = 0; word < dirty.length; word++) {
2209
- let bits = dirty[word];
2210
- if (bits === 0) continue;
2211
- dirty[word] = 0;
2212
- const base = word << 5;
2213
- while (bits !== 0) {
2214
- const index = base + 31 - Math.clz32(bits & -bits);
2215
- super.set(names[index], bankValues[index]);
2216
- bits &= bits - 1;
2217
- }
2218
- }
2351
+ jit.directStale = true;
2352
+ if (running || direct.frame.resume !== 0) {
2353
+ direct.frame.stopAfterInstruction = true;
2354
+ return true;
2219
2355
  }
2220
- get(key) {
2221
- if (this.pending) this.flush();
2222
- return super.get(key);
2356
+ releaseDirectSession(jit);
2357
+ jit.directStale = false;
2358
+ return true;
2359
+ }
2360
+ /** Invalidate direct execution because its translation inputs changed. */
2361
+ function invalidateDirect(jit, cacheInvalid = false) {
2362
+ if (cacheInvalid) jit.directCacheInvalid = true;
2363
+ jit.directSkip = void 0;
2364
+ staleDirectSession(jit, false);
2365
+ }
2366
+ /** Release the session on explicit registration/board disposal. */
2367
+ function disposeDirect(jit) {
2368
+ releaseDirectSession(jit);
2369
+ jit.directStale = false;
2370
+ jit.directSkip = void 0;
2371
+ jit.directMemories.clear();
2372
+ }
2373
+ /** Region that supplies bytes for a logical PC; undefined means the service-PC fallback. */
2374
+ function codeRegionFor(jit, pc) {
2375
+ for (const region of jit.codeRegions) if (pc >= region.base && pc < region.base + region.size) return region;
2376
+ }
2377
+ /** Additional regions stay on the interpreter; only the primary memory feeds direct programs. */
2378
+ function directCodeInstruction(jit, instruction) {
2379
+ const region = instruction.codeRegion;
2380
+ return region === void 0 || region.memory === jit.options.code;
2381
+ }
2382
+ /** One cache entry may join the direct session: primary code and no effective polling. */
2383
+ function directAdmitted(jit, instruction) {
2384
+ return !instruction.polling && !effectivePolling(jit).has(instruction.pc) && directCodeInstruction(jit, instruction);
2385
+ }
2386
+ function directInstruction(jit, instruction) {
2387
+ return {
2388
+ pc: instruction.pc,
2389
+ nextPc: instruction.nextPc,
2390
+ body: instruction.body,
2391
+ ...jit.options.shareDirectBodies === true && instruction.share !== void 0 ? { share: instruction.share } : {}
2392
+ };
2393
+ }
2394
+ /**
2395
+ * Attach validated marks to their translated entries. The block itself is already committed
2396
+ * to the interpreter path, so every rejection only drops sharing for that entry; it never
2397
+ * rejects the translation. Runs once per translated block, never on the `run` hot path.
2398
+ */
2399
+ function applyDirectShareMarks(jit, startRegion, codeLength, instructions, marks) {
2400
+ if (marks.length === 0) return;
2401
+ const indexByPc = /* @__PURE__ */ new Map();
2402
+ for (let index = 0; index < instructions.length; index++) {
2403
+ const pc = instructions[index].pc;
2404
+ if (!indexByPc.has(pc)) indexByPc.set(pc, index);
2405
+ }
2406
+ const stats = directStats(jit);
2407
+ const rejected = stats.directShareMarkRejected;
2408
+ const seen = /* @__PURE__ */ new Set();
2409
+ for (const { pc, byteLength } of marks) {
2410
+ if (!Number.isSafeInteger(pc) || pc < 0) {
2411
+ rejected.invalidPc++;
2412
+ continue;
2413
+ }
2414
+ if (!Number.isSafeInteger(byteLength) || byteLength <= 0) {
2415
+ rejected.invalidLength++;
2416
+ continue;
2417
+ }
2418
+ if (seen.has(pc)) {
2419
+ rejected.duplicate++;
2420
+ continue;
2421
+ }
2422
+ seen.add(pc);
2423
+ const index = indexByPc.get(pc);
2424
+ if (index === void 0) {
2425
+ rejected.unknownPc++;
2426
+ continue;
2427
+ }
2428
+ const instruction = instructions[index];
2429
+ const region = instruction.codeRegion;
2430
+ if (region === void 0) {
2431
+ rejected.service++;
2432
+ continue;
2433
+ }
2434
+ if (startRegion === void 0 || region !== startRegion) {
2435
+ rejected.crossView++;
2436
+ continue;
2437
+ }
2438
+ const offset = pc - region.base;
2439
+ if (offset < 0 || !Number.isSafeInteger(offset + byteLength) || offset + byteLength > region.size || offset + byteLength > codeLength) {
2440
+ rejected.outsideRegion++;
2441
+ continue;
2442
+ }
2443
+ if (!directAdmitted(jit, instruction)) {
2444
+ rejected.notAdmitted++;
2445
+ continue;
2446
+ }
2447
+ instructions[index] = {
2448
+ ...instruction,
2449
+ share: Object.freeze({
2450
+ storage: region.memory,
2451
+ codeVersion: instruction.codeVersion,
2452
+ offset,
2453
+ byteLength
2454
+ })
2455
+ };
2456
+ stats.directShareCandidates++;
2223
2457
  }
2224
- set(key, value) {
2225
- if (this.pending) this.flush();
2226
- return super.set(key, value);
2458
+ }
2459
+ function effectivePolling(jit) {
2460
+ return jit.metadata?.polling ?? jit.polling;
2461
+ }
2462
+ function effectiveDelays(jit) {
2463
+ return jit.metadata?.delays ?? jit.delays;
2464
+ }
2465
+ /** Aliases of the primary memory must refresh together before a direct program is built. */
2466
+ function primaryCodeRegions(jit) {
2467
+ return jit.codeRegions.filter((region) => region.memory === jit.options.code);
2468
+ }
2469
+ /**
2470
+ * Lazily (re)build code-derived metadata for the requested regions. Provider calls never
2471
+ * happen from attach/store; this runs inside the translate phase immediately before the
2472
+ * polling/direct/translate decision that needs it.
2473
+ */
2474
+ function ensureMetadata(board, jit, regions) {
2475
+ const metadata = jit.metadata;
2476
+ const provider = jit.options.codeMetadata;
2477
+ if (metadata === void 0 || provider === void 0) return;
2478
+ const needed = [];
2479
+ const seen = /* @__PURE__ */ new Set();
2480
+ for (const region of regions) {
2481
+ const state = metadata.regions.get(region);
2482
+ if (state === void 0 || seen.has(state)) continue;
2483
+ seen.add(state);
2484
+ const version = jit.instance.codeVersion(region.memory);
2485
+ if (state.appliedVersion === version && state.pending.length === 0 && !state.dirty) continue;
2486
+ const changes = state.appliedVersion === -1 ? [Object.freeze({
2487
+ memory: region.memory,
2488
+ offset: 0,
2489
+ length: region.size
2490
+ })] : state.pending.map((change) => Object.freeze({ ...change }));
2491
+ needed.push({
2492
+ state,
2493
+ changes,
2494
+ version
2495
+ });
2227
2496
  }
2228
- entries() {
2229
- if (this.pending) this.flush();
2230
- return super.entries();
2231
- }
2232
- values() {
2233
- if (this.pending) this.flush();
2234
- return super.values();
2235
- }
2236
- forEach(callbackfn, thisArg) {
2237
- if (this.pending) this.flush();
2238
- super.forEach(callbackfn, thisArg);
2239
- }
2240
- [Symbol.iterator]() {
2241
- if (this.pending) this.flush();
2242
- return super[Symbol.iterator]();
2243
- }
2244
- };
2245
- var Instance = class {
2246
- board;
2247
- entry;
2248
- id;
2249
- declarations = /* @__PURE__ */ new Map();
2250
- props = /* @__PURE__ */ new Map();
2251
- constants = /* @__PURE__ */ new Map();
2252
- states = new StateMirrorMap();
2253
- directBank;
2254
- memories = /* @__PURE__ */ new Map();
2255
- memoryViews = /* @__PURE__ */ new Map();
2256
- memorySizes = /* @__PURE__ */ new Map();
2257
- pins = /* @__PURE__ */ new Map();
2258
- channels = /* @__PURE__ */ new Map();
2259
- notificationInputs = /* @__PURE__ */ new Set();
2260
- notificationOutputs = /* @__PURE__ */ new Map();
2261
- batchInputs = [];
2262
- batchOutputs = [];
2263
- batchNotifications = [];
2264
- emptyOutputs = Object.create(null);
2265
- resources = [];
2266
- jits = [];
2267
- processes = [];
2268
- reactions = [];
2269
- derived = /* @__PURE__ */ new Map();
2270
- /** One-entry memo for repeated `read('derived', name)` calls inside a body. */
2271
- derivedName;
2272
- derivedEntry;
2273
- derivedBuffers = /* @__PURE__ */ new Map();
2274
- stateResources = /* @__PURE__ */ new Map();
2275
- memoryResources = /* @__PURE__ */ new Map();
2276
- sampleResources = /* @__PURE__ */ new Map();
2277
- observerRevision = 0;
2278
- dependencyStack = [];
2279
- observations = /* @__PURE__ */ new WeakMap();
2280
- staticObservations = /* @__PURE__ */ new WeakMap();
2281
- resistorIntents = /* @__PURE__ */ new Map();
2282
- sampleEntries = /* @__PURE__ */ new Map();
2283
- intentEntries = /* @__PURE__ */ new Map();
2284
- stateSlots = /* @__PURE__ */ new Map();
2285
- /** Per-instance handles for the fixed resources a resumable process body binds. */
2286
- resourceHandles = /* @__PURE__ */ new Map();
2287
- memoryPlans = /* @__PURE__ */ new Map();
2288
- /** 按 memory 维护的代码代际;只有 code region 内写入才递增。 */
2289
- codeVersions = /* @__PURE__ */ new Map();
2290
- /**
2291
- * Every memory name any attached JIT binds as a code region. A write outside this set
2292
- * cannot affect a JIT, so the store path skips the region scans entirely.
2293
- */
2294
- codeMemories = /* @__PURE__ */ new Set();
2295
- observationFrames = /* @__PURE__ */ new WeakMap();
2296
- evaluating = /* @__PURE__ */ new Set();
2297
- random;
2298
- host;
2299
- context;
2300
- adapter;
2301
- valid = true;
2302
- rawProps;
2303
- constructor(board, entry, id, props, seed, override) {
2304
- this.board = board;
2305
- this.entry = entry;
2306
- this.id = id;
2307
- for (const declaration of entry.model.declarations) {
2308
- if ("name" in declaration) this.declarations.set(declaration.name, declaration);
2309
- if (declaration.kind === "state" || declaration.kind === "memory" || declaration.kind === "pin") (declaration.kind === "state" ? this.stateResources : declaration.kind === "memory" ? this.memoryResources : this.sampleResources).set(declaration.name, {
2310
- version: 0,
2311
- subscribers: /* @__PURE__ */ new Set(),
2312
- waiters: void 0
2313
- });
2314
- }
2315
- dataObject(props);
2316
- this.rawProps = props;
2317
- for (const key of Object.keys(props)) if (this.declarations.get(key)?.kind !== "property") throw new TypeError(`Unknown property ${key}`);
2318
- this.random = randomState(seed, id, override);
2319
- this.host = {
2320
- read: (kind, name) => this.read(kind, name),
2321
- write: (name, value) => this.writeState(name, value, this.stateSlot(name)),
2322
- sample: (ref) => {
2323
- return this.readSample(ref);
2324
- },
2325
- intent: (pin, value) => {
2326
- this.writeIntent(pin, value);
2327
- },
2328
- resistor: (pin, resistance) => {
2329
- const r = electricalNumber(resistance);
2330
- if (r < .001 || r > 1e9) throw new ElectricalParameterError("Resistance outside [0.001, 1e9]");
2331
- return this.resistorIntent(pin, r);
2332
- },
2333
- memoryLength: (memory) => this.memory(memory).length,
2334
- load: (kind, memory, offset) => {
2335
- const plan = this.memoryPlan(memory);
2336
- const size = kind.startsWith("load8") ? 1 : kind.startsWith("load16") ? 2 : 4;
2337
- const at = range(plan.bytes, offset, size);
2338
- const dependencies = this.dependencies();
2339
- if (dependencies) dependencies.set(plan.slot, plan.slot.version);
2340
- if (size === 1) return plan.bytes[at];
2341
- return size === 2 ? plan.view.getUint16(at, kind.endsWith("le")) : plan.view.getUint32(at, kind.endsWith("le"));
2342
- },
2343
- store: (kind, memory, offset, value) => {
2344
- const plan = this.memoryPlan(memory);
2345
- const size = kind.startsWith("store8") ? 1 : kind.startsWith("store16") ? 2 : 4;
2346
- const at = range(plan.bytes, offset, size);
2347
- const n = integer(value, "stored value");
2348
- if (size === 1) plan.bytes[at] = n;
2349
- else if (size === 2) plan.view.setUint16(at, n, kind.endsWith("le"));
2350
- else plan.view.setUint32(at, n, kind.endsWith("le"));
2351
- this.memoryChangedPlan(plan, at, size);
2352
- },
2353
- copyBytes: (memory, offset, length) => {
2354
- this.track(this.memoryResources, String(memory));
2355
- const bytes = this.memory(memory), at = range(bytes, offset, length);
2356
- return bytes.slice(at, at + Number(length));
2357
- },
2358
- send: (name, value) => this.send(name, value, false),
2359
- notify: (name) => {
2360
- if (!this.notificationOutputs.has(name)) throw new TypeError(`Unknown notification ${name}`);
2361
- this.notificationOutputs.set(name, board.time);
2362
- },
2363
- now: () => board.time,
2364
- random: () => nextRandom(this.random),
2365
- call: (name, args) => this.invoke(name, args),
2366
- assert: (condition, message) => {
2367
- if (condition !== true) throw new Error(message === void 0 ? "Assertion failed" : String(message));
2368
- },
2369
- bind: (specs) => this.bindResources(specs)
2370
- };
2371
- this.context = createContext(this, board);
2372
- }
2373
- track(resources, name) {
2374
- this.trackSlot(resources.get(name));
2375
- }
2376
- /** Innermost dependency sink, or `undefined` outside an evaluation. */
2377
- dependencies() {
2378
- const stack = this.dependencyStack;
2379
- return stack.length === 0 ? void 0 : stack[stack.length - 1];
2380
- }
2381
- trackSlot(slot) {
2382
- const dependencies = this.dependencies();
2383
- if (dependencies) dependencies.set(slot, slot.version);
2384
- }
2385
- /** Read-only evidence that a process frame bound per-instance resource handles. */
2386
- bindingReport() {
2387
- return Object.freeze({
2388
- instance: this.id,
2389
- handles: this.resourceHandles.size,
2390
- bound: Object.freeze([...this.resourceHandles.keys()].sort()),
2391
- processes: Object.freeze(this.processes.map((process) => Object.freeze({
2392
- name: process.declaration.kind === "on" ? process.declaration.name : "start",
2393
- bound: process.frame?.resources?.length ?? 0
2394
- })))
2395
- });
2396
- }
2397
- dependenciesCurrent(dependencies) {
2398
- if (!dependencies) return false;
2399
- for (const [slot, version] of dependencies) if (slot.version !== version) return false;
2400
- return true;
2401
- }
2402
- /** Publishes a derived cache entry; the memo must follow every table write. */
2403
- setDerived(name, entry) {
2404
- if (this.derivedName === name && this.derivedEntry === entry) return;
2405
- this.derived.set(name, entry);
2406
- this.derivedName = name;
2407
- this.derivedEntry = entry;
2408
- }
2409
- evaluate(compute, target) {
2410
- const dependencies = target ?? /* @__PURE__ */ new Map();
2411
- this.dependencyStack.push(dependencies);
2412
- try {
2413
- return {
2414
- value: compute(),
2415
- dependencies
2416
- };
2417
- } finally {
2418
- this.dependencyStack.pop();
2419
- const parent = this.dependencies();
2420
- if (parent) for (const [key, version] of dependencies) parent.set(key, version);
2421
- }
2422
- }
2423
- /** Leaf form of :func:`evaluate` for a source walk: no closure and no result wrapper. */
2424
- evaluateSource(path, dependencies) {
2425
- this.dependencyStack.push(dependencies);
2426
- try {
2427
- return snapshot(this.source(path));
2428
- } finally {
2429
- this.dependencyStack.pop();
2430
- const parent = this.dependencies();
2431
- if (parent) for (const [key, version] of dependencies) parent.set(key, version);
2432
- }
2433
- }
2434
- observe(observation, path) {
2435
- const read = this.staticObservations.get(observation);
2436
- if (read) return read();
2437
- const declaration = this.declarations.get(path[0]);
2438
- if (declaration?.kind === "pin" || declaration?.kind === "state") {
2439
- const resources = declaration.kind === "pin" ? this.sampleResources : this.stateResources;
2440
- const pin = declaration.kind === "pin" ? this.pin(declaration.name) : void 0;
2441
- if (pin && path[1] !== "sample") throw new TypeError(`Invalid source ${path.join(".")}`);
2442
- const read = () => {
2443
- let value = pin ? pin.sample : this.states.get(declaration.name);
2444
- for (let index = pin ? 2 : 1; index < path.length; index++) value = value[path[index]];
2445
- return pin ? value : snapshot(value);
2446
- };
2447
- const value = read();
2448
- const slot = resources.get(declaration.name);
2449
- if (!slot.subscribers.size) this.observerRevision++;
2450
- slot.subscribers.add(observation);
2451
- this.staticObservations.set(observation, read);
2452
- return value;
2453
- }
2454
- const frames = this.observationFrames.get(observation);
2455
- let target;
2456
- if (frames === void 0) {
2457
- target = /* @__PURE__ */ new Map();
2458
- this.observationFrames.set(observation, {
2459
- first: target,
2460
- second: /* @__PURE__ */ new Map(),
2461
- alternate: true
2462
- });
2463
- } else {
2464
- target = frames.alternate ? frames.second : frames.first;
2465
- frames.alternate = !frames.alternate;
2466
- target.clear();
2467
- }
2468
- const observed = this.evaluateSource(path, target);
2469
- const previous = this.observations.get(observation);
2470
- if (previous === void 0 || previous.size !== target.size || !hasEvery(previous, target)) {
2471
- if (previous) {
2472
- for (const slot of previous.keys()) if (!target.has(slot) && slot.subscribers.delete(observation) && !slot.subscribers.size) this.observerRevision++;
2473
- }
2474
- for (const slot of target.keys()) if (!previous?.has(slot)) {
2475
- if (!slot.subscribers.size) this.observerRevision++;
2476
- slot.subscribers.add(observation);
2497
+ if (needed.length === 0) return;
2498
+ const prior = board.phase;
2499
+ board.phase = "translate";
2500
+ const prepared = [];
2501
+ try {
2502
+ for (const item of needed) {
2503
+ const { region } = item.state;
2504
+ const memory = jit.instance.memory(region.memory);
2505
+ const bytes = region.size >= memory.length ? memory : memory.subarray(0, region.size);
2506
+ let valid = true;
2507
+ try {
2508
+ const code = bytesView(bytes, () => {
2509
+ if (!valid) throw board.error("OBJECT_DISPOSED", "Metadata view expired", jit.instance);
2510
+ });
2511
+ const view = Object.freeze({
2512
+ memory: region.memory,
2513
+ base: region.base,
2514
+ size: region.size,
2515
+ codeVersion: item.version,
2516
+ code
2517
+ });
2518
+ const result = provider(Object.freeze({
2519
+ region: view,
2520
+ changes: Object.freeze(item.changes.slice())
2521
+ }));
2522
+ acceptSync(result);
2523
+ const captured = jit.instance.captureCodeMetadata(region, result);
2524
+ prepared.push({
2525
+ state: item.state,
2526
+ version: item.version,
2527
+ polling: captured.polling,
2528
+ delays: captured.delays
2529
+ });
2530
+ } finally {
2531
+ valid = false;
2477
2532
  }
2478
2533
  }
2479
- this.observations.set(observation, target);
2480
- return observed;
2481
- }
2482
- observationReader(observation, path) {
2483
- return this.staticObservations.get(observation) ?? (() => this.observe(observation, path));
2484
- }
2485
- read(kind, name) {
2486
- if (kind === "state") {
2487
- this.trackSlot(this.stateSlot(name));
2488
- return this.states.get(name);
2489
- }
2490
- if (kind === "derived") {
2491
- let cached = name === this.derivedName ? this.derivedEntry : this.derived.get(name);
2492
- const epoch = this.board.resourceEpoch;
2493
- if (cached === void 0 || cached.epoch !== epoch && !this.dependenciesCurrent(cached.dependencies)) {
2494
- const declaration = this.declarations.get(name);
2495
- if (declaration?.kind !== "derived") throw new TypeError(`Unknown derived ${name}`);
2496
- let buffer = this.derivedBuffers.get(name);
2497
- if (buffer === void 0) {
2498
- buffer = /* @__PURE__ */ new Map();
2499
- this.derivedBuffers.set(name, buffer);
2500
- } else buffer.clear();
2501
- const evaluated = this.evaluate(() => computation(declaration.value, this.host), buffer);
2502
- cached = {
2503
- value: evaluated.value,
2504
- dependencies: evaluated.dependencies,
2505
- epoch: this.board.resourceEpoch
2506
- };
2507
- this.setDerived(name, cached);
2508
- } else if (cached.epoch !== epoch) cached.epoch = epoch;
2509
- const parent = this.dependencies();
2510
- if (parent) for (const [key, version] of cached.dependencies) parent.set(key, version);
2511
- return cached.value;
2512
- }
2513
- const values = kind === "property" ? this.props : this.constants;
2514
- if (values.has(name)) return values.get(name);
2515
- if (this.evaluating.has(name)) throw new TypeError(`Circular creation dependency ${name}`);
2516
- this.evaluating.add(name);
2517
- try {
2518
- const declaration = this.declarations.get(name);
2519
- if (declaration?.kind !== "property" && declaration?.kind !== "const") throw new TypeError(`Invalid creation reference ${name}`);
2520
- let value;
2521
- if (declaration.kind === "property") {
2522
- if (Object.hasOwn(this.rawProps, name)) value = captureValue(declaration.type, this.rawProps[name], this.declarations, true);
2523
- else if (declaration.default) value = captureValue(declaration.type, computation(declaration.default, this.host), this.declarations, true);
2524
- else throw new TypeError(`Missing property ${name}`);
2525
- } else value = computation(declaration.value, this.host);
2526
- values.set(name, value);
2527
- return value;
2528
- } finally {
2529
- this.evaluating.delete(name);
2530
- }
2531
- }
2532
- invoke(name, args = []) {
2533
- const fn = this.declarations.get(name);
2534
- if (fn?.kind !== "function") throw new TypeError(`Unknown function ${name}`);
2535
- return body(fn.body)(this.host, args);
2536
- }
2537
- syncCall(name, args = []) {
2538
- const step = this.invoke(name, args).next();
2539
- if (!step.done) throw new TypeError("Unexpected suspension in synchronous function");
2540
- return step.value;
2541
- }
2542
- pin(ref) {
2543
- const pin = this.pins.get(String(ref));
2544
- if (!pin) throw new TypeError(`Unknown pin ${String(ref)}`);
2545
- return pin;
2546
- }
2547
- /** Shared by the generic host and direct JIT, which needs to know whether to publish. */
2548
- writeIntent(ref, value) {
2549
- const name = typeof ref === "string" ? ref : String(ref);
2550
- const board = this.board;
2551
- let entry = this.intentEntries.get(name);
2552
- if (entry === void 0) {
2553
- const pin = this.pin(name);
2554
- entry = {
2555
- pin,
2556
- slot: board.electricalSlot(pin)
2557
- };
2558
- this.intentEntries.set(name, entry);
2559
- }
2560
- if (entry.pin.intent === value) return false;
2561
- entry.pin.intent = value;
2562
- board.markElectricalDirty(entry.slot);
2563
- return true;
2564
- }
2565
- /**
2566
- * One frozen, reusable intent value per (pin, resistance); intents are immutable. The
2567
- * outer map is keyed by pin name and the inner one by resistance, so the hot path builds
2568
- * no key string. Bounds: at most 64 names, and at most 8 resistances per name; a full
2569
- * level is cleared wholesale (no least-recently-used eviction), so identity is only
2570
- * reused while both levels stay under their limits.
2571
- */
2572
- resistorIntent(pin, resistance) {
2573
- const name = typeof pin === "string" ? pin : String(pin);
2574
- let byResistance = this.resistorIntents.get(name);
2575
- if (byResistance === void 0) {
2576
- if (this.resistorIntents.size >= 64) this.resistorIntents.clear();
2577
- byResistance = /* @__PURE__ */ new Map();
2578
- this.resistorIntents.set(name, byResistance);
2579
- }
2580
- let intent = byResistance.get(resistance);
2581
- if (intent === void 0) {
2582
- if (byResistance.size >= 8) byResistance.clear();
2583
- intent = Object.freeze([Object.freeze({
2584
- to: this.pin(name),
2585
- resistance
2586
- })]);
2587
- byResistance.set(resistance, intent);
2534
+ let primary = false;
2535
+ for (const item of prepared) {
2536
+ item.state.appliedVersion = item.version;
2537
+ item.state.dirty = false;
2538
+ item.state.pending.length = 0;
2539
+ item.state.polling.clear();
2540
+ for (const [pc, binding] of item.polling) item.state.polling.set(pc, binding);
2541
+ item.state.delays.clear();
2542
+ for (const [pc, delay] of item.delays) item.state.delays.set(pc, delay);
2543
+ if (item.state.region.memory === jit.options.code) primary = true;
2588
2544
  }
2589
- return intent;
2590
- }
2591
- readSample(ref) {
2592
- const name = typeof ref === "string" ? ref : String(ref);
2593
- let entry = this.sampleEntries.get(name);
2594
- if (entry === void 0) {
2595
- const pin = this.pin(name);
2596
- entry = {
2597
- pin,
2598
- slot: this.sampleResources.get(pin.name)
2599
- };
2600
- if (this.sampleEntries.size >= 512) this.sampleEntries.clear();
2601
- this.sampleEntries.set(name, entry);
2545
+ metadata.polling.clear();
2546
+ metadata.delays.clear();
2547
+ for (const state of metadata.regions.values()) {
2548
+ for (const [pc, binding] of state.polling) metadata.polling.set(pc, binding);
2549
+ for (const [pc, delay] of state.delays) metadata.delays.set(pc, delay);
2602
2550
  }
2603
- const dependencies = this.dependencies();
2604
- if (dependencies) dependencies.set(entry.slot, entry.slot.version);
2605
- return entry.pin.sample;
2606
- }
2607
- memory(ref) {
2608
- const bytes = this.memories.get(String(ref));
2609
- if (!bytes) throw new TypeError(`Unknown memory ${String(ref)}`);
2610
- return bytes;
2551
+ if (primary) invalidateDirect(jit, true);
2552
+ else if (jit.direct !== void 0 && !jit.directStale) updateDirectDelays(jit);
2553
+ } catch (cause) {
2554
+ throw board.wrap(cause, "JIT_FAILED", "translate", jit.instance);
2555
+ } finally {
2556
+ board.phase = prior;
2611
2557
  }
2612
- /** Instance-owned numeric bank, mirrored by every non-direct state write. */
2613
- directStateBank() {
2614
- if (this.directBank === void 0) {
2615
- const stateNames = [...this.states.keys()].filter((name) => {
2616
- const declaration = this.declarations.get(name);
2617
- return declaration.type.kind === "number" || declaration.type.kind === "bool";
2618
- });
2619
- const frozenNames = Object.freeze(stateNames);
2620
- const stateValues = stateNames.map((name) => this.states.get(name));
2621
- this.states.bindDirectBank(frozenNames, stateValues);
2622
- this.directBank = {
2623
- stateNames: frozenNames,
2624
- stateSlots: Object.freeze(stateNames.map((name) => this.stateResources.get(name))),
2625
- states: new Map(stateNames.map((name, index) => [name, index])),
2626
- stateValues
2627
- };
2558
+ }
2559
+ function ensureMetadataForPc(board, jit, pc) {
2560
+ if (jit.metadata === void 0) return;
2561
+ const region = codeRegionFor(jit, pc) ?? jit.codeRegions[0];
2562
+ const needed = [region];
2563
+ if (board.execution === "throughput" && board.jits.length === 1 && region.memory === jit.options.code) needed.push(...primaryCodeRegions(jit));
2564
+ ensureMetadata(board, jit, needed);
2565
+ }
2566
+ /** Publish the current subscriber sets into the masks the compiled blocks test on writes. */
2567
+ function syncDirectBarriers(jit) {
2568
+ const entry = directBarriers(jit);
2569
+ const { stateIndex, memoryIndex } = entry;
2570
+ if (stateIndex === void 0 || memoryIndex === void 0) return;
2571
+ const fill = (mask, index, guards) => {
2572
+ mask.fill(0);
2573
+ for (const name of guards) {
2574
+ const slot = index.get(name);
2575
+ if (slot === void 0) continue;
2576
+ mask[slot >>> 5] = (mask[slot >>> 5] ?? 0) | 1 << (slot & 31);
2628
2577
  }
2629
- return this.directBank;
2630
- }
2631
- /** Direct scalar writes are already in the numeric bank. Commit the mirror and version. */
2632
- commitDirectStates(dirty) {
2633
- const { stateSlots } = this.directBank;
2634
- const states = this.states;
2635
- const board = this.board;
2636
- let wrote = false;
2637
- for (let word = 0; word < dirty.length; word++) {
2638
- let bits = dirty[word];
2639
- if (bits === 0) continue;
2640
- dirty[word] = 0;
2641
- wrote = true;
2642
- states.markDirectDirty(word, bits);
2643
- const base = word << 5;
2644
- while (bits !== 0) {
2645
- const slot = stateSlots[base + 31 - Math.clz32(bits & -bits)];
2646
- if (slot.subscribers.size === 0) {
2647
- slot.version++;
2648
- board.noteResourceVersion(slot);
2649
- } else board.invalidate(slot);
2650
- bits &= bits - 1;
2578
+ };
2579
+ fill(entry.stateMask, stateIndex, jit.directStateGuards);
2580
+ fill(entry.memoryMask, memoryIndex, jit.directMemoryGuards);
2581
+ }
2582
+ /** Settle one checkpoint boundary and attribute it to its source when diagnostics are on. */
2583
+ function checkpointBoundary(board, stats, source) {
2584
+ if (stats !== void 0) stats.boundaryCalls++;
2585
+ board.boundary(source);
2586
+ }
2587
+ /** Reverse-map the hook's resource slots; slot values are not bank indices. */
2588
+ function entryBlockedNames(jit) {
2589
+ const states = /* @__PURE__ */ new Set();
2590
+ const memories = /* @__PURE__ */ new Set([jit.options.code]);
2591
+ const instance = jit.instance;
2592
+ for (const [name, slot] of instance.stateResources) if (jit.directHookReads.has(slot)) states.add(name);
2593
+ for (const [name, slot] of instance.memoryResources) if (jit.directHookReads.has(slot)) memories.add(name);
2594
+ return {
2595
+ states,
2596
+ memories
2597
+ };
2598
+ }
2599
+ /**
2600
+ * Refresh observer masks in place and invalidate the session only when the entry barrier
2601
+ * generation changes (the hook discovered a new state or memory dependency). Returns true
2602
+ * when the running session must stop after the current instruction.
2603
+ */
2604
+ function refreshDirectGuards(jit, hookReads, running = false) {
2605
+ let observersChanged = false;
2606
+ let entryChanged = false;
2607
+ const instance = jit.instance;
2608
+ const hookCount = jit.directHookReads.size;
2609
+ if (hookReads) for (const slot of hookReads.keys()) {
2610
+ if (jit.directHookReads.has(slot)) continue;
2611
+ jit.directHookReads.add(slot);
2612
+ let resource = false;
2613
+ for (const candidate of instance.stateResources.values()) if (candidate === slot) {
2614
+ resource = true;
2615
+ break;
2616
+ }
2617
+ if (!resource) {
2618
+ for (const candidate of instance.memoryResources.values()) if (candidate === slot) {
2619
+ resource = true;
2620
+ break;
2651
2621
  }
2652
2622
  }
2653
- return wrote;
2623
+ if (resource) entryChanged = true;
2654
2624
  }
2655
- writeState(name, value, slot) {
2656
- const captured = snapshot(value);
2657
- this.states.set(name, captured);
2658
- const index = this.directBank?.states.get(name);
2659
- if (index !== void 0) this.directBank.stateValues[index] = captured;
2660
- this.board.invalidate(slot);
2625
+ if (jit.directObserverRevision === instance.observerRevision && hookCount === jit.directHookReads.size && !entryChanged) return false;
2626
+ jit.directObserverRevision = instance.observerRevision;
2627
+ for (const [name, slot] of instance.stateResources) {
2628
+ const blocked = slot.subscribers.size > 0;
2629
+ if (jit.directStateGuards.has(name) === blocked) continue;
2630
+ if (blocked) jit.directStateGuards.add(name);
2631
+ else jit.directStateGuards.delete(name);
2632
+ observersChanged = true;
2661
2633
  }
2662
- stateSlot(name) {
2663
- let slot = this.stateSlots.get(name);
2664
- if (slot === void 0) {
2665
- if (!this.states.has(name)) throw new TypeError(`Unknown state ${name}`);
2666
- slot = this.stateResources.get(name);
2667
- this.stateSlots.set(name, slot);
2668
- }
2669
- return slot;
2634
+ for (const [name, slot] of instance.memoryResources) {
2635
+ const blocked = slot.subscribers.size > 0;
2636
+ if (jit.directMemoryGuards.has(name) === blocked) continue;
2637
+ if (blocked) jit.directMemoryGuards.add(name);
2638
+ else jit.directMemoryGuards.delete(name);
2639
+ observersChanged = true;
2670
2640
  }
2671
- memoryPlan(ref) {
2672
- const name = typeof ref === "string" ? ref : String(ref);
2673
- let plan = this.memoryPlans.get(name);
2674
- if (plan === void 0) {
2675
- const bytes = this.memories.get(name);
2676
- if (!bytes) throw new TypeError(`Unknown memory ${name}`);
2677
- plan = {
2678
- name,
2679
- bytes,
2680
- view: this.memoryViews.get(name),
2681
- slot: this.memoryResources.get(name)
2682
- };
2683
- this.memoryPlans.set(name, plan);
2641
+ let invalidated = false;
2642
+ if (entryChanged && jit.direct !== void 0) invalidated = staleDirectSession(jit, running);
2643
+ if (observersChanged) syncDirectBarriers(jit);
2644
+ if (observersChanged || entryChanged) jit.directSkip = void 0;
2645
+ return invalidated;
2646
+ }
2647
+ /**
2648
+ * Direct programs advance `frame.time` between host calls, while the board only adopts the
2649
+ * final time after `run` returns. Publish the current frame time before every host effect so
2650
+ * channel publications, electrical intents and diagnostics carry the instruction's time.
2651
+ */
2652
+ function directHost(board, instance, frame) {
2653
+ const publishTime = () => {
2654
+ board.time = frame.time;
2655
+ };
2656
+ return {
2657
+ send: (name, value) => {
2658
+ publishTime();
2659
+ instance.host.send(name, value);
2660
+ },
2661
+ sample: (pin) => {
2662
+ publishTime();
2663
+ return instance.host.sample(pin);
2664
+ },
2665
+ intent: (pin, value) => {
2666
+ publishTime();
2667
+ if (instance.writeIntent(pin, value)) frame.publishPending = true;
2668
+ },
2669
+ resistor: (pin, resistance) => {
2670
+ publishTime();
2671
+ return instance.host.resistor(pin, resistance);
2672
+ },
2673
+ notify: (name) => {
2674
+ publishTime();
2675
+ instance.host.notify(name);
2676
+ },
2677
+ now: () => {
2678
+ publishTime();
2679
+ return instance.host.now();
2680
+ },
2681
+ random: () => {
2682
+ publishTime();
2683
+ return instance.host.random();
2684
+ },
2685
+ assert: (condition, message) => {
2686
+ publishTime();
2687
+ instance.host.assert(condition, message);
2688
+ }
2689
+ };
2690
+ }
2691
+ /** Build the numeric bank layout once; rebuilds then only need the cached instruction bodies. */
2692
+ function directLayout(jit) {
2693
+ if (jit.directLayout !== void 0) return jit.directLayout;
2694
+ const instance = jit.instance;
2695
+ const bank = instance.directStateBank();
2696
+ const memoryNames = [...instance.memories.keys()];
2697
+ const memories = new Map(memoryNames.map((name, index) => [name, index]));
2698
+ const memoryBanks = memoryNames.map((name) => instance.memory(name));
2699
+ const memoryViews = memoryBanks.map((memory) => new DataView(memory.buffer, memory.byteOffset, memory.byteLength));
2700
+ const pinNames = [...instance.pins.keys()];
2701
+ const pins = new Map(pinNames.map((name, index) => [name, index]));
2702
+ const pinObjects = pinNames.map((name) => instance.pin(name));
2703
+ const pinElectricalSlots = Int32Array.from(pinObjects, (pin) => instance.board.electricalSlot(pin));
2704
+ jit.directLayout = {
2705
+ ...bank,
2706
+ memoryNames: Object.freeze(memoryNames),
2707
+ memories,
2708
+ memoryBanks: Object.freeze(memoryBanks),
2709
+ memoryViews: Object.freeze(memoryViews),
2710
+ pinNames: Object.freeze(pinNames),
2711
+ pins,
2712
+ pinObjects: Object.freeze(pinObjects),
2713
+ pinElectricalSlots
2714
+ };
2715
+ return jit.directLayout;
2716
+ }
2717
+ function flushDirect(board, instance, layout, frame) {
2718
+ board.time = frame.time;
2719
+ frame.publishPending = false;
2720
+ let wrote = instance.commitDirectStates(frame.stateDirty);
2721
+ for (let word = 0; word < frame.memoryDirty.length; word++) {
2722
+ let bits = frame.memoryDirty[word];
2723
+ if (bits === 0) continue;
2724
+ frame.memoryDirty[word] = 0;
2725
+ while (bits !== 0) {
2726
+ const slot = word * 32 + 31 - Math.clz32(bits & -bits);
2727
+ instance.memoryChanged(layout.memoryNames[slot]);
2728
+ bits &= bits - 1;
2729
+ wrote = true;
2684
2730
  }
2685
- return plan;
2686
2731
  }
2687
- codeVersion(name) {
2688
- return this.codeVersions.get(name) ?? 0;
2732
+ return wrote;
2733
+ }
2734
+ /** Declared busy-wait heads fold their remaining rounds inside the emitted body. */
2735
+ function directDelayLoops(jit, layout) {
2736
+ const delayLoops = /* @__PURE__ */ new Map();
2737
+ for (const [headPc, delay] of effectiveDelays(jit)) {
2738
+ const counter = layout.states.get(delay.counter);
2739
+ if (counter === void 0) continue;
2740
+ const pending = delay.pending === void 0 ? void 0 : {
2741
+ state: layout.states.get(delay.pending.state),
2742
+ period: layout.states.get(delay.pending.period),
2743
+ active: layout.states.get(delay.pending.active)
2744
+ };
2745
+ delayLoops.set(headPc, pending !== void 0 && pending.state !== void 0 && pending.period !== void 0 && pending.active !== void 0 ? {
2746
+ counter,
2747
+ cycles: delay.cycles,
2748
+ pending
2749
+ } : {
2750
+ counter,
2751
+ cycles: delay.cycles
2752
+ });
2689
2753
  }
2690
- intersectsCodeRegion(region, offset, size) {
2691
- if (offset === void 0 || size === void 0) return true;
2692
- return offset < region.size && offset + size > 0;
2754
+ return delayLoops;
2755
+ }
2756
+ /** Binding identity of one session; the compiler keys body and shard reuse off it. */
2757
+ function directBinding(jit, layout) {
2758
+ const { states, memories, pins } = layout;
2759
+ const entry = entryBlockedNames(jit);
2760
+ return {
2761
+ states,
2762
+ memories,
2763
+ pins,
2764
+ pc: {
2765
+ name: jit.options.pc,
2766
+ index: states.get(jit.options.pc)
2767
+ },
2768
+ host: true,
2769
+ ...jit.functions === void 0 ? {} : { functions: jit.functions },
2770
+ split: true,
2771
+ shardSize: DIRECT_SHARD_SIZE,
2772
+ delayLoops: directDelayLoops(jit, layout),
2773
+ entryBlockedStates: entry.states,
2774
+ entryBlockedMemories: entry.memories,
2775
+ blockedStates: jit.directStateGuards,
2776
+ blockedMemories: jit.directMemoryGuards
2777
+ };
2778
+ }
2779
+ /** Grow the frame's local bank only between runs, never while a suffix is suspended. */
2780
+ function growDirectLocals(direct) {
2781
+ if (direct.frame.resume === 0 && direct.frame.locals.length < direct.session.localCount) direct.frame.locals.length = direct.session.localCount;
2782
+ }
2783
+ /** Reconcile busy-wait descriptors; the session recompiles only affected entries. */
2784
+ function updateDirectDelays(jit) {
2785
+ const direct = jit.direct;
2786
+ if (direct === void 0 || jit.directStale) return;
2787
+ direct.session.updateDelays(directDelayLoops(jit, jit.directLayout));
2788
+ growDirectLocals(direct);
2789
+ syncDirectSessionStats(jit, direct.session);
2790
+ }
2791
+ function addDirectInstructions(jit, instructions) {
2792
+ const direct = jit.direct;
2793
+ if (direct === void 0 || jit.directStale || direct.frame.resume !== 0) return;
2794
+ const admitted = [];
2795
+ for (const instruction of instructions) if (directAdmitted(jit, instruction)) admitted.push(instruction);
2796
+ direct.session.updateDelays(directDelayLoops(jit, jit.directLayout));
2797
+ if (admitted.length) {
2798
+ direct.session.add(admitted.map((instruction) => directInstruction(jit, instruction)));
2799
+ for (const instruction of admitted) jit.directMemories.add(instruction.codeRegion?.memory ?? jit.options.code);
2800
+ growDirectLocals(direct);
2801
+ }
2802
+ syncDirectSessionStats(jit, direct.session);
2803
+ }
2804
+ /**
2805
+ * Commit one translated block to the active session. Overlapping replacements are handled by
2806
+ * the session when idle. While an old suffix is suspended, translation must not retarget it:
2807
+ * the session is marked stale so the suffix finishes once and a fresh session rebuilds.
2808
+ */
2809
+ function commitDirectTranslation(jit, instructions, replaced) {
2810
+ const direct = jit.direct;
2811
+ if (direct === void 0 || jit.directStale) return;
2812
+ if (direct.frame.resume !== 0) {
2813
+ if (replaced) staleDirectSession(jit, false);
2814
+ else updateDirectDelays(jit);
2815
+ return;
2693
2816
  }
2694
- hasCodeRegion(name, offset, size) {
2695
- for (const jit of this.jits) {
2696
- if (!jit.active) continue;
2697
- for (const region of jit.codeRegions) if (region.memory === name && this.intersectsCodeRegion(region, offset, size)) return true;
2817
+ addDirectInstructions(jit, instructions);
2818
+ }
2819
+ /** Install the fixed dispatcher and seed it from every admission-eligible cached entry. */
2820
+ function ensureDirectSession(board, jit) {
2821
+ if (jit.direct !== void 0) return jit.direct;
2822
+ if (jit.directStale) jit.directStale = false;
2823
+ const layout = directLayout(jit);
2824
+ if (jit.directCacheInvalid) {
2825
+ if (jit.directCache !== void 0) compileDirectJit.clearCache(jit.directCache);
2826
+ jit.directCacheInvalid = false;
2827
+ }
2828
+ const cache = jit.directCache ??= compileDirectJit.createCache();
2829
+ let session;
2830
+ const admitted = [];
2831
+ try {
2832
+ session = compileDirectJit.createSession(directBinding(jit, layout), cache);
2833
+ for (const instruction of jit.cache.values()) if (directAdmitted(jit, instruction)) admitted.push(instruction);
2834
+ if (admitted.length) session.add(admitted.map((instruction) => directInstruction(jit, instruction)));
2835
+ session.updateDelays(directDelayLoops(jit, layout));
2836
+ } catch (cause) {
2837
+ session?.dispose();
2838
+ throw cause;
2839
+ }
2840
+ for (const instruction of admitted) jit.directMemories.add(instruction.codeRegion?.memory ?? jit.options.code);
2841
+ const barrier = directBarriers(jit);
2842
+ barrier.stateIndex = layout.states;
2843
+ barrier.memoryIndex = layout.memories;
2844
+ const stateMaskWords = Math.ceil(layout.stateNames.length / 32);
2845
+ const memoryMaskWords = Math.ceil(layout.memoryNames.length / 32);
2846
+ if (barrier.stateMask.length !== stateMaskWords) barrier.stateMask = new Int32Array(stateMaskWords);
2847
+ if (barrier.memoryMask.length !== memoryMaskWords) barrier.memoryMask = new Int32Array(memoryMaskWords);
2848
+ syncDirectBarriers(jit);
2849
+ const frame = createDirectFrame(board, jit, layout, session, barrier);
2850
+ const execution = {
2851
+ session,
2852
+ frame,
2853
+ get pcs() {
2854
+ return new Set(session.pcs);
2698
2855
  }
2699
- return false;
2700
- }
2701
- addMetadataChange(state, change) {
2702
- const pending = state.pending;
2703
- let end = change.offset + change.length;
2704
- let start = change.offset;
2705
- for (let index = 0; index < pending.length;) {
2706
- const current = pending[index];
2707
- const currentEnd = current.offset + current.length;
2708
- if (change.offset <= currentEnd && current.offset <= end) {
2709
- start = Math.min(start, current.offset);
2710
- end = Math.max(end, currentEnd);
2711
- pending.splice(index, 1);
2712
- } else index++;
2856
+ };
2857
+ jit.direct = execution;
2858
+ jit.directStale = false;
2859
+ const stats = directStats(jit);
2860
+ stats.directCompiles++;
2861
+ stats.directSessions++;
2862
+ syncDirectSessionStats(jit, session);
2863
+ return execution;
2864
+ }
2865
+ function createDirectFrame(board, jit, layout, session, barrier) {
2866
+ const instance = jit.instance;
2867
+ const { pinObjects, pinNames, pinElectricalSlots } = layout;
2868
+ const checkpointStats = board.checkpointDiagnostics ? directCheckpointStats(jit) : void 0;
2869
+ const frame = {
2870
+ states: layout.stateValues,
2871
+ memories: [...layout.memoryBanks],
2872
+ memoryViews: layout.memoryViews,
2873
+ pins: pinObjects,
2874
+ resistors: [],
2875
+ locals: new Array(session.localCount),
2876
+ stateDirty: new Int32Array(Math.ceil(layout.stateNames.length / 32)),
2877
+ memoryDirty: new Int32Array(Math.ceil(layout.memoryNames.length / 32)),
2878
+ time: board.time,
2879
+ due: board.time,
2880
+ resume: 0,
2881
+ stopAfterInstruction: false,
2882
+ boundarySettled: false
2883
+ };
2884
+ frame.writePinIntent = (pinIndex, value) => {
2885
+ if (!Object.hasOwn(instance, "writeIntent")) {
2886
+ const pin = pinObjects[pinIndex];
2887
+ if (pin.intent === value) return;
2888
+ pin.intent = value;
2889
+ instance.board.markElectricalDirty(pinElectricalSlots[pinIndex]);
2890
+ frame.publishPending = true;
2891
+ return;
2892
+ }
2893
+ board.time = frame.time;
2894
+ if (instance.writeIntent(pinNames[pinIndex], value)) frame.publishPending = true;
2895
+ };
2896
+ frame.host = directHost(board, instance, frame);
2897
+ if (jit.metadata === void 0) {
2898
+ frame.publishCheckpoint = () => {
2899
+ if (checkpointStats !== void 0) checkpointStats.publications++;
2900
+ flushDirect(board, instance, layout, frame);
2901
+ checkpointBoundary(board, checkpointStats, "checkpointPublish");
2902
+ if (jit.directStale || jit.direct?.session !== session || !board.canContinueDirect(jit, frame.due)) {
2903
+ frame.boundarySettled = true;
2904
+ if (checkpointStats !== void 0) checkpointStats.exits++;
2905
+ return false;
2906
+ }
2907
+ board.current = instance;
2908
+ if (checkpointStats !== void 0) checkpointStats.continues++;
2909
+ return true;
2910
+ };
2911
+ if (jit.options.beforeInstruction === void 0) {
2912
+ const pcIndex = layout.states.get(jit.options.pc);
2913
+ frame.finishCheckpoint = (deadline, emptySuffix) => {
2914
+ if (checkpointStats !== void 0) {
2915
+ checkpointStats.finishes++;
2916
+ if (emptySuffix) checkpointStats.emptySuffixes++;
2917
+ }
2918
+ if (emptySuffix) board.time = frame.time;
2919
+ else flushDirect(board, instance, layout, frame);
2920
+ checkpointBoundary(board, checkpointStats, "checkpointFinish");
2921
+ const nextPc = frame.states[pcIndex];
2922
+ if (jit.directStale || jit.direct?.session !== session || !session.has(nextPc) || jit.directSkip === nextPc || frame.time >= deadline || board.events.time < deadline || !emptySuffix && !board.canContinueDirect(jit, frame.time)) {
2923
+ frame.boundarySettled = true;
2924
+ if (checkpointStats !== void 0) checkpointStats.exits++;
2925
+ return false;
2926
+ }
2927
+ if (jit.directObserverRevision !== instance.observerRevision) {
2928
+ if (refreshDirectGuards(jit, void 0, true)) {
2929
+ frame.boundarySettled = true;
2930
+ if (checkpointStats !== void 0) checkpointStats.exits++;
2931
+ return false;
2932
+ }
2933
+ }
2934
+ frame.stopAfterInstruction = false;
2935
+ board.current = instance;
2936
+ if (checkpointStats !== void 0) checkpointStats.continues++;
2937
+ return true;
2938
+ };
2713
2939
  }
2714
- pending.push({
2715
- memory: change.memory,
2716
- offset: start,
2717
- length: end - start
2718
- });
2719
2940
  }
2720
- markMetadataChanged(jit, name, offset, size) {
2721
- if (!jit.metadata) return;
2722
- for (const state of jit.metadata.regions.values()) {
2723
- const region = state.region;
2724
- if (region.memory !== name) continue;
2725
- if (state.appliedVersion === -1) continue;
2726
- if (name === jit.options.code) state.dirty = true;
2727
- if (!this.intersectsCodeRegion(region, offset, size)) continue;
2728
- state.dirty = true;
2729
- const start = offset === void 0 ? 0 : Math.max(0, offset);
2730
- const end = offset === void 0 ? region.size : Math.min(region.size, offset + (size ?? 0));
2731
- if (end > start) this.addMetadataChange(state, {
2732
- memory: name,
2733
- offset: start,
2734
- length: end - start
2735
- });
2941
+ frame.blockedStates = barrier.stateMask;
2942
+ frame.blockedMemories = barrier.memoryMask;
2943
+ return frame;
2944
+ }
2945
+ /**
2946
+ * Run the fixed dispatcher. `untranslated`/`pending` return to `runJit` as an assembly
2947
+ * request; `fallback` means the compiler rejected a PC and the interpreter must take it.
2948
+ */
2949
+ function runDirect(board, jit, hookReads) {
2950
+ const instance = jit.instance;
2951
+ let pending = Boolean(jit.direct?.frame.resume);
2952
+ if (!pending) {
2953
+ if (jit.directStale) {
2954
+ releaseDirectSession(jit);
2955
+ jit.directStale = false;
2736
2956
  }
2957
+ const pc = finite(instance.states.get(jit.options.pc), "pc");
2958
+ const region = codeRegionFor(jit, pc);
2959
+ if (board.execution !== "throughput" || board.jits.length !== 1 || region !== void 0 && region.memory !== jit.options.code || effectivePolling(jit).has(pc) || jit.cache.get(pc)?.polling) return "declined";
2960
+ refreshDirectGuards(jit, hookReads);
2961
+ if (jit.directSkip === pc) return "declined";
2962
+ if (jit.direct === void 0 && ensureDirectSession(board, jit) === void 0) return "declined";
2737
2963
  }
2738
- memoryChanged(name, offset, size) {
2739
- this.memoryChangedSlot(name, this.memoryPlan(name).slot, offset, size);
2740
- }
2741
- memoryChangedPlan(plan, offset, size) {
2742
- this.memoryChangedSlot(plan.name, plan.slot, offset, size);
2743
- }
2744
- memoryChangedSlot(name, slot, offset, size) {
2745
- this.board.invalidate(slot);
2746
- if (!this.codeMemories.has(name)) return;
2747
- if (this.hasCodeRegion(name, offset, size)) this.codeVersions.set(name, this.codeVersion(name) + 1);
2748
- for (const jit of this.jits) {
2749
- let affected = false;
2750
- for (const region of jit.codeRegions) if (region.memory === name && this.intersectsCodeRegion(region, offset, size)) {
2751
- affected = true;
2752
- break;
2964
+ const direct = jit.direct;
2965
+ const frame = direct.frame;
2966
+ const layout = jit.directLayout;
2967
+ for (;;) {
2968
+ if (pending) frame.stopAfterInstruction = true;
2969
+ frame.time = board.time;
2970
+ const start = board.time;
2971
+ let reason;
2972
+ let wrote;
2973
+ const stats = directStats(jit);
2974
+ stats.directCalls++;
2975
+ try {
2976
+ reason = direct.session.run(frame, Math.min(board.executionEnd, board.events.time));
2977
+ } finally {
2978
+ wrote = flushDirect(board, instance, layout, frame);
2979
+ }
2980
+ const progressed = wrote || board.time !== start;
2981
+ if (frame.boundarySettled) frame.boundarySettled = false;
2982
+ else if (reason === "fallback" || reason === "untranslated" || reason === "pending" ? progressed : true) board.boundary("runDirect");
2983
+ if (reason === "untranslated" || reason === "pending") {
2984
+ stats.directDispatchMisses++;
2985
+ if (jit.directStale && frame.resume === 0) {
2986
+ releaseDirectSession(jit);
2987
+ jit.directStale = false;
2753
2988
  }
2754
- if (!affected) continue;
2755
- this.markMetadataChanged(jit, name, offset, size);
2756
- if (jit.options.code === name) {
2757
- jit.cache.clear();
2758
- jit.cacheMemories.clear();
2759
- jit.revision++;
2760
- jit.directPrograms.clear();
2761
- jit.directProgramRevision = -1;
2762
- jit.directSkip = void 0;
2763
- jit.directMisses.clear();
2764
- if (jit.direct?.frame.resume) jit.direct.frame.stopAfterInstruction = true;
2765
- else jit.direct = void 0;
2766
- } else if (jit.cacheMemories.has(name)) {
2767
- for (const [pc, instruction] of jit.cache) if (instruction.codeRegion?.memory === name) jit.cache.delete(pc);
2768
- jit.cacheMemories.delete(name);
2989
+ return progressed ? "assembly-progressed" : "assembly";
2990
+ }
2991
+ if (reason === "fallback") {
2992
+ const nextPc = finite(instance.states.get(jit.options.pc), "pc");
2993
+ if (!(effectivePolling(jit).has(nextPc) || jit.cache.get(nextPc)?.polling)) {
2994
+ stats.directFallbacks++;
2995
+ jit.directSkip = nextPc;
2769
2996
  }
2997
+ if (!progressed && board.time < board.executionEnd) return "fallback";
2998
+ } else if (reason === "stopped") {
2999
+ stats.directStopped++;
3000
+ jit.stopped = true;
3001
+ if (jit.directStale && frame.resume === 0) {
3002
+ releaseDirectSession(jit);
3003
+ jit.directStale = false;
3004
+ }
3005
+ return "ran";
3006
+ } else if (reason === "invalidated") {
3007
+ frame.stopAfterInstruction = false;
3008
+ if (jit.directStale && frame.resume === 0) {
3009
+ releaseDirectSession(jit);
3010
+ jit.directStale = false;
3011
+ }
3012
+ } else stats.directDeadlines++;
3013
+ if (jit.direct === void 0) {
3014
+ board.queueJit(jit);
3015
+ return "ran";
2770
3016
  }
2771
- }
2772
- /**
2773
- * Handles for the fixed names a resumable process body uses. They live on the instance,
2774
- * so a shared program text binds each instance (and each process frame) separately, and
2775
- * every read still resolves the current sample or state value.
2776
- */
2777
- bindResources(specs) {
2778
- const handles = new Array(specs.length);
2779
- for (let index = 0; index < specs.length; index++) {
2780
- const spec = specs[index];
2781
- const key = `${spec[0]}\0${spec[1]}`;
2782
- let handle = this.resourceHandles.get(key);
2783
- if (handle === void 0) {
2784
- handle = this.resourceHandle(spec[0], spec[1]);
2785
- this.resourceHandles.set(key, handle);
3017
+ if (frame.resume) {
3018
+ const wake = Math.max(frame.due, board.time);
3019
+ if (jit.metadata === void 0 && !jit.directStale && board.canContinueDirect(jit, wake)) {
3020
+ board.time = wake;
3021
+ board.current = instance;
3022
+ pending = true;
3023
+ continue;
3024
+ }
3025
+ if (wake > board.time) {
3026
+ board.events.push(wake, () => board.queueJit(jit));
3027
+ return "ran";
2786
3028
  }
2787
- handles[index] = handle;
2788
3029
  }
2789
- return handles;
3030
+ board.queueJit(jit);
3031
+ return "ran";
2790
3032
  }
2791
- /**
2792
- * Each method repeats the generic host operation exactly: dependency slots are still
2793
- * recorded, state writes still snapshot, and memory stores still run the code-memory
2794
- * invalidation that clears JIT caches. Every resource a declaration already provides is
2795
- * resolved here, at bind time; a name that does not exist yet keeps resolving lazily so
2796
- * it still fails at its first real use, not while binding.
2797
- */
2798
- resourceHandle(kind, name) {
2799
- if (kind === "pin") {
2800
- let pin = this.pins.get(name);
2801
- let slot = pin === void 0 ? -1 : this.board.electricalSlot(pin);
2802
- let sample = pin === void 0 ? void 0 : this.sampleResources.get(name);
2803
- let lastResistance;
2804
- let lastIntent;
2805
- const resolve = () => {
2806
- if (pin === void 0) {
2807
- pin = this.pin(name);
2808
- slot = this.board.electricalSlot(pin);
2809
- sample = this.sampleResources.get(name);
2810
- }
2811
- return pin;
2812
- };
2813
- return Object.freeze({
2814
- sample: () => {
2815
- const current = resolve();
2816
- const dependencies = this.dependencies();
2817
- if (dependencies) dependencies.set(sample, sample.version);
2818
- return current.sample;
2819
- },
2820
- intent: (value) => {
2821
- const current = resolve();
2822
- if (current.intent === value) return;
2823
- current.intent = value;
2824
- this.board.markElectricalDirty(slot);
2825
- },
2826
- resistor: (resistance) => {
2827
- if (lastIntent !== void 0 && resistance === lastResistance) return lastIntent;
2828
- const r = electricalNumber(resistance);
2829
- if (r < .001 || r > 1e9) throw new ElectricalParameterError("Resistance outside [0.001, 1e9]");
2830
- const intent = this.resistorIntent(name, r);
2831
- lastResistance = resistance;
2832
- lastIntent = intent;
2833
- return intent;
2834
- }
2835
- });
2836
- }
2837
- if (kind === "state") {
2838
- let slot = this.states.has(name) ? this.stateResources.get(name) : void 0;
2839
- let banked = slot === void 0 ? -1 : this.directBank?.states.get(name) ?? -2;
2840
- const resolve = () => slot ??= this.stateSlot(name);
2841
- const states = this.states;
2842
- return Object.freeze({
2843
- read: () => {
2844
- const current = resolve();
2845
- const dependencies = this.dependencies();
2846
- if (dependencies) dependencies.set(current, current.version);
2847
- if (banked === -2) banked = this.directBank?.states.get(name) ?? -1;
2848
- return banked < 0 ? states.get(name) : this.directBank.stateValues[banked];
2849
- },
2850
- write: (value) => {
2851
- const current = resolve();
2852
- this.writeState(name, value, current);
2853
- }
2854
- });
2855
- }
2856
- let plan = this.memories.has(name) ? this.memoryPlan(name) : void 0;
2857
- const resolve = () => plan ??= this.memoryPlan(name);
2858
- const read = (size, little, offset) => {
2859
- const current = resolve();
2860
- const at = range(current.bytes, offset, size);
2861
- const dependencies = this.dependencies();
2862
- if (dependencies) dependencies.set(current.slot, current.slot.version);
2863
- return size === 1 ? current.bytes[at] : size === 2 ? current.view.getUint16(at, little) : current.view.getUint32(at, little);
2864
- };
2865
- const write = (size, little, offset, value) => {
2866
- const current = resolve();
2867
- const at = range(current.bytes, offset, size);
2868
- const n = integer(value, "stored value");
2869
- if (size === 1) current.bytes[at] = n;
2870
- else if (size === 2) current.view.setUint16(at, n, little);
2871
- else current.view.setUint32(at, n, little);
2872
- this.memoryChangedSlot(name, current.slot, at, size);
2873
- };
2874
- return Object.freeze({
2875
- load8: (offset) => read(1, false, offset),
2876
- load16le: (offset) => read(2, true, offset),
2877
- load16be: (offset) => read(2, false, offset),
2878
- load32le: (offset) => read(4, true, offset),
2879
- load32be: (offset) => read(4, false, offset),
2880
- store8: (offset, value) => write(1, false, offset, value),
2881
- store16le: (offset, value) => write(2, true, offset, value),
2882
- store16be: (offset, value) => write(2, false, offset, value),
2883
- store32le: (offset, value) => write(4, true, offset, value),
2884
- store32be: (offset, value) => write(4, false, offset, value),
2885
- length: () => this.memory(name).length,
2886
- copy: (offset, length) => {
2887
- this.track(this.memoryResources, name);
2888
- const bytes = this.memory(name), at = range(bytes, offset, length);
2889
- return bytes.slice(at, at + Number(length));
2890
- }
3033
+ }
3034
+ /** A PC is ready for direct execution when its translation is not polling or secondary. */
3035
+ function directPcAdmitted(jit, pc) {
3036
+ const region = codeRegionFor(jit, pc);
3037
+ if (region !== void 0 && region.memory !== jit.options.code) return false;
3038
+ if (effectivePolling(jit).has(pc)) return false;
3039
+ return jit.cache.get(pc)?.polling !== true;
3040
+ }
3041
+ /**
3042
+ * Satisfy one assembly request without replaying the boundary that asked for it. A missing
3043
+ * cache entry uses the same translation path as the interpreter; an existing entry is simply
3044
+ * added because it may have been translated while an old suffix was still suspended.
3045
+ */
3046
+ function assembleDirect(board, jit, pc) {
3047
+ if (jit.metadata !== void 0) ensureMetadataForPc(board, jit, pc);
3048
+ const direct = jit.direct;
3049
+ if (direct === void 0 || jit.directStale || direct.frame.resume !== 0) return false;
3050
+ if (!directPcAdmitted(jit, pc)) return false;
3051
+ let instruction = jit.cache.get(pc);
3052
+ if (instruction === void 0) {
3053
+ translateBlock(board, jit, pc);
3054
+ instruction = jit.cache.get(pc);
3055
+ return instruction !== void 0;
3056
+ }
3057
+ if (!direct.session.has(pc)) addDirectInstructions(jit, [instruction]);
3058
+ return true;
3059
+ }
3060
+ /**
3061
+ * Handle `untranslated` from the dispatcher. Hooks and polling `consume` already ran for this
3062
+ * boundary, so they are never repeated here. At most one retry keeps a rejected body from
3063
+ * looping; a progressed prefix that still cannot continue direct yields to the scheduler so
3064
+ * the next instruction gets its own boundary.
3065
+ */
3066
+ function retryDirectAfterAssembly(board, jit, progressed) {
3067
+ if (progressed) {
3068
+ board.queueJit(jit);
3069
+ return true;
3070
+ }
3071
+ if (jit.direct === void 0 || jit.directStale) return false;
3072
+ if (!assembleDirect(board, jit, finite(jit.instance.states.get(jit.options.pc), "pc"))) return false;
3073
+ const retried = runDirect(board, jit);
3074
+ if (retried === "ran") return true;
3075
+ if (retried === "assembly-progressed") {
3076
+ board.queueJit(jit);
3077
+ return true;
3078
+ }
3079
+ return false;
3080
+ }
3081
+ function pollingDependencies(jit, dependencies, pc) {
3082
+ const result = new Map(dependencies);
3083
+ const instance = jit.instance;
3084
+ const pcSlot = instance.stateResources.get(jit.options.pc);
3085
+ result.set(pcSlot, pcSlot.version);
3086
+ const memory = (pc === void 0 ? void 0 : codeRegionFor(jit, pc))?.memory ?? jit.options.code;
3087
+ const slot = instance.memoryResources.get(memory);
3088
+ result.set(slot, slot.version);
3089
+ return result;
3090
+ }
3091
+ /** Park a polling JIT and, when requested, schedule the next device time event. */
3092
+ function waitForPolling(board, jit, dependencies, duration, advance) {
3093
+ jit.dependencies = dependencies;
3094
+ jit.pollingWait = true;
3095
+ jit.pollingPeriod = 0;
3096
+ board.parkWaiter(jit);
3097
+ const token = ++jit.pollingToken;
3098
+ board.boundary("polling");
3099
+ if (duration === 0 || advance === void 0) return;
3100
+ const due = time(board.time + duration);
3101
+ board.events.push(due, () => {
3102
+ if (token !== jit.pollingToken || !jit.active || jit.stopped || !board.waitingJits.has(jit)) return;
3103
+ const pending = jit.dependencies;
3104
+ delete jit.dependencies;
3105
+ board.unparkWaiter(jit);
3106
+ jit.pollingToken++;
3107
+ board.current = jit.instance;
3108
+ if (!jit.instance.dependenciesCurrent(pending)) {
3109
+ board.queueJit(jit);
3110
+ return;
3111
+ }
3112
+ jit.instance.syncCall(advance, [duration]);
3113
+ board.boundary("polling");
3114
+ board.queueJit(jit);
3115
+ });
3116
+ }
3117
+ function jitSignal(board, jit, signal) {
3118
+ if (signal.kind === "elapse") {
3119
+ const duration = time(signal.duration);
3120
+ if (duration === 0) return false;
3121
+ const due = time(board.time + duration);
3122
+ board.events.push(due, () => board.queueJit(jit));
3123
+ board.boundary("jitSignal");
3124
+ return true;
3125
+ }
3126
+ if (signal.kind === "waitUntil") {
3127
+ const checked = jit.instance.evaluate(() => syncJitCall(jit, signal.predicate));
3128
+ if (checked.value === true) return false;
3129
+ jit.predicate = signal.predicate;
3130
+ jit.pollingWait = false;
3131
+ jit.dependencies = checked.dependencies;
3132
+ board.parkWaiter(jit);
3133
+ board.boundary("jitSignal");
3134
+ return true;
3135
+ }
3136
+ if (signal.kind === "stop") {
3137
+ jit.stopped = true;
3138
+ jit.execution = void 0;
3139
+ board.boundary("jitSignal");
3140
+ return true;
3141
+ }
3142
+ if (signal.kind === "redirect") {
3143
+ finite(signal.pc, "redirect target");
3144
+ const duration = time(signal.delay);
3145
+ jit.instance.host.write(jit.options.pc, signal.pc);
3146
+ jit.execution = void 0;
3147
+ const polling = jit.automaticPolling && duration > 0 && signal.pc === jit.currentPc && jit.pollReads;
3148
+ const dependencies = polling ? pollingDependencies(jit, polling, jit.currentPc) : void 0;
3149
+ jit.automaticPolling = false;
3150
+ jit.pollReads = void 0;
3151
+ board.boundary("jitSignal");
3152
+ if (duration === 0) board.queueJit(jit);
3153
+ else board.events.push(time(board.time + duration), () => {
3154
+ if (!jit.active || jit.stopped) return;
3155
+ if (dependencies && jit.instance.dependenciesCurrent(dependencies)) {
3156
+ jit.dependencies = dependencies;
3157
+ jit.pollingWait = true;
3158
+ jit.pollingPeriod = duration;
3159
+ jit.pollingOrigin = board.time;
3160
+ board.parkWaiter(jit);
3161
+ } else board.queueJit(jit);
2891
3162
  });
3163
+ return true;
2892
3164
  }
2893
- prepare() {
2894
- for (const declaration of this.entry.model.declarations) if (declaration.kind === "pin") this.pins.set(declaration.name, {
2895
- id: `${this.id}\0${declaration.name}`,
2896
- instance: this.id,
2897
- name: declaration.name,
2898
- intent: [],
2899
- sample: {
2900
- voltage: null,
2901
- level: "unknown",
2902
- status: "floating"
2903
- }
3165
+ throw new TypeError("Invalid JIT suspension");
3166
+ }
3167
+ /**
3168
+ * Translate one PC, atomically publish the block's cache entries, and commit its admitted
3169
+ * entries to the active session. Reused by both the interpreter path and assembly retries.
3170
+ */
3171
+ function translateBlock(board, jit, pc) {
3172
+ const prior = board.phase;
3173
+ board.phase = "translate";
3174
+ let valid = true;
3175
+ let marking = false;
3176
+ try {
3177
+ const codeRegion = codeRegionFor(jit, pc);
3178
+ const codeMemory = codeRegion?.memory ?? jit.options.code;
3179
+ const memory = jit.instance.memory(codeMemory);
3180
+ const bytes = codeRegion === void 0 || codeRegion.size >= memory.length ? memory : memory.subarray(0, codeRegion.size);
3181
+ const code = bytesView(bytes, () => {
3182
+ if (!valid) throw board.error("OBJECT_DISPOSED", "Translation view expired", jit.instance);
2904
3183
  });
2905
- for (const declaration of this.entry.model.declarations) switch (declaration.kind) {
2906
- case "property":
2907
- case "const":
2908
- this.read(declaration.kind, declaration.name);
2909
- break;
2910
- case "state":
2911
- this.states.set(declaration.name, snapshot(computation(declaration.initial, this.host)));
2912
- break;
2913
- case "memory": {
2914
- const length = nonnegative(computation(declaration.length, this.host), "memory length");
2915
- this.memorySizes.set(declaration.name, length);
2916
- break;
3184
+ const shareMarks = jit.options.shareDirectBodies === true ? [] : void 0;
3185
+ marking = shareMarks !== void 0;
3186
+ const result = jit.options.translate(Object.freeze({
3187
+ pc,
3188
+ code,
3189
+ codeBase: codeRegion?.base ?? 0,
3190
+ codeVersion: jit.instance.codeVersion(codeMemory),
3191
+ ...shareMarks === void 0 ? {} : { markDirectBodyShareable: (markPc, byteLength) => {
3192
+ if (!marking) return;
3193
+ directStats(jit).directShareCallbacks++;
3194
+ shareMarks.push({
3195
+ pc: markPc,
3196
+ byteLength
3197
+ });
3198
+ } }
3199
+ }), createJitBlockBuilder({ device: jit.model }));
3200
+ acceptSync(result);
3201
+ marking = false;
3202
+ const block = validateBoundBlockIR(result, jit.model);
3203
+ if (block.instructions[0]?.pc !== pc) throw new TypeError("Translated first pc does not match");
3204
+ const instructions = block.instructions.map((instruction) => {
3205
+ const region = codeRegionFor(jit, instruction.pc);
3206
+ return {
3207
+ pc: instruction.pc,
3208
+ nextPc: instruction.nextPc,
3209
+ body: instruction.body,
3210
+ polling: isPollingInstruction(instruction.body, instruction.pc, jit.options.pc),
3211
+ execute: body(instruction.body),
3212
+ codeRegion: region,
3213
+ codeVersion: jit.instance.codeVersion(region?.memory ?? jit.options.code)
3214
+ };
3215
+ });
3216
+ if (shareMarks !== void 0) applyDirectShareMarks(jit, codeRegion, code.length, instructions, shareMarks);
3217
+ const replaced = instructions.some((entry) => jit.cache.has(entry.pc));
3218
+ for (let index = instructions.length - 1; index >= 0; index--) {
3219
+ const entry = instructions[index];
3220
+ jit.cache.set(entry.pc, entry);
3221
+ jit.cacheMemories.add(entry.codeRegion?.memory ?? jit.options.code);
3222
+ }
3223
+ if (instructions.some((entry) => entry.codeRegion === void 0 || entry.codeRegion.memory === jit.options.code)) jit.revision++;
3224
+ jit.directSkip = void 0;
3225
+ commitDirectTranslation(jit, instructions, replaced);
3226
+ return instructions;
3227
+ } catch (cause) {
3228
+ throw board.wrap(cause, "JIT_FAILED", "translate", jit.instance);
3229
+ } finally {
3230
+ valid = false;
3231
+ marking = false;
3232
+ board.phase = prior;
3233
+ }
3234
+ }
3235
+ function runJit(board, jit) {
3236
+ jit.queued = false;
3237
+ if (!jit.active || jit.stopped) return;
3238
+ board.current = jit.instance;
3239
+ if (jit.metadata !== void 0) ensureMetadataForPc(board, jit, finite(jit.instance.states.get(jit.options.pc), "pc"));
3240
+ if (jit.direct?.frame.resume) {
3241
+ const outcome = runDirect(board, jit);
3242
+ if (outcome === "assembly" || outcome === "assembly-progressed") retryDirectAfterAssembly(board, jit, true);
3243
+ return;
3244
+ }
3245
+ if (!jit.execution) {
3246
+ jit.automaticPolling = false;
3247
+ jit.pollReads = void 0;
3248
+ let hookReads;
3249
+ let hookPending = false;
3250
+ const hook = jit.options.beforeInstruction;
3251
+ if (hook) {
3252
+ const kind = jit.instance.declarations.get(hook.when).kind;
3253
+ const priorPc = jit.instance.states.get(jit.options.pc);
3254
+ const checked = board.execution === "throughput" && (board.jits.length === 1 || effectivePolling(jit).has(priorPc)) ? jit.instance.evaluate(() => jit.instance.read(kind, hook.when)) : void 0;
3255
+ const handled = (checked ? checked.value : jit.instance.read(kind, hook.when)) === true;
3256
+ if (handled) {
3257
+ const execution = jit.instance.invoke(hook.call);
3258
+ const step = execution.next();
3259
+ if (!step.done) {
3260
+ jit.execution = execution;
3261
+ if (jitSignal(board, jit, step.value)) return;
3262
+ throw new TypeError("Invalid hook suspension");
3263
+ }
2917
3264
  }
2918
- case "pin": {
2919
- const pin = this.pins.get(declaration.name);
2920
- if (declaration.low && declaration.high) {
2921
- const low = electricalNumber(computation(declaration.low, this.host)), high = electricalNumber(computation(declaration.high, this.host));
2922
- if (low >= high) throw new ElectricalParameterError("Pin thresholds must satisfy low < high");
2923
- Object.assign(pin, {
2924
- low,
2925
- high
2926
- });
3265
+ hookReads = checked?.dependencies;
3266
+ hookPending = handled;
3267
+ }
3268
+ const pc = finite(jit.instance.states.get(jit.options.pc), "pc");
3269
+ if (jit.metadata !== void 0 && hook !== void 0) ensureMetadataForPc(board, jit, pc);
3270
+ if (board.execution === "throughput") {
3271
+ const declaration = effectivePolling(jit).get(pc);
3272
+ if (declaration) {
3273
+ const checked = jit.instance.evaluate(() => jit.instance.syncCall(declaration.predicate));
3274
+ if (checked.value !== true) {
3275
+ const dependencies = new Map([...hookReads ?? [], ...checked.dependencies]);
3276
+ let duration = 0;
3277
+ const wait = declaration.wait;
3278
+ if (wait) duration = time(jit.instance.evaluate(() => jit.instance.syncCall(wait.delay), dependencies).value);
3279
+ waitForPolling(board, jit, pollingDependencies(jit, dependencies, pc), duration, wait?.advance);
3280
+ return;
2927
3281
  }
2928
- if (declaration.initial) pin.intent = computation(declaration.initial, this.host);
2929
- break;
3282
+ if (declaration.consume) jit.instance.syncCall(declaration.consume);
2930
3283
  }
2931
- case "channel": {
2932
- const capacity = nonnegative(computation(declaration.capacity, this.host), "capacity");
2933
- if (capacity === 0) throw new RangeError("Capacity must be positive");
2934
- let maxLength;
2935
- if (declaration.maxLength) {
2936
- maxLength = nonnegative(computation(declaration.maxLength, this.host), "maxLength");
2937
- if (maxLength === 0) throw new RangeError("maxLength must be positive");
3284
+ if (!hookPending && board.jits.length === 1) {
3285
+ const outcome = runDirect(board, jit, hookReads);
3286
+ if (outcome === "ran") return;
3287
+ if (outcome === "assembly" || outcome === "assembly-progressed") {
3288
+ if (retryDirectAfterAssembly(board, jit, outcome === "assembly-progressed")) return;
2938
3289
  }
2939
- this.channels.set(declaration.name, {
2940
- declaration,
2941
- capacity,
2942
- ...maxLength === void 0 ? {} : { maxLength },
2943
- overflow: declaration.overflow ? String(computation(declaration.overflow, this.host)) : "drop_new",
2944
- incoming: new Fifo(),
2945
- pending: new Fifo(),
2946
- outgoing: new Fifo()
2947
- });
2948
- break;
2949
3290
  }
2950
- case "notification":
2951
- if (declaration.direction === "output") this.notificationOutputs.set(declaration.name, null);
2952
- break;
2953
- case "start":
2954
- case "on":
2955
- this.processes.push({
2956
- instance: this,
2957
- declaration,
2958
- resumable: resumable(declaration.body),
2959
- ...declaration.kind === "on" ? { source: declaration.sourcePath } : {},
2960
- state: "idle",
2961
- pending: false
2962
- });
2963
- break;
2964
- case "reaction": this.reactions.push({
2965
- instance: this,
2966
- declaration,
2967
- previous: void 0,
2968
- synchronousProgram: synchronousBody(this, declaration.body) ?? null,
2969
- frame: void 0
2970
- });
2971
- }
2972
- for (const [name, channel] of this.channels) if (channel.declaration.direction === "input") this.batchInputs.push(channel);
2973
- else {
2974
- this.batchOutputs.push([name, channel]);
2975
- this.emptyOutputs[name] = EMPTY_MESSAGES;
2976
- }
2977
- for (const name of this.notificationOutputs.keys()) {
2978
- this.batchNotifications.push(name);
2979
- this.emptyOutputs[name] = null;
2980
3291
  }
2981
- Object.freeze(this.emptyOutputs);
3292
+ let instruction = jit.cache.get(pc);
3293
+ if (!instruction) instruction = translateBlock(board, jit, pc)[0];
3294
+ jit.currentPc = pc;
3295
+ if (board.execution === "throughput" && board.jits.length === 1) directStats(jit).directGenericInstructions++;
3296
+ jit.automaticPolling = board.execution === "throughput" && board.jits.length === 1 && instruction.polling && !hookPending && (!hook || hookReads !== void 0);
3297
+ jit.pollReads = hookReads;
3298
+ jit.instance.host.write(jit.options.pc, instruction.nextPc);
3299
+ jit.execution = instruction.execute(jit.host);
3300
+ }
3301
+ for (;;) {
3302
+ const step = jit.automaticPolling ? (() => {
3303
+ const checked = jit.instance.evaluate(() => jit.execution.next());
3304
+ jit.pollReads = new Map([...jit.pollReads ?? [], ...checked.dependencies]);
3305
+ return checked.value;
3306
+ })() : jit.execution.next();
3307
+ if (step.done) {
3308
+ jit.execution = void 0;
3309
+ board.boundary("runJit");
3310
+ board.queueJit(jit);
3311
+ return;
3312
+ }
3313
+ if (jitSignal(board, jit, step.value)) return;
3314
+ }
3315
+ }
3316
+ //#endregion
3317
+ //#region src/runtime/instance.ts
3318
+ var EMPTY_MESSAGES = Object.freeze([]);
3319
+ var jitModels = /* @__PURE__ */ new WeakMap();
3320
+ /** Retain the binding identity when adapters reuse the same immutable function table. */
3321
+ function bindJitFunctions(base, functions) {
3322
+ if (functions.length === 0) return base;
3323
+ let models = jitModels.get(base);
3324
+ const cached = models?.get(functions);
3325
+ if (cached !== void 0) return cached;
3326
+ const model = validateDeviceIR({
3327
+ ...base,
3328
+ declarations: base.declarations.concat(functions)
3329
+ });
3330
+ for (const declaration of model.declarations.slice(base.declarations.length)) if (declaration.kind !== "function") throw new TypeError("Expected JIT function declaration");
3331
+ if (models === void 0) {
3332
+ models = /* @__PURE__ */ new WeakMap();
3333
+ jitModels.set(base, models);
3334
+ }
3335
+ models.set(functions, model);
3336
+ return model;
3337
+ }
3338
+ /** Membership test without allocating: every key of `next` is already in `previous`. */
3339
+ function hasEvery(previous, next) {
3340
+ for (const slot of next.keys()) if (!previous.has(slot)) return false;
3341
+ return true;
3342
+ }
3343
+ function createContext(owner, board) {
3344
+ return Object.freeze({
3345
+ get props() {
3346
+ board.assertReadAllowed(owner);
3347
+ return Object.freeze(Object.fromEntries([...owner.props].map(([key, value]) => [key, externalValue(value)])));
3348
+ },
3349
+ get inputs() {
3350
+ owner.assertCallAllowed();
3351
+ return owner.inputs();
3352
+ },
3353
+ get memory() {
3354
+ board.assertReadAllowed(owner);
3355
+ return owner.publicMemory();
3356
+ },
3357
+ topics: board.topicBridge(owner),
3358
+ reportError: (error) => board.report(owner, error),
3359
+ attachJit: (options) => owner.attach(options),
3360
+ loadBytes: (name, bytes, ...offset) => owner.loadBytes(name, bytes, offset.length ? offset[0] : 0)
3361
+ });
3362
+ }
3363
+ /**
3364
+ * State map whose scalar direct-bank writes are synced lazily on read.
3365
+ *
3366
+ * Direct JIT writes update `stateValues` and invalidate `stateSlots` at every boundary,
3367
+ * while no observer or host reads `instance.states` until a reaction, observation,
3368
+ * fallback or external query accesses it. Deferring the string-keyed `Map.set` calls
3369
+ * until an actual read removes redundant map updates across resident GPIO edges while
3370
+ * keeping `instance.states` an exact `Map<string, unknown>` at every read site.
3371
+ */
3372
+ var StateMirrorMap = class extends Map {
3373
+ names = [];
3374
+ bankValues = [];
3375
+ dirty = /* @__PURE__ */ new Int32Array(0);
3376
+ pending = false;
3377
+ bindDirectBank(names, values) {
3378
+ this.names = names;
3379
+ this.bankValues = values;
3380
+ this.dirty = new Int32Array(Math.ceil(names.length / 32));
3381
+ }
3382
+ markDirectDirty(word, bits) {
3383
+ this.dirty[word] |= bits;
3384
+ this.pending = true;
3385
+ }
3386
+ flush() {
3387
+ if (!this.pending) return;
3388
+ this.pending = false;
3389
+ const { names, bankValues, dirty } = this;
3390
+ for (let word = 0; word < dirty.length; word++) {
3391
+ let bits = dirty[word];
3392
+ if (bits === 0) continue;
3393
+ dirty[word] = 0;
3394
+ const base = word << 5;
3395
+ while (bits !== 0) {
3396
+ const index = base + 31 - Math.clz32(bits & -bits);
3397
+ super.set(names[index], bankValues[index]);
3398
+ bits &= bits - 1;
3399
+ }
3400
+ }
2982
3401
  }
2983
- captureBatch(from, to) {
2984
- for (const channel of this.batchInputs) if (channel.incoming.length) channel.incoming.clear();
2985
- let outputs = this.emptyOutputs;
2986
- for (const [name, channel] of this.batchOutputs) {
2987
- if (!channel.outgoing.length) continue;
2988
- if (outputs === this.emptyOutputs) outputs = Object.assign(Object.create(null), this.emptyOutputs);
2989
- outputs[name] = Object.freeze(channel.outgoing.drain().map((message) => Object.freeze({
2990
- time: message.time,
2991
- value: externalValue(message.value)
2992
- })));
2993
- }
2994
- for (const name of this.batchNotifications) {
2995
- const notified = this.notificationOutputs.get(name);
2996
- if (notified === null) continue;
2997
- if (outputs === this.emptyOutputs) outputs = Object.assign(Object.create(null), this.emptyOutputs);
2998
- outputs[name] = Object.freeze({ time: notified });
2999
- this.notificationOutputs.set(name, null);
3000
- }
3001
- return Object.freeze({
3002
- from,
3003
- to,
3004
- outputs: outputs === this.emptyOutputs ? outputs : Object.freeze(outputs)
3005
- });
3402
+ get(key) {
3403
+ if (this.pending) this.flush();
3404
+ return super.get(key);
3006
3405
  }
3007
- assertCreation() {
3008
- for (const declaration of this.entry.model.declarations) {
3009
- if (declaration.kind !== "assert") continue;
3010
- if (!body(declaration.body)(this.host).next().done) throw new TypeError("Creation assertion suspended");
3011
- }
3406
+ set(key, value) {
3407
+ if (this.pending) this.flush();
3408
+ return super.set(key, value);
3012
3409
  }
3013
- allocate() {
3014
- for (const [name, length] of this.memorySizes) {
3015
- const bytes = new Uint8Array(length);
3016
- this.memories.set(name, bytes);
3017
- this.memoryViews.set(name, new DataView(bytes.buffer));
3018
- }
3019
- this.memorySizes.clear();
3410
+ entries() {
3411
+ if (this.pending) this.flush();
3412
+ return super.entries();
3020
3413
  }
3021
- assertCallAllowed() {
3022
- this.board.assertCallAllowed(this);
3414
+ values() {
3415
+ if (this.pending) this.flush();
3416
+ return super.values();
3023
3417
  }
3024
- inputs() {
3025
- const result = Object.create(null);
3026
- for (const declaration of this.entry.model.declarations) {
3027
- if (declaration.kind === "channel" && declaration.direction === "input") result[declaration.name] = Object.freeze({ send: (value) => {
3028
- this.assertCallAllowed();
3029
- this.send(declaration.name, value, true);
3030
- } });
3031
- if (declaration.kind === "notification" && declaration.direction === "input") result[declaration.name] = Object.freeze({ notify: () => {
3032
- this.assertCallAllowed();
3033
- this.notificationInputs.add(declaration.name);
3034
- } });
3418
+ forEach(callbackfn, thisArg) {
3419
+ if (this.pending) this.flush();
3420
+ super.forEach(callbackfn, thisArg);
3421
+ }
3422
+ [Symbol.iterator]() {
3423
+ if (this.pending) this.flush();
3424
+ return super[Symbol.iterator]();
3425
+ }
3426
+ };
3427
+ var Instance = class {
3428
+ board;
3429
+ entry;
3430
+ id;
3431
+ declarations = /* @__PURE__ */ new Map();
3432
+ props = /* @__PURE__ */ new Map();
3433
+ constants = /* @__PURE__ */ new Map();
3434
+ states = new StateMirrorMap();
3435
+ directBank;
3436
+ memories = /* @__PURE__ */ new Map();
3437
+ memoryViews = /* @__PURE__ */ new Map();
3438
+ memorySizes = /* @__PURE__ */ new Map();
3439
+ pins = /* @__PURE__ */ new Map();
3440
+ channels = /* @__PURE__ */ new Map();
3441
+ notificationInputs = /* @__PURE__ */ new Set();
3442
+ notificationOutputs = /* @__PURE__ */ new Map();
3443
+ batchInputs = [];
3444
+ batchOutputs = [];
3445
+ batchNotifications = [];
3446
+ emptyOutputs = Object.create(null);
3447
+ resources = [];
3448
+ jits = [];
3449
+ processes = [];
3450
+ reactions = [];
3451
+ derived = /* @__PURE__ */ new Map();
3452
+ /** One-entry memo for repeated `read('derived', name)` calls inside a body. */
3453
+ derivedName;
3454
+ derivedEntry;
3455
+ derivedBuffers = /* @__PURE__ */ new Map();
3456
+ stateResources = /* @__PURE__ */ new Map();
3457
+ memoryResources = /* @__PURE__ */ new Map();
3458
+ sampleResources = /* @__PURE__ */ new Map();
3459
+ observerRevision = 0;
3460
+ dependencyStack = [];
3461
+ observations = /* @__PURE__ */ new WeakMap();
3462
+ staticObservations = /* @__PURE__ */ new WeakMap();
3463
+ resistorIntents = /* @__PURE__ */ new Map();
3464
+ sampleEntries = /* @__PURE__ */ new Map();
3465
+ intentEntries = /* @__PURE__ */ new Map();
3466
+ stateSlots = /* @__PURE__ */ new Map();
3467
+ /** Per-instance handles for the fixed resources a resumable process body binds. */
3468
+ resourceHandles = /* @__PURE__ */ new Map();
3469
+ memoryPlans = /* @__PURE__ */ new Map();
3470
+ /** 按 memory 维护的代码代际;只有 code region 内写入才递增。 */
3471
+ codeVersions = /* @__PURE__ */ new Map();
3472
+ /**
3473
+ * Every memory name any attached JIT binds as a code region. A write outside this set
3474
+ * cannot affect a JIT, so the store path skips the region scans entirely.
3475
+ */
3476
+ codeMemories = /* @__PURE__ */ new Set();
3477
+ observationFrames = /* @__PURE__ */ new WeakMap();
3478
+ evaluating = /* @__PURE__ */ new Set();
3479
+ random;
3480
+ host;
3481
+ context;
3482
+ adapter;
3483
+ valid = true;
3484
+ rawProps;
3485
+ constructor(board, entry, id, props, seed, override) {
3486
+ this.board = board;
3487
+ this.entry = entry;
3488
+ this.id = id;
3489
+ for (const declaration of entry.model.declarations) {
3490
+ if ("name" in declaration) this.declarations.set(declaration.name, declaration);
3491
+ if (declaration.kind === "state" || declaration.kind === "memory" || declaration.kind === "pin") (declaration.kind === "state" ? this.stateResources : declaration.kind === "memory" ? this.memoryResources : this.sampleResources).set(declaration.name, {
3492
+ version: 0,
3493
+ subscribers: /* @__PURE__ */ new Set(),
3494
+ waiters: void 0
3495
+ });
3035
3496
  }
3036
- return Object.freeze(result);
3497
+ dataObject(props);
3498
+ this.rawProps = props;
3499
+ for (const key of Object.keys(props)) if (this.declarations.get(key)?.kind !== "property") throw new TypeError(`Unknown property ${key}`);
3500
+ this.random = randomState(seed, id, override);
3501
+ this.host = {
3502
+ read: (kind, name) => this.read(kind, name),
3503
+ write: (name, value) => this.writeState(name, value, this.stateSlot(name)),
3504
+ sample: (ref) => {
3505
+ return this.readSample(ref);
3506
+ },
3507
+ intent: (pin, value) => {
3508
+ this.writeIntent(pin, value);
3509
+ },
3510
+ resistor: (pin, resistance) => {
3511
+ const r = electricalNumber(resistance);
3512
+ if (r < .001 || r > 1e9) throw new ElectricalParameterError("Resistance outside [0.001, 1e9]");
3513
+ return this.resistorIntent(pin, r);
3514
+ },
3515
+ memoryLength: (memory) => this.memory(memory).length,
3516
+ load: (kind, memory, offset) => {
3517
+ const plan = this.memoryPlan(memory);
3518
+ const size = kind.startsWith("load8") ? 1 : kind.startsWith("load16") ? 2 : 4;
3519
+ const at = range(plan.bytes, offset, size);
3520
+ const dependencies = this.dependencies();
3521
+ if (dependencies) dependencies.set(plan.slot, plan.slot.version);
3522
+ if (size === 1) return plan.bytes[at];
3523
+ return size === 2 ? plan.view.getUint16(at, kind.endsWith("le")) : plan.view.getUint32(at, kind.endsWith("le"));
3524
+ },
3525
+ store: (kind, memory, offset, value) => {
3526
+ const plan = this.memoryPlan(memory);
3527
+ const size = kind.startsWith("store8") ? 1 : kind.startsWith("store16") ? 2 : 4;
3528
+ const at = range(plan.bytes, offset, size);
3529
+ const n = integer(value, "stored value");
3530
+ if (size === 1) plan.bytes[at] = n;
3531
+ else if (size === 2) plan.view.setUint16(at, n, kind.endsWith("le"));
3532
+ else plan.view.setUint32(at, n, kind.endsWith("le"));
3533
+ this.memoryChangedPlan(plan, at, size);
3534
+ },
3535
+ copyBytes: (memory, offset, length) => {
3536
+ this.track(this.memoryResources, String(memory));
3537
+ const bytes = this.memory(memory), at = range(bytes, offset, length);
3538
+ return bytes.slice(at, at + Number(length));
3539
+ },
3540
+ send: (name, value) => this.send(name, value, false),
3541
+ notify: (name) => {
3542
+ if (!this.notificationOutputs.has(name)) throw new TypeError(`Unknown notification ${name}`);
3543
+ this.notificationOutputs.set(name, board.time);
3544
+ },
3545
+ now: () => board.time,
3546
+ random: () => nextRandom(this.random),
3547
+ call: (name, args) => this.invoke(name, args),
3548
+ assert: (condition, message) => {
3549
+ if (condition !== true) throw new Error(message === void 0 ? "Assertion failed" : String(message));
3550
+ },
3551
+ bind: (specs) => this.bindResources(specs)
3552
+ };
3553
+ this.context = createContext(this, board);
3554
+ }
3555
+ track(resources, name) {
3556
+ this.trackSlot(resources.get(name));
3557
+ }
3558
+ /** Innermost dependency sink, or `undefined` outside an evaluation. */
3559
+ dependencies() {
3560
+ const stack = this.dependencyStack;
3561
+ return stack.length === 0 ? void 0 : stack[stack.length - 1];
3037
3562
  }
3038
- publicMemory() {
3039
- const result = Object.create(null);
3040
- for (const declaration of this.entry.model.declarations) if (declaration.kind === "memory" && declaration.public) result[declaration.name] = bytesView(this.memory(declaration.name), () => {
3041
- this.board.assertAlive(this);
3042
- if (![
3043
- "idle",
3044
- "initialize",
3045
- "sync"
3046
- ].includes(this.board.phase)) throw this.board.error("INVALID_CALL_STATE", "Memory cannot be borrowed in this phase", this);
3047
- if (this.board.phase === "initialize" && this.board.current !== this) throw this.board.error("INVALID_CALL_STATE", "Another factory is initializing", this);
3048
- });
3049
- return Object.freeze(result);
3563
+ trackSlot(slot) {
3564
+ const dependencies = this.dependencies();
3565
+ if (dependencies) dependencies.set(slot, slot.version);
3050
3566
  }
3051
- send(name, value, input) {
3052
- const channel = this.channels.get(name);
3053
- if (!channel || channel.declaration.direction !== (input ? "input" : "output")) throw new TypeError(`Unknown channel ${name}`);
3054
- const captured = captureValue(channel.declaration.type, value, this.declarations);
3055
- if (channel.maxLength !== void 0 && captured.length > channel.maxLength) throw new RangeError("Message exceeds maxLength");
3056
- const queue = input ? channel.pending : channel.outgoing;
3057
- if (queue.length === channel.capacity) {
3058
- if (channel.overflow === "drop_new") return;
3059
- if (channel.overflow === "error") {
3060
- const error = this.board.error("CHANNEL_OVERFLOW", `Channel ${name} overflow`, this);
3061
- this.board.fault(error);
3062
- throw error;
3063
- }
3064
- queue.shift();
3065
- }
3066
- queue.push({
3067
- time: this.board.time,
3068
- value: captured
3567
+ /** Read-only evidence that a process frame bound per-instance resource handles. */
3568
+ bindingReport() {
3569
+ return Object.freeze({
3570
+ instance: this.id,
3571
+ handles: this.resourceHandles.size,
3572
+ bound: Object.freeze([...this.resourceHandles.keys()].sort()),
3573
+ processes: Object.freeze(this.processes.map((process) => Object.freeze({
3574
+ name: process.declaration.kind === "on" ? process.declaration.name : "start",
3575
+ bound: process.frame?.resources?.length ?? 0
3576
+ })))
3069
3577
  });
3070
3578
  }
3071
- captureCodeRegions(options) {
3072
- const primaryMemory = this.memories.get(options.code);
3073
- const primary = Object.freeze({
3074
- memory: options.code,
3075
- base: 0,
3076
- size: primaryMemory.length
3077
- });
3078
- const additional = [];
3079
- if (Object.hasOwn(options, "codeRegions")) {
3080
- if (!Array.isArray(options.codeRegions)) throw new TypeError("codeRegions must be an array");
3081
- for (const item of options.codeRegions) {
3082
- dataObject(item, [
3083
- "memory",
3084
- "base",
3085
- "size"
3086
- ]);
3087
- const memory = identity(item.memory);
3088
- const base = nonnegative(item.base, "code region base");
3089
- const size = nonnegative(item.size, "code region size");
3090
- if (size === 0) throw new RangeError("Code region size must be positive");
3091
- const length = this.memories.get(memory)?.length;
3092
- if (length === void 0) throw this.board.error("INVALID_BINDING", "Unknown code region memory", this);
3093
- if (size > length) throw this.board.error("INVALID_BINDING", "Code region exceeds memory", this);
3094
- if (base > Number.MAX_SAFE_INTEGER - size) throw this.board.error("INVALID_BINDING", "Code region range is not a safe integer", this);
3095
- const region = Object.freeze({
3096
- memory,
3097
- base,
3098
- size
3099
- });
3100
- for (const existing of [primary, ...additional]) if (region.base < existing.base + existing.size && existing.base < region.base + region.size) throw this.board.error("INVALID_BINDING", "Code regions overlap", this);
3101
- additional.push(region);
3102
- }
3103
- }
3104
- return {
3105
- all: Object.freeze([primary, ...additional]),
3106
- additional: Object.freeze(additional)
3107
- };
3579
+ dependenciesCurrent(dependencies) {
3580
+ if (!dependencies) return false;
3581
+ for (const [slot, version] of dependencies) if (slot.version !== version) return false;
3582
+ return true;
3108
3583
  }
3109
- capturePolling(items, region) {
3110
- const polling = /* @__PURE__ */ new Map();
3111
- if (!Array.isArray(items)) throw new TypeError("polling must be an array");
3112
- for (const item of items) {
3113
- dataObject(item, [
3114
- "pc",
3115
- "predicate",
3116
- "consume",
3117
- "wait"
3118
- ]);
3119
- const pc = finite(item.pc, "polling pc");
3120
- if (region !== void 0 && (pc < region.base || pc >= region.base + region.size)) throw this.board.error("INVALID_BINDING", "Polling pc is outside its code region", this);
3121
- const predicate = identity(item.predicate);
3122
- const declaration = this.declarations.get(predicate);
3123
- if (polling.has(pc) || declaration?.kind !== "function" || !declaration.pure || declaration.params.length || declaration.returns?.kind !== "bool") throw this.board.error("INVALID_BINDING", "Invalid polling declaration", this);
3124
- let consume;
3125
- if (Object.hasOwn(item, "consume")) {
3126
- consume = identity(item.consume);
3127
- const fn = this.declarations.get(consume);
3128
- if (fn?.kind !== "function" || fn.params.length !== 0 || fn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling consume function", this);
3129
- }
3130
- let wait;
3131
- if (Object.hasOwn(item, "wait")) {
3132
- dataObject(item.wait, ["delay", "advance"]);
3133
- const delay = identity(item.wait.delay);
3134
- const advance = identity(item.wait.advance);
3135
- const delayFn = this.declarations.get(delay);
3136
- const advanceFn = this.declarations.get(advance);
3137
- if (delayFn?.kind !== "function" || !delayFn.pure || delayFn.params.length !== 0 || delayFn.returns?.kind !== "number" || advanceFn?.kind !== "function" || advanceFn.params.length !== 1 || advanceFn.params[0].type.kind !== "number" || advanceFn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling wait functions", this);
3138
- wait = Object.freeze({
3139
- delay,
3140
- advance
3141
- });
3142
- }
3143
- polling.set(pc, Object.freeze({
3144
- predicate,
3145
- ...consume === void 0 ? {} : { consume },
3146
- ...wait === void 0 ? {} : { wait }
3147
- }));
3148
- }
3149
- return polling;
3584
+ /** Publishes a derived cache entry; the memo must follow every table write. */
3585
+ setDerived(name, entry) {
3586
+ if (this.derivedName === name && this.derivedEntry === entry) return;
3587
+ this.derived.set(name, entry);
3588
+ this.derivedName = name;
3589
+ this.derivedEntry = entry;
3150
3590
  }
3151
- captureMetadataDelays(value, region) {
3152
- if (!(value instanceof Map)) throw new TypeError("codeMetadata delays must be a Map");
3153
- const delays = /* @__PURE__ */ new Map();
3154
- for (const [key, item] of value) {
3155
- const pc = finite(key, "delay pc");
3156
- if (pc < region.base || pc >= region.base + region.size) throw this.board.error("INVALID_BINDING", "Delay pc is outside its code region", this);
3157
- dataObject(item, [
3158
- "counter",
3159
- "cycles",
3160
- "pending"
3161
- ]);
3162
- const counter = identity(item.counter);
3163
- const cycles = integer(item.cycles, "delay cycles");
3164
- if (cycles <= 0) throw new RangeError("Delay cycles must be positive");
3165
- let pending;
3166
- if (Object.hasOwn(item, "pending")) {
3167
- dataObject(item.pending, [
3168
- "state",
3169
- "period",
3170
- "active"
3171
- ]);
3172
- pending = Object.freeze({
3173
- state: identity(item.pending.state),
3174
- period: identity(item.pending.period),
3175
- active: identity(item.pending.active)
3176
- });
3177
- }
3178
- delays.set(pc, Object.freeze({
3179
- counter,
3180
- cycles,
3181
- ...pending ? { pending } : {}
3182
- }));
3591
+ evaluate(compute, target) {
3592
+ const dependencies = target ?? /* @__PURE__ */ new Map();
3593
+ this.dependencyStack.push(dependencies);
3594
+ try {
3595
+ return {
3596
+ value: compute(),
3597
+ dependencies
3598
+ };
3599
+ } finally {
3600
+ this.dependencyStack.pop();
3601
+ const parent = this.dependencies();
3602
+ if (parent) for (const [key, version] of dependencies) parent.set(key, version);
3183
3603
  }
3184
- return delays;
3185
- }
3186
- /** Validate and copy provider output; caller applies it atomically. */
3187
- captureCodeMetadata(region, value) {
3188
- dataObject(value, ["polling", "delays"]);
3189
- if (!Object.hasOwn(value, "polling") || !Object.hasOwn(value, "delays")) throw new TypeError("codeMetadata must contain polling and delays");
3190
- return {
3191
- polling: this.capturePolling(value.polling, region),
3192
- delays: this.captureMetadataDelays(value.delays, region)
3193
- };
3194
3604
  }
3195
- attach(options) {
3196
- this.assertCallAllowed();
3197
- if (this.board.phase !== "initialize" || this.board.current !== this) throw this.board.error("INVALID_CALL_STATE", "attachJit is initialization-only", this);
3198
- dataObject(options, [
3199
- "entry",
3200
- "code",
3201
- "codeRegions",
3202
- "codeMetadata",
3203
- "pc",
3204
- "functions",
3205
- "beforeInstruction",
3206
- "polling",
3207
- "delays",
3208
- "translate"
3209
- ]);
3210
- identity(options.entry);
3211
- identity(options.code);
3212
- identity(options.pc);
3213
- if (this.jits.some((jit) => jit.active && jit.options.entry === options.entry)) throw this.board.error("INVALID_BINDING", "Duplicate JIT entry", this);
3214
- if (!this.memories.has(options.code) || this.declarations.get(options.pc)?.kind !== "state" || this.declarations.get(options.pc).type.kind !== "number" || typeof options.translate !== "function") throw this.board.error("INVALID_BINDING", "Invalid JIT binding", this);
3215
- const codeRegions = this.captureCodeRegions(options);
3216
- if (Object.hasOwn(options, "codeMetadata")) {
3217
- if (typeof options.codeMetadata !== "function") throw this.board.error("INVALID_BINDING", "Invalid codeMetadata provider", this);
3218
- if (Object.hasOwn(options, "polling") || Object.hasOwn(options, "delays")) throw this.board.error("INVALID_BINDING", "codeMetadata is mutually exclusive with static polling/delays", this);
3219
- }
3220
- if (options.beforeInstruction !== void 0) {
3221
- dataObject(options.beforeInstruction, ["when", "call"]);
3222
- const condition = this.declarations.get(options.beforeInstruction.when), fn = this.declarations.get(options.beforeInstruction.call);
3223
- if (!condition || !["state", "derived"].includes(condition.kind) || !("type" in condition) || condition.type.kind !== "bool" || fn?.kind !== "function" || fn.params.length || fn.returns) throw this.board.error("INVALID_BINDING", "Invalid instruction hook", this);
3224
- } else if (Object.hasOwn(options, "beforeInstruction")) throw new TypeError("Invalid beforeInstruction");
3225
- const polling = Object.hasOwn(options, "polling") ? this.capturePolling(options.polling) : /* @__PURE__ */ new Map();
3226
- if (Object.hasOwn(options, "delays") && !(options.delays instanceof Map)) throw new TypeError("delays must be a Map");
3227
- const metadata = Object.hasOwn(options, "codeMetadata") ? {
3228
- regions: new Map(codeRegions.all.map((region) => [region, {
3229
- region,
3230
- appliedVersion: -1,
3231
- dirty: false,
3232
- pending: [],
3233
- polling: /* @__PURE__ */ new Map(),
3234
- delays: /* @__PURE__ */ new Map()
3235
- }])),
3236
- polling: /* @__PURE__ */ new Map(),
3237
- delays: /* @__PURE__ */ new Map()
3238
- } : void 0;
3239
- const base = this.entry.model;
3240
- const emit = options.functions;
3241
- if (Object.hasOwn(options, "functions") && typeof emit !== "function") throw new TypeError("functions must be a JIT function builder callback");
3242
- let model = base;
3243
- let functions;
3244
- let host = this.host;
3245
- if (emit) {
3246
- const declarations = emit(base);
3247
- acceptSync(declarations);
3248
- if (!Array.isArray(declarations)) throw new TypeError("Expected JIT function declarations");
3249
- model = bindJitFunctions(base, declarations);
3250
- const local = /* @__PURE__ */ new Map();
3251
- for (const declaration of model.declarations.slice(base.declarations.length)) if (declaration.kind === "function") local.set(declaration.name, declaration);
3252
- functions = local;
3253
- host = {
3254
- ...this.host,
3255
- call: (name, args) => {
3256
- const fn = local.get(name);
3257
- return fn ? body(fn.body)(host, args) : this.invoke(name, args);
3258
- }
3605
+ /** Leaf form of :func:`evaluate` for a source walk: no closure and no result wrapper. */
3606
+ evaluateSource(path, dependencies) {
3607
+ this.dependencyStack.push(dependencies);
3608
+ try {
3609
+ return snapshot(this.source(path));
3610
+ } finally {
3611
+ this.dependencyStack.pop();
3612
+ const parent = this.dependencies();
3613
+ if (parent) for (const [key, version] of dependencies) parent.set(key, version);
3614
+ }
3615
+ }
3616
+ observe(observation, path) {
3617
+ const read = this.staticObservations.get(observation);
3618
+ if (read) return read();
3619
+ const declaration = this.declarations.get(path[0]);
3620
+ if (declaration?.kind === "pin" || declaration?.kind === "state") {
3621
+ const resources = declaration.kind === "pin" ? this.sampleResources : this.stateResources;
3622
+ const pin = declaration.kind === "pin" ? this.pin(declaration.name) : void 0;
3623
+ if (pin && path[1] !== "sample") throw new TypeError(`Invalid source ${path.join(".")}`);
3624
+ const read = () => {
3625
+ let value = pin ? pin.sample : this.states.get(declaration.name);
3626
+ for (let index = pin ? 2 : 1; index < path.length; index++) value = value[path[index]];
3627
+ return pin ? value : snapshot(value);
3259
3628
  };
3629
+ const value = read();
3630
+ const slot = resources.get(declaration.name);
3631
+ if (!slot.subscribers.size) this.observerRevision++;
3632
+ slot.subscribers.add(observation);
3633
+ this.staticObservations.set(observation, read);
3634
+ return value;
3260
3635
  }
3261
- const jit = {
3262
- instance: this,
3263
- model,
3264
- host,
3265
- ...functions === void 0 ? {} : { functions },
3266
- options: Object.freeze({
3267
- ...options,
3268
- ...options.codeRegions === void 0 ? {} : { codeRegions: codeRegions.additional },
3269
- ...options.beforeInstruction ? { beforeInstruction: Object.freeze({ ...options.beforeInstruction }) } : {}
3270
- }),
3271
- codeRegions: codeRegions.all,
3272
- cache: /* @__PURE__ */ new Map(),
3273
- cacheMemories: /* @__PURE__ */ new Set(),
3274
- metadata,
3275
- polling,
3276
- delays: options.delays ?? /* @__PURE__ */ new Map(),
3277
- revision: 0,
3278
- directRevision: -1,
3279
- directObserverRevision: -1,
3280
- directStateGuards: /* @__PURE__ */ new Set(),
3281
- directMemoryGuards: /* @__PURE__ */ new Set(),
3282
- directHookReads: /* @__PURE__ */ new Set(),
3283
- directPrograms: /* @__PURE__ */ new Map(),
3284
- directProgramRevision: -1,
3285
- direct: void 0,
3286
- directSkip: void 0,
3287
- directMisses: /* @__PURE__ */ new Map(),
3288
- pollReads: void 0,
3289
- currentPc: void 0,
3290
- automaticPolling: false,
3291
- pollingWait: false,
3292
- pollingPeriod: 0,
3293
- pollingOrigin: 0,
3294
- pollingToken: 0,
3295
- dependencyDirty: true,
3296
- waiterSlots: void 0,
3297
- active: true,
3298
- stopped: false,
3299
- queued: false,
3300
- execution: void 0
3301
- };
3302
- this.jits.push(jit);
3303
- this.board.jits.push(jit);
3304
- for (const region of jit.codeRegions) this.codeMemories.add(region.memory);
3305
- const disposable = { dispose: () => {
3306
- if (!jit.active) return;
3307
- jit.active = false;
3308
- jit.execution = void 0;
3309
- delete jit.predicate;
3310
- jit.pollingToken++;
3311
- this.board.unparkWaiter(jit);
3312
- jit.cache.clear();
3313
- jit.cacheMemories.clear();
3314
- jit.directPrograms.clear();
3315
- jit.direct = void 0;
3316
- jit.directMisses.clear();
3317
- jit.pollReads = void 0;
3318
- } };
3319
- this.resources.push(disposable);
3320
- return disposable;
3636
+ const frames = this.observationFrames.get(observation);
3637
+ let target;
3638
+ if (frames === void 0) {
3639
+ target = /* @__PURE__ */ new Map();
3640
+ this.observationFrames.set(observation, {
3641
+ first: target,
3642
+ second: /* @__PURE__ */ new Map(),
3643
+ alternate: true
3644
+ });
3645
+ } else {
3646
+ target = frames.alternate ? frames.second : frames.first;
3647
+ frames.alternate = !frames.alternate;
3648
+ target.clear();
3649
+ }
3650
+ const observed = this.evaluateSource(path, target);
3651
+ const previous = this.observations.get(observation);
3652
+ if (previous === void 0 || previous.size !== target.size || !hasEvery(previous, target)) {
3653
+ if (previous) {
3654
+ for (const slot of previous.keys()) if (!target.has(slot) && slot.subscribers.delete(observation) && !slot.subscribers.size) this.observerRevision++;
3655
+ }
3656
+ for (const slot of target.keys()) if (!previous?.has(slot)) {
3657
+ if (!slot.subscribers.size) this.observerRevision++;
3658
+ slot.subscribers.add(observation);
3659
+ }
3660
+ }
3661
+ this.observations.set(observation, target);
3662
+ return observed;
3321
3663
  }
3322
- loadBytes(name, bytes, offset) {
3323
- this.assertCallAllowed();
3324
- if (this.board.phase !== "idle" && !(this.board.phase === "initialize" && this.board.current === this)) throw this.board.error("INVALID_CALL_STATE", "Code loading is not allowed in this phase", this);
3325
- if (typeof name !== "string" || !this.jits.some((jit) => jit.active && jit.codeRegions.some((region) => region.memory === name))) throw this.board.error("INVALID_BINDING", "Memory is not bound as code", this);
3326
- if (!(bytes instanceof Uint8Array)) throw new TypeError("Code must be Uint8Array");
3327
- const memory = this.memory(name), at = range(memory, offset, bytes.length);
3328
- if (bytes.length) {
3329
- memory.set(bytes.slice(), at);
3330
- this.memoryChanged(name, at, bytes.length);
3664
+ observationReader(observation, path) {
3665
+ return this.staticObservations.get(observation) ?? (() => this.observe(observation, path));
3666
+ }
3667
+ read(kind, name) {
3668
+ if (kind === "state") {
3669
+ this.trackSlot(this.stateSlot(name));
3670
+ return this.states.get(name);
3671
+ }
3672
+ if (kind === "derived") {
3673
+ let cached = name === this.derivedName ? this.derivedEntry : this.derived.get(name);
3674
+ const epoch = this.board.resourceEpoch;
3675
+ if (cached === void 0 || cached.epoch !== epoch && !this.dependenciesCurrent(cached.dependencies)) {
3676
+ const declaration = this.declarations.get(name);
3677
+ if (declaration?.kind !== "derived") throw new TypeError(`Unknown derived ${name}`);
3678
+ let buffer = this.derivedBuffers.get(name);
3679
+ if (buffer === void 0) {
3680
+ buffer = /* @__PURE__ */ new Map();
3681
+ this.derivedBuffers.set(name, buffer);
3682
+ } else buffer.clear();
3683
+ const evaluated = this.evaluate(() => computation(declaration.value, this.host), buffer);
3684
+ cached = {
3685
+ value: evaluated.value,
3686
+ dependencies: evaluated.dependencies,
3687
+ epoch: this.board.resourceEpoch
3688
+ };
3689
+ this.setDerived(name, cached);
3690
+ } else if (cached.epoch !== epoch) cached.epoch = epoch;
3691
+ const parent = this.dependencies();
3692
+ if (parent) for (const [key, version] of cached.dependencies) parent.set(key, version);
3693
+ return cached.value;
3694
+ }
3695
+ const values = kind === "property" ? this.props : this.constants;
3696
+ if (values.has(name)) return values.get(name);
3697
+ if (this.evaluating.has(name)) throw new TypeError(`Circular creation dependency ${name}`);
3698
+ this.evaluating.add(name);
3699
+ try {
3700
+ const declaration = this.declarations.get(name);
3701
+ if (declaration?.kind !== "property" && declaration?.kind !== "const") throw new TypeError(`Invalid creation reference ${name}`);
3702
+ let value;
3703
+ if (declaration.kind === "property") {
3704
+ if (Object.hasOwn(this.rawProps, name)) value = captureValue(declaration.type, this.rawProps[name], this.declarations, true);
3705
+ else if (declaration.default) value = captureValue(declaration.type, computation(declaration.default, this.host), this.declarations, true);
3706
+ else throw new TypeError(`Missing property ${name}`);
3707
+ } else value = computation(declaration.value, this.host);
3708
+ values.set(name, value);
3709
+ return value;
3710
+ } finally {
3711
+ this.evaluating.delete(name);
3331
3712
  }
3332
3713
  }
3333
- source(path) {
3334
- const declaration = this.declarations.get(path[0]);
3335
- let value;
3336
- let firstField = 1;
3337
- if (declaration?.kind === "pin") {
3338
- this.track(this.sampleResources, declaration.name);
3339
- if (path[1] !== "sample") throw new TypeError(`Invalid source ${path.join(".")}`);
3340
- value = this.pin(declaration.name).sample;
3341
- firstField = 2;
3342
- } else if (declaration?.kind === "state" || declaration?.kind === "derived") value = this.read(declaration.kind, declaration.name);
3343
- else throw new TypeError(`Invalid source ${path.join(".")}`);
3344
- for (let index = firstField; index < path.length; index++) value = value[path[index]];
3345
- return value;
3714
+ invoke(name, args = []) {
3715
+ const fn = this.declarations.get(name);
3716
+ if (fn?.kind !== "function") throw new TypeError(`Unknown function ${name}`);
3717
+ return body(fn.body)(this.host, args);
3346
3718
  }
3347
- };
3348
- //#endregion
3349
- //#region src/runtime/publish-gate.ts
3350
- var gates = /* @__PURE__ */ new WeakMap();
3351
- /** Attach the gate to the facade the board hands out; never exposed through the package entry. */
3352
- function registerPublishGate(bridge, gate) {
3353
- gates.set(bridge, gate);
3354
- }
3355
- function publishGate(bridge) {
3356
- const gate = gates.get(bridge);
3357
- if (gate === void 0) throw new TypeError("Topic bridge was not created by a board");
3358
- return gate;
3359
- }
3360
- //#endregion
3361
- //#region src/polling.ts
3362
- function isPollingInstruction(body, pc, pcName) {
3363
- const definitions = /* @__PURE__ */ new Map();
3364
- const redirects = [];
3365
- const visit = (region) => {
3366
- for (const operation of region.operations) {
3367
- if ("result" in operation) definitions.set(operation.result, operation);
3368
- switch (operation.kind) {
3369
- case "constant":
3370
- case "unary":
3371
- case "binary":
3372
- case "numeric":
3373
- case "field":
3374
- case "length":
3375
- case "index":
3376
- case "isNone":
3377
- case "nonNull":
3378
- case "optional":
3379
- case "local":
3380
- case "localRead":
3381
- case "localWrite":
3382
- case "memoryLength":
3383
- case "load8":
3384
- case "load16le":
3385
- case "load16be":
3386
- case "load32le":
3387
- case "load32be":
3388
- case "readSample":
3389
- case "yield": break;
3390
- case "read":
3391
- if (operation.resource === "derived" || operation.name === pcName) return false;
3392
- break;
3393
- case "if":
3394
- if (!visit(operation.yes) || operation.no && !visit(operation.no)) return false;
3395
- break;
3396
- case "select":
3397
- if (!visit(operation.yes.body) || !visit(operation.no.body)) return false;
3398
- break;
3399
- case "and":
3400
- case "or":
3401
- if (!visit(operation.right.body)) return false;
3402
- break;
3403
- case "match":
3404
- if (operation.arms.some((arm) => !visit(arm.body)) || operation.otherwise && !visit(operation.otherwise)) return false;
3405
- break;
3406
- case "redirect":
3407
- redirects.push(operation.target);
3408
- break;
3409
- default: return false;
3410
- }
3719
+ syncCall(name, args = []) {
3720
+ const step = this.invoke(name, args).next();
3721
+ if (!step.done) throw new TypeError("Unexpected suspension in synchronous function");
3722
+ return step.value;
3723
+ }
3724
+ pin(ref) {
3725
+ const pin = this.pins.get(String(ref));
3726
+ if (!pin) throw new TypeError(`Unknown pin ${String(ref)}`);
3727
+ return pin;
3728
+ }
3729
+ /** Shared by the generic host and direct JIT, which needs to know whether to publish. */
3730
+ writeIntent(ref, value) {
3731
+ const name = typeof ref === "string" ? ref : String(ref);
3732
+ const board = this.board;
3733
+ let entry = this.intentEntries.get(name);
3734
+ if (entry === void 0) {
3735
+ const pin = this.pin(name);
3736
+ entry = {
3737
+ pin,
3738
+ slot: board.electricalSlot(pin)
3739
+ };
3740
+ this.intentEntries.set(name, entry);
3411
3741
  }
3742
+ if (entry.pin.intent === value) return false;
3743
+ entry.pin.intent = value;
3744
+ board.markElectricalDirty(entry.slot);
3412
3745
  return true;
3413
- };
3414
- if (!visit(body)) return false;
3415
- return redirects.some((target) => {
3416
- const definition = definitions.get(target);
3417
- return definition?.kind !== "constant" || definition.constant.kind === "number" && definition.constant.value === pc;
3418
- });
3419
- }
3420
- //#endregion
3421
- //#region src/runtime/jit.ts
3422
- /** Large programs dispatch through shards; small ones stay on the faster monolithic form. */
3423
- var DIRECT_SHARD_SIZE = 32;
3424
- function syncJitCall(jit, name) {
3425
- const step = jit.host.call(name, []).next();
3426
- if (!step.done) throw new TypeError("Unexpected suspension in synchronous function");
3427
- return step.value;
3428
- }
3429
- /**
3430
- * Program size above which whole-program rebuilds are amortized instead of immediate.
3431
- *
3432
- * Translation only ever adds cache entries, so a compiled program stays valid for every PC it
3433
- * already contains; only a missing PC needs a rebuild. Rebuilding on every new block is
3434
- * quadratic, and that dominated warm-up on a real firmware image (411 blocks: 43 rebuilds and
3435
- * ~1.7 s before any simulated time). Small programs rebuild in milliseconds, so they keep the
3436
- * exact behaviour; only larger ones switch to a stride that grows with the program.
3437
- */
3438
- var DIRECT_REBUILD_LINEAR_LIMIT = 16;
3439
- /** Stride floor once a program exceeds `DIRECT_REBUILD_LINEAR_LIMIT`. */
3440
- var DIRECT_REBUILD_MIN_BLOCKS = 64;
3441
- /** A repeatedly visited translated PC can force a rebuild before the append-only stride. */
3442
- var DIRECT_REBUILD_PATIENCE = 4;
3443
- function directRebuildStride(compiled) {
3444
- return compiled < DIRECT_REBUILD_LINEAR_LIMIT ? 1 : Math.max(DIRECT_REBUILD_MIN_BLOCKS, compiled);
3445
- }
3446
- var barriers = /* @__PURE__ */ new WeakMap();
3447
- function directBarriers(jit) {
3448
- let entry = barriers.get(jit);
3449
- if (entry === void 0) {
3450
- entry = {
3451
- stateMask: /* @__PURE__ */ new Int32Array(0),
3452
- memoryMask: /* @__PURE__ */ new Int32Array(0)
3453
- };
3454
- barriers.set(jit, entry);
3455
- }
3456
- return entry;
3457
- }
3458
- function directStats(jit) {
3459
- const counted = jit;
3460
- return counted.directStats ??= {
3461
- directCompiles: 0,
3462
- directShards: 0,
3463
- directCalls: 0,
3464
- directFallbacks: 0,
3465
- directDeadlines: 0,
3466
- directStopped: 0
3467
- };
3468
- }
3469
- /** Region that supplies bytes for a logical PC; undefined means the service-PC fallback. */
3470
- function codeRegionFor(jit, pc) {
3471
- for (const region of jit.codeRegions) if (pc >= region.base && pc < region.base + region.size) return region;
3472
- }
3473
- /** Additional regions stay on the interpreter; only the primary memory feeds direct programs. */
3474
- function directCodeInstruction(jit, instruction) {
3475
- const region = instruction.codeRegion;
3476
- return region === void 0 || region.memory === jit.options.code;
3477
- }
3478
- function effectivePolling(jit) {
3479
- return jit.metadata?.polling ?? jit.polling;
3480
- }
3481
- function effectiveDelays(jit) {
3482
- return jit.metadata?.delays ?? jit.delays;
3483
- }
3484
- /** Aliases of the primary memory must refresh together before a direct program is built. */
3485
- function primaryCodeRegions(jit) {
3486
- return jit.codeRegions.filter((region) => region.memory === jit.options.code);
3487
- }
3488
- /**
3489
- * Lazily (re)build code-derived metadata for the requested regions. Provider calls never
3490
- * happen from attach/store; this runs inside the translate phase immediately before the
3491
- * polling/direct/translate decision that needs it.
3492
- */
3493
- function ensureMetadata(board, jit, regions) {
3494
- const metadata = jit.metadata;
3495
- const provider = jit.options.codeMetadata;
3496
- if (metadata === void 0 || provider === void 0) return;
3497
- const needed = [];
3498
- const seen = /* @__PURE__ */ new Set();
3499
- for (const region of regions) {
3500
- const state = metadata.regions.get(region);
3501
- if (state === void 0 || seen.has(state)) continue;
3502
- seen.add(state);
3503
- const version = jit.instance.codeVersion(region.memory);
3504
- if (state.appliedVersion === version && state.pending.length === 0 && !state.dirty) continue;
3505
- const changes = state.appliedVersion === -1 ? [Object.freeze({
3506
- memory: region.memory,
3507
- offset: 0,
3508
- length: region.size
3509
- })] : state.pending.map((change) => Object.freeze({ ...change }));
3510
- needed.push({
3511
- state,
3512
- changes,
3513
- version
3514
- });
3515
3746
  }
3516
- if (needed.length === 0) return;
3517
- const prior = board.phase;
3518
- board.phase = "translate";
3519
- const prepared = [];
3520
- try {
3521
- for (const item of needed) {
3522
- const { region } = item.state;
3523
- const memory = jit.instance.memory(region.memory);
3524
- const bytes = region.size >= memory.length ? memory : memory.subarray(0, region.size);
3525
- let valid = true;
3526
- try {
3527
- const code = bytesView(bytes, () => {
3528
- if (!valid) throw board.error("OBJECT_DISPOSED", "Metadata view expired", jit.instance);
3529
- });
3530
- const view = Object.freeze({
3531
- memory: region.memory,
3532
- base: region.base,
3533
- size: region.size,
3534
- codeVersion: item.version,
3535
- code
3536
- });
3537
- const result = provider(Object.freeze({
3538
- region: view,
3539
- changes: Object.freeze(item.changes.slice())
3540
- }));
3541
- acceptSync(result);
3542
- const captured = jit.instance.captureCodeMetadata(region, result);
3543
- prepared.push({
3544
- state: item.state,
3545
- version: item.version,
3546
- polling: captured.polling,
3547
- delays: captured.delays
3548
- });
3549
- } finally {
3550
- valid = false;
3551
- }
3747
+ /**
3748
+ * One frozen, reusable intent value per (pin, resistance); intents are immutable. The
3749
+ * outer map is keyed by pin name and the inner one by resistance, so the hot path builds
3750
+ * no key string. Bounds: at most 64 names, and at most 8 resistances per name; a full
3751
+ * level is cleared wholesale (no least-recently-used eviction), so identity is only
3752
+ * reused while both levels stay under their limits.
3753
+ */
3754
+ resistorIntent(pin, resistance) {
3755
+ const name = typeof pin === "string" ? pin : String(pin);
3756
+ let byResistance = this.resistorIntents.get(name);
3757
+ if (byResistance === void 0) {
3758
+ if (this.resistorIntents.size >= 64) this.resistorIntents.clear();
3759
+ byResistance = /* @__PURE__ */ new Map();
3760
+ this.resistorIntents.set(name, byResistance);
3552
3761
  }
3553
- let primary = false;
3554
- for (const item of prepared) {
3555
- item.state.appliedVersion = item.version;
3556
- item.state.dirty = false;
3557
- item.state.pending.length = 0;
3558
- item.state.polling.clear();
3559
- for (const [pc, binding] of item.polling) item.state.polling.set(pc, binding);
3560
- item.state.delays.clear();
3561
- for (const [pc, delay] of item.delays) item.state.delays.set(pc, delay);
3562
- if (item.state.region.memory === jit.options.code) primary = true;
3762
+ let intent = byResistance.get(resistance);
3763
+ if (intent === void 0) {
3764
+ if (byResistance.size >= 8) byResistance.clear();
3765
+ intent = Object.freeze([Object.freeze({
3766
+ to: this.pin(name),
3767
+ resistance
3768
+ })]);
3769
+ byResistance.set(resistance, intent);
3563
3770
  }
3564
- metadata.polling.clear();
3565
- metadata.delays.clear();
3566
- for (const state of metadata.regions.values()) {
3567
- for (const [pc, binding] of state.polling) metadata.polling.set(pc, binding);
3568
- for (const [pc, delay] of state.delays) metadata.delays.set(pc, delay);
3771
+ return intent;
3772
+ }
3773
+ readSample(ref) {
3774
+ const name = typeof ref === "string" ? ref : String(ref);
3775
+ let entry = this.sampleEntries.get(name);
3776
+ if (entry === void 0) {
3777
+ const pin = this.pin(name);
3778
+ entry = {
3779
+ pin,
3780
+ slot: this.sampleResources.get(pin.name)
3781
+ };
3782
+ if (this.sampleEntries.size >= 512) this.sampleEntries.clear();
3783
+ this.sampleEntries.set(name, entry);
3784
+ }
3785
+ const dependencies = this.dependencies();
3786
+ if (dependencies) dependencies.set(entry.slot, entry.slot.version);
3787
+ return entry.pin.sample;
3788
+ }
3789
+ memory(ref) {
3790
+ const bytes = this.memories.get(String(ref));
3791
+ if (!bytes) throw new TypeError(`Unknown memory ${String(ref)}`);
3792
+ return bytes;
3793
+ }
3794
+ /** Instance-owned numeric bank, mirrored by every non-direct state write. */
3795
+ directStateBank() {
3796
+ if (this.directBank === void 0) {
3797
+ const stateNames = [...this.states.keys()].filter((name) => {
3798
+ const declaration = this.declarations.get(name);
3799
+ return declaration.type.kind === "number" || declaration.type.kind === "bool";
3800
+ });
3801
+ const frozenNames = Object.freeze(stateNames);
3802
+ const stateValues = stateNames.map((name) => this.states.get(name));
3803
+ this.states.bindDirectBank(frozenNames, stateValues);
3804
+ this.directBank = {
3805
+ stateNames: frozenNames,
3806
+ stateSlots: Object.freeze(stateNames.map((name) => this.stateResources.get(name))),
3807
+ states: new Map(stateNames.map((name, index) => [name, index])),
3808
+ stateValues
3809
+ };
3569
3810
  }
3570
- if (primary) {
3571
- jit.directPrograms.clear();
3572
- jit.directProgramRevision = -1;
3573
- jit.directSkip = void 0;
3574
- if (!jit.direct?.frame.resume) {
3575
- jit.direct = void 0;
3576
- jit.directRevision = -1;
3811
+ return this.directBank;
3812
+ }
3813
+ /** Direct scalar writes are already in the numeric bank. Commit the mirror and version. */
3814
+ commitDirectStates(dirty) {
3815
+ const { stateSlots } = this.directBank;
3816
+ const states = this.states;
3817
+ const board = this.board;
3818
+ let wrote = false;
3819
+ for (let word = 0; word < dirty.length; word++) {
3820
+ let bits = dirty[word];
3821
+ if (bits === 0) continue;
3822
+ dirty[word] = 0;
3823
+ wrote = true;
3824
+ states.markDirectDirty(word, bits);
3825
+ const base = word << 5;
3826
+ while (bits !== 0) {
3827
+ const slot = stateSlots[base + 31 - Math.clz32(bits & -bits)];
3828
+ if (slot.subscribers.size === 0) {
3829
+ slot.version++;
3830
+ board.noteResourceVersion(slot);
3831
+ } else board.invalidate(slot);
3832
+ bits &= bits - 1;
3577
3833
  }
3578
3834
  }
3579
- } catch (cause) {
3580
- throw board.wrap(cause, "JIT_FAILED", "translate", jit.instance);
3581
- } finally {
3582
- board.phase = prior;
3835
+ return wrote;
3583
3836
  }
3584
- }
3585
- function ensureMetadataForPc(board, jit, pc) {
3586
- if (jit.metadata === void 0) return;
3587
- const region = codeRegionFor(jit, pc) ?? jit.codeRegions[0];
3588
- const needed = [region];
3589
- if (board.execution === "throughput" && board.jits.length === 1 && region.memory === jit.options.code) needed.push(...primaryCodeRegions(jit));
3590
- ensureMetadata(board, jit, needed);
3591
- }
3592
- /** Publish the current guard sets into the masks the compiled blocks test at entry. */
3593
- function syncDirectBarriers(jit) {
3594
- const entry = directBarriers(jit);
3595
- const { stateIndex, memoryIndex } = entry;
3596
- if (stateIndex === void 0 || memoryIndex === void 0) return;
3597
- const fill = (mask, index, guards) => {
3598
- mask.fill(0);
3599
- for (const name of guards) {
3600
- const slot = index.get(name);
3601
- if (slot === void 0) continue;
3602
- mask[slot >>> 5] = (mask[slot >>> 5] ?? 0) | 1 << (slot & 31);
3837
+ writeState(name, value, slot) {
3838
+ const captured = snapshot(value);
3839
+ this.states.set(name, captured);
3840
+ const index = this.directBank?.states.get(name);
3841
+ if (index !== void 0) this.directBank.stateValues[index] = captured;
3842
+ this.board.invalidate(slot);
3843
+ }
3844
+ stateSlot(name) {
3845
+ let slot = this.stateSlots.get(name);
3846
+ if (slot === void 0) {
3847
+ if (!this.states.has(name)) throw new TypeError(`Unknown state ${name}`);
3848
+ slot = this.stateResources.get(name);
3849
+ this.stateSlots.set(name, slot);
3603
3850
  }
3604
- };
3605
- fill(entry.stateMask, stateIndex, jit.directStateGuards);
3606
- fill(entry.memoryMask, memoryIndex, jit.directMemoryGuards);
3607
- }
3608
- function refreshDirectGuards(jit, hookReads) {
3609
- let changed = false;
3610
- const instance = jit.instance;
3611
- const hookCount = jit.directHookReads.size;
3612
- if (hookReads) for (const slot of hookReads.keys()) jit.directHookReads.add(slot);
3613
- if (jit.directObserverRevision === instance.observerRevision && hookCount === jit.directHookReads.size) return;
3614
- jit.directObserverRevision = instance.observerRevision;
3615
- for (const [name, slot] of instance.stateResources) {
3616
- const blocked = slot.subscribers.size > 0 || jit.directHookReads.has(slot);
3617
- if (jit.directStateGuards.has(name) === blocked) continue;
3618
- if (blocked) jit.directStateGuards.add(name);
3619
- else jit.directStateGuards.delete(name);
3620
- changed = true;
3851
+ return slot;
3621
3852
  }
3622
- for (const [name, slot] of instance.memoryResources) {
3623
- const blocked = slot.subscribers.size > 0 || jit.directHookReads.has(slot) || name === jit.options.code;
3624
- if (jit.directMemoryGuards.has(name) === blocked) continue;
3625
- if (blocked) jit.directMemoryGuards.add(name);
3626
- else jit.directMemoryGuards.delete(name);
3627
- changed = true;
3853
+ memoryPlan(ref) {
3854
+ const name = typeof ref === "string" ? ref : String(ref);
3855
+ let plan = this.memoryPlans.get(name);
3856
+ if (plan === void 0) {
3857
+ const bytes = this.memories.get(name);
3858
+ if (!bytes) throw new TypeError(`Unknown memory ${name}`);
3859
+ plan = {
3860
+ name,
3861
+ bytes,
3862
+ view: this.memoryViews.get(name),
3863
+ slot: this.memoryResources.get(name)
3864
+ };
3865
+ this.memoryPlans.set(name, plan);
3866
+ }
3867
+ return plan;
3628
3868
  }
3629
- if (changed) {
3630
- syncDirectBarriers(jit);
3631
- jit.directSkip = void 0;
3869
+ codeVersion(name) {
3870
+ return this.codeVersions.get(name) ?? 0;
3632
3871
  }
3633
- }
3634
- /**
3635
- * Direct programs advance `frame.time` between host calls, while the board only adopts the
3636
- * final time after `run` returns. Publish the current frame time before every host effect so
3637
- * channel publications, electrical intents and diagnostics carry the instruction's time.
3638
- */
3639
- function directHost(board, instance, frame) {
3640
- const publishTime = () => {
3641
- board.time = frame.time;
3642
- };
3643
- return {
3644
- send: (name, value) => {
3645
- publishTime();
3646
- instance.host.send(name, value);
3647
- },
3648
- sample: (pin) => {
3649
- publishTime();
3650
- return instance.host.sample(pin);
3651
- },
3652
- intent: (pin, value) => {
3653
- publishTime();
3654
- if (instance.writeIntent(pin, value)) frame.publishPending = true;
3655
- },
3656
- resistor: (pin, resistance) => {
3657
- publishTime();
3658
- return instance.host.resistor(pin, resistance);
3659
- },
3660
- notify: (name) => {
3661
- publishTime();
3662
- instance.host.notify(name);
3663
- },
3664
- now: () => {
3665
- publishTime();
3666
- return instance.host.now();
3667
- },
3668
- random: () => {
3669
- publishTime();
3670
- return instance.host.random();
3671
- },
3672
- assert: (condition, message) => {
3673
- publishTime();
3674
- instance.host.assert(condition, message);
3872
+ intersectsCodeRegion(region, offset, size) {
3873
+ if (offset === void 0 || size === void 0) return true;
3874
+ return offset < region.size && offset + size > 0;
3875
+ }
3876
+ hasCodeRegion(name, offset, size) {
3877
+ for (const jit of this.jits) {
3878
+ if (!jit.active) continue;
3879
+ for (const region of jit.codeRegions) if (region.memory === name && this.intersectsCodeRegion(region, offset, size)) return true;
3675
3880
  }
3676
- };
3677
- }
3678
- /** Build the numeric bank layout once; rebuilds then only need the cached instruction bodies. */
3679
- function directLayout(jit) {
3680
- if (jit.directLayout !== void 0) return jit.directLayout;
3681
- const instance = jit.instance;
3682
- const bank = instance.directStateBank();
3683
- const memoryNames = [...instance.memories.keys()];
3684
- const memories = new Map(memoryNames.map((name, index) => [name, index]));
3685
- const memoryBanks = memoryNames.map((name) => instance.memory(name));
3686
- const memoryViews = memoryBanks.map((memory) => new DataView(memory.buffer, memory.byteOffset, memory.byteLength));
3687
- const pinNames = [...instance.pins.keys()];
3688
- const pins = new Map(pinNames.map((name, index) => [name, index]));
3689
- const pinObjects = pinNames.map((name) => instance.pin(name));
3690
- const pinElectricalSlots = Int32Array.from(pinObjects, (pin) => instance.board.electricalSlot(pin));
3691
- jit.directLayout = {
3692
- ...bank,
3693
- memoryNames: Object.freeze(memoryNames),
3694
- memories,
3695
- memoryBanks: Object.freeze(memoryBanks),
3696
- memoryViews: Object.freeze(memoryViews),
3697
- pinNames: Object.freeze(pinNames),
3698
- pins,
3699
- pinObjects: Object.freeze(pinObjects),
3700
- pinElectricalSlots
3701
- };
3702
- return jit.directLayout;
3703
- }
3704
- function flushDirect(board, instance, layout, frame) {
3705
- board.time = frame.time;
3706
- frame.publishPending = false;
3707
- let wrote = instance.commitDirectStates(frame.stateDirty);
3708
- for (let word = 0; word < frame.memoryDirty.length; word++) {
3709
- let bits = frame.memoryDirty[word];
3710
- if (bits === 0) continue;
3711
- frame.memoryDirty[word] = 0;
3712
- while (bits !== 0) {
3713
- const slot = word * 32 + 31 - Math.clz32(bits & -bits);
3714
- instance.memoryChanged(layout.memoryNames[slot]);
3715
- bits &= bits - 1;
3716
- wrote = true;
3881
+ return false;
3882
+ }
3883
+ addMetadataChange(state, change) {
3884
+ const pending = state.pending;
3885
+ let end = change.offset + change.length;
3886
+ let start = change.offset;
3887
+ for (let index = 0; index < pending.length;) {
3888
+ const current = pending[index];
3889
+ const currentEnd = current.offset + current.length;
3890
+ if (change.offset <= currentEnd && current.offset <= end) {
3891
+ start = Math.min(start, current.offset);
3892
+ end = Math.max(end, currentEnd);
3893
+ pending.splice(index, 1);
3894
+ } else index++;
3717
3895
  }
3896
+ pending.push({
3897
+ memory: change.memory,
3898
+ offset: start,
3899
+ length: end - start
3900
+ });
3718
3901
  }
3719
- return wrote;
3720
- }
3721
- function createDirectFrame(board, jit, layout, program, barrier) {
3722
- const instance = jit.instance;
3723
- const { pinObjects, pinNames, pinElectricalSlots } = layout;
3724
- const frame = {
3725
- states: layout.stateValues,
3726
- memories: [...layout.memoryBanks],
3727
- memoryViews: layout.memoryViews,
3728
- pins: pinObjects,
3729
- resistors: [],
3730
- locals: new Array(program.localCount),
3731
- stateDirty: new Int32Array(Math.ceil(layout.stateNames.length / 32)),
3732
- memoryDirty: new Int32Array(Math.ceil(layout.memoryNames.length / 32)),
3733
- time: board.time,
3734
- due: board.time,
3735
- resume: 0,
3736
- stopAfterInstruction: false,
3737
- boundarySettled: false
3738
- };
3739
- frame.writePinIntent = (pinIndex, value) => {
3740
- if (!Object.hasOwn(instance, "writeIntent")) {
3741
- const pin = pinObjects[pinIndex];
3742
- if (pin.intent === value) return;
3743
- pin.intent = value;
3744
- instance.board.markElectricalDirty(pinElectricalSlots[pinIndex]);
3745
- frame.publishPending = true;
3746
- return;
3902
+ markMetadataChanged(jit, name, offset, size) {
3903
+ if (!jit.metadata) return;
3904
+ for (const state of jit.metadata.regions.values()) {
3905
+ const region = state.region;
3906
+ if (region.memory !== name) continue;
3907
+ if (state.appliedVersion === -1) continue;
3908
+ if (name === jit.options.code) state.dirty = true;
3909
+ if (!this.intersectsCodeRegion(region, offset, size)) continue;
3910
+ state.dirty = true;
3911
+ const start = offset === void 0 ? 0 : Math.max(0, offset);
3912
+ const end = offset === void 0 ? region.size : Math.min(region.size, offset + (size ?? 0));
3913
+ if (end > start) this.addMetadataChange(state, {
3914
+ memory: name,
3915
+ offset: start,
3916
+ length: end - start
3917
+ });
3747
3918
  }
3748
- board.time = frame.time;
3749
- if (instance.writeIntent(pinNames[pinIndex], value)) frame.publishPending = true;
3750
- };
3751
- frame.host = directHost(board, instance, frame);
3752
- if (jit.metadata === void 0) {
3753
- frame.publishCheckpoint = () => {
3754
- flushDirect(board, instance, layout, frame);
3755
- board.boundary();
3756
- if (jit.directProgramRevision === -1 || !board.canContinueDirect(jit, frame.due)) {
3757
- frame.boundarySettled = true;
3758
- return false;
3919
+ }
3920
+ memoryChanged(name, offset, size) {
3921
+ this.memoryChangedSlot(name, this.memoryPlan(name).slot, offset, size);
3922
+ }
3923
+ memoryChangedPlan(plan, offset, size) {
3924
+ this.memoryChangedSlot(plan.name, plan.slot, offset, size);
3925
+ }
3926
+ memoryChangedSlot(name, slot, offset, size) {
3927
+ this.board.invalidate(slot);
3928
+ if (!this.codeMemories.has(name)) return;
3929
+ if (this.hasCodeRegion(name, offset, size)) this.codeVersions.set(name, this.codeVersion(name) + 1);
3930
+ for (const jit of this.jits) {
3931
+ let affected = false;
3932
+ for (const region of jit.codeRegions) if (region.memory === name && this.intersectsCodeRegion(region, offset, size)) {
3933
+ affected = true;
3934
+ break;
3759
3935
  }
3760
- board.current = instance;
3761
- return true;
3762
- };
3763
- if (jit.options.beforeInstruction === void 0) {
3764
- const pcIndex = layout.states.get(jit.options.pc);
3765
- frame.finishCheckpoint = (deadline, emptySuffix) => {
3766
- if (emptySuffix) board.time = frame.time;
3767
- else flushDirect(board, instance, layout, frame);
3768
- board.boundary();
3769
- const direct = jit.direct;
3770
- const nextPc = frame.states[pcIndex];
3771
- if (jit.directProgramRevision === -1 || direct?.frame !== frame || !direct.pcs.has(nextPc) || jit.directSkip === nextPc || jit.directRevision !== jit.revision && jit.revision - jit.directRevision >= directRebuildStride(direct.pcs.size) || frame.time >= deadline || board.events.time < deadline || !emptySuffix && !board.canContinueDirect(jit, frame.time)) {
3772
- frame.boundarySettled = true;
3773
- return false;
3774
- }
3775
- if (jit.directObserverRevision !== instance.observerRevision) refreshDirectGuards(jit);
3776
- frame.stopAfterInstruction = false;
3777
- board.current = instance;
3778
- return true;
3779
- };
3936
+ if (!affected) continue;
3937
+ this.markMetadataChanged(jit, name, offset, size);
3938
+ if (jit.options.code === name) {
3939
+ jit.cache.clear();
3940
+ jit.cacheMemories.clear();
3941
+ jit.revision++;
3942
+ invalidateDirect(jit, true);
3943
+ } else if (jit.cacheMemories.has(name)) {
3944
+ for (const [pc, instruction] of jit.cache) if (instruction.codeRegion?.memory === name) jit.cache.delete(pc);
3945
+ jit.cacheMemories.delete(name);
3946
+ if (jit.directMemories.has(name)) invalidateDirect(jit, false);
3947
+ jit.directMemories.delete(name);
3948
+ }
3949
+ }
3950
+ }
3951
+ /**
3952
+ * Handles for the fixed names a resumable process body uses. They live on the instance,
3953
+ * so a shared program text binds each instance (and each process frame) separately, and
3954
+ * every read still resolves the current sample or state value.
3955
+ */
3956
+ bindResources(specs) {
3957
+ const handles = new Array(specs.length);
3958
+ for (let index = 0; index < specs.length; index++) {
3959
+ const spec = specs[index];
3960
+ const key = `${spec[0]}\0${spec[1]}`;
3961
+ let handle = this.resourceHandles.get(key);
3962
+ if (handle === void 0) {
3963
+ handle = this.resourceHandle(spec[0], spec[1]);
3964
+ this.resourceHandles.set(key, handle);
3965
+ }
3966
+ handles[index] = handle;
3780
3967
  }
3968
+ return handles;
3781
3969
  }
3782
- frame.blockedStates = barrier.stateMask;
3783
- frame.blockedMemories = barrier.memoryMask;
3784
- return frame;
3785
- }
3786
- function runDirect(board, jit, hookReads) {
3787
- const instance = jit.instance;
3788
- let pending = Boolean(jit.direct?.frame.resume);
3789
- if (!pending) {
3790
- const pc = finite(instance.states.get(jit.options.pc), "pc");
3791
- const region = codeRegionFor(jit, pc);
3792
- if (board.execution !== "throughput" || board.jits.length !== 1 || region !== void 0 && region.memory !== jit.options.code || effectivePolling(jit).has(pc) || jit.cache.get(pc)?.polling) return false;
3793
- refreshDirectGuards(jit, hookReads);
3794
- if (jit.directSkip === pc) return false;
3795
- if (jit.directRevision !== jit.revision) {
3796
- const compiled = jit.direct?.pcs.size ?? 0;
3797
- const stale = jit.revision - jit.directRevision;
3798
- const stride = directRebuildStride(compiled);
3799
- const covered = jit.direct?.pcs.has(pc) === true;
3800
- const misses = covered ? 0 : jit.directMisses.get(pc) ?? 0;
3801
- if (!(jit.direct === void 0 || stale >= stride || misses >= DIRECT_REBUILD_PATIENCE)) {
3802
- if (!covered) {
3803
- const stats = directStats(jit);
3804
- stats.directCalls++;
3805
- stats.directFallbacks++;
3806
- if (jit.cache.has(pc)) jit.directMisses.set(pc, misses + 1);
3807
- return false;
3808
- }
3809
- } else {
3810
- if (jit.directProgramRevision !== jit.revision) {
3811
- if (jit.directProgramRevision === -1 && jit.directCache !== void 0) compileDirectJit.clearCache(jit.directCache);
3812
- jit.directPrograms.clear();
3813
- jit.directProgramRevision = jit.revision;
3970
+ /**
3971
+ * Each method repeats the generic host operation exactly: dependency slots are still
3972
+ * recorded, state writes still snapshot, and memory stores still run the code-memory
3973
+ * invalidation that clears JIT caches. Every resource a declaration already provides is
3974
+ * resolved here, at bind time; a name that does not exist yet keeps resolving lazily so
3975
+ * it still fails at its first real use, not while binding.
3976
+ */
3977
+ resourceHandle(kind, name) {
3978
+ if (kind === "pin") {
3979
+ let pin = this.pins.get(name);
3980
+ let slot = pin === void 0 ? -1 : this.board.electricalSlot(pin);
3981
+ let sample = pin === void 0 ? void 0 : this.sampleResources.get(name);
3982
+ let lastResistance;
3983
+ let lastIntent;
3984
+ const resolve = () => {
3985
+ if (pin === void 0) {
3986
+ pin = this.pin(name);
3987
+ slot = this.board.electricalSlot(pin);
3988
+ sample = this.sampleResources.get(name);
3814
3989
  }
3815
- const layout = directLayout(jit);
3816
- const instructions = [...jit.cache.values()].filter((instruction) => !instruction.polling && !effectivePolling(jit).has(instruction.pc) && directCodeInstruction(jit, instruction));
3817
- /** Declared busy-wait heads fold their remaining rounds inside the emitted body. */
3818
- const delayLoops = /* @__PURE__ */ new Map();
3819
- for (const [headPc, delay] of effectiveDelays(jit)) {
3820
- const counter = layout.states.get(delay.counter);
3821
- if (counter === void 0) continue;
3822
- const pending = delay.pending === void 0 ? void 0 : {
3823
- state: layout.states.get(delay.pending.state),
3824
- period: layout.states.get(delay.pending.period),
3825
- active: layout.states.get(delay.pending.active)
3826
- };
3827
- delayLoops.set(headPc, pending !== void 0 && pending.state !== void 0 && pending.period !== void 0 && pending.active !== void 0 ? {
3828
- counter,
3829
- cycles: delay.cycles,
3830
- pending
3831
- } : {
3832
- counter,
3833
- cycles: delay.cycles
3834
- });
3990
+ return pin;
3991
+ };
3992
+ return Object.freeze({
3993
+ sample: () => {
3994
+ const current = resolve();
3995
+ const dependencies = this.dependencies();
3996
+ if (dependencies) dependencies.set(sample, sample.version);
3997
+ return current.sample;
3998
+ },
3999
+ intent: (value) => {
4000
+ const current = resolve();
4001
+ if (current.intent === value) return;
4002
+ current.intent = value;
4003
+ this.board.markElectricalDirty(slot);
4004
+ },
4005
+ resistor: (resistance) => {
4006
+ if (lastIntent !== void 0 && resistance === lastResistance) return lastIntent;
4007
+ const r = electricalNumber(resistance);
4008
+ if (r < .001 || r > 1e9) throw new ElectricalParameterError("Resistance outside [0.001, 1e9]");
4009
+ const intent = this.resistorIntent(name, r);
4010
+ lastResistance = resistance;
4011
+ lastIntent = intent;
4012
+ return intent;
3835
4013
  }
3836
- const key = JSON.stringify([...delayLoops].sort(([left], [right]) => left - right));
3837
- const cached = jit.directPrograms.get(key);
3838
- if (cached) {
3839
- jit.direct = cached;
3840
- jit.directRevision = jit.revision;
3841
- } else {
3842
- const { states, memories, pins } = layout;
3843
- const cache = jit.directCache ??= compileDirectJit.createCache();
3844
- const program = compileDirectJit(instructions, {
3845
- states,
3846
- memories,
3847
- pins,
3848
- pc: {
3849
- name: jit.options.pc,
3850
- index: states.get(jit.options.pc)
3851
- },
3852
- host: true,
3853
- ...jit.functions === void 0 ? {} : { functions: jit.functions },
3854
- split: true,
3855
- shardSize: DIRECT_SHARD_SIZE,
3856
- delayLoops
3857
- }, cache);
3858
- jit.directRevision = jit.revision;
3859
- jit.directMisses.clear();
3860
- const stats = directStats(jit);
3861
- stats.directShards = program?.shards ?? 0;
3862
- if (program) stats.directCompiles++;
3863
- const barrier = directBarriers(jit);
3864
- barrier.stateIndex = states;
3865
- barrier.memoryIndex = memories;
3866
- const stateMaskWords = Math.ceil(layout.stateNames.length / 32);
3867
- const memoryMaskWords = Math.ceil(layout.memoryNames.length / 32);
3868
- if (barrier.stateMask.length !== stateMaskWords) barrier.stateMask = new Int32Array(stateMaskWords);
3869
- if (barrier.memoryMask.length !== memoryMaskWords) barrier.memoryMask = new Int32Array(memoryMaskWords);
3870
- syncDirectBarriers(jit);
3871
- jit.direct = program ? {
3872
- program,
3873
- pcs: new Set(program.pcs),
3874
- frame: createDirectFrame(board, jit, layout, program, barrier)
3875
- } : void 0;
3876
- if (!jit.direct) jit.directPrograms.delete(key);
3877
- else jit.directPrograms.set(key, jit.direct);
4014
+ });
4015
+ }
4016
+ if (kind === "state") {
4017
+ let slot = this.states.has(name) ? this.stateResources.get(name) : void 0;
4018
+ let banked = slot === void 0 ? -1 : this.directBank?.states.get(name) ?? -2;
4019
+ const resolve = () => slot ??= this.stateSlot(name);
4020
+ const states = this.states;
4021
+ return Object.freeze({
4022
+ read: () => {
4023
+ const current = resolve();
4024
+ const dependencies = this.dependencies();
4025
+ if (dependencies) dependencies.set(current, current.version);
4026
+ if (banked === -2) banked = this.directBank?.states.get(name) ?? -1;
4027
+ return banked < 0 ? states.get(name) : this.directBank.stateValues[banked];
4028
+ },
4029
+ write: (value) => {
4030
+ const current = resolve();
4031
+ this.writeState(name, value, current);
3878
4032
  }
3879
- }
4033
+ });
3880
4034
  }
3881
- if (!jit.direct) return false;
4035
+ let plan = this.memories.has(name) ? this.memoryPlan(name) : void 0;
4036
+ const resolve = () => plan ??= this.memoryPlan(name);
4037
+ const read = (size, little, offset) => {
4038
+ const current = resolve();
4039
+ const at = range(current.bytes, offset, size);
4040
+ const dependencies = this.dependencies();
4041
+ if (dependencies) dependencies.set(current.slot, current.slot.version);
4042
+ return size === 1 ? current.bytes[at] : size === 2 ? current.view.getUint16(at, little) : current.view.getUint32(at, little);
4043
+ };
4044
+ const write = (size, little, offset, value) => {
4045
+ const current = resolve();
4046
+ const at = range(current.bytes, offset, size);
4047
+ const n = integer(value, "stored value");
4048
+ if (size === 1) current.bytes[at] = n;
4049
+ else if (size === 2) current.view.setUint16(at, n, little);
4050
+ else current.view.setUint32(at, n, little);
4051
+ this.memoryChangedSlot(name, current.slot, at, size);
4052
+ };
4053
+ return Object.freeze({
4054
+ load8: (offset) => read(1, false, offset),
4055
+ load16le: (offset) => read(2, true, offset),
4056
+ load16be: (offset) => read(2, false, offset),
4057
+ load32le: (offset) => read(4, true, offset),
4058
+ load32be: (offset) => read(4, false, offset),
4059
+ store8: (offset, value) => write(1, false, offset, value),
4060
+ store16le: (offset, value) => write(2, true, offset, value),
4061
+ store16be: (offset, value) => write(2, false, offset, value),
4062
+ store32le: (offset, value) => write(4, true, offset, value),
4063
+ store32be: (offset, value) => write(4, false, offset, value),
4064
+ length: () => this.memory(name).length,
4065
+ copy: (offset, length) => {
4066
+ this.track(this.memoryResources, name);
4067
+ const bytes = this.memory(name), at = range(bytes, offset, length);
4068
+ return bytes.slice(at, at + Number(length));
4069
+ }
4070
+ });
3882
4071
  }
3883
- const direct = jit.direct;
3884
- const frame = direct.frame;
3885
- const layout = jit.directLayout;
3886
- for (;;) {
3887
- if (pending) frame.stopAfterInstruction = true;
3888
- frame.time = board.time;
3889
- const start = board.time;
3890
- let reason;
3891
- let wrote;
3892
- const stats = directStats(jit);
3893
- stats.directCalls++;
3894
- try {
3895
- reason = direct.program.run(frame, Math.min(board.executionEnd, board.events.time));
3896
- } finally {
3897
- wrote = flushDirect(board, instance, layout, frame);
3898
- }
3899
- if (frame.boundarySettled) frame.boundarySettled = false;
3900
- else if (reason !== "fallback" || wrote || board.time !== start) board.boundary();
3901
- if (reason === "fallback") {
3902
- const nextPc = finite(instance.states.get(jit.options.pc), "pc");
3903
- if (!(effectivePolling(jit).has(nextPc) || jit.cache.get(nextPc)?.polling)) {
3904
- stats.directFallbacks++;
3905
- jit.directSkip = nextPc;
4072
+ prepare() {
4073
+ for (const declaration of this.entry.model.declarations) if (declaration.kind === "pin") this.pins.set(declaration.name, {
4074
+ id: `${this.id}\0${declaration.name}`,
4075
+ instance: this.id,
4076
+ name: declaration.name,
4077
+ intent: [],
4078
+ sample: {
4079
+ voltage: null,
4080
+ level: "unknown",
4081
+ status: "floating"
3906
4082
  }
3907
- if (!wrote && board.time === start && board.time < board.executionEnd) return false;
3908
- } else if (reason === "stopped") {
3909
- stats.directStopped++;
3910
- jit.stopped = true;
3911
- return true;
3912
- } else if (reason === "invalidated") {
3913
- frame.stopAfterInstruction = false;
3914
- if (jit.directProgramRevision === -1 && frame.resume === 0) {
3915
- jit.direct = void 0;
3916
- jit.directRevision = -1;
4083
+ });
4084
+ for (const declaration of this.entry.model.declarations) switch (declaration.kind) {
4085
+ case "property":
4086
+ case "const":
4087
+ this.read(declaration.kind, declaration.name);
4088
+ break;
4089
+ case "state":
4090
+ this.states.set(declaration.name, snapshot(computation(declaration.initial, this.host)));
4091
+ break;
4092
+ case "memory": {
4093
+ const length = nonnegative(computation(declaration.length, this.host), "memory length");
4094
+ this.memorySizes.set(declaration.name, length);
4095
+ break;
3917
4096
  }
3918
- } else stats.directDeadlines++;
3919
- if (frame.resume) {
3920
- const wake = Math.max(frame.due, board.time);
3921
- if (jit.metadata === void 0 && board.canContinueDirect(jit, wake)) {
3922
- board.time = wake;
3923
- board.current = instance;
3924
- pending = true;
3925
- continue;
4097
+ case "pin": {
4098
+ const pin = this.pins.get(declaration.name);
4099
+ if (declaration.low && declaration.high) {
4100
+ const low = electricalNumber(computation(declaration.low, this.host)), high = electricalNumber(computation(declaration.high, this.host));
4101
+ if (low >= high) throw new ElectricalParameterError("Pin thresholds must satisfy low < high");
4102
+ Object.assign(pin, {
4103
+ low,
4104
+ high
4105
+ });
4106
+ }
4107
+ if (declaration.initial) pin.intent = computation(declaration.initial, this.host);
4108
+ break;
3926
4109
  }
3927
- if (wake > board.time) {
3928
- board.events.push(wake, () => board.queueJit(jit));
3929
- return true;
4110
+ case "channel": {
4111
+ const capacity = nonnegative(computation(declaration.capacity, this.host), "capacity");
4112
+ if (capacity === 0) throw new RangeError("Capacity must be positive");
4113
+ let maxLength;
4114
+ if (declaration.maxLength) {
4115
+ maxLength = nonnegative(computation(declaration.maxLength, this.host), "maxLength");
4116
+ if (maxLength === 0) throw new RangeError("maxLength must be positive");
4117
+ }
4118
+ this.channels.set(declaration.name, {
4119
+ declaration,
4120
+ capacity,
4121
+ ...maxLength === void 0 ? {} : { maxLength },
4122
+ overflow: declaration.overflow ? String(computation(declaration.overflow, this.host)) : "drop_new",
4123
+ incoming: new Fifo(),
4124
+ pending: new Fifo(),
4125
+ outgoing: new Fifo()
4126
+ });
4127
+ break;
3930
4128
  }
4129
+ case "notification":
4130
+ if (declaration.direction === "output") this.notificationOutputs.set(declaration.name, null);
4131
+ break;
4132
+ case "start":
4133
+ case "on":
4134
+ this.processes.push({
4135
+ instance: this,
4136
+ declaration,
4137
+ resumable: resumable(declaration.body),
4138
+ ...declaration.kind === "on" ? { source: declaration.sourcePath } : {},
4139
+ state: "idle",
4140
+ pending: false
4141
+ });
4142
+ break;
4143
+ case "reaction": this.reactions.push({
4144
+ instance: this,
4145
+ declaration,
4146
+ previous: void 0,
4147
+ synchronousProgram: synchronousBody(this, declaration.body) ?? null,
4148
+ frame: void 0
4149
+ });
4150
+ }
4151
+ for (const [name, channel] of this.channels) if (channel.declaration.direction === "input") this.batchInputs.push(channel);
4152
+ else {
4153
+ this.batchOutputs.push([name, channel]);
4154
+ this.emptyOutputs[name] = EMPTY_MESSAGES;
4155
+ }
4156
+ for (const name of this.notificationOutputs.keys()) {
4157
+ this.batchNotifications.push(name);
4158
+ this.emptyOutputs[name] = null;
4159
+ }
4160
+ Object.freeze(this.emptyOutputs);
4161
+ }
4162
+ captureBatch(from, to) {
4163
+ for (const channel of this.batchInputs) if (channel.incoming.length) channel.incoming.clear();
4164
+ let outputs = this.emptyOutputs;
4165
+ for (const [name, channel] of this.batchOutputs) {
4166
+ if (!channel.outgoing.length) continue;
4167
+ if (outputs === this.emptyOutputs) outputs = Object.assign(Object.create(null), this.emptyOutputs);
4168
+ outputs[name] = Object.freeze(channel.outgoing.drain().map((message) => Object.freeze({
4169
+ time: message.time,
4170
+ value: externalValue(message.value)
4171
+ })));
3931
4172
  }
3932
- board.queueJit(jit);
3933
- return true;
4173
+ for (const name of this.batchNotifications) {
4174
+ const notified = this.notificationOutputs.get(name);
4175
+ if (notified === null) continue;
4176
+ if (outputs === this.emptyOutputs) outputs = Object.assign(Object.create(null), this.emptyOutputs);
4177
+ outputs[name] = Object.freeze({ time: notified });
4178
+ this.notificationOutputs.set(name, null);
4179
+ }
4180
+ return Object.freeze({
4181
+ from,
4182
+ to,
4183
+ outputs: outputs === this.emptyOutputs ? outputs : Object.freeze(outputs)
4184
+ });
3934
4185
  }
3935
- }
3936
- function pollingDependencies(jit, dependencies, pc) {
3937
- const result = new Map(dependencies);
3938
- const instance = jit.instance;
3939
- const pcSlot = instance.stateResources.get(jit.options.pc);
3940
- result.set(pcSlot, pcSlot.version);
3941
- const memory = (pc === void 0 ? void 0 : codeRegionFor(jit, pc))?.memory ?? jit.options.code;
3942
- const slot = instance.memoryResources.get(memory);
3943
- result.set(slot, slot.version);
3944
- return result;
3945
- }
3946
- /** Park a polling JIT and, when requested, schedule the next device time event. */
3947
- function waitForPolling(board, jit, dependencies, duration, advance) {
3948
- jit.dependencies = dependencies;
3949
- jit.pollingWait = true;
3950
- jit.pollingPeriod = 0;
3951
- board.parkWaiter(jit);
3952
- const token = ++jit.pollingToken;
3953
- board.boundary();
3954
- if (duration === 0 || advance === void 0) return;
3955
- const due = time(board.time + duration);
3956
- board.events.push(due, () => {
3957
- if (token !== jit.pollingToken || !jit.active || jit.stopped || !board.waitingJits.has(jit)) return;
3958
- const pending = jit.dependencies;
3959
- delete jit.dependencies;
3960
- board.unparkWaiter(jit);
3961
- jit.pollingToken++;
3962
- board.current = jit.instance;
3963
- if (!jit.instance.dependenciesCurrent(pending)) {
3964
- board.queueJit(jit);
3965
- return;
4186
+ assertCreation() {
4187
+ for (const declaration of this.entry.model.declarations) {
4188
+ if (declaration.kind !== "assert") continue;
4189
+ if (!body(declaration.body)(this.host).next().done) throw new TypeError("Creation assertion suspended");
3966
4190
  }
3967
- jit.instance.syncCall(advance, [duration]);
3968
- board.boundary();
3969
- board.queueJit(jit);
3970
- });
3971
- }
3972
- function jitSignal(board, jit, signal) {
3973
- if (signal.kind === "elapse") {
3974
- const duration = time(signal.duration);
3975
- if (duration === 0) return false;
3976
- const due = time(board.time + duration);
3977
- board.events.push(due, () => board.queueJit(jit));
3978
- board.boundary();
3979
- return true;
3980
4191
  }
3981
- if (signal.kind === "waitUntil") {
3982
- const checked = jit.instance.evaluate(() => syncJitCall(jit, signal.predicate));
3983
- if (checked.value === true) return false;
3984
- jit.predicate = signal.predicate;
3985
- jit.pollingWait = false;
3986
- jit.dependencies = checked.dependencies;
3987
- board.parkWaiter(jit);
3988
- board.boundary();
3989
- return true;
4192
+ allocate() {
4193
+ for (const [name, length] of this.memorySizes) {
4194
+ const bytes = new Uint8Array(length);
4195
+ this.memories.set(name, bytes);
4196
+ this.memoryViews.set(name, new DataView(bytes.buffer));
4197
+ }
4198
+ this.memorySizes.clear();
3990
4199
  }
3991
- if (signal.kind === "stop") {
3992
- jit.stopped = true;
3993
- jit.execution = void 0;
3994
- board.boundary();
3995
- return true;
4200
+ assertCallAllowed() {
4201
+ this.board.assertCallAllowed(this);
3996
4202
  }
3997
- if (signal.kind === "redirect") {
3998
- finite(signal.pc, "redirect target");
3999
- const duration = time(signal.delay);
4000
- jit.instance.host.write(jit.options.pc, signal.pc);
4001
- jit.execution = void 0;
4002
- const polling = jit.automaticPolling && duration > 0 && signal.pc === jit.currentPc && jit.pollReads;
4003
- const dependencies = polling ? pollingDependencies(jit, polling, jit.currentPc) : void 0;
4004
- jit.automaticPolling = false;
4005
- jit.pollReads = void 0;
4006
- board.boundary();
4007
- if (duration === 0) board.queueJit(jit);
4008
- else board.events.push(time(board.time + duration), () => {
4009
- if (!jit.active || jit.stopped) return;
4010
- if (dependencies && jit.instance.dependenciesCurrent(dependencies)) {
4011
- jit.dependencies = dependencies;
4012
- jit.pollingWait = true;
4013
- jit.pollingPeriod = duration;
4014
- jit.pollingOrigin = board.time;
4015
- board.parkWaiter(jit);
4016
- } else board.queueJit(jit);
4203
+ inputs() {
4204
+ const result = Object.create(null);
4205
+ for (const declaration of this.entry.model.declarations) {
4206
+ if (declaration.kind === "channel" && declaration.direction === "input") result[declaration.name] = Object.freeze({ send: (value) => {
4207
+ this.assertCallAllowed();
4208
+ this.send(declaration.name, value, true);
4209
+ } });
4210
+ if (declaration.kind === "notification" && declaration.direction === "input") result[declaration.name] = Object.freeze({ notify: () => {
4211
+ this.assertCallAllowed();
4212
+ this.notificationInputs.add(declaration.name);
4213
+ } });
4214
+ }
4215
+ return Object.freeze(result);
4216
+ }
4217
+ publicMemory() {
4218
+ const result = Object.create(null);
4219
+ for (const declaration of this.entry.model.declarations) if (declaration.kind === "memory" && declaration.public) result[declaration.name] = bytesView(this.memory(declaration.name), () => {
4220
+ this.board.assertAlive(this);
4221
+ if (![
4222
+ "idle",
4223
+ "initialize",
4224
+ "sync"
4225
+ ].includes(this.board.phase)) throw this.board.error("INVALID_CALL_STATE", "Memory cannot be borrowed in this phase", this);
4226
+ if (this.board.phase === "initialize" && this.board.current !== this) throw this.board.error("INVALID_CALL_STATE", "Another factory is initializing", this);
4017
4227
  });
4018
- return true;
4228
+ return Object.freeze(result);
4019
4229
  }
4020
- throw new TypeError("Invalid JIT suspension");
4021
- }
4022
- function runJit(board, jit) {
4023
- jit.queued = false;
4024
- if (!jit.active || jit.stopped) return;
4025
- board.current = jit.instance;
4026
- if (jit.metadata !== void 0) ensureMetadataForPc(board, jit, finite(jit.instance.states.get(jit.options.pc), "pc"));
4027
- if (jit.direct?.frame.resume) {
4028
- runDirect(board, jit);
4029
- return;
4230
+ send(name, value, input) {
4231
+ const channel = this.channels.get(name);
4232
+ if (!channel || channel.declaration.direction !== (input ? "input" : "output")) throw new TypeError(`Unknown channel ${name}`);
4233
+ const captured = captureValue(channel.declaration.type, value, this.declarations);
4234
+ if (channel.maxLength !== void 0 && captured.length > channel.maxLength) throw new RangeError("Message exceeds maxLength");
4235
+ const queue = input ? channel.pending : channel.outgoing;
4236
+ if (queue.length === channel.capacity) {
4237
+ if (channel.overflow === "drop_new") return;
4238
+ if (channel.overflow === "error") {
4239
+ const error = this.board.error("CHANNEL_OVERFLOW", `Channel ${name} overflow`, this);
4240
+ this.board.fault(error);
4241
+ throw error;
4242
+ }
4243
+ queue.shift();
4244
+ }
4245
+ queue.push({
4246
+ time: this.board.time,
4247
+ value: captured
4248
+ });
4030
4249
  }
4031
- if (!jit.execution) {
4032
- jit.automaticPolling = false;
4033
- jit.pollReads = void 0;
4034
- let hookReads;
4035
- let hookPending = false;
4036
- const hook = jit.options.beforeInstruction;
4037
- if (hook) {
4038
- const kind = jit.instance.declarations.get(hook.when).kind;
4039
- const priorPc = jit.instance.states.get(jit.options.pc);
4040
- const checked = board.execution === "throughput" && (board.jits.length === 1 || effectivePolling(jit).has(priorPc)) ? jit.instance.evaluate(() => jit.instance.read(kind, hook.when)) : void 0;
4041
- const handled = (checked ? checked.value : jit.instance.read(kind, hook.when)) === true;
4042
- if (handled) {
4043
- const execution = jit.instance.invoke(hook.call);
4044
- const step = execution.next();
4045
- if (!step.done) {
4046
- jit.execution = execution;
4047
- if (jitSignal(board, jit, step.value)) return;
4048
- throw new TypeError("Invalid hook suspension");
4049
- }
4250
+ captureCodeRegions(options) {
4251
+ const primaryMemory = this.memories.get(options.code);
4252
+ const primary = Object.freeze({
4253
+ memory: options.code,
4254
+ base: 0,
4255
+ size: primaryMemory.length
4256
+ });
4257
+ const additional = [];
4258
+ if (Object.hasOwn(options, "codeRegions")) {
4259
+ if (!Array.isArray(options.codeRegions)) throw new TypeError("codeRegions must be an array");
4260
+ for (const item of options.codeRegions) {
4261
+ dataObject(item, [
4262
+ "memory",
4263
+ "base",
4264
+ "size"
4265
+ ]);
4266
+ const memory = identity(item.memory);
4267
+ const base = nonnegative(item.base, "code region base");
4268
+ const size = nonnegative(item.size, "code region size");
4269
+ if (size === 0) throw new RangeError("Code region size must be positive");
4270
+ const length = this.memories.get(memory)?.length;
4271
+ if (length === void 0) throw this.board.error("INVALID_BINDING", "Unknown code region memory", this);
4272
+ if (size > length) throw this.board.error("INVALID_BINDING", "Code region exceeds memory", this);
4273
+ if (base > Number.MAX_SAFE_INTEGER - size) throw this.board.error("INVALID_BINDING", "Code region range is not a safe integer", this);
4274
+ const region = Object.freeze({
4275
+ memory,
4276
+ base,
4277
+ size
4278
+ });
4279
+ for (const existing of [primary, ...additional]) if (region.base < existing.base + existing.size && existing.base < region.base + region.size) throw this.board.error("INVALID_BINDING", "Code regions overlap", this);
4280
+ additional.push(region);
4050
4281
  }
4051
- hookReads = checked?.dependencies;
4052
- hookPending = handled;
4053
4282
  }
4054
- const pc = finite(jit.instance.states.get(jit.options.pc), "pc");
4055
- if (board.execution === "throughput") {
4056
- const declaration = effectivePolling(jit).get(pc);
4057
- if (declaration) {
4058
- const checked = jit.instance.evaluate(() => jit.instance.syncCall(declaration.predicate));
4059
- if (checked.value !== true) {
4060
- const dependencies = new Map([...hookReads ?? [], ...checked.dependencies]);
4061
- let duration = 0;
4062
- const wait = declaration.wait;
4063
- if (wait) duration = time(jit.instance.evaluate(() => jit.instance.syncCall(wait.delay), dependencies).value);
4064
- waitForPolling(board, jit, pollingDependencies(jit, dependencies, pc), duration, wait?.advance);
4065
- return;
4066
- }
4067
- if (declaration.consume) jit.instance.syncCall(declaration.consume);
4283
+ return {
4284
+ all: Object.freeze([primary, ...additional]),
4285
+ additional: Object.freeze(additional)
4286
+ };
4287
+ }
4288
+ capturePolling(items, region) {
4289
+ const polling = /* @__PURE__ */ new Map();
4290
+ if (!Array.isArray(items)) throw new TypeError("polling must be an array");
4291
+ for (const item of items) {
4292
+ dataObject(item, [
4293
+ "pc",
4294
+ "predicate",
4295
+ "consume",
4296
+ "wait"
4297
+ ]);
4298
+ const pc = finite(item.pc, "polling pc");
4299
+ if (region !== void 0 && (pc < region.base || pc >= region.base + region.size)) throw this.board.error("INVALID_BINDING", "Polling pc is outside its code region", this);
4300
+ const predicate = identity(item.predicate);
4301
+ const declaration = this.declarations.get(predicate);
4302
+ if (polling.has(pc) || declaration?.kind !== "function" || !declaration.pure || declaration.params.length || declaration.returns?.kind !== "bool") throw this.board.error("INVALID_BINDING", "Invalid polling declaration", this);
4303
+ let consume;
4304
+ if (Object.hasOwn(item, "consume")) {
4305
+ consume = identity(item.consume);
4306
+ const fn = this.declarations.get(consume);
4307
+ if (fn?.kind !== "function" || fn.params.length !== 0 || fn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling consume function", this);
4308
+ }
4309
+ let wait;
4310
+ if (Object.hasOwn(item, "wait")) {
4311
+ dataObject(item.wait, ["delay", "advance"]);
4312
+ const delay = identity(item.wait.delay);
4313
+ const advance = identity(item.wait.advance);
4314
+ const delayFn = this.declarations.get(delay);
4315
+ const advanceFn = this.declarations.get(advance);
4316
+ if (delayFn?.kind !== "function" || !delayFn.pure || delayFn.params.length !== 0 || delayFn.returns?.kind !== "number" || advanceFn?.kind !== "function" || advanceFn.params.length !== 1 || advanceFn.params[0].type.kind !== "number" || advanceFn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling wait functions", this);
4317
+ wait = Object.freeze({
4318
+ delay,
4319
+ advance
4320
+ });
4068
4321
  }
4069
- if (!hookPending && board.jits.length === 1 && runDirect(board, jit, hookReads)) return;
4322
+ polling.set(pc, Object.freeze({
4323
+ predicate,
4324
+ ...consume === void 0 ? {} : { consume },
4325
+ ...wait === void 0 ? {} : { wait }
4326
+ }));
4070
4327
  }
4071
- let instruction = jit.cache.get(pc);
4072
- if (!instruction) {
4073
- const prior = board.phase;
4074
- board.phase = "translate";
4075
- let valid = true;
4076
- try {
4077
- const codeRegion = codeRegionFor(jit, pc);
4078
- const codeMemory = codeRegion?.memory ?? jit.options.code;
4079
- const memory = jit.instance.memory(codeMemory);
4080
- const bytes = codeRegion === void 0 || codeRegion.size >= memory.length ? memory : memory.subarray(0, codeRegion.size);
4081
- const code = bytesView(bytes, () => {
4082
- if (!valid) throw board.error("OBJECT_DISPOSED", "Translation view expired", jit.instance);
4083
- });
4084
- const result = jit.options.translate(Object.freeze({
4085
- pc,
4086
- code,
4087
- codeBase: codeRegion?.base ?? 0,
4088
- codeVersion: jit.instance.codeVersion(codeMemory)
4089
- }), createJitBlockBuilder({ device: jit.model }));
4090
- acceptSync(result);
4091
- const block = validateBoundBlockIR(result, jit.model);
4092
- if (block.instructions[0]?.pc !== pc) throw new TypeError("Translated first pc does not match");
4093
- const instructions = block.instructions.map((instruction) => {
4094
- const region = codeRegionFor(jit, instruction.pc);
4095
- return {
4096
- pc: instruction.pc,
4097
- nextPc: instruction.nextPc,
4098
- body: instruction.body,
4099
- polling: isPollingInstruction(instruction.body, instruction.pc, jit.options.pc),
4100
- execute: body(instruction.body),
4101
- codeRegion: region
4102
- };
4328
+ return polling;
4329
+ }
4330
+ captureMetadataDelays(value, region) {
4331
+ if (!(value instanceof Map)) throw new TypeError("codeMetadata delays must be a Map");
4332
+ const delays = /* @__PURE__ */ new Map();
4333
+ for (const [key, item] of value) {
4334
+ const pc = finite(key, "delay pc");
4335
+ if (pc < region.base || pc >= region.base + region.size) throw this.board.error("INVALID_BINDING", "Delay pc is outside its code region", this);
4336
+ dataObject(item, [
4337
+ "counter",
4338
+ "cycles",
4339
+ "pending"
4340
+ ]);
4341
+ const counter = identity(item.counter);
4342
+ const cycles = integer(item.cycles, "delay cycles");
4343
+ if (cycles <= 0) throw new RangeError("Delay cycles must be positive");
4344
+ let pending;
4345
+ if (Object.hasOwn(item, "pending")) {
4346
+ dataObject(item.pending, [
4347
+ "state",
4348
+ "period",
4349
+ "active"
4350
+ ]);
4351
+ pending = Object.freeze({
4352
+ state: identity(item.pending.state),
4353
+ period: identity(item.pending.period),
4354
+ active: identity(item.pending.active)
4103
4355
  });
4104
- if (instructions.some((entry) => jit.direct?.pcs.has(entry.pc))) {
4105
- jit.direct = void 0;
4106
- jit.directPrograms.clear();
4107
- }
4108
- for (let index = instructions.length - 1; index >= 0; index--) {
4109
- const entry = instructions[index];
4110
- jit.cache.set(entry.pc, entry);
4111
- jit.cacheMemories.add(entry.codeRegion?.memory ?? jit.options.code);
4112
- }
4113
- if (instructions.some((entry) => entry.codeRegion === void 0 || entry.codeRegion.memory === jit.options.code)) jit.revision++;
4114
- jit.directSkip = void 0;
4115
- instruction = instructions[0];
4116
- } catch (cause) {
4117
- throw board.wrap(cause, "JIT_FAILED", "translate", jit.instance);
4118
- } finally {
4119
- valid = false;
4120
- board.phase = prior;
4121
4356
  }
4357
+ delays.set(pc, Object.freeze({
4358
+ counter,
4359
+ cycles,
4360
+ ...pending ? { pending } : {}
4361
+ }));
4122
4362
  }
4123
- jit.currentPc = pc;
4124
- jit.automaticPolling = board.execution === "throughput" && board.jits.length === 1 && instruction.polling && !hookPending && (!hook || hookReads !== void 0);
4125
- jit.pollReads = hookReads;
4126
- jit.instance.host.write(jit.options.pc, instruction.nextPc);
4127
- jit.execution = instruction.execute(jit.host);
4363
+ return delays;
4128
4364
  }
4129
- for (;;) {
4130
- const step = jit.automaticPolling ? (() => {
4131
- const checked = jit.instance.evaluate(() => jit.execution.next());
4132
- jit.pollReads = new Map([...jit.pollReads ?? [], ...checked.dependencies]);
4133
- return checked.value;
4134
- })() : jit.execution.next();
4135
- if (step.done) {
4365
+ /** Validate and copy provider output; caller applies it atomically. */
4366
+ captureCodeMetadata(region, value) {
4367
+ dataObject(value, ["polling", "delays"]);
4368
+ if (!Object.hasOwn(value, "polling") || !Object.hasOwn(value, "delays")) throw new TypeError("codeMetadata must contain polling and delays");
4369
+ return {
4370
+ polling: this.capturePolling(value.polling, region),
4371
+ delays: this.captureMetadataDelays(value.delays, region)
4372
+ };
4373
+ }
4374
+ attach(options) {
4375
+ this.assertCallAllowed();
4376
+ if (this.board.phase !== "initialize" || this.board.current !== this) throw this.board.error("INVALID_CALL_STATE", "attachJit is initialization-only", this);
4377
+ dataObject(options, [
4378
+ "entry",
4379
+ "code",
4380
+ "codeRegions",
4381
+ "codeMetadata",
4382
+ "pc",
4383
+ "functions",
4384
+ "beforeInstruction",
4385
+ "polling",
4386
+ "delays",
4387
+ "shareDirectBodies",
4388
+ "translate"
4389
+ ]);
4390
+ identity(options.entry);
4391
+ identity(options.code);
4392
+ identity(options.pc);
4393
+ if (this.jits.some((jit) => jit.active && jit.options.entry === options.entry)) throw this.board.error("INVALID_BINDING", "Duplicate JIT entry", this);
4394
+ if (!this.memories.has(options.code) || this.declarations.get(options.pc)?.kind !== "state" || this.declarations.get(options.pc).type.kind !== "number" || typeof options.translate !== "function") throw this.board.error("INVALID_BINDING", "Invalid JIT binding", this);
4395
+ const codeRegions = this.captureCodeRegions(options);
4396
+ if (Object.hasOwn(options, "codeMetadata")) {
4397
+ if (typeof options.codeMetadata !== "function") throw this.board.error("INVALID_BINDING", "Invalid codeMetadata provider", this);
4398
+ if (Object.hasOwn(options, "polling") || Object.hasOwn(options, "delays")) throw this.board.error("INVALID_BINDING", "codeMetadata is mutually exclusive with static polling/delays", this);
4399
+ }
4400
+ if (options.beforeInstruction !== void 0) {
4401
+ dataObject(options.beforeInstruction, ["when", "call"]);
4402
+ const condition = this.declarations.get(options.beforeInstruction.when), fn = this.declarations.get(options.beforeInstruction.call);
4403
+ if (!condition || !["state", "derived"].includes(condition.kind) || !("type" in condition) || condition.type.kind !== "bool" || fn?.kind !== "function" || fn.params.length || fn.returns) throw this.board.error("INVALID_BINDING", "Invalid instruction hook", this);
4404
+ } else if (Object.hasOwn(options, "beforeInstruction")) throw new TypeError("Invalid beforeInstruction");
4405
+ const polling = Object.hasOwn(options, "polling") ? this.capturePolling(options.polling) : /* @__PURE__ */ new Map();
4406
+ if (Object.hasOwn(options, "delays") && !(options.delays instanceof Map)) throw new TypeError("delays must be a Map");
4407
+ if (Object.hasOwn(options, "shareDirectBodies") && typeof options.shareDirectBodies !== "boolean") throw new TypeError("shareDirectBodies must be a boolean");
4408
+ const metadata = Object.hasOwn(options, "codeMetadata") ? {
4409
+ regions: new Map(codeRegions.all.map((region) => [region, {
4410
+ region,
4411
+ appliedVersion: -1,
4412
+ dirty: false,
4413
+ pending: [],
4414
+ polling: /* @__PURE__ */ new Map(),
4415
+ delays: /* @__PURE__ */ new Map()
4416
+ }])),
4417
+ polling: /* @__PURE__ */ new Map(),
4418
+ delays: /* @__PURE__ */ new Map()
4419
+ } : void 0;
4420
+ const base = this.entry.model;
4421
+ const emit = options.functions;
4422
+ if (Object.hasOwn(options, "functions") && typeof emit !== "function") throw new TypeError("functions must be a JIT function builder callback");
4423
+ let model = base;
4424
+ let functions;
4425
+ let host = this.host;
4426
+ if (emit) {
4427
+ const declarations = emit(base);
4428
+ acceptSync(declarations);
4429
+ if (!Array.isArray(declarations)) throw new TypeError("Expected JIT function declarations");
4430
+ model = bindJitFunctions(base, declarations);
4431
+ const local = /* @__PURE__ */ new Map();
4432
+ for (const declaration of model.declarations.slice(base.declarations.length)) if (declaration.kind === "function") local.set(declaration.name, declaration);
4433
+ functions = local;
4434
+ host = {
4435
+ ...this.host,
4436
+ call: (name, args) => {
4437
+ const fn = local.get(name);
4438
+ return fn ? body(fn.body)(host, args) : this.invoke(name, args);
4439
+ }
4440
+ };
4441
+ }
4442
+ const jit = {
4443
+ instance: this,
4444
+ model,
4445
+ host,
4446
+ ...functions === void 0 ? {} : { functions },
4447
+ options: Object.freeze({
4448
+ ...options,
4449
+ ...options.codeRegions === void 0 ? {} : { codeRegions: codeRegions.additional },
4450
+ ...options.beforeInstruction ? { beforeInstruction: Object.freeze({ ...options.beforeInstruction }) } : {}
4451
+ }),
4452
+ codeRegions: codeRegions.all,
4453
+ cache: /* @__PURE__ */ new Map(),
4454
+ cacheMemories: /* @__PURE__ */ new Set(),
4455
+ metadata,
4456
+ polling,
4457
+ delays: options.delays ?? /* @__PURE__ */ new Map(),
4458
+ revision: 0,
4459
+ directObserverRevision: -1,
4460
+ directStateGuards: /* @__PURE__ */ new Set(),
4461
+ directMemoryGuards: /* @__PURE__ */ new Set(),
4462
+ directHookReads: /* @__PURE__ */ new Set(),
4463
+ directMemories: /* @__PURE__ */ new Set(),
4464
+ direct: void 0,
4465
+ directSkip: void 0,
4466
+ directStale: false,
4467
+ directCacheInvalid: false,
4468
+ pollReads: void 0,
4469
+ currentPc: void 0,
4470
+ automaticPolling: false,
4471
+ pollingWait: false,
4472
+ pollingPeriod: 0,
4473
+ pollingOrigin: 0,
4474
+ pollingToken: 0,
4475
+ dependencyDirty: true,
4476
+ waiterSlots: void 0,
4477
+ active: true,
4478
+ stopped: false,
4479
+ queued: false,
4480
+ execution: void 0
4481
+ };
4482
+ this.jits.push(jit);
4483
+ this.board.jits.push(jit);
4484
+ for (const region of jit.codeRegions) this.codeMemories.add(region.memory);
4485
+ const disposable = { dispose: () => {
4486
+ if (!jit.active) return;
4487
+ jit.active = false;
4136
4488
  jit.execution = void 0;
4137
- board.boundary();
4138
- board.queueJit(jit);
4139
- return;
4489
+ delete jit.predicate;
4490
+ jit.pollingToken++;
4491
+ this.board.unparkWaiter(jit);
4492
+ jit.cache.clear();
4493
+ jit.cacheMemories.clear();
4494
+ disposeDirect(jit);
4495
+ jit.pollReads = void 0;
4496
+ } };
4497
+ this.resources.push(disposable);
4498
+ return disposable;
4499
+ }
4500
+ loadBytes(name, bytes, offset) {
4501
+ this.assertCallAllowed();
4502
+ if (this.board.phase !== "idle" && !(this.board.phase === "initialize" && this.board.current === this)) throw this.board.error("INVALID_CALL_STATE", "Code loading is not allowed in this phase", this);
4503
+ if (typeof name !== "string" || !this.jits.some((jit) => jit.active && jit.codeRegions.some((region) => region.memory === name))) throw this.board.error("INVALID_BINDING", "Memory is not bound as code", this);
4504
+ if (!(bytes instanceof Uint8Array)) throw new TypeError("Code must be Uint8Array");
4505
+ const memory = this.memory(name), at = range(memory, offset, bytes.length);
4506
+ if (bytes.length) {
4507
+ memory.set(bytes.slice(), at);
4508
+ this.memoryChanged(name, at, bytes.length);
4140
4509
  }
4141
- if (jitSignal(board, jit, step.value)) return;
4142
4510
  }
4511
+ source(path) {
4512
+ const declaration = this.declarations.get(path[0]);
4513
+ let value;
4514
+ let firstField = 1;
4515
+ if (declaration?.kind === "pin") {
4516
+ this.track(this.sampleResources, declaration.name);
4517
+ if (path[1] !== "sample") throw new TypeError(`Invalid source ${path.join(".")}`);
4518
+ value = this.pin(declaration.name).sample;
4519
+ firstField = 2;
4520
+ } else if (declaration?.kind === "state" || declaration?.kind === "derived") value = this.read(declaration.kind, declaration.name);
4521
+ else throw new TypeError(`Invalid source ${path.join(".")}`);
4522
+ for (let index = firstField; index < path.length; index++) value = value[path[index]];
4523
+ return value;
4524
+ }
4525
+ };
4526
+ //#endregion
4527
+ //#region src/runtime/publish-gate.ts
4528
+ var gates = /* @__PURE__ */ new WeakMap();
4529
+ /** Attach the gate to the facade the board hands out; never exposed through the package entry. */
4530
+ function registerPublishGate(bridge, gate) {
4531
+ gates.set(bridge, gate);
4532
+ }
4533
+ function publishGate(bridge) {
4534
+ const gate = gates.get(bridge);
4535
+ if (gate === void 0) throw new TypeError("Topic bridge was not created by a board");
4536
+ return gate;
4143
4537
  }
4144
4538
  //#endregion
4145
4539
  //#region src/runtime.ts
4146
4540
  var OBSERVATION_PROBE = Symbol.for("mica-js.simulator/observations");
4147
4541
  var PROCESS_PROBE = Symbol.for("mica-js.simulator/processes");
4542
+ var CHECKPOINT_PROBE = Symbol.for("mica-js.simulator/checkpoints");
4543
+ /**
4544
+ * Internal diagnostics opt-in. It stays a `globalThis` symbol so the runtime remains
4545
+ * browser-compatible and the public SDK surface does not grow:
4546
+ *
4547
+ * `globalThis[Symbol.for('mica-js.simulator/checkpoint-experiment')]?.diagnostics`
4548
+ *
4549
+ * Counters default to off; they classify boundary sources without changing runtime behavior.
4550
+ */
4551
+ var CHECKPOINT_EXPERIMENT = Symbol.for("mica-js.simulator/checkpoint-experiment");
4552
+ var EMPTY_BOUNDARY_SOURCES = Object.freeze({
4553
+ checkpointPublish: 0,
4554
+ checkpointFinish: 0,
4555
+ jitSignal: 0,
4556
+ runJit: 0,
4557
+ runDirect: 0,
4558
+ polling: 0,
4559
+ process: 0,
4560
+ other: 0
4561
+ });
4562
+ function createBoundaryStats() {
4563
+ return {
4564
+ calls: 0,
4565
+ empty: 0,
4566
+ publishes: 0,
4567
+ batches: 0,
4568
+ reactions: 0,
4569
+ captures: 0,
4570
+ sources: { ...EMPTY_BOUNDARY_SOURCES }
4571
+ };
4572
+ }
4573
+ function checkpointDiagnosticsEnabled() {
4574
+ const value = globalThis[CHECKPOINT_EXPERIMENT];
4575
+ return typeof value === "object" && value !== null && value.diagnostics === true;
4576
+ }
4148
4577
  var EMPTY_QUEUE_ENTRY = Object.freeze({});
4149
4578
  var libraries = /* @__PURE__ */ new WeakMap();
4150
4579
  function createDeviceLibrary(entries) {
@@ -4239,6 +4668,9 @@ var BoardRuntime = class {
4239
4668
  pollingWaiterCount = 0;
4240
4669
  jits = [];
4241
4670
  instances = [];
4671
+ /** Aggregate counters are disabled by default so formal runs avoid per-checkpoint writes. */
4672
+ checkpointDiagnostics;
4673
+ boundaryStats;
4242
4674
  network;
4243
4675
  primary;
4244
4676
  execution;
@@ -4266,6 +4698,8 @@ var BoardRuntime = class {
4266
4698
  "execution",
4267
4699
  "cpuQuantum"
4268
4700
  ]);
4701
+ this.checkpointDiagnostics = checkpointDiagnosticsEnabled();
4702
+ this.boundaryStats = this.checkpointDiagnostics ? createBoundaryStats() : void 0;
4269
4703
  const execution = Object.hasOwn(options, "execution") ? options.execution : "throughput";
4270
4704
  if (execution !== "throughput" && execution !== "precise") throw new TypeError("Invalid execution mode");
4271
4705
  this.execution = execution;
@@ -4371,6 +4805,10 @@ var BoardRuntime = class {
4371
4805
  value: () => this.processReport(),
4372
4806
  enumerable: false
4373
4807
  });
4808
+ Object.defineProperty(this, CHECKPOINT_PROBE, {
4809
+ value: () => this.checkpointReport(),
4810
+ enumerable: false
4811
+ });
4374
4812
  } catch (cause) {
4375
4813
  const error = cause instanceof SimulationError ? cause : this.wrap(cause, "INVALID_CONFIGURATION", "assembly", this.current);
4376
4814
  this.primary = error;
@@ -4428,6 +4866,37 @@ var BoardRuntime = class {
4428
4866
  bindings: Object.freeze(this.instances.map((instance) => instance.bindingReport()))
4429
4867
  });
4430
4868
  }
4869
+ /**
4870
+ * Read-only diagnostic view of boundary and Direct-checkpoint counters. Reachable only via
4871
+ * `Symbol.for('mica-js.simulator/checkpoints')`; zero counters mean diagnostics were off.
4872
+ */
4873
+ checkpointReport() {
4874
+ const boundary = this.boundaryStats;
4875
+ return Object.freeze({
4876
+ diagnostics: this.checkpointDiagnostics,
4877
+ boundary: Object.freeze({
4878
+ calls: boundary?.calls ?? 0,
4879
+ empty: boundary?.empty ?? 0,
4880
+ publishes: boundary?.publishes ?? 0,
4881
+ batches: boundary?.batches ?? 0,
4882
+ reactions: boundary?.reactions ?? 0,
4883
+ captures: boundary?.captures ?? 0,
4884
+ sources: Object.freeze({ ...boundary?.sources ?? EMPTY_BOUNDARY_SOURCES })
4885
+ }),
4886
+ checkpoints: Object.freeze(this.instances.flatMap((instance) => instance.jits.map((jit) => {
4887
+ const stats = readDirectCheckpointStats(jit);
4888
+ return Object.freeze({
4889
+ instance: instance.id,
4890
+ publications: stats?.publications ?? 0,
4891
+ finishes: stats?.finishes ?? 0,
4892
+ emptySuffixes: stats?.emptySuffixes ?? 0,
4893
+ boundaryCalls: stats?.boundaryCalls ?? 0,
4894
+ continues: stats?.continues ?? 0,
4895
+ exits: stats?.exits ?? 0
4896
+ });
4897
+ })))
4898
+ });
4899
+ }
4431
4900
  assertAlive(instance) {
4432
4901
  if (this.status === "disposed" || instance && !instance.valid) throw this.error("OBJECT_DISPOSED", "Object is disposed", instance);
4433
4902
  }
@@ -4857,10 +5326,25 @@ var BoardRuntime = class {
4857
5326
  current.splice(at, 0, after);
4858
5327
  }
4859
5328
  }
4860
- boundary() {
5329
+ boundary(source = "other") {
5330
+ const stats = this.boundaryStats;
5331
+ if (stats !== void 0) {
5332
+ stats.calls++;
5333
+ stats.sources[source]++;
5334
+ }
5335
+ let worked = false;
4861
5336
  for (;;) {
4862
- if (this.pendingElectricalSlot !== -1) this.publish();
4863
- if (!this.observations.size) return;
5337
+ if (this.pendingElectricalSlot !== -1) {
5338
+ if (stats !== void 0) stats.publishes++;
5339
+ this.publish();
5340
+ worked = true;
5341
+ }
5342
+ if (!this.observations.size) {
5343
+ if (stats !== void 0 && !worked) stats.empty++;
5344
+ return;
5345
+ }
5346
+ if (stats !== void 0) stats.batches++;
5347
+ worked = true;
4864
5348
  const reactions = this.reactionBatch;
4865
5349
  if (reactions.length) reactions.length = 0;
4866
5350
  const changes = this.changeObservations;
@@ -4875,8 +5359,10 @@ var BoardRuntime = class {
4875
5359
  this.changePrevious.length = 0;
4876
5360
  this.changeCurrent.length = 0;
4877
5361
  }
4878
- if (reactions.length) this.runBoundaryReactions(reactions);
4879
- else return;
5362
+ if (reactions.length) {
5363
+ if (stats !== void 0) stats.reactions += reactions.length;
5364
+ this.runBoundaryReactions(reactions);
5365
+ } else return;
4880
5366
  }
4881
5367
  }
4882
5368
  /** One due receiver: chains collapse their members, plain sources apply inline. */
@@ -4895,7 +5381,9 @@ var BoardRuntime = class {
4895
5381
  /** Shared capture barrier and ordered body runner for generic and static boundaries. */
4896
5382
  runBoundaryReactions(reactions) {
4897
5383
  try {
5384
+ const stats = this.boundaryStats;
4898
5385
  for (const reaction of reactions) if (reaction.declaration.captures.length) {
5386
+ if (stats !== void 0) stats.captures += reaction.declaration.captures.length;
4899
5387
  const frame = reaction.frame;
4900
5388
  frame.captures = reaction.declaration.captures.map((capture) => snapshot(computation(capture.value, reaction.instance.host)));
4901
5389
  }
@@ -4953,7 +5441,7 @@ var BoardRuntime = class {
4953
5441
  for (;;) {
4954
5442
  const step = process.execution.next(value);
4955
5443
  if (step.done) {
4956
- this.boundary();
5444
+ this.boundary("process");
4957
5445
  process.execution = void 0;
4958
5446
  process.state = "idle";
4959
5447
  if (process.pending) {
@@ -4971,13 +5459,13 @@ var BoardRuntime = class {
4971
5459
  }
4972
5460
  process.state = "waiting";
4973
5461
  channel.receiver = process;
4974
- this.boundary();
5462
+ this.boundary("process");
4975
5463
  return;
4976
5464
  }
4977
5465
  if (signal.kind !== "ticks") throw new TypeError("Invalid process suspension");
4978
5466
  const duration = time(signal.duration), due = time(this.time + duration);
4979
5467
  process.state = "waiting";
4980
- this.boundary();
5468
+ this.boundary("process");
4981
5469
  if (duration === 0) {
4982
5470
  process.state = "queued";
4983
5471
  this.models.push(process);
@@ -5005,7 +5493,7 @@ var BoardRuntime = class {
5005
5493
  for (;;) {
5006
5494
  state.value = input;
5007
5495
  if (!program.run(host, void 0, void 0, state)) {
5008
- this.boundary();
5496
+ this.boundary("process");
5009
5497
  process.state = "idle";
5010
5498
  if (process.pending) {
5011
5499
  process.pending = false;
@@ -5021,12 +5509,12 @@ var BoardRuntime = class {
5021
5509
  }
5022
5510
  process.state = "waiting";
5023
5511
  channel.receiver = process;
5024
- this.boundary();
5512
+ this.boundary("process");
5025
5513
  return;
5026
5514
  }
5027
5515
  const duration = state.duration, due = time(this.time + duration);
5028
5516
  process.state = "waiting";
5029
- this.boundary();
5517
+ this.boundary("process");
5030
5518
  if (duration === 0) {
5031
5519
  process.state = "queued";
5032
5520
  this.models.push(process);