@mica-js/simulator 0.4.0 → 2.0.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
@@ -1,7 +1,7 @@
1
1
  import { n as deviceSimulationHostGuestService, t as deviceSimulationHostFileSystemService } from "./rpc-BIxQr_wd.js";
2
- import { INTEGER_TYPES, SCALAR_TYPES, createIRInterpreter, createIRJIT, createIRModule, validateIR } from "@mica-js/ir";
3
- import { deriveSchematicTopology, parseDeviceReference, parseSchematic, symbolRole } from "@mica-js/core/schematic";
4
- import { Emitter, toDisposable } from "@mica-js/core/lifecycle";
2
+ import { INTEGER_TYPES, SCALAR_TYPES, createIRInterpreter, createIRJIT, createIRModule, toNumber, validateIR } from "@mica-js/ir";
3
+ import { deriveSchematicTopology, parseDeviceReference, parseSchematic, propertyValueProblem, readPropertyDescriptors, symbolRole } from "@mica-js/core/schematic";
4
+ import { Emitter } from "@mica-js/core/lifecycle";
5
5
  import { createRpc } from "@mica-js/core/rpc";
6
6
  import { loggerService } from "@mica-js/core/logging";
7
7
  //#region src/unified-ir/validation.ts
@@ -53,7 +53,7 @@ function createModuleValidation(module, updateResources = []) {
53
53
  *
54
54
  * Every device of a circuit shares one global pin address space, so the
55
55
  * compiler and every device kernel must agree on the capacity, the per-device
56
- * stride and the meaning of a `pin_mode` slot. Capacity and stride are limits
56
+ * stride and the physical output configuration values. Capacity and stride are limits
57
57
  * checked at allocation time; the shared pin memories are sized to the pins a
58
58
  * circuit actually declares, so a larger ceiling costs no runtime memory.
59
59
  */
@@ -61,7 +61,7 @@ function createModuleValidation(module, updateResources = []) {
61
61
  var UNIFIED_PIN_CAPACITY = 4096;
62
62
  /** Global pin addresses one device may own; enough for the largest packages. */
63
63
  var DEVICE_PIN_STRIDE = 512;
64
- /** Values stored in the global `pin_mode` array. */
64
+ /** Physical output configuration values. */
65
65
  var PIN_MODE = Object.freeze({
66
66
  highZ: 0,
67
67
  pushPull: 1,
@@ -76,15 +76,11 @@ var UnifiedIRCompilerError = class extends Error {
76
76
  code;
77
77
  deviceId;
78
78
  pinName;
79
- netId;
80
- diagnostics;
81
79
  constructor(code, message, options = {}) {
82
80
  super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
83
81
  this.code = code;
84
82
  this.deviceId = options.deviceId;
85
83
  this.pinName = options.pinName;
86
- this.netId = options.netId;
87
- this.diagnostics = options.diagnostics ?? [];
88
84
  }
89
85
  };
90
86
  //#endregion
@@ -98,12 +94,11 @@ var DEVICE_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
98
94
  * ids: 0 = drive1.PA0 1 = drive1.PA1 2 = sink1.anode 3 = sink1.cathode
99
95
  * |<-- drive1 -->| |<----------- sink1 ----------->|
100
96
  *
101
- * pin_mode[n] u8 pin_output[n] bool pin_input[n] bool (n = totalPins)
102
97
  * device_state_bool[n] / device_state_u32[m] / ... (one array per used type)
103
98
  * ```
104
99
  *
105
100
  * Pins are packed in declaration order across devices — the addresses the
106
- * device IR and every net solver embed as constants. States are packed per
101
+ * device IR embeds as constants. States are packed per
107
102
  * scalar type into one shared array, so a device's slot stays typed while all
108
103
  * devices share one storage region.
109
104
  */
@@ -112,11 +107,10 @@ var GlobalResourceAllocator = class {
112
107
  constructor(module) {
113
108
  this.module = module;
114
109
  }
115
- /** Allocates the shared pin memories, the pin space and the state space. */
110
+ /** Allocates pin addresses and typed device state arrays. */
116
111
  allocate(devices) {
117
112
  const pins = this.allocatePins(devices);
118
113
  return Object.freeze({
119
- memory: createPinMemory(this.module, Math.max(1, pins.totalPins)),
120
114
  pins,
121
115
  states: this.allocateStates(devices)
122
116
  });
@@ -140,19 +134,14 @@ var GlobalResourceAllocator = class {
140
134
  const offset = totalPins;
141
135
  const devicePins = /* @__PURE__ */ new Map();
142
136
  const resolved = /* @__PURE__ */ new Map();
143
- for (const [name, descriptor] of entries) {
137
+ for (const [name] of entries) {
144
138
  const globalPinId = totalPins;
145
139
  totalPins += 1;
146
- const direction = resolvePinDirection(descriptor, device.id, name);
147
- const { role, senses } = resolvePinRole(direction, descriptor?.role, device.id, name);
148
140
  devicePins.set(name, globalPinId);
149
141
  resolved.set(name, Object.freeze({
150
142
  name,
151
143
  deviceId: device.id,
152
- globalPinId,
153
- direction,
154
- role,
155
- senses
144
+ globalPinId
156
145
  }));
157
146
  pins.set(`${device.id}.${name}`, globalPinId);
158
147
  }
@@ -226,20 +215,6 @@ var GlobalResourceAllocator = class {
226
215
  });
227
216
  }
228
217
  };
229
- /**
230
- * Declares the three pin memories shared by every device and net solver.
231
- *
232
- * The memories are sized to the pins the circuit declares, never to
233
- * {@link UNIFIED_PIN_CAPACITY}: the capacity only bounds how many pins a
234
- * circuit may have, so a large ceiling costs neither memory nor setup time.
235
- */
236
- function createPinMemory(module, capacity = UNIFIED_PIN_CAPACITY) {
237
- return Object.freeze({
238
- mode: module.array("pin_mode", "u8", Array.from({ length: capacity }, () => PIN_MODE.highZ)),
239
- output: module.array("pin_output", "bool", Array.from({ length: capacity }, () => false)),
240
- input: module.array("pin_input", "bool", Array.from({ length: capacity }, () => false))
241
- });
242
- }
243
218
  /** First state slot ordinal of every device; used for `DeviceMetadata.stateOffset`. */
244
219
  function stateOffsetOf(states, deviceId) {
245
220
  let offset = 0;
@@ -281,53 +256,6 @@ function pinEntries(device) {
281
256
  }
282
257
  return entries;
283
258
  }
284
- var PIN_DIRECTIONS = /* @__PURE__ */ new Set([
285
- "input",
286
- "output",
287
- "bidirectional",
288
- "passive"
289
- ]);
290
- function resolvePinDirection(descriptor, deviceId, pinName) {
291
- const direction = descriptor?.direction ?? "passive";
292
- if (!PIN_DIRECTIONS.has(direction)) throw new UnifiedIRCompilerError("invalid-input", `Device "${deviceId}" pin "${pinName}" has direction ${JSON.stringify(direction)}; expected input, output, bidirectional or passive`, {
293
- deviceId,
294
- pinName
295
- });
296
- return direction;
297
- }
298
- /**
299
- * Derives the electrical role and the read behavior of a pin.
300
- *
301
- * `output` drives only, `input`/`passive` sense only, `bidirectional` drives and
302
- * senses. An explicit `role` overrides the derived drive role while
303
- * `bidirectional` keeps its sense side.
304
- */
305
- function resolvePinRole(direction, explicit, deviceId, pinName) {
306
- if (explicit !== void 0 && explicit !== "driver" && explicit !== "load") throw new UnifiedIRCompilerError("invalid-input", `Device "${deviceId}" pin "${pinName}" has role ${JSON.stringify(explicit)}; expected driver or load`, {
307
- deviceId,
308
- pinName
309
- });
310
- if (explicit === "driver") return {
311
- role: "driver",
312
- senses: direction === "bidirectional"
313
- };
314
- if (explicit === "load") return {
315
- role: "load",
316
- senses: true
317
- };
318
- if (direction === "output") return {
319
- role: "driver",
320
- senses: false
321
- };
322
- if (direction === "bidirectional") return {
323
- role: "driver",
324
- senses: true
325
- };
326
- return {
327
- role: "load",
328
- senses: true
329
- };
330
- }
331
259
  function stateEntries(device) {
332
260
  const raw = device.description.states;
333
261
  if (raw === void 0) return [];
@@ -354,11 +282,8 @@ function assertStateInitial(deviceId, name, type, initial) {
354
282
  /**
355
283
  * Generates one IR function per device phase into the unified module.
356
284
  *
357
- * Domain operations are inlined while the behavior runs: `pin.configure`,
358
- * `pin.writeDigital` and `pin.sampleDigital` become `array.store`/`array.load`
359
- * on the shared `pin_mode` / `pin_output` / `pin_input` memories, so no device
360
- * keeps its own module, protocol or host hop. A device without an explicit
361
- * `initialize` still gets one that configures its output pins as push-pull.
285
+ * Domain operations use the shared resistive electrical network, including
286
+ * explicit output configuration, finite drive impedance and solved sampling.
362
287
  *
363
288
  * The compiler ships no device models: every description must declare its own
364
289
  * pins, states and behaviors (or a `kernel`) before it reaches this generator.
@@ -369,21 +294,21 @@ var DeviceIRGenerator = class {
369
294
  this.context = context;
370
295
  }
371
296
  /**
372
- * @throws {UnifiedIRCompilerError} when the device has no kernel/behaviors or
373
- * a behavior reaches for a pin or state the description does not declare.
297
+ * @throws {UnifiedIRCompilerError} when a behavior reaches for a pin or state
298
+ * the paired description does not declare.
374
299
  */
375
300
  generate(device) {
376
301
  const allocation = this.context.pins.devices.get(device.id);
377
302
  if (allocation === void 0) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" has no pin allocation; allocate resources before generating IR`, { deviceId: device.id });
303
+ const functionOffset = this.context.module.functions.length;
378
304
  const kernelResult = device.description.kernel?.({
379
305
  deviceId: device.id,
380
306
  config: device.config,
381
307
  module: this.context.module,
382
- memory: this.context.memory,
308
+ bind: (builder) => this.createApi(device, allocation, builder),
383
309
  pins: [...allocation.resolved.values()].map((pin) => Object.freeze({
384
310
  name: pin.name,
385
- globalPinId: pin.globalPinId,
386
- role: pin.role
311
+ globalPinId: pin.globalPinId
387
312
  }))
388
313
  });
389
314
  const kernelRuntime = kernelResult !== void 0 && isKernelRuntime(kernelResult) ? kernelResult : void 0;
@@ -396,10 +321,9 @@ var DeviceIRGenerator = class {
396
321
  tick = phaseFromRef(this.context.module, device.id, kernelRuntime.tick);
397
322
  update = phaseFromRef(this.context.module, device.id, kernelRuntime.update);
398
323
  } else {
399
- if (behaviors === void 0 || !hasAnyBehavior(behaviors)) throw new UnifiedIRCompilerError("unsupported-device", `Device "${device.id}" of type "${device.type}" declares no behaviors. Provide description.behaviors or description.kernel`, { deviceId: device.id });
400
- initialize = this.generatePhase(device, allocation, "initialize", behaviors.initialize) ?? this.generateDefaultInitialize(device, allocation);
401
- tick = this.generatePhase(device, allocation, "tick", behaviors.tick);
402
- update = this.generatePhase(device, allocation, "update", behaviors.update);
324
+ initialize = this.generatePhase(device, allocation, "initialize", behaviors?.initialize);
325
+ tick = this.generatePhase(device, allocation, "tick", behaviors?.tick);
326
+ update = this.generatePhase(device, allocation, "update", behaviors?.update);
403
327
  }
404
328
  const functions = [];
405
329
  for (const phase of [
@@ -410,6 +334,7 @@ var DeviceIRGenerator = class {
410
334
  const metadata = Object.freeze({
411
335
  deviceId: device.id,
412
336
  type: device.type,
337
+ entries: Object.freeze(this.context.module.functions.slice(functionOffset).filter((fn) => fn.category === "entry").map((fn) => fn.ref)),
413
338
  pinOffset: allocation.offset,
414
339
  stateOffset: stateOffsetOf(this.context.states, device.id),
415
340
  pins: allocation.pins,
@@ -418,8 +343,8 @@ var DeviceIRGenerator = class {
418
343
  initialize: initialize?.name,
419
344
  tick: tick?.name,
420
345
  update: update?.name,
421
- accessor: device.description.accessor,
422
- kernel: device.description.kernel
346
+ ...device.description.applyInputs === void 0 ? {} : { applyInputs: device.description.applyInputs },
347
+ ...device.description.flushOutputs === void 0 ? {} : { flushOutputs: device.description.flushOutputs }
423
348
  });
424
349
  return Object.freeze({
425
350
  metadata,
@@ -447,53 +372,21 @@ var DeviceIRGenerator = class {
447
372
  ref
448
373
  };
449
374
  }
450
- generateDefaultInitialize(device, allocation) {
451
- const outputs = [...allocation.resolved.values()].filter((pin) => pin.role === "driver");
452
- if (outputs.length === 0) return void 0;
453
- const name = `${device.id}_initialize`;
454
- const ref = this.context.module.func(name, {
455
- params: [],
456
- results: []
457
- });
458
- ref.body((b) => {
459
- for (const pin of outputs) b.array.store(this.context.memory.mode, b.const("u32", pin.globalPinId), b.const("u8", PIN_MODE.pushPull));
460
- b.return([]);
461
- });
462
- return {
463
- name,
464
- ref
465
- };
466
- }
467
375
  createApi(device, allocation, builder) {
468
- const handles = /* @__PURE__ */ new Map();
469
- const pins = [];
470
- const outputs = [];
471
- for (const pin of allocation.resolved.values()) {
472
- const handle = this.createPinHandle(pin.globalPinId, pin.name, builder);
473
- handles.set(pin.name, handle);
474
- pins.push(handle);
475
- if (pin.role === "driver") outputs.push(handle);
476
- }
477
376
  const slots = this.context.states.devices.get(device.id);
377
+ const electrical = this.context.electrical.bindDevice(device.id, builder, new Map([...allocation.resolved].map(([name, pin]) => [name, pin.globalPinId])));
478
378
  return Object.freeze({
479
379
  deviceId: device.id,
480
380
  builder,
481
381
  module: this.context.module,
482
- memory: this.context.memory,
483
382
  config: device.config,
484
- pins: Object.freeze(pins),
485
- outputs: Object.freeze(outputs),
486
- pin(name) {
487
- const handle = handles.get(name);
488
- if (handle === void 0) {
489
- const available = [...handles.keys()].map((entry) => `${device.id}.${entry}`);
490
- throw new UnifiedIRCompilerError("pin-not-found", `Pin '${device.id}.${name}' not found. Available: [${available.join(", ")}]`, {
491
- deviceId: device.id,
492
- pinName: name
493
- });
494
- }
495
- return handle;
496
- },
383
+ pins: electrical.pins,
384
+ outputs: electrical.outputs,
385
+ resistor: electrical.resistor,
386
+ writeDigitalGroup: electrical.writeDigitalGroup,
387
+ applyResistors: electrical.applyResistors,
388
+ applyConnections: electrical.applyConnections,
389
+ pin: electrical.pin,
497
390
  state(name) {
498
391
  const slot = slots?.get(name);
499
392
  if (slot === void 0) throw new UnifiedIRCompilerError("state-not-found", `Device "${device.id}" has no state "${name}". Available: [${[...slots?.keys() ?? []].join(", ")}]`, { deviceId: device.id });
@@ -501,27 +394,6 @@ var DeviceIRGenerator = class {
501
394
  }
502
395
  });
503
396
  }
504
- createPinHandle(globalId, name, builder) {
505
- const memory = this.context.memory;
506
- const index = () => builder.const("u32", globalId);
507
- return Object.freeze({
508
- name,
509
- globalId,
510
- configure(mode) {
511
- if (!Number.isInteger(mode) || mode < 0 || mode > 255) throw new UnifiedIRCompilerError("invalid-input", `Pin "${name}" configure(${String(mode)}) needs a u8 pin mode`);
512
- builder.array.store(memory.mode, index(), builder.const("u8", mode));
513
- },
514
- writeDigital(level) {
515
- builder.array.store(memory.output, index(), level);
516
- },
517
- sampleDigital() {
518
- return builder.array.load(memory.input, index());
519
- },
520
- readDrivenDigital() {
521
- return builder.array.load(memory.output, index());
522
- }
523
- });
524
- }
525
397
  };
526
398
  function createStateHandle(deviceId, slot, builder) {
527
399
  const array = slot.array;
@@ -537,27 +409,1809 @@ function createStateHandle(deviceId, slot, builder) {
537
409
  builder.array.store(array, index, value);
538
410
  }
539
411
  });
540
- }
541
- function hasAnyBehavior(behaviors) {
542
- return behaviors.initialize !== void 0 || behaviors.tick !== void 0 || behaviors.update !== void 0;
543
- }
544
- /** Bulk kernel results carry phase refs; behaviour hooks are plain functions. */
545
- function isKernelRuntime(value) {
546
- if (value === null || typeof value !== "object") return false;
547
- return [
548
- "initialize",
549
- "tick",
550
- "update"
551
- ].some((phase) => typeof value[phase] === "object");
552
- }
553
- /** Resolves one kernel phase ref to its generated function name. */
554
- function phaseFromRef(module, deviceId, ref) {
555
- if (ref === void 0) return void 0;
556
- const definition = module.functions.find((fn) => fn.ref === ref);
557
- if (definition === void 0) throw new UnifiedIRCompilerError("invalid-ir", `Device "${deviceId}" returned a kernel phase ref that is not part of the module`, { deviceId });
412
+ }
413
+ /** Bulk kernel results carry phase refs; behaviour hooks are plain functions. */
414
+ function isKernelRuntime(value) {
415
+ if (value === null || typeof value !== "object") return false;
416
+ return [
417
+ "initialize",
418
+ "tick",
419
+ "update"
420
+ ].some((phase) => typeof value[phase] === "object");
421
+ }
422
+ /** Resolves one kernel phase ref to its generated function name. */
423
+ function phaseFromRef(module, deviceId, ref) {
424
+ if (ref === void 0) return void 0;
425
+ const definition = module.functions.find((fn) => fn.ref === ref);
426
+ if (definition === void 0) throw new UnifiedIRCompilerError("invalid-ir", `Device "${deviceId}" returned a kernel phase ref that is not part of the module`, { deviceId });
427
+ return {
428
+ name: definition.name,
429
+ ref
430
+ };
431
+ }
432
+ //#endregion
433
+ //#region src/electrical-authoring.ts
434
+ var ElectricalDefinitionError = class extends Error {
435
+ code;
436
+ name = "ElectricalDefinitionError";
437
+ constructor(code, message) {
438
+ super(message);
439
+ this.code = code;
440
+ }
441
+ };
442
+ /** Resolves a JSON declaration and calls its paired synchronous factory exactly once. */
443
+ function prepareElectricalDevice(definition, values, factory) {
444
+ const raw = record(definition, "device");
445
+ const declarations = record(raw["pins"], "pins");
446
+ const pinDeclarations = [];
447
+ for (const [id, value] of Object.entries(declarations)) {
448
+ resourceId(id);
449
+ const pin = record(value, `pins.${id}`);
450
+ rejectFields(pin, [
451
+ "direction",
452
+ "role",
453
+ "electrical"
454
+ ], `pins.${id}`);
455
+ if (![
456
+ "signal",
457
+ "power",
458
+ "gnd"
459
+ ].includes(String(pin["kind"]))) fail("electrical/invalid-definition", `pins.${id}.kind must be signal, power or gnd`);
460
+ if (pin["side"] !== void 0 && ![
461
+ "left",
462
+ "right",
463
+ "top",
464
+ "bottom"
465
+ ].includes(String(pin["side"]))) fail("electrical/invalid-definition", `pins.${id}.side is invalid`);
466
+ pinDeclarations.push([id, Object.freeze({
467
+ kind: pin["kind"],
468
+ ...pin["side"] === void 0 ? {} : { side: pin["side"] }
469
+ })]);
470
+ }
471
+ const resistors = parseBranches(raw["resistors"], declarations, false);
472
+ const connections = parseBranches(raw["connections"], declarations, true);
473
+ const descriptors = readPropertyDescriptors(raw["properties"]);
474
+ const resolved = [];
475
+ for (const [key, descriptor] of descriptors) {
476
+ const value = Object.hasOwn(values, key) ? values[key] : descriptor.default;
477
+ if (value === void 0) continue;
478
+ const problem = propertyValueProblem(descriptor, value);
479
+ if (problem !== void 0) fail("electrical/invalid-parameter", problem.message);
480
+ resolved.push([key, freezeCopy(value)]);
481
+ }
482
+ const properties = Object.freeze(Object.fromEntries(resolved));
483
+ const initializedPins = /* @__PURE__ */ new Map();
484
+ const initializedResistors = /* @__PURE__ */ new Map();
485
+ let open = true;
486
+ const assertOpen = () => {
487
+ if (!open) fail("electrical/factory-closed", "Electrical declarations are closed");
488
+ };
489
+ const electrical = Object.freeze({
490
+ initializeResistor(id, initial) {
491
+ assertOpen();
492
+ const branch = resistors.get(id);
493
+ if (branch === void 0) fail("electrical/unknown-resource", `Unknown resistor "${id}"`);
494
+ if (initializedResistors.has(id)) fail("electrical/duplicate-initialization", `Resistor "${id}" is already initialized`);
495
+ const state = record(initial, `resistor ${id}`);
496
+ positive(state["resistance"], `resistor ${id}.resistance`);
497
+ if (typeof state["enabled"] !== "boolean") fail("electrical/invalid-parameter", `resistor ${id}.enabled must be boolean`);
498
+ optionalCurrent(state, `resistor ${id}`);
499
+ initializedResistors.set(id, freezeCopy({
500
+ pins: branch.pins,
501
+ resistance: initial.resistance,
502
+ enabled: initial.enabled,
503
+ ...initial.maxAbsCurrent === void 0 ? {} : { maxAbsCurrent: initial.maxAbsCurrent }
504
+ }));
505
+ },
506
+ initializePin(id, initial) {
507
+ assertOpen();
508
+ if (!Object.hasOwn(declarations, id)) fail("electrical/unknown-resource", `Unknown pin "${id}"`);
509
+ if (initializedPins.has(id)) fail("electrical/duplicate-initialization", `Pin "${id}" is already initialized`);
510
+ validatePin(initial, id);
511
+ initializedPins.set(id, freezeCopy(initial));
512
+ }
513
+ });
514
+ let implementation;
515
+ try {
516
+ implementation = factory(Object.freeze({
517
+ properties,
518
+ electrical
519
+ }));
520
+ if (implementation !== null && (typeof implementation === "object" || typeof implementation === "function") && "then" in implementation) fail("electrical/invalid-definition", "The paired device factory must be synchronous");
521
+ } finally {
522
+ open = false;
523
+ }
524
+ for (const id of resistors.keys()) if (!initializedResistors.has(id)) fail("electrical/missing-initialization", `Resistor "${id}" has no initial state`);
525
+ return Object.freeze({
526
+ pinDeclarations: Object.freeze(Object.fromEntries(pinDeclarations)),
527
+ properties,
528
+ pins: Object.freeze(Object.fromEntries(initializedPins)),
529
+ resistors: Object.freeze(Object.fromEntries(initializedResistors)),
530
+ connections: Object.freeze(Object.fromEntries(connections)),
531
+ implementation
532
+ });
533
+ }
534
+ function parseBranches(value, pins, contact) {
535
+ const result = /* @__PURE__ */ new Map();
536
+ if (value === void 0) return result;
537
+ for (const [id, item] of Object.entries(record(value, contact ? "connections" : "resistors"))) {
538
+ resourceId(id);
539
+ const branch = record(item, id);
540
+ rejectFields(branch, [
541
+ "resistance",
542
+ "adjustable",
543
+ "initialEnabled"
544
+ ], id);
545
+ const endpoints = branch["pins"];
546
+ if (!Array.isArray(endpoints) || endpoints.length !== 2 || endpoints[0] === endpoints[1] || endpoints.some((pin) => typeof pin !== "string" || !Object.hasOwn(pins, pin))) fail("electrical/invalid-definition", `${id}.pins must name two distinct declared pins`);
547
+ const pair = [endpoints[0], endpoints[1]];
548
+ if (contact) {
549
+ const initial = branch["initial"] ?? "open";
550
+ if (initial !== "open" && initial !== "closed") fail("electrical/invalid-definition", `${id}.initial must be open or closed`);
551
+ result.set(id, freezeCopy({
552
+ pins: pair,
553
+ initial
554
+ }));
555
+ } else result.set(id, freezeCopy({ pins: pair }));
556
+ }
557
+ return result;
558
+ }
559
+ function validatePin(value, id) {
560
+ const pin = record(value, `pin ${id}`);
561
+ rejectFields(pin, [
562
+ "direction",
563
+ "role",
564
+ "interpretation"
565
+ ], id);
566
+ if (![
567
+ "drive",
568
+ "bias",
569
+ "input"
570
+ ].some((key) => pin[key] !== void 0)) fail("electrical/invalid-parameter", `pin ${id} needs drive, bias or input parameters`);
571
+ for (const category of [
572
+ "drive",
573
+ "bias",
574
+ "input"
575
+ ]) {
576
+ if (pin[category] === void 0) continue;
577
+ const part = record(pin[category], `${id}.${category}`);
578
+ const reference = record(part["reference"], `${id}.${category}.reference`);
579
+ if (typeof reference["source"] !== "string" || reference["source"].length === 0) fail("electrical/invalid-parameter", `${id}.${category} needs an explicit source reference`);
580
+ if (category === "drive") {
581
+ positive(part["highResistance"], `${id}.highResistance`);
582
+ positive(part["lowResistance"], `${id}.lowResistance`);
583
+ if (part["analogResistance"] !== void 0) positive(part["analogResistance"], `${id}.analogResistance`);
584
+ optionalCurrent(part, id);
585
+ } else if (category === "bias") {
586
+ positive(part["upResistance"], `${id}.upResistance`);
587
+ positive(part["downResistance"], `${id}.downResistance`);
588
+ } else {
589
+ rejectFields(part, ["interpretation"], `${id}.input`);
590
+ const low = part["low"];
591
+ const high = part["high"];
592
+ if (typeof low !== "number" || typeof high !== "number" || !Number.isFinite(low) || !Number.isFinite(high) || low < 0 || low >= high || high > 1) fail("electrical/invalid-parameter", `${id} thresholds must satisfy 0 <= low < high <= 1`);
593
+ }
594
+ }
595
+ }
596
+ function record(value, label) {
597
+ if (value === null || typeof value !== "object" || Array.isArray(value)) fail("electrical/invalid-definition", `${label} must be an object`);
598
+ return value;
599
+ }
600
+ function resourceId(id) {
601
+ if (id.length === 0) fail("electrical/invalid-definition", "Resource IDs must not be empty");
602
+ }
603
+ function positive(value, label) {
604
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) fail("electrical/invalid-parameter", `${label} must be finite and greater than zero`);
605
+ }
606
+ function optionalCurrent(value, label) {
607
+ if (value["maxAbsCurrent"] !== void 0) positive(value["maxAbsCurrent"], `${label}.maxAbsCurrent`);
608
+ }
609
+ function rejectFields(value, fields, label) {
610
+ for (const field of fields) if (Object.hasOwn(value, field)) fail("electrical/invalid-definition", `${label}.${field} is not part of the electrical declaration`);
611
+ }
612
+ function freezeCopy(value) {
613
+ const copy = structuredClone(value);
614
+ const freeze = (item) => {
615
+ if (item === null || typeof item !== "object") return;
616
+ for (const child of Object.values(item)) freeze(child);
617
+ Object.freeze(item);
618
+ };
619
+ freeze(copy);
620
+ return copy;
621
+ }
622
+ function fail(code, message) {
623
+ throw new ElectricalDefinitionError(code, message);
624
+ }
625
+ //#endregion
626
+ //#region src/unified-ir/compiler/electrical-network.ts
627
+ /** Links prepared authoring resources. Only wires union nodes; resistors never do. */
628
+ function allocateElectricalNetwork(devices, sources, wires) {
629
+ const fail = (message) => {
630
+ throw new ElectricalDefinitionError("electrical/invalid-definition", message);
631
+ };
632
+ const parent = [];
633
+ const makeNode = () => {
634
+ const node = parent.length;
635
+ parent.push(node);
636
+ return node;
637
+ };
638
+ const root = (node) => {
639
+ let current = node;
640
+ while (parent[current] !== current) current = parent[current];
641
+ while (node !== current) {
642
+ const next = parent[node];
643
+ parent[node] = current;
644
+ node = next;
645
+ }
646
+ return current;
647
+ };
648
+ const sourceIndices = /* @__PURE__ */ new Map([["GND", 0]]);
649
+ const initialSources = [{
650
+ node: makeNode(),
651
+ voltage: 0,
652
+ enabled: true
653
+ }];
654
+ for (const [id, source] of Object.entries(sources)) {
655
+ if (!id || sourceIndices.has(id) || !Number.isFinite(source.voltage)) fail(`Invalid or duplicate voltage source "${id}"`);
656
+ sourceIndices.set(id, initialSources.length);
657
+ initialSources.push({
658
+ node: makeNode(),
659
+ voltage: source.voltage,
660
+ enabled: true
661
+ });
662
+ }
663
+ const pinNodes = /* @__PURE__ */ new Map();
664
+ for (const device of devices) {
665
+ if (!device.id || pinNodes.has(device.id)) fail(`Invalid or duplicate device "${device.id}"`);
666
+ pinNodes.set(device.id, new Map(Object.keys(device.prepared.pinDeclarations).map((id) => [id, makeNode()])));
667
+ }
668
+ const reference = (name) => sourceIndices.get(name) ?? fail(`Unknown voltage source "${name}"`);
669
+ const endpoint = (item) => {
670
+ if ("source" in item) return initialSources[reference(item.source)].node;
671
+ return pinNodes.get(item.device)?.get(item.pin) ?? fail(`Unknown pin "${item.device}.${item.pin}"`);
672
+ };
673
+ for (const [a, b] of wires) {
674
+ const left = root(endpoint(a));
675
+ const right = root(endpoint(b));
676
+ if (left !== right) parent[Math.max(left, right)] = Math.min(left, right);
677
+ }
678
+ const nodes = /* @__PURE__ */ new Map();
679
+ const compact = (node) => {
680
+ const representative = root(node);
681
+ let index = nodes.get(representative);
682
+ if (index === void 0) {
683
+ index = nodes.size;
684
+ nodes.set(representative, index);
685
+ }
686
+ return index;
687
+ };
688
+ for (let node = 0; node < parent.length; node++) compact(node);
689
+ const compiledSources = initialSources.map((source) => ({
690
+ ...source,
691
+ node: compact(source.node)
692
+ }));
693
+ const compiledResistors = [];
694
+ const compiledContacts = [];
695
+ const pins = /* @__PURE__ */ new Map();
696
+ const resistors = /* @__PURE__ */ new Map();
697
+ const contacts = /* @__PURE__ */ new Map();
698
+ const currentLimits = /* @__PURE__ */ new Map();
699
+ const branch = (a, b, resistance, enabled, limit) => {
700
+ const index = compiledResistors.length;
701
+ compiledResistors.push({
702
+ a,
703
+ b,
704
+ resistance,
705
+ enabled
706
+ });
707
+ if (limit !== void 0) currentLimits.set(index, limit);
708
+ return index;
709
+ };
710
+ const ground = compiledSources[0].node;
711
+ let nodeCount = nodes.size;
712
+ for (const device of devices) {
713
+ const rawPins = pinNodes.get(device.id);
714
+ const pin = (id) => compact(rawPins.get(id) ?? fail(`Unknown pin "${device.id}.${id}"`));
715
+ const deviceResistors = /* @__PURE__ */ new Map();
716
+ for (const [id, resistor] of Object.entries(device.prepared.resistors)) deviceResistors.set(id, branch(pin(resistor.pins[0]), pin(resistor.pins[1]), resistor.resistance, resistor.enabled, resistor.maxAbsCurrent));
717
+ resistors.set(device.id, deviceResistors);
718
+ const deviceContacts = /* @__PURE__ */ new Map();
719
+ for (const [id, contact] of Object.entries(device.prepared.connections)) {
720
+ deviceContacts.set(id, compiledContacts.length);
721
+ compiledContacts.push({
722
+ a: pin(contact.pins[0]),
723
+ b: pin(contact.pins[1]),
724
+ closed: contact.initial === "closed"
725
+ });
726
+ }
727
+ contacts.set(device.id, deviceContacts);
728
+ const devicePins = /* @__PURE__ */ new Map();
729
+ for (const id of rawPins.keys()) {
730
+ const node = pin(id);
731
+ const description = Object.hasOwn(device.prepared.pins, id) ? device.prepared.pins[id] : {};
732
+ let drive;
733
+ let bias;
734
+ let input;
735
+ if (description.drive !== void 0) {
736
+ const config = description.drive;
737
+ const supply = reference(config.reference.source);
738
+ const high = branch(node, compiledSources[supply].node, config.highResistance, false, config.maxAbsCurrent);
739
+ const low = branch(node, ground, config.lowResistance, false, config.maxAbsCurrent);
740
+ let analog;
741
+ if (config.analogResistance !== void 0) {
742
+ const source = compiledSources.length;
743
+ const sourceNode = nodeCount++;
744
+ compiledSources.push({
745
+ node: sourceNode,
746
+ voltage: 0,
747
+ enabled: true
748
+ });
749
+ analog = Object.freeze({
750
+ source,
751
+ resistor: branch(node, sourceNode, config.analogResistance, false, config.maxAbsCurrent)
752
+ });
753
+ }
754
+ drive = Object.freeze({
755
+ high,
756
+ low,
757
+ reference: supply,
758
+ ...analog === void 0 ? {} : { analog },
759
+ ...config.maxAbsCurrent === void 0 ? {} : { maxAbsCurrent: config.maxAbsCurrent }
760
+ });
761
+ }
762
+ if (description.bias !== void 0) {
763
+ const config = description.bias;
764
+ const supply = reference(config.reference.source);
765
+ bias = Object.freeze({
766
+ up: branch(node, compiledSources[supply].node, config.upResistance, false),
767
+ down: branch(node, ground, config.downResistance, false)
768
+ });
769
+ }
770
+ if (description.input !== void 0) {
771
+ const config = description.input;
772
+ input = Object.freeze({
773
+ reference: reference(config.reference.source),
774
+ low: config.low,
775
+ high: config.high
776
+ });
777
+ }
778
+ devicePins.set(id, Object.freeze({
779
+ node,
780
+ ...drive === void 0 ? {} : { drive },
781
+ ...bias === void 0 ? {} : { bias },
782
+ ...input === void 0 ? {} : { input }
783
+ }));
784
+ }
785
+ pins.set(device.id, devicePins);
786
+ }
787
+ const network = Object.freeze({
788
+ nodes: nodeCount,
789
+ sources: Object.freeze(compiledSources.map((source) => Object.freeze(source))),
790
+ resistors: Object.freeze(compiledResistors.map((resistor) => Object.freeze(resistor))),
791
+ contacts: Object.freeze(compiledContacts.map((contact) => Object.freeze(contact)))
792
+ });
793
+ return Object.freeze({
794
+ network,
795
+ pins,
796
+ resistors,
797
+ contacts,
798
+ sources: sourceIndices,
799
+ currentLimits
800
+ });
801
+ }
802
+ //#endregion
803
+ //#region src/unified-ir/compiler/floating-input.ts
804
+ var u = (b, n) => b.const("u32", n);
805
+ function mix(b, x) {
806
+ x = b.int.mul(b.int.xor(x, b.int.lshr(x, u(b, 16))), u(b, 2146121005));
807
+ x = b.int.mul(b.int.xor(x, b.int.lshr(x, u(b, 15))), u(b, 2221713035));
808
+ return b.int.xor(x, b.int.lshr(x, u(b, 16)));
809
+ }
810
+ function random(b, x) {
811
+ return b.float.div(b.convert.intToFloat("f64", x), b.const("f64", 4294967296));
812
+ }
813
+ /** mica-floating-v2 phase identity is hashed at build time except for the decimal episode count. */
814
+ function createFloatingInput(module, solver, clock, prefix, seed, deviceId, pinName, node, reference, sample = module.func(`${prefix}_sample`, {
815
+ params: [],
816
+ results: ["f64"]
817
+ })) {
818
+ const text = JSON.stringify([
819
+ "mica-floating-v2",
820
+ seed,
821
+ deviceId,
822
+ pinName
823
+ ]).slice(0, -1) + ",";
824
+ let prefixHash = 2166136261;
825
+ for (const byte of new TextEncoder().encode(text)) prefixHash = Math.imul(prefixHash ^ byte, 16777619) >>> 0;
826
+ const count = module.state(`${prefix}_count`, "u32", 0);
827
+ const wasFloating = module.state(`${prefix}_floating`, "bool", false);
828
+ const episode = module.state(`${prefix}_episode`, "u32", 0);
829
+ const initialized = module.state(`${prefix}_initialized`, "bool", false);
830
+ const initial = module.state(`${prefix}_initial`, "f64", 0);
831
+ const update = module.func(`${prefix}_update`, {
832
+ params: [],
833
+ results: []
834
+ });
835
+ const ready = (b) => b.bool.and(b.array.load(solver.sourceEnabled, u(b, reference)), b.float.cmp("gt", b.array.load(solver.sourceVoltage, u(b, reference)), b.const("f64", 0)));
836
+ update.body((b) => {
837
+ const floating = b.int.cmp("eq", b.array.load(solver.voltageState, u(b, node)), b.const("u8", 1));
838
+ const enter = b.block([]);
839
+ const after = b.block([]);
840
+ b.branch(b.bool.and(floating, b.bool.not(b.state.load(wasFloating))), {
841
+ target: enter,
842
+ args: []
843
+ }, {
844
+ target: after,
845
+ args: []
846
+ });
847
+ b.at(enter, (b) => {
848
+ const next = b.int.add(b.state.load(count), u(b, 1));
849
+ b.state.store(count, next);
850
+ let hash = u(b, prefixHash);
851
+ let started = b.const("bool", false);
852
+ for (const power of [
853
+ 1e9,
854
+ 1e8,
855
+ 1e7,
856
+ 1e6,
857
+ 1e5,
858
+ 1e4,
859
+ 1e3,
860
+ 100,
861
+ 10,
862
+ 1
863
+ ]) {
864
+ const digit = b.int.rem(b.int.div(next, u(b, power)), u(b, 10));
865
+ started = b.bool.or(started, power === 1 ? b.const("bool", true) : b.int.cmp("ne", digit, u(b, 0)));
866
+ hash = b.select(started, b.int.mul(b.int.xor(hash, b.int.add(digit, u(b, 48))), u(b, 16777619)), hash);
867
+ }
868
+ hash = b.int.mul(b.int.xor(hash, u(b, 93)), u(b, 16777619));
869
+ b.state.store(episode, b.select(b.int.cmp("eq", hash, u(b, 0)), u(b, 1), hash));
870
+ b.state.store(initialized, b.const("bool", false));
871
+ b.jump(after, []);
872
+ });
873
+ b.at(after, (b) => {
874
+ b.state.store(wasFloating, floating);
875
+ const initialize = b.block([]);
876
+ const done = b.block([]);
877
+ b.branch(b.bool.and(floating, b.bool.and(ready(b), b.bool.not(b.state.load(initialized)))), {
878
+ target: initialize,
879
+ args: []
880
+ }, {
881
+ target: done,
882
+ args: []
883
+ });
884
+ b.at(initialize, (b) => {
885
+ let value = b.state.load(episode);
886
+ value = b.int.xor(value, b.int.shl(value, u(b, 13)));
887
+ value = b.int.xor(value, b.int.lshr(value, u(b, 17)));
888
+ value = b.int.xor(value, b.int.shl(value, u(b, 5)));
889
+ b.state.store(initial, b.float.mul(random(b, value), b.array.load(solver.sourceVoltage, u(b, reference))));
890
+ b.state.store(initialized, b.const("bool", true));
891
+ b.jump(done, []);
892
+ });
893
+ b.at(done, (b) => b.return([]));
894
+ });
895
+ });
896
+ sample.body((b) => {
897
+ const active = b.block([]);
898
+ const gated = b.block([]);
899
+ b.branch(ready(b), {
900
+ target: active,
901
+ args: []
902
+ }, {
903
+ target: gated,
904
+ args: []
905
+ });
906
+ b.at(gated, (b) => b.return([b.const("f64", 0)]));
907
+ b.at(active, (b) => {
908
+ const physical = b.block([]);
909
+ const floating = b.block([]);
910
+ b.branch(b.int.cmp("eq", b.array.load(solver.voltageState, u(b, node)), b.const("u8", 0)), {
911
+ target: physical,
912
+ args: []
913
+ }, {
914
+ target: floating,
915
+ args: []
916
+ });
917
+ b.at(physical, (b) => b.return([b.array.load(solver.voltage, u(b, node))]));
918
+ b.at(floating, (b) => {
919
+ const value = mix(b, b.int.xor(mix(b, b.int.xor(b.state.load(episode), b.array.load(clock, u(b, 0)))), b.array.load(clock, u(b, 1))));
920
+ const noise = b.float.mul(b.float.sub(b.float.mul(random(b, value), b.const("f64", 2)), b.const("f64", 1)), b.const("f64", .1));
921
+ const raw = b.float.add(b.state.load(initial), noise);
922
+ const supply = b.array.load(solver.sourceVoltage, u(b, reference));
923
+ b.return([b.select(b.float.cmp("lt", raw, b.const("f64", 0)), b.const("f64", 0), b.select(b.float.cmp("gt", raw, supply), supply, raw))]);
924
+ });
925
+ });
926
+ });
927
+ return {
928
+ update,
929
+ sample
930
+ };
931
+ }
932
+ //#endregion
933
+ //#region src/unified-ir/compiler/resistive-solver.ts
934
+ var RESISTIVE_FAULT = Object.freeze({
935
+ none: 0,
936
+ invalidParameter: 1,
937
+ sourceConflict: 2,
938
+ numericalFailure: 3
939
+ });
940
+ Object.freeze({
941
+ determinate: 0,
942
+ floating: 1,
943
+ indeterminate: 2
944
+ });
945
+ var Flow = class {
946
+ b;
947
+ constructor(b) {
948
+ this.b = b;
949
+ }
950
+ u(value) {
951
+ return this.b.const("u32", value);
952
+ }
953
+ f(value) {
954
+ return this.b.const("f64", value);
955
+ }
956
+ load(array, index) {
957
+ return this.b.array.load(array, typeof index === "number" ? this.u(index) : index);
958
+ }
959
+ store(array, index, value) {
960
+ this.b.array.store(array, typeof index === "number" ? this.u(index) : index, value);
961
+ }
962
+ abs(value) {
963
+ return this.b.select(this.b.float.cmp("lt", value, this.f(0)), this.b.float.sub(this.f(0), value), value);
964
+ }
965
+ *when(condition, emit) {
966
+ yield {
967
+ kind: "when",
968
+ condition,
969
+ emit
970
+ };
971
+ }
972
+ *loop(count, emit) {
973
+ yield {
974
+ kind: "loop",
975
+ count,
976
+ emit
977
+ };
978
+ }
979
+ *guard(valid, fault, code, onFailure) {
980
+ yield {
981
+ kind: "guard",
982
+ valid,
983
+ fault,
984
+ code,
985
+ ...onFailure === void 0 ? {} : { onFailure }
986
+ };
987
+ }
988
+ run(program) {
989
+ this.advance(program(), this.b, () => {});
990
+ }
991
+ advance(program, builder, finish) {
992
+ this.b = builder;
993
+ if (program === void 0) {
994
+ finish(this.b);
995
+ return;
996
+ }
997
+ const result = program.next();
998
+ if (result.done) {
999
+ finish(this.b);
1000
+ return;
1001
+ }
1002
+ const step = result.value;
1003
+ const owner = this.b;
1004
+ const done = owner.block([]);
1005
+ if (step.kind === "guard") {
1006
+ const failed = owner.block([]);
1007
+ owner.branch(step.valid, {
1008
+ target: done,
1009
+ args: []
1010
+ }, {
1011
+ target: failed,
1012
+ args: []
1013
+ });
1014
+ owner.at(failed, (b) => {
1015
+ b.state.store(step.fault, b.const("u8", step.code));
1016
+ step.onFailure?.(b);
1017
+ b.return([]);
1018
+ });
1019
+ } else if (step.kind === "when") {
1020
+ const yes = owner.block([]);
1021
+ owner.branch(step.condition, {
1022
+ target: yes,
1023
+ args: []
1024
+ }, {
1025
+ target: done,
1026
+ args: []
1027
+ });
1028
+ owner.at(yes, (b) => this.advance(step.emit(), b, (tail) => {
1029
+ tail.jump(done, []);
1030
+ }));
1031
+ } else {
1032
+ const header = owner.block(["u32"]);
1033
+ const body = owner.block(["u32"]);
1034
+ owner.jump(header, [owner.const("u32", 0)]);
1035
+ owner.at(header, (b, [index]) => {
1036
+ b.branch(b.int.cmp("lt", index, typeof step.count === "number" ? b.const("u32", step.count) : step.count), {
1037
+ target: body,
1038
+ args: [index]
1039
+ }, {
1040
+ target: done,
1041
+ args: []
1042
+ });
1043
+ });
1044
+ owner.at(body, (b, [index]) => this.advance(step.emit(index), b, (tail) => {
1045
+ tail.jump(header, [tail.int.add(index, tail.const("u32", 1))]);
1046
+ }));
1047
+ }
1048
+ owner.at(done, (b) => this.advance(program, b, finish));
1049
+ }
1050
+ };
1051
+ /** Generates a linear solve inside the caller's unified module; no host solver callbacks. */
1052
+ function generateResistiveSolver(module, network, prefix, onPublish = []) {
1053
+ validateNetwork(network);
1054
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(prefix)) throw new Error("Invalid resistive solver prefix");
1055
+ const n = network.nodes;
1056
+ const matrixSize = n * n;
1057
+ const sourceNodes = new Set(network.sources.map((source) => source.node));
1058
+ const unknownNodes = Array.from({ length: n }, (_, i) => i).filter((i) => !sourceNodes.has(i));
1059
+ const singleton = network.contacts.length === 0 && unknownNodes.length === 1 ? unknownNodes[0] : void 0;
1060
+ const array = (name, type, initial) => module.array(`${prefix}_${name}`, type, initial);
1061
+ const floats = (name, length) => array(name, "f64", Array(Math.max(1, length)).fill(0));
1062
+ const flags = (name, length) => array(name, "bool", Array(Math.max(1, length)).fill(false));
1063
+ const resistance = array("resistance", "f64", network.resistors.length ? network.resistors.map((r) => r.resistance) : [1]);
1064
+ const resistorEnabled = array("resistor_enabled", "bool", network.resistors.length ? network.resistors.map((r) => r.enabled) : [false]);
1065
+ const sourceVoltage = array("source_voltage", "f64", network.sources.length ? network.sources.map((s) => s.voltage) : [0]);
1066
+ const sourceEnabled = array("source_enabled", "bool", network.sources.length ? network.sources.map((s) => s.enabled) : [false]);
1067
+ const contactClosed = array("contact_closed", "bool", network.contacts.length ? network.contacts.map((c) => c.closed) : [false]);
1068
+ const voltage = floats("voltage", n);
1069
+ const voltageState = array("voltage_state", "u8", Array(n).fill(1));
1070
+ const current = floats("current", network.resistors.length);
1071
+ const currentState = array("current_state", "u8", Array(Math.max(1, network.resistors.length)).fill(2));
1072
+ const sourceCurrent = floats("source_current", network.sources.length);
1073
+ const sourceCurrentState = array("source_current_state", "u8", Array(Math.max(1, network.sources.length)).fill(2));
1074
+ const contactCurrent = floats("contact_current", network.contacts.length);
1075
+ const contactCurrentState = array("contact_current_state", "u8", Array(Math.max(1, network.contacts.length)).fill(2));
1076
+ const candidateContactCurrent = floats("candidate_contact_current", network.contacts.length);
1077
+ const candidateContactState = array("candidate_contact_state", "u8", Array(Math.max(1, network.contacts.length)).fill(2));
1078
+ const contactSide = flags("contact_side", n);
1079
+ const fault = module.state(`${prefix}_fault`, "u8", 0);
1080
+ const faultTargetKind = module.state(`${prefix}_fault_target_kind`, "u8", 0);
1081
+ const faultTargetIndex = module.state(`${prefix}_fault_target_index`, "u32", 0);
1082
+ const origin = (kind, index) => (b) => {
1083
+ b.state.store(faultTargetKind, b.const("u8", kind));
1084
+ b.state.store(faultTargetIndex, typeof index === "number" ? b.const("u32", index) : index);
1085
+ };
1086
+ const factorizations = module.state(`${prefix}_factorizations`, "u32", 0);
1087
+ const validFactors = module.state(`${prefix}_valid_factors`, "bool", false);
1088
+ const topologyVersion = module.state(`${prefix}_topology_version`, "u32", 0);
1089
+ const matrixVersion = module.state(`${prefix}_matrix_version`, "u32", 0);
1090
+ const rhsVersion = module.state(`${prefix}_rhs_version`, "u32", 0);
1091
+ const factoredTopology = module.state(`${prefix}_factored_topology`, "u32", 0);
1092
+ const factoredMatrix = module.state(`${prefix}_factored_matrix`, "u32", 0);
1093
+ const solvedRhs = module.state(`${prefix}_solved_rhs`, "u32", 0);
1094
+ const hasSolution = module.state(`${prefix}_has_solution`, "bool", false);
1095
+ const invalidator = (kind, version) => {
1096
+ const fn = module.func(`${prefix}_invalidate_${kind}`, {
1097
+ params: [],
1098
+ results: []
1099
+ });
1100
+ fn.body((b) => {
1101
+ b.state.store(version, b.int.add(b.state.load(version), b.const("u32", 1)));
1102
+ b.state.store(hasSolution, b.const("bool", false));
1103
+ if (kind !== "rhs") b.state.store(validFactors, b.const("bool", false));
1104
+ b.return([]);
1105
+ });
1106
+ return fn;
1107
+ };
1108
+ const invalidate = Object.freeze({
1109
+ topology: invalidator("topology", topologyVersion),
1110
+ matrix: invalidator("matrix", matrixVersion),
1111
+ rhs: invalidator("rhs", rhsVersion)
1112
+ });
1113
+ const label = array("label", "u32", Array.from({ length: n }, (_, i) => i));
1114
+ const permutation = array("permutation", "u32", Array.from({ length: n }, (_, i) => i));
1115
+ const known = flags("known", n);
1116
+ const reachable = flags("reachable", n);
1117
+ const anchor = floats("anchor", n);
1118
+ const assigned = flags("assigned", n);
1119
+ const conductance = floats("conductance", matrixSize);
1120
+ const system = floats("system", matrixSize);
1121
+ const factors = floats("factors", matrixSize);
1122
+ const scale = floats("scale", n);
1123
+ const rhs = floats("rhs", n);
1124
+ const work = floats("work", n);
1125
+ const candidate = floats("candidate", n);
1126
+ const candidateCurrent = floats("candidate_current", network.resistors.length);
1127
+ const candidateSourceCurrent = floats("candidate_source_current", network.sources.length);
1128
+ const candidateSourceState = array("candidate_source_state", "u8", Array(Math.max(1, network.sources.length)).fill(2));
1129
+ const group = array("group", "u32", Array.from({ length: n }, (_, i) => i));
1130
+ const groupSize = array("group_size", "u32", Array(n).fill(0));
1131
+ const groupNodes = array("group_nodes", "u32", Array(matrixSize).fill(0));
1132
+ const groupDirty = flags("group_dirty", n);
1133
+ const groupSolveDirty = flags("group_solve_dirty", n);
1134
+ const groupRebuilds = array("group_rebuilds", "u32", Array(n).fill(0));
1135
+ const groupSolves = array("group_solves", "u32", Array(n).fill(0));
1136
+ const previousResistance = floats("previous_resistance", network.resistors.length);
1137
+ const previousEnabled = flags("previous_enabled", network.resistors.length);
1138
+ const previousSourceEnabled = flags("previous_source_enabled", network.sources.length);
1139
+ const factorsInitialized = module.state(`${prefix}_factors_initialized`, "bool", false);
1140
+ const repartition = module.state(`${prefix}_repartition`, "bool", true);
1141
+ const relaxing = module.state(`${prefix}_relaxing`, "bool", true);
1142
+ const pivotRow = module.state(`${prefix}_pivot_row`, "u32", 0);
1143
+ const pivotMagnitude = module.state(`${prefix}_pivot_magnitude`, "f64", 0);
1144
+ const accumulator = module.state(`${prefix}_accumulator`, "f64", 0);
1145
+ const magnitude = module.state(`${prefix}_magnitude`, "f64", 0);
1146
+ const factorGeneral = module.func(`${prefix}_factor_general`, {
1147
+ params: [],
1148
+ results: []
1149
+ });
1150
+ const factor = singleton === void 0 ? factorGeneral : module.func(`${prefix}_factor`, {
1151
+ params: [],
1152
+ results: []
1153
+ });
1154
+ const solve = module.func(`${prefix}_solve`, {
1155
+ params: [],
1156
+ results: []
1157
+ });
1158
+ const at = (q, row, column) => q.b.int.add(q.b.int.mul(row, q.u(n)), column);
1159
+ const addAt = (q, row, column, delta) => {
1160
+ const index = at(q, row, column);
1161
+ q.store(conductance, index, q.b.float.add(q.load(conductance, index), delta));
1162
+ };
1163
+ factorGeneral.body((builder) => {
1164
+ const q = new Flow(builder);
1165
+ q.run(function* () {
1166
+ q.b.state.store(validFactors, q.b.const("bool", false));
1167
+ yield* q.loop(n, function(i) {
1168
+ q.store(label, i, i);
1169
+ q.store(known, i, q.b.const("bool", false));
1170
+ q.store(reachable, i, q.b.const("bool", false));
1171
+ });
1172
+ q.b.state.store(relaxing, q.b.const("bool", true));
1173
+ yield* q.loop(n, function* () {
1174
+ yield* q.when(q.b.state.load(relaxing), function* () {
1175
+ q.b.state.store(relaxing, q.b.const("bool", false));
1176
+ for (const [index, contact] of network.contacts.entries()) yield* q.when(q.load(contactClosed, index), function() {
1177
+ const a = q.load(label, contact.a);
1178
+ const b = q.load(label, contact.b);
1179
+ const min = q.b.select(q.b.int.cmp("lt", a, b), a, b);
1180
+ q.b.state.store(relaxing, q.b.bool.or(q.b.state.load(relaxing), q.b.int.cmp("ne", a, b)));
1181
+ q.store(label, contact.a, min);
1182
+ q.store(label, contact.b, min);
1183
+ });
1184
+ });
1185
+ });
1186
+ for (const [index, source] of network.sources.entries()) yield* q.when(q.load(sourceEnabled, index), function() {
1187
+ const root = q.load(label, source.node);
1188
+ q.store(known, root, q.b.const("bool", true));
1189
+ q.store(reachable, root, q.b.const("bool", true));
1190
+ });
1191
+ q.b.state.store(relaxing, q.b.const("bool", true));
1192
+ yield* q.loop(n, function* () {
1193
+ yield* q.when(q.b.state.load(relaxing), function* () {
1194
+ q.b.state.store(relaxing, q.b.const("bool", false));
1195
+ for (const [index, resistor] of network.resistors.entries()) yield* q.when(q.load(resistorEnabled, index), function() {
1196
+ const a = q.load(label, resistor.a);
1197
+ const b = q.load(label, resistor.b);
1198
+ const ra = q.load(reachable, a);
1199
+ const rb = q.load(reachable, b);
1200
+ const connected = q.b.bool.or(ra, rb);
1201
+ q.b.state.store(relaxing, q.b.bool.or(q.b.state.load(relaxing), q.b.bool.xor(ra, rb)));
1202
+ q.store(reachable, a, connected);
1203
+ q.store(reachable, b, connected);
1204
+ });
1205
+ });
1206
+ });
1207
+ q.b.state.store(repartition, q.b.bool.or(q.b.bool.not(q.b.state.load(factorsInitialized)), q.b.int.cmp("ne", q.b.state.load(topologyVersion), q.b.state.load(factoredTopology))));
1208
+ for (const [i] of network.sources.entries()) q.b.state.store(repartition, q.b.bool.or(q.b.state.load(repartition), q.b.bool.xor(q.load(sourceEnabled, i), q.load(previousSourceEnabled, i))));
1209
+ yield* q.loop(n, function(i) {
1210
+ q.store(group, i, i);
1211
+ q.store(groupSize, i, q.u(0));
1212
+ });
1213
+ q.b.state.store(relaxing, q.b.const("bool", true));
1214
+ yield* q.loop(n, function* () {
1215
+ yield* q.when(q.b.state.load(relaxing), function* () {
1216
+ q.b.state.store(relaxing, q.b.const("bool", false));
1217
+ for (const resistor of network.resistors) {
1218
+ const a = q.load(label, resistor.a);
1219
+ const b = q.load(label, resistor.b);
1220
+ yield* q.when(q.b.bool.not(q.b.bool.or(q.load(known, a), q.load(known, b))), function() {
1221
+ const ga = q.load(group, a);
1222
+ const gb = q.load(group, b);
1223
+ const root = q.b.select(q.b.int.cmp("lt", ga, gb), ga, gb);
1224
+ q.b.state.store(relaxing, q.b.bool.or(q.b.state.load(relaxing), q.b.int.cmp("ne", ga, gb)));
1225
+ q.store(group, a, root);
1226
+ q.store(group, b, root);
1227
+ });
1228
+ }
1229
+ });
1230
+ });
1231
+ yield* q.loop(n, function(i) {
1232
+ q.store(groupDirty, i, q.b.state.load(repartition));
1233
+ });
1234
+ for (const [i, resistor] of network.resistors.entries()) yield* q.when(q.b.bool.or(q.b.float.cmp("ne", q.load(resistance, i), q.load(previousResistance, i)), q.b.bool.xor(q.load(resistorEnabled, i), q.load(previousEnabled, i))), function() {
1235
+ q.store(groupDirty, q.load(group, q.load(label, resistor.a)), q.b.const("bool", true));
1236
+ q.store(groupDirty, q.load(group, q.load(label, resistor.b)), q.b.const("bool", true));
1237
+ });
1238
+ yield* q.loop(n, function* (row) {
1239
+ yield* q.when(q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row))), function() {
1240
+ const root = q.load(group, row);
1241
+ const size = q.load(groupSize, root);
1242
+ q.store(groupNodes, at(q, root, size), row);
1243
+ q.store(groupSize, root, q.b.int.add(size, q.u(1)));
1244
+ });
1245
+ });
1246
+ yield* q.loop(matrixSize, function(i) {
1247
+ q.store(conductance, i, q.f(0));
1248
+ });
1249
+ for (const [index, resistor] of network.resistors.entries()) yield* q.when(q.load(resistorEnabled, index), function* () {
1250
+ const a = q.load(label, resistor.a);
1251
+ const b = q.load(label, resistor.b);
1252
+ const g = q.b.float.div(q.f(1), q.load(resistance, index));
1253
+ yield* q.guard(q.b.bool.and(q.b.float.isFinite(g), q.b.float.cmp("gt", g, q.f(0))), fault, RESISTIVE_FAULT.numericalFailure, origin(1, index));
1254
+ yield* q.when(q.b.int.cmp("ne", a, b), function() {
1255
+ const negative = q.b.float.sub(q.f(0), g);
1256
+ addAt(q, a, a, g);
1257
+ addAt(q, b, b, g);
1258
+ addAt(q, a, b, negative);
1259
+ addAt(q, b, a, negative);
1260
+ });
1261
+ });
1262
+ yield* q.loop(n, function* (row) {
1263
+ const active = q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row)));
1264
+ const diagonal = q.load(conductance, at(q, row, row));
1265
+ const divisor = q.b.select(active, diagonal, q.f(1));
1266
+ yield* q.guard(q.b.bool.and(q.b.float.isFinite(divisor), q.b.float.cmp("gt", divisor, q.f(0))), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
1267
+ q.store(scale, row, divisor);
1268
+ yield* q.when(q.b.bool.and(active, q.load(groupDirty, q.load(group, row))), function* () {
1269
+ yield* q.loop(n, function* (column) {
1270
+ const coefficient = q.b.select(q.load(known, column), q.f(0), q.b.float.div(q.load(conductance, at(q, row, column)), divisor));
1271
+ yield* q.guard(q.b.float.isFinite(coefficient), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
1272
+ q.store(system, at(q, row, column), coefficient);
1273
+ q.store(factors, at(q, row, column), coefficient);
1274
+ });
1275
+ q.store(permutation, row, row);
1276
+ });
1277
+ });
1278
+ yield* q.loop(n, function* (root) {
1279
+ const size = q.load(groupSize, root);
1280
+ yield* q.when(q.b.bool.and(q.load(groupDirty, root), q.b.int.cmp("gt", size, q.u(0))), function* () {
1281
+ q.store(groupRebuilds, root, q.b.int.add(q.load(groupRebuilds, root), q.u(1)));
1282
+ yield* q.when(q.b.int.cmp("gt", size, q.u(1)), function* () {
1283
+ yield* q.loop(size, function* (ki) {
1284
+ const k = q.load(groupNodes, at(q, root, ki));
1285
+ q.b.state.store(pivotRow, k);
1286
+ q.b.state.store(pivotMagnitude, q.f(0));
1287
+ yield* q.loop(size, function* (ri) {
1288
+ yield* q.when(q.b.int.cmp("ge", ri, ki), function* () {
1289
+ const row = q.load(groupNodes, at(q, root, ri));
1290
+ const abs = q.abs(q.load(factors, at(q, row, k)));
1291
+ yield* q.when(q.b.float.cmp("gt", abs, q.b.state.load(pivotMagnitude)), function() {
1292
+ q.b.state.store(pivotMagnitude, abs);
1293
+ q.b.state.store(pivotRow, row);
1294
+ });
1295
+ });
1296
+ });
1297
+ yield* q.guard(q.b.float.cmp("gt", q.b.state.load(pivotMagnitude), q.f(1e-14)), fault, RESISTIVE_FAULT.numericalFailure, origin(4, k));
1298
+ const selected = q.b.state.load(pivotRow);
1299
+ const old = q.load(permutation, k);
1300
+ q.store(permutation, k, q.load(permutation, selected));
1301
+ q.store(permutation, selected, old);
1302
+ yield* q.loop(size, function(ci) {
1303
+ const column = q.load(groupNodes, at(q, root, ci));
1304
+ const before = q.load(factors, at(q, k, column));
1305
+ q.store(factors, at(q, k, column), q.load(factors, at(q, selected, column)));
1306
+ q.store(factors, at(q, selected, column), before);
1307
+ });
1308
+ yield* q.loop(size, function* (ri) {
1309
+ yield* q.when(q.b.int.cmp("gt", ri, ki), function* () {
1310
+ const row = q.load(groupNodes, at(q, root, ri));
1311
+ const multiplier = q.b.float.div(q.load(factors, at(q, row, k)), q.load(factors, at(q, k, k)));
1312
+ yield* q.guard(q.b.float.isFinite(multiplier), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
1313
+ q.store(factors, at(q, row, k), multiplier);
1314
+ yield* q.loop(size, function* (ci) {
1315
+ yield* q.when(q.b.int.cmp("gt", ci, ki), function* () {
1316
+ const column = q.load(groupNodes, at(q, root, ci));
1317
+ const value = q.b.float.sub(q.load(factors, at(q, row, column)), q.b.float.mul(multiplier, q.load(factors, at(q, k, column))));
1318
+ yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
1319
+ q.store(factors, at(q, row, column), value);
1320
+ });
1321
+ });
1322
+ });
1323
+ });
1324
+ });
1325
+ });
1326
+ });
1327
+ });
1328
+ for (const [i] of network.resistors.entries()) {
1329
+ q.store(previousResistance, i, q.load(resistance, i));
1330
+ q.store(previousEnabled, i, q.load(resistorEnabled, i));
1331
+ }
1332
+ for (const [i] of network.sources.entries()) q.store(previousSourceEnabled, i, q.load(sourceEnabled, i));
1333
+ q.b.state.store(factorsInitialized, q.b.const("bool", true));
1334
+ q.b.state.store(factoredTopology, q.b.state.load(topologyVersion));
1335
+ q.b.state.store(factoredMatrix, q.b.state.load(matrixVersion));
1336
+ q.b.state.store(validFactors, q.b.const("bool", true));
1337
+ q.b.state.store(factorizations, q.b.int.add(q.b.state.load(factorizations), q.u(1)));
1338
+ q.b.return([]);
1339
+ });
1340
+ });
1341
+ if (singleton !== void 0) {
1342
+ const direct = module.func(`${prefix}_factor_singleton`, {
1343
+ params: [],
1344
+ results: []
1345
+ });
1346
+ direct.body((builder) => {
1347
+ const q = new Flow(builder);
1348
+ q.run(function* () {
1349
+ q.b.state.store(validFactors, q.b.const("bool", false));
1350
+ for (let node = 0; node < n; node++) {
1351
+ q.store(label, node, q.u(node));
1352
+ q.store(known, node, q.b.const("bool", node !== singleton));
1353
+ q.store(reachable, node, q.b.const("bool", node !== singleton));
1354
+ q.store(group, node, q.u(node));
1355
+ q.store(groupSize, node, q.u(0));
1356
+ q.store(groupDirty, node, q.b.const("bool", node === singleton));
1357
+ q.store(scale, node, q.f(1));
1358
+ q.store(conductance, singleton * n + node, q.f(0));
1359
+ }
1360
+ for (const [i, resistor] of network.resistors.entries()) yield* q.when(q.load(resistorEnabled, i), function* () {
1361
+ const g = q.b.float.div(q.f(1), q.load(resistance, i));
1362
+ yield* q.guard(q.b.bool.and(q.b.float.isFinite(g), q.b.float.cmp("gt", g, q.f(0))), fault, RESISTIVE_FAULT.numericalFailure, origin(1, i));
1363
+ if (resistor.a === singleton !== (resistor.b === singleton)) {
1364
+ const other = resistor.a === singleton ? resistor.b : resistor.a;
1365
+ addAt(q, q.u(singleton), q.u(singleton), g);
1366
+ addAt(q, q.u(singleton), q.u(other), q.b.float.sub(q.f(0), g));
1367
+ q.store(reachable, singleton, q.b.const("bool", true));
1368
+ }
1369
+ });
1370
+ const active = q.load(reachable, singleton);
1371
+ const divisor = q.b.select(active, q.load(conductance, singleton * n + singleton), q.f(1));
1372
+ yield* q.guard(q.b.bool.and(q.b.float.isFinite(divisor), q.b.float.cmp("gt", divisor, q.f(0))), fault, RESISTIVE_FAULT.numericalFailure, origin(4, singleton));
1373
+ q.store(scale, singleton, divisor);
1374
+ for (let column = 0; column < n; column++) q.store(system, singleton * n + column, q.f(column === singleton ? 1 : 0));
1375
+ q.store(groupSize, singleton, q.b.select(active, q.u(1), q.u(0)));
1376
+ q.store(groupNodes, singleton * n, q.u(singleton));
1377
+ yield* q.when(active, function() {
1378
+ q.store(groupRebuilds, singleton, q.b.int.add(q.load(groupRebuilds, singleton), q.u(1)));
1379
+ });
1380
+ for (const [i] of network.sources.entries()) q.store(previousSourceEnabled, i, q.load(sourceEnabled, i));
1381
+ q.b.state.store(factorsInitialized, q.b.const("bool", true));
1382
+ q.b.state.store(factoredTopology, q.b.state.load(topologyVersion));
1383
+ q.b.state.store(factoredMatrix, q.b.state.load(matrixVersion));
1384
+ q.b.state.store(validFactors, q.b.const("bool", true));
1385
+ q.b.state.store(factorizations, q.b.int.add(q.b.state.load(factorizations), q.u(1)));
1386
+ q.b.return([]);
1387
+ });
1388
+ });
1389
+ factor.body((b) => {
1390
+ let fixed = b.const("bool", true);
1391
+ for (const node of sourceNodes) {
1392
+ let enabled = b.const("bool", false);
1393
+ for (const [i, source] of network.sources.entries()) if (source.node === node) enabled = b.bool.or(enabled, b.array.load(sourceEnabled, b.const("u32", i)));
1394
+ fixed = b.bool.and(fixed, enabled);
1395
+ }
1396
+ const yes = b.block([]);
1397
+ const no = b.block([]);
1398
+ b.branch(fixed, {
1399
+ target: yes,
1400
+ args: []
1401
+ }, {
1402
+ target: no,
1403
+ args: []
1404
+ });
1405
+ b.at(yes, (b) => {
1406
+ b.call(direct, []);
1407
+ b.return([]);
1408
+ });
1409
+ b.at(no, (b) => {
1410
+ b.call(factorGeneral, []);
1411
+ b.return([]);
1412
+ });
1413
+ });
1414
+ }
1415
+ solve.body((builder) => {
1416
+ const sameTopology = builder.int.cmp("eq", builder.state.load(topologyVersion), builder.state.load(factoredTopology));
1417
+ const sameMatrix = builder.int.cmp("eq", builder.state.load(matrixVersion), builder.state.load(factoredMatrix));
1418
+ const sameRhs = builder.int.cmp("eq", builder.state.load(rhsVersion), builder.state.load(solvedRhs));
1419
+ const sameFactors = builder.bool.and(builder.state.load(validFactors), builder.bool.and(sameTopology, sameMatrix));
1420
+ const cached = builder.bool.and(builder.state.load(hasSolution), builder.bool.and(sameFactors, sameRhs));
1421
+ const done = builder.block([]);
1422
+ const dirty = builder.block([]);
1423
+ builder.branch(cached, {
1424
+ target: done,
1425
+ args: []
1426
+ }, {
1427
+ target: dirty,
1428
+ args: []
1429
+ });
1430
+ builder.at(done, (b) => b.return([]));
1431
+ builder.at(dirty, (builder) => {
1432
+ const q = new Flow(builder);
1433
+ q.run(function* () {
1434
+ q.b.state.store(hasSolution, q.b.const("bool", false));
1435
+ q.b.state.store(fault, q.b.const("u8", 0));
1436
+ q.b.state.store(faultTargetKind, q.b.const("u8", 0));
1437
+ const changed = q.b.bool.not(sameFactors);
1438
+ for (const [i] of network.resistors.entries()) {
1439
+ const r = q.load(resistance, i);
1440
+ yield* q.guard(q.b.bool.and(q.b.float.isFinite(r), q.b.float.cmp("gt", r, q.f(0))), fault, RESISTIVE_FAULT.invalidParameter, origin(1, i));
1441
+ }
1442
+ for (const [i] of network.sources.entries()) yield* q.guard(q.b.float.isFinite(q.load(sourceVoltage, i)), fault, RESISTIVE_FAULT.invalidParameter, origin(2, i));
1443
+ yield* q.when(changed, function() {
1444
+ q.b.call(factor, []);
1445
+ });
1446
+ yield* q.guard(q.b.int.cmp("eq", q.b.state.load(fault), q.b.const("u8", 0)), fault, RESISTIVE_FAULT.numericalFailure);
1447
+ yield* q.loop(n, function(i) {
1448
+ q.store(anchor, i, q.f(0));
1449
+ q.store(assigned, i, q.b.const("bool", false));
1450
+ });
1451
+ for (const [i, source] of network.sources.entries()) yield* q.when(q.load(sourceEnabled, i), function* () {
1452
+ const root = q.load(label, source.node);
1453
+ const value = q.load(sourceVoltage, i);
1454
+ const compatible = q.b.bool.or(q.b.bool.not(q.load(assigned, root)), q.b.float.cmp("eq", q.load(anchor, root), value));
1455
+ yield* q.guard(compatible, fault, RESISTIVE_FAULT.sourceConflict, origin(2, i));
1456
+ q.store(anchor, root, value);
1457
+ q.store(assigned, root, q.b.const("bool", true));
1458
+ });
1459
+ yield* q.loop(n, function(root) {
1460
+ q.store(groupSolveDirty, root, q.b.bool.and(changed, q.load(groupDirty, root)));
1461
+ });
1462
+ yield* q.loop(n, function* (row) {
1463
+ const active = q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row)));
1464
+ q.b.state.store(accumulator, q.f(0));
1465
+ yield* q.when(active, function* () {
1466
+ yield* q.loop(n, function(column) {
1467
+ const sourceTerm = q.b.select(q.load(known, column), q.b.float.mul(q.b.float.div(q.load(conductance, at(q, row, column)), q.load(scale, row)), q.load(anchor, column)), q.f(0));
1468
+ q.b.state.store(accumulator, q.b.float.sub(q.b.state.load(accumulator), sourceTerm));
1469
+ });
1470
+ });
1471
+ const value = q.b.select(q.load(known, row), q.load(anchor, row), q.b.select(active, q.b.state.load(accumulator), q.f(0)));
1472
+ yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
1473
+ yield* q.when(q.b.bool.and(active, q.b.float.cmp("ne", value, q.load(rhs, row))), function() {
1474
+ q.store(groupSolveDirty, q.load(group, row), q.b.const("bool", true));
1475
+ });
1476
+ q.store(rhs, row, value);
1477
+ yield* q.when(q.b.bool.not(active), function() {
1478
+ q.store(candidate, row, value);
1479
+ });
1480
+ });
1481
+ yield* q.loop(n, function* (root) {
1482
+ const size = q.load(groupSize, root);
1483
+ yield* q.when(q.b.bool.and(q.load(groupSolveDirty, root), q.b.int.cmp("gt", size, q.u(0))), function* () {
1484
+ q.store(groupSolves, root, q.b.int.add(q.load(groupSolves, root), q.u(1)));
1485
+ yield* q.when(q.b.int.cmp("eq", size, q.u(1)), function() {
1486
+ const row = q.load(groupNodes, at(q, root, q.u(0)));
1487
+ q.store(candidate, row, q.load(rhs, row));
1488
+ });
1489
+ yield* q.when(q.b.int.cmp("gt", size, q.u(1)), function* () {
1490
+ yield* q.loop(size, function* (ri) {
1491
+ const row = q.load(groupNodes, at(q, root, ri));
1492
+ q.b.state.store(accumulator, q.load(rhs, q.load(permutation, row)));
1493
+ yield* q.loop(size, function* (ci) {
1494
+ yield* q.when(q.b.int.cmp("lt", ci, ri), function() {
1495
+ const column = q.load(groupNodes, at(q, root, ci));
1496
+ q.b.state.store(accumulator, q.b.float.sub(q.b.state.load(accumulator), q.b.float.mul(q.load(factors, at(q, row, column)), q.load(work, column))));
1497
+ });
1498
+ });
1499
+ q.store(work, row, q.b.state.load(accumulator));
1500
+ });
1501
+ yield* q.loop(size, function* (reverse) {
1502
+ const ri = q.b.int.sub(q.b.int.sub(size, q.u(1)), reverse);
1503
+ const row = q.load(groupNodes, at(q, root, ri));
1504
+ q.b.state.store(accumulator, q.load(work, row));
1505
+ yield* q.loop(size, function* (ci) {
1506
+ yield* q.when(q.b.int.cmp("gt", ci, ri), function() {
1507
+ const column = q.load(groupNodes, at(q, root, ci));
1508
+ q.b.state.store(accumulator, q.b.float.sub(q.b.state.load(accumulator), q.b.float.mul(q.load(factors, at(q, row, column)), q.load(candidate, column))));
1509
+ });
1510
+ });
1511
+ const value = q.b.float.div(q.b.state.load(accumulator), q.load(factors, at(q, row, row)));
1512
+ yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
1513
+ q.store(candidate, row, value);
1514
+ });
1515
+ });
1516
+ });
1517
+ });
1518
+ yield* q.loop(n, function* (row) {
1519
+ yield* q.when(q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row))), function* () {
1520
+ q.b.state.store(accumulator, q.f(0));
1521
+ q.b.state.store(magnitude, q.b.float.mul(q.f(1e-10), q.abs(q.load(rhs, row))));
1522
+ yield* q.loop(n, function(column) {
1523
+ const term = q.b.float.mul(q.load(system, at(q, row, column)), q.load(candidate, column));
1524
+ q.b.state.store(accumulator, q.b.float.add(q.b.state.load(accumulator), term));
1525
+ q.b.state.store(magnitude, q.b.float.add(q.b.state.load(magnitude), q.b.float.mul(q.f(1e-10), q.abs(term))));
1526
+ });
1527
+ const error = q.abs(q.b.float.sub(q.b.state.load(accumulator), q.load(rhs, row)));
1528
+ const tolerance = q.b.float.add(q.f(1e-22), q.b.state.load(magnitude));
1529
+ yield* q.guard(q.b.bool.and(q.b.float.isFinite(error), q.b.float.cmp("le", error, tolerance)), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
1530
+ });
1531
+ });
1532
+ for (const [i, resistor] of network.resistors.entries()) {
1533
+ const delta = q.b.float.sub(q.load(candidate, q.load(label, resistor.a)), q.load(candidate, q.load(label, resistor.b)));
1534
+ const value = q.b.select(q.load(resistorEnabled, i), q.b.float.div(delta, q.load(resistance, i)), q.f(0));
1535
+ yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(1, i));
1536
+ q.store(candidateCurrent, i, value);
1537
+ }
1538
+ for (const [i, source] of network.sources.entries()) {
1539
+ const root = q.load(label, source.node);
1540
+ let unique = q.b.const("bool", true);
1541
+ for (const [j, other] of network.sources.entries()) {
1542
+ if (i === j) continue;
1543
+ unique = q.b.bool.and(unique, q.b.bool.not(q.b.bool.and(q.load(sourceEnabled, j), q.b.int.cmp("eq", root, q.load(label, other.node)))));
1544
+ }
1545
+ q.b.state.store(accumulator, q.f(0));
1546
+ for (const [j, resistor] of network.resistors.entries()) {
1547
+ const a = q.load(label, resistor.a);
1548
+ const b = q.load(label, resistor.b);
1549
+ const outward = q.b.select(q.b.int.cmp("eq", root, a), q.load(candidateCurrent, j), q.f(0));
1550
+ const inward = q.b.select(q.b.int.cmp("eq", root, b), q.load(candidateCurrent, j), q.f(0));
1551
+ q.b.state.store(accumulator, q.b.float.add(q.b.state.load(accumulator), q.b.float.sub(outward, inward)));
1552
+ }
1553
+ const enabled = q.load(sourceEnabled, i);
1554
+ const value = q.b.select(q.b.bool.and(enabled, unique), q.b.state.load(accumulator), q.f(0));
1555
+ yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(2, i));
1556
+ q.store(candidateSourceCurrent, i, value);
1557
+ q.store(candidateSourceState, i, q.b.select(q.b.bool.or(q.b.bool.not(enabled), unique), q.b.const("u8", 0), q.b.const("u8", 2)));
1558
+ }
1559
+ for (const [i, contact] of network.contacts.entries()) {
1560
+ q.store(candidateContactCurrent, i, q.f(0));
1561
+ q.store(candidateContactState, i, q.b.const("u8", 0));
1562
+ yield* q.when(q.load(contactClosed, i), function* () {
1563
+ yield* q.loop(n, function(node) {
1564
+ q.store(contactSide, node, q.b.int.cmp("eq", node, q.u(contact.a)));
1565
+ });
1566
+ yield* q.loop(n, function* () {
1567
+ for (const [j, edge] of network.contacts.entries()) {
1568
+ if (i === j) continue;
1569
+ yield* q.when(q.load(contactClosed, j), function() {
1570
+ const connected = q.b.bool.or(q.load(contactSide, edge.a), q.load(contactSide, edge.b));
1571
+ q.store(contactSide, edge.a, connected);
1572
+ q.store(contactSide, edge.b, connected);
1573
+ });
1574
+ }
1575
+ });
1576
+ const root = q.load(label, contact.a);
1577
+ let leftSource = q.b.const("bool", false);
1578
+ let rightSource = q.b.const("bool", false);
1579
+ for (const [j, source] of network.sources.entries()) {
1580
+ const same = q.b.bool.and(q.load(sourceEnabled, j), q.b.int.cmp("eq", root, q.load(label, source.node)));
1581
+ leftSource = q.b.bool.or(leftSource, q.b.bool.and(same, q.load(contactSide, source.node)));
1582
+ rightSource = q.b.bool.or(rightSource, q.b.bool.and(same, q.b.bool.not(q.load(contactSide, source.node))));
1583
+ }
1584
+ let leftOut = q.f(0);
1585
+ let rightOut = q.f(0);
1586
+ const right = (node) => q.b.bool.and(q.b.int.cmp("eq", root, q.load(label, node)), q.b.bool.not(q.load(contactSide, node)));
1587
+ for (const [j, resistor] of network.resistors.entries()) {
1588
+ const value = q.load(candidateCurrent, j);
1589
+ const netOut = (a, b) => q.b.float.sub(q.b.select(a, value, q.f(0)), q.b.select(b, value, q.f(0)));
1590
+ leftOut = q.b.float.add(leftOut, netOut(q.load(contactSide, resistor.a), q.load(contactSide, resistor.b)));
1591
+ rightOut = q.b.float.add(rightOut, netOut(right(resistor.a), right(resistor.b)));
1592
+ }
1593
+ const unique = q.b.bool.and(q.b.bool.not(q.load(contactSide, contact.b)), q.b.bool.not(q.b.bool.and(leftSource, rightSource)));
1594
+ const value = q.b.select(leftSource, rightOut, q.b.float.sub(q.f(0), leftOut));
1595
+ yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(3, i));
1596
+ q.store(candidateContactCurrent, i, q.b.select(unique, value, q.f(0)));
1597
+ q.store(candidateContactState, i, q.b.select(unique, q.b.const("u8", 0), q.b.const("u8", 2)));
1598
+ });
1599
+ }
1600
+ yield* q.loop(n, function(node) {
1601
+ const root = q.load(label, node);
1602
+ q.store(voltage, node, q.load(candidate, root));
1603
+ q.store(voltageState, node, q.b.select(q.load(reachable, root), q.b.const("u8", 0), q.b.const("u8", 1)));
1604
+ });
1605
+ for (const [i] of network.resistors.entries()) {
1606
+ q.store(current, i, q.load(candidateCurrent, i));
1607
+ q.store(currentState, i, q.b.const("u8", 0));
1608
+ }
1609
+ for (const [i] of network.sources.entries()) {
1610
+ q.store(sourceCurrent, i, q.load(candidateSourceCurrent, i));
1611
+ q.store(sourceCurrentState, i, q.load(candidateSourceState, i));
1612
+ }
1613
+ for (const [i] of network.contacts.entries()) {
1614
+ q.store(contactCurrent, i, q.load(candidateContactCurrent, i));
1615
+ q.store(contactCurrentState, i, q.load(candidateContactState, i));
1616
+ }
1617
+ q.b.state.store(solvedRhs, q.b.state.load(rhsVersion));
1618
+ q.b.state.store(hasSolution, q.b.const("bool", true));
1619
+ for (const observer of onPublish) q.b.call(observer, []);
1620
+ q.b.return([]);
1621
+ });
1622
+ });
1623
+ });
1624
+ return Object.freeze({
1625
+ solve,
1626
+ resistance,
1627
+ resistorEnabled,
1628
+ sourceVoltage,
1629
+ sourceEnabled,
1630
+ contactClosed,
1631
+ voltage,
1632
+ voltageState,
1633
+ current,
1634
+ currentState,
1635
+ sourceCurrent,
1636
+ sourceCurrentState,
1637
+ contactCurrent,
1638
+ contactCurrentState,
1639
+ fault,
1640
+ faultTargetKind,
1641
+ faultTargetIndex,
1642
+ factorizations,
1643
+ groupRebuilds,
1644
+ groupSolves,
1645
+ topologyVersion,
1646
+ matrixVersion,
1647
+ rhsVersion,
1648
+ invalidate
1649
+ });
1650
+ }
1651
+ function validateNetwork(network) {
1652
+ if (!Number.isSafeInteger(network.nodes) || network.nodes < 1) throw new Error("A resistive network needs a positive node count");
1653
+ const node = (index) => {
1654
+ if (!Number.isSafeInteger(index) || index < 0 || index >= network.nodes) throw new Error(`Invalid node ${index}`);
1655
+ };
1656
+ for (const resistor of network.resistors) {
1657
+ node(resistor.a);
1658
+ node(resistor.b);
1659
+ if (!Number.isFinite(resistor.resistance) || resistor.resistance <= 0 || typeof resistor.enabled !== "boolean") throw new Error("Invalid initial resistor state");
1660
+ }
1661
+ for (const source of network.sources) {
1662
+ node(source.node);
1663
+ if (!Number.isFinite(source.voltage) || typeof source.enabled !== "boolean") throw new Error("Invalid initial source state");
1664
+ }
1665
+ for (const contact of network.contacts) {
1666
+ node(contact.a);
1667
+ node(contact.b);
1668
+ if (typeof contact.closed !== "boolean") throw new Error("Invalid initial contact state");
1669
+ }
1670
+ }
1671
+ //#endregion
1672
+ //#region src/unified-ir/compiler/electrical-operations.ts
1673
+ /** Compiler-owned lowering helpers; none of their private storage is given to devices. */
1674
+ function createElectricalOperations(module, allocation, interpretation, prefix, floatingSeed = 0) {
1675
+ if (!Number.isInteger(floatingSeed) || floatingSeed < 0 || floatingSeed > 4294967295) throw new Error("floatingSeed must be a u32");
1676
+ if (interpretation !== "two-state" && interpretation !== "retain-in-band") throw new Error("Invalid electrical interpretation");
1677
+ const inputs = module.func(`${prefix}_interpret_inputs`, {
1678
+ params: [],
1679
+ results: []
1680
+ });
1681
+ const solver = generateResistiveSolver(module, allocation.network, prefix, [inputs]);
1682
+ const allPins = [...allocation.pins].flatMap(([deviceId, pins]) => [...pins].map(([name, pin]) => ({
1683
+ deviceId,
1684
+ name,
1685
+ pin
1686
+ })));
1687
+ const size = Math.max(1, allPins.length);
1688
+ const mode = module.array(`${prefix}_mode`, "u8", Array(size).fill(PIN_MODE.highZ));
1689
+ const enabled = module.array(`${prefix}_output_enabled`, "bool", Array(size).fill(false));
1690
+ const digital = module.array(`${prefix}_digital_intent`, "bool", Array(size).fill(false));
1691
+ const digitalReady = module.array(`${prefix}_digital_ready`, "bool", Array(size).fill(false));
1692
+ const voltageReady = module.array(`${prefix}_voltage_ready`, "bool", Array(size).fill(false));
1693
+ const memory = module.array(`${prefix}_input_memory`, "bool", Array(size).fill(false));
1694
+ const sampled = module.array(`${prefix}_digital_sample`, "bool", Array(size).fill(false));
1695
+ const index = (b, i) => b.const("u32", i);
1696
+ const badResource = (message) => {
1697
+ throw new UnifiedIRCompilerError("invalid-input", message);
1698
+ };
1699
+ const running = (b, emit) => {
1700
+ const body = b.block([]);
1701
+ const done = b.block([]);
1702
+ b.branch(b.int.cmp("eq", b.state.load(solver.fault), b.const("u8", 0)), {
1703
+ target: body,
1704
+ args: []
1705
+ }, {
1706
+ target: done,
1707
+ args: []
1708
+ });
1709
+ b.at(body, emit);
1710
+ b.at(done, (b) => b.return([]));
1711
+ };
1712
+ const checked = (b, valid, target, commit) => {
1713
+ const yes = b.block([]);
1714
+ const no = b.block([]);
1715
+ b.branch(valid, {
1716
+ target: yes,
1717
+ args: []
1718
+ }, {
1719
+ target: no,
1720
+ args: []
1721
+ });
1722
+ b.at(yes, commit);
1723
+ b.at(no, (b) => {
1724
+ b.state.store(solver.fault, b.const("u8", RESISTIVE_FAULT.invalidParameter));
1725
+ b.state.store(solver.faultTargetKind, b.const("u8", target.kind));
1726
+ b.state.store(solver.faultTargetIndex, target.index);
1727
+ b.return([]);
1728
+ });
1729
+ };
1730
+ const complete = (b, changed, kind, otherwise = (b) => b.return([])) => {
1731
+ const yes = b.block([]);
1732
+ const no = b.block([]);
1733
+ b.branch(changed, {
1734
+ target: yes,
1735
+ args: []
1736
+ }, {
1737
+ target: no,
1738
+ args: []
1739
+ });
1740
+ b.at(yes, (b) => {
1741
+ b.call(solver.invalidate[kind], []);
1742
+ b.return([]);
1743
+ });
1744
+ b.at(no, otherwise);
1745
+ };
1746
+ const loop = (b, count, emit, done) => {
1747
+ const header = b.block(["u32"]);
1748
+ const body = b.block(["u32"]);
1749
+ const exit = b.block([]);
1750
+ b.jump(header, [b.const("u32", 0)]);
1751
+ b.at(header, (b, [i]) => b.branch(b.int.cmp("lt", i, count), {
1752
+ target: body,
1753
+ args: [i]
1754
+ }, {
1755
+ target: exit,
1756
+ args: []
1757
+ }));
1758
+ b.at(body, (b, [i]) => {
1759
+ emit(b, i);
1760
+ b.jump(header, [b.int.add(i, b.const("u32", 1))]);
1761
+ });
1762
+ b.at(exit, done);
1763
+ };
1764
+ const ensure = module.func(`${prefix}_ensure`, {
1765
+ params: [],
1766
+ results: []
1767
+ });
1768
+ ensure.body((b) => running(b, (b) => {
1769
+ b.call(solver.solve, []);
1770
+ b.return([]);
1771
+ }));
1772
+ const clock = module.array(`${prefix}_time`, "u32", [0, 0]);
1773
+ const timeStep = module.array(`${prefix}_time_step`, "u32", [1, 0]);
1774
+ const advanceTime = module.func(`${prefix}_advance_time`, {
1775
+ params: [],
1776
+ results: []
1777
+ });
1778
+ const analogInputs = /* @__PURE__ */ new Map();
1779
+ const analogRequests = /* @__PURE__ */ new Map();
1780
+ let finalized = false;
1781
+ const finalize = () => {
1782
+ if (finalized) return;
1783
+ finalized = true;
1784
+ for (const [id, sample] of analogRequests) {
1785
+ const { deviceId, name, pin } = allPins[id];
1786
+ analogInputs.set(id, createFloatingInput(module, solver, clock, `${prefix}_analog_${id}`, floatingSeed, deviceId, name, pin.node, pin.input.reference, sample));
1787
+ }
1788
+ advanceTime.body((b) => {
1789
+ if (analogInputs.size === 0) {
1790
+ b.return([]);
1791
+ return;
1792
+ }
1793
+ const previous = b.array.load(clock, index(b, 0));
1794
+ const low = b.int.add(previous, b.array.load(timeStep, index(b, 0)));
1795
+ const carry = b.select(b.int.cmp("lt", low, previous), index(b, 1), index(b, 0));
1796
+ const high = b.int.add(b.int.add(b.array.load(clock, index(b, 1)), b.array.load(timeStep, index(b, 1))), carry);
1797
+ b.array.store(clock, index(b, 0), low);
1798
+ b.array.store(clock, index(b, 1), b.int.and(high, index(b, 2097151)));
1799
+ b.return([]);
1800
+ });
1801
+ inputs.body((b) => {
1802
+ allPins.forEach(({ pin }, id) => {
1803
+ const analog = analogInputs.get(id);
1804
+ if (analog !== void 0) b.call(analog.update, []);
1805
+ if (pin.input === void 0) return;
1806
+ const ref = pin.input.reference;
1807
+ const supply = b.array.load(solver.sourceVoltage, index(b, ref));
1808
+ const value = b.array.load(solver.voltage, index(b, pin.node));
1809
+ const low = b.float.cmp("le", value, b.float.mul(supply, b.const("f64", pin.input.low)));
1810
+ const high = b.float.cmp("ge", value, b.float.mul(supply, b.const("f64", pin.input.high)));
1811
+ const ready = b.bool.and(b.array.load(solver.sourceEnabled, index(b, ref)), b.bool.and(b.float.cmp("gt", supply, b.const("f64", 0)), b.int.cmp("eq", b.array.load(solver.voltageState, index(b, pin.node)), b.const("u8", 0))));
1812
+ const remembered = b.array.load(memory, index(b, id));
1813
+ const next = b.select(low, b.const("bool", false), b.select(high, b.const("bool", true), remembered));
1814
+ b.array.store(memory, index(b, id), b.select(ready, next, remembered));
1815
+ b.array.store(sampled, index(b, id), b.bool.and(ready, interpretation === "two-state" ? high : next));
1816
+ });
1817
+ b.return([]);
1818
+ });
1819
+ };
1820
+ const refresh = /* @__PURE__ */ new Map();
1821
+ const pinFunctions = /* @__PURE__ */ new Map();
1822
+ allPins.forEach(({ pin }, id) => {
1823
+ if (pin.drive === void 0) return;
1824
+ const drive = pin.drive;
1825
+ const recompute = module.func(`${prefix}_pin_${id}_refresh`, {
1826
+ params: [],
1827
+ results: ["bool"]
1828
+ });
1829
+ refresh.set(id, recompute);
1830
+ recompute.body((b) => {
1831
+ const at = b.const("u32", id);
1832
+ const active = b.array.load(enabled, at);
1833
+ const selection = b.array.load(mode, at);
1834
+ const is = (which) => b.int.cmp("eq", selection, b.const("u8", which));
1835
+ const pushPull = is(PIN_MODE.pushPull);
1836
+ const digitalActive = b.bool.and(active, b.array.load(digitalReady, at));
1837
+ const level = b.array.load(digital, at);
1838
+ const high = b.bool.and(digitalActive, b.bool.and(pushPull, level));
1839
+ const low = b.bool.and(digitalActive, b.bool.and(b.bool.or(pushPull, is(PIN_MODE.openDrain)), b.bool.not(level)));
1840
+ let changed = b.const("bool", false);
1841
+ const update = (branch, value) => {
1842
+ changed = b.bool.or(changed, b.bool.xor(b.array.load(solver.resistorEnabled, b.const("u32", branch)), value));
1843
+ b.array.store(solver.resistorEnabled, b.const("u32", branch), value);
1844
+ };
1845
+ update(drive.high, high);
1846
+ update(drive.low, low);
1847
+ if (drive.analog !== void 0) update(drive.analog.resistor, b.bool.and(active, b.bool.and(is(PIN_MODE.analog), b.array.load(voltageReady, at))));
1848
+ b.return([changed]);
1849
+ });
1850
+ const setMode = module.func(`${prefix}_pin_${id}_mode`, {
1851
+ params: ["u8"],
1852
+ results: []
1853
+ });
1854
+ setMode.body((b, [value]) => running(b, (b) => {
1855
+ b.array.store(mode, index(b, id), value);
1856
+ const [changed] = b.call(recompute, []);
1857
+ return complete(b, changed, "matrix");
1858
+ }));
1859
+ const setEnabled = module.func(`${prefix}_pin_${id}_enable`, {
1860
+ params: ["bool"],
1861
+ results: []
1862
+ });
1863
+ setEnabled.body((b, [value]) => running(b, (b) => {
1864
+ b.array.store(enabled, index(b, id), value);
1865
+ const [changed] = b.call(recompute, []);
1866
+ return complete(b, changed, "matrix");
1867
+ }));
1868
+ const writeDigital = module.func(`${prefix}_pin_${id}_digital`, {
1869
+ params: ["bool"],
1870
+ results: []
1871
+ });
1872
+ writeDigital.body((b, [value]) => running(b, (b) => {
1873
+ b.array.store(digital, index(b, id), value);
1874
+ b.array.store(digitalReady, index(b, id), b.const("bool", true));
1875
+ const [changed] = b.call(recompute, []);
1876
+ return complete(b, changed, "matrix");
1877
+ }));
1878
+ const writeVoltage = module.func(`${prefix}_pin_${id}_voltage`, {
1879
+ params: ["f64"],
1880
+ results: []
1881
+ });
1882
+ writeVoltage.body((b, [value]) => running(b, (b) => checked(b, b.float.isFinite(value), {
1883
+ kind: 1,
1884
+ index: index(b, drive.analog?.resistor ?? drive.high)
1885
+ }, (b) => {
1886
+ if (drive.analog === void 0) {
1887
+ b.return([]);
1888
+ return;
1889
+ }
1890
+ const at = index(b, drive.analog.source);
1891
+ const changedRhs = b.float.cmp("ne", b.array.load(solver.sourceVoltage, at), value);
1892
+ b.array.store(solver.sourceVoltage, at, value);
1893
+ b.array.store(voltageReady, index(b, id), b.const("bool", true));
1894
+ const [changedMatrix] = b.call(recompute, []);
1895
+ return complete(b, changedMatrix, "matrix", (b) => complete(b, changedRhs, "rhs"));
1896
+ })));
1897
+ pinFunctions.set(id, {
1898
+ setMode,
1899
+ setEnabled,
1900
+ writeDigital,
1901
+ writeVoltage
1902
+ });
1903
+ });
1904
+ const pinIds = /* @__PURE__ */ new Map();
1905
+ allPins.forEach(({ deviceId, name }, id) => {
1906
+ let pins = pinIds.get(deviceId);
1907
+ if (pins === void 0) {
1908
+ pins = /* @__PURE__ */ new Map();
1909
+ pinIds.set(deviceId, pins);
1910
+ }
1911
+ pins.set(name, id);
1912
+ });
1913
+ for (const deviceId of allocation.pins.keys()) if (!pinIds.has(deviceId)) pinIds.set(deviceId, /* @__PURE__ */ new Map());
1914
+ const deviceBinders = /* @__PURE__ */ new Map();
1915
+ for (const [deviceId, ids] of pinIds) {
1916
+ const ordinaryResistors = allocation.resistors.get(deviceId);
1917
+ const contacts = allocation.contacts.get(deviceId);
1918
+ const queueSize = Math.max(1, ids.size, ordinaryResistors.size, contacts.size);
1919
+ const tag = `${prefix}_device_${deviceBinders.size}`;
1920
+ const queueId = module.array(`${tag}_ids`, "u32", Array(queueSize).fill(0));
1921
+ const queueNumber = module.array(`${tag}_numbers`, "f64", Array(queueSize).fill(1));
1922
+ const queueBool = module.array(`${tag}_flags`, "bool", Array(queueSize).fill(false));
1923
+ const valid = module.state(`${tag}_valid`, "bool", true);
1924
+ const changed = module.state(`${tag}_changed`, "bool", false);
1925
+ const positive = (b, value) => b.bool.and(b.float.isFinite(value), b.float.cmp("gt", value, b.const("f64", 0)));
1926
+ const applyResistors = module.func(`${tag}_resistances`, {
1927
+ params: ["u32"],
1928
+ results: []
1929
+ });
1930
+ applyResistors.body((b, [count]) => running(b, (b) => {
1931
+ b.state.store(valid, b.const("bool", true));
1932
+ return loop(b, count, (b, i) => {
1933
+ const accepted = positive(b, b.array.load(queueNumber, i));
1934
+ b.state.store(solver.faultTargetIndex, b.select(accepted, b.state.load(solver.faultTargetIndex), b.array.load(queueId, i)));
1935
+ b.state.store(valid, b.bool.and(b.state.load(valid), accepted));
1936
+ }, (b) => checked(b, b.state.load(valid), {
1937
+ kind: 1,
1938
+ index: b.state.load(solver.faultTargetIndex)
1939
+ }, (b) => {
1940
+ b.state.store(changed, b.const("bool", false));
1941
+ return loop(b, count, (b, i) => {
1942
+ const target = b.array.load(queueId, i);
1943
+ const value = b.array.load(queueNumber, i);
1944
+ b.state.store(changed, b.bool.or(b.state.load(changed), b.float.cmp("ne", b.array.load(solver.resistance, target), value)));
1945
+ b.array.store(solver.resistance, target, value);
1946
+ }, (b) => complete(b, b.state.load(changed), "matrix"));
1947
+ }));
1948
+ }));
1949
+ const applyConnections = module.func(`${tag}_contacts`, {
1950
+ params: ["u32"],
1951
+ results: []
1952
+ });
1953
+ applyConnections.body((b, [count]) => running(b, (b) => {
1954
+ b.state.store(changed, b.const("bool", false));
1955
+ return loop(b, count, (b, i) => {
1956
+ const target = b.array.load(queueId, i);
1957
+ const value = b.array.load(queueBool, i);
1958
+ b.state.store(changed, b.bool.or(b.state.load(changed), b.bool.xor(b.array.load(solver.contactClosed, target), value)));
1959
+ b.array.store(solver.contactClosed, target, value);
1960
+ }, (b) => complete(b, b.state.load(changed), "topology"));
1961
+ }));
1962
+ const writeDigitalGroup = module.func(`${tag}_digital_group`, {
1963
+ params: ["u32"],
1964
+ results: []
1965
+ });
1966
+ writeDigitalGroup.body((b, [count]) => running(b, (b) => loop(b, count, (b, i) => {
1967
+ const target = b.array.load(queueId, i);
1968
+ b.array.store(digital, target, b.array.load(queueBool, i));
1969
+ b.array.store(digitalReady, target, b.const("bool", true));
1970
+ }, (b) => {
1971
+ let changed = b.const("bool", false);
1972
+ for (const id of ids.values()) {
1973
+ const recompute = refresh.get(id);
1974
+ if (recompute === void 0) continue;
1975
+ const [value] = b.call(recompute, []);
1976
+ changed = b.bool.or(changed, value);
1977
+ }
1978
+ return complete(b, changed, "matrix");
1979
+ })));
1980
+ const setResistorEnabled = module.func(`${tag}_resistor_enable`, {
1981
+ params: ["u32", "bool"],
1982
+ results: []
1983
+ });
1984
+ setResistorEnabled.body((b, [target, value]) => running(b, (b) => {
1985
+ const changed = b.bool.xor(b.array.load(solver.resistorEnabled, target), value);
1986
+ b.array.store(solver.resistorEnabled, target, value);
1987
+ return complete(b, changed, "matrix");
1988
+ }));
1989
+ const setPull = /* @__PURE__ */ new Map();
1990
+ for (const id of ids.values()) {
1991
+ const bias = allPins[id].pin.bias;
1992
+ if (bias === void 0) continue;
1993
+ const fn = module.func(`${prefix}_pin_${id}_pull`, {
1994
+ params: ["u8"],
1995
+ results: []
1996
+ });
1997
+ fn.body((b, [value]) => running(b, (b) => {
1998
+ const up = b.int.cmp("eq", value, b.const("u8", 1));
1999
+ const down = b.int.cmp("eq", value, b.const("u8", 2));
2000
+ const changed = b.bool.or(b.bool.xor(b.array.load(solver.resistorEnabled, index(b, bias.up)), up), b.bool.xor(b.array.load(solver.resistorEnabled, index(b, bias.down)), down));
2001
+ b.array.store(solver.resistorEnabled, index(b, bias.up), up);
2002
+ b.array.store(solver.resistorEnabled, index(b, bias.down), down);
2003
+ return complete(b, changed, "matrix");
2004
+ }));
2005
+ setPull.set(id, fn);
2006
+ }
2007
+ deviceBinders.set(deviceId, (b, globalIds) => {
2008
+ const lookup = (names, values, resources) => {
2009
+ if (names.length === 0 || names.length !== values.length || new Set(names).size !== names.length) badResource(`Invalid atomic patch for "${deviceId}"`);
2010
+ return names.map((name) => resources.get(name) ?? badResource(`Unknown electrical resource "${deviceId}.${name}"`));
2011
+ };
2012
+ const patch = (targets, values, numeric, fn) => {
2013
+ targets.forEach((target, i) => {
2014
+ b.array.store(queueId, index(b, i), index(b, target));
2015
+ if (numeric) b.array.store(queueNumber, index(b, i), values[i]);
2016
+ else b.array.store(queueBool, index(b, i), values[i]);
2017
+ });
2018
+ b.call(fn, [index(b, targets.length)]);
2019
+ };
2020
+ const handles = /* @__PURE__ */ new Map();
2021
+ for (const [name, id] of ids) {
2022
+ const description = allPins[id].pin;
2023
+ const functions = () => pinFunctions.get(id) ?? badResource(`Pin "${deviceId}.${name}" has no drive capability`);
2024
+ const handle = Object.freeze({
2025
+ name,
2026
+ globalId: globalIds?.get(name) ?? id,
2027
+ configure(selection) {
2028
+ if (!Object.values(PIN_MODE).includes(selection)) badResource(`Invalid pin mode ${selection}`);
2029
+ if (selection === PIN_MODE.analog && description.drive?.analog === void 0) badResource(`Pin "${deviceId}.${name}" has no analog drive capability`);
2030
+ if (selection === PIN_MODE.highZ && description.drive === void 0) return;
2031
+ b.call(functions().setMode, [b.const("u8", selection)]);
2032
+ },
2033
+ setOutputEnabled(value) {
2034
+ b.call(functions().setEnabled, [value]);
2035
+ },
2036
+ setPull(selection) {
2037
+ if (![
2038
+ "none",
2039
+ "up",
2040
+ "down"
2041
+ ].includes(selection)) badResource(`Invalid pull ${selection}`);
2042
+ const fn = setPull.get(id) ?? (selection === "none" ? void 0 : badResource(`Pin "${deviceId}.${name}" has no bias capability`));
2043
+ if (fn === void 0) return;
2044
+ b.call(fn, [b.const("u8", selection === "none" ? 0 : selection === "up" ? 1 : 2)]);
2045
+ },
2046
+ writeDigital(value) {
2047
+ b.call(functions().writeDigital, [value]);
2048
+ },
2049
+ writeVoltage(value) {
2050
+ if (description.drive?.analog === void 0) badResource(`Pin "${deviceId}.${name}" has no analog drive capability`);
2051
+ b.call(functions().writeVoltage, [value]);
2052
+ },
2053
+ sampleDigital() {
2054
+ if (description.input === void 0) badResource(`Pin "${deviceId}.${name}" has no input capability`);
2055
+ b.call(ensure, []);
2056
+ return b.array.load(sampled, index(b, id));
2057
+ },
2058
+ sampleVoltage() {
2059
+ if (description.input === void 0) badResource(`Pin "${deviceId}.${name}" has no input capability`);
2060
+ let sample = analogRequests.get(id);
2061
+ if (sample === void 0) {
2062
+ if (finalized) badResource("Analog sampling must be declared before electrical finalization");
2063
+ sample = module.func(`${prefix}_analog_${id}_sample`, {
2064
+ params: [],
2065
+ results: ["f64"]
2066
+ });
2067
+ analogRequests.set(id, sample);
2068
+ }
2069
+ b.call(ensure, []);
2070
+ return b.call(sample, [])[0];
2071
+ },
2072
+ readDrivenDigital() {
2073
+ functions();
2074
+ return b.array.load(digital, index(b, id));
2075
+ }
2076
+ });
2077
+ handles.set(name, handle);
2078
+ }
2079
+ return Object.freeze({
2080
+ pins: Object.freeze([...handles.values()]),
2081
+ outputs: Object.freeze([...handles].filter(([name]) => allPins[ids.get(name)].pin.drive !== void 0).map(([, handle]) => handle)),
2082
+ pin(name) {
2083
+ return handles.get(name) ?? badResource(`Unknown pin "${deviceId}.${name}"`);
2084
+ },
2085
+ resistor(name) {
2086
+ const target = ordinaryResistors.get(name) ?? badResource(`Unknown resistor "${deviceId}.${name}"`);
2087
+ return Object.freeze({
2088
+ setResistance(value) {
2089
+ patch([target], [value], true, applyResistors);
2090
+ },
2091
+ setEnabled(value) {
2092
+ b.call(setResistorEnabled, [index(b, target), value]);
2093
+ },
2094
+ sampleCurrent() {
2095
+ b.call(ensure, []);
2096
+ return b.array.load(solver.current, index(b, target));
2097
+ }
2098
+ });
2099
+ },
2100
+ writeDigitalGroup(names, values) {
2101
+ const targets = lookup(names, values, ids);
2102
+ for (const id of targets) if (!pinFunctions.has(id)) badResource(`Pin "${allPins[id].name}" has no drive capability`);
2103
+ patch(targets, values, false, writeDigitalGroup);
2104
+ },
2105
+ applyResistors(names, values) {
2106
+ patch(lookup(names, values, ordinaryResistors), values, true, applyResistors);
2107
+ },
2108
+ applyConnections(names, values) {
2109
+ patch(lookup(names, values, contacts), values, false, applyConnections);
2110
+ }
2111
+ });
2112
+ });
2113
+ }
2114
+ return Object.freeze({
2115
+ solver,
2116
+ ensure,
2117
+ clock,
2118
+ timeStep,
2119
+ advanceTime,
2120
+ finalize,
2121
+ digitalSample: sampled,
2122
+ digitalIntent: digital,
2123
+ pinIndices: new Map(allPins.map(({ deviceId, name }, index) => [`${deviceId}.${name}`, index])),
2124
+ bindDevice(deviceId, builder, globalIds) {
2125
+ return (deviceBinders.get(deviceId) ?? badResource(`Unknown electrical device "${deviceId}"`))(builder, globalIds);
2126
+ }
2127
+ });
2128
+ }
2129
+ //#endregion
2130
+ //#region src/unified-ir/compiler/electrical-compilation.ts
2131
+ var circuits = /* @__PURE__ */ new WeakMap();
2132
+ var electricalCompilationOf = (circuit) => circuits.get(circuit);
2133
+ function retainElectricalCompilation(circuit, electrical) {
2134
+ circuits.set(circuit, electrical);
2135
+ }
2136
+ /** Keeps prepared resources and solver storage out of the public compiled description. */
2137
+ function prepareElectricalCompilation(module, devices, connections, options) {
2138
+ const fail = (message) => {
2139
+ throw new UnifiedIRCompilerError("invalid-input", message);
2140
+ };
2141
+ if ("rails" in options) fail("Unsupported boolean rails; declare explicit voltage sources");
2142
+ if (options.interpretation !== "two-state" && options.interpretation !== "retain-in-band") fail("Resistive circuits require an explicit digital interpretation");
2143
+ if (options.floatingSeed !== void 0 && (!Number.isInteger(options.floatingSeed) || options.floatingSeed < 0 || options.floatingSeed > 4294967295)) fail("floatingSeed must be a u32");
2144
+ const sources = options.sources ?? {};
2145
+ if (sources === null || typeof sources !== "object" || Array.isArray(sources)) fail("Voltage sources must be an object");
2146
+ for (const [id, source] of Object.entries(sources)) if (!id || id === "GND" || source === null || typeof source !== "object" || !Number.isFinite(source.voltage)) fail(`Invalid voltage source "${id}"`);
2147
+ const prepared = devices.map((device) => {
2148
+ const { description } = device;
2149
+ if (typeof description.factory !== "function") fail(`Device "${device.id}" needs a paired electrical factory`);
2150
+ const properties = device.properties === void 0 ? {} : device.properties;
2151
+ if (properties === null || typeof properties !== "object" || Array.isArray(properties)) fail(`Invalid properties for device "${device.id}"`);
2152
+ const result = prepareElectricalDevice({
2153
+ ...description,
2154
+ pins: description.pins instanceof Map ? Object.fromEntries(description.pins) : description.pins
2155
+ }, properties, description.factory);
2156
+ const implementation = result.implementation;
2157
+ if (implementation !== void 0) {
2158
+ if (implementation === null || typeof implementation !== "object" || Array.isArray(implementation)) fail(`Device "${device.id}" factory must return behavior hooks or undefined`);
2159
+ for (const [name, callback] of Object.entries(implementation)) if (![
2160
+ "initialize",
2161
+ "tick",
2162
+ "update",
2163
+ "kernel",
2164
+ "applyInputs",
2165
+ "flushOutputs"
2166
+ ].includes(name) || callback !== void 0 && typeof callback !== "function") fail(`Invalid factory behavior "${device.id}.${name}"`);
2167
+ }
2168
+ const phases = implementation === void 0 ? description.behaviors : {
2169
+ ...implementation.initialize === void 0 ? {} : { initialize: implementation.initialize },
2170
+ ...implementation.tick === void 0 ? {} : { tick: implementation.tick },
2171
+ ...implementation.update === void 0 ? {} : { update: implementation.update }
2172
+ };
2173
+ if (phases !== void 0) {
2174
+ for (const [phase, callback] of Object.entries(phases)) if (![
2175
+ "initialize",
2176
+ "tick",
2177
+ "update"
2178
+ ].includes(phase) || callback !== void 0 && typeof callback !== "function") fail(`Invalid factory behavior "${device.id}.${phase}"`);
2179
+ }
2180
+ const hasPhases = phases !== void 0 && Object.values(phases).some((value) => value !== void 0);
2181
+ if (implementation !== void 0 && description.behaviors !== void 0) fail(`Device "${device.id}" declares both factory and static behaviors`);
2182
+ if (implementation?.kernel !== void 0 && description.kernel !== void 0) fail(`Device "${device.id}" declares two kernels`);
2183
+ const kernel = implementation?.kernel ?? description.kernel;
2184
+ if (hasPhases && kernel !== void 0) fail(`Device "${device.id}" declares both behavior hooks and a kernel`);
2185
+ return {
2186
+ id: device.id,
2187
+ prepared: result,
2188
+ device: {
2189
+ ...device,
2190
+ properties: result.properties,
2191
+ description: {
2192
+ ...description,
2193
+ ...phases === void 0 || !hasPhases ? {} : { behaviors: phases },
2194
+ ...kernel === void 0 ? {} : { kernel },
2195
+ ...implementation?.applyInputs === void 0 ? {} : { applyInputs: implementation.applyInputs },
2196
+ ...implementation?.flushOutputs === void 0 ? {} : { flushOutputs: implementation.flushOutputs }
2197
+ }
2198
+ }
2199
+ };
2200
+ });
2201
+ const endpoint = (name) => {
2202
+ if (name === "GND" || Object.hasOwn(sources, name)) return { source: name };
2203
+ const dot = name.indexOf(".");
2204
+ if (dot <= 0 || dot === name.length - 1) return fail(`Unknown electrical endpoint "${name}"`);
2205
+ return {
2206
+ device: name.slice(0, dot),
2207
+ pin: name.slice(dot + 1)
2208
+ };
2209
+ };
2210
+ const allocation = allocateElectricalNetwork(prepared, sources, connections.map(({ from, to }) => [endpoint(from), endpoint(to)]));
558
2211
  return {
559
- name: definition.name,
560
- ref
2212
+ devices: prepared.map(({ device }) => device),
2213
+ allocation,
2214
+ operations: createElectricalOperations(module, allocation, options.interpretation, "electrical", options.floatingSeed)
561
2215
  };
562
2216
  }
563
2217
  //#endregion
@@ -578,99 +2232,81 @@ var DEFAULT_ENTRY_POINT_NAMES = Object.freeze({
578
2232
  *
579
2233
  * unified_tick: // one simulation step
580
2234
  * drive1_tick() // drivers publish their outputs
581
- * solve_net_0() // the electrical network resolves
2235
+ * electrical_ensure() // solve only if the network changed
582
2236
  * sink1_update() // loads observe the solved inputs
583
2237
  *
584
2238
  * unified_tick_batch(count): // the same step, looped inside the IR
585
2239
  * for i in 0 .. count { <step> }
586
2240
  * ```
587
2241
  *
588
- * Devices run in dependency order: a device that drives a net executes before
589
- * every device that senses it. Feedback loops fall back to declaration order
590
- * after the topological prefix, so clock cycles stay valid.
2242
+ * Devices run in declaration order, with all tick phases before update phases.
2243
+ * Typed electrical sampling ensures pending network changes are solved.
591
2244
  */
592
2245
  var MainLoopGenerator = class {
2246
+ electrical;
593
2247
  module;
594
- constructor(module) {
2248
+ constructor(module, electrical) {
2249
+ this.electrical = electrical;
595
2250
  this.module = module;
596
2251
  }
597
- /** Stable topological order of the devices; cycles fall back to declaration order. */
598
- order(entries, netlist) {
599
- const indexById = new Map(entries.map((entry, index) => [entry.deviceId, index]));
600
- const consumers = /* @__PURE__ */ new Map();
601
- const indegree = new Map(entries.map((entry) => [entry.deviceId, 0]));
602
- for (const net of netlist.nets) {
603
- const driverDevices = new Set(net.drivers.map((pin) => pin.deviceId));
604
- const sinkDevices = new Set(net.sinks.map((pin) => pin.deviceId));
605
- for (const driver of driverDevices) for (const sink of sinkDevices) {
606
- if (driver === sink) continue;
607
- let targets = consumers.get(driver);
608
- if (targets === void 0) {
609
- targets = /* @__PURE__ */ new Set();
610
- consumers.set(driver, targets);
611
- }
612
- if (targets.has(sink)) continue;
613
- targets.add(sink);
614
- indegree.set(sink, (indegree.get(sink) ?? 0) + 1);
615
- }
616
- }
617
- const ready = new Set(entries.filter((entry) => (indegree.get(entry.deviceId) ?? 0) === 0).map((entry) => entry.deviceId));
618
- const order = [];
619
- while (ready.size > 0) {
620
- let nextId;
621
- let nextIndex = Number.POSITIVE_INFINITY;
622
- for (const id of ready) {
623
- const index = indexById.get(id) ?? 0;
624
- if (index < nextIndex) {
625
- nextIndex = index;
626
- nextId = id;
627
- }
628
- }
629
- if (nextId === void 0) break;
630
- ready.delete(nextId);
631
- order.push(nextId);
632
- for (const consumer of consumers.get(nextId) ?? []) {
633
- const remaining = (indegree.get(consumer) ?? 0) - 1;
634
- indegree.set(consumer, remaining);
635
- if (remaining === 0) ready.add(consumer);
636
- }
637
- }
638
- for (const entry of entries) if (!order.includes(entry.deviceId)) order.push(entry.deviceId);
639
- return Object.freeze(order);
640
- }
641
2252
  /** Generates `initialize`, `tick` and the batched tick loop. */
642
- generate(entries, solvers, netlist, names = DEFAULT_ENTRY_POINT_NAMES) {
643
- const order = this.order(entries, netlist);
2253
+ generate(entries, names = DEFAULT_ENTRY_POINT_NAMES) {
2254
+ const order = Object.freeze(entries.map((entry) => entry.deviceId));
644
2255
  const byId = new Map(entries.map((entry) => [entry.deviceId, entry]));
645
- const emitStep = (b) => {
646
- for (const deviceId of order) {
647
- const entry = byId.get(deviceId);
648
- if (entry?.tick !== void 0) b.call(entry.tick, []);
649
- }
650
- for (const solver of solvers) b.call(solver.solve, []);
651
- for (const deviceId of order) {
652
- const entry = byId.get(deviceId);
653
- if (entry?.update !== void 0) b.call(entry.update, []);
654
- }
2256
+ const electrical = this.electrical;
2257
+ electrical.finalize();
2258
+ const progress = this.module.state(`${names.tick}_completed`, "u32", 0);
2259
+ const collect = (phase) => order.flatMap((id) => {
2260
+ const ref = byId.get(id)?.[phase];
2261
+ return ref === void 0 ? [] : [ref];
2262
+ });
2263
+ const ensure = [electrical.ensure];
2264
+ const phases = [
2265
+ ...collect("tick"),
2266
+ ...ensure,
2267
+ ...collect("update"),
2268
+ ...ensure
2269
+ ];
2270
+ const emitCalls = (b, calls, finish) => {
2271
+ const emit = (b, at) => {
2272
+ const next = b.block([]);
2273
+ const failed = b.block([]);
2274
+ b.branch(b.int.cmp("eq", b.state.load(electrical.solver.fault), b.const("u8", 0)), {
2275
+ target: next,
2276
+ args: []
2277
+ }, {
2278
+ target: failed,
2279
+ args: []
2280
+ });
2281
+ b.at(failed, (b) => b.return([]));
2282
+ b.at(next, (b) => {
2283
+ const call = calls[at];
2284
+ if (call === void 0) return finish(b);
2285
+ b.call(call, []);
2286
+ return emit(b, at + 1);
2287
+ });
2288
+ };
2289
+ return emit(b, 0);
2290
+ };
2291
+ const completed = (b) => {
2292
+ b.call(electrical.advanceTime, []);
2293
+ b.state.store(progress, b.int.add(b.state.load(progress), b.const("u32", 1)));
655
2294
  };
656
2295
  const initialize = this.module.func(names.initialize, {
657
2296
  params: [],
658
2297
  results: []
659
2298
  });
660
- initialize.body((b) => {
661
- for (const deviceId of order) {
662
- const entry = byId.get(deviceId);
663
- if (entry?.initialize !== void 0) b.call(entry.initialize, []);
664
- }
665
- b.return([]);
666
- });
2299
+ initialize.body((b) => emitCalls(b, [...collect("initialize"), ...ensure], (b) => b.return([])));
667
2300
  const tick = this.module.func(names.tick, {
668
2301
  params: [],
669
2302
  results: []
670
2303
  });
671
2304
  tick.body((b) => {
672
- emitStep(b);
673
- b.return([]);
2305
+ b.state.store(progress, b.const("u32", 0));
2306
+ return emitCalls(b, phases, (b) => {
2307
+ completed(b);
2308
+ b.return([]);
2309
+ });
674
2310
  });
675
2311
  const batch = this.module.func(names.batch, {
676
2312
  params: ["u32"],
@@ -680,320 +2316,32 @@ var MainLoopGenerator = class {
680
2316
  const header = b.block(["u32"]);
681
2317
  const body = b.block(["u32"]);
682
2318
  const done = b.block([]);
2319
+ b.state.store(progress, b.const("u32", 0));
683
2320
  b.jump(header, [b.const("u32", 0)]);
684
- b.at(header, (ib, [index]) => ib.branch(ib.int.cmp("lt", index, count), {
2321
+ b.at(header, (b, [index]) => b.branch(b.int.cmp("lt", index, count), {
685
2322
  target: body,
686
2323
  args: [index]
687
2324
  }, {
688
2325
  target: done,
689
2326
  args: []
690
2327
  }));
691
- b.at(body, (ib, [index]) => {
692
- emitStep(ib);
693
- ib.jump(header, [ib.int.add(index, ib.const("u32", 1))]);
694
- });
695
- b.at(done, (ib) => ib.return([]));
2328
+ b.at(body, (b, [index]) => emitCalls(b, phases, (b) => {
2329
+ completed(b);
2330
+ b.jump(header, [b.int.add(index, b.const("u32", 1))]);
2331
+ }));
2332
+ b.at(done, (b) => b.return([]));
696
2333
  });
697
2334
  return Object.freeze({
698
2335
  names,
699
2336
  initialize,
700
2337
  tick,
701
2338
  batch,
2339
+ progress,
702
2340
  order
703
2341
  });
704
2342
  }
705
2343
  };
706
2344
  //#endregion
707
- //#region src/unified-ir/compiler/solver-gen.ts
708
- /**
709
- * Generates the electrical solve, one `solve_net_<id>` function per net.
710
- *
711
- * Each net solves as a branch-free function. One driver is the common shape:
712
- *
713
- * ```text
714
- * solve_net_0:
715
- * let mode = PIN_MODE[driver]
716
- * let output = PIN_OUTPUT[driver]
717
- * let driven = mode == PUSH_PULL && output
718
- * PIN_INPUT[load] = driven // once per sink
719
- * ```
720
- *
721
- * Only a push-pull driver holds its net; high-z, open-drain and analog modes
722
- * leave it floating. A driver-less net loads the constant of its rail, or
723
- * `false` when it is truly floating. Several drivers OR into a wired-OR level.
724
- */
725
- var ElectricalSolverGenerator = class {
726
- context;
727
- constructor(context) {
728
- this.context = context;
729
- }
730
- generate(netlist) {
731
- return Object.freeze(netlist.nets.map((net) => this.generateNetSolver(net)));
732
- }
733
- generateNetSolver(net) {
734
- const name = `solve_net_${net.netId}`;
735
- const solve = this.context.module.func(name, {
736
- params: [],
737
- results: []
738
- });
739
- solve.body((b) => {
740
- if (net.sinks.length > 0) {
741
- const driven = net.drivers.length === 0 ? b.const("bool", net.level) : this.combineDrivers(b, net.drivers);
742
- if (driven !== void 0) for (const sink of net.sinks) b.array.store(this.context.memory.input, b.const("u32", sink.globalPinId), driven);
743
- }
744
- b.return([]);
745
- });
746
- return Object.freeze({
747
- netId: net.netId,
748
- name,
749
- net,
750
- solve
751
- });
752
- }
753
- /**
754
- * Folds the drivers of one net into the level its sinks observe.
755
- *
756
- * A single driver yields `mode == push-pull && output`; several drivers are
757
- * OR-ed into a wired-OR level.
758
- */
759
- combineDrivers(b, drivers) {
760
- let driven;
761
- for (const driver of drivers) {
762
- const index = b.const("u32", driver.globalPinId);
763
- const mode = b.array.load(this.context.memory.mode, index);
764
- const output = b.array.load(this.context.memory.output, index);
765
- const pushed = b.int.cmp("eq", mode, b.const("u8", PIN_MODE.pushPull));
766
- const value = b.bool.and(pushed, output);
767
- driven = driven === void 0 ? value : b.bool.or(driven, value);
768
- }
769
- return driven;
770
- }
771
- };
772
- //#endregion
773
- //#region src/unified-ir/compiler/topology.ts
774
- /** Rails every circuit understands without declaring them. */
775
- var DEFAULT_RAILS = Object.freeze({
776
- GND: false,
777
- VCC: true,
778
- VDD: true
779
- });
780
- /**
781
- * Analyses the pin-to-pin connections of a circuit.
782
- *
783
- * 1. every connection edge joins two nodes (pins and rails);
784
- * 2. a union-find pass collapses them into electrical nets (connected components);
785
- * 3. each net gets an id in first-appearance order and is split into drivers,
786
- * loads and sinks;
787
- * 4. electrical conflicts (a driver against a rail, two rails of opposite
788
- * level) become diagnostics instead of silently wrong IR.
789
- *
790
- * Several drivers on one net are legal and solved as a wired-OR, which is what
791
- * a bidirectional pin fighting a switch looks like on a bench.
792
- */
793
- var NetworkTopologyAnalyzer = class {
794
- rails;
795
- constructor(options = {}) {
796
- this.rails = new Map([...Object.entries(DEFAULT_RAILS), ...Object.entries(options.rails ?? {})]);
797
- }
798
- /**
799
- * @throws {UnifiedIRCompilerError} when a connection is malformed, names an
800
- * unknown device, or names a pin the device does not declare.
801
- */
802
- analyze(connections, pins) {
803
- if (!Array.isArray(connections)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput.connections must be an array");
804
- const set = new DisjointSet();
805
- const pinNodes = /* @__PURE__ */ new Map();
806
- const railNodes = /* @__PURE__ */ new Map();
807
- const railNodeIds = /* @__PURE__ */ new Map();
808
- const connectionOrder = [];
809
- for (const [index, connection] of connections.entries()) {
810
- if (connection === null || typeof connection !== "object") throw new UnifiedIRCompilerError("invalid-connection", `Connection[${index}] must be an object with "from" and "to"`);
811
- const from = this.resolveEndpoint(connection.from, pins, railNodeIds, index);
812
- const to = this.resolveEndpoint(connection.to, pins, railNodeIds, index);
813
- set.union(from.nodeId, to.nodeId);
814
- connectionOrder.push(from.nodeId);
815
- if (from.kind === "pin") pinNodes.set(from.pin.globalPinId, toConnection(from.pin));
816
- else railNodes.set(from.nodeId, Object.freeze({
817
- name: from.name,
818
- level: from.level
819
- }));
820
- if (to.kind === "pin") pinNodes.set(to.pin.globalPinId, toConnection(to.pin));
821
- else railNodes.set(to.nodeId, Object.freeze({
822
- name: to.name,
823
- level: to.level
824
- }));
825
- }
826
- const components = /* @__PURE__ */ new Map();
827
- const componentOf = (nodeId) => {
828
- const root = set.find(nodeId);
829
- let component = components.get(root);
830
- if (component === void 0) {
831
- component = {
832
- pins: [],
833
- rails: [],
834
- endpoints: []
835
- };
836
- components.set(root, component);
837
- }
838
- return component;
839
- };
840
- for (const [pinId, connection] of pinNodes) componentOf(pinId).pins.push(connection);
841
- for (const [nodeId, rail] of railNodes) {
842
- const component = componentOf(nodeId);
843
- component.rails.push(rail);
844
- component.endpoints.push(rail.name);
845
- }
846
- const orderedRoots = [];
847
- const seen = /* @__PURE__ */ new Set();
848
- for (const nodeId of connectionOrder) {
849
- const root = set.find(nodeId);
850
- if (seen.has(root)) continue;
851
- seen.add(root);
852
- orderedRoots.push(root);
853
- }
854
- const diagnostics = [];
855
- const nets = [];
856
- for (const root of orderedRoots) {
857
- const component = components.get(root);
858
- if (component === void 0) continue;
859
- component.pins.sort((left, right) => left.globalPinId - right.globalPinId);
860
- component.rails.sort((left, right) => left.name.localeCompare(right.name));
861
- const endpoints = [...component.endpoints, ...component.pins.map((pin) => pin.endpoint)];
862
- if (component.pins.length === 0) {
863
- if (new Set(component.rails.map((rail) => rail.level)).size > 1) diagnostics.push(diagnostic("rail-conflict", "error", `Rails ${component.rails.map((rail) => rail.name).join(" and ")} are wired together with opposite levels`, void 0, endpoints));
864
- continue;
865
- }
866
- const netId = nets.length;
867
- const net = this.classify(netId, component.pins, component.rails, diagnostics);
868
- nets.push(net);
869
- }
870
- return Object.freeze({
871
- nets: Object.freeze(nets),
872
- diagnostics: Object.freeze(diagnostics)
873
- });
874
- }
875
- classify(netId, pins, rails, diagnostics) {
876
- const drivers = pins.filter((pin) => pin.role === "driver");
877
- const loads = pins.filter((pin) => pin.role === "load");
878
- const sinks = pins.filter((pin) => pin.senses);
879
- const endpoints = [...rails.map((rail) => rail.name), ...pins.map((pin) => pin.endpoint)];
880
- const levels = new Set(rails.map((rail) => rail.level));
881
- if (rails.length > 1 && levels.size > 1) diagnostics.push(diagnostic("rail-conflict", "error", `Net ${netId} ties rails ${rails.map((rail) => rail.name).join(" and ")} with opposite levels`, netId, endpoints));
882
- if (drivers.length > 0 && rails.length > 0) diagnostics.push(diagnostic("power-short", "error", `Net ${netId} shorts rail ${rails[0]?.name ?? "?"} against driver ${drivers[0]?.endpoint ?? "?"}`, netId, endpoints));
883
- if (drivers.length === 0 && rails.length === 0) diagnostics.push(diagnostic("floating-net", "warning", `Net ${netId} has no driver and no rail; its loads read a constant low`, netId, endpoints));
884
- const source = drivers.length > 0 ? "driver" : rails.length > 0 ? "rail" : "floating";
885
- const level = rails[0]?.level ?? false;
886
- return Object.freeze({
887
- netId,
888
- pins: Object.freeze([...pins]),
889
- rails: Object.freeze([...rails]),
890
- drivers: Object.freeze(drivers),
891
- loads: Object.freeze(loads),
892
- sinks: Object.freeze(sinks),
893
- source,
894
- level
895
- });
896
- }
897
- resolveEndpoint(raw, pins, railNodeIds, index) {
898
- if (typeof raw !== "string" || raw.length === 0) throw new UnifiedIRCompilerError("invalid-connection", `Connection[${index}] endpoint must be a non-empty "device.pin" string or a rail name`);
899
- const railLevel = this.rails.get(raw);
900
- if (railLevel !== void 0) {
901
- let nodeId = railNodeIds.get(raw);
902
- if (nodeId === void 0) {
903
- nodeId = pins.totalPins + railNodeIds.size;
904
- railNodeIds.set(raw, nodeId);
905
- }
906
- return {
907
- kind: "rail",
908
- nodeId,
909
- name: raw,
910
- level: railLevel
911
- };
912
- }
913
- const dot = raw.indexOf(".");
914
- if (dot <= 0 || dot === raw.length - 1) throw new UnifiedIRCompilerError("invalid-connection", `Connection endpoint "${raw}" must be "device.pin" or a known rail (${[...this.rails.keys()].join(", ")})`);
915
- const deviceId = raw.slice(0, dot);
916
- const pinName = raw.slice(dot + 1);
917
- const allocation = pins.devices.get(deviceId);
918
- if (allocation === void 0) throw new UnifiedIRCompilerError("unknown-device", `Connection endpoint "${raw}" references unknown device "${deviceId}". Available: [${[...pins.devices.keys()].join(", ")}]`, { deviceId });
919
- const pin = allocation.resolved.get(pinName);
920
- if (pin === void 0) throw new UnifiedIRCompilerError("pin-not-found", `Pin '${raw}' not found. Available: [${[...allocation.resolved.keys()].map((name) => `${deviceId}.${name}`).join(", ")}]`, {
921
- deviceId,
922
- pinName
923
- });
924
- return {
925
- kind: "pin",
926
- nodeId: pin.globalPinId,
927
- pin
928
- };
929
- }
930
- };
931
- /**
932
- * Throws the first error diagnostic of a netlist, or returns it unchanged.
933
- *
934
- * @throws {UnifiedIRCompilerError} carrying every diagnostic for inspection.
935
- */
936
- function assertNoElectricalErrors(netlist) {
937
- const first = netlist.diagnostics.filter((entry) => entry.severity === "error")[0];
938
- if (first === void 0) return netlist;
939
- throw new UnifiedIRCompilerError(mapErrorCode(first.code), first.message, {
940
- ...first.netId === void 0 ? {} : { netId: first.netId },
941
- diagnostics: netlist.diagnostics
942
- });
943
- }
944
- function mapErrorCode(code) {
945
- return code === "rail-conflict" ? "rail-conflict" : "power-short";
946
- }
947
- function diagnostic(code, severity, message, netId, endpoints) {
948
- return Object.freeze({
949
- code,
950
- severity,
951
- message,
952
- netId,
953
- endpoints: Object.freeze([...endpoints])
954
- });
955
- }
956
- function toConnection(pin) {
957
- return Object.freeze({
958
- endpoint: `${pin.deviceId}.${pin.name}`,
959
- deviceId: pin.deviceId,
960
- pinName: pin.name,
961
- globalPinId: pin.globalPinId,
962
- role: pin.role,
963
- senses: pin.senses
964
- });
965
- }
966
- /** Union-find over pin ids and rail node ids. */
967
- var DisjointSet = class {
968
- parent = /* @__PURE__ */ new Map();
969
- rank = /* @__PURE__ */ new Map();
970
- find(id) {
971
- const parent = this.parent.get(id);
972
- if (parent === void 0) {
973
- this.parent.set(id, id);
974
- this.rank.set(id, 0);
975
- return id;
976
- }
977
- if (parent === id) return id;
978
- const root = this.find(parent);
979
- this.parent.set(id, root);
980
- return root;
981
- }
982
- union(left, right) {
983
- const leftRoot = this.find(left);
984
- const rightRoot = this.find(right);
985
- if (leftRoot === rightRoot) return;
986
- const leftRank = this.rank.get(leftRoot) ?? 0;
987
- const rightRank = this.rank.get(rightRoot) ?? 0;
988
- if (leftRank < rightRank) {
989
- this.parent.set(leftRoot, rightRoot);
990
- return;
991
- }
992
- this.parent.set(rightRoot, leftRoot);
993
- if (leftRank === rightRank) this.rank.set(leftRoot, leftRank + 1);
994
- }
995
- };
996
- //#endregion
997
2345
  //#region src/unified-ir/compiler/index.ts
998
2346
  /**
999
2347
  * Compiles several devices and their wiring into one unified IR module (U01).
@@ -1020,37 +2368,34 @@ var DisjointSet = class {
1020
2368
  *
1021
2369
  * The pipeline is: validate the input, allocate the global pin and state
1022
2370
  * spaces, analyse the electrical topology, generate one function per device
1023
- * phase, generate one solver per net, generate the main loop, then validate the
2371
+ * phase, generate the resistive network solver and main loop, then validate the
1024
2372
  * resulting module with `validateIR`.
1025
2373
  *
1026
2374
  * @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown
1027
2375
  * pins, electrical conflicts, or when the generated module fails validation.
1028
2376
  */
1029
2377
  function compileCircuit(input, options = {}) {
1030
- const { devices, connections } = validateInput(input);
2378
+ const validated = validateInput(input);
2379
+ const { connections } = validated;
1031
2380
  const resolvedOptions = validateOptions(options);
1032
2381
  const names = resolveEntryNames(resolvedOptions);
1033
2382
  const module = createIRModule();
1034
- const allocation = new GlobalResourceAllocator(module).allocate(devices);
1035
- const netlist = new NetworkTopologyAnalyzer({ ...resolvedOptions.rails === void 0 ? {} : { rails: resolvedOptions.rails } }).analyze(connections, allocation.pins);
1036
- assertNoElectricalErrors(netlist);
2383
+ const allocation = new GlobalResourceAllocator(module).allocate(validated.devices);
2384
+ const electrical = prepareElectricalCompilation(module, validated.devices, connections, resolvedOptions);
2385
+ const devices = electrical.devices;
1037
2386
  const generator = new DeviceIRGenerator({
1038
2387
  module,
1039
- memory: allocation.memory,
1040
2388
  pins: allocation.pins,
1041
- states: allocation.states
2389
+ states: allocation.states,
2390
+ electrical: electrical.operations
1042
2391
  });
1043
2392
  const generated = devices.map((device) => generator.generate(device));
1044
- const solvers = new ElectricalSolverGenerator({
1045
- module,
1046
- memory: allocation.memory
1047
- }).generate(netlist);
1048
- assertNoNameCollisions(devices, solvers.map((solver) => solver.name), names);
1049
- const loop = new MainLoopGenerator(module).generate(generated.map((device) => device.entry), solvers, netlist, names);
2393
+ assertNoNameCollisions(devices, names);
2394
+ const loop = new MainLoopGenerator(module, electrical.operations).generate(generated.map((device) => device.entry), names);
1050
2395
  const validation = createModuleValidation(module, devices.flatMap((device) => device.description.updateResources ?? []));
1051
2396
  if (resolvedOptions.validate !== false) validateModule(module, validation);
1052
2397
  const deviceMap = new Map(generated.map((device) => [device.metadata.deviceId, device.metadata]));
1053
- return Object.freeze({
2398
+ const compiled = Object.freeze({
1054
2399
  module,
1055
2400
  entryPoints: Object.freeze({
1056
2401
  tick: loop.names.tick,
@@ -1062,16 +2407,17 @@ function compileCircuit(input, options = {}) {
1062
2407
  batch: loop.batch
1063
2408
  })
1064
2409
  }),
2410
+ progress: loop.progress,
1065
2411
  pinMap: allocation.pins.pins,
1066
2412
  deviceMap,
1067
- netlist,
1068
2413
  pins: allocation.pins,
1069
2414
  states: allocation.states,
1070
- memory: allocation.memory,
1071
2415
  validation,
1072
2416
  executionOrder: loop.order,
1073
2417
  functions: Object.freeze(module.functions.map((fn) => fn.name))
1074
2418
  });
2419
+ retainElectricalCompilation(compiled, electrical);
2420
+ return compiled;
1075
2421
  }
1076
2422
  function validateInput(input) {
1077
2423
  if (input === null || typeof input !== "object" || Array.isArray(input)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput must be an object with devices and connections");
@@ -1087,10 +2433,6 @@ function validateOptions(options) {
1087
2433
  if (options === null || typeof options !== "object" || Array.isArray(options)) throw new UnifiedIRCompilerError("invalid-input", "Compile options must be an object");
1088
2434
  const resolved = options;
1089
2435
  if (resolved.validate !== void 0 && typeof resolved.validate !== "boolean") throw new UnifiedIRCompilerError("invalid-input", "options.validate must be a boolean");
1090
- if (resolved.rails !== void 0) {
1091
- if (resolved.rails === null || typeof resolved.rails !== "object" || Array.isArray(resolved.rails)) throw new UnifiedIRCompilerError("invalid-input", "options.rails must be a plain object");
1092
- for (const [name, level] of Object.entries(resolved.rails)) if (name.length === 0 || typeof level !== "boolean") throw new UnifiedIRCompilerError("invalid-input", `options.rails["${name}"] must be a boolean`);
1093
- }
1094
2436
  return resolved;
1095
2437
  }
1096
2438
  function resolveEntryNames(options) {
@@ -1103,12 +2445,11 @@ function resolveEntryNames(options) {
1103
2445
  if (new Set(Object.values(names)).size !== 3) throw new UnifiedIRCompilerError("invalid-input", `Entry point names must be distinct: ${JSON.stringify(names)}`);
1104
2446
  return Object.freeze(names);
1105
2447
  }
1106
- function assertNoNameCollisions(devices, solverNames, names) {
2448
+ function assertNoNameCollisions(devices, names) {
1107
2449
  const reserved = /* @__PURE__ */ new Set([
1108
2450
  names.tick,
1109
2451
  names.initialize,
1110
- names.batch,
1111
- ...solverNames
2452
+ names.batch
1112
2453
  ]);
1113
2454
  for (const device of devices) for (const phase of [
1114
2455
  "initialize",
@@ -1137,113 +2478,125 @@ var CircuitError = class extends Error {
1137
2478
  name = "CircuitError";
1138
2479
  code;
1139
2480
  deviceId;
1140
- pinName;
1141
2481
  stateName;
1142
2482
  constructor(code, message, options = {}) {
1143
2483
  super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
1144
2484
  this.code = code;
1145
2485
  this.deviceId = options.deviceId;
1146
- this.pinName = options.pinName;
1147
2486
  this.stateName = options.stateName;
1148
2487
  }
1149
2488
  };
1150
2489
  //#endregion
1151
- //#region src/unified-ir/runtime/accessors.ts
1152
- /**
1153
- * Builds one accessor per compiled device.
1154
- *
1155
- * A description that declares `accessor` owns its surface; every other device
1156
- * keeps the generic state/pin accessor. The returned record is frozen and keyed
1157
- * by device id.
1158
- */
1159
- function buildDeviceAccessors(context) {
1160
- const entries = [];
1161
- for (const device of context.compiled.deviceMap.values()) {
1162
- const base = createBaseAccessor(context, device);
1163
- if (device.accessor !== void 0) entries.push([device.deviceId, device.accessor({
1164
- deviceId: device.deviceId,
1165
- storage: context.jit.storage,
1166
- assertActive: context.assertActive,
1167
- step: context.step,
1168
- runBatch: context.runBatch
1169
- })]);
1170
- else entries.push([device.deviceId, base]);
1171
- }
1172
- return Object.freeze(Object.fromEntries(entries));
1173
- }
1174
- function createBaseAccessor(context, device) {
1175
- const { jit } = context;
1176
- const storage = jit.storage;
1177
- const memory = context.compiled.memory;
1178
- const resolved = context.compiled.pins.devices.get(device.deviceId)?.resolved;
1179
- const accessor = {
1180
- deviceId: device.deviceId,
1181
- type: device.type,
1182
- pinNames: Object.freeze([...device.pins.keys()]),
1183
- stateNames: Object.freeze([...device.states.keys()]),
1184
- readPin(pinName) {
1185
- context.assertActive();
1186
- const pin = pinOf(device, resolved, pinName);
1187
- return storage.loadArray(memory.output, pin.globalPinId) === true;
1188
- },
1189
- writePin(pinName, value) {
1190
- context.assertActive();
1191
- const pin = pinOf(device, resolved, pinName);
1192
- if (pin.role !== "driver") throw new CircuitError("pin-not-writable", `Pin "${device.deviceId}.${pinName}" has role "${pin.role}"; only driver pins can be written. Use Circuit.setPin to override a sensed level`, {
1193
- deviceId: device.deviceId,
1194
- pinName
1195
- });
1196
- assertBoolean(device.deviceId, pinName, value);
1197
- storage.storeArray(memory.output, pin.globalPinId, value);
1198
- },
1199
- getState(name) {
2490
+ //#region src/unified-ir/runtime/bridge.ts
2491
+ function createDeviceBoundary(context) {
2492
+ const metadataOf = (deviceId) => {
2493
+ const device = context.compiled.deviceMap.get(deviceId);
2494
+ if (device === void 0) throw new CircuitError("unresolved-device", `Circuit has no device "${deviceId}"`, { deviceId });
2495
+ return device;
2496
+ };
2497
+ return {
2498
+ hasInputHook: (deviceId) => metadataOf(deviceId).applyInputs !== void 0,
2499
+ deliverInputs(deviceId, inputs) {
1200
2500
  context.assertActive();
1201
- const slot = stateOf(device, name);
1202
- return storage.loadArray(slot.array, slot.index);
2501
+ const device = metadataOf(deviceId);
2502
+ const hook = device.applyInputs;
2503
+ if (hook === void 0) {
2504
+ if (inputs.length === 0) return;
2505
+ throw new CircuitError("unsupported-operation", `Device "${device.deviceId}" (${device.type}) declares no applyInputs hook`, { deviceId });
2506
+ }
2507
+ const entries = new Set(device.entries ?? []);
2508
+ const pending = /* @__PURE__ */ new Map();
2509
+ for (const input of inputs) {
2510
+ const values = pending.get(input.port) ?? [];
2511
+ values.push(input.payload);
2512
+ pending.set(input.port, values);
2513
+ }
2514
+ let open = true;
2515
+ const active = () => {
2516
+ context.assertActive();
2517
+ if (!open) throw new TypeError("Input IO is only valid during applyInputs");
2518
+ };
2519
+ try {
2520
+ hook({
2521
+ takeInput(port) {
2522
+ active();
2523
+ const values = pending.get(port);
2524
+ pending.delete(port);
2525
+ return values?.at(-1);
2526
+ },
2527
+ takeInputs(port) {
2528
+ active();
2529
+ const values = pending.get(port) ?? [];
2530
+ pending.delete(port);
2531
+ return Object.freeze(values);
2532
+ },
2533
+ writeState(name, value) {
2534
+ active();
2535
+ const slot = stateSlotOf(device, name);
2536
+ const accepted = coerceStateValue(device, slot, value);
2537
+ try {
2538
+ context.jit.storage.storeArray(slot.array, slot.index, accepted);
2539
+ } catch (cause) {
2540
+ throw new CircuitError("invalid-state-value", `State "${device.deviceId}.${name}" (${slot.type}) rejected ${String(value)}`, {
2541
+ deviceId: device.deviceId,
2542
+ stateName: name,
2543
+ cause
2544
+ });
2545
+ }
2546
+ },
2547
+ call(entry, args) {
2548
+ active();
2549
+ if (!entries.has(entry)) throw new TypeError("Input entry must belong to this device");
2550
+ context.execute(entry, args);
2551
+ }
2552
+ });
2553
+ } finally {
2554
+ open = false;
2555
+ }
1203
2556
  },
1204
- setState(name, value) {
2557
+ publishOutputs(deviceId, publish) {
1205
2558
  context.assertActive();
1206
- const slot = stateOf(device, name);
1207
- const accepted = coerceStateValue(device, slot, value);
2559
+ const device = metadataOf(deviceId);
2560
+ const hook = device.flushOutputs;
2561
+ if (hook === void 0) return;
2562
+ let open = true;
2563
+ const active = () => {
2564
+ context.assertActive();
2565
+ if (!open) throw new TypeError("Output IO is only valid during flushOutputs");
2566
+ };
1208
2567
  try {
1209
- storage.storeArray(slot.array, slot.index, accepted);
1210
- } catch (cause) {
1211
- throw new CircuitError("invalid-state-value", `State "${device.deviceId}.${name}" (${slot.type}) rejected ${String(value)}`, {
1212
- deviceId: device.deviceId,
1213
- stateName: name,
1214
- cause
2568
+ hook({
2569
+ readState(name) {
2570
+ active();
2571
+ const slot = stateSlotOf(device, name);
2572
+ const value = context.jit.storage.loadArray(slot.array, slot.index);
2573
+ return typeof value === "object" && value !== null && "bits" in value ? toNumber(value) : value;
2574
+ },
2575
+ publish(port, payload) {
2576
+ active();
2577
+ publish(port, payload);
2578
+ }
1215
2579
  });
2580
+ } finally {
2581
+ open = false;
1216
2582
  }
1217
2583
  }
1218
2584
  };
1219
- return Object.freeze(accessor);
1220
2585
  }
1221
- /** Resolves one pin of `device`, or throws with every pin the device declares. */
1222
- function pinOf(device, resolved, pinName) {
1223
- const pin = resolved?.get(pinName);
1224
- if (pin === void 0) throw new CircuitError("pin-not-found", `Device "${device.deviceId}" (${device.type}) has no pin "${pinName}". Available: ${formatNames(device.pins.keys())}`, {
1225
- deviceId: device.deviceId,
1226
- pinName
1227
- });
1228
- return pin;
1229
- }
1230
- /** Resolves one state slot of `device`, or throws with every state it declares. */
1231
- function stateOf(device, name) {
2586
+ /** Resolves one declared state slot of `device`, or throws with every state it declares. */
2587
+ function stateSlotOf(device, name) {
1232
2588
  const slot = device.states.get(name);
1233
- if (slot === void 0) throw new CircuitError("state-not-found", `Device "${device.deviceId}" (${device.type}) has no state "${name}". Available: ${formatNames(device.states.keys())}`, {
1234
- deviceId: device.deviceId,
1235
- stateName: name
1236
- });
2589
+ if (slot === void 0) {
2590
+ const available = [...device.states.keys()];
2591
+ throw new CircuitError("state-not-found", `Device "${device.deviceId}" (${device.type}) has no state "${name}". Available: ${available.length === 0 ? "(none)" : `[${available.join(", ")}]`}`, {
2592
+ deviceId: device.deviceId,
2593
+ stateName: name
2594
+ });
2595
+ }
1237
2596
  return slot;
1238
2597
  }
1239
- function assertBoolean(deviceId, pinName, value) {
1240
- if (typeof value !== "boolean") throw new CircuitError("invalid-state-value", `Pin "${deviceId}.${pinName}" needs a boolean level, received ${typeof value}`, {
1241
- deviceId,
1242
- pinName
1243
- });
1244
- }
1245
2598
  /**
1246
- * Validates a host-written state value against the declared scalar type.
2599
+ * Validates a hook-written state value against the declared scalar type.
1247
2600
  * Range checks stay in storage, which owns the encoding.
1248
2601
  */
1249
2602
  function coerceStateValue(device, slot, value) {
@@ -1272,10 +2625,6 @@ function isFloatBits(value) {
1272
2625
  const candidate = value;
1273
2626
  return (candidate.type === "f32" || candidate.type === "f64") && typeof candidate.bits === "string";
1274
2627
  }
1275
- function formatNames(names) {
1276
- const list = [...names];
1277
- return list.length === 0 ? "(none)" : `[${list.join(", ")}]`;
1278
- }
1279
2628
  //#endregion
1280
2629
  //#region src/unified-ir/runtime/circuit.ts
1281
2630
  /** Every generated entry takes no arguments, so one frozen array is reused. */
@@ -1302,48 +2651,42 @@ var DEFAULT_INSTANCE_ID = "unified-circuit";
1302
2651
  *
1303
2652
  * circuit.runBatch(1_000_000); // one engine call
1304
2653
  * expect(circuit.tickCount).toBe(1_000_000n);
1305
- *
1306
2654
  * circuit.reset();
1307
- * circuit.setPin('drive1.PA0', true); // host drives the pin
1308
2655
  * circuit.step();
1309
- * expect(circuit.devices.sink1.getState('lamp')).toBe(true);
1310
2656
  * ```
1311
2657
  *
1312
- * `Circuit` owns the engine instance and the tick counter; the compiled module
1313
- * keeps every device, net and the main loop in one `@mica-js/ir` module, so a
1314
- * batch is one interpreter/JIT call for the whole circuit.
2658
+ * `Circuit` owns the engine instance, the tick counter and the private
2659
+ * step-boundary hook plumbing. RFC 0017 traffic belongs to the
2660
+ * `DeviceSimulationHost`: it delivers topic inputs before a step and publishes
2661
+ * the topic outputs the device hooks report afterwards. `Circuit` itself
2662
+ * exposes no device state, pin or electrical readback.
2663
+ *
2664
+ * The compiled module keeps every device, net and the main loop in one
2665
+ * `@mica-js/ir` module, so a batch is one interpreter/JIT call for the whole
2666
+ * circuit.
1315
2667
  */
1316
2668
  var Circuit = class Circuit {
1317
- /** Typed per-device accessors, keyed by device id. */
1318
- devices;
1319
2669
  #compiled;
1320
2670
  #jit;
1321
2671
  #context;
1322
- #pins;
1323
- #pinNames;
1324
2672
  #seeds;
1325
2673
  #tickCount = 0n;
1326
2674
  #virtualTime = 0;
1327
2675
  #disposed = false;
1328
- constructor(compiled, jit, instanceId, accessors, pins, seeds) {
2676
+ constructor(compiled, jit, instanceId, boundary, seeds) {
1329
2677
  this.#compiled = compiled;
1330
2678
  this.#jit = jit;
1331
2679
  this.#context = {
1332
2680
  instanceId,
1333
2681
  virtualTime: 0
1334
2682
  };
1335
- this.devices = accessors;
1336
- this.#pins = pins;
1337
- this.#pinNames = Object.freeze([...pins.keys()]);
1338
2683
  this.#seeds = seeds;
2684
+ boundaries.set(this, boundary);
1339
2685
  }
1340
2686
  /**
1341
2687
  * Compiles `input`, builds the engine instance and runs the generated
1342
2688
  * `initialize` entry once.
1343
2689
  *
1344
- * The input is inferred as a `const` type, so a literal device list keeps its
1345
- * ids and `circuit.devices.<id>` is typed without a cast.
1346
- *
1347
2690
  * @throws {UnifiedIRCompilerError} when the circuit cannot be compiled.
1348
2691
  * @throws {CircuitError} for invalid options.
1349
2692
  */
@@ -1351,50 +2694,56 @@ var Circuit = class Circuit {
1351
2694
  const resolved = resolveOptions(options);
1352
2695
  const compiled = compileCircuit(input, compileOptionsOf(resolved));
1353
2696
  const jit = createEngine(compiled, resolved);
1354
- const host = { circuit: void 0 };
1355
- const circuit = new Circuit(compiled, jit, resolved.instanceId, buildDeviceAccessors({
2697
+ const boundary = createDeviceBoundary({
1356
2698
  compiled,
1357
2699
  jit,
2700
+ execute: (entry, args) => {
2701
+ circuit.#context.virtualTime = circuit.#virtualTime;
2702
+ jit.execute(entry, args, circuit.#context);
2703
+ },
1358
2704
  assertActive: () => {
1359
2705
  circuit.#assertActive();
1360
- },
1361
- step: () => {
1362
- host.circuit?.step();
1363
- },
1364
- runBatch: (count) => {
1365
- host.circuit?.runBatch(count);
1366
2706
  }
1367
- }), pinRuntimeOf(compiled), resetSeedsOf(compiled));
1368
- host.circuit = circuit;
2707
+ });
2708
+ const circuit = new Circuit(compiled, jit, resolved.instanceId, boundary, resetSeedsOf(compiled));
1369
2709
  jit.execute(compiled.entryPoints.refs.initialize, NO_ARGS, circuit.#context);
1370
2710
  return circuit;
1371
2711
  }
1372
2712
  /**
1373
2713
  * Runs `count` ticks inside one generated loop — the throughput path.
1374
2714
  *
1375
- * The whole batch is one engine call; `tickCount` grows by `count` once the
1376
- * call returns, so a failed batch never advances the clock.
2715
+ * The whole batch is one engine call. The clock advances by completed ticks,
2716
+ * including the completed prefix of a failed batch.
1377
2717
  *
1378
2718
  * @throws {CircuitError} with code `invalid-count` unless `count` is a u32.
1379
2719
  */
1380
- runBatch(count) {
2720
+ runBatch(count, dt = 1) {
1381
2721
  this.#assertActive();
1382
2722
  if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0 || count > MAX_BATCH_TICKS) throw new CircuitError("invalid-count", `runBatch(count) needs an integer in [0, ${MAX_BATCH_TICKS}], received ${String(count)}`);
2723
+ this.#setTimeStep(dt);
1383
2724
  if (count === 0) return;
1384
2725
  this.#context.virtualTime = this.#virtualTime;
1385
- this.#jit.execute(this.#compiled.entryPoints.refs.batch, [count], this.#context);
1386
- this.#advance(count);
2726
+ this.#jit.storage.storeState(this.#compiled.progress, 0);
2727
+ try {
2728
+ this.#jit.execute(this.#compiled.entryPoints.refs.batch, [count], this.#context);
2729
+ } finally {
2730
+ this.#advance(this.#jit.storage.loadState(this.#compiled.progress), dt);
2731
+ }
1387
2732
  }
1388
2733
  /**
1389
2734
  * Advances exactly one tick — the debugging path.
1390
2735
  *
1391
2736
  * Every call is one engine entry, so prefer `runBatch` for throughput.
1392
2737
  */
1393
- step() {
2738
+ step(dt = 1) {
1394
2739
  this.#assertActive();
2740
+ this.#setTimeStep(dt);
1395
2741
  this.#context.virtualTime = this.#virtualTime;
1396
- this.#jit.execute(this.#compiled.entryPoints.refs.tick, NO_ARGS, this.#context);
1397
- this.#advance(1);
2742
+ try {
2743
+ this.#jit.execute(this.#compiled.entryPoints.refs.tick, NO_ARGS, this.#context);
2744
+ } finally {
2745
+ this.#advance(this.#jit.storage.loadState(this.#compiled.progress), dt);
2746
+ }
1398
2747
  }
1399
2748
  /**
1400
2749
  * Restores every memory to its declared initial value, re-runs `initialize`
@@ -1427,38 +2776,6 @@ var Circuit = class Circuit {
1427
2776
  this.#context.virtualTime = 0;
1428
2777
  this.#jit.execute(this.#compiled.entryPoints.refs.initialize, NO_ARGS, this.#context);
1429
2778
  }
1430
- /**
1431
- * Reads the level one pin observes.
1432
- *
1433
- * A sensing pin (input, passive or bidirectional) reports the solved net
1434
- * level; a pure driver pin reports the level it actually drives, which is
1435
- * `false` unless it is configured push-pull.
1436
- *
1437
- * @throws {CircuitError} with code `pin-not-found`.
1438
- */
1439
- getPin(pinName) {
1440
- this.#assertActive();
1441
- const pin = this.#pinRuntime(pinName);
1442
- const storage = this.#jit.storage;
1443
- if (pin.senses) return storage.loadArray(this.#compiled.memory.input, pin.globalPinId) === true;
1444
- return Number(storage.loadArray(this.#compiled.memory.mode, pin.globalPinId)) === PIN_MODE.pushPull && storage.loadArray(this.#compiled.memory.output, pin.globalPinId) === true;
1445
- }
1446
- /**
1447
- * Forces the level of one pin from the host.
1448
- *
1449
- * A driver pin gets its output latch written, so the level survives the next
1450
- * electrical solve. A sensing pin gets the solved-value slot overridden, which
1451
- * lasts until the next tick recomputes its net.
1452
- *
1453
- * @throws {CircuitError} with code `pin-not-found`.
1454
- */
1455
- setPin(pinName, value) {
1456
- this.#assertActive();
1457
- const pin = this.#pinRuntime(pinName);
1458
- if (typeof value !== "boolean") throw new CircuitError("invalid-state-value", `Pin "${pinName}" needs a boolean level, received ${typeof value}`, { pinName });
1459
- const target = pin.role === "driver" ? this.#compiled.memory.output : this.#compiled.memory.input;
1460
- this.#jit.storage.storeArray(target, pin.globalPinId, value);
1461
- }
1462
2779
  /** Number of ticks completed since creation or the last `reset()`. */
1463
2780
  get tickCount() {
1464
2781
  this.#assertActive();
@@ -1469,48 +2786,51 @@ var Circuit = class Circuit {
1469
2786
  this.#assertActive();
1470
2787
  return this.#virtualTime;
1471
2788
  }
1472
- /** Underlying engine instance, e.g. for diagnostics or custom entries. */
1473
- get jit() {
1474
- this.#assertActive();
1475
- return this.#jit;
1476
- }
1477
2789
  /** Whether `dispose()` already ran. */
1478
2790
  get disposed() {
1479
2791
  return this.#disposed;
1480
2792
  }
1481
2793
  /**
1482
2794
  * Releases the runtime. Idempotent; every later call throws a `CircuitError`
1483
- * with code `disposed`, including stale device accessors.
2795
+ * with code `disposed`.
1484
2796
  */
1485
2797
  dispose() {
1486
2798
  this.#disposed = true;
1487
2799
  this.#tickCount = 0n;
1488
2800
  this.#virtualTime = 0;
1489
2801
  }
1490
- /** @internal Shared guard of the circuit and all of its accessors. */
2802
+ /** @internal Shared guard of the circuit and its boundary hooks. */
1491
2803
  #assertActive() {
1492
2804
  if (this.#disposed) throw new CircuitError("disposed", "Circuit has been disposed; create a new circuit to keep simulating");
1493
2805
  }
1494
- #advance(count) {
1495
- this.#tickCount += BigInt(count);
1496
- const next = this.#virtualTime + count;
1497
- this.#virtualTime = next > MAX_VIRTUAL_TIME ? 0 : next;
2806
+ #setTimeStep(dt) {
2807
+ if (!Number.isSafeInteger(dt) || dt <= 0) throw new CircuitError("invalid-options", "Tick duration must be a positive safe integer in picoseconds");
2808
+ const electrical = electricalCompilationOf(this.#compiled);
2809
+ if (electrical !== void 0) {
2810
+ this.#jit.storage.storeArray(electrical.operations.timeStep, 0, dt >>> 0);
2811
+ this.#jit.storage.storeArray(electrical.operations.timeStep, 1, Math.floor(dt / 4294967296));
2812
+ }
1498
2813
  }
1499
- #pinRuntime(pinName) {
1500
- const pin = this.#pins.get(pinName);
1501
- if (pin === void 0) throw new CircuitError("pin-not-found", `Pin "${pinName}" not found. Available: ${this.#pinNames.length === 0 ? "(none)" : `[${this.#pinNames.join(", ")}]`}`, { pinName });
1502
- return pin;
2814
+ #advance(count, dt) {
2815
+ this.#tickCount += BigInt(count);
2816
+ const elapsed = count * dt;
2817
+ const next = this.#virtualTime + elapsed;
2818
+ this.#virtualTime = Number.isSafeInteger(next) ? next : Number((BigInt(this.#virtualTime) + BigInt(count) * BigInt(dt)) % (BigInt(MAX_VIRTUAL_TIME) + 1n));
1503
2819
  }
1504
2820
  };
1505
- /** Resolves every pin of the global address space into its runtime view. */
1506
- function pinRuntimeOf(compiled) {
1507
- const pins = /* @__PURE__ */ new Map();
1508
- for (const [deviceId, allocation] of compiled.pins.devices) for (const [pinName, pin] of allocation.resolved) pins.set(`${deviceId}.${pinName}`, Object.freeze({
1509
- globalPinId: pin.globalPinId,
1510
- role: pin.role,
1511
- senses: pin.senses
1512
- }));
1513
- return pins;
2821
+ var boundaries = /* @__PURE__ */ new WeakMap();
2822
+ /**
2823
+ * Step-boundary hooks of one circuit.
2824
+ *
2825
+ * The device simulation host is the only package-level caller: RFC 0017 traffic
2826
+ * enters through `applyInputs` and leaves through `flushOutputs`, never through
2827
+ * a device accessor. This function is deliberately absent from the package
2828
+ * entry points.
2829
+ */
2830
+ function deviceBoundaryOf(circuit) {
2831
+ const boundary = boundaries.get(circuit);
2832
+ if (boundary === void 0) throw new CircuitError("invalid-options", "Argument must be a Circuit created by Circuit.create");
2833
+ return boundary;
1514
2834
  }
1515
2835
  /**
1516
2836
  * Captures the declared initial value of every scalar memory, which is what
@@ -1559,7 +2879,9 @@ function createEngine(compiled, options) {
1559
2879
  function compileOptionsOf(options) {
1560
2880
  return {
1561
2881
  validate: options.validateIR,
1562
- ...options.rails === void 0 ? {} : { rails: options.rails }
2882
+ ...options.sources === void 0 ? {} : { sources: options.sources },
2883
+ ...options.interpretation === void 0 ? {} : { interpretation: options.interpretation },
2884
+ ...options.floatingSeed === void 0 ? {} : { floatingSeed: options.floatingSeed }
1563
2885
  };
1564
2886
  }
1565
2887
  function resolveOptions(options) {
@@ -1572,17 +2894,18 @@ function resolveOptions(options) {
1572
2894
  if (candidate.jit !== void 0) {
1573
2895
  if (candidate.jit === null || typeof candidate.jit !== "object" || Array.isArray(candidate.jit)) throw new CircuitError("invalid-options", "jit must be a JIT tuning object");
1574
2896
  }
1575
- let rails;
1576
2897
  if (candidate.electrical !== void 0) {
1577
2898
  const electrical = candidate.electrical;
1578
2899
  if (electrical === null || typeof electrical !== "object" || Array.isArray(electrical)) throw new CircuitError("invalid-options", "electrical must be a plain object");
1579
- rails = electrical.rails;
2900
+ if ("rails" in electrical) throw new CircuitError("invalid-options", "Boolean rails are unsupported; declare explicit voltage sources");
1580
2901
  }
1581
2902
  return Object.freeze({
1582
2903
  engine,
1583
2904
  jit: candidate.jit,
1584
2905
  validateIR: candidate.validateIR ?? true,
1585
- rails,
2906
+ sources: candidate.electrical?.sources,
2907
+ interpretation: candidate.electrical?.interpretation,
2908
+ floatingSeed: candidate.electrical?.floatingSeed,
1586
2909
  instanceId: candidate.instanceId ?? DEFAULT_INSTANCE_ID
1587
2910
  });
1588
2911
  }
@@ -1610,15 +2933,16 @@ async function createCircuitFromSchematic(schematic, options) {
1610
2933
  return (await createSchematicCircuit(schematic, options)).circuit;
1611
2934
  }
1612
2935
  /**
1613
- * Compiles a schematic and reports which circuit device each symbol became.
2936
+ * Lowers a schematic sheet to the netlist {@link createSchematicCircuit} compiles.
1614
2937
  *
1615
- * {@link createCircuitFromSchematic} returns only the circuit; hosts that route
1616
- * schematic endpoints to circuit accessors need the mapping as well.
2938
+ * Kept package-internal: the public factory returns the running circuit, while
2939
+ * the solver suites need the same device configs and connections without a
2940
+ * second schematic implementation.
1617
2941
  */
1618
- async function createSchematicCircuit(schematic, options) {
2942
+ function compileSchematicInput(schematic, options) {
1619
2943
  if (schematic === null || typeof schematic !== "object" || schematic.sheet === null || typeof schematic.sheet !== "object" || !Array.isArray(schematic.sheet.symbols) || !Array.isArray(schematic.sheet.wires) || !Array.isArray(schematic.sheet.junctions)) throw new CircuitError("invalid-options", "createSchematicCircuit needs a schematic with sheet.symbols, sheet.wires and sheet.junctions");
1620
2944
  if (options === null || typeof options !== "object") throw new CircuitError("invalid-options", "createSchematicCircuit needs options");
1621
- const { resolveDevice, devices, tolerance, ...runtime } = options;
2945
+ const { resolveDevice, devices, tolerance } = options;
1622
2946
  if (typeof resolveDevice !== "function") throw new CircuitError("invalid-options", "resolveDevice must be a function");
1623
2947
  const usedIds = /* @__PURE__ */ new Set();
1624
2948
  const deviceIdBySymbol = /* @__PURE__ */ new Map();
@@ -1638,6 +2962,7 @@ async function createSchematicCircuit(schematic, options) {
1638
2962
  id: deviceId,
1639
2963
  type: binding.type,
1640
2964
  description: binding.description,
2965
+ ...symbol.properties === void 0 ? {} : { properties: symbol.properties },
1641
2966
  ...binding.config === void 0 ? {} : { config: binding.config }
1642
2967
  });
1643
2968
  if (reference !== void 0) bindings.push({
@@ -1652,7 +2977,7 @@ async function createSchematicCircuit(schematic, options) {
1652
2977
  ...tolerance === void 0 ? {} : { tolerance }
1653
2978
  });
1654
2979
  if (componentCount > 0 && topology.pins.length === 0) throw new CircuitError("invalid-options", "The derived topology has no pins; pass the DeviceSymbolProvider that authored the schematic so pins can be located");
1655
- const railNames = /* @__PURE__ */ new Set([...Object.keys(DEFAULT_RAILS), ...Object.keys(options.electrical?.rails ?? {})]);
2980
+ const railNames = /* @__PURE__ */ new Set(["GND", ...Object.keys(options.electrical?.sources ?? {})]);
1656
2981
  const connections = [];
1657
2982
  for (const net of topology.nets) {
1658
2983
  const endpoints = [];
@@ -1685,13 +3010,26 @@ async function createSchematicCircuit(schematic, options) {
1685
3010
  devices: Object.freeze(deviceConfigs),
1686
3011
  connections: Object.freeze(connections)
1687
3012
  };
1688
- const circuit = await Circuit.create(input, runtime);
1689
3013
  return Object.freeze({
1690
- circuit,
3014
+ input,
1691
3015
  bindings: Object.freeze(bindings)
1692
3016
  });
1693
3017
  }
1694
3018
  /**
3019
+ * Compiles a schematic and reports which circuit device each symbol became.
3020
+ *
3021
+ * {@link createCircuitFromSchematic} returns only the circuit; the host needs
3022
+ * the symbol-to-device mapping as well.
3023
+ */
3024
+ async function createSchematicCircuit(schematic, options) {
3025
+ const { input, bindings } = compileSchematicInput(schematic, options);
3026
+ const circuit = await Circuit.create(input, options);
3027
+ return Object.freeze({
3028
+ circuit,
3029
+ bindings
3030
+ });
3031
+ }
3032
+ /**
1695
3033
  * Turns a designator or symbol id into a compiler-safe device id.
1696
3034
  *
1697
3035
  * Device ids prefix generated IR function names, so they must be identifiers.
@@ -1710,50 +3048,6 @@ function sanitizeDeviceId(value) {
1710
3048
  return /^[A-Za-z_]/.test(cleaned) ? cleaned : `d_${cleaned}`;
1711
3049
  }
1712
3050
  //#endregion
1713
- //#region src/host/circuit-host.ts
1714
- /** Picoseconds per circuit step used when mapping `Circuit.virtualTime` to simulation time. */
1715
- var DEFAULT_STEP_PS = 1e4;
1716
- /**
1717
- * Adapts one already-loaded unified-IR circuit to the RFC 0018 device host.
1718
- *
1719
- * This is the same-thread adapter for an owner that keeps `Circuit` accessors for itself (a
1720
- * diagnostics bench, for example). Application/canvas integration uses
1721
- * `createDeviceSimulationHostFromSandbox` from `@mica-js/simulator/sandbox` and never holds a circuit.
1722
- */
1723
- function createCircuitDeviceSimulationHost({ circuit, ownsCircuit = true, schematic, topics = [], stepPs = DEFAULT_STEP_PS, deliver }) {
1724
- const simTime = () => circuit.virtualTime * stepPs;
1725
- return {
1726
- async loadSchematic() {},
1727
- async reset() {
1728
- circuit.reset();
1729
- },
1730
- async tick(dt) {
1731
- if (!Number.isSafeInteger(dt) || dt <= 0) throw new TypeError(`DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`);
1732
- circuit.runBatch(1);
1733
- return {
1734
- simTime: simTime(),
1735
- executed: 1
1736
- };
1737
- },
1738
- async deliver(target, payload) {
1739
- deliver(target.symbol, target.port, payload);
1740
- },
1741
- onDidPublish: () => toDisposable(() => {}),
1742
- async getTopics() {
1743
- return topics;
1744
- },
1745
- async getSimTime() {
1746
- return simTime();
1747
- },
1748
- async getSchematic() {
1749
- return schematic;
1750
- },
1751
- async dispose() {
1752
- if (ownsCircuit) circuit.dispose();
1753
- }
1754
- };
1755
- }
1756
- //#endregion
1757
3051
  //#region src/host/runtime.ts
1758
3052
  var INSTANCE_ID = "device-simulation-host";
1759
3053
  function targetKey(deviceId, port) {
@@ -1806,14 +3100,13 @@ function buildRuntime(circuit, schematic, bindings, resolveDevice) {
1806
3100
  const inputs = /* @__PURE__ */ new Map();
1807
3101
  for (const binding of bindings) {
1808
3102
  const deviceBinding = resolveDevice(binding.reference);
1809
- const accessor = circuit.devices[binding.deviceId];
1810
- if (deviceBinding === void 0 || accessor === void 0) continue;
3103
+ if (deviceBinding === void 0) continue;
1811
3104
  const designator = symbols.get(binding.symbolId)?.designator ?? binding.symbolId;
1812
3105
  const device = {
1813
3106
  symbol: binding.symbolId,
3107
+ deviceId: binding.deviceId,
1814
3108
  designator,
1815
- binding: deviceBinding,
1816
- accessor
3109
+ binding: deviceBinding
1817
3110
  };
1818
3111
  devices.push(device);
1819
3112
  for (const topic of deviceBinding.topics ?? []) {
@@ -1833,6 +3126,7 @@ function buildRuntime(circuit, schematic, bindings, resolveDevice) {
1833
3126
  }
1834
3127
  return {
1835
3128
  circuit,
3129
+ boundary: deviceBoundaryOf(circuit),
1836
3130
  schematic,
1837
3131
  devices,
1838
3132
  topics: Object.freeze(topics),
@@ -1858,23 +3152,32 @@ function createSchematicDeviceSimulationHost(options) {
1858
3152
  let runtime;
1859
3153
  let simTimePs = 0;
1860
3154
  let disposed = false;
1861
- const publishOutputs = (active) => {
3155
+ const publishOutput = (device, port, payload) => {
3156
+ const topic = device.binding.topics?.find((value) => value.port === port && value.direction === "output");
3157
+ if (topic === void 0) throw new TypeError(`Unknown output topic ${device.designator}.${port}`);
3158
+ if (!payloadMatches(topic.type, payload)) throw new TypeError(`Invalid output payload for ${device.designator}.${port}`);
1862
3159
  if (!publishes.hasListeners) return;
1863
- for (const device of active.devices) for (const topic of device.binding.topics ?? []) {
1864
- if (topic.direction !== "output" || device.binding.read === void 0) continue;
1865
- const key = targetKey(device.symbol, topic.port);
1866
- const payload = device.binding.read(device.accessor, topic.port);
1867
- if (published.has(key) && samePayload(published.get(key), payload)) continue;
1868
- published.set(key, payload);
1869
- const publish = {
1870
- target: {
1871
- symbol: device.symbol,
1872
- port: topic.port
1873
- },
1874
- payload,
1875
- simTime: simTimePs
1876
- };
1877
- publishes.fire(publish);
3160
+ const key = targetKey(device.symbol, port);
3161
+ if (published.has(key) && samePayload(published.get(key), payload)) return;
3162
+ published.set(key, payload);
3163
+ publishes.fire({
3164
+ target: {
3165
+ symbol: device.symbol,
3166
+ port
3167
+ },
3168
+ payload,
3169
+ simTime: simTimePs
3170
+ });
3171
+ };
3172
+ const publishOutputs = (active, diagnostics) => {
3173
+ for (const device of active.devices) try {
3174
+ active.boundary.publishOutputs(device.deviceId, (port, payload) => publishOutput(device, port, payload));
3175
+ } catch (cause) {
3176
+ diagnostics.push({
3177
+ code: "device/output-failed",
3178
+ deviceId: device.symbol,
3179
+ message: cause instanceof Error ? cause.message : String(cause)
3180
+ });
1878
3181
  }
1879
3182
  };
1880
3183
  const clearRuntime = () => {
@@ -1896,6 +3199,7 @@ function createSchematicDeviceSimulationHost(options) {
1896
3199
  const compiled = await createSchematicCircuit(schematic, {
1897
3200
  ...symbolProvider === void 0 ? {} : { devices: symbolProvider },
1898
3201
  resolveDevice,
3202
+ ...options.electrical === void 0 ? {} : { electrical: options.electrical },
1899
3203
  instanceId: INSTANCE_ID
1900
3204
  });
1901
3205
  const next = buildRuntime(compiled.circuit, schematic, compiled.bindings, resolveDevice);
@@ -1927,16 +3231,40 @@ function createSchematicDeviceSimulationHost(options) {
1927
3231
  };
1928
3232
  }
1929
3233
  const queued = pending.splice(0, pending.length);
3234
+ const deliveries = /* @__PURE__ */ new Map();
1930
3235
  for (const delivery of queued) {
1931
- if (delivery.device.binding.deliver === void 0) throw new TypeError(`${delivery.device.binding.type} has no writable topic ${JSON.stringify(delivery.port)}`);
1932
- delivery.device.binding.deliver(delivery.device.accessor, delivery.port, delivery.payload);
3236
+ const values = deliveries.get(delivery.device) ?? [];
3237
+ values.push({
3238
+ port: delivery.port,
3239
+ payload: delivery.payload
3240
+ });
3241
+ deliveries.set(delivery.device, values);
3242
+ }
3243
+ const diagnostics = [];
3244
+ for (const device of active.devices) {
3245
+ const inputs = deliveries.get(device);
3246
+ if (inputs === void 0 && !active.boundary.hasInputHook(device.deviceId)) continue;
3247
+ try {
3248
+ active.boundary.deliverInputs(device.deviceId, inputs ?? []);
3249
+ } catch (cause) {
3250
+ diagnostics.push({
3251
+ code: "device/input-failed",
3252
+ deviceId: device.symbol,
3253
+ message: cause instanceof Error ? cause.message : String(cause)
3254
+ });
3255
+ }
3256
+ }
3257
+ const before = active.circuit.tickCount;
3258
+ try {
3259
+ active.circuit.runBatch(1, dt);
3260
+ } finally {
3261
+ simTimePs += dt * Number(active.circuit.tickCount - before);
1933
3262
  }
1934
- active.circuit.runBatch(1);
1935
- simTimePs += dt;
1936
- publishOutputs(active);
3263
+ publishOutputs(active, diagnostics);
1937
3264
  return {
1938
3265
  simTime: simTimePs,
1939
- executed: 1
3266
+ executed: Number(active.circuit.tickCount - before),
3267
+ ...diagnostics.length === 0 ? {} : { diagnostics: Object.freeze(diagnostics) }
1940
3268
  };
1941
3269
  },
1942
3270
  async deliver(target, payload) {
@@ -1947,7 +3275,6 @@ function createSchematicDeviceSimulationHost(options) {
1947
3275
  if (binding === void 0) throw new Error(`Unknown device input ${target.symbol}.${target.port}`);
1948
3276
  if (!payloadMatches(binding.topic.type, payload)) throw new TypeError(`${target.symbol}.${target.port} expects a ${binding.topic.type} payload`);
1949
3277
  const device = binding.device;
1950
- if (device.binding.deliver === void 0) throw new Error(`${device.binding.type} has no writable topic ${JSON.stringify(target.port)}`);
1951
3278
  pending.push({
1952
3279
  device,
1953
3280
  port: target.port,
@@ -2001,6 +3328,7 @@ function startDeviceSimulationHostGuest(port, options = {}) {
2001
3328
  return bytes;
2002
3329
  },
2003
3330
  ...devices === void 0 ? {} : { devices },
3331
+ ...options.electrical === void 0 ? {} : { electrical: options.electrical },
2004
3332
  resolveDevice: resolveDevice ?? (() => void 0)
2005
3333
  });
2006
3334
  let prepared;
@@ -2076,6 +3404,6 @@ function startDeviceSimulationHostGuest(port, options = {}) {
2076
3404
  };
2077
3405
  }
2078
3406
  //#endregion
2079
- export { Circuit, CircuitError, DEFAULT_RAILS, DEVICE_PIN_STRIDE, PIN_MODE, UNIFIED_PIN_CAPACITY, UnifiedIRCompilerError, compileCircuit, createCircuitDeviceSimulationHost, createCircuitFromSchematic, createModuleValidation, createSchematicCircuit, createSchematicDeviceSimulationHost, startDeviceSimulationHostGuest };
3407
+ export { Circuit, CircuitError, DEVICE_PIN_STRIDE, ElectricalDefinitionError, PIN_MODE, UNIFIED_PIN_CAPACITY, UnifiedIRCompilerError, compileCircuit, createCircuitFromSchematic, createModuleValidation, createSchematicCircuit, createSchematicDeviceSimulationHost, startDeviceSimulationHostGuest };
2080
3408
 
2081
3409
  //# sourceMappingURL=index.js.map