@mica-js/simulator 0.2.1 → 0.4.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,500 +1,2081 @@
1
- import { createPowerRuntime, createScheduler, timePs } from "@mica-js/core";
2
- import { deriveSchematicTopology, designatorOf, symbolRole, synthesizeDeviceSymbol } from "@mica-js/core/schematic";
3
- import { createDeviceInstance, loadDeviceModule } from "@mica-js/device";
4
- //#region src/errors.ts
5
- /** Error raised by the executor's host-facing calls. */
6
- var SimulatorError = class extends Error {
7
- name = "SimulatorError";
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";
5
+ import { createRpc } from "@mica-js/core/rpc";
6
+ import { loggerService } from "@mica-js/core/logging";
7
+ //#region src/unified-ir/validation.ts
8
+ /**
9
+ * Builds the validation grants a module needs to run on the reference engine or
10
+ * the JIT: every instruction the model uses, authorized once, plus a grant for
11
+ * each declared memory.
12
+ *
13
+ * `@mica-js/ir` deliberately keeps its core instruction list internal, so the
14
+ * names are collected from the generated bodies instead of being restated here.
15
+ *
16
+ * @param module - Generated module whose bodies and memories are granted.
17
+ * @param updateResources - Read-only byte regions that opt into the host-only
18
+ * versioned update path (for example MCU firmware patching).
19
+ */
20
+ function createModuleValidation(module, updateResources = []) {
21
+ const names = /* @__PURE__ */ new Set();
22
+ for (const fn of module.functions) {
23
+ const body = fn.body;
24
+ if (body === void 0) continue;
25
+ for (const block of body.blocks) {
26
+ for (const instruction of block.instructions) names.add(instruction.op);
27
+ if (block.terminator !== void 0) names.add(block.terminator.kind);
28
+ }
29
+ }
30
+ const instructions = Object.freeze([...names]);
31
+ const resources = module.memories.map((memory) => Object.freeze({
32
+ ref: memory.ref,
33
+ access: memory.writable ? "read-write" : "read"
34
+ }));
35
+ const memories = new Set(module.memories.map((memory) => memory.ref));
36
+ for (const ref of new Set(updateResources)) {
37
+ if (!memories.has(ref)) continue;
38
+ resources.push(Object.freeze({
39
+ ref,
40
+ access: "update"
41
+ }));
42
+ }
43
+ return Object.freeze({
44
+ supportedInstructions: instructions,
45
+ authorizedInstructions: instructions,
46
+ resources: Object.freeze(resources)
47
+ });
48
+ }
49
+ //#endregion
50
+ //#region src/unified-ir/pin-space.ts
51
+ /**
52
+ * Shared memory-layout constants of the unified IR compiler and devices.
53
+ *
54
+ * Every device of a circuit shares one global pin address space, so the
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
57
+ * checked at allocation time; the shared pin memories are sized to the pins a
58
+ * circuit actually declares, so a larger ceiling costs no runtime memory.
59
+ */
60
+ /** Global pin addresses available to one circuit (8 devices x 512 pins). */
61
+ var UNIFIED_PIN_CAPACITY = 4096;
62
+ /** Global pin addresses one device may own; enough for the largest packages. */
63
+ var DEVICE_PIN_STRIDE = 512;
64
+ /** Values stored in the global `pin_mode` array. */
65
+ var PIN_MODE = Object.freeze({
66
+ highZ: 0,
67
+ pushPull: 1,
68
+ openDrain: 2,
69
+ analog: 3
70
+ });
71
+ //#endregion
72
+ //#region src/unified-ir/compiler/types.ts
73
+ /** Error raised while compiling a circuit. */
74
+ var UnifiedIRCompilerError = class extends Error {
75
+ name = "UnifiedIRCompilerError";
8
76
  code;
9
- symbol;
77
+ deviceId;
78
+ pinName;
79
+ netId;
80
+ diagnostics;
10
81
  constructor(code, message, options = {}) {
11
82
  super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
12
83
  this.code = code;
13
- this.symbol = options.symbol;
84
+ this.deviceId = options.deviceId;
85
+ this.pinName = options.pinName;
86
+ this.netId = options.netId;
87
+ this.diagnostics = options.diagnostics ?? [];
14
88
  }
15
89
  };
16
90
  //#endregion
17
- //#region src/circuit.ts
18
- /** Synthetic pin owner for the supplies the schematic's power/ground symbols name. */
19
- var SUPPLY_INSTANCE = "power";
20
- /** Scheduler identity of the electrical network; distinct from every symbol id. */
21
- var POWER_INSTANCE_ID = "simulator/power";
22
- /** Every pin uses the same digital interpretation; module pins override mode and pull. */
23
- var PIN_MODEL = Object.freeze({
24
- kind: "ideal-voltage",
25
- minVoltage: 0,
26
- maxVoltage: 5,
27
- lowVoltage: .8,
28
- highVoltage: 2
29
- });
91
+ //#region src/unified-ir/compiler/allocator.ts
92
+ /** Generated device ids prefix IR function names, so they must be identifiers. */
93
+ var DEVICE_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
30
94
  /**
31
- * Wiring host for schemes that are drawn, not described.
95
+ * Allocates the circuit-wide pin and state address spaces.
96
+ *
97
+ * ```
98
+ * ids: 0 = drive1.PA0 1 = drive1.PA1 2 = sink1.anode 3 = sink1.cathode
99
+ * |<-- drive1 -->| |<----------- sink1 ----------->|
32
100
  *
33
- * Pass it as `DeviceSimExecutorOptions.host` and the executor mounts one electrical network per
34
- * runtime: the sheet's wires become nets, power/ground symbols become the supply rails, and every
35
- * device instance reads real pin voltages and connection states instead of host-recorded values.
101
+ * pin_mode[n] u8 pin_output[n] bool pin_input[n] bool (n = totalPins)
102
+ * device_state_bool[n] / device_state_u32[m] / ... (one array per used type)
103
+ * ```
36
104
  *
37
- * @example
38
- * createDeviceSimExecutor({ devices, host: createCircuitHost() });
105
+ * 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
107
+ * scalar type into one shared array, so a device's slot stays typed while all
108
+ * devices share one storage region.
39
109
  */
40
- function createCircuitHost(options = {}) {
41
- return ({ scheduler, schematic, modules }) => {
42
- const circuit = buildCircuit(schematic, modules, options);
43
- if (circuit === void 0) return {};
44
- const runtime = createPowerRuntime(scheduler, circuit.power, {
45
- instanceId: POWER_INSTANCE_ID,
46
- pinStates: circuit.pinStates,
47
- floating: { seed: 1 }
110
+ var GlobalResourceAllocator = class {
111
+ module;
112
+ constructor(module) {
113
+ this.module = module;
114
+ }
115
+ /** Allocates the shared pin memories, the pin space and the state space. */
116
+ allocate(devices) {
117
+ const pins = this.allocatePins(devices);
118
+ return Object.freeze({
119
+ memory: createPinMemory(this.module, Math.max(1, pins.totalPins)),
120
+ pins,
121
+ states: this.allocateStates(devices)
48
122
  });
49
- return {
50
- pinHost: runtime,
51
- topology: runtime,
52
- dispose: () => {
53
- runtime.destroy();
123
+ }
124
+ /**
125
+ * Packs every device pin into one contiguous global address space.
126
+ *
127
+ * @throws {UnifiedIRCompilerError} on invalid or duplicate device ids, more
128
+ * than {@link DEVICE_PIN_STRIDE} pins for one device, or more than
129
+ * {@link UNIFIED_PIN_CAPACITY} pins for the circuit.
130
+ */
131
+ allocatePins(devices) {
132
+ assertDeviceList(devices);
133
+ let totalPins = 0;
134
+ const pins = /* @__PURE__ */ new Map();
135
+ const allocations = /* @__PURE__ */ new Map();
136
+ for (const device of devices) {
137
+ const entries = pinEntries(device);
138
+ if (entries.length > 512) throw new UnifiedIRCompilerError("capacity-exceeded", `Device "${device.id}" declares ${entries.length} pins; one device may own at most 512`, { deviceId: device.id });
139
+ if (totalPins + entries.length > 4096) throw new UnifiedIRCompilerError("capacity-exceeded", `Device "${device.id}" does not fit: the circuit already uses ${totalPins} of ${UNIFIED_PIN_CAPACITY} global pins`, { deviceId: device.id });
140
+ const offset = totalPins;
141
+ const devicePins = /* @__PURE__ */ new Map();
142
+ const resolved = /* @__PURE__ */ new Map();
143
+ for (const [name, descriptor] of entries) {
144
+ const globalPinId = totalPins;
145
+ totalPins += 1;
146
+ const direction = resolvePinDirection(descriptor, device.id, name);
147
+ const { role, senses } = resolvePinRole(direction, descriptor?.role, device.id, name);
148
+ devicePins.set(name, globalPinId);
149
+ resolved.set(name, Object.freeze({
150
+ name,
151
+ deviceId: device.id,
152
+ globalPinId,
153
+ direction,
154
+ role,
155
+ senses
156
+ }));
157
+ pins.set(`${device.id}.${name}`, globalPinId);
54
158
  }
55
- };
159
+ allocations.set(device.id, Object.freeze({
160
+ deviceId: device.id,
161
+ offset,
162
+ pins: devicePins,
163
+ resolved
164
+ }));
165
+ }
166
+ return Object.freeze({
167
+ pins,
168
+ devices: allocations,
169
+ totalPins,
170
+ capacity: UNIFIED_PIN_CAPACITY
171
+ });
172
+ }
173
+ /**
174
+ * Allocates one typed slot per declared device state and creates the backing
175
+ * `device_state_<type>` arrays.
176
+ *
177
+ * @throws {UnifiedIRCompilerError} when a state declaration is malformed.
178
+ */
179
+ allocateStates(devices) {
180
+ assertDeviceList(devices);
181
+ const plans = [];
182
+ const slotsByDevice = /* @__PURE__ */ new Map();
183
+ const plansByType = /* @__PURE__ */ new Map();
184
+ for (const device of devices) {
185
+ const slots = /* @__PURE__ */ new Map();
186
+ slotsByDevice.set(device.id, slots);
187
+ for (const [name, declaration] of stateEntries(device)) {
188
+ const plan = {
189
+ deviceId: device.id,
190
+ name,
191
+ type: declaration.type,
192
+ initial: declaration.initial,
193
+ slot: plans.length
194
+ };
195
+ plans.push(plan);
196
+ const typePlans = plansByType.get(plan.type);
197
+ if (typePlans === void 0) plansByType.set(plan.type, [plan]);
198
+ else typePlans.push(plan);
199
+ }
200
+ }
201
+ const arrays = /* @__PURE__ */ new Map();
202
+ const totals = /* @__PURE__ */ new Map();
203
+ for (const [type, typePlans] of plansByType) {
204
+ const array = this.module.array(`device_state_${type}`, type, typePlans.map((plan) => plan.initial));
205
+ arrays.set(type, array);
206
+ totals.set(type, typePlans.length);
207
+ typePlans.forEach((plan, index) => {
208
+ const slot = Object.freeze({
209
+ name: plan.name,
210
+ deviceId: plan.deviceId,
211
+ type,
212
+ array,
213
+ index,
214
+ slot: plan.slot
215
+ });
216
+ slotsByDevice.get(plan.deviceId)?.set(plan.name, slot);
217
+ });
218
+ }
219
+ const devicesMap = /* @__PURE__ */ new Map();
220
+ for (const [deviceId, slots] of slotsByDevice) devicesMap.set(deviceId, slots);
221
+ return Object.freeze({
222
+ devices: devicesMap,
223
+ arrays,
224
+ totals,
225
+ totalStates: plans.length
226
+ });
227
+ }
228
+ };
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
+ /** First state slot ordinal of every device; used for `DeviceMetadata.stateOffset`. */
244
+ function stateOffsetOf(states, deviceId) {
245
+ let offset = 0;
246
+ for (const [id, slots] of states.devices) {
247
+ if (id === deviceId) return offset;
248
+ offset += slots.size;
249
+ }
250
+ return offset;
251
+ }
252
+ function assertDeviceList(devices) {
253
+ if (!Array.isArray(devices) || devices.length === 0) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput.devices must be a non-empty array");
254
+ const ids = /* @__PURE__ */ new Set();
255
+ for (const device of devices) {
256
+ if (device === null || typeof device !== "object" || Array.isArray(device)) throw new UnifiedIRCompilerError("invalid-input", "Every device must be an object");
257
+ const { id, type, description } = device;
258
+ if (typeof id !== "string" || !DEVICE_ID_PATTERN.test(id)) throw new UnifiedIRCompilerError("invalid-input", `Device id ${JSON.stringify(id)} must be an identifier ([A-Za-z_][A-Za-z0-9_]*) because it prefixes generated IR function names`);
259
+ if (ids.has(id)) throw new UnifiedIRCompilerError("duplicate-device", `Duplicate device id "${id}"; every device id must be unique`, { deviceId: id });
260
+ ids.add(id);
261
+ if (typeof type !== "string" || type.length === 0) throw new UnifiedIRCompilerError("invalid-input", `Device "${id}" needs a non-empty type`, { deviceId: id });
262
+ if (description === null || typeof description !== "object") throw new UnifiedIRCompilerError("invalid-input", `Device "${id}" needs a description object with a pins map`, { deviceId: id });
263
+ }
264
+ }
265
+ function pinEntries(device) {
266
+ const raw = device.description.pins;
267
+ let entries;
268
+ if (raw instanceof Map) entries = [...raw.entries()];
269
+ else if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) entries = Object.entries(raw);
270
+ else throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" needs description.pins as a Map or a plain object`, { deviceId: device.id });
271
+ for (const [name, descriptor] of entries) {
272
+ if (typeof name !== "string" || name.length === 0) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" declares a pin with an empty name`, { deviceId: device.id });
273
+ if (name.includes(".")) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" pin "${name}" may not contain ".": connection endpoints use "device.pin"`, {
274
+ deviceId: device.id,
275
+ pinName: name
276
+ });
277
+ if (descriptor !== void 0 && (descriptor === null || typeof descriptor !== "object")) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" pin "${name}" description must be an object`, {
278
+ deviceId: device.id,
279
+ pinName: name
280
+ });
281
+ }
282
+ return entries;
283
+ }
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
56
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
+ function stateEntries(device) {
332
+ const raw = device.description.states;
333
+ if (raw === void 0) return [];
334
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" needs description.states as a plain object`, { deviceId: device.id });
335
+ return Object.entries(raw).map(([name, declaration]) => {
336
+ if (typeof name !== "string" || name.length === 0) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" declares a state with an empty name`, { deviceId: device.id });
337
+ if (declaration === null || typeof declaration !== "object") throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" state "${name}" must be an object with type and initial`, { deviceId: device.id });
338
+ const type = declaration.type;
339
+ if (typeof type !== "string" || !SCALAR_TYPES.includes(type)) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" state "${name}" has type ${JSON.stringify(type)}; expected one of ${SCALAR_TYPES.join(", ")}`, { deviceId: device.id });
340
+ assertStateInitial(device.id, name, type, declaration.initial);
341
+ return [name, declaration];
342
+ });
57
343
  }
344
+ function assertStateInitial(deviceId, name, type, initial) {
345
+ if (type === "bool") {
346
+ if (typeof initial !== "boolean") throw new UnifiedIRCompilerError("invalid-input", `Device "${deviceId}" state "${name}" (bool) needs a boolean initial value`, { deviceId });
347
+ return;
348
+ }
349
+ if (typeof initial !== "number" || !Number.isFinite(initial)) throw new UnifiedIRCompilerError("invalid-input", `Device "${deviceId}" state "${name}" (${type}) needs a finite numeric initial value`, { deviceId });
350
+ if (INTEGER_TYPES.includes(type) && !Number.isInteger(initial)) throw new UnifiedIRCompilerError("invalid-input", `Device "${deviceId}" state "${name}" (${type}) needs an integer initial value`, { deviceId });
351
+ }
352
+ //#endregion
353
+ //#region src/unified-ir/compiler/device-gen.ts
58
354
  /**
59
- * Turns a schematic into a topology plus power definition.
355
+ * Generates one IR function per device phase into the unified module.
60
356
  *
61
- * Wire geometry is resolved by `deriveSchematicTopology` against synthesized symbols, so the
62
- * simulator never has to know pin coordinates. Every device pin becomes a topology pin, each net
63
- * becomes one external wire, and the device descriptions' connections become the switchable pairs.
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.
64
362
  *
65
- * @returns `undefined` when the schematic declares no pins at all (nothing to solve).
363
+ * The compiler ships no device models: every description must declare its own
364
+ * pins, states and behaviors (or a `kernel`) before it reaches this generator.
66
365
  */
67
- function buildCircuit(document, modules, options = {}) {
68
- const supplyVoltage = options.supplyVoltage ?? 5;
69
- const derived = deriveSchematicTopology(document, { devices: createSymbolProvider(modules) });
70
- if (derived.pins.length === 0) return;
71
- const kinds = pinKinds(document, modules);
72
- const pins = derived.pins.map((pin) => ({
73
- instanceId: pin.symbolId,
74
- pinName: pin.pinId,
75
- kind: kinds.get(`${pin.symbolId}\u0000${pin.pinId}`) ?? "signal"
76
- }));
77
- const wires = [];
78
- let supplyPin;
79
- let groundPin;
80
- for (const [index, net] of derived.nets.entries()) {
81
- const members = net.members.filter((member) => member.kind === "pin").map((member) => ({
82
- instanceId: member.symbolId,
83
- pinName: member.pinId
84
- }));
85
- const ground = net.members.some((member) => member.kind === "ground");
86
- const power = net.members.some((member) => member.kind === "power");
87
- const name = net.name ?? `net-${index}`;
88
- if (power) {
89
- supplyPin ??= name;
90
- pins.push({
91
- instanceId: SUPPLY_INSTANCE,
92
- pinName: name,
93
- kind: "power"
94
- });
95
- members.push({
96
- instanceId: SUPPLY_INSTANCE,
97
- pinName: name
98
- });
366
+ var DeviceIRGenerator = class {
367
+ context;
368
+ constructor(context) {
369
+ this.context = context;
370
+ }
371
+ /**
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.
374
+ */
375
+ generate(device) {
376
+ const allocation = this.context.pins.devices.get(device.id);
377
+ if (allocation === void 0) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" has no pin allocation; allocate resources before generating IR`, { deviceId: device.id });
378
+ const kernelResult = device.description.kernel?.({
379
+ deviceId: device.id,
380
+ config: device.config,
381
+ module: this.context.module,
382
+ memory: this.context.memory,
383
+ pins: [...allocation.resolved.values()].map((pin) => Object.freeze({
384
+ name: pin.name,
385
+ globalPinId: pin.globalPinId,
386
+ role: pin.role
387
+ }))
388
+ });
389
+ const kernelRuntime = kernelResult !== void 0 && isKernelRuntime(kernelResult) ? kernelResult : void 0;
390
+ const behaviors = kernelRuntime === void 0 ? kernelResult ?? device.description.behaviors : void 0;
391
+ let initialize;
392
+ let tick;
393
+ let update;
394
+ if (kernelRuntime !== void 0) {
395
+ initialize = phaseFromRef(this.context.module, device.id, kernelRuntime.initialize);
396
+ tick = phaseFromRef(this.context.module, device.id, kernelRuntime.tick);
397
+ update = phaseFromRef(this.context.module, device.id, kernelRuntime.update);
398
+ } 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);
99
403
  }
100
- if (ground) {
101
- groundPin ??= name;
102
- pins.push({
103
- instanceId: SUPPLY_INSTANCE,
104
- pinName: name,
105
- kind: "gnd"
106
- });
107
- members.push({
108
- instanceId: SUPPLY_INSTANCE,
109
- pinName: name
110
- });
404
+ const functions = [];
405
+ for (const phase of [
406
+ initialize,
407
+ tick,
408
+ update
409
+ ]) if (phase !== void 0) functions.push(phase.name);
410
+ const metadata = Object.freeze({
411
+ deviceId: device.id,
412
+ type: device.type,
413
+ pinOffset: allocation.offset,
414
+ stateOffset: stateOffsetOf(this.context.states, device.id),
415
+ pins: allocation.pins,
416
+ states: this.context.states.devices.get(device.id) ?? /* @__PURE__ */ new Map(),
417
+ functions: Object.freeze(functions),
418
+ initialize: initialize?.name,
419
+ tick: tick?.name,
420
+ update: update?.name,
421
+ accessor: device.description.accessor,
422
+ kernel: device.description.kernel
423
+ });
424
+ return Object.freeze({
425
+ metadata,
426
+ entry: Object.freeze({
427
+ deviceId: device.id,
428
+ initialize: initialize?.ref,
429
+ tick: tick?.ref,
430
+ update: update?.ref
431
+ })
432
+ });
433
+ }
434
+ generatePhase(device, allocation, phase, behavior) {
435
+ if (behavior === void 0) return void 0;
436
+ const name = `${device.id}_${phase}`;
437
+ const ref = this.context.module.func(name, {
438
+ params: [],
439
+ results: []
440
+ });
441
+ ref.body((b) => {
442
+ behavior(this.createApi(device, allocation, b));
443
+ b.return([]);
444
+ });
445
+ return {
446
+ name,
447
+ ref
448
+ };
449
+ }
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
+ 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);
111
476
  }
112
- if (members.length > 0) wires.push({
113
- wireId: `net-${index}`,
114
- pins: members,
115
- ...ground ? { globalGnd: true } : {}
477
+ const slots = this.context.states.devices.get(device.id);
478
+ return Object.freeze({
479
+ deviceId: device.id,
480
+ builder,
481
+ module: this.context.module,
482
+ memory: this.context.memory,
483
+ 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
+ },
497
+ state(name) {
498
+ const slot = slots?.get(name);
499
+ if (slot === void 0) throw new UnifiedIRCompilerError("state-not-found", `Device "${device.id}" has no state "${name}". Available: [${[...slots?.keys() ?? []].join(", ")}]`, { deviceId: device.id });
500
+ return createStateHandle(device.id, slot, builder);
501
+ }
116
502
  });
117
503
  }
118
- const devices = [];
119
- if (supplyPin !== void 0 && groundPin !== void 0) devices.push({
120
- instanceId: SUPPLY_INSTANCE,
121
- powerDomains: { board: {
122
- supply: supplyPin,
123
- ground: groundPin,
124
- voltage: {
125
- turnOn: 3,
126
- turnOff: 2
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());
127
522
  }
128
- } }
523
+ });
524
+ }
525
+ };
526
+ function createStateHandle(deviceId, slot, builder) {
527
+ const array = slot.array;
528
+ const index = builder.const("u32", slot.index);
529
+ return Object.freeze({
530
+ name: slot.name,
531
+ type: slot.type,
532
+ index: slot.index,
533
+ load() {
534
+ return builder.array.load(array, index);
535
+ },
536
+ store(value) {
537
+ builder.array.store(array, index, value);
538
+ }
129
539
  });
130
- const topology = {
131
- pins,
132
- wires,
133
- connections: deviceConnections(document, modules)
134
- };
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 });
135
558
  return {
136
- topology,
137
- power: {
138
- topology,
139
- devices
140
- },
141
- pinStates: pins.map((pin) => {
142
- const rail = pin.instanceId === SUPPLY_INSTANCE;
143
- if (rail && pin.kind === "power") return {
144
- instanceId: pin.instanceId,
145
- pinName: pin.pinName,
146
- powerReady: true,
147
- mode: "analog",
148
- outputEnabled: true,
149
- pull: "none",
150
- voltageIntent: supplyVoltage,
151
- model: PIN_MODEL
152
- };
153
- if (rail) return {
154
- instanceId: pin.instanceId,
155
- pinName: pin.pinName,
156
- powerReady: true,
157
- mode: "push-pull",
158
- outputEnabled: true,
159
- pull: "none",
160
- digitalIntent: false,
161
- model: PIN_MODEL
162
- };
163
- return {
164
- instanceId: pin.instanceId,
165
- pinName: pin.pinName,
166
- powerReady: true,
167
- mode: "high-z",
168
- outputEnabled: false,
169
- pull: "none",
170
- model: PIN_MODEL
171
- };
172
- })
559
+ name: definition.name,
560
+ ref
173
561
  };
174
562
  }
563
+ //#endregion
564
+ //#region src/unified-ir/compiler/mainloop-gen.ts
565
+ /** Names used when the caller does not override them. */
566
+ var DEFAULT_ENTRY_POINT_NAMES = Object.freeze({
567
+ tick: "unified_tick",
568
+ initialize: "unified_initialize",
569
+ batch: "unified_tick_batch"
570
+ });
175
571
  /**
176
- * Symbols for every device the schematic names.
572
+ * Generates the circuit entries.
573
+ *
574
+ * ```text
575
+ * unified_initialize: // once, before the first tick
576
+ * drive1_initialize()
577
+ * sink1_initialize() // if the device has one
578
+ *
579
+ * unified_tick: // one simulation step
580
+ * drive1_tick() // drivers publish their outputs
581
+ * solve_net_0() // the electrical network resolves
582
+ * sink1_update() // loads observe the solved inputs
177
583
  *
178
- * The synthesized geometry must be the same one the `.sch` was authored against, so the name is
179
- * the full device id and pins keep their declared side; that is what the playground generator uses.
584
+ * unified_tick_batch(count): // the same step, looped inside the IR
585
+ * for i in 0 .. count { <step> }
586
+ * ```
587
+ *
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.
180
591
  */
181
- function createSymbolProvider(modules) {
182
- const cache = /* @__PURE__ */ new Map();
183
- const symbolOf = (deviceId) => {
184
- if (!cache.has(deviceId)) {
185
- const module = modules.get(deviceId);
186
- cache.set(deviceId, module === void 0 ? void 0 : synthesizeDeviceSymbol({
187
- name: deviceId,
188
- pins: Object.fromEntries([...module.description.pins.values()].map((pin) => [pin.key, { side: pin.side }]))
189
- }));
592
+ var MainLoopGenerator = class {
593
+ module;
594
+ constructor(module) {
595
+ this.module = module;
596
+ }
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
+ }
190
616
  }
191
- return cache.get(deviceId);
192
- };
193
- return {
194
- getDeviceSymbol: (reference) => symbolOf(`${reference.packageId}:${reference.deviceId}`),
195
- getDeviceName: (reference) => `${reference.packageId}:${reference.deviceId}`
196
- };
197
- }
198
- function pinKinds(document, modules) {
199
- const kinds = /* @__PURE__ */ new Map();
200
- for (const symbol of document.sheet.symbols) {
201
- const module = modules.get(symbol.device);
202
- if (module === void 0) continue;
203
- for (const pin of module.description.pins.values()) kinds.set(`${symbol.id}\u0000${pin.key}`, pin.kind);
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);
204
640
  }
205
- return kinds;
206
- }
207
- function deviceConnections(document, modules) {
208
- const connections = [];
209
- for (const symbol of document.sheet.symbols) {
210
- const module = modules.get(symbol.device);
211
- if (module === void 0) continue;
212
- for (const [connectionId, descriptor] of module.description.connections) {
213
- const [first, second] = descriptor.pins;
214
- if (first === void 0 || second === void 0) continue;
215
- connections.push({
216
- instanceId: symbol.id,
217
- connectionId,
218
- pins: [first, second],
219
- initial: descriptor.initial
641
+ /** 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);
644
+ 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
+ }
655
+ };
656
+ const initialize = this.module.func(names.initialize, {
657
+ params: [],
658
+ results: []
659
+ });
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
+ });
667
+ const tick = this.module.func(names.tick, {
668
+ params: [],
669
+ results: []
670
+ });
671
+ tick.body((b) => {
672
+ emitStep(b);
673
+ b.return([]);
674
+ });
675
+ const batch = this.module.func(names.batch, {
676
+ params: ["u32"],
677
+ results: []
678
+ });
679
+ batch.body((b, [count]) => {
680
+ const header = b.block(["u32"]);
681
+ const body = b.block(["u32"]);
682
+ const done = b.block([]);
683
+ b.jump(header, [b.const("u32", 0)]);
684
+ b.at(header, (ib, [index]) => ib.branch(ib.int.cmp("lt", index, count), {
685
+ target: body,
686
+ args: [index]
687
+ }, {
688
+ target: done,
689
+ args: []
690
+ }));
691
+ b.at(body, (ib, [index]) => {
692
+ emitStep(ib);
693
+ ib.jump(header, [ib.int.add(index, ib.const("u32", 1))]);
220
694
  });
695
+ b.at(done, (ib) => ib.return([]));
696
+ });
697
+ return Object.freeze({
698
+ names,
699
+ initialize,
700
+ tick,
701
+ batch,
702
+ order
703
+ });
704
+ }
705
+ };
706
+ //#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);
221
768
  }
769
+ return driven;
222
770
  }
223
- return connections;
224
- }
771
+ };
225
772
  //#endregion
226
- //#region src/create-device-sim-executor.ts
227
- var EMPTY_SCHEMATIC = Object.freeze({
228
- version: 1,
229
- sheet: Object.freeze({
230
- symbols: Object.freeze([]),
231
- wires: Object.freeze([]),
232
- junctions: Object.freeze([])
233
- })
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
234
779
  });
235
- var EMPTY_TOPICS = Object.freeze([]);
236
780
  /**
237
- * Creates an executor for one schematic at a time.
781
+ * Analyses the pin-to-pin connections of a circuit.
238
782
  *
239
- * Every component symbol becomes a device instance on a private scheduler. Pin and connection
240
- * wiring comes from `options.host`, which is rebuilt for every runtime so it always belongs to the
241
- * scheduler that is running; schematic wiring itself is available as `createCircuitHost`.
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.
242
792
  */
243
- function createDeviceSimExecutor(options) {
244
- return new DeviceSimExecutorImpl(options);
245
- }
246
- var DeviceSimExecutorImpl = class {
247
- #options;
248
- #publishListeners = /* @__PURE__ */ new Set();
249
- #pending = [];
250
- /** Loaded device modules, so `reset` can rebuild instances without touching the provider. */
251
- #modules = /* @__PURE__ */ new Map();
252
- #runtime;
253
- #schematic = EMPTY_SCHEMATIC;
254
- #state = "idle";
255
- constructor(options) {
256
- this.#options = options;
257
- }
258
- getState() {
259
- return this.#state;
260
- }
261
- getSimTime() {
262
- return this.#runtime?.scheduler.now ?? timePs(0);
263
- }
264
- getSchematic() {
265
- return this.#schematic;
266
- }
267
- getTopics() {
268
- return this.#runtime?.topics ?? EMPTY_TOPICS;
269
- }
270
- async loadSchematic(document) {
271
- this.#assertNotDisposed();
272
- await this.#loadModules(document);
273
- const runtime = this.#buildRuntime(document);
274
- this.#teardown();
275
- this.#runtime = runtime;
276
- this.#schematic = document;
277
- this.#state = "ready";
278
- }
279
- advance(delta) {
280
- const runtime = this.#requireRuntime();
281
- if (!Number.isSafeInteger(delta) || delta <= 0) throw new SimulatorError("simulator/invalid-delta", `advance expects a positive whole number of picoseconds, received ${String(delta)}.`);
282
- const { scheduler } = runtime;
283
- const from = scheduler.now;
284
- this.#flush(runtime);
285
- try {
286
- const result = scheduler.start({ until: from + delta });
287
- return Object.freeze({
288
- from,
289
- to: result.timePs,
290
- executed: result.executed,
291
- reason: result.reason
292
- });
293
- } catch (cause) {
294
- this.#state = "faulted";
295
- this.#report({
296
- code: "simulator/advance-failed",
297
- message: `Advancing ${delta} ps failed.`,
298
- cause
299
- });
300
- throw cause;
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);
301
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
+ });
302
896
  }
303
- onPublish(listener) {
304
- if (this.#state === "disposed") return () => {};
305
- this.#publishListeners.add(listener);
306
- return () => {
307
- this.#publishListeners.delete(listener);
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
308
928
  };
309
929
  }
310
- deliver(target, payload) {
311
- const instance = this.#requireRuntime().instances.get(target.symbol);
312
- if (instance === void 0) throw new SimulatorError("simulator/unknown-target", `The schematic has no symbol "${target.symbol}".`, { symbol: target.symbol });
313
- const port = instance.description.ports.get(target.port);
314
- if (port === void 0) throw new SimulatorError("simulator/unknown-port", `Device ${JSON.stringify(instance.deviceId)} has no port "${target.port}".`, { symbol: target.symbol });
315
- if (port.direction !== "input") throw new SimulatorError("simulator/unknown-port", `Port "${target.port}" of symbol "${target.symbol}" is an output, not an input.`, { symbol: target.symbol });
316
- this.#pending.push(Object.freeze({
317
- target: Object.freeze({ ...target }),
318
- payload
319
- }));
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;
320
981
  }
321
- reset() {
322
- this.#assertNotDisposed();
323
- if (this.#runtime === void 0) {
324
- this.#pending.length = 0;
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);
325
990
  return;
326
991
  }
327
- const runtime = this.#buildRuntime(this.#schematic);
328
- this.#teardown();
329
- this.#runtime = runtime;
330
- this.#state = "ready";
992
+ this.parent.set(rightRoot, leftRoot);
993
+ if (leftRank === rightRank) this.rank.set(leftRoot, leftRank + 1);
331
994
  }
332
- dispose() {
333
- if (this.#state === "disposed") return;
334
- this.#state = "disposed";
335
- this.#publishListeners.clear();
336
- this.#teardown();
337
- this.#modules.clear();
338
- }
339
- /** Loads the devices the schematic names; already loaded ids are reused. */
340
- async #loadModules(document) {
341
- for (const symbol of document.sheet.symbols) {
342
- if (!isComponent(symbol) || this.#modules.has(symbol.device)) continue;
995
+ };
996
+ //#endregion
997
+ //#region src/unified-ir/compiler/index.ts
998
+ /**
999
+ * Compiles several devices and their wiring into one unified IR module (U01).
1000
+ *
1001
+ * Device models are caller-supplied: every entry of `devices` carries the pins,
1002
+ * states and behaviors (or `kernel`) its type needs.
1003
+ *
1004
+ * ```ts
1005
+ * const circuit = compileCircuit({
1006
+ * devices: [
1007
+ * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },
1008
+ * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },
1009
+ * ],
1010
+ * connections: [
1011
+ * { from: 'drive1.channel0', to: 'sink1.anode' },
1012
+ * { from: 'sink1.cathode', to: 'GND' },
1013
+ * ],
1014
+ * });
1015
+ *
1016
+ * const jit = createIRJIT(circuit.module, { validation: circuit.validation });
1017
+ * jit.execute(circuit.entryPoints.refs.initialize, []);
1018
+ * jit.execute(circuit.entryPoints.refs.tick, []); // drive1 + nets + sink1
1019
+ * ```
1020
+ *
1021
+ * The pipeline is: validate the input, allocate the global pin and state
1022
+ * spaces, analyse the electrical topology, generate one function per device
1023
+ * phase, generate one solver per net, generate the main loop, then validate the
1024
+ * resulting module with `validateIR`.
1025
+ *
1026
+ * @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown
1027
+ * pins, electrical conflicts, or when the generated module fails validation.
1028
+ */
1029
+ function compileCircuit(input, options = {}) {
1030
+ const { devices, connections } = validateInput(input);
1031
+ const resolvedOptions = validateOptions(options);
1032
+ const names = resolveEntryNames(resolvedOptions);
1033
+ 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);
1037
+ const generator = new DeviceIRGenerator({
1038
+ module,
1039
+ memory: allocation.memory,
1040
+ pins: allocation.pins,
1041
+ states: allocation.states
1042
+ });
1043
+ 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);
1050
+ const validation = createModuleValidation(module, devices.flatMap((device) => device.description.updateResources ?? []));
1051
+ if (resolvedOptions.validate !== false) validateModule(module, validation);
1052
+ const deviceMap = new Map(generated.map((device) => [device.metadata.deviceId, device.metadata]));
1053
+ return Object.freeze({
1054
+ module,
1055
+ entryPoints: Object.freeze({
1056
+ tick: loop.names.tick,
1057
+ initialize: loop.names.initialize,
1058
+ batch: loop.names.batch,
1059
+ refs: Object.freeze({
1060
+ tick: loop.tick,
1061
+ initialize: loop.initialize,
1062
+ batch: loop.batch
1063
+ })
1064
+ }),
1065
+ pinMap: allocation.pins.pins,
1066
+ deviceMap,
1067
+ netlist,
1068
+ pins: allocation.pins,
1069
+ states: allocation.states,
1070
+ memory: allocation.memory,
1071
+ validation,
1072
+ executionOrder: loop.order,
1073
+ functions: Object.freeze(module.functions.map((fn) => fn.name))
1074
+ });
1075
+ }
1076
+ function validateInput(input) {
1077
+ if (input === null || typeof input !== "object" || Array.isArray(input)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput must be an object with devices and connections");
1078
+ const { devices, connections } = input;
1079
+ if (!Array.isArray(devices) || devices.length === 0) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput.devices must be a non-empty array");
1080
+ if (!Array.isArray(connections)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput.connections must be an array");
1081
+ return {
1082
+ devices,
1083
+ connections
1084
+ };
1085
+ }
1086
+ function validateOptions(options) {
1087
+ if (options === null || typeof options !== "object" || Array.isArray(options)) throw new UnifiedIRCompilerError("invalid-input", "Compile options must be an object");
1088
+ const resolved = options;
1089
+ 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
+ return resolved;
1095
+ }
1096
+ function resolveEntryNames(options) {
1097
+ const names = {
1098
+ tick: options.entryPointNames?.tick ?? DEFAULT_ENTRY_POINT_NAMES.tick,
1099
+ initialize: options.entryPointNames?.initialize ?? DEFAULT_ENTRY_POINT_NAMES.initialize,
1100
+ batch: options.entryPointNames?.batch ?? DEFAULT_ENTRY_POINT_NAMES.batch
1101
+ };
1102
+ for (const [role, name] of Object.entries(names)) if (typeof name !== "string" || name.length === 0) throw new UnifiedIRCompilerError("invalid-input", `Entry point names.${role} must be a non-empty string`);
1103
+ if (new Set(Object.values(names)).size !== 3) throw new UnifiedIRCompilerError("invalid-input", `Entry point names must be distinct: ${JSON.stringify(names)}`);
1104
+ return Object.freeze(names);
1105
+ }
1106
+ function assertNoNameCollisions(devices, solverNames, names) {
1107
+ const reserved = /* @__PURE__ */ new Set([
1108
+ names.tick,
1109
+ names.initialize,
1110
+ names.batch,
1111
+ ...solverNames
1112
+ ]);
1113
+ for (const device of devices) for (const phase of [
1114
+ "initialize",
1115
+ "tick",
1116
+ "update"
1117
+ ]) {
1118
+ const generated = `${device.id}_${phase}`;
1119
+ if (reserved.has(generated)) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" generates "${generated}", which collides with another generated function; rename the device or the entry point`, { deviceId: device.id });
1120
+ }
1121
+ }
1122
+ function validateModule(module, validation) {
1123
+ const result = validateIR(module, validation);
1124
+ if (result.ok) return;
1125
+ const details = result.diagnostics.map((entry) => `- [${entry.code}] ${entry.message} at ${entry.location.path}`).join("\n");
1126
+ throw new UnifiedIRCompilerError("invalid-ir", `Generated IR failed validateIR (${result.diagnostics.length} diagnostic(s)):\n${details}`);
1127
+ }
1128
+ //#endregion
1129
+ //#region src/unified-ir/runtime/types.ts
1130
+ /**
1131
+ * Error raised while driving a `Circuit`.
1132
+ *
1133
+ * The code is stable and machine-checkable, and the message always names the
1134
+ * offending device/pin/state plus the values that would have been accepted.
1135
+ */
1136
+ var CircuitError = class extends Error {
1137
+ name = "CircuitError";
1138
+ code;
1139
+ deviceId;
1140
+ pinName;
1141
+ stateName;
1142
+ constructor(code, message, options = {}) {
1143
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
1144
+ this.code = code;
1145
+ this.deviceId = options.deviceId;
1146
+ this.pinName = options.pinName;
1147
+ this.stateName = options.stateName;
1148
+ }
1149
+ };
1150
+ //#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) {
1200
+ context.assertActive();
1201
+ const slot = stateOf(device, name);
1202
+ return storage.loadArray(slot.array, slot.index);
1203
+ },
1204
+ setState(name, value) {
1205
+ context.assertActive();
1206
+ const slot = stateOf(device, name);
1207
+ const accepted = coerceStateValue(device, slot, value);
343
1208
  try {
344
- this.#modules.set(symbol.device, await loadDeviceModule(symbol.device, this.#options.devices));
1209
+ storage.storeArray(slot.array, slot.index, accepted);
345
1210
  } catch (cause) {
346
- throw new SimulatorError("simulator/device-load-failed", `Device ${JSON.stringify(symbol.device)} of symbol "${symbol.id}" could not be loaded.`, {
347
- symbol: symbol.id,
1211
+ throw new CircuitError("invalid-state-value", `State "${device.deviceId}.${name}" (${slot.type}) rejected ${String(value)}`, {
1212
+ deviceId: device.deviceId,
1213
+ stateName: name,
348
1214
  cause
349
1215
  });
350
1216
  }
351
1217
  }
1218
+ };
1219
+ return Object.freeze(accessor);
1220
+ }
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) {
1232
+ 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
+ });
1237
+ return slot;
1238
+ }
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
+ /**
1246
+ * Validates a host-written state value against the declared scalar type.
1247
+ * Range checks stay in storage, which owns the encoding.
1248
+ */
1249
+ function coerceStateValue(device, slot, value) {
1250
+ if (slot.type === "bool") {
1251
+ if (typeof value !== "boolean") throw new CircuitError("invalid-state-value", `State "${device.deviceId}.${slot.name}" is bool and needs true or false, received ${String(value)}`, {
1252
+ deviceId: device.deviceId,
1253
+ stateName: slot.name
1254
+ });
1255
+ return value;
352
1256
  }
353
- /** Mounts every symbol of the schematic and runs the `initialize` pass on a fresh scheduler. */
354
- #buildRuntime(document) {
355
- const scheduler = this.#options.scheduler === void 0 ? createScheduler() : createScheduler(this.#options.scheduler);
356
- const host = this.#options.host?.({
357
- scheduler,
358
- schematic: document,
359
- modules: this.#modules
1257
+ if (slot.type === "f32" || slot.type === "f64") {
1258
+ if (typeof value === "number" || isFloatBits(value)) return value;
1259
+ throw new CircuitError("invalid-state-value", `State "${device.deviceId}.${slot.name}" is ${slot.type} and needs a number or FloatBits`, {
1260
+ deviceId: device.deviceId,
1261
+ stateName: slot.name
360
1262
  });
361
- const instances = /* @__PURE__ */ new Map();
362
- const topics = [];
363
- try {
364
- for (const symbol of document.sheet.symbols) {
365
- if (!isComponent(symbol)) continue;
366
- const instance = this.#createInstance(symbol, scheduler, host);
367
- instances.set(symbol.id, instance);
368
- collectTopics(symbol, instance, topics);
1263
+ }
1264
+ if (typeof value !== "number" || !Number.isInteger(value)) throw new CircuitError("invalid-state-value", `State "${device.deviceId}.${slot.name}" is ${slot.type} and needs an integer, received ${String(value)}`, {
1265
+ deviceId: device.deviceId,
1266
+ stateName: slot.name
1267
+ });
1268
+ return value;
1269
+ }
1270
+ function isFloatBits(value) {
1271
+ if (typeof value !== "object" || value === null) return false;
1272
+ const candidate = value;
1273
+ return (candidate.type === "f32" || candidate.type === "f64") && typeof candidate.bits === "string";
1274
+ }
1275
+ function formatNames(names) {
1276
+ const list = [...names];
1277
+ return list.length === 0 ? "(none)" : `[${list.join(", ")}]`;
1278
+ }
1279
+ //#endregion
1280
+ //#region src/unified-ir/runtime/circuit.ts
1281
+ /** Every generated entry takes no arguments, so one frozen array is reused. */
1282
+ var NO_ARGS = Object.freeze([]);
1283
+ /** `unified_tick_batch` takes a u32 tick count. */
1284
+ var MAX_BATCH_TICKS = 4294967295;
1285
+ /** Virtual time is a JS number, so it wraps before losing integer precision. */
1286
+ var MAX_VIRTUAL_TIME = Number.MAX_SAFE_INTEGER;
1287
+ var DEFAULT_INSTANCE_ID = "unified-circuit";
1288
+ /**
1289
+ * Host-facing runtime of one compiled unified circuit (U02).
1290
+ *
1291
+ * ```ts
1292
+ * const circuit = await Circuit.create({
1293
+ * devices: [
1294
+ * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },
1295
+ * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },
1296
+ * ],
1297
+ * connections: [
1298
+ * { from: 'drive1.PA0', to: 'sink1.anode' },
1299
+ * { from: 'sink1.cathode', to: 'GND' },
1300
+ * ],
1301
+ * });
1302
+ *
1303
+ * circuit.runBatch(1_000_000); // one engine call
1304
+ * expect(circuit.tickCount).toBe(1_000_000n);
1305
+ *
1306
+ * circuit.reset();
1307
+ * circuit.setPin('drive1.PA0', true); // host drives the pin
1308
+ * circuit.step();
1309
+ * expect(circuit.devices.sink1.getState('lamp')).toBe(true);
1310
+ * ```
1311
+ *
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.
1315
+ */
1316
+ var Circuit = class Circuit {
1317
+ /** Typed per-device accessors, keyed by device id. */
1318
+ devices;
1319
+ #compiled;
1320
+ #jit;
1321
+ #context;
1322
+ #pins;
1323
+ #pinNames;
1324
+ #seeds;
1325
+ #tickCount = 0n;
1326
+ #virtualTime = 0;
1327
+ #disposed = false;
1328
+ constructor(compiled, jit, instanceId, accessors, pins, seeds) {
1329
+ this.#compiled = compiled;
1330
+ this.#jit = jit;
1331
+ this.#context = {
1332
+ instanceId,
1333
+ virtualTime: 0
1334
+ };
1335
+ this.devices = accessors;
1336
+ this.#pins = pins;
1337
+ this.#pinNames = Object.freeze([...pins.keys()]);
1338
+ this.#seeds = seeds;
1339
+ }
1340
+ /**
1341
+ * Compiles `input`, builds the engine instance and runs the generated
1342
+ * `initialize` entry once.
1343
+ *
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
+ * @throws {UnifiedIRCompilerError} when the circuit cannot be compiled.
1348
+ * @throws {CircuitError} for invalid options.
1349
+ */
1350
+ static async create(input, options = {}) {
1351
+ const resolved = resolveOptions(options);
1352
+ const compiled = compileCircuit(input, compileOptionsOf(resolved));
1353
+ const jit = createEngine(compiled, resolved);
1354
+ const host = { circuit: void 0 };
1355
+ const circuit = new Circuit(compiled, jit, resolved.instanceId, buildDeviceAccessors({
1356
+ compiled,
1357
+ jit,
1358
+ assertActive: () => {
1359
+ circuit.#assertActive();
1360
+ },
1361
+ step: () => {
1362
+ host.circuit?.step();
1363
+ },
1364
+ runBatch: (count) => {
1365
+ host.circuit?.runBatch(count);
369
1366
  }
370
- scheduler.start({ until: scheduler.now });
371
- return {
372
- scheduler,
373
- instances,
374
- topics: Object.freeze(topics),
375
- host
376
- };
377
- } catch (error) {
378
- for (const instance of instances.values()) destroyQuietly(instance, (diagnostic) => this.#report(diagnostic));
379
- disposeHostQuietly(host, (diagnostic) => this.#report(diagnostic));
380
- throw error;
381
- }
1367
+ }), pinRuntimeOf(compiled), resetSeedsOf(compiled));
1368
+ host.circuit = circuit;
1369
+ jit.execute(compiled.entryPoints.refs.initialize, NO_ARGS, circuit.#context);
1370
+ return circuit;
382
1371
  }
383
- #createInstance(symbol, scheduler, host) {
384
- const loaded = this.#modules.get(symbol.device);
385
- if (loaded === void 0) throw new SimulatorError("simulator/device-load-failed", `Device ${JSON.stringify(symbol.device)} of symbol "${symbol.id}" was not loaded.`, { symbol: symbol.id });
386
- const additions = host?.instanceOptions?.(symbol);
387
- try {
388
- return createDeviceInstance(loaded, scheduler, {
389
- ...additions,
390
- instanceId: symbol.id,
391
- ...symbol.properties === void 0 ? {} : { properties: symbol.properties },
392
- ...host?.pinHost === void 0 ? {} : { pinHost: host.pinHost },
393
- ...host?.topology === void 0 ? {} : { connections: { topology: host.topology } },
394
- onTopic: (message) => {
395
- this.#publish(scheduler, symbol.id, message.port, message.payload);
396
- }
397
- });
398
- } catch (cause) {
399
- throw new SimulatorError("simulator/instance-create-failed", `Symbol "${symbol.id}" could not be instantiated with device ${JSON.stringify(symbol.device)}.`, {
400
- symbol: symbol.id,
401
- cause
402
- });
403
- }
1372
+ /**
1373
+ * Runs `count` ticks inside one generated loop — the throughput path.
1374
+ *
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.
1377
+ *
1378
+ * @throws {CircuitError} with code `invalid-count` unless `count` is a u32.
1379
+ */
1380
+ runBatch(count) {
1381
+ this.#assertActive();
1382
+ 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)}`);
1383
+ if (count === 0) return;
1384
+ this.#context.virtualTime = this.#virtualTime;
1385
+ this.#jit.execute(this.#compiled.entryPoints.refs.batch, [count], this.#context);
1386
+ this.#advance(count);
404
1387
  }
405
- #publish(scheduler, symbol, port, payload) {
406
- const publish = Object.freeze({
407
- target: Object.freeze({
408
- symbol,
409
- port
410
- }),
411
- payload,
412
- simTime: scheduler.now
413
- });
414
- for (const listener of [...this.#publishListeners]) try {
415
- listener(publish);
416
- } catch (cause) {
417
- this.#report({
418
- code: "simulator/publish-failed",
419
- message: "A publish listener threw.",
420
- symbol,
421
- cause
422
- });
423
- }
1388
+ /**
1389
+ * Advances exactly one tick — the debugging path.
1390
+ *
1391
+ * Every call is one engine entry, so prefer `runBatch` for throughput.
1392
+ */
1393
+ step() {
1394
+ this.#assertActive();
1395
+ this.#context.virtualTime = this.#virtualTime;
1396
+ this.#jit.execute(this.#compiled.entryPoints.refs.tick, NO_ARGS, this.#context);
1397
+ this.#advance(1);
424
1398
  }
425
- /** Hands the payloads queued by `deliver` to their instances at the slice's start time. */
426
- #flush(runtime) {
427
- if (this.#pending.length === 0) return;
428
- const deliveries = this.#pending.splice(0);
429
- const simTime = runtime.scheduler.now;
430
- for (const delivery of deliveries) {
431
- const instance = runtime.instances.get(delivery.target.symbol);
432
- if (instance === void 0) continue;
433
- instance.deliver(delivery.target.port, delivery.payload, { simTime });
1399
+ /**
1400
+ * Restores every memory to its declared initial value, re-runs `initialize`
1401
+ * and resets `tickCount` to `0n`.
1402
+ *
1403
+ * Device state written by earlier ticks is discarded, so the circuit behaves
1404
+ * exactly like a freshly created one.
1405
+ */
1406
+ reset() {
1407
+ this.#assertActive();
1408
+ for (const seed of this.#seeds) {
1409
+ if (seed.kind === "state") {
1410
+ this.#jit.storage.storeState(seed.ref, seed.value);
1411
+ continue;
1412
+ }
1413
+ if (seed.kind === "bytes") {
1414
+ for (let index = 0; index < seed.values.length; index += 1) this.#jit.storage.storeBytes("u8", "little", seed.ref, index, seed.values[index]);
1415
+ continue;
1416
+ }
1417
+ if (seed.kind === "readonly-bytes") {
1418
+ try {
1419
+ this.#jit.storage.updateBytesFromBytes(seed.ref, 0, seed.values);
1420
+ } catch {}
1421
+ continue;
1422
+ }
1423
+ for (let index = 0; index < seed.values.length; index += 1) this.#jit.storage.storeArray(seed.ref, index, seed.values[index]);
434
1424
  }
1425
+ this.#tickCount = 0n;
1426
+ this.#virtualTime = 0;
1427
+ this.#context.virtualTime = 0;
1428
+ this.#jit.execute(this.#compiled.entryPoints.refs.initialize, NO_ARGS, this.#context);
435
1429
  }
436
- #teardown() {
437
- const runtime = this.#runtime;
438
- this.#runtime = void 0;
439
- this.#pending.length = 0;
440
- if (runtime === void 0) return;
441
- for (const instance of runtime.instances.values()) destroyQuietly(instance, (diagnostic) => this.#report(diagnostic));
442
- disposeHostQuietly(runtime.host, (diagnostic) => this.#report(diagnostic));
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;
443
1445
  }
444
- #requireRuntime() {
445
- this.#assertNotDisposed();
446
- const runtime = this.#runtime;
447
- if (runtime === void 0) throw new SimulatorError("simulator/not-ready", "Load a schematic before advancing the simulation.");
448
- return runtime;
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);
449
1461
  }
450
- #assertNotDisposed() {
451
- if (this.#state === "disposed") throw new SimulatorError("simulator/disposed", "The executor is disposed.");
1462
+ /** Number of ticks completed since creation or the last `reset()`. */
1463
+ get tickCount() {
1464
+ this.#assertActive();
1465
+ return this.#tickCount;
452
1466
  }
453
- #report(diagnostic) {
454
- try {
455
- this.#options.onDiagnostic?.(diagnostic);
456
- } catch {}
1467
+ /** Virtual tick time completed since creation or the last `reset()`. */
1468
+ get virtualTime() {
1469
+ this.#assertActive();
1470
+ return this.#virtualTime;
1471
+ }
1472
+ /** Underlying engine instance, e.g. for diagnostics or custom entries. */
1473
+ get jit() {
1474
+ this.#assertActive();
1475
+ return this.#jit;
1476
+ }
1477
+ /** Whether `dispose()` already ran. */
1478
+ get disposed() {
1479
+ return this.#disposed;
1480
+ }
1481
+ /**
1482
+ * Releases the runtime. Idempotent; every later call throws a `CircuitError`
1483
+ * with code `disposed`, including stale device accessors.
1484
+ */
1485
+ dispose() {
1486
+ this.#disposed = true;
1487
+ this.#tickCount = 0n;
1488
+ this.#virtualTime = 0;
1489
+ }
1490
+ /** @internal Shared guard of the circuit and all of its accessors. */
1491
+ #assertActive() {
1492
+ if (this.#disposed) throw new CircuitError("disposed", "Circuit has been disposed; create a new circuit to keep simulating");
1493
+ }
1494
+ #advance(count) {
1495
+ this.#tickCount += BigInt(count);
1496
+ const next = this.#virtualTime + count;
1497
+ this.#virtualTime = next > MAX_VIRTUAL_TIME ? 0 : next;
1498
+ }
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;
457
1503
  }
458
1504
  };
459
- /** True when the symbol stands for a device the executor instantiates. */
460
- function isComponent(symbol) {
461
- return symbolRole(symbol.device) === "component";
462
- }
463
- function collectTopics(symbol, instance, into) {
464
- const designator = designatorOf(symbol) ?? symbol.id;
465
- for (const [port, descriptor] of instance.description.ports) into.push(Object.freeze({
466
- symbol: symbol.id,
467
- designator,
468
- port,
469
- direction: descriptor.direction,
470
- type: descriptor.type,
471
- ...descriptor.title === void 0 ? {} : { title: descriptor.title }
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
472
1512
  }));
1513
+ return pins;
473
1514
  }
474
- function destroyQuietly(instance, report) {
475
- try {
476
- instance.destroy();
477
- } catch (cause) {
478
- report({
479
- code: "simulator/dispose-failed",
480
- message: `Device instance "${instance.instanceId}" failed to destroy.`,
481
- symbol: instance.instanceId,
482
- cause
1515
+ /**
1516
+ * Captures the declared initial value of every scalar memory, which is what
1517
+ * `reset()` restores before the generated `initialize` runs again.
1518
+ */
1519
+ function resetSeedsOf(compiled) {
1520
+ const seeds = [];
1521
+ for (const memory of compiled.module.memories) if (memory.kind === "array") seeds.push({
1522
+ kind: "array",
1523
+ ref: memory.ref,
1524
+ values: memory.initial
1525
+ });
1526
+ else if (memory.kind === "state") seeds.push({
1527
+ kind: "state",
1528
+ ref: memory.ref,
1529
+ value: memory.initial[0]
1530
+ });
1531
+ else if (memory.kind === "bytes") {
1532
+ if (memory.writable) seeds.push({
1533
+ kind: "bytes",
1534
+ ref: memory.ref,
1535
+ values: memory.initial
1536
+ });
1537
+ else seeds.push({
1538
+ kind: "readonly-bytes",
1539
+ ref: memory.ref,
1540
+ values: Uint8Array.from(memory.initial)
483
1541
  });
484
1542
  }
1543
+ return Object.freeze(seeds);
485
1544
  }
486
- function disposeHostQuietly(host, report) {
487
- try {
488
- host?.dispose?.();
489
- } catch (cause) {
490
- report({
491
- code: "simulator/dispose-failed",
492
- message: "The host wiring failed to dispose.",
493
- cause
1545
+ function createEngine(compiled, options) {
1546
+ const base = {
1547
+ validation: compiled.validation,
1548
+ maxSteps: Number.MAX_SAFE_INTEGER
1549
+ };
1550
+ if (options.engine === "reference") return createIRInterpreter(compiled.module, base);
1551
+ return createIRJIT(compiled.module, {
1552
+ ...base,
1553
+ jit: {
1554
+ tierUpThreshold: 0,
1555
+ ...options.jit
1556
+ }
1557
+ });
1558
+ }
1559
+ function compileOptionsOf(options) {
1560
+ return {
1561
+ validate: options.validateIR,
1562
+ ...options.rails === void 0 ? {} : { rails: options.rails }
1563
+ };
1564
+ }
1565
+ function resolveOptions(options) {
1566
+ if (options === null || typeof options !== "object" || Array.isArray(options)) throw new CircuitError("invalid-options", "Circuit options must be a plain object");
1567
+ const candidate = options;
1568
+ const engine = candidate.engine ?? "jit";
1569
+ if (engine !== "jit" && engine !== "reference") throw new CircuitError("invalid-options", `engine=${String(engine)} must be "jit" or "reference"`);
1570
+ if (candidate.validateIR !== void 0 && typeof candidate.validateIR !== "boolean") throw new CircuitError("invalid-options", "validateIR must be a boolean");
1571
+ if (candidate.instanceId !== void 0 && candidate.instanceId.length === 0) throw new CircuitError("invalid-options", "instanceId must be a non-empty string");
1572
+ if (candidate.jit !== void 0) {
1573
+ 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
+ }
1575
+ let rails;
1576
+ if (candidate.electrical !== void 0) {
1577
+ const electrical = candidate.electrical;
1578
+ if (electrical === null || typeof electrical !== "object" || Array.isArray(electrical)) throw new CircuitError("invalid-options", "electrical must be a plain object");
1579
+ rails = electrical.rails;
1580
+ }
1581
+ return Object.freeze({
1582
+ engine,
1583
+ jit: candidate.jit,
1584
+ validateIR: candidate.validateIR ?? true,
1585
+ rails,
1586
+ instanceId: candidate.instanceId ?? DEFAULT_INSTANCE_ID
1587
+ });
1588
+ }
1589
+ //#endregion
1590
+ //#region src/unified-ir/runtime/factory.ts
1591
+ /**
1592
+ * Compiles a schematic sheet into a circuit.
1593
+ *
1594
+ * Nets come from `deriveSchematicTopology`, so wires, junctions, labels and
1595
+ * power symbols keep their usual meaning: a net that names a rail connects
1596
+ * every member to that rail, and any other net joins its pins pairwise (the
1597
+ * compiler merges transitively).
1598
+ *
1599
+ * ```ts
1600
+ * const circuit = await createCircuitFromSchematic(schematic, {
1601
+ * devices: symbolProvider,
1602
+ * resolveDevice: (reference) => bindings.get(reference.deviceId),
1603
+ * });
1604
+ * ```
1605
+ *
1606
+ * @throws {CircuitError} with code `unresolved-device` when a component symbol
1607
+ * has no binding; `SchematicError` for malformed sheets.
1608
+ */
1609
+ async function createCircuitFromSchematic(schematic, options) {
1610
+ return (await createSchematicCircuit(schematic, options)).circuit;
1611
+ }
1612
+ /**
1613
+ * Compiles a schematic and reports which circuit device each symbol became.
1614
+ *
1615
+ * {@link createCircuitFromSchematic} returns only the circuit; hosts that route
1616
+ * schematic endpoints to circuit accessors need the mapping as well.
1617
+ */
1618
+ async function createSchematicCircuit(schematic, options) {
1619
+ 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
+ if (options === null || typeof options !== "object") throw new CircuitError("invalid-options", "createSchematicCircuit needs options");
1621
+ const { resolveDevice, devices, tolerance, ...runtime } = options;
1622
+ if (typeof resolveDevice !== "function") throw new CircuitError("invalid-options", "resolveDevice must be a function");
1623
+ const usedIds = /* @__PURE__ */ new Set();
1624
+ const deviceIdBySymbol = /* @__PURE__ */ new Map();
1625
+ const deviceConfigs = [];
1626
+ const bindings = [];
1627
+ let componentCount = 0;
1628
+ for (const symbol of schematic.sheet.symbols) {
1629
+ if (symbolRole(symbol.device) !== "component") continue;
1630
+ componentCount += 1;
1631
+ const reference = parseDeviceReference(symbol.device);
1632
+ const binding = reference === void 0 ? void 0 : resolveDevice(reference);
1633
+ if (binding === void 0) throw new CircuitError("unresolved-device", `Symbol "${symbol.id}" (${symbol.device}) has no runtime device binding; resolve it in resolveDevice`, { deviceId: symbol.id });
1634
+ const deviceId = uniqueDeviceId(symbol.designator ?? symbol.id, usedIds);
1635
+ usedIds.add(deviceId);
1636
+ deviceIdBySymbol.set(symbol.id, deviceId);
1637
+ deviceConfigs.push({
1638
+ id: deviceId,
1639
+ type: binding.type,
1640
+ description: binding.description,
1641
+ ...binding.config === void 0 ? {} : { config: binding.config }
1642
+ });
1643
+ if (reference !== void 0) bindings.push({
1644
+ symbolId: symbol.id,
1645
+ deviceId,
1646
+ reference,
1647
+ type: binding.type
494
1648
  });
495
1649
  }
1650
+ const topology = deriveSchematicTopology(schematic, {
1651
+ ...devices === void 0 ? {} : { devices },
1652
+ ...tolerance === void 0 ? {} : { tolerance }
1653
+ });
1654
+ 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 ?? {})]);
1656
+ const connections = [];
1657
+ for (const net of topology.nets) {
1658
+ const endpoints = [];
1659
+ let rail;
1660
+ for (const member of net.members) {
1661
+ if (member.kind === "pin") {
1662
+ const deviceId = deviceIdBySymbol.get(member.symbolId);
1663
+ if (deviceId === void 0) throw new CircuitError("unresolved-device", `Net "${net.name ?? "anonymous"}" references pin "${member.pinId}" of symbol "${member.symbolId}", which has no runtime device`, { deviceId: member.symbolId });
1664
+ endpoints.push(`${deviceId}.${member.pinId}`);
1665
+ continue;
1666
+ }
1667
+ if (member.kind === "power" || member.kind === "ground") rail = net.name ?? rail;
1668
+ }
1669
+ if (endpoints.length === 0) continue;
1670
+ const railName = rail ?? (net.name !== null && railNames.has(net.name) ? net.name : void 0);
1671
+ if (railName !== void 0) {
1672
+ for (const endpoint of endpoints) connections.push({
1673
+ from: endpoint,
1674
+ to: railName
1675
+ });
1676
+ continue;
1677
+ }
1678
+ const first = endpoints[0];
1679
+ for (const endpoint of endpoints.slice(1)) connections.push({
1680
+ from: first,
1681
+ to: endpoint
1682
+ });
1683
+ }
1684
+ const input = {
1685
+ devices: Object.freeze(deviceConfigs),
1686
+ connections: Object.freeze(connections)
1687
+ };
1688
+ const circuit = await Circuit.create(input, runtime);
1689
+ return Object.freeze({
1690
+ circuit,
1691
+ bindings: Object.freeze(bindings)
1692
+ });
1693
+ }
1694
+ /**
1695
+ * Turns a designator or symbol id into a compiler-safe device id.
1696
+ *
1697
+ * Device ids prefix generated IR function names, so they must be identifiers.
1698
+ */
1699
+ function uniqueDeviceId(preferred, used) {
1700
+ const base = sanitizeDeviceId(preferred);
1701
+ if (!used.has(base)) return base;
1702
+ for (let suffix = 2;; suffix += 1) {
1703
+ const candidate = `${base}_${suffix}`;
1704
+ if (!used.has(candidate)) return candidate;
1705
+ }
1706
+ }
1707
+ function sanitizeDeviceId(value) {
1708
+ const cleaned = value.replace(/[^A-Za-z0-9_]/g, "_");
1709
+ if (cleaned.length === 0) return "device";
1710
+ return /^[A-Za-z_]/.test(cleaned) ? cleaned : `d_${cleaned}`;
1711
+ }
1712
+ //#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
+ //#region src/host/runtime.ts
1758
+ var INSTANCE_ID = "device-simulation-host";
1759
+ function targetKey(deviceId, port) {
1760
+ return `${deviceId}\u0000${port}`;
1761
+ }
1762
+ /**
1763
+ * Value equality of two topic payloads.
1764
+ *
1765
+ * A canvas topic is a `level` unless it carries text or bytes (RFC 0017), so re-sending the value a
1766
+ * device already published only costs a widget repaint. Byte payloads compare by content because a
1767
+ * device may hand out a fresh buffer per step.
1768
+ */
1769
+ function samePayload(previous, next) {
1770
+ if (Object.is(previous, next)) return true;
1771
+ if (previous instanceof Uint8Array && next instanceof Uint8Array) {
1772
+ if (previous.length !== next.length) return false;
1773
+ for (let index = 0; index < previous.length; index += 1) if (previous[index] !== next[index]) return false;
1774
+ return true;
1775
+ }
1776
+ if (typeof previous !== "object" || previous === null) return false;
1777
+ if (typeof next !== "object" || next === null) return false;
1778
+ const a = previous;
1779
+ const b = next;
1780
+ return a.x === b.x && a.y === b.y && a.z === b.z;
1781
+ }
1782
+ function isVec2d(value) {
1783
+ if (typeof value !== "object" || value === null) return false;
1784
+ const point = value;
1785
+ return typeof point.x === "number" && typeof point.y === "number";
1786
+ }
1787
+ function payloadMatches(type, payload) {
1788
+ switch (type) {
1789
+ case "boolean": return typeof payload === "boolean";
1790
+ case "number": return typeof payload === "number";
1791
+ case "string": return typeof payload === "string";
1792
+ case "bytes":
1793
+ case "bytes<rgb565>":
1794
+ case "bytes<segments>": return payload instanceof Uint8Array;
1795
+ case "vec2d": return isVec2d(payload);
1796
+ case "vec3d": return isVec2d(payload) && typeof payload.z === "number";
1797
+ }
1798
+ }
1799
+ function decodeSchematic(bytes) {
1800
+ return parseSchematic(new TextDecoder().decode(bytes));
1801
+ }
1802
+ function buildRuntime(circuit, schematic, bindings, resolveDevice) {
1803
+ const symbols = new Map(schematic.sheet.symbols.map((symbol) => [symbol.id, symbol]));
1804
+ const devices = [];
1805
+ const topics = [];
1806
+ const inputs = /* @__PURE__ */ new Map();
1807
+ for (const binding of bindings) {
1808
+ const deviceBinding = resolveDevice(binding.reference);
1809
+ const accessor = circuit.devices[binding.deviceId];
1810
+ if (deviceBinding === void 0 || accessor === void 0) continue;
1811
+ const designator = symbols.get(binding.symbolId)?.designator ?? binding.symbolId;
1812
+ const device = {
1813
+ symbol: binding.symbolId,
1814
+ designator,
1815
+ binding: deviceBinding,
1816
+ accessor
1817
+ };
1818
+ devices.push(device);
1819
+ for (const topic of deviceBinding.topics ?? []) {
1820
+ topics.push({
1821
+ symbol: binding.symbolId,
1822
+ designator,
1823
+ port: topic.port,
1824
+ direction: topic.direction,
1825
+ type: topic.type,
1826
+ ...topic.title === void 0 ? {} : { title: topic.title }
1827
+ });
1828
+ if (topic.direction === "input") inputs.set(targetKey(binding.symbolId, topic.port), {
1829
+ device,
1830
+ topic
1831
+ });
1832
+ }
1833
+ }
1834
+ return {
1835
+ circuit,
1836
+ schematic,
1837
+ devices,
1838
+ topics: Object.freeze(topics),
1839
+ inputs
1840
+ };
1841
+ }
1842
+ /**
1843
+ * Same-thread `DeviceSimulationHost` over a schematic compiled by the unified-IR runtime.
1844
+ *
1845
+ * The host owns the circuit: `loadSchematic` reads, parses and compiles it, `tick` advances one
1846
+ * circuit step and publishes the output topics that changed, and `deliver` queues widget payloads
1847
+ * for the next step. Device models and their endpoints come from `resolveDevice`, so the host stays
1848
+ * generic. Nothing here touches the DOM, so the sandbox guest and a Node test use the same
1849
+ * implementation.
1850
+ */
1851
+ function createSchematicDeviceSimulationHost(options) {
1852
+ if (typeof options?.resolveDevice !== "function") throw new TypeError("createSchematicDeviceSimulationHost needs a resolveDevice function");
1853
+ const { read, devices: symbols, resolveDevice } = options;
1854
+ const publishes = new Emitter();
1855
+ const pending = [];
1856
+ /** Last payload published per endpoint, so an unchanged level topic stays silent. */
1857
+ const published = /* @__PURE__ */ new Map();
1858
+ let runtime;
1859
+ let simTimePs = 0;
1860
+ let disposed = false;
1861
+ const publishOutputs = (active) => {
1862
+ 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);
1878
+ }
1879
+ };
1880
+ const clearRuntime = () => {
1881
+ runtime?.circuit.dispose();
1882
+ runtime = void 0;
1883
+ pending.length = 0;
1884
+ published.clear();
1885
+ simTimePs = 0;
1886
+ };
1887
+ return {
1888
+ async loadSchematic(uri) {
1889
+ if (disposed) return;
1890
+ if (uri === void 0) {
1891
+ clearRuntime();
1892
+ return;
1893
+ }
1894
+ const schematic = decodeSchematic(await read(uri));
1895
+ const symbolProvider = typeof symbols === "function" ? symbols() : symbols;
1896
+ const compiled = await createSchematicCircuit(schematic, {
1897
+ ...symbolProvider === void 0 ? {} : { devices: symbolProvider },
1898
+ resolveDevice,
1899
+ instanceId: INSTANCE_ID
1900
+ });
1901
+ const next = buildRuntime(compiled.circuit, schematic, compiled.bindings, resolveDevice);
1902
+ runtime?.circuit.dispose();
1903
+ pending.length = 0;
1904
+ published.clear();
1905
+ simTimePs = 0;
1906
+ runtime = next;
1907
+ },
1908
+ async reset() {
1909
+ if (disposed) return;
1910
+ pending.length = 0;
1911
+ published.clear();
1912
+ simTimePs = 0;
1913
+ runtime?.circuit.reset();
1914
+ },
1915
+ async tick(dt) {
1916
+ if (!Number.isSafeInteger(dt) || dt <= 0) throw new TypeError(`DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`);
1917
+ if (disposed) return {
1918
+ simTime: simTimePs,
1919
+ executed: 0
1920
+ };
1921
+ const active = runtime;
1922
+ if (active === void 0) {
1923
+ simTimePs += dt;
1924
+ return {
1925
+ simTime: simTimePs,
1926
+ executed: 0
1927
+ };
1928
+ }
1929
+ const queued = pending.splice(0, pending.length);
1930
+ 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);
1933
+ }
1934
+ active.circuit.runBatch(1);
1935
+ simTimePs += dt;
1936
+ publishOutputs(active);
1937
+ return {
1938
+ simTime: simTimePs,
1939
+ executed: 1
1940
+ };
1941
+ },
1942
+ async deliver(target, payload) {
1943
+ if (disposed) return;
1944
+ const active = runtime;
1945
+ if (active === void 0) throw new Error("DeviceSimulationHost has no loaded schematic");
1946
+ const binding = active.inputs.get(targetKey(target.symbol, target.port));
1947
+ if (binding === void 0) throw new Error(`Unknown device input ${target.symbol}.${target.port}`);
1948
+ if (!payloadMatches(binding.topic.type, payload)) throw new TypeError(`${target.symbol}.${target.port} expects a ${binding.topic.type} payload`);
1949
+ 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
+ pending.push({
1952
+ device,
1953
+ port: target.port,
1954
+ payload
1955
+ });
1956
+ },
1957
+ onDidPublish: publishes.event,
1958
+ async getTopics() {
1959
+ return runtime?.topics ?? [];
1960
+ },
1961
+ async getSimTime() {
1962
+ return simTimePs;
1963
+ },
1964
+ async getSchematic() {
1965
+ return runtime?.schematic;
1966
+ },
1967
+ async dispose() {
1968
+ if (disposed) return;
1969
+ disposed = true;
1970
+ publishes.dispose();
1971
+ clearRuntime();
1972
+ }
1973
+ };
1974
+ }
1975
+ //#endregion
1976
+ //#region src/host/guest.ts
1977
+ /**
1978
+ * Registers RFC 0018's device simulation services on a sandbox RPC port.
1979
+ *
1980
+ * A worker script obtains the port from `event.ports[0]` and calls this function; nothing else is
1981
+ * needed, because the guest is a plain module the `@mica-js/sandbox/vite` plugin bundles into a
1982
+ * self-contained script. The guest registers `deviceSimulationHostGuestService` and reads schematics
1983
+ * through `deviceSimulationHostFileSystemService`, so schematic bytes never enter the guest's own
1984
+ * message handling and every payload is a typed RPC DTO.
1985
+ */
1986
+ function startDeviceSimulationHostGuest(port, options = {}) {
1987
+ const { devices, resolveDevice, prepare, ports = [] } = options;
1988
+ const rpc = createRpc(port);
1989
+ const logger = rpc.getProxy(loggerService);
1990
+ logger.write({
1991
+ level: "debug",
1992
+ scope: "device-simulation",
1993
+ message: "guest-started",
1994
+ data: [{ extraPortCount: ports.length }]
1995
+ }).catch(() => void 0);
1996
+ const files = rpc.getProxy(deviceSimulationHostFileSystemService);
1997
+ const host = createSchematicDeviceSimulationHost({
1998
+ async read(uri) {
1999
+ const bytes = await files.read(uri);
2000
+ if (!(bytes instanceof Uint8Array)) throw new TypeError(`DeviceSimulationHost file system returned ${typeof bytes} for ${uri}`);
2001
+ return bytes;
2002
+ },
2003
+ ...devices === void 0 ? {} : { devices },
2004
+ resolveDevice: resolveDevice ?? (() => void 0)
2005
+ });
2006
+ let prepared;
2007
+ const ensurePrepared = async () => {
2008
+ if (prepare === void 0) return;
2009
+ prepared ??= prepare();
2010
+ try {
2011
+ await prepared;
2012
+ } catch (error) {
2013
+ prepared = void 0;
2014
+ throw error;
2015
+ }
2016
+ };
2017
+ const service = {
2018
+ async loadSchematic(uri) {
2019
+ logger.write({
2020
+ level: "debug",
2021
+ scope: "device-simulation",
2022
+ message: "load-schematic-start",
2023
+ data: [uri]
2024
+ }).catch(() => void 0);
2025
+ try {
2026
+ if (uri !== void 0) await ensurePrepared();
2027
+ await host.loadSchematic(uri);
2028
+ logger.write({
2029
+ level: "debug",
2030
+ scope: "device-simulation",
2031
+ message: "load-schematic-end",
2032
+ data: [uri]
2033
+ }).catch(() => void 0);
2034
+ } catch (error) {
2035
+ logger.write({
2036
+ level: "error",
2037
+ scope: "device-simulation",
2038
+ message: "load-schematic-failed",
2039
+ data: [uri, String(error)]
2040
+ }).catch(() => void 0);
2041
+ throw error;
2042
+ }
2043
+ },
2044
+ async reset() {
2045
+ await ensurePrepared();
2046
+ return host.reset();
2047
+ },
2048
+ tick: (dt) => host.tick(dt),
2049
+ deliver: (target, payload, simTime) => host.deliver(target, payload, simTime),
2050
+ onDidPublish: (listener) => {
2051
+ const subscription = host.onDidPublish(listener);
2052
+ return () => subscription.dispose();
2053
+ },
2054
+ getTopics: () => host.getTopics(),
2055
+ getSimTime: () => host.getSimTime(),
2056
+ getSchematic: () => host.getSchematic(),
2057
+ dispose: () => host.dispose()
2058
+ };
2059
+ const registration = rpc.register(deviceSimulationHostGuestService, service);
2060
+ const topicPort = ports[0];
2061
+ const topicRpc = topicPort === void 0 ? void 0 : createRpc(topicPort);
2062
+ const topicRegistration = topicRpc?.register(deviceSimulationHostGuestService, service);
2063
+ let disposed = false;
2064
+ return {
2065
+ rpc,
2066
+ ports,
2067
+ async dispose() {
2068
+ if (disposed) return;
2069
+ disposed = true;
2070
+ topicRegistration?.dispose();
2071
+ topicRpc?.dispose();
2072
+ registration.dispose();
2073
+ await host.dispose();
2074
+ rpc.dispose();
2075
+ }
2076
+ };
496
2077
  }
497
2078
  //#endregion
498
- export { SimulatorError, createCircuitHost, createDeviceSimExecutor };
2079
+ export { Circuit, CircuitError, DEFAULT_RAILS, DEVICE_PIN_STRIDE, PIN_MODE, UNIFIED_PIN_CAPACITY, UnifiedIRCompilerError, compileCircuit, createCircuitDeviceSimulationHost, createCircuitFromSchematic, createModuleValidation, createSchematicCircuit, createSchematicDeviceSimulationHost, startDeviceSimulationHostGuest };
499
2080
 
500
2081
  //# sourceMappingURL=index.js.map