@mica-js/simulator 0.2.0 → 0.3.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,2094 @@
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. The values are part of the
57
+ * generated module's memory layout and must stay stable across releases.
58
+ */
59
+ /** Global pin addresses available to one circuit (8 devices x 32 pins). */
60
+ var UNIFIED_PIN_CAPACITY = 256;
61
+ /** Global pin addresses reserved per device (one 32-pin port). */
62
+ var DEVICE_PIN_STRIDE = 32;
63
+ /** Values stored in the global `pin_mode` array. */
64
+ var PIN_MODE = Object.freeze({
65
+ highZ: 0,
66
+ pushPull: 1,
67
+ openDrain: 2,
68
+ analog: 3
69
+ });
70
+ //#endregion
71
+ //#region src/unified-ir/compiler/types.ts
72
+ /** Error raised while compiling a circuit. */
73
+ var UnifiedIRCompilerError = class extends Error {
74
+ name = "UnifiedIRCompilerError";
8
75
  code;
9
- symbol;
76
+ deviceId;
77
+ pinName;
78
+ netId;
79
+ diagnostics;
10
80
  constructor(code, message, options = {}) {
11
81
  super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
12
82
  this.code = code;
13
- this.symbol = options.symbol;
83
+ this.deviceId = options.deviceId;
84
+ this.pinName = options.pinName;
85
+ this.netId = options.netId;
86
+ this.diagnostics = options.diagnostics ?? [];
14
87
  }
15
88
  };
16
89
  //#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
- });
90
+ //#region src/unified-ir/compiler/allocator.ts
91
+ /** Generated device ids prefix IR function names, so they must be identifiers. */
92
+ var DEVICE_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
30
93
  /**
31
- * Wiring host for schemes that are drawn, not described.
94
+ * Allocates the circuit-wide pin and state address spaces.
95
+ *
96
+ * ```
97
+ * ids: 0 = drive1.PA0 1 = drive1.PA1 2 = sink1.anode 3 = sink1.cathode
98
+ * |<-- drive1 -->| |<----------- sink1 ----------->|
32
99
  *
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.
100
+ * pin_mode[256] u8 pin_output[256] bool pin_input[256] bool
101
+ * device_state_bool[n] / device_state_u32[m] / ... (one array per used type)
102
+ * ```
36
103
  *
37
- * @example
38
- * createDeviceSimExecutor({ devices, host: createCircuitHost() });
104
+ * Pins are packed in declaration order across devices — the addresses the
105
+ * device IR and every net solver embed as constants. States are packed per
106
+ * scalar type into one shared array, so a device's slot stays typed while all
107
+ * devices share one storage region.
39
108
  */
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 }
109
+ var GlobalResourceAllocator = class {
110
+ module;
111
+ constructor(module) {
112
+ this.module = module;
113
+ }
114
+ /** Allocates the shared pin memories, the pin space and the state space. */
115
+ allocate(devices) {
116
+ const memory = createPinMemory(this.module);
117
+ return Object.freeze({
118
+ memory,
119
+ pins: this.allocatePins(devices),
120
+ states: this.allocateStates(devices)
48
121
  });
49
- return {
50
- pinHost: runtime,
51
- topology: runtime,
52
- dispose: () => {
53
- runtime.destroy();
122
+ }
123
+ /**
124
+ * Packs every device pin into one contiguous global address space.
125
+ *
126
+ * @throws {UnifiedIRCompilerError} on invalid or duplicate device ids, more
127
+ * than {@link DEVICE_PIN_STRIDE} pins for one device, or more than
128
+ * {@link UNIFIED_PIN_CAPACITY} pins for the circuit.
129
+ */
130
+ allocatePins(devices) {
131
+ assertDeviceList(devices);
132
+ let totalPins = 0;
133
+ const pins = /* @__PURE__ */ new Map();
134
+ const allocations = /* @__PURE__ */ new Map();
135
+ for (const device of devices) {
136
+ const entries = pinEntries(device);
137
+ if (entries.length > 32) throw new UnifiedIRCompilerError("capacity-exceeded", `Device "${device.id}" declares ${entries.length} pins; one device may own at most 32`, { deviceId: device.id });
138
+ if (totalPins + entries.length > 256) throw new UnifiedIRCompilerError("capacity-exceeded", `Device "${device.id}" does not fit: the circuit already uses ${totalPins} of 256 global pins`, { deviceId: device.id });
139
+ const offset = totalPins;
140
+ const devicePins = /* @__PURE__ */ new Map();
141
+ const resolved = /* @__PURE__ */ new Map();
142
+ for (const [name, descriptor] of entries) {
143
+ const globalPinId = totalPins;
144
+ totalPins += 1;
145
+ const direction = resolvePinDirection(descriptor, device.id, name);
146
+ const { role, senses } = resolvePinRole(direction, descriptor?.role, device.id, name);
147
+ devicePins.set(name, globalPinId);
148
+ resolved.set(name, Object.freeze({
149
+ name,
150
+ deviceId: device.id,
151
+ globalPinId,
152
+ direction,
153
+ role,
154
+ senses
155
+ }));
156
+ pins.set(`${device.id}.${name}`, globalPinId);
54
157
  }
55
- };
158
+ allocations.set(device.id, Object.freeze({
159
+ deviceId: device.id,
160
+ offset,
161
+ pins: devicePins,
162
+ resolved
163
+ }));
164
+ }
165
+ return Object.freeze({
166
+ pins,
167
+ devices: allocations,
168
+ totalPins,
169
+ capacity: 256
170
+ });
171
+ }
172
+ /**
173
+ * Allocates one typed slot per declared device state and creates the backing
174
+ * `device_state_<type>` arrays.
175
+ *
176
+ * @throws {UnifiedIRCompilerError} when a state declaration is malformed.
177
+ */
178
+ allocateStates(devices) {
179
+ assertDeviceList(devices);
180
+ const plans = [];
181
+ const slotsByDevice = /* @__PURE__ */ new Map();
182
+ const plansByType = /* @__PURE__ */ new Map();
183
+ for (const device of devices) {
184
+ const slots = /* @__PURE__ */ new Map();
185
+ slotsByDevice.set(device.id, slots);
186
+ for (const [name, declaration] of stateEntries(device)) {
187
+ const plan = {
188
+ deviceId: device.id,
189
+ name,
190
+ type: declaration.type,
191
+ initial: declaration.initial,
192
+ slot: plans.length
193
+ };
194
+ plans.push(plan);
195
+ const typePlans = plansByType.get(plan.type);
196
+ if (typePlans === void 0) plansByType.set(plan.type, [plan]);
197
+ else typePlans.push(plan);
198
+ }
199
+ }
200
+ const arrays = /* @__PURE__ */ new Map();
201
+ const totals = /* @__PURE__ */ new Map();
202
+ for (const [type, typePlans] of plansByType) {
203
+ const array = this.module.array(`device_state_${type}`, type, typePlans.map((plan) => plan.initial));
204
+ arrays.set(type, array);
205
+ totals.set(type, typePlans.length);
206
+ typePlans.forEach((plan, index) => {
207
+ const slot = Object.freeze({
208
+ name: plan.name,
209
+ deviceId: plan.deviceId,
210
+ type,
211
+ array,
212
+ index,
213
+ slot: plan.slot
214
+ });
215
+ slotsByDevice.get(plan.deviceId)?.set(plan.name, slot);
216
+ });
217
+ }
218
+ const devicesMap = /* @__PURE__ */ new Map();
219
+ for (const [deviceId, slots] of slotsByDevice) devicesMap.set(deviceId, slots);
220
+ return Object.freeze({
221
+ devices: devicesMap,
222
+ arrays,
223
+ totals,
224
+ totalStates: plans.length
225
+ });
226
+ }
227
+ };
228
+ /** Declares the three pin memories shared by every device and net solver. */
229
+ function createPinMemory(module) {
230
+ return Object.freeze({
231
+ mode: module.array("pin_mode", "u8", Array.from({ length: 256 }, () => PIN_MODE.highZ)),
232
+ output: module.array("pin_output", "bool", Array.from({ length: 256 }, () => false)),
233
+ input: module.array("pin_input", "bool", Array.from({ length: 256 }, () => false))
234
+ });
235
+ }
236
+ /** First state slot ordinal of every device; used for `DeviceMetadata.stateOffset`. */
237
+ function stateOffsetOf(states, deviceId) {
238
+ let offset = 0;
239
+ for (const [id, slots] of states.devices) {
240
+ if (id === deviceId) return offset;
241
+ offset += slots.size;
242
+ }
243
+ return offset;
244
+ }
245
+ function assertDeviceList(devices) {
246
+ if (!Array.isArray(devices) || devices.length === 0) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput.devices must be a non-empty array");
247
+ const ids = /* @__PURE__ */ new Set();
248
+ for (const device of devices) {
249
+ if (device === null || typeof device !== "object" || Array.isArray(device)) throw new UnifiedIRCompilerError("invalid-input", "Every device must be an object");
250
+ const { id, type, description } = device;
251
+ 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`);
252
+ if (ids.has(id)) throw new UnifiedIRCompilerError("duplicate-device", `Duplicate device id "${id}"; every device id must be unique`, { deviceId: id });
253
+ ids.add(id);
254
+ if (typeof type !== "string" || type.length === 0) throw new UnifiedIRCompilerError("invalid-input", `Device "${id}" needs a non-empty type`, { deviceId: id });
255
+ if (description === null || typeof description !== "object") throw new UnifiedIRCompilerError("invalid-input", `Device "${id}" needs a description object with a pins map`, { deviceId: id });
256
+ }
257
+ }
258
+ function pinEntries(device) {
259
+ const raw = device.description.pins;
260
+ let entries;
261
+ if (raw instanceof Map) entries = [...raw.entries()];
262
+ else if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) entries = Object.entries(raw);
263
+ else throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" needs description.pins as a Map or a plain object`, { deviceId: device.id });
264
+ for (const [name, descriptor] of entries) {
265
+ 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 });
266
+ if (name.includes(".")) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" pin "${name}" may not contain ".": connection endpoints use "device.pin"`, {
267
+ deviceId: device.id,
268
+ pinName: name
269
+ });
270
+ if (descriptor !== void 0 && (descriptor === null || typeof descriptor !== "object")) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" pin "${name}" description must be an object`, {
271
+ deviceId: device.id,
272
+ pinName: name
273
+ });
274
+ }
275
+ return entries;
276
+ }
277
+ var PIN_DIRECTIONS = /* @__PURE__ */ new Set([
278
+ "input",
279
+ "output",
280
+ "bidirectional",
281
+ "passive"
282
+ ]);
283
+ function resolvePinDirection(descriptor, deviceId, pinName) {
284
+ const direction = descriptor?.direction ?? "passive";
285
+ 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`, {
286
+ deviceId,
287
+ pinName
288
+ });
289
+ return direction;
290
+ }
291
+ /**
292
+ * Derives the electrical role and the read behavior of a pin.
293
+ *
294
+ * `output` drives only, `input`/`passive` sense only, `bidirectional` drives and
295
+ * senses. An explicit `role` overrides the derived drive role while
296
+ * `bidirectional` keeps its sense side.
297
+ */
298
+ function resolvePinRole(direction, explicit, deviceId, pinName) {
299
+ 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`, {
300
+ deviceId,
301
+ pinName
302
+ });
303
+ if (explicit === "driver") return {
304
+ role: "driver",
305
+ senses: direction === "bidirectional"
56
306
  };
307
+ if (explicit === "load") return {
308
+ role: "load",
309
+ senses: true
310
+ };
311
+ if (direction === "output") return {
312
+ role: "driver",
313
+ senses: false
314
+ };
315
+ if (direction === "bidirectional") return {
316
+ role: "driver",
317
+ senses: true
318
+ };
319
+ return {
320
+ role: "load",
321
+ senses: true
322
+ };
323
+ }
324
+ function stateEntries(device) {
325
+ const raw = device.description.states;
326
+ if (raw === void 0) return [];
327
+ 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 });
328
+ return Object.entries(raw).map(([name, declaration]) => {
329
+ 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 });
330
+ 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 });
331
+ const type = declaration.type;
332
+ 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 });
333
+ assertStateInitial(device.id, name, type, declaration.initial);
334
+ return [name, declaration];
335
+ });
57
336
  }
337
+ function assertStateInitial(deviceId, name, type, initial) {
338
+ if (type === "bool") {
339
+ if (typeof initial !== "boolean") throw new UnifiedIRCompilerError("invalid-input", `Device "${deviceId}" state "${name}" (bool) needs a boolean initial value`, { deviceId });
340
+ return;
341
+ }
342
+ if (typeof initial !== "number" || !Number.isFinite(initial)) throw new UnifiedIRCompilerError("invalid-input", `Device "${deviceId}" state "${name}" (${type}) needs a finite numeric initial value`, { deviceId });
343
+ if (INTEGER_TYPES.includes(type) && !Number.isInteger(initial)) throw new UnifiedIRCompilerError("invalid-input", `Device "${deviceId}" state "${name}" (${type}) needs an integer initial value`, { deviceId });
344
+ }
345
+ //#endregion
346
+ //#region src/unified-ir/compiler/device-gen.ts
58
347
  /**
59
- * Turns a schematic into a topology plus power definition.
348
+ * Generates one IR function per device phase into the unified module.
60
349
  *
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.
350
+ * Domain operations are inlined while the behavior runs: `pin.configure`,
351
+ * `pin.writeDigital` and `pin.sampleDigital` become `array.store`/`array.load`
352
+ * on the shared `pin_mode` / `pin_output` / `pin_input` memories, so no device
353
+ * keeps its own module, protocol or host hop. A device without an explicit
354
+ * `initialize` still gets one that configures its output pins as push-pull.
64
355
  *
65
- * @returns `undefined` when the schematic declares no pins at all (nothing to solve).
356
+ * The compiler ships no device models: every description must declare its own
357
+ * pins, states and behaviors (or a `kernel`) before it reaches this generator.
66
358
  */
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
- });
359
+ var DeviceIRGenerator = class {
360
+ context;
361
+ constructor(context) {
362
+ this.context = context;
363
+ }
364
+ /**
365
+ * @throws {UnifiedIRCompilerError} when the device has no kernel/behaviors or
366
+ * a behavior reaches for a pin or state the description does not declare.
367
+ */
368
+ generate(device) {
369
+ const allocation = this.context.pins.devices.get(device.id);
370
+ if (allocation === void 0) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" has no pin allocation; allocate resources before generating IR`, { deviceId: device.id });
371
+ const kernelResult = device.description.kernel?.({
372
+ deviceId: device.id,
373
+ config: device.config,
374
+ module: this.context.module,
375
+ memory: this.context.memory,
376
+ pins: [...allocation.resolved.values()].map((pin) => Object.freeze({
377
+ name: pin.name,
378
+ globalPinId: pin.globalPinId,
379
+ role: pin.role
380
+ }))
381
+ });
382
+ const kernelRuntime = kernelResult !== void 0 && isKernelRuntime(kernelResult) ? kernelResult : void 0;
383
+ const behaviors = kernelRuntime === void 0 ? kernelResult ?? device.description.behaviors : void 0;
384
+ let initialize;
385
+ let tick;
386
+ let update;
387
+ if (kernelRuntime !== void 0) {
388
+ initialize = phaseFromRef(this.context.module, device.id, kernelRuntime.initialize);
389
+ tick = phaseFromRef(this.context.module, device.id, kernelRuntime.tick);
390
+ update = phaseFromRef(this.context.module, device.id, kernelRuntime.update);
391
+ } else {
392
+ 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 });
393
+ initialize = this.generatePhase(device, allocation, "initialize", behaviors.initialize) ?? this.generateDefaultInitialize(device, allocation);
394
+ tick = this.generatePhase(device, allocation, "tick", behaviors.tick);
395
+ update = this.generatePhase(device, allocation, "update", behaviors.update);
99
396
  }
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
- });
397
+ const functions = [];
398
+ for (const phase of [
399
+ initialize,
400
+ tick,
401
+ update
402
+ ]) if (phase !== void 0) functions.push(phase.name);
403
+ const metadata = Object.freeze({
404
+ deviceId: device.id,
405
+ type: device.type,
406
+ pinOffset: allocation.offset,
407
+ stateOffset: stateOffsetOf(this.context.states, device.id),
408
+ pins: allocation.pins,
409
+ states: this.context.states.devices.get(device.id) ?? /* @__PURE__ */ new Map(),
410
+ functions: Object.freeze(functions),
411
+ initialize: initialize?.name,
412
+ tick: tick?.name,
413
+ update: update?.name,
414
+ accessor: device.description.accessor,
415
+ kernel: device.description.kernel
416
+ });
417
+ return Object.freeze({
418
+ metadata,
419
+ entry: Object.freeze({
420
+ deviceId: device.id,
421
+ initialize: initialize?.ref,
422
+ tick: tick?.ref,
423
+ update: update?.ref
424
+ })
425
+ });
426
+ }
427
+ generatePhase(device, allocation, phase, behavior) {
428
+ if (behavior === void 0) return void 0;
429
+ const name = `${device.id}_${phase}`;
430
+ const ref = this.context.module.func(name, {
431
+ params: [],
432
+ results: []
433
+ });
434
+ ref.body((b) => {
435
+ behavior(this.createApi(device, allocation, b));
436
+ b.return([]);
437
+ });
438
+ return {
439
+ name,
440
+ ref
441
+ };
442
+ }
443
+ generateDefaultInitialize(device, allocation) {
444
+ const outputs = [...allocation.resolved.values()].filter((pin) => pin.role === "driver");
445
+ if (outputs.length === 0) return void 0;
446
+ const name = `${device.id}_initialize`;
447
+ const ref = this.context.module.func(name, {
448
+ params: [],
449
+ results: []
450
+ });
451
+ ref.body((b) => {
452
+ for (const pin of outputs) b.array.store(this.context.memory.mode, b.const("u32", pin.globalPinId), b.const("u8", PIN_MODE.pushPull));
453
+ b.return([]);
454
+ });
455
+ return {
456
+ name,
457
+ ref
458
+ };
459
+ }
460
+ createApi(device, allocation, builder) {
461
+ const handles = /* @__PURE__ */ new Map();
462
+ const pins = [];
463
+ const outputs = [];
464
+ for (const pin of allocation.resolved.values()) {
465
+ const handle = this.createPinHandle(pin.globalPinId, pin.name, builder);
466
+ handles.set(pin.name, handle);
467
+ pins.push(handle);
468
+ if (pin.role === "driver") outputs.push(handle);
111
469
  }
112
- if (members.length > 0) wires.push({
113
- wireId: `net-${index}`,
114
- pins: members,
115
- ...ground ? { globalGnd: true } : {}
470
+ const slots = this.context.states.devices.get(device.id);
471
+ return Object.freeze({
472
+ deviceId: device.id,
473
+ builder,
474
+ module: this.context.module,
475
+ memory: this.context.memory,
476
+ config: device.config,
477
+ pins: Object.freeze(pins),
478
+ outputs: Object.freeze(outputs),
479
+ pin(name) {
480
+ const handle = handles.get(name);
481
+ if (handle === void 0) {
482
+ const available = [...handles.keys()].map((entry) => `${device.id}.${entry}`);
483
+ throw new UnifiedIRCompilerError("pin-not-found", `Pin '${device.id}.${name}' not found. Available: [${available.join(", ")}]`, {
484
+ deviceId: device.id,
485
+ pinName: name
486
+ });
487
+ }
488
+ return handle;
489
+ },
490
+ state(name) {
491
+ const slot = slots?.get(name);
492
+ if (slot === void 0) throw new UnifiedIRCompilerError("state-not-found", `Device "${device.id}" has no state "${name}". Available: [${[...slots?.keys() ?? []].join(", ")}]`, { deviceId: device.id });
493
+ return createStateHandle(device.id, slot, builder);
494
+ }
116
495
  });
117
496
  }
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
497
+ createPinHandle(globalId, name, builder) {
498
+ const memory = this.context.memory;
499
+ const index = () => builder.const("u32", globalId);
500
+ return Object.freeze({
501
+ name,
502
+ globalId,
503
+ configure(mode) {
504
+ if (!Number.isInteger(mode) || mode < 0 || mode > 255) throw new UnifiedIRCompilerError("invalid-input", `Pin "${name}" configure(${String(mode)}) needs a u8 pin mode`);
505
+ builder.array.store(memory.mode, index(), builder.const("u8", mode));
506
+ },
507
+ writeDigital(level) {
508
+ builder.array.store(memory.output, index(), level);
509
+ },
510
+ sampleDigital() {
511
+ return builder.array.load(memory.input, index());
512
+ },
513
+ readDrivenDigital() {
514
+ return builder.array.load(memory.output, index());
127
515
  }
128
- } }
516
+ });
517
+ }
518
+ };
519
+ function createStateHandle(deviceId, slot, builder) {
520
+ const array = slot.array;
521
+ const index = builder.const("u32", slot.index);
522
+ return Object.freeze({
523
+ name: slot.name,
524
+ type: slot.type,
525
+ index: slot.index,
526
+ load() {
527
+ return builder.array.load(array, index);
528
+ },
529
+ store(value) {
530
+ builder.array.store(array, index, value);
531
+ }
129
532
  });
130
- const topology = {
131
- pins,
132
- wires,
133
- connections: deviceConnections(document, modules)
134
- };
533
+ }
534
+ function hasAnyBehavior(behaviors) {
535
+ return behaviors.initialize !== void 0 || behaviors.tick !== void 0 || behaviors.update !== void 0;
536
+ }
537
+ /** Bulk kernel results carry phase refs; behaviour hooks are plain functions. */
538
+ function isKernelRuntime(value) {
539
+ if (value === null || typeof value !== "object") return false;
540
+ return [
541
+ "initialize",
542
+ "tick",
543
+ "update"
544
+ ].some((phase) => typeof value[phase] === "object");
545
+ }
546
+ /** Resolves one kernel phase ref to its generated function name. */
547
+ function phaseFromRef(module, deviceId, ref) {
548
+ if (ref === void 0) return void 0;
549
+ const definition = module.functions.find((fn) => fn.ref === ref);
550
+ 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
551
  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
- })
552
+ name: definition.name,
553
+ ref
173
554
  };
174
555
  }
556
+ //#endregion
557
+ //#region src/unified-ir/compiler/mainloop-gen.ts
558
+ /** Names used when the caller does not override them. */
559
+ var DEFAULT_ENTRY_POINT_NAMES = Object.freeze({
560
+ tick: "unified_tick",
561
+ initialize: "unified_initialize",
562
+ batch: "unified_tick_batch"
563
+ });
175
564
  /**
176
- * Symbols for every device the schematic names.
565
+ * Generates the circuit entries.
177
566
  *
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.
567
+ * ```text
568
+ * unified_initialize: // once, before the first tick
569
+ * drive1_initialize()
570
+ * sink1_initialize() // if the device has one
571
+ *
572
+ * unified_tick: // one simulation step
573
+ * drive1_tick() // drivers publish their outputs
574
+ * solve_net_0() // the electrical network resolves
575
+ * sink1_update() // loads observe the solved inputs
576
+ *
577
+ * unified_tick_batch(count): // the same step, looped inside the IR
578
+ * for i in 0 .. count { <step> }
579
+ * ```
580
+ *
581
+ * Devices run in dependency order: a device that drives a net executes before
582
+ * every device that senses it. Feedback loops fall back to declaration order
583
+ * after the topological prefix, so clock cycles stay valid.
180
584
  */
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
- }));
585
+ var MainLoopGenerator = class {
586
+ module;
587
+ constructor(module) {
588
+ this.module = module;
589
+ }
590
+ /** Stable topological order of the devices; cycles fall back to declaration order. */
591
+ order(entries, netlist) {
592
+ const indexById = new Map(entries.map((entry, index) => [entry.deviceId, index]));
593
+ const consumers = /* @__PURE__ */ new Map();
594
+ const indegree = new Map(entries.map((entry) => [entry.deviceId, 0]));
595
+ for (const net of netlist.nets) {
596
+ const driverDevices = new Set(net.drivers.map((pin) => pin.deviceId));
597
+ const sinkDevices = new Set(net.sinks.map((pin) => pin.deviceId));
598
+ for (const driver of driverDevices) for (const sink of sinkDevices) {
599
+ if (driver === sink) continue;
600
+ let targets = consumers.get(driver);
601
+ if (targets === void 0) {
602
+ targets = /* @__PURE__ */ new Set();
603
+ consumers.set(driver, targets);
604
+ }
605
+ if (targets.has(sink)) continue;
606
+ targets.add(sink);
607
+ indegree.set(sink, (indegree.get(sink) ?? 0) + 1);
608
+ }
190
609
  }
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);
610
+ const ready = new Set(entries.filter((entry) => (indegree.get(entry.deviceId) ?? 0) === 0).map((entry) => entry.deviceId));
611
+ const order = [];
612
+ while (ready.size > 0) {
613
+ let nextId;
614
+ let nextIndex = Number.POSITIVE_INFINITY;
615
+ for (const id of ready) {
616
+ const index = indexById.get(id) ?? 0;
617
+ if (index < nextIndex) {
618
+ nextIndex = index;
619
+ nextId = id;
620
+ }
621
+ }
622
+ if (nextId === void 0) break;
623
+ ready.delete(nextId);
624
+ order.push(nextId);
625
+ for (const consumer of consumers.get(nextId) ?? []) {
626
+ const remaining = (indegree.get(consumer) ?? 0) - 1;
627
+ indegree.set(consumer, remaining);
628
+ if (remaining === 0) ready.add(consumer);
629
+ }
630
+ }
631
+ for (const entry of entries) if (!order.includes(entry.deviceId)) order.push(entry.deviceId);
632
+ return Object.freeze(order);
204
633
  }
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
634
+ /** Generates `initialize`, `tick` and the batched tick loop. */
635
+ generate(entries, solvers, netlist, names = DEFAULT_ENTRY_POINT_NAMES) {
636
+ const order = this.order(entries, netlist);
637
+ const byId = new Map(entries.map((entry) => [entry.deviceId, entry]));
638
+ const emitStep = (b) => {
639
+ for (const deviceId of order) {
640
+ const entry = byId.get(deviceId);
641
+ if (entry?.tick !== void 0) b.call(entry.tick, []);
642
+ }
643
+ for (const solver of solvers) b.call(solver.solve, []);
644
+ for (const deviceId of order) {
645
+ const entry = byId.get(deviceId);
646
+ if (entry?.update !== void 0) b.call(entry.update, []);
647
+ }
648
+ };
649
+ const initialize = this.module.func(names.initialize, {
650
+ params: [],
651
+ results: []
652
+ });
653
+ initialize.body((b) => {
654
+ for (const deviceId of order) {
655
+ const entry = byId.get(deviceId);
656
+ if (entry?.initialize !== void 0) b.call(entry.initialize, []);
657
+ }
658
+ b.return([]);
659
+ });
660
+ const tick = this.module.func(names.tick, {
661
+ params: [],
662
+ results: []
663
+ });
664
+ tick.body((b) => {
665
+ emitStep(b);
666
+ b.return([]);
667
+ });
668
+ const batch = this.module.func(names.batch, {
669
+ params: ["u32"],
670
+ results: []
671
+ });
672
+ batch.body((b, [count]) => {
673
+ const header = b.block(["u32"]);
674
+ const body = b.block(["u32"]);
675
+ const done = b.block([]);
676
+ b.jump(header, [b.const("u32", 0)]);
677
+ b.at(header, (ib, [index]) => ib.branch(ib.int.cmp("lt", index, count), {
678
+ target: body,
679
+ args: [index]
680
+ }, {
681
+ target: done,
682
+ args: []
683
+ }));
684
+ b.at(body, (ib, [index]) => {
685
+ emitStep(ib);
686
+ ib.jump(header, [ib.int.add(index, ib.const("u32", 1))]);
220
687
  });
688
+ b.at(done, (ib) => ib.return([]));
689
+ });
690
+ return Object.freeze({
691
+ names,
692
+ initialize,
693
+ tick,
694
+ batch,
695
+ order
696
+ });
697
+ }
698
+ };
699
+ //#endregion
700
+ //#region src/unified-ir/compiler/solver-gen.ts
701
+ /**
702
+ * Generates the electrical solve, one `solve_net_<id>` function per net.
703
+ *
704
+ * Single driver — the only shape v1 compiles without `allowMultiDriver` — is a
705
+ * branch-free path:
706
+ *
707
+ * ```text
708
+ * solve_net_0:
709
+ * let mode = PIN_MODE[driver]
710
+ * let output = PIN_OUTPUT[driver]
711
+ * let driven = mode == PUSH_PULL && output
712
+ * PIN_INPUT[load] = driven // once per sink
713
+ * ```
714
+ *
715
+ * Only a push-pull driver holds its net; high-z, open-drain and analog modes
716
+ * leave it floating. A driver-less net loads the constant of its rail, or
717
+ * `false` when it is truly floating.
718
+ */
719
+ var ElectricalSolverGenerator = class {
720
+ context;
721
+ constructor(context) {
722
+ this.context = context;
723
+ }
724
+ generate(netlist) {
725
+ return Object.freeze(netlist.nets.map((net) => this.generateNetSolver(net)));
726
+ }
727
+ generateNetSolver(net) {
728
+ const name = `solve_net_${net.netId}`;
729
+ const solve = this.context.module.func(name, {
730
+ params: [],
731
+ results: []
732
+ });
733
+ solve.body((b) => {
734
+ if (net.sinks.length > 0) {
735
+ const driven = net.drivers.length === 0 ? b.const("bool", net.level) : this.combineDrivers(b, net.drivers);
736
+ if (driven !== void 0) for (const sink of net.sinks) b.array.store(this.context.memory.input, b.const("u32", sink.globalPinId), driven);
737
+ }
738
+ b.return([]);
739
+ });
740
+ return Object.freeze({
741
+ netId: net.netId,
742
+ name,
743
+ net,
744
+ solve
745
+ });
746
+ }
747
+ /**
748
+ * Folds the drivers of one net into the level its sinks observe.
749
+ *
750
+ * A single driver yields `mode == push-pull && output`; several drivers (only
751
+ * reachable with `allowMultiDriver`) are OR-ed into a wired-OR level.
752
+ */
753
+ combineDrivers(b, drivers) {
754
+ let driven;
755
+ for (const driver of drivers) {
756
+ const index = b.const("u32", driver.globalPinId);
757
+ const mode = b.array.load(this.context.memory.mode, index);
758
+ const output = b.array.load(this.context.memory.output, index);
759
+ const pushed = b.int.cmp("eq", mode, b.const("u8", PIN_MODE.pushPull));
760
+ const value = b.bool.and(pushed, output);
761
+ driven = driven === void 0 ? value : b.bool.or(driven, value);
221
762
  }
763
+ return driven;
222
764
  }
223
- return connections;
224
- }
765
+ };
225
766
  //#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
- })
767
+ //#region src/unified-ir/compiler/topology.ts
768
+ /** Rails every circuit understands without declaring them. */
769
+ var DEFAULT_RAILS = Object.freeze({
770
+ GND: false,
771
+ VCC: true,
772
+ VDD: true
234
773
  });
235
- var EMPTY_TOPICS = Object.freeze([]);
236
774
  /**
237
- * Creates an executor for one schematic at a time.
775
+ * Analyses the pin-to-pin connections of a circuit.
776
+ *
777
+ * 1. every connection edge joins two nodes (pins and rails);
778
+ * 2. a union-find pass collapses them into electrical nets (connected components);
779
+ * 3. each net gets an id in first-appearance order and is split into drivers,
780
+ * loads and sinks;
781
+ * 4. electrical conflicts (several drivers, a driver against a rail, two rails
782
+ * of opposite level) become diagnostics instead of silently wrong IR.
238
783
  *
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`.
784
+ * The v1 electrical model supports one driver per net. `allowMultiDriver`
785
+ * accepts more and the solver then emits a wired-OR instead of failing.
242
786
  */
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;
787
+ var NetworkTopologyAnalyzer = class {
788
+ rails;
789
+ allowMultiDriver;
790
+ constructor(options = {}) {
791
+ this.rails = new Map([...Object.entries(DEFAULT_RAILS), ...Object.entries(options.rails ?? {})]);
792
+ this.allowMultiDriver = options.allowMultiDriver ?? false;
793
+ }
794
+ /**
795
+ * @throws {UnifiedIRCompilerError} when a connection is malformed, names an
796
+ * unknown device, or names a pin the device does not declare.
797
+ */
798
+ analyze(connections, pins) {
799
+ if (!Array.isArray(connections)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput.connections must be an array");
800
+ const set = new DisjointSet();
801
+ const pinNodes = /* @__PURE__ */ new Map();
802
+ const railNodes = /* @__PURE__ */ new Map();
803
+ const railNodeIds = /* @__PURE__ */ new Map();
804
+ const connectionOrder = [];
805
+ for (const [index, connection] of connections.entries()) {
806
+ if (connection === null || typeof connection !== "object") throw new UnifiedIRCompilerError("invalid-connection", `Connection[${index}] must be an object with "from" and "to"`);
807
+ const from = this.resolveEndpoint(connection.from, pins, railNodeIds, index);
808
+ const to = this.resolveEndpoint(connection.to, pins, railNodeIds, index);
809
+ set.union(from.nodeId, to.nodeId);
810
+ connectionOrder.push(from.nodeId);
811
+ if (from.kind === "pin") pinNodes.set(from.pin.globalPinId, toConnection(from.pin));
812
+ else railNodes.set(from.nodeId, Object.freeze({
813
+ name: from.name,
814
+ level: from.level
815
+ }));
816
+ if (to.kind === "pin") pinNodes.set(to.pin.globalPinId, toConnection(to.pin));
817
+ else railNodes.set(to.nodeId, Object.freeze({
818
+ name: to.name,
819
+ level: to.level
820
+ }));
301
821
  }
822
+ const components = /* @__PURE__ */ new Map();
823
+ const componentOf = (nodeId) => {
824
+ const root = set.find(nodeId);
825
+ let component = components.get(root);
826
+ if (component === void 0) {
827
+ component = {
828
+ pins: [],
829
+ rails: [],
830
+ endpoints: []
831
+ };
832
+ components.set(root, component);
833
+ }
834
+ return component;
835
+ };
836
+ for (const [pinId, connection] of pinNodes) componentOf(pinId).pins.push(connection);
837
+ for (const [nodeId, rail] of railNodes) {
838
+ const component = componentOf(nodeId);
839
+ component.rails.push(rail);
840
+ component.endpoints.push(rail.name);
841
+ }
842
+ const orderedRoots = [];
843
+ const seen = /* @__PURE__ */ new Set();
844
+ for (const nodeId of connectionOrder) {
845
+ const root = set.find(nodeId);
846
+ if (seen.has(root)) continue;
847
+ seen.add(root);
848
+ orderedRoots.push(root);
849
+ }
850
+ const diagnostics = [];
851
+ const nets = [];
852
+ for (const root of orderedRoots) {
853
+ const component = components.get(root);
854
+ if (component === void 0) continue;
855
+ component.pins.sort((left, right) => left.globalPinId - right.globalPinId);
856
+ component.rails.sort((left, right) => left.name.localeCompare(right.name));
857
+ const endpoints = [...component.endpoints, ...component.pins.map((pin) => pin.endpoint)];
858
+ if (component.pins.length === 0) {
859
+ 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));
860
+ continue;
861
+ }
862
+ const netId = nets.length;
863
+ const net = this.classify(netId, component.pins, component.rails, diagnostics);
864
+ nets.push(net);
865
+ }
866
+ return Object.freeze({
867
+ nets: Object.freeze(nets),
868
+ diagnostics: Object.freeze(diagnostics)
869
+ });
870
+ }
871
+ classify(netId, pins, rails, diagnostics) {
872
+ const drivers = pins.filter((pin) => pin.role === "driver");
873
+ const loads = pins.filter((pin) => pin.role === "load");
874
+ const sinks = pins.filter((pin) => pin.senses);
875
+ const endpoints = [...rails.map((rail) => rail.name), ...pins.map((pin) => pin.endpoint)];
876
+ const levels = new Set(rails.map((rail) => rail.level));
877
+ 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));
878
+ if (drivers.length > 1) {
879
+ const names = drivers.map((driver) => driver.endpoint).join(", ");
880
+ diagnostics.push(diagnostic("driver-conflict", this.allowMultiDriver ? "warning" : "error", this.allowMultiDriver ? `Net ${netId} has ${drivers.length} drivers (${names}); solving them as a wired-OR` : `Net ${netId} has ${drivers.length} drivers (${names}); v1 supports one driver per net (set allowMultiDriver to solve them as a wired-OR)`, netId, endpoints));
881
+ }
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
+ if (code === "driver-conflict") return "driver-conflict";
946
+ if (code === "rail-conflict") return "rail-conflict";
947
+ return "power-short";
948
+ }
949
+ function diagnostic(code, severity, message, netId, endpoints) {
950
+ return Object.freeze({
951
+ code,
952
+ severity,
953
+ message,
954
+ netId,
955
+ endpoints: Object.freeze([...endpoints])
956
+ });
957
+ }
958
+ function toConnection(pin) {
959
+ return Object.freeze({
960
+ endpoint: `${pin.deviceId}.${pin.name}`,
961
+ deviceId: pin.deviceId,
962
+ pinName: pin.name,
963
+ globalPinId: pin.globalPinId,
964
+ role: pin.role,
965
+ senses: pin.senses
966
+ });
967
+ }
968
+ /** Union-find over pin ids and rail node ids. */
969
+ var DisjointSet = class {
970
+ parent = /* @__PURE__ */ new Map();
971
+ rank = /* @__PURE__ */ new Map();
972
+ find(id) {
973
+ const parent = this.parent.get(id);
974
+ if (parent === void 0) {
975
+ this.parent.set(id, id);
976
+ this.rank.set(id, 0);
977
+ return id;
978
+ }
979
+ if (parent === id) return id;
980
+ const root = this.find(parent);
981
+ this.parent.set(id, root);
982
+ return root;
320
983
  }
321
- reset() {
322
- this.#assertNotDisposed();
323
- if (this.#runtime === void 0) {
324
- this.#pending.length = 0;
984
+ union(left, right) {
985
+ const leftRoot = this.find(left);
986
+ const rightRoot = this.find(right);
987
+ if (leftRoot === rightRoot) return;
988
+ const leftRank = this.rank.get(leftRoot) ?? 0;
989
+ const rightRank = this.rank.get(rightRoot) ?? 0;
990
+ if (leftRank < rightRank) {
991
+ this.parent.set(leftRoot, rightRoot);
325
992
  return;
326
993
  }
327
- const runtime = this.#buildRuntime(this.#schematic);
328
- this.#teardown();
329
- this.#runtime = runtime;
330
- this.#state = "ready";
994
+ this.parent.set(rightRoot, leftRoot);
995
+ if (leftRank === rightRank) this.rank.set(leftRoot, leftRank + 1);
331
996
  }
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;
997
+ };
998
+ //#endregion
999
+ //#region src/unified-ir/compiler/index.ts
1000
+ /**
1001
+ * Compiles several devices and their wiring into one unified IR module (U01).
1002
+ *
1003
+ * Device models are caller-supplied: every entry of `devices` carries the pins,
1004
+ * states and behaviors (or `kernel`) its type needs.
1005
+ *
1006
+ * ```ts
1007
+ * const circuit = compileCircuit({
1008
+ * devices: [
1009
+ * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },
1010
+ * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },
1011
+ * ],
1012
+ * connections: [
1013
+ * { from: 'drive1.channel0', to: 'sink1.anode' },
1014
+ * { from: 'sink1.cathode', to: 'GND' },
1015
+ * ],
1016
+ * });
1017
+ *
1018
+ * const jit = createIRJIT(circuit.module, { validation: circuit.validation });
1019
+ * jit.execute(circuit.entryPoints.refs.initialize, []);
1020
+ * jit.execute(circuit.entryPoints.refs.tick, []); // drive1 + nets + sink1
1021
+ * ```
1022
+ *
1023
+ * The pipeline is: validate the input, allocate the global pin and state
1024
+ * spaces, analyse the electrical topology, generate one function per device
1025
+ * phase, generate one solver per net, generate the main loop, then validate the
1026
+ * resulting module with `validateIR`.
1027
+ *
1028
+ * @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown
1029
+ * pins, electrical conflicts, or when the generated module fails validation.
1030
+ */
1031
+ function compileCircuit(input, options = {}) {
1032
+ const { devices, connections } = validateInput(input);
1033
+ const resolvedOptions = validateOptions(options);
1034
+ const names = resolveEntryNames(resolvedOptions);
1035
+ const module = createIRModule();
1036
+ const allocation = new GlobalResourceAllocator(module).allocate(devices);
1037
+ const netlist = new NetworkTopologyAnalyzer({
1038
+ ...resolvedOptions.rails === void 0 ? {} : { rails: resolvedOptions.rails },
1039
+ ...resolvedOptions.allowMultiDriver === void 0 ? {} : { allowMultiDriver: resolvedOptions.allowMultiDriver }
1040
+ }).analyze(connections, allocation.pins);
1041
+ assertNoElectricalErrors(netlist);
1042
+ const generator = new DeviceIRGenerator({
1043
+ module,
1044
+ memory: allocation.memory,
1045
+ pins: allocation.pins,
1046
+ states: allocation.states
1047
+ });
1048
+ const generated = devices.map((device) => generator.generate(device));
1049
+ const solvers = new ElectricalSolverGenerator({
1050
+ module,
1051
+ memory: allocation.memory
1052
+ }).generate(netlist);
1053
+ assertNoNameCollisions(devices, solvers.map((solver) => solver.name), names);
1054
+ const loop = new MainLoopGenerator(module).generate(generated.map((device) => device.entry), solvers, netlist, names);
1055
+ const validation = createModuleValidation(module, devices.flatMap((device) => device.description.updateResources ?? []));
1056
+ if (resolvedOptions.validate !== false) validateModule(module, validation);
1057
+ const deviceMap = new Map(generated.map((device) => [device.metadata.deviceId, device.metadata]));
1058
+ return Object.freeze({
1059
+ module,
1060
+ entryPoints: Object.freeze({
1061
+ tick: loop.names.tick,
1062
+ initialize: loop.names.initialize,
1063
+ batch: loop.names.batch,
1064
+ refs: Object.freeze({
1065
+ tick: loop.tick,
1066
+ initialize: loop.initialize,
1067
+ batch: loop.batch
1068
+ })
1069
+ }),
1070
+ pinMap: allocation.pins.pins,
1071
+ deviceMap,
1072
+ netlist,
1073
+ pins: allocation.pins,
1074
+ states: allocation.states,
1075
+ memory: allocation.memory,
1076
+ validation,
1077
+ executionOrder: loop.order,
1078
+ functions: Object.freeze(module.functions.map((fn) => fn.name))
1079
+ });
1080
+ }
1081
+ function validateInput(input) {
1082
+ if (input === null || typeof input !== "object" || Array.isArray(input)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput must be an object with devices and connections");
1083
+ const { devices, connections } = input;
1084
+ if (!Array.isArray(devices) || devices.length === 0) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput.devices must be a non-empty array");
1085
+ if (!Array.isArray(connections)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput.connections must be an array");
1086
+ return {
1087
+ devices,
1088
+ connections
1089
+ };
1090
+ }
1091
+ function validateOptions(options) {
1092
+ if (options === null || typeof options !== "object" || Array.isArray(options)) throw new UnifiedIRCompilerError("invalid-input", "Compile options must be an object");
1093
+ const resolved = options;
1094
+ if (resolved.validate !== void 0 && typeof resolved.validate !== "boolean") throw new UnifiedIRCompilerError("invalid-input", "options.validate must be a boolean");
1095
+ if (resolved.allowMultiDriver !== void 0 && typeof resolved.allowMultiDriver !== "boolean") throw new UnifiedIRCompilerError("invalid-input", "options.allowMultiDriver must be a boolean");
1096
+ if (resolved.rails !== void 0) {
1097
+ if (resolved.rails === null || typeof resolved.rails !== "object" || Array.isArray(resolved.rails)) throw new UnifiedIRCompilerError("invalid-input", "options.rails must be a plain object");
1098
+ 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`);
1099
+ }
1100
+ return resolved;
1101
+ }
1102
+ function resolveEntryNames(options) {
1103
+ const names = {
1104
+ tick: options.entryPointNames?.tick ?? DEFAULT_ENTRY_POINT_NAMES.tick,
1105
+ initialize: options.entryPointNames?.initialize ?? DEFAULT_ENTRY_POINT_NAMES.initialize,
1106
+ batch: options.entryPointNames?.batch ?? DEFAULT_ENTRY_POINT_NAMES.batch
1107
+ };
1108
+ 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`);
1109
+ if (new Set(Object.values(names)).size !== 3) throw new UnifiedIRCompilerError("invalid-input", `Entry point names must be distinct: ${JSON.stringify(names)}`);
1110
+ return Object.freeze(names);
1111
+ }
1112
+ function assertNoNameCollisions(devices, solverNames, names) {
1113
+ const reserved = /* @__PURE__ */ new Set([
1114
+ names.tick,
1115
+ names.initialize,
1116
+ names.batch,
1117
+ ...solverNames
1118
+ ]);
1119
+ for (const device of devices) for (const phase of [
1120
+ "initialize",
1121
+ "tick",
1122
+ "update"
1123
+ ]) {
1124
+ const generated = `${device.id}_${phase}`;
1125
+ 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 });
1126
+ }
1127
+ }
1128
+ function validateModule(module, validation) {
1129
+ const result = validateIR(module, validation);
1130
+ if (result.ok) return;
1131
+ const details = result.diagnostics.map((entry) => `- [${entry.code}] ${entry.message} at ${entry.location.path}`).join("\n");
1132
+ throw new UnifiedIRCompilerError("invalid-ir", `Generated IR failed validateIR (${result.diagnostics.length} diagnostic(s)):\n${details}`);
1133
+ }
1134
+ //#endregion
1135
+ //#region src/unified-ir/runtime/types.ts
1136
+ /**
1137
+ * Error raised while driving a `Circuit`.
1138
+ *
1139
+ * The code is stable and machine-checkable, and the message always names the
1140
+ * offending device/pin/state plus the values that would have been accepted.
1141
+ */
1142
+ var CircuitError = class extends Error {
1143
+ name = "CircuitError";
1144
+ code;
1145
+ deviceId;
1146
+ pinName;
1147
+ stateName;
1148
+ constructor(code, message, options = {}) {
1149
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
1150
+ this.code = code;
1151
+ this.deviceId = options.deviceId;
1152
+ this.pinName = options.pinName;
1153
+ this.stateName = options.stateName;
1154
+ }
1155
+ };
1156
+ //#endregion
1157
+ //#region src/unified-ir/runtime/accessors.ts
1158
+ /**
1159
+ * Builds one accessor per compiled device.
1160
+ *
1161
+ * A description that declares `accessor` owns its surface; every other device
1162
+ * keeps the generic state/pin accessor. The returned record is frozen and keyed
1163
+ * by device id.
1164
+ */
1165
+ function buildDeviceAccessors(context) {
1166
+ const entries = [];
1167
+ for (const device of context.compiled.deviceMap.values()) {
1168
+ const base = createBaseAccessor(context, device);
1169
+ if (device.accessor !== void 0) entries.push([device.deviceId, device.accessor({
1170
+ deviceId: device.deviceId,
1171
+ storage: context.jit.storage,
1172
+ assertActive: context.assertActive,
1173
+ step: context.step,
1174
+ runBatch: context.runBatch
1175
+ })]);
1176
+ else entries.push([device.deviceId, base]);
1177
+ }
1178
+ return Object.freeze(Object.fromEntries(entries));
1179
+ }
1180
+ function createBaseAccessor(context, device) {
1181
+ const { jit } = context;
1182
+ const storage = jit.storage;
1183
+ const memory = context.compiled.memory;
1184
+ const resolved = context.compiled.pins.devices.get(device.deviceId)?.resolved;
1185
+ const accessor = {
1186
+ deviceId: device.deviceId,
1187
+ type: device.type,
1188
+ pinNames: Object.freeze([...device.pins.keys()]),
1189
+ stateNames: Object.freeze([...device.states.keys()]),
1190
+ readPin(pinName) {
1191
+ context.assertActive();
1192
+ const pin = pinOf(device, resolved, pinName);
1193
+ return storage.loadArray(memory.output, pin.globalPinId) === true;
1194
+ },
1195
+ writePin(pinName, value) {
1196
+ context.assertActive();
1197
+ const pin = pinOf(device, resolved, pinName);
1198
+ 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`, {
1199
+ deviceId: device.deviceId,
1200
+ pinName
1201
+ });
1202
+ assertBoolean(device.deviceId, pinName, value);
1203
+ storage.storeArray(memory.output, pin.globalPinId, value);
1204
+ },
1205
+ getState(name) {
1206
+ context.assertActive();
1207
+ const slot = stateOf(device, name);
1208
+ return storage.loadArray(slot.array, slot.index);
1209
+ },
1210
+ setState(name, value) {
1211
+ context.assertActive();
1212
+ const slot = stateOf(device, name);
1213
+ const accepted = coerceStateValue(device, slot, value);
343
1214
  try {
344
- this.#modules.set(symbol.device, await loadDeviceModule(symbol.device, this.#options.devices));
1215
+ storage.storeArray(slot.array, slot.index, accepted);
345
1216
  } 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,
1217
+ throw new CircuitError("invalid-state-value", `State "${device.deviceId}.${name}" (${slot.type}) rejected ${String(value)}`, {
1218
+ deviceId: device.deviceId,
1219
+ stateName: name,
348
1220
  cause
349
1221
  });
350
1222
  }
351
1223
  }
1224
+ };
1225
+ return Object.freeze(accessor);
1226
+ }
1227
+ /** Resolves one pin of `device`, or throws with every pin the device declares. */
1228
+ function pinOf(device, resolved, pinName) {
1229
+ const pin = resolved?.get(pinName);
1230
+ if (pin === void 0) throw new CircuitError("pin-not-found", `Device "${device.deviceId}" (${device.type}) has no pin "${pinName}". Available: ${formatNames(device.pins.keys())}`, {
1231
+ deviceId: device.deviceId,
1232
+ pinName
1233
+ });
1234
+ return pin;
1235
+ }
1236
+ /** Resolves one state slot of `device`, or throws with every state it declares. */
1237
+ function stateOf(device, name) {
1238
+ const slot = device.states.get(name);
1239
+ if (slot === void 0) throw new CircuitError("state-not-found", `Device "${device.deviceId}" (${device.type}) has no state "${name}". Available: ${formatNames(device.states.keys())}`, {
1240
+ deviceId: device.deviceId,
1241
+ stateName: name
1242
+ });
1243
+ return slot;
1244
+ }
1245
+ function assertBoolean(deviceId, pinName, value) {
1246
+ if (typeof value !== "boolean") throw new CircuitError("invalid-state-value", `Pin "${deviceId}.${pinName}" needs a boolean level, received ${typeof value}`, {
1247
+ deviceId,
1248
+ pinName
1249
+ });
1250
+ }
1251
+ /**
1252
+ * Validates a host-written state value against the declared scalar type.
1253
+ * Range checks stay in storage, which owns the encoding.
1254
+ */
1255
+ function coerceStateValue(device, slot, value) {
1256
+ if (slot.type === "bool") {
1257
+ 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)}`, {
1258
+ deviceId: device.deviceId,
1259
+ stateName: slot.name
1260
+ });
1261
+ return value;
352
1262
  }
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
1263
+ if (slot.type === "f32" || slot.type === "f64") {
1264
+ if (typeof value === "number" || isFloatBits(value)) return value;
1265
+ throw new CircuitError("invalid-state-value", `State "${device.deviceId}.${slot.name}" is ${slot.type} and needs a number or FloatBits`, {
1266
+ deviceId: device.deviceId,
1267
+ stateName: slot.name
360
1268
  });
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);
1269
+ }
1270
+ 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)}`, {
1271
+ deviceId: device.deviceId,
1272
+ stateName: slot.name
1273
+ });
1274
+ return value;
1275
+ }
1276
+ function isFloatBits(value) {
1277
+ if (typeof value !== "object" || value === null) return false;
1278
+ const candidate = value;
1279
+ return (candidate.type === "f32" || candidate.type === "f64") && typeof candidate.bits === "string";
1280
+ }
1281
+ function formatNames(names) {
1282
+ const list = [...names];
1283
+ return list.length === 0 ? "(none)" : `[${list.join(", ")}]`;
1284
+ }
1285
+ //#endregion
1286
+ //#region src/unified-ir/runtime/circuit.ts
1287
+ /** Every generated entry takes no arguments, so one frozen array is reused. */
1288
+ var NO_ARGS = Object.freeze([]);
1289
+ /** `unified_tick_batch` takes a u32 tick count. */
1290
+ var MAX_BATCH_TICKS = 4294967295;
1291
+ /** Virtual time is a JS number, so it wraps before losing integer precision. */
1292
+ var MAX_VIRTUAL_TIME = Number.MAX_SAFE_INTEGER;
1293
+ var DEFAULT_INSTANCE_ID = "unified-circuit";
1294
+ /**
1295
+ * Host-facing runtime of one compiled unified circuit (U02).
1296
+ *
1297
+ * ```ts
1298
+ * const circuit = await Circuit.create({
1299
+ * devices: [
1300
+ * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },
1301
+ * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },
1302
+ * ],
1303
+ * connections: [
1304
+ * { from: 'drive1.PA0', to: 'sink1.anode' },
1305
+ * { from: 'sink1.cathode', to: 'GND' },
1306
+ * ],
1307
+ * });
1308
+ *
1309
+ * circuit.runBatch(1_000_000); // one engine call
1310
+ * expect(circuit.tickCount).toBe(1_000_000n);
1311
+ *
1312
+ * circuit.reset();
1313
+ * circuit.setPin('drive1.PA0', true); // host drives the pin
1314
+ * circuit.step();
1315
+ * expect(circuit.devices.sink1.getState('lamp')).toBe(true);
1316
+ * ```
1317
+ *
1318
+ * `Circuit` owns the engine instance and the tick counter; the compiled module
1319
+ * keeps every device, net and the main loop in one `@mica-js/ir` module, so a
1320
+ * batch is one interpreter/JIT call for the whole circuit.
1321
+ */
1322
+ var Circuit = class Circuit {
1323
+ /** Typed per-device accessors, keyed by device id. */
1324
+ devices;
1325
+ #compiled;
1326
+ #jit;
1327
+ #context;
1328
+ #pins;
1329
+ #pinNames;
1330
+ #seeds;
1331
+ #tickCount = 0n;
1332
+ #virtualTime = 0;
1333
+ #disposed = false;
1334
+ constructor(compiled, jit, instanceId, accessors, pins, seeds) {
1335
+ this.#compiled = compiled;
1336
+ this.#jit = jit;
1337
+ this.#context = {
1338
+ instanceId,
1339
+ virtualTime: 0
1340
+ };
1341
+ this.devices = accessors;
1342
+ this.#pins = pins;
1343
+ this.#pinNames = Object.freeze([...pins.keys()]);
1344
+ this.#seeds = seeds;
1345
+ }
1346
+ /**
1347
+ * Compiles `input`, builds the engine instance and runs the generated
1348
+ * `initialize` entry once.
1349
+ *
1350
+ * The input is inferred as a `const` type, so a literal device list keeps its
1351
+ * ids and `circuit.devices.<id>` is typed without a cast.
1352
+ *
1353
+ * @throws {UnifiedIRCompilerError} when the circuit cannot be compiled.
1354
+ * @throws {CircuitError} for invalid options.
1355
+ */
1356
+ static async create(input, options = {}) {
1357
+ const resolved = resolveOptions(options);
1358
+ const compiled = compileCircuit(input, compileOptionsOf(resolved));
1359
+ const jit = createEngine(compiled, resolved);
1360
+ const host = { circuit: void 0 };
1361
+ const circuit = new Circuit(compiled, jit, resolved.instanceId, buildDeviceAccessors({
1362
+ compiled,
1363
+ jit,
1364
+ assertActive: () => {
1365
+ circuit.#assertActive();
1366
+ },
1367
+ step: () => {
1368
+ host.circuit?.step();
1369
+ },
1370
+ runBatch: (count) => {
1371
+ host.circuit?.runBatch(count);
369
1372
  }
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
- }
1373
+ }), pinRuntimeOf(compiled), resetSeedsOf(compiled));
1374
+ host.circuit = circuit;
1375
+ jit.execute(compiled.entryPoints.refs.initialize, NO_ARGS, circuit.#context);
1376
+ return circuit;
382
1377
  }
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
- }
1378
+ /**
1379
+ * Runs `count` ticks inside one generated loop — the throughput path.
1380
+ *
1381
+ * The whole batch is one engine call; `tickCount` grows by `count` once the
1382
+ * call returns, so a failed batch never advances the clock.
1383
+ *
1384
+ * @throws {CircuitError} with code `invalid-count` unless `count` is a u32.
1385
+ */
1386
+ runBatch(count) {
1387
+ this.#assertActive();
1388
+ 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)}`);
1389
+ if (count === 0) return;
1390
+ this.#context.virtualTime = this.#virtualTime;
1391
+ this.#jit.execute(this.#compiled.entryPoints.refs.batch, [count], this.#context);
1392
+ this.#advance(count);
404
1393
  }
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
- }
1394
+ /**
1395
+ * Advances exactly one tick — the debugging path.
1396
+ *
1397
+ * Every call is one engine entry, so prefer `runBatch` for throughput.
1398
+ */
1399
+ step() {
1400
+ this.#assertActive();
1401
+ this.#context.virtualTime = this.#virtualTime;
1402
+ this.#jit.execute(this.#compiled.entryPoints.refs.tick, NO_ARGS, this.#context);
1403
+ this.#advance(1);
424
1404
  }
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 });
1405
+ /**
1406
+ * Restores every memory to its declared initial value, re-runs `initialize`
1407
+ * and resets `tickCount` to `0n`.
1408
+ *
1409
+ * Device state written by earlier ticks is discarded, so the circuit behaves
1410
+ * exactly like a freshly created one.
1411
+ */
1412
+ reset() {
1413
+ this.#assertActive();
1414
+ for (const seed of this.#seeds) {
1415
+ if (seed.kind === "state") {
1416
+ this.#jit.storage.storeState(seed.ref, seed.value);
1417
+ continue;
1418
+ }
1419
+ if (seed.kind === "bytes") {
1420
+ for (let index = 0; index < seed.values.length; index += 1) this.#jit.storage.storeBytes("u8", "little", seed.ref, index, seed.values[index]);
1421
+ continue;
1422
+ }
1423
+ if (seed.kind === "readonly-bytes") {
1424
+ try {
1425
+ this.#jit.storage.updateBytesFromBytes(seed.ref, 0, seed.values);
1426
+ } catch {}
1427
+ continue;
1428
+ }
1429
+ for (let index = 0; index < seed.values.length; index += 1) this.#jit.storage.storeArray(seed.ref, index, seed.values[index]);
434
1430
  }
1431
+ this.#tickCount = 0n;
1432
+ this.#virtualTime = 0;
1433
+ this.#context.virtualTime = 0;
1434
+ this.#jit.execute(this.#compiled.entryPoints.refs.initialize, NO_ARGS, this.#context);
435
1435
  }
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));
1436
+ /**
1437
+ * Reads the level one pin observes.
1438
+ *
1439
+ * A sensing pin (input, passive or bidirectional) reports the solved net
1440
+ * level; a pure driver pin reports the level it actually drives, which is
1441
+ * `false` unless it is configured push-pull.
1442
+ *
1443
+ * @throws {CircuitError} with code `pin-not-found`.
1444
+ */
1445
+ getPin(pinName) {
1446
+ this.#assertActive();
1447
+ const pin = this.#pinRuntime(pinName);
1448
+ const storage = this.#jit.storage;
1449
+ if (pin.senses) return storage.loadArray(this.#compiled.memory.input, pin.globalPinId) === true;
1450
+ return Number(storage.loadArray(this.#compiled.memory.mode, pin.globalPinId)) === PIN_MODE.pushPull && storage.loadArray(this.#compiled.memory.output, pin.globalPinId) === true;
443
1451
  }
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;
1452
+ /**
1453
+ * Forces the level of one pin from the host.
1454
+ *
1455
+ * A driver pin gets its output latch written, so the level survives the next
1456
+ * electrical solve. A sensing pin gets the solved-value slot overridden, which
1457
+ * lasts until the next tick recomputes its net.
1458
+ *
1459
+ * @throws {CircuitError} with code `pin-not-found`.
1460
+ */
1461
+ setPin(pinName, value) {
1462
+ this.#assertActive();
1463
+ const pin = this.#pinRuntime(pinName);
1464
+ if (typeof value !== "boolean") throw new CircuitError("invalid-state-value", `Pin "${pinName}" needs a boolean level, received ${typeof value}`, { pinName });
1465
+ const target = pin.role === "driver" ? this.#compiled.memory.output : this.#compiled.memory.input;
1466
+ this.#jit.storage.storeArray(target, pin.globalPinId, value);
449
1467
  }
450
- #assertNotDisposed() {
451
- if (this.#state === "disposed") throw new SimulatorError("simulator/disposed", "The executor is disposed.");
1468
+ /** Number of ticks completed since creation or the last `reset()`. */
1469
+ get tickCount() {
1470
+ this.#assertActive();
1471
+ return this.#tickCount;
452
1472
  }
453
- #report(diagnostic) {
454
- try {
455
- this.#options.onDiagnostic?.(diagnostic);
456
- } catch {}
1473
+ /** Virtual tick time completed since creation or the last `reset()`. */
1474
+ get virtualTime() {
1475
+ this.#assertActive();
1476
+ return this.#virtualTime;
1477
+ }
1478
+ /** Underlying engine instance, e.g. for diagnostics or custom entries. */
1479
+ get jit() {
1480
+ this.#assertActive();
1481
+ return this.#jit;
1482
+ }
1483
+ /** Whether `dispose()` already ran. */
1484
+ get disposed() {
1485
+ return this.#disposed;
1486
+ }
1487
+ /**
1488
+ * Releases the runtime. Idempotent; every later call throws a `CircuitError`
1489
+ * with code `disposed`, including stale device accessors.
1490
+ */
1491
+ dispose() {
1492
+ this.#disposed = true;
1493
+ this.#tickCount = 0n;
1494
+ this.#virtualTime = 0;
1495
+ }
1496
+ /** @internal Shared guard of the circuit and all of its accessors. */
1497
+ #assertActive() {
1498
+ if (this.#disposed) throw new CircuitError("disposed", "Circuit has been disposed; create a new circuit to keep simulating");
1499
+ }
1500
+ #advance(count) {
1501
+ this.#tickCount += BigInt(count);
1502
+ const next = this.#virtualTime + count;
1503
+ this.#virtualTime = next > MAX_VIRTUAL_TIME ? 0 : next;
1504
+ }
1505
+ #pinRuntime(pinName) {
1506
+ const pin = this.#pins.get(pinName);
1507
+ if (pin === void 0) throw new CircuitError("pin-not-found", `Pin "${pinName}" not found. Available: ${this.#pinNames.length === 0 ? "(none)" : `[${this.#pinNames.join(", ")}]`}`, { pinName });
1508
+ return pin;
457
1509
  }
458
1510
  };
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 }
1511
+ /** Resolves every pin of the global address space into its runtime view. */
1512
+ function pinRuntimeOf(compiled) {
1513
+ const pins = /* @__PURE__ */ new Map();
1514
+ for (const [deviceId, allocation] of compiled.pins.devices) for (const [pinName, pin] of allocation.resolved) pins.set(`${deviceId}.${pinName}`, Object.freeze({
1515
+ globalPinId: pin.globalPinId,
1516
+ role: pin.role,
1517
+ senses: pin.senses
472
1518
  }));
1519
+ return pins;
473
1520
  }
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
1521
+ /**
1522
+ * Captures the declared initial value of every scalar memory, which is what
1523
+ * `reset()` restores before the generated `initialize` runs again.
1524
+ */
1525
+ function resetSeedsOf(compiled) {
1526
+ const seeds = [];
1527
+ for (const memory of compiled.module.memories) if (memory.kind === "array") seeds.push({
1528
+ kind: "array",
1529
+ ref: memory.ref,
1530
+ values: memory.initial
1531
+ });
1532
+ else if (memory.kind === "state") seeds.push({
1533
+ kind: "state",
1534
+ ref: memory.ref,
1535
+ value: memory.initial[0]
1536
+ });
1537
+ else if (memory.kind === "bytes") {
1538
+ if (memory.writable) seeds.push({
1539
+ kind: "bytes",
1540
+ ref: memory.ref,
1541
+ values: memory.initial
1542
+ });
1543
+ else seeds.push({
1544
+ kind: "readonly-bytes",
1545
+ ref: memory.ref,
1546
+ values: Uint8Array.from(memory.initial)
483
1547
  });
484
1548
  }
1549
+ return Object.freeze(seeds);
485
1550
  }
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
1551
+ function createEngine(compiled, options) {
1552
+ const base = {
1553
+ validation: compiled.validation,
1554
+ maxSteps: Number.MAX_SAFE_INTEGER
1555
+ };
1556
+ if (options.engine === "reference") return createIRInterpreter(compiled.module, base);
1557
+ return createIRJIT(compiled.module, {
1558
+ ...base,
1559
+ jit: {
1560
+ tierUpThreshold: 0,
1561
+ ...options.jit
1562
+ }
1563
+ });
1564
+ }
1565
+ function compileOptionsOf(options) {
1566
+ return {
1567
+ validate: options.validateIR,
1568
+ allowMultiDriver: options.allowMultiDriver,
1569
+ ...options.rails === void 0 ? {} : { rails: options.rails }
1570
+ };
1571
+ }
1572
+ function resolveOptions(options) {
1573
+ if (options === null || typeof options !== "object" || Array.isArray(options)) throw new CircuitError("invalid-options", "Circuit options must be a plain object");
1574
+ const candidate = options;
1575
+ const engine = candidate.engine ?? "jit";
1576
+ if (engine !== "jit" && engine !== "reference") throw new CircuitError("invalid-options", `engine=${String(engine)} must be "jit" or "reference"`);
1577
+ if (candidate.validateIR !== void 0 && typeof candidate.validateIR !== "boolean") throw new CircuitError("invalid-options", "validateIR must be a boolean");
1578
+ if (candidate.instanceId !== void 0 && candidate.instanceId.length === 0) throw new CircuitError("invalid-options", "instanceId must be a non-empty string");
1579
+ if (candidate.jit !== void 0) {
1580
+ if (candidate.jit === null || typeof candidate.jit !== "object" || Array.isArray(candidate.jit)) throw new CircuitError("invalid-options", "jit must be a JIT tuning object");
1581
+ }
1582
+ let allowMultiDriver = false;
1583
+ let rails;
1584
+ if (candidate.electrical !== void 0) {
1585
+ const electrical = candidate.electrical;
1586
+ if (electrical === null || typeof electrical !== "object" || Array.isArray(electrical)) throw new CircuitError("invalid-options", "electrical must be a plain object");
1587
+ if (electrical.allowMultiDriver !== void 0) {
1588
+ if (typeof electrical.allowMultiDriver !== "boolean") throw new CircuitError("invalid-options", "electrical.allowMultiDriver must be a boolean");
1589
+ allowMultiDriver = electrical.allowMultiDriver;
1590
+ }
1591
+ rails = electrical.rails;
1592
+ }
1593
+ return Object.freeze({
1594
+ engine,
1595
+ jit: candidate.jit,
1596
+ validateIR: candidate.validateIR ?? true,
1597
+ allowMultiDriver,
1598
+ rails,
1599
+ instanceId: candidate.instanceId ?? DEFAULT_INSTANCE_ID
1600
+ });
1601
+ }
1602
+ //#endregion
1603
+ //#region src/unified-ir/runtime/factory.ts
1604
+ /**
1605
+ * Compiles a schematic sheet into a circuit.
1606
+ *
1607
+ * Nets come from `deriveSchematicTopology`, so wires, junctions, labels and
1608
+ * power symbols keep their usual meaning: a net that names a rail connects
1609
+ * every member to that rail, and any other net joins its pins pairwise (the
1610
+ * compiler merges transitively).
1611
+ *
1612
+ * ```ts
1613
+ * const circuit = await createCircuitFromSchematic(schematic, {
1614
+ * devices: symbolProvider,
1615
+ * resolveDevice: (reference) => bindings.get(reference.deviceId),
1616
+ * });
1617
+ * ```
1618
+ *
1619
+ * @throws {CircuitError} with code `unresolved-device` when a component symbol
1620
+ * has no binding; `SchematicError` for malformed sheets.
1621
+ */
1622
+ async function createCircuitFromSchematic(schematic, options) {
1623
+ return (await createSchematicCircuit(schematic, options)).circuit;
1624
+ }
1625
+ /**
1626
+ * Compiles a schematic and reports which circuit device each symbol became.
1627
+ *
1628
+ * {@link createCircuitFromSchematic} returns only the circuit; hosts that route
1629
+ * schematic endpoints to circuit accessors need the mapping as well.
1630
+ */
1631
+ async function createSchematicCircuit(schematic, options) {
1632
+ 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");
1633
+ if (options === null || typeof options !== "object") throw new CircuitError("invalid-options", "createSchematicCircuit needs options");
1634
+ const { resolveDevice, devices, tolerance, ...runtime } = options;
1635
+ if (typeof resolveDevice !== "function") throw new CircuitError("invalid-options", "resolveDevice must be a function");
1636
+ const usedIds = /* @__PURE__ */ new Set();
1637
+ const deviceIdBySymbol = /* @__PURE__ */ new Map();
1638
+ const deviceConfigs = [];
1639
+ const bindings = [];
1640
+ let componentCount = 0;
1641
+ for (const symbol of schematic.sheet.symbols) {
1642
+ if (symbolRole(symbol.device) !== "component") continue;
1643
+ componentCount += 1;
1644
+ const reference = parseDeviceReference(symbol.device);
1645
+ const binding = reference === void 0 ? void 0 : resolveDevice(reference);
1646
+ 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 });
1647
+ const deviceId = uniqueDeviceId(symbol.designator ?? symbol.id, usedIds);
1648
+ usedIds.add(deviceId);
1649
+ deviceIdBySymbol.set(symbol.id, deviceId);
1650
+ deviceConfigs.push({
1651
+ id: deviceId,
1652
+ type: binding.type,
1653
+ description: binding.description,
1654
+ ...binding.config === void 0 ? {} : { config: binding.config }
1655
+ });
1656
+ if (reference !== void 0) bindings.push({
1657
+ symbolId: symbol.id,
1658
+ deviceId,
1659
+ reference,
1660
+ type: binding.type
494
1661
  });
495
1662
  }
1663
+ const topology = deriveSchematicTopology(schematic, {
1664
+ ...devices === void 0 ? {} : { devices },
1665
+ ...tolerance === void 0 ? {} : { tolerance }
1666
+ });
1667
+ 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");
1668
+ const railNames = /* @__PURE__ */ new Set([...Object.keys(DEFAULT_RAILS), ...Object.keys(options.electrical?.rails ?? {})]);
1669
+ const connections = [];
1670
+ for (const net of topology.nets) {
1671
+ const endpoints = [];
1672
+ let rail;
1673
+ for (const member of net.members) {
1674
+ if (member.kind === "pin") {
1675
+ const deviceId = deviceIdBySymbol.get(member.symbolId);
1676
+ 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 });
1677
+ endpoints.push(`${deviceId}.${member.pinId}`);
1678
+ continue;
1679
+ }
1680
+ if (member.kind === "power" || member.kind === "ground") rail = net.name ?? rail;
1681
+ }
1682
+ if (endpoints.length === 0) continue;
1683
+ const railName = rail ?? (net.name !== null && railNames.has(net.name) ? net.name : void 0);
1684
+ if (railName !== void 0) {
1685
+ for (const endpoint of endpoints) connections.push({
1686
+ from: endpoint,
1687
+ to: railName
1688
+ });
1689
+ continue;
1690
+ }
1691
+ const first = endpoints[0];
1692
+ for (const endpoint of endpoints.slice(1)) connections.push({
1693
+ from: first,
1694
+ to: endpoint
1695
+ });
1696
+ }
1697
+ const input = {
1698
+ devices: Object.freeze(deviceConfigs),
1699
+ connections: Object.freeze(connections)
1700
+ };
1701
+ const circuit = await Circuit.create(input, runtime);
1702
+ return Object.freeze({
1703
+ circuit,
1704
+ bindings: Object.freeze(bindings)
1705
+ });
1706
+ }
1707
+ /**
1708
+ * Turns a designator or symbol id into a compiler-safe device id.
1709
+ *
1710
+ * Device ids prefix generated IR function names, so they must be identifiers.
1711
+ */
1712
+ function uniqueDeviceId(preferred, used) {
1713
+ const base = sanitizeDeviceId(preferred);
1714
+ if (!used.has(base)) return base;
1715
+ for (let suffix = 2;; suffix += 1) {
1716
+ const candidate = `${base}_${suffix}`;
1717
+ if (!used.has(candidate)) return candidate;
1718
+ }
1719
+ }
1720
+ function sanitizeDeviceId(value) {
1721
+ const cleaned = value.replace(/[^A-Za-z0-9_]/g, "_");
1722
+ if (cleaned.length === 0) return "device";
1723
+ return /^[A-Za-z_]/.test(cleaned) ? cleaned : `d_${cleaned}`;
1724
+ }
1725
+ //#endregion
1726
+ //#region src/host/circuit-host.ts
1727
+ /** Picoseconds per circuit step used when mapping `Circuit.virtualTime` to simulation time. */
1728
+ var DEFAULT_STEP_PS = 1e4;
1729
+ /**
1730
+ * Adapts one already-loaded unified-IR circuit to the RFC 0018 device host.
1731
+ *
1732
+ * This is the same-thread adapter for an owner that keeps `Circuit` accessors for itself (a
1733
+ * diagnostics bench, for example). Application/canvas integration uses
1734
+ * `createDeviceSimulationHostFromSandbox` from `@mica-js/simulator/sandbox` and never holds a circuit.
1735
+ */
1736
+ function createCircuitDeviceSimulationHost({ circuit, ownsCircuit = true, schematic, topics = [], stepPs = DEFAULT_STEP_PS, deliver }) {
1737
+ const simTime = () => circuit.virtualTime * stepPs;
1738
+ return {
1739
+ async loadSchematic() {},
1740
+ async reset() {
1741
+ circuit.reset();
1742
+ },
1743
+ async tick(dt) {
1744
+ if (!Number.isSafeInteger(dt) || dt <= 0) throw new TypeError(`DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`);
1745
+ circuit.runBatch(1);
1746
+ return {
1747
+ simTime: simTime(),
1748
+ executed: 1
1749
+ };
1750
+ },
1751
+ async deliver(target, payload) {
1752
+ deliver(target.symbol, target.port, payload);
1753
+ },
1754
+ onDidPublish: () => toDisposable(() => {}),
1755
+ async getTopics() {
1756
+ return topics;
1757
+ },
1758
+ async getSimTime() {
1759
+ return simTime();
1760
+ },
1761
+ async getSchematic() {
1762
+ return schematic;
1763
+ },
1764
+ async dispose() {
1765
+ if (ownsCircuit) circuit.dispose();
1766
+ }
1767
+ };
1768
+ }
1769
+ //#endregion
1770
+ //#region src/host/runtime.ts
1771
+ var INSTANCE_ID = "device-simulation-host";
1772
+ function targetKey(deviceId, port) {
1773
+ return `${deviceId}\u0000${port}`;
1774
+ }
1775
+ /**
1776
+ * Value equality of two topic payloads.
1777
+ *
1778
+ * A canvas topic is a `level` unless it carries text or bytes (RFC 0017), so re-sending the value a
1779
+ * device already published only costs a widget repaint. Byte payloads compare by content because a
1780
+ * device may hand out a fresh buffer per step.
1781
+ */
1782
+ function samePayload(previous, next) {
1783
+ if (Object.is(previous, next)) return true;
1784
+ if (previous instanceof Uint8Array && next instanceof Uint8Array) {
1785
+ if (previous.length !== next.length) return false;
1786
+ for (let index = 0; index < previous.length; index += 1) if (previous[index] !== next[index]) return false;
1787
+ return true;
1788
+ }
1789
+ if (typeof previous !== "object" || previous === null) return false;
1790
+ if (typeof next !== "object" || next === null) return false;
1791
+ const a = previous;
1792
+ const b = next;
1793
+ return a.x === b.x && a.y === b.y && a.z === b.z;
1794
+ }
1795
+ function isVec2d(value) {
1796
+ if (typeof value !== "object" || value === null) return false;
1797
+ const point = value;
1798
+ return typeof point.x === "number" && typeof point.y === "number";
1799
+ }
1800
+ function payloadMatches(type, payload) {
1801
+ switch (type) {
1802
+ case "boolean": return typeof payload === "boolean";
1803
+ case "number": return typeof payload === "number";
1804
+ case "string": return typeof payload === "string";
1805
+ case "bytes":
1806
+ case "bytes<rgb565>":
1807
+ case "bytes<segments>": return payload instanceof Uint8Array;
1808
+ case "vec2d": return isVec2d(payload);
1809
+ case "vec3d": return isVec2d(payload) && typeof payload.z === "number";
1810
+ }
1811
+ }
1812
+ function decodeSchematic(bytes) {
1813
+ return parseSchematic(new TextDecoder().decode(bytes));
1814
+ }
1815
+ function buildRuntime(circuit, schematic, bindings, resolveDevice) {
1816
+ const symbols = new Map(schematic.sheet.symbols.map((symbol) => [symbol.id, symbol]));
1817
+ const devices = [];
1818
+ const topics = [];
1819
+ const inputs = /* @__PURE__ */ new Map();
1820
+ for (const binding of bindings) {
1821
+ const deviceBinding = resolveDevice(binding.reference);
1822
+ const accessor = circuit.devices[binding.deviceId];
1823
+ if (deviceBinding === void 0 || accessor === void 0) continue;
1824
+ const designator = symbols.get(binding.symbolId)?.designator ?? binding.symbolId;
1825
+ const device = {
1826
+ symbol: binding.symbolId,
1827
+ designator,
1828
+ binding: deviceBinding,
1829
+ accessor
1830
+ };
1831
+ devices.push(device);
1832
+ for (const topic of deviceBinding.topics ?? []) {
1833
+ topics.push({
1834
+ symbol: binding.symbolId,
1835
+ designator,
1836
+ port: topic.port,
1837
+ direction: topic.direction,
1838
+ type: topic.type,
1839
+ ...topic.title === void 0 ? {} : { title: topic.title }
1840
+ });
1841
+ if (topic.direction === "input") inputs.set(targetKey(binding.symbolId, topic.port), {
1842
+ device,
1843
+ topic
1844
+ });
1845
+ }
1846
+ }
1847
+ return {
1848
+ circuit,
1849
+ schematic,
1850
+ devices,
1851
+ topics: Object.freeze(topics),
1852
+ inputs
1853
+ };
1854
+ }
1855
+ /**
1856
+ * Same-thread `DeviceSimulationHost` over a schematic compiled by the unified-IR runtime.
1857
+ *
1858
+ * The host owns the circuit: `loadSchematic` reads, parses and compiles it, `tick` advances one
1859
+ * circuit step and publishes the output topics that changed, and `deliver` queues widget payloads
1860
+ * for the next step. Device models and their endpoints come from `resolveDevice`, so the host stays
1861
+ * generic. Nothing here touches the DOM, so the sandbox guest and a Node test use the same
1862
+ * implementation.
1863
+ */
1864
+ function createSchematicDeviceSimulationHost(options) {
1865
+ if (typeof options?.resolveDevice !== "function") throw new TypeError("createSchematicDeviceSimulationHost needs a resolveDevice function");
1866
+ const { read, devices: symbols, resolveDevice } = options;
1867
+ const publishes = new Emitter();
1868
+ const pending = [];
1869
+ /** Last payload published per endpoint, so an unchanged level topic stays silent. */
1870
+ const published = /* @__PURE__ */ new Map();
1871
+ let runtime;
1872
+ let simTimePs = 0;
1873
+ let disposed = false;
1874
+ const publishOutputs = (active) => {
1875
+ if (!publishes.hasListeners) return;
1876
+ for (const device of active.devices) for (const topic of device.binding.topics ?? []) {
1877
+ if (topic.direction !== "output" || device.binding.read === void 0) continue;
1878
+ const key = targetKey(device.symbol, topic.port);
1879
+ const payload = device.binding.read(device.accessor, topic.port);
1880
+ if (published.has(key) && samePayload(published.get(key), payload)) continue;
1881
+ published.set(key, payload);
1882
+ const publish = {
1883
+ target: {
1884
+ symbol: device.symbol,
1885
+ port: topic.port
1886
+ },
1887
+ payload,
1888
+ simTime: simTimePs
1889
+ };
1890
+ publishes.fire(publish);
1891
+ }
1892
+ };
1893
+ const clearRuntime = () => {
1894
+ runtime?.circuit.dispose();
1895
+ runtime = void 0;
1896
+ pending.length = 0;
1897
+ published.clear();
1898
+ simTimePs = 0;
1899
+ };
1900
+ return {
1901
+ async loadSchematic(uri) {
1902
+ if (disposed) return;
1903
+ if (uri === void 0) {
1904
+ clearRuntime();
1905
+ return;
1906
+ }
1907
+ const schematic = decodeSchematic(await read(uri));
1908
+ const symbolProvider = typeof symbols === "function" ? symbols() : symbols;
1909
+ const compiled = await createSchematicCircuit(schematic, {
1910
+ ...symbolProvider === void 0 ? {} : { devices: symbolProvider },
1911
+ resolveDevice,
1912
+ instanceId: INSTANCE_ID
1913
+ });
1914
+ const next = buildRuntime(compiled.circuit, schematic, compiled.bindings, resolveDevice);
1915
+ runtime?.circuit.dispose();
1916
+ pending.length = 0;
1917
+ published.clear();
1918
+ simTimePs = 0;
1919
+ runtime = next;
1920
+ },
1921
+ async reset() {
1922
+ if (disposed) return;
1923
+ pending.length = 0;
1924
+ published.clear();
1925
+ simTimePs = 0;
1926
+ runtime?.circuit.reset();
1927
+ },
1928
+ async tick(dt) {
1929
+ if (!Number.isSafeInteger(dt) || dt <= 0) throw new TypeError(`DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`);
1930
+ if (disposed) return {
1931
+ simTime: simTimePs,
1932
+ executed: 0
1933
+ };
1934
+ const active = runtime;
1935
+ if (active === void 0) {
1936
+ simTimePs += dt;
1937
+ return {
1938
+ simTime: simTimePs,
1939
+ executed: 0
1940
+ };
1941
+ }
1942
+ const queued = pending.splice(0, pending.length);
1943
+ for (const delivery of queued) {
1944
+ if (delivery.device.binding.deliver === void 0) throw new TypeError(`${delivery.device.binding.type} has no writable topic ${JSON.stringify(delivery.port)}`);
1945
+ delivery.device.binding.deliver(delivery.device.accessor, delivery.port, delivery.payload);
1946
+ }
1947
+ active.circuit.runBatch(1);
1948
+ simTimePs += dt;
1949
+ publishOutputs(active);
1950
+ return {
1951
+ simTime: simTimePs,
1952
+ executed: 1
1953
+ };
1954
+ },
1955
+ async deliver(target, payload) {
1956
+ if (disposed) return;
1957
+ const active = runtime;
1958
+ if (active === void 0) throw new Error("DeviceSimulationHost has no loaded schematic");
1959
+ const binding = active.inputs.get(targetKey(target.symbol, target.port));
1960
+ if (binding === void 0) throw new Error(`Unknown device input ${target.symbol}.${target.port}`);
1961
+ if (!payloadMatches(binding.topic.type, payload)) throw new TypeError(`${target.symbol}.${target.port} expects a ${binding.topic.type} payload`);
1962
+ const device = binding.device;
1963
+ if (device.binding.deliver === void 0) throw new Error(`${device.binding.type} has no writable topic ${JSON.stringify(target.port)}`);
1964
+ pending.push({
1965
+ device,
1966
+ port: target.port,
1967
+ payload
1968
+ });
1969
+ },
1970
+ onDidPublish: publishes.event,
1971
+ async getTopics() {
1972
+ return runtime?.topics ?? [];
1973
+ },
1974
+ async getSimTime() {
1975
+ return simTimePs;
1976
+ },
1977
+ async getSchematic() {
1978
+ return runtime?.schematic;
1979
+ },
1980
+ async dispose() {
1981
+ if (disposed) return;
1982
+ disposed = true;
1983
+ publishes.dispose();
1984
+ clearRuntime();
1985
+ }
1986
+ };
1987
+ }
1988
+ //#endregion
1989
+ //#region src/host/guest.ts
1990
+ /**
1991
+ * Registers RFC 0018's device simulation services on a sandbox RPC port.
1992
+ *
1993
+ * A worker script obtains the port from `event.ports[0]` and calls this function; nothing else is
1994
+ * needed, because the guest is a plain module the `@mica-js/sandbox/vite` plugin bundles into a
1995
+ * self-contained script. The guest registers `deviceSimulationHostGuestService` and reads schematics
1996
+ * through `deviceSimulationHostFileSystemService`, so schematic bytes never enter the guest's own
1997
+ * message handling and every payload is a typed RPC DTO.
1998
+ */
1999
+ function startDeviceSimulationHostGuest(port, options = {}) {
2000
+ const { devices, resolveDevice, prepare, ports = [] } = options;
2001
+ const rpc = createRpc(port);
2002
+ const logger = rpc.getProxy(loggerService);
2003
+ logger.write({
2004
+ level: "debug",
2005
+ scope: "device-simulation",
2006
+ message: "guest-started",
2007
+ data: [{ extraPortCount: ports.length }]
2008
+ }).catch(() => void 0);
2009
+ const files = rpc.getProxy(deviceSimulationHostFileSystemService);
2010
+ const host = createSchematicDeviceSimulationHost({
2011
+ async read(uri) {
2012
+ const bytes = await files.read(uri);
2013
+ if (!(bytes instanceof Uint8Array)) throw new TypeError(`DeviceSimulationHost file system returned ${typeof bytes} for ${uri}`);
2014
+ return bytes;
2015
+ },
2016
+ ...devices === void 0 ? {} : { devices },
2017
+ resolveDevice: resolveDevice ?? (() => void 0)
2018
+ });
2019
+ let prepared;
2020
+ const ensurePrepared = async () => {
2021
+ if (prepare === void 0) return;
2022
+ prepared ??= prepare();
2023
+ try {
2024
+ await prepared;
2025
+ } catch (error) {
2026
+ prepared = void 0;
2027
+ throw error;
2028
+ }
2029
+ };
2030
+ const service = {
2031
+ async loadSchematic(uri) {
2032
+ logger.write({
2033
+ level: "debug",
2034
+ scope: "device-simulation",
2035
+ message: "load-schematic-start",
2036
+ data: [uri]
2037
+ }).catch(() => void 0);
2038
+ try {
2039
+ if (uri !== void 0) await ensurePrepared();
2040
+ await host.loadSchematic(uri);
2041
+ logger.write({
2042
+ level: "debug",
2043
+ scope: "device-simulation",
2044
+ message: "load-schematic-end",
2045
+ data: [uri]
2046
+ }).catch(() => void 0);
2047
+ } catch (error) {
2048
+ logger.write({
2049
+ level: "error",
2050
+ scope: "device-simulation",
2051
+ message: "load-schematic-failed",
2052
+ data: [uri, String(error)]
2053
+ }).catch(() => void 0);
2054
+ throw error;
2055
+ }
2056
+ },
2057
+ async reset() {
2058
+ await ensurePrepared();
2059
+ return host.reset();
2060
+ },
2061
+ tick: (dt) => host.tick(dt),
2062
+ deliver: (target, payload, simTime) => host.deliver(target, payload, simTime),
2063
+ onDidPublish: (listener) => {
2064
+ const subscription = host.onDidPublish(listener);
2065
+ return () => subscription.dispose();
2066
+ },
2067
+ getTopics: () => host.getTopics(),
2068
+ getSimTime: () => host.getSimTime(),
2069
+ getSchematic: () => host.getSchematic(),
2070
+ dispose: () => host.dispose()
2071
+ };
2072
+ const registration = rpc.register(deviceSimulationHostGuestService, service);
2073
+ const topicPort = ports[0];
2074
+ const topicRpc = topicPort === void 0 ? void 0 : createRpc(topicPort);
2075
+ const topicRegistration = topicRpc?.register(deviceSimulationHostGuestService, service);
2076
+ let disposed = false;
2077
+ return {
2078
+ rpc,
2079
+ ports,
2080
+ async dispose() {
2081
+ if (disposed) return;
2082
+ disposed = true;
2083
+ topicRegistration?.dispose();
2084
+ topicRpc?.dispose();
2085
+ registration.dispose();
2086
+ await host.dispose();
2087
+ rpc.dispose();
2088
+ }
2089
+ };
496
2090
  }
497
2091
  //#endregion
498
- export { SimulatorError, createCircuitHost, createDeviceSimExecutor };
2092
+ export { Circuit, CircuitError, DEFAULT_RAILS, DEVICE_PIN_STRIDE, PIN_MODE, UNIFIED_PIN_CAPACITY, UnifiedIRCompilerError, compileCircuit, createCircuitDeviceSimulationHost, createCircuitFromSchematic, createModuleValidation, createSchematicCircuit, createSchematicDeviceSimulationHost, startDeviceSimulationHostGuest };
499
2093
 
500
2094
  //# sourceMappingURL=index.js.map