@mica-js/simulator 0.4.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/unified-ir/validation.ts","../src/unified-ir/pin-space.ts","../src/unified-ir/compiler/types.ts","../src/unified-ir/compiler/allocator.ts","../src/unified-ir/compiler/device-gen.ts","../src/unified-ir/compiler/mainloop-gen.ts","../src/unified-ir/compiler/solver-gen.ts","../src/unified-ir/compiler/topology.ts","../src/unified-ir/compiler/index.ts","../src/unified-ir/runtime/types.ts","../src/unified-ir/runtime/accessors.ts","../src/unified-ir/runtime/circuit.ts","../src/unified-ir/runtime/factory.ts","../src/host/circuit-host.ts","../src/host/runtime.ts","../src/host/guest.ts"],"sourcesContent":["import type { BytesRef, IRModule, IRResourcePermission, IRValidationOptions } from '@mica-js/ir';\n\n/**\n * Builds the validation grants a module needs to run on the reference engine or\n * the JIT: every instruction the model uses, authorized once, plus a grant for\n * each declared memory.\n *\n * `@mica-js/ir` deliberately keeps its core instruction list internal, so the\n * names are collected from the generated bodies instead of being restated here.\n *\n * @param module - Generated module whose bodies and memories are granted.\n * @param updateResources - Read-only byte regions that opt into the host-only\n * versioned update path (for example MCU firmware patching).\n */\nexport function createModuleValidation(\n module: IRModule,\n updateResources: readonly BytesRef[] = [],\n): IRValidationOptions {\n const names = new Set<string>();\n for (const fn of module.functions) {\n const body = fn.body;\n if (body === undefined) continue;\n // `body.blocks` already contains the entry block.\n for (const block of body.blocks) {\n for (const instruction of block.instructions) names.add(instruction.op);\n if (block.terminator !== undefined) names.add(block.terminator.kind);\n }\n }\n const instructions = Object.freeze([...names]);\n const resources: IRResourcePermission[] = module.memories.map((memory) =>\n Object.freeze({\n ref: memory.ref,\n access: memory.writable ? ('read-write' as const) : ('read' as const),\n }),\n );\n // Read-only byte regions such as firmware stay unreadable to guest stores but\n // can opt into the host-only versioned update path (`patchFirmware`).\n const memories = new Set(module.memories.map((memory) => memory.ref));\n for (const ref of new Set(updateResources)) {\n if (!memories.has(ref)) continue;\n resources.push(Object.freeze({ ref, access: 'update' as const }));\n }\n return Object.freeze({\n supportedInstructions: instructions,\n authorizedInstructions: instructions,\n resources: Object.freeze(resources),\n });\n}\n","/**\n * Shared memory-layout constants of the unified IR compiler and devices.\n *\n * Every device of a circuit shares one global pin address space, so the\n * compiler and every device kernel must agree on the capacity, the per-device\n * stride and the meaning of a `pin_mode` slot. Capacity and stride are limits\n * checked at allocation time; the shared pin memories are sized to the pins a\n * circuit actually declares, so a larger ceiling costs no runtime memory.\n */\n\n/** Global pin addresses available to one circuit (8 devices x 512 pins). */\nexport const UNIFIED_PIN_CAPACITY = 4096;\n\n/** Global pin addresses one device may own; enough for the largest packages. */\nexport const DEVICE_PIN_STRIDE = 512;\n\n/** Values stored in the global `pin_mode` array. */\nexport const PIN_MODE = Object.freeze({\n highZ: 0,\n pushPull: 1,\n openDrain: 2,\n analog: 3,\n} as const);\n\n/** One value of the global `pin_mode` array. */\nexport type PinMode = (typeof PIN_MODE)[keyof typeof PIN_MODE];\n","import type {\n ArrayRef,\n BytesRef,\n FunctionBuilder,\n FunctionRef,\n IRModule,\n IRValidationOptions,\n ScalarType,\n Value,\n} from '@mica-js/ir';\n\n/**\n * Types for the unified IR compiler (U01).\n *\n * The compiler turns several device descriptions plus a pin-to-pin netlist into\n * one `@mica-js/ir` module. Device logic, the electrical solve and the main\n * loop all share one global pin space, one state space and one engine entry, so\n * a tick costs one interpreter/JIT call for the whole circuit.\n *\n * The shared constants (`UNIFIED_PIN_CAPACITY`, `DEVICE_PIN_STRIDE`, `PIN_MODE`)\n * live in `../pin-space` and are reused here. The compiler ships no device\n * models: every description is supplied by the caller.\n */\n\n/** Electrical intent of one device pin. */\nexport type DevicePinDirection = 'input' | 'output' | 'bidirectional' | 'passive';\n\n/** Role a pin plays on its net; v1 supports one driver per net. */\nexport type CompiledPinRole = 'driver' | 'load';\n\n/** One pin declared by a device description. */\nexport interface DevicePinDescription {\n /** Defaults to `'passive'`: the pin only senses the net. */\n readonly direction?: DevicePinDirection;\n /** Overrides the role derived from `direction`. */\n readonly role?: CompiledPinRole;\n /** Purely informational kind, e.g. `'signal'`, `'power'`, `'gnd'`. */\n readonly kind?: string;\n}\n\n/**\n * Declared pins of one device. A `Map` keeps duplicate names impossible and an\n * object keeps authored descriptions terse; both preserve declaration order.\n */\nexport type DevicePinMap =\n ReadonlyMap<string, DevicePinDescription> | Readonly<Record<string, DevicePinDescription>>;\n\n/** One scalar internal state of a device, allocated in the global state space. */\nexport interface DeviceStateDescription {\n readonly type: ScalarType;\n readonly initial: boolean | number;\n}\n\n/** Pin operations a behavior may use; each call inlines into global memory. */\nexport interface DevicePinHandle {\n readonly name: string;\n readonly globalId: number;\n /** `pin.configure`: writes `pin_mode[globalId]`. */\n configure(mode: number): void;\n /** `pin.write_digital`: writes `pin_output[globalId]`. */\n writeDigital(level: Value<'bool'>): void;\n /** `pin.sample_digital`: reads the solved `pin_input[globalId]`. */\n sampleDigital(): Value<'bool'>;\n /** Reads the device's own `pin_output[globalId]`. */\n readDrivenDigital(): Value<'bool'>;\n}\n\n/** Internal state slot a behavior may read and write. */\nexport interface DeviceStateHandle<T extends ScalarType = ScalarType> {\n readonly name: string;\n readonly type: T;\n /** Index inside the generated `device_state_<type>` array. */\n readonly index: number;\n load(): Value<T>;\n store(value: Value<T>): void;\n}\n\n/** One pin as seen by a device kernel factory (no builder attached yet). */\nexport interface DeviceKernelPin {\n readonly name: string;\n readonly globalPinId: number;\n readonly role: CompiledPinRole;\n}\n\n/**\n * Everything a complex device kernel needs to declare its own IR before any\n * phase function body is opened: the module (for `array`/`bytes`/`provider`),\n * the shared pin memories and the allocated pin ids.\n */\nexport interface DeviceKernelContext {\n readonly deviceId: string;\n readonly config: Readonly<Record<string, unknown>> | undefined;\n readonly module: IRModule;\n readonly memory: CompiledCircuitMemory;\n readonly pins: readonly DeviceKernelPin[];\n}\n\n/**\n * Direct phase refs a complex kernel may return instead of behaviour hooks.\n * The compiler then uses these functions as the device's loop entries, with\n * no wrapper phase around them.\n */\nexport interface DeviceKernelRuntime {\n readonly initialize?: FunctionRef<readonly [], readonly []>;\n readonly tick?: FunctionRef<readonly [], readonly []>;\n readonly update?: FunctionRef<readonly [], readonly []>;\n}\n\n/**\n * Builds the phase hooks of a complex device after resource allocation but\n * before phase functions are generated. Declaring arrays, byte memories and\n * providers is only legal here (never inside a function body).\n *\n * Returning {@link DeviceKernelRuntime} lets the kernel own its phase\n * functions directly; returning {@link DeviceBehaviors} asks the compiler to\n * generate `<id>_initialize` / `<id>_tick` / `<id>_update` wrappers.\n */\nexport type DeviceKernelFactory = (\n context: DeviceKernelContext,\n) => DeviceBehaviors | DeviceKernelRuntime;\n\n/** Build surface handed to one device behavior. */\nexport interface DeviceBehaviorApi {\n readonly deviceId: string;\n readonly builder: FunctionBuilder<readonly []>;\n /**\n * Module the phase is generated into. Complex devices use it to declare\n * their own typed arrays (`module.array`, `module.bytes`) and providers;\n * simple devices never need to touch it.\n */\n readonly module: IRModule;\n /** Shared `pin_mode` / `pin_output` / `pin_input` memories. */\n readonly memory: CompiledCircuitMemory;\n /** Instance configuration from {@link DeviceConfig.config}. */\n readonly config: Readonly<Record<string, unknown>> | undefined;\n /** Every declared pin of the device, in declaration order. */\n readonly pins: readonly DevicePinHandle[];\n /** Pins whose role is `driver`. */\n readonly outputs: readonly DevicePinHandle[];\n pin(name: string): DevicePinHandle;\n state<T extends ScalarType = ScalarType>(name: string): DeviceStateHandle<T>;\n}\n\n/**\n * Structural surface every device accessor exposes.\n *\n * The compiler keeps this declaration independent from the runtime's\n * `DeviceAccessor` so a device kernel can ship its own typed accessor without\n * making the compiler depend on the runtime module.\n */\nexport interface DeviceAccessorSurface {\n readonly deviceId: string;\n readonly type: string;\n readonly pinNames: readonly string[];\n readonly stateNames: readonly string[];\n readPin(pinName: string): boolean;\n writePin(pinName: string, value: boolean): void;\n getState(name: string): unknown;\n setState(name: string, value: unknown): void;\n}\n\n/** Host services handed to a device accessor factory at circuit creation. */\nexport interface DeviceAccessorFactoryContext {\n readonly deviceId: string;\n /** Live engine storage (`IRStorage` in practice). */\n readonly storage: unknown;\n /** Throws once the owning circuit has been disposed. */\n readonly assertActive: () => void;\n /** Advances the owning circuit by one tick. */\n readonly step: () => void;\n /** Advances the owning circuit by `count` ticks. */\n readonly runBatch: (count: number) => void;\n}\n\n/**\n * Builds the typed accessor of a device after its module is compiled.\n *\n * A description that supplies `accessor` replaces the generic accessor the\n * runtime would otherwise synthesize from `type`. The factory runs once per\n * circuit and closes over the layout its IR factory allocated.\n */\nexport type DeviceAccessorFactory = (\n context: DeviceAccessorFactoryContext,\n) => DeviceAccessorSurface;\n\n/**\n * Per-device behavior hooks. The compiler emits one IR function per hook:\n * `initialize` -> `<id>_initialize`, `tick` -> `<id>_tick`,\n * `update` -> `<id>_update`. Missing hooks simply produce no function.\n */\nexport interface DeviceBehaviors {\n readonly initialize?: (api: DeviceBehaviorApi) => void;\n readonly tick?: (api: DeviceBehaviorApi) => void;\n readonly update?: (api: DeviceBehaviorApi) => void;\n}\n\n/** IR-level device description consumed by the compiler. */\nexport interface DeviceDescription {\n readonly name?: string;\n readonly pins: DevicePinMap;\n readonly states?: Readonly<Record<string, DeviceStateDescription>>;\n readonly behaviors?: DeviceBehaviors;\n /**\n * Complex-kernel hook. Runs once per module before phase generation so the\n * kernel may declare typed arrays, byte memories and providers, then return\n * the behaviour hooks the compiler should call inside each phase.\n */\n readonly kernel?: DeviceKernelFactory;\n /**\n * Optional typed accessor factory. Kernels with a richer surface than the\n * generic state/pin accessor (a register file, a memory map) use it.\n */\n readonly accessor?: DeviceAccessorFactory;\n /**\n * Read-only byte regions the kernel wants host updates for. The compiler\n * grants `update` access on top of the normal `read` grant so kernels can\n * expose firmware patching without allowing guest stores.\n */\n readonly updateResources?: readonly BytesRef[];\n}\n\n/** One device instance of the circuit. */\nexport interface DeviceConfig {\n /** Circuit-unique identity; prefix of every generated function name. */\n readonly id: string;\n /** Device type, e.g. `'push-pull-driver'`; free-form label of the device model. */\n readonly type: string;\n readonly description: DeviceDescription;\n /** Instance configuration; reserved for device kernels that take parameters. */\n readonly config?: Readonly<Record<string, unknown>>;\n}\n\n/** One pin-to-pin (or pin-to-rail) connection. */\nexport interface Connection {\n /** `'mcu1.PA0'` or a rail name such as `'GND'`. */\n readonly from: string;\n readonly to: string;\n}\n\n/** Options for the compiler. */\nexport interface CircuitCompilationOptions {\n /** Named fixed-level rails; merged over `GND`/`VCC`/`VDD`. */\n readonly rails?: Readonly<Record<string, boolean>>;\n /** Runs `validateIR` over the generated module. Defaults to `true`. */\n readonly validate?: boolean;\n /** Overrides for the generated entry-point names. */\n readonly entryPointNames?: {\n readonly tick?: string;\n readonly initialize?: string;\n readonly batch?: string;\n };\n}\n\n/** Compiler input: devices plus the connections between their pins. */\nexport interface CircuitCompilationInput {\n readonly devices: readonly DeviceConfig[];\n readonly connections: readonly Connection[];\n}\n\n/** One resolved pin in the global pin space. */\nexport interface ResolvedDevicePin {\n readonly name: string;\n readonly deviceId: string;\n readonly globalPinId: number;\n readonly direction: DevicePinDirection;\n readonly role: CompiledPinRole;\n /** Whether the device reads the solved value of this pin. */\n readonly senses: boolean;\n}\n\n/** Pins of one device mapped into the global pin space. */\nexport interface DevicePinAllocation {\n readonly deviceId: string;\n /** First global pin id of the device. */\n readonly offset: number;\n readonly pins: ReadonlyMap<string, number>;\n readonly resolved: ReadonlyMap<string, ResolvedDevicePin>;\n}\n\n/** Result of the global pin allocation. */\nexport interface GlobalPinMap {\n /** `'mcu1.PA0'` -> global pin id. */\n readonly pins: ReadonlyMap<string, number>;\n readonly devices: ReadonlyMap<string, DevicePinAllocation>;\n readonly totalPins: number;\n readonly capacity: number;\n}\n\n/** One device state slot inside the global state space. */\nexport interface DeviceStateSlot {\n readonly name: string;\n readonly deviceId: string;\n readonly type: ScalarType;\n /** Generated array that holds the slot. */\n readonly array: ArrayRef;\n /** Index inside {@link array}. */\n readonly index: number;\n /** Ordinal in the whole state space, across scalar types. */\n readonly slot: number;\n}\n\n/** Result of the global state allocation. */\nexport interface GlobalStateMap {\n readonly devices: ReadonlyMap<string, ReadonlyMap<string, DeviceStateSlot>>;\n /** One generated array per scalar type actually used. */\n readonly arrays: ReadonlyMap<ScalarType, ArrayRef>;\n /** Slot count per scalar type. */\n readonly totals: ReadonlyMap<ScalarType, number>;\n readonly totalStates: number;\n}\n\n/** Pin memories every device and every net solver shares. */\nexport interface CompiledCircuitMemory {\n readonly mode: ArrayRef<'u8'>;\n readonly output: ArrayRef<'bool'>;\n readonly input: ArrayRef<'bool'>;\n}\n\n/** One pin resolved onto a net. */\nexport interface CompiledPinConnection {\n /** `'mcu1.PA0'`. */\n readonly endpoint: string;\n readonly deviceId: string;\n readonly pinName: string;\n readonly globalPinId: number;\n readonly role: CompiledPinRole;\n readonly senses: boolean;\n}\n\n/** One fixed-level rail on a net, e.g. `GND` (low) or `VCC` (high). */\nexport interface CompiledRail {\n readonly name: string;\n readonly level: boolean;\n}\n\n/** Where a net's level comes from. */\nexport type CompiledNetSource = 'driver' | 'rail' | 'floating';\n\n/** One electrical net: a connected component of pins and rails. */\nexport interface CompiledNet {\n readonly netId: number;\n readonly pins: readonly CompiledPinConnection[];\n readonly rails: readonly CompiledRail[];\n readonly drivers: readonly CompiledPinConnection[];\n /** Pins whose role is `load`. */\n readonly loads: readonly CompiledPinConnection[];\n /** Every pin that reads the solved level, including bidirectional drivers. */\n readonly sinks: readonly CompiledPinConnection[];\n readonly source: CompiledNetSource;\n /** Constant level of a driver-less net; unused when `source === 'driver'`. */\n readonly level: boolean;\n}\n\n/** Diagnostic codes produced by the compiler's electrical analysis. */\nexport type CompilationDiagnosticCode = 'power-short' | 'rail-conflict' | 'floating-net';\n\nexport type CompilationDiagnosticSeverity = 'error' | 'warning';\n\n/** One electrical-analysis finding; errors abort `compileCircuit`. */\nexport interface CompilationDiagnostic {\n readonly code: CompilationDiagnosticCode;\n readonly severity: CompilationDiagnosticSeverity;\n readonly message: string;\n readonly netId: number | undefined;\n readonly endpoints: readonly string[];\n}\n\n/** Result of the network topology analysis. */\nexport interface CompiledNetlist {\n readonly nets: readonly CompiledNet[];\n readonly diagnostics: readonly CompilationDiagnostic[];\n}\n\n/** Metadata of one compiled device. */\nexport interface DeviceMetadata {\n readonly deviceId: string;\n readonly type: string;\n /** First global pin id of the device. */\n readonly pinOffset: number;\n /** First slot ordinal of the device in the global state space. */\n readonly stateOffset: number;\n readonly pins: ReadonlyMap<string, number>;\n readonly states: ReadonlyMap<string, DeviceStateSlot>;\n /** Every IR function generated for this device. */\n readonly functions: readonly string[];\n readonly initialize: string | undefined;\n readonly tick: string | undefined;\n readonly update: string | undefined;\n /** Typed accessor factory supplied by the device description, if any. */\n readonly accessor: DeviceAccessorFactory | undefined;\n /** Kernel factory that generated the device's extra IR resources. */\n readonly kernel: DeviceKernelFactory | undefined;\n}\n\n/** Generated entry points, both by name and as executable refs. */\nexport interface CompiledEntryPoints {\n readonly tick: string;\n readonly initialize: string;\n readonly batch: string;\n readonly refs: {\n readonly tick: FunctionRef<readonly [], readonly []>;\n readonly initialize: FunctionRef<readonly [], readonly []>;\n readonly batch: FunctionRef<readonly ['u32'], readonly []>;\n };\n}\n\n/** The compiled circuit: one module for every device, net and the main loop. */\nexport interface CompiledCircuit {\n readonly module: IRModule;\n readonly entryPoints: CompiledEntryPoints;\n /** `'mcu1.PA0'` -> global pin id. */\n readonly pinMap: ReadonlyMap<string, number>;\n readonly deviceMap: ReadonlyMap<string, DeviceMetadata>;\n readonly netlist: CompiledNetlist;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n readonly memory: CompiledCircuitMemory;\n /** Validation grants covering every instruction and memory of the module. */\n readonly validation: IRValidationOptions;\n /** Device ids in dependency order (drivers before the devices they feed). */\n readonly executionOrder: readonly string[];\n /** Every generated function name, in definition order. */\n readonly functions: readonly string[];\n}\n\n/** Error codes raised by {@link UnifiedIRCompilerError}. */\nexport type UnifiedIRCompilerErrorCode =\n | 'invalid-input'\n | 'duplicate-device'\n | 'unknown-device'\n | 'pin-not-found'\n | 'state-not-found'\n | 'invalid-connection'\n | 'capacity-exceeded'\n | 'unsupported-device'\n | 'power-short'\n | 'rail-conflict'\n | 'invalid-ir';\n\nexport interface UnifiedIRCompilerErrorOptions {\n readonly deviceId?: string;\n readonly pinName?: string;\n readonly netId?: number;\n readonly diagnostics?: readonly CompilationDiagnostic[];\n readonly cause?: unknown;\n}\n\n/** Error raised while compiling a circuit. */\nexport class UnifiedIRCompilerError extends Error {\n override readonly name = 'UnifiedIRCompilerError';\n readonly code: UnifiedIRCompilerErrorCode;\n readonly deviceId: string | undefined;\n readonly pinName: string | undefined;\n readonly netId: number | undefined;\n readonly diagnostics: readonly CompilationDiagnostic[];\n\n constructor(\n code: UnifiedIRCompilerErrorCode,\n message: string,\n options: UnifiedIRCompilerErrorOptions = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.code = code;\n this.deviceId = options.deviceId;\n this.pinName = options.pinName;\n this.netId = options.netId;\n this.diagnostics = options.diagnostics ?? [];\n }\n}\n","import { INTEGER_TYPES, SCALAR_TYPES } from '@mica-js/ir';\nimport type { ArrayRef, IRModule, ScalarType } from '@mica-js/ir';\nimport { DEVICE_PIN_STRIDE, PIN_MODE, UNIFIED_PIN_CAPACITY } from '../pin-space';\nimport {\n UnifiedIRCompilerError,\n type CompiledCircuitMemory,\n type DeviceConfig,\n type DevicePinAllocation,\n type DevicePinDescription,\n type DevicePinDirection,\n type DeviceStateDescription,\n type DeviceStateSlot,\n type GlobalPinMap,\n type GlobalStateMap,\n type ResolvedDevicePin,\n} from './types';\n\n/** Generated device ids prefix IR function names, so they must be identifiers. */\nconst DEVICE_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Everything the compiler allocates before a single instruction is generated. */\nexport interface ResourceAllocation {\n readonly memory: CompiledCircuitMemory;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n}\n\n/**\n * Allocates the circuit-wide pin and state address spaces.\n *\n * ```\n * ids: 0 = drive1.PA0 1 = drive1.PA1 2 = sink1.anode 3 = sink1.cathode\n * |<-- drive1 -->| |<----------- sink1 ----------->|\n *\n * pin_mode[n] u8 pin_output[n] bool pin_input[n] bool (n = totalPins)\n * device_state_bool[n] / device_state_u32[m] / ... (one array per used type)\n * ```\n *\n * Pins are packed in declaration order across devices — the addresses the\n * device IR and every net solver embed as constants. States are packed per\n * scalar type into one shared array, so a device's slot stays typed while all\n * devices share one storage region.\n */\nexport class GlobalResourceAllocator {\n private readonly module: IRModule;\n\n constructor(module: IRModule) {\n this.module = module;\n }\n\n /** Allocates the shared pin memories, the pin space and the state space. */\n allocate(devices: readonly DeviceConfig[]): ResourceAllocation {\n const pins = this.allocatePins(devices);\n return Object.freeze({\n memory: createPinMemory(this.module, Math.max(1, pins.totalPins)),\n pins,\n states: this.allocateStates(devices),\n });\n }\n\n /**\n * Packs every device pin into one contiguous global address space.\n *\n * @throws {UnifiedIRCompilerError} on invalid or duplicate device ids, more\n * than {@link DEVICE_PIN_STRIDE} pins for one device, or more than\n * {@link UNIFIED_PIN_CAPACITY} pins for the circuit.\n */\n allocatePins(devices: readonly DeviceConfig[]): GlobalPinMap {\n assertDeviceList(devices);\n\n let totalPins = 0;\n const pins = new Map<string, number>();\n const allocations = new Map<string, DevicePinAllocation>();\n\n for (const device of devices) {\n const entries = pinEntries(device);\n if (entries.length > DEVICE_PIN_STRIDE) {\n throw new UnifiedIRCompilerError(\n 'capacity-exceeded',\n `Device \"${device.id}\" declares ${entries.length} pins; one device may own at most ${DEVICE_PIN_STRIDE}`,\n { deviceId: device.id },\n );\n }\n if (totalPins + entries.length > UNIFIED_PIN_CAPACITY) {\n throw new UnifiedIRCompilerError(\n 'capacity-exceeded',\n `Device \"${device.id}\" does not fit: the circuit already uses ${totalPins} of ${UNIFIED_PIN_CAPACITY} global pins`,\n { deviceId: device.id },\n );\n }\n\n const offset = totalPins;\n const devicePins = new Map<string, number>();\n const resolved = new Map<string, ResolvedDevicePin>();\n\n for (const [name, descriptor] of entries) {\n const globalPinId = totalPins;\n totalPins += 1;\n const direction = resolvePinDirection(descriptor, device.id, name);\n const { role, senses } = resolvePinRole(direction, descriptor?.role, device.id, name);\n devicePins.set(name, globalPinId);\n resolved.set(\n name,\n Object.freeze({\n name,\n deviceId: device.id,\n globalPinId,\n direction,\n role,\n senses,\n }),\n );\n pins.set(`${device.id}.${name}`, globalPinId);\n }\n\n allocations.set(\n device.id,\n Object.freeze({ deviceId: device.id, offset, pins: devicePins, resolved }),\n );\n }\n\n return Object.freeze({\n pins,\n devices: allocations,\n totalPins,\n capacity: UNIFIED_PIN_CAPACITY,\n });\n }\n\n /**\n * Allocates one typed slot per declared device state and creates the backing\n * `device_state_<type>` arrays.\n *\n * @throws {UnifiedIRCompilerError} when a state declaration is malformed.\n */\n allocateStates(devices: readonly DeviceConfig[]): GlobalStateMap {\n assertDeviceList(devices);\n\n interface StatePlan {\n readonly deviceId: string;\n readonly name: string;\n readonly type: ScalarType;\n readonly initial: boolean | number;\n readonly slot: number;\n }\n\n const plans: StatePlan[] = [];\n const slotsByDevice = new Map<string, Map<string, DeviceStateSlot>>();\n const plansByType = new Map<ScalarType, StatePlan[]>();\n\n for (const device of devices) {\n // Every device owns a block in the state table, even when it is empty.\n const slots = new Map<string, DeviceStateSlot>();\n slotsByDevice.set(device.id, slots);\n for (const [name, declaration] of stateEntries(device)) {\n const plan: StatePlan = {\n deviceId: device.id,\n name,\n type: declaration.type,\n initial: declaration.initial,\n slot: plans.length,\n };\n plans.push(plan);\n const typePlans = plansByType.get(plan.type);\n if (typePlans === undefined) {\n plansByType.set(plan.type, [plan]);\n } else {\n typePlans.push(plan);\n }\n }\n }\n\n const arrays = new Map<ScalarType, ArrayRef>();\n const totals = new Map<ScalarType, number>();\n for (const [type, typePlans] of plansByType) {\n const array = this.module.array(\n `device_state_${type}`,\n type,\n typePlans.map((plan) => plan.initial),\n );\n arrays.set(type, array);\n totals.set(type, typePlans.length);\n typePlans.forEach((plan, index) => {\n const slot: DeviceStateSlot = Object.freeze({\n name: plan.name,\n deviceId: plan.deviceId,\n type,\n array,\n index,\n slot: plan.slot,\n });\n slotsByDevice.get(plan.deviceId)?.set(plan.name, slot);\n });\n }\n\n const devicesMap = new Map<string, ReadonlyMap<string, DeviceStateSlot>>();\n for (const [deviceId, slots] of slotsByDevice) devicesMap.set(deviceId, slots);\n\n return Object.freeze({\n devices: devicesMap,\n arrays,\n totals,\n totalStates: plans.length,\n });\n }\n}\n\n/**\n * Declares the three pin memories shared by every device and net solver.\n *\n * The memories are sized to the pins the circuit declares, never to\n * {@link UNIFIED_PIN_CAPACITY}: the capacity only bounds how many pins a\n * circuit may have, so a large ceiling costs neither memory nor setup time.\n */\nexport function createPinMemory(\n module: IRModule,\n capacity: number = UNIFIED_PIN_CAPACITY,\n): CompiledCircuitMemory {\n return Object.freeze({\n mode: module.array(\n 'pin_mode',\n 'u8',\n Array.from({ length: capacity }, () => PIN_MODE.highZ),\n ),\n output: module.array(\n 'pin_output',\n 'bool',\n Array.from({ length: capacity }, () => false),\n ),\n input: module.array(\n 'pin_input',\n 'bool',\n Array.from({ length: capacity }, () => false),\n ),\n });\n}\n\n/** First state slot ordinal of every device; used for `DeviceMetadata.stateOffset`. */\nexport function stateOffsetOf(states: GlobalStateMap, deviceId: string): number {\n let offset = 0;\n for (const [id, slots] of states.devices) {\n if (id === deviceId) return offset;\n offset += slots.size;\n }\n return offset;\n}\n\nfunction assertDeviceList(devices: readonly DeviceConfig[]): void {\n if (!Array.isArray(devices) || devices.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.devices must be a non-empty array',\n );\n }\n const ids = new Set<string>();\n for (const device of devices as readonly unknown[]) {\n if (device === null || typeof device !== 'object' || Array.isArray(device)) {\n throw new UnifiedIRCompilerError('invalid-input', 'Every device must be an object');\n }\n const { id, type, description } = device as Partial<DeviceConfig>;\n if (typeof id !== 'string' || !DEVICE_ID_PATTERN.test(id)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device id ${JSON.stringify(id)} must be an identifier ([A-Za-z_][A-Za-z0-9_]*) because it prefixes generated IR function names`,\n );\n }\n if (ids.has(id)) {\n throw new UnifiedIRCompilerError(\n 'duplicate-device',\n `Duplicate device id \"${id}\"; every device id must be unique`,\n { deviceId: id },\n );\n }\n ids.add(id);\n if (typeof type !== 'string' || type.length === 0) {\n throw new UnifiedIRCompilerError('invalid-input', `Device \"${id}\" needs a non-empty type`, {\n deviceId: id,\n });\n }\n if (description === null || typeof description !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${id}\" needs a description object with a pins map`,\n { deviceId: id },\n );\n }\n }\n}\n\nfunction pinEntries(\n device: DeviceConfig,\n): readonly (readonly [string, DevicePinDescription | undefined])[] {\n const raw: unknown = device.description.pins;\n let entries: (readonly [string, DevicePinDescription | undefined])[];\n if (raw instanceof Map) {\n entries = [...(raw as ReadonlyMap<string, DevicePinDescription>).entries()];\n } else if (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) {\n entries = Object.entries(raw as Record<string, DevicePinDescription>) as (readonly [\n string,\n DevicePinDescription | undefined,\n ])[];\n } else {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" needs description.pins as a Map or a plain object`,\n { deviceId: device.id },\n );\n }\n for (const [name, descriptor] of entries) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" declares a pin with an empty name`,\n { deviceId: device.id },\n );\n }\n if (name.includes('.')) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" pin \"${name}\" may not contain \".\": connection endpoints use \"device.pin\"`,\n { deviceId: device.id, pinName: name },\n );\n }\n if (descriptor !== undefined && (descriptor === null || typeof descriptor !== 'object')) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" pin \"${name}\" description must be an object`,\n { deviceId: device.id, pinName: name },\n );\n }\n }\n return entries;\n}\n\nconst PIN_DIRECTIONS: ReadonlySet<string> = new Set([\n 'input',\n 'output',\n 'bidirectional',\n 'passive',\n]);\n\nfunction resolvePinDirection(\n descriptor: DevicePinDescription | undefined,\n deviceId: string,\n pinName: string,\n): DevicePinDirection {\n const direction = descriptor?.direction ?? 'passive';\n if (!PIN_DIRECTIONS.has(direction)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" pin \"${pinName}\" has direction ${JSON.stringify(direction)}; expected input, output, bidirectional or passive`,\n { deviceId, pinName },\n );\n }\n return direction;\n}\n\n/**\n * Derives the electrical role and the read behavior of a pin.\n *\n * `output` drives only, `input`/`passive` sense only, `bidirectional` drives and\n * senses. An explicit `role` overrides the derived drive role while\n * `bidirectional` keeps its sense side.\n */\nfunction resolvePinRole(\n direction: DevicePinDirection,\n explicit: DevicePinDescription['role'],\n deviceId: string,\n pinName: string,\n): { readonly role: 'driver' | 'load'; readonly senses: boolean } {\n if (explicit !== undefined && explicit !== 'driver' && explicit !== 'load') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" pin \"${pinName}\" has role ${JSON.stringify(explicit)}; expected driver or load`,\n { deviceId, pinName },\n );\n }\n if (explicit === 'driver') return { role: 'driver', senses: direction === 'bidirectional' };\n if (explicit === 'load') return { role: 'load', senses: true };\n if (direction === 'output') return { role: 'driver', senses: false };\n if (direction === 'bidirectional') return { role: 'driver', senses: true };\n return { role: 'load', senses: true };\n}\n\nfunction stateEntries(\n device: DeviceConfig,\n): readonly (readonly [string, DeviceStateDescription])[] {\n const raw: unknown = device.description.states;\n if (raw === undefined) return [];\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" needs description.states as a plain object`,\n { deviceId: device.id },\n );\n }\n return Object.entries(raw as Record<string, DeviceStateDescription>).map(\n ([name, declaration]) => {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" declares a state with an empty name`,\n { deviceId: device.id },\n );\n }\n if (declaration === null || typeof declaration !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" state \"${name}\" must be an object with type and initial`,\n { deviceId: device.id },\n );\n }\n const type: unknown = declaration.type;\n if (typeof type !== 'string' || !(SCALAR_TYPES as readonly string[]).includes(type)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" state \"${name}\" has type ${JSON.stringify(type)}; expected one of ${SCALAR_TYPES.join(', ')}`,\n { deviceId: device.id },\n );\n }\n assertStateInitial(device.id, name, type as ScalarType, declaration.initial);\n return [name, declaration] as const;\n },\n );\n}\n\nfunction assertStateInitial(\n deviceId: string,\n name: string,\n type: ScalarType,\n initial: unknown,\n): void {\n if (type === 'bool') {\n if (typeof initial !== 'boolean') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (bool) needs a boolean initial value`,\n { deviceId },\n );\n }\n return;\n }\n if (typeof initial !== 'number' || !Number.isFinite(initial)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (${type}) needs a finite numeric initial value`,\n { deviceId },\n );\n }\n if ((INTEGER_TYPES as readonly string[]).includes(type) && !Number.isInteger(initial)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (${type}) needs an integer initial value`,\n { deviceId },\n );\n }\n}\n","import type {\n ArrayRef,\n FunctionBuilder,\n FunctionRef,\n IRModule,\n ScalarType,\n Value,\n} from '@mica-js/ir';\nimport { PIN_MODE } from '../pin-space';\nimport { stateOffsetOf } from './allocator';\nimport {\n UnifiedIRCompilerError,\n type CompiledCircuitMemory,\n type DeviceBehaviorApi,\n type DeviceBehaviors,\n type DeviceConfig,\n type DeviceKernelRuntime,\n type DeviceMetadata,\n type DevicePinAllocation,\n type DevicePinHandle,\n type DeviceStateHandle,\n type DeviceStateSlot,\n type GlobalPinMap,\n type GlobalStateMap,\n} from './types';\n\n/** Refs the main loop calls for one device; `undefined` means \"no such phase\". */\nexport interface DeviceLoopEntry {\n readonly deviceId: string;\n readonly initialize: FunctionRef<readonly [], readonly []> | undefined;\n readonly tick: FunctionRef<readonly [], readonly []> | undefined;\n readonly update: FunctionRef<readonly [], readonly []> | undefined;\n}\n\n/** One generated device: public metadata plus the refs the main loop needs. */\nexport interface GeneratedDevice {\n readonly metadata: DeviceMetadata;\n readonly entry: DeviceLoopEntry;\n}\n\ninterface GeneratedPhase {\n readonly name: string;\n readonly ref: FunctionRef<readonly [], readonly []>;\n}\n\n/** Everything the device generator reads from the prior compilation stages. */\nexport interface DeviceGenerationContext {\n readonly module: IRModule;\n readonly memory: CompiledCircuitMemory;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n}\n\n/**\n * Generates one IR function per device phase into the unified module.\n *\n * Domain operations are inlined while the behavior runs: `pin.configure`,\n * `pin.writeDigital` and `pin.sampleDigital` become `array.store`/`array.load`\n * on the shared `pin_mode` / `pin_output` / `pin_input` memories, so no device\n * keeps its own module, protocol or host hop. A device without an explicit\n * `initialize` still gets one that configures its output pins as push-pull.\n *\n * The compiler ships no device models: every description must declare its own\n * pins, states and behaviors (or a `kernel`) before it reaches this generator.\n */\nexport class DeviceIRGenerator {\n private readonly context: DeviceGenerationContext;\n\n constructor(context: DeviceGenerationContext) {\n this.context = context;\n }\n\n /**\n * @throws {UnifiedIRCompilerError} when the device has no kernel/behaviors or\n * a behavior reaches for a pin or state the description does not declare.\n */\n generate(device: DeviceConfig): GeneratedDevice {\n const allocation = this.context.pins.devices.get(device.id);\n if (allocation === undefined) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" has no pin allocation; allocate resources before generating IR`,\n { deviceId: device.id },\n );\n }\n const kernelResult = device.description.kernel?.({\n deviceId: device.id,\n config: device.config,\n module: this.context.module,\n memory: this.context.memory,\n pins: [...allocation.resolved.values()].map((pin) =>\n Object.freeze({\n name: pin.name,\n globalPinId: pin.globalPinId,\n role: pin.role,\n }),\n ),\n });\n const kernelRuntime =\n kernelResult !== undefined && isKernelRuntime(kernelResult) ? kernelResult : undefined;\n const behaviors =\n kernelRuntime === undefined\n ? ((kernelResult as DeviceBehaviors | undefined) ?? device.description.behaviors)\n : undefined;\n\n let initialize: GeneratedPhase | undefined;\n let tick: GeneratedPhase | undefined;\n let update: GeneratedPhase | undefined;\n if (kernelRuntime !== undefined) {\n initialize = phaseFromRef(this.context.module, device.id, kernelRuntime.initialize);\n tick = phaseFromRef(this.context.module, device.id, kernelRuntime.tick);\n update = phaseFromRef(this.context.module, device.id, kernelRuntime.update);\n } else {\n if (behaviors === undefined || !hasAnyBehavior(behaviors)) {\n throw new UnifiedIRCompilerError(\n 'unsupported-device',\n `Device \"${device.id}\" of type \"${device.type}\" declares no behaviors. Provide description.behaviors or description.kernel`,\n { deviceId: device.id },\n );\n }\n initialize =\n this.generatePhase(device, allocation, 'initialize', behaviors.initialize) ??\n this.generateDefaultInitialize(device, allocation);\n tick = this.generatePhase(device, allocation, 'tick', behaviors.tick);\n update = this.generatePhase(device, allocation, 'update', behaviors.update);\n }\n\n const functions: string[] = [];\n for (const phase of [initialize, tick, update]) {\n if (phase !== undefined) functions.push(phase.name);\n }\n\n const metadata: DeviceMetadata = Object.freeze({\n deviceId: device.id,\n type: device.type,\n pinOffset: allocation.offset,\n stateOffset: stateOffsetOf(this.context.states, device.id),\n pins: allocation.pins,\n states: this.context.states.devices.get(device.id) ?? new Map(),\n functions: Object.freeze(functions),\n initialize: initialize?.name,\n tick: tick?.name,\n update: update?.name,\n accessor: device.description.accessor,\n kernel: device.description.kernel,\n });\n\n return Object.freeze({\n metadata,\n entry: Object.freeze({\n deviceId: device.id,\n initialize: initialize?.ref,\n tick: tick?.ref,\n update: update?.ref,\n }),\n });\n }\n\n private generatePhase(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n phase: 'initialize' | 'tick' | 'update',\n behavior: ((api: DeviceBehaviorApi) => void) | undefined,\n ): GeneratedPhase | undefined {\n if (behavior === undefined) return undefined;\n const name = `${device.id}_${phase}`;\n const ref = this.context.module.func(name, { params: [], results: [] });\n ref.body((b) => {\n behavior(this.createApi(device, allocation, b));\n b.return([]);\n });\n return { name, ref };\n }\n\n private generateDefaultInitialize(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n ): GeneratedPhase | undefined {\n const outputs = [...allocation.resolved.values()].filter((pin) => pin.role === 'driver');\n if (outputs.length === 0) return undefined;\n const name = `${device.id}_initialize`;\n const ref = this.context.module.func(name, { params: [], results: [] });\n ref.body((b) => {\n for (const pin of outputs) {\n b.array.store(\n this.context.memory.mode,\n b.const('u32', pin.globalPinId),\n b.const('u8', PIN_MODE.pushPull),\n );\n }\n b.return([]);\n });\n return { name, ref };\n }\n\n private createApi(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n builder: FunctionBuilder<readonly []>,\n ): DeviceBehaviorApi {\n const handles = new Map<string, DevicePinHandle>();\n const pins: DevicePinHandle[] = [];\n const outputs: DevicePinHandle[] = [];\n for (const pin of allocation.resolved.values()) {\n const handle = this.createPinHandle(pin.globalPinId, pin.name, builder);\n handles.set(pin.name, handle);\n pins.push(handle);\n if (pin.role === 'driver') outputs.push(handle);\n }\n const slots = this.context.states.devices.get(device.id);\n return Object.freeze({\n deviceId: device.id,\n builder,\n module: this.context.module,\n memory: this.context.memory,\n config: device.config,\n pins: Object.freeze(pins),\n outputs: Object.freeze(outputs),\n pin(name: string): DevicePinHandle {\n const handle = handles.get(name);\n if (handle === undefined) {\n const available = [...handles.keys()].map((entry) => `${device.id}.${entry}`);\n throw new UnifiedIRCompilerError(\n 'pin-not-found',\n `Pin '${device.id}.${name}' not found. Available: [${available.join(', ')}]`,\n { deviceId: device.id, pinName: name },\n );\n }\n return handle;\n },\n state<T extends ScalarType = ScalarType>(name: string): DeviceStateHandle<T> {\n const slot = slots?.get(name);\n if (slot === undefined) {\n throw new UnifiedIRCompilerError(\n 'state-not-found',\n `Device \"${device.id}\" has no state \"${name}\". Available: [${[...(slots?.keys() ?? [])].join(', ')}]`,\n { deviceId: device.id },\n );\n }\n return createStateHandle<T>(device.id, slot, builder);\n },\n });\n }\n\n private createPinHandle(\n globalId: number,\n name: string,\n builder: FunctionBuilder<readonly []>,\n ): DevicePinHandle {\n const memory = this.context.memory;\n // Resolved lazily so a behavior that only samples a pin does not also emit\n // an unused constant for every other pin of the device.\n const index = (): Value<'u32'> => builder.const('u32', globalId);\n return Object.freeze({\n name,\n globalId,\n configure(mode: number): void {\n if (!Number.isInteger(mode) || mode < 0 || mode > 0xff) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Pin \"${name}\" configure(${String(mode)}) needs a u8 pin mode`,\n );\n }\n builder.array.store(memory.mode, index(), builder.const('u8', mode));\n },\n writeDigital(level: Value<'bool'>): void {\n builder.array.store(memory.output, index(), level);\n },\n sampleDigital(): Value<'bool'> {\n return builder.array.load(memory.input, index());\n },\n readDrivenDigital(): Value<'bool'> {\n return builder.array.load(memory.output, index());\n },\n });\n }\n}\n\nfunction createStateHandle<T extends ScalarType>(\n deviceId: string,\n slot: DeviceStateSlot,\n builder: FunctionBuilder<readonly []>,\n): DeviceStateHandle<T> {\n // The array was declared with `slot.type`, so a matching `T` is exactly the\n // array's element type; the cast only recovers that from the untied slot.\n const array = slot.array as unknown as ArrayRef<T>;\n const index = builder.const('u32', slot.index);\n return Object.freeze({\n name: slot.name,\n type: slot.type as T,\n index: slot.index,\n load(): Value<T> {\n return builder.array.load(array, index);\n },\n store(value: Value<T>): void {\n builder.array.store(array, index, value);\n },\n });\n}\n\nfunction hasAnyBehavior(behaviors: DeviceBehaviors): boolean {\n return (\n behaviors.initialize !== undefined ||\n behaviors.tick !== undefined ||\n behaviors.update !== undefined\n );\n}\n\n/** Bulk kernel results carry phase refs; behaviour hooks are plain functions. */\nfunction isKernelRuntime(\n value: DeviceBehaviors | DeviceKernelRuntime,\n): value is DeviceKernelRuntime {\n if (value === null || typeof value !== 'object') return false;\n // A kernel may own any subset of the phases (a passive sink only needs\n // `update`), so the first phase ref that is an object — not a behaviour\n // callback — decides.\n const phases: readonly (keyof DeviceKernelRuntime)[] = ['initialize', 'tick', 'update'];\n return phases.some((phase) => typeof value[phase] === 'object');\n}\n\n/** Resolves one kernel phase ref to its generated function name. */\nfunction phaseFromRef(\n module: IRModule,\n deviceId: string,\n ref: FunctionRef<readonly [], readonly []> | undefined,\n): GeneratedPhase | undefined {\n if (ref === undefined) return undefined;\n const definition = module.functions.find((fn) => fn.ref === ref);\n if (definition === undefined) {\n throw new UnifiedIRCompilerError(\n 'invalid-ir',\n `Device \"${deviceId}\" returned a kernel phase ref that is not part of the module`,\n { deviceId },\n );\n }\n return { name: definition.name, ref };\n}\n","import type { FunctionBuilder, FunctionRef, IRModule } from '@mica-js/ir';\nimport type { DeviceLoopEntry } from './device-gen';\nimport type { NetSolverRuntime } from './solver-gen';\nimport type { CompiledNetlist } from './types';\n\n/** Generated entry-point names. */\nexport interface MainLoopNames {\n readonly tick: string;\n readonly initialize: string;\n readonly batch: string;\n}\n\n/** Names used when the caller does not override them. */\nexport const DEFAULT_ENTRY_POINT_NAMES: MainLoopNames = Object.freeze({\n tick: 'unified_tick',\n initialize: 'unified_initialize',\n batch: 'unified_tick_batch',\n});\n\n/** The generated main loop. */\nexport interface MainLoopOutput {\n readonly names: MainLoopNames;\n readonly initialize: FunctionRef<readonly [], readonly []>;\n readonly tick: FunctionRef<readonly [], readonly []>;\n readonly batch: FunctionRef<readonly ['u32'], readonly []>;\n /** Device ids in dependency order. */\n readonly order: readonly string[];\n}\n\n/**\n * Generates the circuit entries.\n *\n * ```text\n * unified_initialize: // once, before the first tick\n * drive1_initialize()\n * sink1_initialize() // if the device has one\n *\n * unified_tick: // one simulation step\n * drive1_tick() // drivers publish their outputs\n * solve_net_0() // the electrical network resolves\n * sink1_update() // loads observe the solved inputs\n *\n * unified_tick_batch(count): // the same step, looped inside the IR\n * for i in 0 .. count { <step> }\n * ```\n *\n * Devices run in dependency order: a device that drives a net executes before\n * every device that senses it. Feedback loops fall back to declaration order\n * after the topological prefix, so clock cycles stay valid.\n */\nexport class MainLoopGenerator {\n private readonly module: IRModule;\n\n constructor(module: IRModule) {\n this.module = module;\n }\n\n /** Stable topological order of the devices; cycles fall back to declaration order. */\n order(entries: readonly DeviceLoopEntry[], netlist: CompiledNetlist): readonly string[] {\n const indexById = new Map(entries.map((entry, index) => [entry.deviceId, index]));\n const consumers = new Map<string, Set<string>>();\n const indegree = new Map<string, number>(entries.map((entry) => [entry.deviceId, 0]));\n\n for (const net of netlist.nets) {\n const driverDevices = new Set(net.drivers.map((pin) => pin.deviceId));\n const sinkDevices = new Set(net.sinks.map((pin) => pin.deviceId));\n for (const driver of driverDevices) {\n for (const sink of sinkDevices) {\n if (driver === sink) continue;\n let targets = consumers.get(driver);\n if (targets === undefined) {\n targets = new Set();\n consumers.set(driver, targets);\n }\n if (targets.has(sink)) continue;\n targets.add(sink);\n indegree.set(sink, (indegree.get(sink) ?? 0) + 1);\n }\n }\n }\n\n const ready = new Set(\n entries\n .filter((entry) => (indegree.get(entry.deviceId) ?? 0) === 0)\n .map((entry) => entry.deviceId),\n );\n const order: string[] = [];\n while (ready.size > 0) {\n let nextId: string | undefined;\n let nextIndex = Number.POSITIVE_INFINITY;\n for (const id of ready) {\n const index = indexById.get(id) ?? 0;\n if (index < nextIndex) {\n nextIndex = index;\n nextId = id;\n }\n }\n if (nextId === undefined) break;\n ready.delete(nextId);\n order.push(nextId);\n for (const consumer of consumers.get(nextId) ?? []) {\n const remaining = (indegree.get(consumer) ?? 0) - 1;\n indegree.set(consumer, remaining);\n if (remaining === 0) ready.add(consumer);\n }\n }\n for (const entry of entries) {\n if (!order.includes(entry.deviceId)) order.push(entry.deviceId);\n }\n return Object.freeze(order);\n }\n\n /** Generates `initialize`, `tick` and the batched tick loop. */\n generate(\n entries: readonly DeviceLoopEntry[],\n solvers: readonly NetSolverRuntime[],\n netlist: CompiledNetlist,\n names: MainLoopNames = DEFAULT_ENTRY_POINT_NAMES,\n ): MainLoopOutput {\n const order = this.order(entries, netlist);\n const byId = new Map(entries.map((entry) => [entry.deviceId, entry]));\n\n const emitStep = (b: FunctionBuilder<readonly []>): void => {\n for (const deviceId of order) {\n const entry = byId.get(deviceId);\n if (entry?.tick !== undefined) b.call(entry.tick, []);\n }\n for (const solver of solvers) b.call(solver.solve, []);\n for (const deviceId of order) {\n const entry = byId.get(deviceId);\n if (entry?.update !== undefined) b.call(entry.update, []);\n }\n };\n\n const initialize = this.module.func(names.initialize, { params: [], results: [] });\n initialize.body((b) => {\n for (const deviceId of order) {\n const entry = byId.get(deviceId);\n if (entry?.initialize !== undefined) b.call(entry.initialize, []);\n }\n b.return([]);\n });\n\n const tick = this.module.func(names.tick, { params: [], results: [] });\n tick.body((b) => {\n emitStep(b);\n b.return([]);\n });\n\n // The batch entry keeps the loop inside the IR: one engine call per batch\n // instead of one host entry per tick, which is the throughput path.\n const batch = this.module.func(names.batch, { params: ['u32'], results: [] });\n batch.body((b, [count]) => {\n const header = b.block(['u32']);\n const body = b.block(['u32']);\n const done = b.block([]);\n b.jump(header, [b.const('u32', 0)]);\n b.at(header, (ib, [index]) =>\n ib.branch(\n ib.int.cmp('lt', index, count),\n { target: body, args: [index] },\n { target: done, args: [] },\n ),\n );\n b.at(body, (ib, [index]) => {\n emitStep(ib);\n ib.jump(header, [ib.int.add(index, ib.const('u32', 1))]);\n });\n b.at(done, (ib) => ib.return([]));\n });\n\n return Object.freeze({\n names,\n initialize,\n tick,\n batch,\n order,\n });\n }\n}\n","import type { FunctionBuilder, FunctionRef, IRModule, Value } from '@mica-js/ir';\nimport { PIN_MODE } from '../pin-space';\nimport type {\n CompiledCircuitMemory,\n CompiledNet,\n CompiledNetlist,\n CompiledPinConnection,\n} from './types';\n\n/** One generated net solver. */\nexport interface NetSolverRuntime {\n readonly netId: number;\n /** Generated `solve_net_<id>`. */\n readonly name: string;\n readonly net: CompiledNet;\n readonly solve: FunctionRef<readonly [], readonly []>;\n}\n\n/** Everything the solver generator reads from the prior compilation stages. */\nexport interface SolverGenerationContext {\n readonly module: IRModule;\n readonly memory: CompiledCircuitMemory;\n}\n\n/**\n * Generates the electrical solve, one `solve_net_<id>` function per net.\n *\n * Each net solves as a branch-free function. One driver is the common shape:\n *\n * ```text\n * solve_net_0:\n * let mode = PIN_MODE[driver]\n * let output = PIN_OUTPUT[driver]\n * let driven = mode == PUSH_PULL && output\n * PIN_INPUT[load] = driven // once per sink\n * ```\n *\n * Only a push-pull driver holds its net; high-z, open-drain and analog modes\n * leave it floating. A driver-less net loads the constant of its rail, or\n * `false` when it is truly floating. Several drivers OR into a wired-OR level.\n */\nexport class ElectricalSolverGenerator {\n private readonly context: SolverGenerationContext;\n\n constructor(context: SolverGenerationContext) {\n this.context = context;\n }\n\n generate(netlist: CompiledNetlist): readonly NetSolverRuntime[] {\n return Object.freeze(netlist.nets.map((net) => this.generateNetSolver(net)));\n }\n\n private generateNetSolver(net: CompiledNet): NetSolverRuntime {\n const name = `solve_net_${net.netId}`;\n const solve = this.context.module.func(name, { params: [], results: [] });\n\n solve.body((b) => {\n if (net.sinks.length > 0) {\n const driven =\n net.drivers.length === 0\n ? b.const('bool', net.level)\n : this.combineDrivers(b, net.drivers);\n if (driven !== undefined) {\n for (const sink of net.sinks) {\n b.array.store(this.context.memory.input, b.const('u32', sink.globalPinId), driven);\n }\n }\n }\n b.return([]);\n });\n\n return Object.freeze({ netId: net.netId, name, net, solve });\n }\n\n /**\n * Folds the drivers of one net into the level its sinks observe.\n *\n * A single driver yields `mode == push-pull && output`; several drivers are\n * OR-ed into a wired-OR level.\n */\n private combineDrivers(\n b: FunctionBuilder<readonly []>,\n drivers: readonly CompiledPinConnection[],\n ): Value<'bool'> | undefined {\n let driven: Value<'bool'> | undefined;\n for (const driver of drivers) {\n const index = b.const('u32', driver.globalPinId);\n const mode = b.array.load(this.context.memory.mode, index);\n const output = b.array.load(this.context.memory.output, index);\n const pushed = b.int.cmp('eq', mode, b.const('u8', PIN_MODE.pushPull));\n const value = b.bool.and(pushed, output);\n driven = driven === undefined ? value : b.bool.or(driven, value);\n }\n return driven;\n }\n}\n","import {\n UnifiedIRCompilerError,\n type CompilationDiagnostic,\n type CompiledNet,\n type CompiledNetlist,\n type CompiledPinConnection,\n type CompiledRail,\n type Connection,\n type GlobalPinMap,\n type ResolvedDevicePin,\n} from './types';\n\n/** Rails every circuit understands without declaring them. */\nexport const DEFAULT_RAILS: Readonly<Record<string, boolean>> = Object.freeze({\n GND: false,\n VCC: true,\n VDD: true,\n});\n\n/** Options for {@link NetworkTopologyAnalyzer}. */\nexport interface TopologyOptions {\n /** Extra or overriding rails; merged over {@link DEFAULT_RAILS}. */\n readonly rails?: Readonly<Record<string, boolean>>;\n}\n\ninterface ResolvedPinEndpoint {\n readonly kind: 'pin';\n readonly nodeId: number;\n readonly pin: ResolvedDevicePin;\n}\n\ninterface ResolvedRailEndpoint {\n readonly kind: 'rail';\n readonly nodeId: number;\n readonly name: string;\n readonly level: boolean;\n}\n\ntype ResolvedEndpoint = ResolvedPinEndpoint | ResolvedRailEndpoint;\n\ninterface ComponentPins {\n readonly pins: CompiledPinConnection[];\n readonly rails: CompiledRail[];\n readonly endpoints: string[];\n}\n\n/**\n * Analyses the pin-to-pin connections of a circuit.\n *\n * 1. every connection edge joins two nodes (pins and rails);\n * 2. a union-find pass collapses them into electrical nets (connected components);\n * 3. each net gets an id in first-appearance order and is split into drivers,\n * loads and sinks;\n * 4. electrical conflicts (a driver against a rail, two rails of opposite\n * level) become diagnostics instead of silently wrong IR.\n *\n * Several drivers on one net are legal and solved as a wired-OR, which is what\n * a bidirectional pin fighting a switch looks like on a bench.\n */\nexport class NetworkTopologyAnalyzer {\n private readonly rails: ReadonlyMap<string, boolean>;\n\n constructor(options: TopologyOptions = {}) {\n this.rails = new Map([\n ...Object.entries(DEFAULT_RAILS),\n ...Object.entries(options.rails ?? {}),\n ]);\n }\n\n /**\n * @throws {UnifiedIRCompilerError} when a connection is malformed, names an\n * unknown device, or names a pin the device does not declare.\n */\n analyze(connections: readonly Connection[], pins: GlobalPinMap): CompiledNetlist {\n if (!Array.isArray(connections)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.connections must be an array',\n );\n }\n\n const set = new DisjointSet();\n const pinNodes = new Map<number, CompiledPinConnection>();\n const railNodes = new Map<number, CompiledRail>();\n const railNodeIds = new Map<string, number>();\n const connectionOrder: number[] = [];\n\n for (const [index, connection] of connections.entries()) {\n if (connection === null || typeof connection !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-connection',\n `Connection[${index}] must be an object with \"from\" and \"to\"`,\n );\n }\n const from = this.resolveEndpoint(connection.from, pins, railNodeIds, index);\n const to = this.resolveEndpoint(connection.to, pins, railNodeIds, index);\n set.union(from.nodeId, to.nodeId);\n connectionOrder.push(from.nodeId);\n if (from.kind === 'pin') pinNodes.set(from.pin.globalPinId, toConnection(from.pin));\n else railNodes.set(from.nodeId, Object.freeze({ name: from.name, level: from.level }));\n if (to.kind === 'pin') pinNodes.set(to.pin.globalPinId, toConnection(to.pin));\n else railNodes.set(to.nodeId, Object.freeze({ name: to.name, level: to.level }));\n }\n\n // Component identity is the union-find root; the first connection that\n // touches a component decides its net id, which keeps ids stable.\n const components = new Map<number, ComponentPins>();\n const componentOf = (nodeId: number): ComponentPins => {\n const root = set.find(nodeId);\n let component = components.get(root);\n if (component === undefined) {\n component = { pins: [], rails: [], endpoints: [] };\n components.set(root, component);\n }\n return component;\n };\n\n for (const [pinId, connection] of pinNodes) componentOf(pinId).pins.push(connection);\n for (const [nodeId, rail] of railNodes) {\n const component = componentOf(nodeId);\n component.rails.push(rail);\n component.endpoints.push(rail.name);\n }\n\n const orderedRoots: number[] = [];\n const seen = new Set<number>();\n for (const nodeId of connectionOrder) {\n const root = set.find(nodeId);\n if (seen.has(root)) continue;\n seen.add(root);\n orderedRoots.push(root);\n }\n\n const diagnostics: CompilationDiagnostic[] = [];\n const nets: CompiledNet[] = [];\n for (const root of orderedRoots) {\n const component = components.get(root);\n if (component === undefined) continue;\n component.pins.sort((left, right) => left.globalPinId - right.globalPinId);\n component.rails.sort((left, right) => left.name.localeCompare(right.name));\n const endpoints = [...component.endpoints, ...component.pins.map((pin) => pin.endpoint)];\n\n if (component.pins.length === 0) {\n // Rail-to-rail wiring only: report a short, never emit a net.\n const levels = new Set(component.rails.map((rail) => rail.level));\n if (levels.size > 1) {\n diagnostics.push(\n diagnostic(\n 'rail-conflict',\n 'error',\n `Rails ${component.rails.map((rail) => rail.name).join(' and ')} are wired together with opposite levels`,\n undefined,\n endpoints,\n ),\n );\n }\n continue;\n }\n\n const netId = nets.length;\n const net = this.classify(netId, component.pins, component.rails, diagnostics);\n nets.push(net);\n }\n\n return Object.freeze({ nets: Object.freeze(nets), diagnostics: Object.freeze(diagnostics) });\n }\n\n private classify(\n netId: number,\n pins: readonly CompiledPinConnection[],\n rails: readonly CompiledRail[],\n diagnostics: CompilationDiagnostic[],\n ): CompiledNet {\n const drivers = pins.filter((pin) => pin.role === 'driver');\n const loads = pins.filter((pin) => pin.role === 'load');\n const sinks = pins.filter((pin) => pin.senses);\n const endpoints = [...rails.map((rail) => rail.name), ...pins.map((pin) => pin.endpoint)];\n const levels = new Set(rails.map((rail) => rail.level));\n\n if (rails.length > 1 && levels.size > 1) {\n diagnostics.push(\n diagnostic(\n 'rail-conflict',\n 'error',\n `Net ${netId} ties rails ${rails.map((rail) => rail.name).join(' and ')} with opposite levels`,\n netId,\n endpoints,\n ),\n );\n }\n if (drivers.length > 0 && rails.length > 0) {\n diagnostics.push(\n diagnostic(\n 'power-short',\n 'error',\n `Net ${netId} shorts rail ${rails[0]?.name ?? '?'} against driver ${drivers[0]?.endpoint ?? '?'}`,\n netId,\n endpoints,\n ),\n );\n }\n if (drivers.length === 0 && rails.length === 0) {\n diagnostics.push(\n diagnostic(\n 'floating-net',\n 'warning',\n `Net ${netId} has no driver and no rail; its loads read a constant low`,\n netId,\n endpoints,\n ),\n );\n }\n\n const source = drivers.length > 0 ? 'driver' : rails.length > 0 ? 'rail' : 'floating';\n const level = rails[0]?.level ?? false;\n\n return Object.freeze({\n netId,\n pins: Object.freeze([...pins]),\n rails: Object.freeze([...rails]),\n drivers: Object.freeze(drivers),\n loads: Object.freeze(loads),\n sinks: Object.freeze(sinks),\n source,\n level,\n });\n }\n\n private resolveEndpoint(\n raw: unknown,\n pins: GlobalPinMap,\n railNodeIds: Map<string, number>,\n index: number,\n ): ResolvedEndpoint {\n if (typeof raw !== 'string' || raw.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-connection',\n `Connection[${index}] endpoint must be a non-empty \"device.pin\" string or a rail name`,\n );\n }\n const railLevel = this.rails.get(raw);\n if (railLevel !== undefined) {\n let nodeId = railNodeIds.get(raw);\n if (nodeId === undefined) {\n nodeId = pins.totalPins + railNodeIds.size;\n railNodeIds.set(raw, nodeId);\n }\n return { kind: 'rail', nodeId, name: raw, level: railLevel };\n }\n\n const dot = raw.indexOf('.');\n if (dot <= 0 || dot === raw.length - 1) {\n throw new UnifiedIRCompilerError(\n 'invalid-connection',\n `Connection endpoint \"${raw}\" must be \"device.pin\" or a known rail (${[...this.rails.keys()].join(', ')})`,\n );\n }\n const deviceId = raw.slice(0, dot);\n const pinName = raw.slice(dot + 1);\n const allocation = pins.devices.get(deviceId);\n if (allocation === undefined) {\n throw new UnifiedIRCompilerError(\n 'unknown-device',\n `Connection endpoint \"${raw}\" references unknown device \"${deviceId}\". Available: [${[...pins.devices.keys()].join(', ')}]`,\n { deviceId },\n );\n }\n const pin = allocation.resolved.get(pinName);\n if (pin === undefined) {\n const available = [...allocation.resolved.keys()].map((name) => `${deviceId}.${name}`);\n throw new UnifiedIRCompilerError(\n 'pin-not-found',\n `Pin '${raw}' not found. Available: [${available.join(', ')}]`,\n { deviceId, pinName },\n );\n }\n return { kind: 'pin', nodeId: pin.globalPinId, pin };\n }\n}\n\n/**\n * Throws the first error diagnostic of a netlist, or returns it unchanged.\n *\n * @throws {UnifiedIRCompilerError} carrying every diagnostic for inspection.\n */\nexport function assertNoElectricalErrors(netlist: CompiledNetlist): CompiledNetlist {\n const errors = netlist.diagnostics.filter((entry) => entry.severity === 'error');\n const first = errors[0];\n if (first === undefined) return netlist;\n throw new UnifiedIRCompilerError(mapErrorCode(first.code), first.message, {\n ...(first.netId === undefined ? {} : { netId: first.netId }),\n diagnostics: netlist.diagnostics,\n });\n}\n\nfunction mapErrorCode(code: CompilationDiagnostic['code']): 'power-short' | 'rail-conflict' {\n return code === 'rail-conflict' ? 'rail-conflict' : 'power-short';\n}\n\nfunction diagnostic(\n code: CompilationDiagnostic['code'],\n severity: CompilationDiagnostic['severity'],\n message: string,\n netId: number | undefined,\n endpoints: readonly string[],\n): CompilationDiagnostic {\n return Object.freeze({\n code,\n severity,\n message,\n netId,\n endpoints: Object.freeze([...endpoints]),\n });\n}\n\nfunction toConnection(pin: ResolvedDevicePin): CompiledPinConnection {\n return Object.freeze({\n endpoint: `${pin.deviceId}.${pin.name}`,\n deviceId: pin.deviceId,\n pinName: pin.name,\n globalPinId: pin.globalPinId,\n role: pin.role,\n senses: pin.senses,\n });\n}\n\n/** Union-find over pin ids and rail node ids. */\nclass DisjointSet {\n private readonly parent = new Map<number, number>();\n private readonly rank = new Map<number, number>();\n\n find(id: number): number {\n const parent = this.parent.get(id);\n if (parent === undefined) {\n this.parent.set(id, id);\n this.rank.set(id, 0);\n return id;\n }\n if (parent === id) return id;\n const root = this.find(parent);\n this.parent.set(id, root);\n return root;\n }\n\n union(left: number, right: number): void {\n const leftRoot = this.find(left);\n const rightRoot = this.find(right);\n if (leftRoot === rightRoot) return;\n const leftRank = this.rank.get(leftRoot) ?? 0;\n const rightRank = this.rank.get(rightRoot) ?? 0;\n if (leftRank < rightRank) {\n this.parent.set(leftRoot, rightRoot);\n return;\n }\n this.parent.set(rightRoot, leftRoot);\n if (leftRank === rightRank) this.rank.set(leftRoot, leftRank + 1);\n }\n}\n","import { createIRModule, validateIR } from '@mica-js/ir';\nimport type { IRModule, IRValidationOptions } from '@mica-js/ir';\nimport { createModuleValidation } from '../validation';\nimport { GlobalResourceAllocator } from './allocator';\nimport { DeviceIRGenerator } from './device-gen';\nimport { DEFAULT_ENTRY_POINT_NAMES, MainLoopGenerator, type MainLoopNames } from './mainloop-gen';\nimport { ElectricalSolverGenerator } from './solver-gen';\nimport {\n NetworkTopologyAnalyzer,\n assertNoElectricalErrors,\n type TopologyOptions,\n} from './topology';\nimport {\n UnifiedIRCompilerError,\n type CircuitCompilationInput,\n type CircuitCompilationOptions,\n type CompiledCircuit,\n type Connection,\n type DeviceConfig,\n} from './types';\n\n/**\n * Compiles several devices and their wiring into one unified IR module (U01).\n *\n * Device models are caller-supplied: every entry of `devices` carries the pins,\n * states and behaviors (or `kernel`) its type needs.\n *\n * ```ts\n * const circuit = compileCircuit({\n * devices: [\n * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },\n * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },\n * ],\n * connections: [\n * { from: 'drive1.channel0', to: 'sink1.anode' },\n * { from: 'sink1.cathode', to: 'GND' },\n * ],\n * });\n *\n * const jit = createIRJIT(circuit.module, { validation: circuit.validation });\n * jit.execute(circuit.entryPoints.refs.initialize, []);\n * jit.execute(circuit.entryPoints.refs.tick, []); // drive1 + nets + sink1\n * ```\n *\n * The pipeline is: validate the input, allocate the global pin and state\n * spaces, analyse the electrical topology, generate one function per device\n * phase, generate one solver per net, generate the main loop, then validate the\n * resulting module with `validateIR`.\n *\n * @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown\n * pins, electrical conflicts, or when the generated module fails validation.\n */\nexport function compileCircuit(\n input: CircuitCompilationInput,\n options: CircuitCompilationOptions = {},\n): CompiledCircuit {\n const { devices, connections } = validateInput(input);\n const resolvedOptions = validateOptions(options);\n const names = resolveEntryNames(resolvedOptions);\n\n const module = createIRModule();\n const allocation = new GlobalResourceAllocator(module).allocate(devices);\n\n const topologyOptions: TopologyOptions = {\n ...(resolvedOptions.rails === undefined ? {} : { rails: resolvedOptions.rails }),\n };\n const netlist = new NetworkTopologyAnalyzer(topologyOptions).analyze(\n connections,\n allocation.pins,\n );\n assertNoElectricalErrors(netlist);\n\n const generator = new DeviceIRGenerator({\n module,\n memory: allocation.memory,\n pins: allocation.pins,\n states: allocation.states,\n });\n const generated = devices.map((device) => generator.generate(device));\n\n const solvers = new ElectricalSolverGenerator({\n module,\n memory: allocation.memory,\n }).generate(netlist);\n\n assertNoNameCollisions(\n devices,\n solvers.map((solver) => solver.name),\n names,\n );\n\n const loop = new MainLoopGenerator(module).generate(\n generated.map((device) => device.entry),\n solvers,\n netlist,\n names,\n );\n\n const validation = createModuleValidation(\n module,\n devices.flatMap((device) => device.description.updateResources ?? []),\n );\n if (resolvedOptions.validate !== false) validateModule(module, validation);\n\n const deviceMap = new Map(generated.map((device) => [device.metadata.deviceId, device.metadata]));\n\n return Object.freeze({\n module,\n entryPoints: Object.freeze({\n tick: loop.names.tick,\n initialize: loop.names.initialize,\n batch: loop.names.batch,\n refs: Object.freeze({\n tick: loop.tick,\n initialize: loop.initialize,\n batch: loop.batch,\n }),\n }),\n pinMap: allocation.pins.pins,\n deviceMap,\n netlist,\n pins: allocation.pins,\n states: allocation.states,\n memory: allocation.memory,\n validation,\n executionOrder: loop.order,\n functions: Object.freeze(module.functions.map((fn) => fn.name)),\n });\n}\n\nfunction validateInput(input: unknown): {\n readonly devices: readonly DeviceConfig[];\n readonly connections: readonly Connection[];\n} {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput must be an object with devices and connections',\n );\n }\n const { devices, connections } = input as Partial<CircuitCompilationInput>;\n if (!Array.isArray(devices) || devices.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.devices must be a non-empty array',\n );\n }\n if (!Array.isArray(connections)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.connections must be an array',\n );\n }\n return { devices, connections };\n}\n\nfunction validateOptions(options: unknown): CircuitCompilationOptions {\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw new UnifiedIRCompilerError('invalid-input', 'Compile options must be an object');\n }\n const resolved = options as CircuitCompilationOptions;\n if (resolved.validate !== undefined && typeof resolved.validate !== 'boolean') {\n throw new UnifiedIRCompilerError('invalid-input', 'options.validate must be a boolean');\n }\n if (resolved.rails !== undefined) {\n if (\n resolved.rails === null ||\n typeof resolved.rails !== 'object' ||\n Array.isArray(resolved.rails)\n ) {\n throw new UnifiedIRCompilerError('invalid-input', 'options.rails must be a plain object');\n }\n for (const [name, level] of Object.entries(resolved.rails)) {\n if (name.length === 0 || typeof level !== 'boolean') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `options.rails[\"${name}\"] must be a boolean`,\n );\n }\n }\n }\n return resolved;\n}\n\nfunction resolveEntryNames(options: CircuitCompilationOptions): MainLoopNames {\n const names: MainLoopNames = {\n tick: options.entryPointNames?.tick ?? DEFAULT_ENTRY_POINT_NAMES.tick,\n initialize: options.entryPointNames?.initialize ?? DEFAULT_ENTRY_POINT_NAMES.initialize,\n batch: options.entryPointNames?.batch ?? DEFAULT_ENTRY_POINT_NAMES.batch,\n };\n for (const [role, name] of Object.entries(names)) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Entry point names.${role} must be a non-empty string`,\n );\n }\n }\n if (new Set(Object.values(names)).size !== 3) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Entry point names must be distinct: ${JSON.stringify(names)}`,\n );\n }\n return Object.freeze(names);\n}\n\nfunction assertNoNameCollisions(\n devices: readonly DeviceConfig[],\n solverNames: readonly string[],\n names: MainLoopNames,\n): void {\n const reserved = new Set<string>([names.tick, names.initialize, names.batch, ...solverNames]);\n for (const device of devices) {\n for (const phase of ['initialize', 'tick', 'update'] as const) {\n const generated = `${device.id}_${phase}`;\n if (reserved.has(generated)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" generates \"${generated}\", which collides with another generated function; rename the device or the entry point`,\n { deviceId: device.id },\n );\n }\n }\n }\n}\n\nfunction validateModule(module: IRModule, validation: IRValidationOptions): void {\n const result = validateIR(module, validation);\n if (result.ok) return;\n const details = result.diagnostics\n .map((entry) => `- [${entry.code}] ${entry.message} at ${entry.location.path}`)\n .join('\\n');\n throw new UnifiedIRCompilerError(\n 'invalid-ir',\n `Generated IR failed validateIR (${result.diagnostics.length} diagnostic(s)):\\n${details}`,\n );\n}\n\nexport * from './types';\nexport { GlobalResourceAllocator, createPinMemory, stateOffsetOf } from './allocator';\nexport type { ResourceAllocation } from './allocator';\nexport { DEFAULT_RAILS, NetworkTopologyAnalyzer, assertNoElectricalErrors } from './topology';\nexport type { TopologyOptions } from './topology';\nexport { DeviceIRGenerator } from './device-gen';\nexport type { DeviceGenerationContext, DeviceLoopEntry, GeneratedDevice } from './device-gen';\nexport { ElectricalSolverGenerator } from './solver-gen';\nexport type { NetSolverRuntime, SolverGenerationContext } from './solver-gen';\nexport { DEFAULT_ENTRY_POINT_NAMES, MainLoopGenerator } from './mainloop-gen';\nexport type { MainLoopNames, MainLoopOutput } from './mainloop-gen';\n","import type { IRJITTuning } from '@mica-js/ir';\nimport type { CircuitCompilationInput } from '../compiler';\n\n/**\n * Types of the unified circuit runtime (U02).\n *\n * `Circuit` is the host-facing facade over one compiled unified IR module: it\n * owns the engine instance, exposes typed per-device accessors and keeps the\n * tick counter. Everything here is transport-neutral; no type mentions the\n * device host or the schematic editor.\n */\n\n/** Execution engine a `Circuit` runs on. */\nexport type CircuitEngine = 'jit' | 'reference';\n\n/** Electrical-solve options forwarded to `compileCircuit`. */\nexport interface CircuitElectricalOptions {\n /** Named fixed-level rails; merged over `GND`/`VCC`/`VDD`. */\n readonly rails?: Readonly<Record<string, boolean>>;\n}\n\n/**\n * Options for `Circuit.create`.\n *\n * @example\n * const circuit = await Circuit.create(input, { engine: 'reference' });\n */\nexport interface CircuitRuntimeOptions {\n /** Execution engine. Defaults to `'jit'`; `'reference'` runs the interpreter. */\n readonly engine?: CircuitEngine;\n /** JIT tuning. The runtime always supplies the module's own validation grant. */\n readonly jit?: IRJITTuning;\n /**\n * Run `validateIR` over the generated module during compilation.\n * Defaults to `true`; pass `false` only for measured warm paths.\n */\n readonly validateIR?: boolean;\n /** Electrical-solve options. */\n readonly electrical?: CircuitElectricalOptions;\n /** Instance id reported to the engine. Defaults to `'unified-circuit'`. */\n readonly instanceId?: string;\n}\n\n/** Error codes raised by `CircuitError`. */\nexport type CircuitErrorCode =\n | 'invalid-options'\n | 'invalid-count'\n | 'pin-not-found'\n | 'pin-not-writable'\n | 'state-not-found'\n | 'invalid-state-value'\n | 'unresolved-device'\n | 'disposed';\n\nexport interface CircuitErrorOptions {\n readonly deviceId?: string;\n readonly pinName?: string;\n readonly stateName?: string;\n readonly cause?: unknown;\n}\n\n/**\n * Error raised while driving a `Circuit`.\n *\n * The code is stable and machine-checkable, and the message always names the\n * offending device/pin/state plus the values that would have been accepted.\n */\nexport class CircuitError extends Error {\n override readonly name = 'CircuitError';\n readonly code: CircuitErrorCode;\n readonly deviceId: string | undefined;\n readonly pinName: string | undefined;\n readonly stateName: string | undefined;\n\n constructor(code: CircuitErrorCode, message: string, options: CircuitErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.code = code;\n this.deviceId = options.deviceId;\n this.pinName = options.pinName;\n this.stateName = options.stateName;\n }\n}\n\n/**\n * What every device accessor offers, whatever its type.\n *\n * `readPin` returns the level the *device* drives onto one of its pins (its\n * output latch), while `Circuit.getPin('device.pin')` returns the level the pin\n * *observes* after the electrical solve. Writing a pin only makes sense for\n * driver pins, so `writePin` rejects load and passive pins.\n */\nexport interface DeviceAccessor {\n /** Circuit-unique device id. */\n readonly deviceId: string;\n /** Device type, e.g. `'push-pull-driver'`. */\n readonly type: string;\n /** Declared pin names, in declaration order. */\n readonly pinNames: readonly string[];\n /** Declared internal state names, in declaration order. */\n readonly stateNames: readonly string[];\n /** Reads the level the device drives onto `pinName`. */\n readPin(pinName: string): boolean;\n /** Writes the level the device drives onto `pinName`. */\n writePin(pinName: string, value: boolean): void;\n /** Reads one declared internal state. */\n getState(name: string): unknown;\n /** Writes one declared internal state. */\n setState(name: string, value: unknown): void;\n}\n\n/** Every accessor of one circuit, keyed by device id. */\nexport type DeviceAccessors = Readonly<Record<string, DeviceAccessor>>;\n\n/**\n * Accessor map derived from a literal compilation input.\n *\n * `Circuit.create` infers the device ids of a `const` input, so\n * `circuit.devices.<id>` is typed without a cast. A device package that wants a\n * richer surface builds it through `DeviceDescription.accessor` and casts at\n * the call site.\n */\nexport type DeviceAccessorsOf<I extends CircuitCompilationInput> = {\n readonly [D in I['devices'][number] as D['id']]: DeviceAccessor;\n};\n","import type { FloatBits, IRInterpreter, RuntimeScalar } from '@mica-js/ir';\nimport type {\n CompiledCircuit,\n DeviceMetadata,\n DeviceStateSlot,\n ResolvedDevicePin,\n} from '../compiler';\nimport { CircuitError, type DeviceAccessor, type DeviceAccessors } from './types';\n\n/** Everything the accessor builders read from one live circuit. */\nexport interface DeviceAccessorContext {\n readonly compiled: CompiledCircuit;\n readonly jit: IRInterpreter;\n /** Invoked before every read or write; throws once the circuit is disposed. */\n readonly assertActive: () => void;\n /** Advances the circuit by one tick; used by custom accessors. */\n readonly step: () => void;\n /** Advances the circuit by `count` ticks; used by custom accessors. */\n readonly runBatch: (count: number) => void;\n}\n\n/**\n * Builds one accessor per compiled device.\n *\n * A description that declares `accessor` owns its surface; every other device\n * keeps the generic state/pin accessor. The returned record is frozen and keyed\n * by device id.\n */\nexport function buildDeviceAccessors(context: DeviceAccessorContext): DeviceAccessors {\n const entries: [string, DeviceAccessor][] = [];\n for (const device of context.compiled.deviceMap.values()) {\n const base = createBaseAccessor(context, device);\n if (device.accessor !== undefined) {\n // A custom kernel owns its accessor: the factory closes over the layout\n // its IR factory allocated in this module.\n entries.push([\n device.deviceId,\n device.accessor({\n deviceId: device.deviceId,\n storage: context.jit.storage,\n assertActive: context.assertActive,\n step: context.step,\n runBatch: context.runBatch,\n }) as unknown as DeviceAccessor,\n ]);\n } else {\n entries.push([device.deviceId, base]);\n }\n }\n // `Object.fromEntries` defines own data properties, so ids such as\n // `__proto__` stay ordinary keys instead of reaching the prototype chain.\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction createBaseAccessor(\n context: DeviceAccessorContext,\n device: DeviceMetadata,\n): DeviceAccessor {\n const { jit } = context;\n const storage = jit.storage;\n const memory = context.compiled.memory;\n const resolved = context.compiled.pins.devices.get(device.deviceId)?.resolved;\n\n const accessor: DeviceAccessor = {\n deviceId: device.deviceId,\n type: device.type,\n pinNames: Object.freeze([...device.pins.keys()]),\n stateNames: Object.freeze([...device.states.keys()]),\n readPin(pinName: string): boolean {\n context.assertActive();\n const pin = pinOf(device, resolved, pinName);\n return storage.loadArray(memory.output, pin.globalPinId) === true;\n },\n writePin(pinName: string, value: boolean): void {\n context.assertActive();\n const pin = pinOf(device, resolved, pinName);\n if (pin.role !== 'driver') {\n throw new CircuitError(\n 'pin-not-writable',\n `Pin \"${device.deviceId}.${pinName}\" has role \"${pin.role}\"; only driver pins can be written. Use Circuit.setPin to override a sensed level`,\n { deviceId: device.deviceId, pinName },\n );\n }\n assertBoolean(device.deviceId, pinName, value);\n storage.storeArray(memory.output, pin.globalPinId, value);\n },\n getState(name: string): unknown {\n context.assertActive();\n const slot = stateOf(device, name);\n return storage.loadArray(slot.array, slot.index);\n },\n setState(name: string, value: unknown): void {\n context.assertActive();\n const slot = stateOf(device, name);\n const accepted = coerceStateValue(device, slot, value);\n try {\n storage.storeArray(slot.array, slot.index, accepted);\n } catch (cause) {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${name}\" (${slot.type}) rejected ${String(value)}`,\n { deviceId: device.deviceId, stateName: name, cause },\n );\n }\n },\n };\n return Object.freeze(accessor);\n}\n\n/** Resolves one pin of `device`, or throws with every pin the device declares. */\nfunction pinOf(\n device: DeviceMetadata,\n resolved: ReadonlyMap<string, ResolvedDevicePin> | undefined,\n pinName: string,\n): ResolvedDevicePin {\n const pin = resolved?.get(pinName);\n if (pin === undefined) {\n throw new CircuitError(\n 'pin-not-found',\n `Device \"${device.deviceId}\" (${device.type}) has no pin \"${pinName}\". Available: ${formatNames(device.pins.keys())}`,\n { deviceId: device.deviceId, pinName },\n );\n }\n return pin;\n}\n\n/** Resolves one state slot of `device`, or throws with every state it declares. */\nfunction stateOf(device: DeviceMetadata, name: string): DeviceStateSlot {\n const slot = device.states.get(name);\n if (slot === undefined) {\n throw new CircuitError(\n 'state-not-found',\n `Device \"${device.deviceId}\" (${device.type}) has no state \"${name}\". Available: ${formatNames(device.states.keys())}`,\n { deviceId: device.deviceId, stateName: name },\n );\n }\n return slot;\n}\n\nfunction assertBoolean(\n deviceId: string,\n pinName: string,\n value: unknown,\n): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new CircuitError(\n 'invalid-state-value',\n `Pin \"${deviceId}.${pinName}\" needs a boolean level, received ${typeof value}`,\n { deviceId, pinName },\n );\n }\n}\n\n/**\n * Validates a host-written state value against the declared scalar type.\n * Range checks stay in storage, which owns the encoding.\n */\nfunction coerceStateValue(\n device: DeviceMetadata,\n slot: DeviceStateSlot,\n value: unknown,\n): RuntimeScalar {\n if (slot.type === 'bool') {\n if (typeof value !== 'boolean') {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is bool and needs true or false, received ${String(value)}`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n return value;\n }\n if (slot.type === 'f32' || slot.type === 'f64') {\n if (typeof value === 'number' || isFloatBits(value)) return value;\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is ${slot.type} and needs a number or FloatBits`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is ${slot.type} and needs an integer, received ${String(value)}`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n return value;\n}\n\nfunction isFloatBits(value: unknown): value is FloatBits {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as { readonly type?: unknown; readonly bits?: unknown };\n return (\n (candidate.type === 'f32' || candidate.type === 'f64') && typeof candidate.bits === 'string'\n );\n}\n\nfunction formatNames(names: Iterable<string>): string {\n const list = [...names];\n return list.length === 0 ? '(none)' : `[${list.join(', ')}]`;\n}\n","import { createIRInterpreter, createIRJIT } from '@mica-js/ir';\nimport type {\n ArrayRef,\n BytesRef,\n IRInterpreter,\n IRJITTuning,\n RuntimeScalar,\n StateRef,\n} from '@mica-js/ir';\nimport { compileCircuit } from '../compiler';\nimport type {\n CircuitCompilationInput,\n CircuitCompilationOptions,\n CompiledCircuit,\n} from '../compiler';\nimport { PIN_MODE } from '../pin-space';\nimport { buildDeviceAccessors } from './accessors';\nimport {\n CircuitError,\n type CircuitEngine,\n type CircuitRuntimeOptions,\n type DeviceAccessorsOf,\n} from './types';\n\n/** Every generated entry takes no arguments, so one frozen array is reused. */\nconst NO_ARGS: readonly RuntimeScalar[] = Object.freeze([]);\n\n/** `unified_tick_batch` takes a u32 tick count. */\nconst MAX_BATCH_TICKS = 0xffff_ffff;\n\n/** Virtual time is a JS number, so it wraps before losing integer precision. */\nconst MAX_VIRTUAL_TIME = Number.MAX_SAFE_INTEGER;\n\nconst DEFAULT_INSTANCE_ID = 'unified-circuit';\n\n/**\n * Mutable execution context. `IRExecutionContext` is readonly for callers; the\n * runtime owns this object and updates `virtualTime` in place so that `step()`\n * allocates nothing on the hot path.\n */\ninterface RuntimeContext {\n instanceId: string;\n virtualTime: number;\n}\n\n/** One pin of the global address space, resolved at construction time. */\ninterface PinRuntime {\n readonly globalPinId: number;\n readonly role: 'driver' | 'load';\n /** Whether the device reads the solved level of this pin. */\n readonly senses: boolean;\n}\n\n/** Declared initial value of one memory resource, replayed by `reset()`. */\ntype ResetSeed =\n | { readonly kind: 'array'; readonly ref: ArrayRef; readonly values: readonly RuntimeScalar[] }\n | { readonly kind: 'state'; readonly ref: StateRef; readonly value: RuntimeScalar }\n | {\n readonly kind: 'bytes';\n readonly ref: BytesRef<false>;\n readonly values: readonly RuntimeScalar[];\n }\n | {\n readonly kind: 'readonly-bytes';\n readonly ref: BytesRef<true>;\n readonly values: Uint8Array;\n };\n\ninterface ResolvedRuntimeOptions {\n readonly engine: CircuitEngine;\n readonly jit: IRJITTuning | undefined;\n readonly validateIR: boolean;\n readonly rails: Readonly<Record<string, boolean>> | undefined;\n readonly instanceId: string;\n}\n\n/**\n * Host-facing runtime of one compiled unified circuit (U02).\n *\n * ```ts\n * const circuit = await Circuit.create({\n * devices: [\n * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },\n * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },\n * ],\n * connections: [\n * { from: 'drive1.PA0', to: 'sink1.anode' },\n * { from: 'sink1.cathode', to: 'GND' },\n * ],\n * });\n *\n * circuit.runBatch(1_000_000); // one engine call\n * expect(circuit.tickCount).toBe(1_000_000n);\n *\n * circuit.reset();\n * circuit.setPin('drive1.PA0', true); // host drives the pin\n * circuit.step();\n * expect(circuit.devices.sink1.getState('lamp')).toBe(true);\n * ```\n *\n * `Circuit` owns the engine instance and the tick counter; the compiled module\n * keeps every device, net and the main loop in one `@mica-js/ir` module, so a\n * batch is one interpreter/JIT call for the whole circuit.\n */\nexport class Circuit<I extends CircuitCompilationInput = CircuitCompilationInput> {\n /** Typed per-device accessors, keyed by device id. */\n readonly devices: DeviceAccessorsOf<I>;\n\n readonly #compiled: CompiledCircuit;\n readonly #jit: IRInterpreter;\n readonly #context: RuntimeContext;\n readonly #pins: ReadonlyMap<string, PinRuntime>;\n readonly #pinNames: readonly string[];\n readonly #seeds: readonly ResetSeed[];\n #tickCount = 0n;\n #virtualTime = 0;\n #disposed = false;\n\n private constructor(\n compiled: CompiledCircuit,\n jit: IRInterpreter,\n instanceId: string,\n accessors: DeviceAccessorsOf<I>,\n pins: ReadonlyMap<string, PinRuntime>,\n seeds: readonly ResetSeed[],\n ) {\n this.#compiled = compiled;\n this.#jit = jit;\n this.#context = { instanceId, virtualTime: 0 };\n this.devices = accessors;\n this.#pins = pins;\n this.#pinNames = Object.freeze([...pins.keys()]);\n this.#seeds = seeds;\n }\n\n /**\n * Compiles `input`, builds the engine instance and runs the generated\n * `initialize` entry once.\n *\n * The input is inferred as a `const` type, so a literal device list keeps its\n * ids and `circuit.devices.<id>` is typed without a cast.\n *\n * @throws {UnifiedIRCompilerError} when the circuit cannot be compiled.\n * @throws {CircuitError} for invalid options.\n */\n static async create<const I extends CircuitCompilationInput>(\n input: I,\n options: CircuitRuntimeOptions = {},\n ): Promise<Circuit<I>> {\n const resolved = resolveOptions(options);\n const compiled = compileCircuit(input, compileOptionsOf(resolved));\n const jit = createEngine(compiled, resolved);\n // The accessor factories run inside `buildDeviceAccessors`, which happens\n // before `circuit` is assigned. They only close over this holder; the\n // callbacks are invoked after construction.\n const host: { circuit: Circuit<I> | undefined } = { circuit: undefined };\n const circuit = new Circuit<I>(\n compiled,\n jit,\n resolved.instanceId,\n buildDeviceAccessors({\n compiled,\n jit,\n assertActive: () => {\n circuit.#assertActive();\n },\n step: () => {\n host.circuit?.step();\n },\n runBatch: (count) => {\n host.circuit?.runBatch(count);\n },\n }) as DeviceAccessorsOf<I>,\n pinRuntimeOf(compiled),\n resetSeedsOf(compiled),\n );\n host.circuit = circuit;\n // `initialize` runs once at creation; `reset()` replays the same sequence\n // after restoring every memory to its declared initial value.\n jit.execute(compiled.entryPoints.refs.initialize, NO_ARGS, circuit.#context);\n return circuit;\n }\n\n /**\n * Runs `count` ticks inside one generated loop — the throughput path.\n *\n * The whole batch is one engine call; `tickCount` grows by `count` once the\n * call returns, so a failed batch never advances the clock.\n *\n * @throws {CircuitError} with code `invalid-count` unless `count` is a u32.\n */\n runBatch(count: number): void {\n this.#assertActive();\n if (\n typeof count !== 'number' ||\n !Number.isSafeInteger(count) ||\n count < 0 ||\n count > MAX_BATCH_TICKS\n ) {\n throw new CircuitError(\n 'invalid-count',\n `runBatch(count) needs an integer in [0, ${MAX_BATCH_TICKS}], received ${String(count)}`,\n );\n }\n if (count === 0) return;\n this.#context.virtualTime = this.#virtualTime;\n this.#jit.execute(this.#compiled.entryPoints.refs.batch, [count], this.#context);\n this.#advance(count);\n }\n\n /**\n * Advances exactly one tick — the debugging path.\n *\n * Every call is one engine entry, so prefer `runBatch` for throughput.\n */\n step(): void {\n this.#assertActive();\n this.#context.virtualTime = this.#virtualTime;\n this.#jit.execute(this.#compiled.entryPoints.refs.tick, NO_ARGS, this.#context);\n this.#advance(1);\n }\n\n /**\n * Restores every memory to its declared initial value, re-runs `initialize`\n * and resets `tickCount` to `0n`.\n *\n * Device state written by earlier ticks is discarded, so the circuit behaves\n * exactly like a freshly created one.\n */\n reset(): void {\n this.#assertActive();\n for (const seed of this.#seeds) {\n if (seed.kind === 'state') {\n this.#jit.storage.storeState(seed.ref, seed.value);\n continue;\n }\n if (seed.kind === 'bytes') {\n for (let index = 0; index < seed.values.length; index += 1) {\n this.#jit.storage.storeBytes(\n 'u8',\n 'little',\n seed.ref,\n index,\n seed.values[index] as RuntimeScalar,\n );\n }\n continue;\n }\n if (seed.kind === 'readonly-bytes') {\n try {\n this.#jit.storage.updateBytesFromBytes(seed.ref, 0, seed.values);\n } catch {\n // Read-only memories are constants unless their device explicitly\n // grants host update access (for example MCU firmware patching).\n }\n continue;\n }\n for (let index = 0; index < seed.values.length; index += 1) {\n this.#jit.storage.storeArray(seed.ref, index, seed.values[index] as RuntimeScalar);\n }\n }\n this.#tickCount = 0n;\n this.#virtualTime = 0;\n this.#context.virtualTime = 0;\n this.#jit.execute(this.#compiled.entryPoints.refs.initialize, NO_ARGS, this.#context);\n }\n\n /**\n * Reads the level one pin observes.\n *\n * A sensing pin (input, passive or bidirectional) reports the solved net\n * level; a pure driver pin reports the level it actually drives, which is\n * `false` unless it is configured push-pull.\n *\n * @throws {CircuitError} with code `pin-not-found`.\n */\n getPin(pinName: string): boolean {\n this.#assertActive();\n const pin = this.#pinRuntime(pinName);\n const storage = this.#jit.storage;\n if (pin.senses) {\n return storage.loadArray(this.#compiled.memory.input, pin.globalPinId) === true;\n }\n const mode = Number(storage.loadArray(this.#compiled.memory.mode, pin.globalPinId));\n return (\n mode === PIN_MODE.pushPull &&\n storage.loadArray(this.#compiled.memory.output, pin.globalPinId) === true\n );\n }\n\n /**\n * Forces the level of one pin from the host.\n *\n * A driver pin gets its output latch written, so the level survives the next\n * electrical solve. A sensing pin gets the solved-value slot overridden, which\n * lasts until the next tick recomputes its net.\n *\n * @throws {CircuitError} with code `pin-not-found`.\n */\n setPin(pinName: string, value: boolean): void {\n this.#assertActive();\n const pin = this.#pinRuntime(pinName);\n if (typeof value !== 'boolean') {\n throw new CircuitError(\n 'invalid-state-value',\n `Pin \"${pinName}\" needs a boolean level, received ${typeof value}`,\n { pinName },\n );\n }\n const target =\n pin.role === 'driver' ? this.#compiled.memory.output : this.#compiled.memory.input;\n this.#jit.storage.storeArray(target, pin.globalPinId, value);\n }\n\n /** Number of ticks completed since creation or the last `reset()`. */\n get tickCount(): bigint {\n this.#assertActive();\n return this.#tickCount;\n }\n\n /** Virtual tick time completed since creation or the last `reset()`. */\n get virtualTime(): number {\n this.#assertActive();\n return this.#virtualTime;\n }\n\n /** Underlying engine instance, e.g. for diagnostics or custom entries. */\n get jit(): IRInterpreter {\n this.#assertActive();\n return this.#jit;\n }\n\n /** Whether `dispose()` already ran. */\n get disposed(): boolean {\n return this.#disposed;\n }\n\n /**\n * Releases the runtime. Idempotent; every later call throws a `CircuitError`\n * with code `disposed`, including stale device accessors.\n */\n dispose(): void {\n this.#disposed = true;\n this.#tickCount = 0n;\n this.#virtualTime = 0;\n }\n\n /** @internal Shared guard of the circuit and all of its accessors. */\n #assertActive(): void {\n if (this.#disposed) {\n throw new CircuitError(\n 'disposed',\n 'Circuit has been disposed; create a new circuit to keep simulating',\n );\n }\n }\n\n #advance(count: number): void {\n this.#tickCount += BigInt(count);\n const next = this.#virtualTime + count;\n this.#virtualTime = next > MAX_VIRTUAL_TIME ? 0 : next;\n }\n\n #pinRuntime(pinName: string): PinRuntime {\n const pin = this.#pins.get(pinName);\n if (pin === undefined) {\n throw new CircuitError(\n 'pin-not-found',\n `Pin \"${pinName}\" not found. Available: ${this.#pinNames.length === 0 ? '(none)' : `[${this.#pinNames.join(', ')}]`}`,\n { pinName },\n );\n }\n return pin;\n }\n}\n\n/** Resolves every pin of the global address space into its runtime view. */\nfunction pinRuntimeOf(compiled: CompiledCircuit): ReadonlyMap<string, PinRuntime> {\n const pins = new Map<string, PinRuntime>();\n for (const [deviceId, allocation] of compiled.pins.devices) {\n for (const [pinName, pin] of allocation.resolved) {\n pins.set(\n `${deviceId}.${pinName}`,\n Object.freeze({\n globalPinId: pin.globalPinId,\n role: pin.role,\n senses: pin.senses,\n }),\n );\n }\n }\n return pins;\n}\n\n/**\n * Captures the declared initial value of every scalar memory, which is what\n * `reset()` restores before the generated `initialize` runs again.\n */\nfunction resetSeedsOf(compiled: CompiledCircuit): readonly ResetSeed[] {\n const seeds: ResetSeed[] = [];\n for (const memory of compiled.module.memories) {\n if (memory.kind === 'array') {\n seeds.push({\n kind: 'array',\n ref: memory.ref as ArrayRef,\n values: memory.initial as readonly RuntimeScalar[],\n });\n } else if (memory.kind === 'state') {\n seeds.push({\n kind: 'state',\n ref: memory.ref as StateRef,\n value: memory.initial[0] as RuntimeScalar,\n });\n } else if (memory.kind === 'bytes') {\n if (memory.writable) {\n seeds.push({\n kind: 'bytes',\n ref: memory.ref as BytesRef<false>,\n values: memory.initial as readonly RuntimeScalar[],\n });\n } else {\n seeds.push({\n kind: 'readonly-bytes',\n ref: memory.ref as BytesRef<true>,\n values: Uint8Array.from(memory.initial as readonly number[]),\n });\n }\n }\n }\n return Object.freeze(seeds);\n}\n\nfunction createEngine(compiled: CompiledCircuit, options: ResolvedRuntimeOptions): IRInterpreter {\n const base = {\n validation: compiled.validation,\n // One batch can execute hundreds of millions of instructions; the default\n // step budget is tuned for single entries, not for a loop in the IR.\n maxSteps: Number.MAX_SAFE_INTEGER,\n };\n if (options.engine === 'reference') {\n return createIRInterpreter(compiled.module, base);\n }\n return createIRJIT(compiled.module, {\n ...base,\n jit: { tierUpThreshold: 0, ...options.jit },\n });\n}\n\nfunction compileOptionsOf(options: ResolvedRuntimeOptions): CircuitCompilationOptions {\n return {\n validate: options.validateIR,\n ...(options.rails === undefined ? {} : { rails: options.rails }),\n };\n}\n\nfunction resolveOptions(options: unknown): ResolvedRuntimeOptions {\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw new CircuitError('invalid-options', 'Circuit options must be a plain object');\n }\n const candidate = options as CircuitRuntimeOptions;\n\n const engine = candidate.engine ?? 'jit';\n if (engine !== 'jit' && engine !== 'reference') {\n throw new CircuitError(\n 'invalid-options',\n `engine=${String(engine)} must be \"jit\" or \"reference\"`,\n );\n }\n\n if (candidate.validateIR !== undefined && typeof candidate.validateIR !== 'boolean') {\n throw new CircuitError('invalid-options', 'validateIR must be a boolean');\n }\n\n if (candidate.instanceId !== undefined && candidate.instanceId.length === 0) {\n throw new CircuitError('invalid-options', 'instanceId must be a non-empty string');\n }\n\n if (candidate.jit !== undefined) {\n if (\n candidate.jit === null ||\n typeof candidate.jit !== 'object' ||\n Array.isArray(candidate.jit)\n ) {\n throw new CircuitError('invalid-options', 'jit must be a JIT tuning object');\n }\n }\n\n let rails: Readonly<Record<string, boolean>> | undefined;\n if (candidate.electrical !== undefined) {\n const electrical = candidate.electrical;\n if (electrical === null || typeof electrical !== 'object' || Array.isArray(electrical)) {\n throw new CircuitError('invalid-options', 'electrical must be a plain object');\n }\n rails = electrical.rails;\n }\n\n return Object.freeze({\n engine,\n jit: candidate.jit,\n validateIR: candidate.validateIR ?? true,\n rails,\n instanceId: candidate.instanceId ?? DEFAULT_INSTANCE_ID,\n });\n}\n","import type { PayloadType } from '@mica-js/core/canvas';\nimport { deriveSchematicTopology, parseDeviceReference, symbolRole } from '@mica-js/core/schematic';\nimport type {\n DeviceReference,\n DeviceSymbolProvider,\n SchematicDocument,\n} from '@mica-js/core/schematic';\nimport { DEFAULT_RAILS } from '../compiler';\nimport type {\n CircuitCompilationInput,\n Connection,\n DeviceConfig,\n DeviceDescription,\n} from '../compiler';\nimport { Circuit } from './circuit';\nimport { CircuitError, type CircuitRuntimeOptions, type DeviceAccessor } from './types';\n\n/**\n * One endpoint a caller-supplied device declares to the simulation host.\n *\n * The simulator never guesses ports from a device type: the package that\n * resolves the reference states which payloads the device accepts and which it\n * publishes, in the same place it supplies the IR description.\n */\nexport interface SchematicDeviceTopic {\n readonly port: string;\n readonly direction: 'input' | 'output';\n readonly type: PayloadType;\n readonly title?: string;\n}\n\n/** Runtime behaviour of one schematic device package. */\nexport interface SchematicDeviceBinding {\n /** Device type, e.g. `'counter-ir'`. */\n readonly type: string;\n /** IR description: pins, states and behaviours. */\n readonly description: DeviceDescription;\n /** Instance configuration reserved for device kernels. */\n readonly config?: Readonly<Record<string, unknown>>;\n /** Endpoints the simulation host exposes; absent means the device has none. */\n readonly topics?: readonly SchematicDeviceTopic[];\n /** Bridges one input topic payload onto the compiled device accessor. */\n deliver?(accessor: DeviceAccessor, port: string, payload: unknown): void;\n /** Reads one output topic from the compiled device accessor. */\n read?(accessor: DeviceAccessor, port: string): unknown;\n}\n\n/** Options for {@link createCircuitFromSchematic}. */\nexport interface SchematicCircuitOptions extends CircuitRuntimeOptions {\n /**\n * Symbol geometry provider — pass the same provider that authored the\n * schematic. Without it the derived topology contains no pins.\n */\n readonly devices?: DeviceSymbolProvider;\n /** Resolves a schematic device reference to its runtime description. */\n readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n /** Coordinate tolerance used when matching pins to wires. */\n readonly tolerance?: number;\n}\n\n/**\n * Compiles a schematic sheet into a circuit.\n *\n * Nets come from `deriveSchematicTopology`, so wires, junctions, labels and\n * power symbols keep their usual meaning: a net that names a rail connects\n * every member to that rail, and any other net joins its pins pairwise (the\n * compiler merges transitively).\n *\n * ```ts\n * const circuit = await createCircuitFromSchematic(schematic, {\n * devices: symbolProvider,\n * resolveDevice: (reference) => bindings.get(reference.deviceId),\n * });\n * ```\n *\n * @throws {CircuitError} with code `unresolved-device` when a component symbol\n * has no binding; `SchematicError` for malformed sheets.\n */\nexport async function createCircuitFromSchematic(\n schematic: SchematicDocument,\n options: SchematicCircuitOptions,\n): Promise<Circuit> {\n return (await createSchematicCircuit(schematic, options)).circuit;\n}\n\n/** One component symbol of a compiled schematic. */\nexport interface SchematicCircuitBinding {\n /** Symbol id as written in the schematic. */\n readonly symbolId: string;\n /** Compiler-safe device id assigned to the symbol. */\n readonly deviceId: string;\n /** Parsed `\"<packageId>:<deviceId>\"` reference. */\n readonly reference: DeviceReference;\n /** Device type from the resolved runtime binding. */\n readonly type: string;\n}\n\n/** A compiled schematic circuit plus the symbol-to-device mapping it produced. */\nexport interface SchematicCircuitResult {\n readonly circuit: Circuit;\n /** Component symbols in schematic order; non-component symbols are absent. */\n readonly bindings: readonly SchematicCircuitBinding[];\n}\n\n/**\n * Compiles a schematic and reports which circuit device each symbol became.\n *\n * {@link createCircuitFromSchematic} returns only the circuit; hosts that route\n * schematic endpoints to circuit accessors need the mapping as well.\n */\nexport async function createSchematicCircuit(\n schematic: SchematicDocument,\n options: SchematicCircuitOptions,\n): Promise<SchematicCircuitResult> {\n if (\n schematic === null ||\n typeof schematic !== 'object' ||\n schematic.sheet === null ||\n typeof schematic.sheet !== 'object' ||\n !Array.isArray(schematic.sheet.symbols) ||\n !Array.isArray(schematic.sheet.wires) ||\n !Array.isArray(schematic.sheet.junctions)\n ) {\n throw new CircuitError(\n 'invalid-options',\n 'createSchematicCircuit needs a schematic with sheet.symbols, sheet.wires and sheet.junctions',\n );\n }\n if (options === null || typeof options !== 'object') {\n throw new CircuitError('invalid-options', 'createSchematicCircuit needs options');\n }\n const { resolveDevice, devices, tolerance, ...runtime } = options;\n if (typeof resolveDevice !== 'function') {\n throw new CircuitError('invalid-options', 'resolveDevice must be a function');\n }\n\n const usedIds = new Set<string>();\n const deviceIdBySymbol = new Map<string, string>();\n const deviceConfigs: DeviceConfig[] = [];\n const bindings: SchematicCircuitBinding[] = [];\n let componentCount = 0;\n\n for (const symbol of schematic.sheet.symbols) {\n if (symbolRole(symbol.device) !== 'component') continue;\n componentCount += 1;\n const reference = parseDeviceReference(symbol.device);\n const binding = reference === undefined ? undefined : resolveDevice(reference);\n if (binding === undefined) {\n throw new CircuitError(\n 'unresolved-device',\n `Symbol \"${symbol.id}\" (${symbol.device}) has no runtime device binding; resolve it in resolveDevice`,\n { deviceId: symbol.id },\n );\n }\n const deviceId = uniqueDeviceId(symbol.designator ?? symbol.id, usedIds);\n usedIds.add(deviceId);\n deviceIdBySymbol.set(symbol.id, deviceId);\n deviceConfigs.push({\n id: deviceId,\n type: binding.type,\n description: binding.description,\n ...(binding.config === undefined ? {} : { config: binding.config }),\n });\n if (reference !== undefined) {\n bindings.push({\n symbolId: symbol.id,\n deviceId,\n reference,\n type: binding.type,\n });\n }\n }\n\n const topology = deriveSchematicTopology(schematic, {\n ...(devices === undefined ? {} : { devices }),\n ...(tolerance === undefined ? {} : { tolerance }),\n });\n if (componentCount > 0 && topology.pins.length === 0) {\n throw new CircuitError(\n 'invalid-options',\n 'The derived topology has no pins; pass the DeviceSymbolProvider that authored the schematic so pins can be located',\n );\n }\n\n const railNames = new Set([\n ...Object.keys(DEFAULT_RAILS),\n ...Object.keys(options.electrical?.rails ?? {}),\n ]);\n const connections: Connection[] = [];\n\n for (const net of topology.nets) {\n const endpoints: string[] = [];\n let rail: string | undefined;\n for (const member of net.members) {\n if (member.kind === 'pin') {\n const deviceId = deviceIdBySymbol.get(member.symbolId);\n if (deviceId === undefined) {\n throw new CircuitError(\n 'unresolved-device',\n `Net \"${net.name ?? 'anonymous'}\" references pin \"${member.pinId}\" of symbol \"${member.symbolId}\", which has no runtime device`,\n { deviceId: member.symbolId },\n );\n }\n endpoints.push(`${deviceId}.${member.pinId}`);\n continue;\n }\n if (member.kind === 'power' || member.kind === 'ground') {\n rail = net.name ?? rail;\n }\n }\n if (endpoints.length === 0) continue;\n // A named net that matches a rail ties its pins to that rail; everything\n // else is joined to the first pin, which the compiler merges transitively.\n const railName = rail ?? (net.name !== null && railNames.has(net.name) ? net.name : undefined);\n if (railName !== undefined) {\n for (const endpoint of endpoints) connections.push({ from: endpoint, to: railName });\n continue;\n }\n const first = endpoints[0] as string;\n for (const endpoint of endpoints.slice(1)) connections.push({ from: first, to: endpoint });\n }\n\n const input: CircuitCompilationInput = {\n devices: Object.freeze(deviceConfigs),\n connections: Object.freeze(connections),\n };\n const circuit = await Circuit.create(input, runtime);\n return Object.freeze({ circuit, bindings: Object.freeze(bindings) });\n}\n\n/**\n * Turns a designator or symbol id into a compiler-safe device id.\n *\n * Device ids prefix generated IR function names, so they must be identifiers.\n */\nfunction uniqueDeviceId(preferred: string, used: ReadonlySet<string>): string {\n const base = sanitizeDeviceId(preferred);\n if (!used.has(base)) return base;\n for (let suffix = 2; ; suffix += 1) {\n const candidate = `${base}_${suffix}`;\n if (!used.has(candidate)) return candidate;\n }\n}\n\nfunction sanitizeDeviceId(value: string): string {\n const cleaned = value.replace(/[^A-Za-z0-9_]/g, '_');\n if (cleaned.length === 0) return 'device';\n return /^[A-Za-z_]/.test(cleaned) ? cleaned : `d_${cleaned}`;\n}\n","import type { SchematicDocument } from '@mica-js/core/schematic';\nimport type { CanvasBindingTarget } from '@mica-js/core/canvas';\nimport { toDisposable } from '@mica-js/core/lifecycle';\nimport type { Circuit } from '../unified-ir/runtime';\nimport type { DeviceSimulationHost, DeviceSimTickReport, DeviceTopic } from './types';\n\n/** Picoseconds per circuit step used when mapping `Circuit.virtualTime` to simulation time. */\nconst DEFAULT_STEP_PS = 10_000;\n\nexport interface CircuitDeviceSimulationHostOptions {\n /** Circuit the caller already created. */\n readonly circuit: Circuit;\n /** Whether `dispose()` also disposes the circuit. Defaults to `true`. */\n readonly ownsCircuit?: boolean;\n /** Schematic the circuit was built from, reported through `getSchematic`. */\n readonly schematic?: SchematicDocument;\n /** Endpoints the running devices expose. */\n readonly topics?: readonly DeviceTopic[];\n /** Picoseconds per circuit step. Defaults to 10 ns. */\n readonly stepPs?: number;\n /** Routes one widget payload into the caller's device layer. */\n readonly deliver: (symbol: string, port: string, payload: unknown) => void;\n}\n\n/**\n * Adapts one already-loaded unified-IR circuit to the RFC 0018 device host.\n *\n * This is the same-thread adapter for an owner that keeps `Circuit` accessors for itself (a\n * diagnostics bench, for example). Application/canvas integration uses\n * `createDeviceSimulationHostFromSandbox` from `@mica-js/simulator/sandbox` and never holds a circuit.\n */\nexport function createCircuitDeviceSimulationHost({\n circuit,\n ownsCircuit = true,\n schematic,\n topics = [],\n stepPs = DEFAULT_STEP_PS,\n deliver,\n}: CircuitDeviceSimulationHostOptions): DeviceSimulationHost {\n const simTime = (): number => circuit.virtualTime * stepPs;\n\n return {\n async loadSchematic() {\n // The caller built the circuit before constructing this adapter.\n },\n async reset() {\n circuit.reset();\n },\n async tick(dt: number): Promise<DeviceSimTickReport> {\n if (!Number.isSafeInteger(dt) || dt <= 0) {\n throw new TypeError(\n `DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`,\n );\n }\n circuit.runBatch(1);\n return { simTime: simTime(), executed: 1 };\n },\n async deliver(target: CanvasBindingTarget, payload: unknown) {\n deliver(target.symbol, target.port, payload);\n },\n onDidPublish: () =>\n toDisposable(() => {\n // The owner drives publishing through its own device layer.\n }),\n async getTopics() {\n return topics;\n },\n async getSimTime() {\n return simTime();\n },\n async getSchematic() {\n return schematic;\n },\n async dispose() {\n if (ownsCircuit) circuit.dispose();\n },\n };\n}\n","import type { DeviceReference, DeviceSymbolProvider } from '@mica-js/core/schematic';\nimport { parseSchematic } from '@mica-js/core/schematic';\nimport type { SchematicDocument } from '@mica-js/core/schematic';\nimport type { CanvasBindingTarget, PayloadType } from '@mica-js/core/canvas';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport { createSchematicCircuit } from '../unified-ir/runtime';\nimport type { Circuit, SchematicDeviceBinding, SchematicDeviceTopic } from '../unified-ir/runtime';\nimport type { DeviceAccessor } from '../unified-ir/runtime/types';\nimport type {\n DeviceSimulationHost,\n DeviceSimTickReport,\n DeviceTopic,\n SimulationPublish,\n} from './types';\n\n/** Reads the bytes of one schematic URI; the caller resolves relative references. */\nexport interface SchematicDeviceSimulationHostOptions {\n readonly read: (uri: string) => Promise<Uint8Array>;\n /**\n * Symbol geometry of the schematics this host loads. Pass the same provider the schematic was\n * authored with; without it the derived topology contains no pins. A factory is called when a\n * schematic loads, so a caller can read its device library first.\n */\n readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);\n /**\n * Resolves one schematic device reference to its runtime description and endpoints.\n *\n * The host ships no device models: the package that owns the devices decides which references\n * exist, what they look like and which topics they expose.\n */\n readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n}\n\ninterface LoadedDevice {\n readonly symbol: string;\n readonly designator: string;\n readonly binding: SchematicDeviceBinding;\n readonly accessor: DeviceAccessor;\n}\n\ninterface LoadedRuntime {\n readonly circuit: Circuit;\n readonly schematic: SchematicDocument;\n readonly devices: readonly LoadedDevice[];\n readonly topics: readonly DeviceTopic[];\n readonly inputs: ReadonlyMap<string, InputBinding>;\n}\n\ninterface InputBinding {\n readonly device: LoadedDevice;\n readonly topic: SchematicDeviceTopic;\n}\n\ninterface PendingDelivery {\n readonly device: LoadedDevice;\n readonly port: string;\n readonly payload: unknown;\n}\n\nconst INSTANCE_ID = 'device-simulation-host';\n\nfunction targetKey(deviceId: string, port: string): string {\n return `${deviceId}\\u0000${port}`;\n}\n\n/**\n * Value equality of two topic payloads.\n *\n * A canvas topic is a `level` unless it carries text or bytes (RFC 0017), so re-sending the value a\n * device already published only costs a widget repaint. Byte payloads compare by content because a\n * device may hand out a fresh buffer per step.\n */\nfunction samePayload(previous: unknown, next: unknown): boolean {\n if (Object.is(previous, next)) return true;\n if (previous instanceof Uint8Array && next instanceof Uint8Array) {\n if (previous.length !== next.length) return false;\n for (let index = 0; index < previous.length; index += 1) {\n if (previous[index] !== next[index]) return false;\n }\n return true;\n }\n if (typeof previous !== 'object' || previous === null) return false;\n if (typeof next !== 'object' || next === null) return false;\n const a = previous as { readonly x?: unknown; readonly y?: unknown; readonly z?: unknown };\n const b = next as { readonly x?: unknown; readonly y?: unknown; readonly z?: unknown };\n return a.x === b.x && a.y === b.y && a.z === b.z;\n}\n\nfunction isVec2d(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) return false;\n const point = value as { readonly x?: unknown; readonly y?: unknown };\n return typeof point.x === 'number' && typeof point.y === 'number';\n}\n\nfunction payloadMatches(type: PayloadType, payload: unknown): boolean {\n switch (type) {\n case 'boolean':\n return typeof payload === 'boolean';\n case 'number':\n return typeof payload === 'number';\n case 'string':\n return typeof payload === 'string';\n case 'bytes':\n case 'bytes<rgb565>':\n case 'bytes<segments>':\n return payload instanceof Uint8Array;\n case 'vec2d':\n return isVec2d(payload);\n case 'vec3d':\n return isVec2d(payload) && typeof (payload as { readonly z?: unknown }).z === 'number';\n }\n}\n\nfunction decodeSchematic(bytes: Uint8Array): SchematicDocument {\n return parseSchematic(new TextDecoder().decode(bytes));\n}\n\nfunction buildRuntime(\n circuit: Circuit,\n schematic: SchematicDocument,\n bindings: Awaited<ReturnType<typeof createSchematicCircuit>>['bindings'],\n resolveDevice: SchematicDeviceSimulationHostOptions['resolveDevice'],\n): LoadedRuntime {\n const symbols = new Map(schematic.sheet.symbols.map((symbol) => [symbol.id, symbol]));\n const devices: LoadedDevice[] = [];\n const topics: DeviceTopic[] = [];\n const inputs = new Map<string, InputBinding>();\n\n for (const binding of bindings) {\n const deviceBinding = resolveDevice(binding.reference);\n const accessor = circuit.devices[binding.deviceId];\n if (deviceBinding === undefined || accessor === undefined) continue;\n const symbol = symbols.get(binding.symbolId);\n const designator = symbol?.designator ?? binding.symbolId;\n const device: LoadedDevice = {\n symbol: binding.symbolId,\n designator,\n binding: deviceBinding,\n accessor,\n };\n devices.push(device);\n for (const topic of deviceBinding.topics ?? []) {\n topics.push({\n symbol: binding.symbolId,\n designator,\n port: topic.port,\n direction: topic.direction,\n type: topic.type,\n ...(topic.title === undefined ? {} : { title: topic.title }),\n });\n if (topic.direction === 'input')\n inputs.set(targetKey(binding.symbolId, topic.port), { device, topic });\n }\n }\n\n return {\n circuit,\n schematic,\n devices,\n topics: Object.freeze(topics),\n inputs,\n };\n}\n\n/**\n * Same-thread `DeviceSimulationHost` over a schematic compiled by the unified-IR runtime.\n *\n * The host owns the circuit: `loadSchematic` reads, parses and compiles it, `tick` advances one\n * circuit step and publishes the output topics that changed, and `deliver` queues widget payloads\n * for the next step. Device models and their endpoints come from `resolveDevice`, so the host stays\n * generic. Nothing here touches the DOM, so the sandbox guest and a Node test use the same\n * implementation.\n */\nexport function createSchematicDeviceSimulationHost(\n options: SchematicDeviceSimulationHostOptions,\n): DeviceSimulationHost {\n if (typeof options?.resolveDevice !== 'function') {\n throw new TypeError('createSchematicDeviceSimulationHost needs a resolveDevice function');\n }\n const { read, devices: symbols, resolveDevice } = options;\n const publishes = new Emitter<SimulationPublish>();\n const pending: PendingDelivery[] = [];\n /** Last payload published per endpoint, so an unchanged level topic stays silent. */\n const published = new Map<string, unknown>();\n let runtime: LoadedRuntime | undefined;\n let simTimePs = 0;\n let disposed = false;\n\n const publishOutputs = (active: LoadedRuntime): void => {\n if (!publishes.hasListeners) return;\n for (const device of active.devices) {\n for (const topic of device.binding.topics ?? []) {\n if (topic.direction !== 'output' || device.binding.read === undefined) continue;\n const key = targetKey(device.symbol, topic.port);\n const payload = device.binding.read(device.accessor, topic.port);\n // Only a change is news to a level port; repeating it would make every widget repaint on\n // every step the circuit does not touch.\n if (published.has(key) && samePayload(published.get(key), payload)) continue;\n published.set(key, payload);\n const publish: SimulationPublish = {\n target: { symbol: device.symbol, port: topic.port },\n payload,\n simTime: simTimePs,\n };\n publishes.fire(publish);\n }\n }\n };\n\n const clearRuntime = (): void => {\n runtime?.circuit.dispose();\n runtime = undefined;\n pending.length = 0;\n published.clear();\n simTimePs = 0;\n };\n\n return {\n async loadSchematic(uri: string | undefined): Promise<void> {\n if (disposed) return;\n if (uri === undefined) {\n clearRuntime();\n return;\n }\n const bytes = await read(uri);\n const schematic = decodeSchematic(bytes);\n const symbolProvider = typeof symbols === 'function' ? symbols() : symbols;\n const compiled = await createSchematicCircuit(schematic, {\n ...(symbolProvider === undefined ? {} : { devices: symbolProvider }),\n resolveDevice,\n instanceId: INSTANCE_ID,\n });\n const next = buildRuntime(compiled.circuit, schematic, compiled.bindings, resolveDevice);\n runtime?.circuit.dispose();\n pending.length = 0;\n // A fresh runtime starts from its initial state, so the first step after it publishes again.\n published.clear();\n simTimePs = 0;\n runtime = next;\n },\n\n async reset(): Promise<void> {\n if (disposed) return;\n pending.length = 0;\n published.clear();\n simTimePs = 0;\n runtime?.circuit.reset();\n },\n\n async tick(dt: number): Promise<DeviceSimTickReport> {\n if (!Number.isSafeInteger(dt) || dt <= 0) {\n throw new TypeError(\n `DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`,\n );\n }\n if (disposed) {\n return { simTime: simTimePs, executed: 0 };\n }\n const active = runtime;\n if (active === undefined) {\n simTimePs += dt;\n return { simTime: simTimePs, executed: 0 };\n }\n const queued = pending.splice(0, pending.length);\n for (const delivery of queued) {\n if (delivery.device.binding.deliver === undefined) {\n throw new TypeError(\n `${delivery.device.binding.type} has no writable topic ${JSON.stringify(delivery.port)}`,\n );\n }\n delivery.device.binding.deliver(delivery.device.accessor, delivery.port, delivery.payload);\n }\n active.circuit.runBatch(1);\n simTimePs += dt;\n publishOutputs(active);\n return { simTime: simTimePs, executed: 1 };\n },\n\n async deliver(target: CanvasBindingTarget, payload: unknown): Promise<void> {\n if (disposed) return;\n const active = runtime;\n if (active === undefined) {\n throw new Error('DeviceSimulationHost has no loaded schematic');\n }\n const binding = active.inputs.get(targetKey(target.symbol, target.port));\n if (binding === undefined) {\n throw new Error(`Unknown device input ${target.symbol}.${target.port}`);\n }\n if (!payloadMatches(binding.topic.type, payload)) {\n throw new TypeError(\n `${target.symbol}.${target.port} expects a ${binding.topic.type} payload`,\n );\n }\n const device = binding.device;\n if (device.binding.deliver === undefined) {\n throw new Error(\n `${device.binding.type} has no writable topic ${JSON.stringify(target.port)}`,\n );\n }\n pending.push({ device, port: target.port, payload });\n },\n\n onDidPublish: publishes.event,\n\n async getTopics(): Promise<readonly DeviceTopic[]> {\n return runtime?.topics ?? [];\n },\n\n async getSimTime(): Promise<number> {\n return simTimePs;\n },\n\n async getSchematic(): Promise<SchematicDocument | undefined> {\n return runtime?.schematic;\n },\n\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n publishes.dispose();\n clearRuntime();\n },\n };\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport { loggerService } from '@mica-js/core/logging';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { DeviceReference, DeviceSymbolProvider } from '@mica-js/core/schematic';\nimport type { SchematicDeviceBinding } from '../unified-ir/runtime';\nimport { deviceSimulationHostFileSystemService, deviceSimulationHostGuestService } from './rpc';\nimport type { DeviceSimulationHostRpc } from './rpc';\nimport { createSchematicDeviceSimulationHost } from './runtime';\n\n/**\n * Device wiring a worker script hands to {@link startDeviceSimulationHostGuest}.\n *\n * The simulator ships no device models, so every option defaults to \"knows no references\": a\n * package that owns devices bundles its own worker script and supplies these.\n */\nexport interface DeviceSimulationHostGuestOptions {\n /** Symbol geometry of the schematics this guest loads, or a factory called per load. */\n readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);\n /** Resolves a schematic device reference; when omitted every reference stays unresolved. */\n readonly resolveDevice?: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n /**\n * Awaited before the first schematic load, so a device library can be read through the host file\n * system before anything compiles. Runs at most once.\n */\n readonly prepare?: () => Promise<void>;\n /**\n * Extra ports the worker received in the first ordinary message. The RPC port comes first, so these are\n * `event.ports` from index 1 onward, in the order the caller transferred them. The first one is\n * the direct topic channel (RFC 0018): the widget guest holds the other end and talks to this\n * guest without the host relaying.\n */\n readonly ports?: readonly MessagePort[];\n}\n\n/** Running guest: where the typed services live and which ports the worker was handed. */\nexport interface DeviceSimulationHostGuest {\n /**\n * Endpoint the typed device simulation services are registered on. A worker script that owns\n * further capabilities registers them here instead of opening a second sandbox channel.\n */\n readonly rpc: RpcEndpoint;\n /** Extra startup ports, in the order the worker received them. */\n readonly ports: readonly MessagePort[];\n /** Releases the circuit and closes the endpoint. */\n dispose(): Promise<void>;\n}\n\n/**\n * Registers RFC 0018's device simulation services on a sandbox RPC port.\n *\n * A worker script obtains the port from `event.ports[0]` and calls this function; nothing else is\n * needed, because the guest is a plain module the `@mica-js/sandbox/vite` plugin bundles into a\n * self-contained script. The guest registers `deviceSimulationHostGuestService` and reads schematics\n * through `deviceSimulationHostFileSystemService`, so schematic bytes never enter the guest's own\n * message handling and every payload is a typed RPC DTO.\n */\nexport function startDeviceSimulationHostGuest(\n port: MessagePort,\n options: DeviceSimulationHostGuestOptions = {},\n): DeviceSimulationHostGuest {\n const { devices, resolveDevice, prepare, ports = [] } = options;\n const rpc = createRpc(port);\n const logger = rpc.getProxy(loggerService);\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'guest-started',\n data: [{ extraPortCount: ports.length }],\n })\n .catch(() => undefined);\n const files = rpc.getProxy(deviceSimulationHostFileSystemService);\n const host = createSchematicDeviceSimulationHost({\n async read(uri: string): Promise<Uint8Array> {\n const bytes = await files.read(uri);\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError(`DeviceSimulationHost file system returned ${typeof bytes} for ${uri}`);\n }\n return bytes;\n },\n ...(devices === undefined ? {} : { devices }),\n resolveDevice: resolveDevice ?? (() => undefined),\n });\n\n let prepared: Promise<void> | undefined;\n const ensurePrepared = async (): Promise<void> => {\n if (prepare === undefined) return;\n prepared ??= prepare();\n try {\n await prepared;\n } catch (error) {\n // A failed preparation must not poison later loads: forget it so the next call retries.\n prepared = undefined;\n throw error;\n }\n };\n\n const service: DeviceSimulationHostRpc = {\n async loadSchematic(uri: string | undefined): Promise<void> {\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'load-schematic-start',\n data: [uri],\n })\n .catch(() => undefined);\n try {\n if (uri !== undefined) await ensurePrepared();\n await host.loadSchematic(uri);\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'load-schematic-end',\n data: [uri],\n })\n .catch(() => undefined);\n } catch (error) {\n void logger\n .write({\n level: 'error',\n scope: 'device-simulation',\n message: 'load-schematic-failed',\n data: [uri, String(error)],\n })\n .catch(() => undefined);\n throw error;\n }\n },\n async reset(): Promise<void> {\n await ensurePrepared();\n return host.reset();\n },\n tick: (dt: number) => host.tick(dt),\n deliver: (target, payload, simTime) => host.deliver(target, payload, simTime),\n onDidPublish: (listener) => {\n const subscription = host.onDidPublish(listener);\n return () => subscription.dispose();\n },\n getTopics: () => host.getTopics(),\n getSimTime: () => host.getSimTime(),\n getSchematic: () => host.getSchematic(),\n dispose: () => host.dispose(),\n };\n\n const registration = rpc.register(deviceSimulationHostGuestService, service);\n\n // The direct topic channel registers the same contract on the extra port, so the widget guest can\n // deliver and subscribe without the host in between. It only calls `deliver` and `onDidPublish`;\n // schematic, topics and the clock stay the host's business.\n const topicPort = ports[0];\n const topicRpc = topicPort === undefined ? undefined : createRpc(topicPort);\n const topicRegistration = topicRpc?.register(deviceSimulationHostGuestService, service);\n\n let disposed = false;\n return {\n rpc,\n ports,\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n topicRegistration?.dispose();\n topicRpc?.dispose();\n registration.dispose();\n await host.dispose();\n rpc.dispose();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAcA,SAAgB,uBACd,QACA,kBAAuC,CAAC,GACnB;CACrB,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,MAAM,OAAO,WAAW;EACjC,MAAM,OAAO,GAAG;EAChB,IAAI,SAAS,KAAA,GAAW;EAExB,KAAK,MAAM,SAAS,KAAK,QAAQ;GAC/B,KAAK,MAAM,eAAe,MAAM,cAAc,MAAM,IAAI,YAAY,EAAE;GACtE,IAAI,MAAM,eAAe,KAAA,GAAW,MAAM,IAAI,MAAM,WAAW,IAAI;EACrE;CACF;CACA,MAAM,eAAe,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC;CAC7C,MAAM,YAAoC,OAAO,SAAS,KAAK,WAC7D,OAAO,OAAO;EACZ,KAAK,OAAO;EACZ,QAAQ,OAAO,WAAY,eAA0B;CACvD,CAAC,CACH;CAGA,MAAM,WAAW,IAAI,IAAI,OAAO,SAAS,KAAK,WAAW,OAAO,GAAG,CAAC;CACpE,KAAK,MAAM,OAAO,IAAI,IAAI,eAAe,GAAG;EAC1C,IAAI,CAAC,SAAS,IAAI,GAAG,GAAG;EACxB,UAAU,KAAK,OAAO,OAAO;GAAE;GAAK,QAAQ;EAAkB,CAAC,CAAC;CAClE;CACA,OAAO,OAAO,OAAO;EACnB,uBAAuB;EACvB,wBAAwB;EACxB,WAAW,OAAO,OAAO,SAAS;CACpC,CAAC;AACH;;;;;;;;;;;;;ACpCA,IAAa,uBAAuB;;AAGpC,IAAa,oBAAoB;;AAGjC,IAAa,WAAW,OAAO,OAAO;CACpC,OAAO;CACP,UAAU;CACV,WAAW;CACX,QAAQ;AACV,CAAU;;;;AC0aV,IAAa,yBAAb,cAA4C,MAAM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M,eAAe;GACrB,OAAO,KAAK,MAAM;EACpB;EACA,OAAO,OAAe,KAAK,KAAK,EAAE;EAClC,UAAU,QAAQ,SAAS,YAAY,KAAK,QAAQ,QAAQ,SAAS,OAAO;EAC5E,eAAe,aAAa;GAC1B,MAAM,eAAe,KAAK,aAAa,QAAQ;GAC/C,aAAa,aAAa,QAAQ;EACpC;EACA,iBAAiB,KAAK,UAAU;EAChC,kBAAkB,KAAK,WAAW;EAClC,oBAAoB,KAAK,aAAa;EACtC,eAAe,KAAK,QAAQ;CAC9B;CAEA,MAAM,eAAe,IAAI,SAAS,kCAAkC,OAAO;CAK3E,MAAM,YAAY,MAAM;CACxB,MAAM,WAAW,cAAc,KAAA,IAAY,KAAA,IAAY,UAAU,SAAS;CAC1E,MAAM,oBAAoB,UAAU,SAAS,kCAAkC,OAAO;CAEtF,IAAI,WAAW;CACf,OAAO;EACL;EACA;EACA,MAAM,UAAyB;GAC7B,IAAI,UAAU;GACd,WAAW;GACX,mBAAmB,QAAQ;GAC3B,UAAU,QAAQ;GAClB,aAAa,QAAQ;GACrB,MAAM,KAAK,QAAQ;GACnB,IAAI,QAAQ;EACd;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/unified-ir/validation.ts","../src/unified-ir/pin-space.ts","../src/unified-ir/compiler/types.ts","../src/unified-ir/compiler/allocator.ts","../src/unified-ir/compiler/device-gen.ts","../src/electrical-authoring.ts","../src/unified-ir/compiler/electrical-network.ts","../src/unified-ir/compiler/floating-input.ts","../src/unified-ir/compiler/resistive-solver.ts","../src/unified-ir/compiler/electrical-operations.ts","../src/unified-ir/compiler/electrical-compilation.ts","../src/unified-ir/compiler/mainloop-gen.ts","../src/unified-ir/compiler/index.ts","../src/unified-ir/runtime/types.ts","../src/unified-ir/runtime/bridge.ts","../src/unified-ir/runtime/circuit.ts","../src/unified-ir/runtime/factory.ts","../src/host/runtime.ts","../src/host/guest.ts"],"sourcesContent":["import type { BytesRef, IRModule, IRResourcePermission, IRValidationOptions } from '@mica-js/ir';\n\n/**\n * Builds the validation grants a module needs to run on the reference engine or\n * the JIT: every instruction the model uses, authorized once, plus a grant for\n * each declared memory.\n *\n * `@mica-js/ir` deliberately keeps its core instruction list internal, so the\n * names are collected from the generated bodies instead of being restated here.\n *\n * @param module - Generated module whose bodies and memories are granted.\n * @param updateResources - Read-only byte regions that opt into the host-only\n * versioned update path (for example MCU firmware patching).\n */\nexport function createModuleValidation(\n module: IRModule,\n updateResources: readonly BytesRef[] = [],\n): IRValidationOptions {\n const names = new Set<string>();\n for (const fn of module.functions) {\n const body = fn.body;\n if (body === undefined) continue;\n // `body.blocks` already contains the entry block.\n for (const block of body.blocks) {\n for (const instruction of block.instructions) names.add(instruction.op);\n if (block.terminator !== undefined) names.add(block.terminator.kind);\n }\n }\n const instructions = Object.freeze([...names]);\n const resources: IRResourcePermission[] = module.memories.map((memory) =>\n Object.freeze({\n ref: memory.ref,\n access: memory.writable ? ('read-write' as const) : ('read' as const),\n }),\n );\n // Read-only byte regions such as firmware stay unreadable to guest stores but\n // can opt into the host-only versioned update path (`patchFirmware`).\n const memories = new Set(module.memories.map((memory) => memory.ref));\n for (const ref of new Set(updateResources)) {\n if (!memories.has(ref)) continue;\n resources.push(Object.freeze({ ref, access: 'update' as const }));\n }\n return Object.freeze({\n supportedInstructions: instructions,\n authorizedInstructions: instructions,\n resources: Object.freeze(resources),\n });\n}\n","/**\n * Shared memory-layout constants of the unified IR compiler and devices.\n *\n * Every device of a circuit shares one global pin address space, so the\n * compiler and every device kernel must agree on the capacity, the per-device\n * stride and the physical output configuration values. Capacity and stride are limits\n * checked at allocation time; the shared pin memories are sized to the pins a\n * circuit actually declares, so a larger ceiling costs no runtime memory.\n */\n\n/** Global pin addresses available to one circuit (8 devices x 512 pins). */\nexport const UNIFIED_PIN_CAPACITY = 4096;\n\n/** Global pin addresses one device may own; enough for the largest packages. */\nexport const DEVICE_PIN_STRIDE = 512;\n\n/** Physical output configuration values. */\nexport const PIN_MODE = Object.freeze({\n highZ: 0,\n pushPull: 1,\n openDrain: 2,\n analog: 3,\n} as const);\n\n/** One physical output configuration value. */\nexport type PinMode = (typeof PIN_MODE)[keyof typeof PIN_MODE];\n","import type { PropertyValue } from '@mica-js/core/schematic';\nimport type {\n ContactDeclaration,\n ElectricalFactoryContext,\n ResistorDeclaration,\n} from '../../electrical-authoring';\nimport type {\n ArrayRef,\n BytesRef,\n FunctionBuilder,\n FunctionRef,\n EntryRef,\n RuntimeScalar,\n IRModule,\n IRValidationOptions,\n ScalarType,\n StateRef,\n Value,\n} from '@mica-js/ir';\n\n/**\n * Types for the unified IR compiler (U01).\n *\n * The compiler turns several device descriptions plus a pin-to-pin netlist into\n * one `@mica-js/ir` module. Device logic, the electrical solve and the main\n * loop all share one global pin space, one state space and one engine entry, so\n * a tick costs one interpreter/JIT call for the whole circuit.\n *\n * The shared constants (`UNIFIED_PIN_CAPACITY`, `DEVICE_PIN_STRIDE`, `PIN_MODE`)\n * live in `../pin-space` and are reused here. The compiler ships no device\n * models: every description is supplied by the caller.\n */\n\n/** One pin declared by the paired electrical device definition. */\nexport interface DevicePinDescription {\n readonly kind: 'signal' | 'power' | 'gnd';\n readonly side?: 'left' | 'right' | 'top' | 'bottom';\n}\n\n/**\n * Declared pins of one device. A `Map` keeps duplicate names impossible and an\n * object keeps authored descriptions terse; both preserve declaration order.\n */\nexport type DevicePinMap =\n ReadonlyMap<string, DevicePinDescription> | Readonly<Record<string, DevicePinDescription>>;\n\n/** One scalar internal state of a device, allocated in the global state space. */\nexport interface DeviceStateDescription {\n readonly type: ScalarType;\n readonly initial: boolean | number;\n}\n\n/** Pin operations a behavior may use; each call inlines into global memory. */\nexport interface DevicePinHandle {\n readonly name: string;\n readonly globalId: number;\n /** Selects the physical output configuration. */\n configure(mode: number): void;\n setOutputEnabled(enabled: Value<'bool'>): void;\n setPull(pull: 'none' | 'up' | 'down'): void;\n writeVoltage(voltage: Value<'f64'>): void;\n /** Writes digital drive intent through the finite output impedance. */\n writeDigital(level: Value<'bool'>): void;\n /** Samples the solved voltage with the explicitly declared input thresholds. */\n sampleDigital(): Value<'bool'>;\n sampleVoltage(): Value<'f64'>;\n /** Reads this pin's digital drive intent. */\n readDrivenDigital(): Value<'bool'>;\n}\n\nexport interface DeviceResistorHandle {\n setResistance(ohms: Value<'f64'>): void;\n setEnabled(enabled: Value<'bool'>): void;\n /** Solved current in amperes, positive from the first declared pin to the second. */\n sampleCurrent(): Value<'f64'>;\n}\n\n/** Internal state slot a behavior may read and write. */\nexport interface DeviceStateHandle<T extends ScalarType = ScalarType> {\n readonly name: string;\n readonly type: T;\n /** Index inside the generated `device_state_<type>` array. */\n readonly index: number;\n load(): Value<T>;\n store(value: Value<T>): void;\n}\n\n/** One pin as seen by a device kernel factory (no builder attached yet). */\nexport interface DeviceKernelPin {\n readonly name: string;\n readonly globalPinId: number;\n}\n\n/**\n * Everything a complex device kernel needs to declare its own IR before any\n * phase function body is opened: the module (for `array`/`bytes`/`provider`),\n * typed operations through `bind(builder)` and the allocated pin ids.\n */\nexport interface DeviceKernelContext {\n readonly deviceId: string;\n readonly config: Readonly<Record<string, unknown>> | undefined;\n readonly module: IRModule;\n bind(builder: FunctionBuilder<readonly []>): DeviceBehaviorApi;\n readonly pins: readonly DeviceKernelPin[];\n}\n\n/**\n * Direct phase refs a complex kernel may return instead of behaviour hooks.\n * The compiler then uses these functions as the device's loop entries, with\n * no wrapper phase around them.\n */\nexport interface DeviceKernelRuntime {\n readonly initialize?: FunctionRef<readonly [], readonly []>;\n readonly tick?: FunctionRef<readonly [], readonly []>;\n readonly update?: FunctionRef<readonly [], readonly []>;\n}\n\n/**\n * Builds the phase hooks of a complex device after resource allocation but\n * before phase functions are generated. Declaring arrays, byte memories and\n * providers is only legal here (never inside a function body).\n *\n * Returning {@link DeviceKernelRuntime} lets the kernel own its phase\n * functions directly; returning {@link DeviceBehaviors} asks the compiler to\n * generate `<id>_initialize` / `<id>_tick` / `<id>_update` wrappers.\n */\nexport type DeviceKernelFactory = (\n context: DeviceKernelContext,\n) => DeviceBehaviors | DeviceKernelRuntime;\n\n/** Build surface handed to one device behavior. */\nexport interface DeviceBehaviorApi {\n readonly deviceId: string;\n readonly builder: FunctionBuilder<readonly []>;\n /**\n * Module the phase is generated into. Complex devices use it to declare\n * their own typed arrays (`module.array`, `module.bytes`) and providers;\n * simple devices never need to touch it.\n */\n readonly module: IRModule;\n /** Instance configuration from {@link DeviceConfig.config}. */\n readonly config: Readonly<Record<string, unknown>> | undefined;\n /** Every declared pin of the device, in declaration order. */\n readonly pins: readonly DevicePinHandle[];\n /** Pins initialized with physical drive capability. */\n readonly outputs: readonly DevicePinHandle[];\n pin(name: string): DevicePinHandle;\n resistor(name: string): DeviceResistorHandle;\n writeDigitalGroup(names: readonly string[], levels: readonly Value<'bool'>[]): void;\n applyResistors(names: readonly string[], ohms: readonly Value<'f64'>[]): void;\n applyConnections(names: readonly string[], closed: readonly Value<'bool'>[]): void;\n state<T extends ScalarType = ScalarType>(name: string): DeviceStateHandle<T>;\n}\n\n/**\n * Per-device behavior hooks. The compiler emits one IR function per hook:\n * `initialize` -> `<id>_initialize`, `tick` -> `<id>_tick`,\n * `update` -> `<id>_update`. Missing hooks simply produce no function.\n */\nexport interface DeviceBehaviors {\n readonly initialize?: (api: DeviceBehaviorApi) => void;\n readonly tick?: (api: DeviceBehaviorApi) => void;\n readonly update?: (api: DeviceBehaviorApi) => void;\n}\n\nexport interface DeviceInput {\n readonly port: string;\n readonly payload: unknown;\n}\n\nexport interface DeviceInputIo {\n takeInput(port: string): unknown;\n takeInputs(port: string): readonly unknown[];\n writeState(name: string, value: unknown): void;\n call(entry: EntryRef, args: readonly RuntimeScalar[]): void;\n}\n\nexport interface DeviceOutputIo {\n readState(name: string): unknown;\n publish(port: string, payload: unknown): void;\n}\n\nexport interface DeviceBridgeHooks {\n readonly applyInputs?: (io: DeviceInputIo) => void;\n readonly flushOutputs?: (io: DeviceOutputIo) => void;\n}\n\n/** Per-instance construction and boundary hooks returned by the paired factory. */\nexport interface DeviceImplementation extends DeviceBehaviors, DeviceBridgeHooks {\n readonly kernel?: DeviceKernelFactory;\n}\n\n/** IR-level device description consumed by the compiler. */\nexport interface DeviceDescription extends DeviceBridgeHooks {\n readonly name?: string;\n readonly pins: DevicePinMap;\n readonly properties?: Readonly<Record<string, unknown>>;\n readonly resistors?: Readonly<Record<string, ResistorDeclaration>>;\n readonly connections?: Readonly<Record<string, ContactDeclaration>>;\n /** Paired synchronous JS factory, invoked once per instance before IR generation. */\n readonly factory: (context: ElectricalFactoryContext) => DeviceImplementation | void;\n readonly states?: Readonly<Record<string, DeviceStateDescription>>;\n readonly behaviors?: DeviceBehaviors;\n /**\n * Complex-kernel hook. Runs once per module before phase generation so the\n * kernel may declare typed arrays, byte memories and providers, then return\n * the behaviour hooks the compiler should call inside each phase.\n */\n readonly kernel?: DeviceKernelFactory;\n /**\n * Read-only byte regions the kernel wants host updates for. The compiler\n * grants `update` access on top of the normal `read` grant so kernels can\n * expose firmware patching without allowing guest stores.\n */\n readonly updateResources?: readonly BytesRef[];\n}\n\n/** One device instance of the circuit. */\nexport interface DeviceConfig {\n /** Circuit-unique identity; prefix of every generated function name. */\n readonly id: string;\n /** Device type, e.g. `'push-pull-driver'`; free-form label of the device model. */\n readonly type: string;\n readonly description: DeviceDescription;\n /** Persistent instance values resolved against the JSON property declarations. */\n readonly properties?: Readonly<Record<string, PropertyValue>>;\n /** Instance configuration; reserved for device kernels that take parameters. */\n readonly config?: Readonly<Record<string, unknown>>;\n}\n\n/** One pin-to-pin (or pin-to-rail) connection. */\nexport interface Connection {\n /** `'mcu1.PA0'` or a rail name such as `'GND'`. */\n readonly from: string;\n readonly to: string;\n}\n\n/** Options for the compiler. */\nexport interface CircuitCompilationOptions {\n /** Explicit GND-referenced voltage sources; GND itself is always 0 V. */\n readonly sources?: Readonly<Record<string, { readonly voltage: number }>>;\n readonly interpretation?: 'two-state' | 'retain-in-band';\n /** Reproducible mica-floating-v2 input seed; defaults to 0. */\n readonly floatingSeed?: number;\n /** Runs `validateIR` over the generated module. Defaults to `true`. */\n readonly validate?: boolean;\n /** Overrides for the generated entry-point names. */\n readonly entryPointNames?: {\n readonly tick?: string;\n readonly initialize?: string;\n readonly batch?: string;\n };\n}\n\n/** Compiler input: devices plus the connections between their pins. */\nexport interface CircuitCompilationInput {\n readonly devices: readonly DeviceConfig[];\n readonly connections: readonly Connection[];\n}\n\n/** One resolved pin in the global pin space. */\nexport interface ResolvedDevicePin {\n readonly name: string;\n readonly deviceId: string;\n readonly globalPinId: number;\n}\n\n/** Pins of one device mapped into the global pin space. */\nexport interface DevicePinAllocation {\n readonly deviceId: string;\n /** First global pin id of the device. */\n readonly offset: number;\n readonly pins: ReadonlyMap<string, number>;\n readonly resolved: ReadonlyMap<string, ResolvedDevicePin>;\n}\n\n/** Result of the global pin allocation. */\nexport interface GlobalPinMap {\n /** `'mcu1.PA0'` -> global pin id. */\n readonly pins: ReadonlyMap<string, number>;\n readonly devices: ReadonlyMap<string, DevicePinAllocation>;\n readonly totalPins: number;\n readonly capacity: number;\n}\n\n/** One device state slot inside the global state space. */\nexport interface DeviceStateSlot {\n readonly name: string;\n readonly deviceId: string;\n readonly type: ScalarType;\n /** Generated array that holds the slot. */\n readonly array: ArrayRef;\n /** Index inside {@link array}. */\n readonly index: number;\n /** Ordinal in the whole state space, across scalar types. */\n readonly slot: number;\n}\n\n/** Result of the global state allocation. */\nexport interface GlobalStateMap {\n readonly devices: ReadonlyMap<string, ReadonlyMap<string, DeviceStateSlot>>;\n /** One generated array per scalar type actually used. */\n readonly arrays: ReadonlyMap<ScalarType, ArrayRef>;\n /** Slot count per scalar type. */\n readonly totals: ReadonlyMap<ScalarType, number>;\n readonly totalStates: number;\n}\n\n/** Metadata of one compiled device. */\nexport interface DeviceMetadata extends DeviceBridgeHooks {\n readonly deviceId: string;\n readonly entries?: readonly EntryRef[];\n readonly type: string;\n /** First global pin id of the device. */\n readonly pinOffset: number;\n /** First slot ordinal of the device in the global state space. */\n readonly stateOffset: number;\n readonly pins: ReadonlyMap<string, number>;\n readonly states: ReadonlyMap<string, DeviceStateSlot>;\n /** Every IR function generated for this device. */\n readonly functions: readonly string[];\n readonly initialize: string | undefined;\n readonly tick: string | undefined;\n readonly update: string | undefined;\n}\n\n/** Generated entry points, both by name and as executable refs. */\nexport interface CompiledEntryPoints {\n readonly tick: string;\n readonly initialize: string;\n readonly batch: string;\n readonly refs: {\n readonly tick: FunctionRef<readonly [], readonly []>;\n readonly initialize: FunctionRef<readonly [], readonly []>;\n readonly batch: FunctionRef<readonly ['u32'], readonly []>;\n };\n}\n\n/** The compiled circuit: one module for every device, net and the main loop. */\nexport interface CompiledCircuit {\n readonly module: IRModule;\n readonly entryPoints: CompiledEntryPoints;\n /** Completed ticks in the most recent step/batch, including before a fault. */\n readonly progress: StateRef<'u32'>;\n /** `'mcu1.PA0'` -> global pin id. */\n readonly pinMap: ReadonlyMap<string, number>;\n readonly deviceMap: ReadonlyMap<string, DeviceMetadata>;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n /** Validation grants covering every instruction and memory of the module. */\n readonly validation: IRValidationOptions;\n /** Device ids in stable declaration order. */\n readonly executionOrder: readonly string[];\n /** Every generated function name, in definition order. */\n readonly functions: readonly string[];\n}\n\n/** Error codes raised by {@link UnifiedIRCompilerError}. */\nexport type UnifiedIRCompilerErrorCode =\n 'invalid-input' | 'duplicate-device' | 'state-not-found' | 'capacity-exceeded' | 'invalid-ir';\n\nexport interface UnifiedIRCompilerErrorOptions {\n readonly deviceId?: string;\n readonly pinName?: string;\n readonly cause?: unknown;\n}\n\n/** Error raised while compiling a circuit. */\nexport class UnifiedIRCompilerError extends Error {\n override readonly name = 'UnifiedIRCompilerError';\n readonly code: UnifiedIRCompilerErrorCode;\n readonly deviceId: string | undefined;\n readonly pinName: string | undefined;\n\n constructor(\n code: UnifiedIRCompilerErrorCode,\n message: string,\n options: UnifiedIRCompilerErrorOptions = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.code = code;\n this.deviceId = options.deviceId;\n this.pinName = options.pinName;\n }\n}\n","import { INTEGER_TYPES, SCALAR_TYPES } from '@mica-js/ir';\nimport type { ArrayRef, IRModule, ScalarType } from '@mica-js/ir';\nimport { DEVICE_PIN_STRIDE, UNIFIED_PIN_CAPACITY } from '../pin-space';\nimport {\n UnifiedIRCompilerError,\n type DeviceConfig,\n type DevicePinAllocation,\n type DevicePinDescription,\n type DeviceStateDescription,\n type DeviceStateSlot,\n type GlobalPinMap,\n type GlobalStateMap,\n type ResolvedDevicePin,\n} from './types';\n\n/** Generated device ids prefix IR function names, so they must be identifiers. */\nconst DEVICE_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Everything the compiler allocates before a single instruction is generated. */\nexport interface ResourceAllocation {\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n}\n\n/**\n * Allocates the circuit-wide pin and state address spaces.\n *\n * ```\n * ids: 0 = drive1.PA0 1 = drive1.PA1 2 = sink1.anode 3 = sink1.cathode\n * |<-- drive1 -->| |<----------- sink1 ----------->|\n *\n * device_state_bool[n] / device_state_u32[m] / ... (one array per used type)\n * ```\n *\n * Pins are packed in declaration order across devices — the addresses the\n * device IR embeds as constants. States are packed per\n * scalar type into one shared array, so a device's slot stays typed while all\n * devices share one storage region.\n */\nexport class GlobalResourceAllocator {\n private readonly module: IRModule;\n\n constructor(module: IRModule) {\n this.module = module;\n }\n\n /** Allocates pin addresses and typed device state arrays. */\n allocate(devices: readonly DeviceConfig[]): ResourceAllocation {\n const pins = this.allocatePins(devices);\n return Object.freeze({\n pins,\n states: this.allocateStates(devices),\n });\n }\n\n /**\n * Packs every device pin into one contiguous global address space.\n *\n * @throws {UnifiedIRCompilerError} on invalid or duplicate device ids, more\n * than {@link DEVICE_PIN_STRIDE} pins for one device, or more than\n * {@link UNIFIED_PIN_CAPACITY} pins for the circuit.\n */\n allocatePins(devices: readonly DeviceConfig[]): GlobalPinMap {\n assertDeviceList(devices);\n\n let totalPins = 0;\n const pins = new Map<string, number>();\n const allocations = new Map<string, DevicePinAllocation>();\n\n for (const device of devices) {\n const entries = pinEntries(device);\n if (entries.length > DEVICE_PIN_STRIDE) {\n throw new UnifiedIRCompilerError(\n 'capacity-exceeded',\n `Device \"${device.id}\" declares ${entries.length} pins; one device may own at most ${DEVICE_PIN_STRIDE}`,\n { deviceId: device.id },\n );\n }\n if (totalPins + entries.length > UNIFIED_PIN_CAPACITY) {\n throw new UnifiedIRCompilerError(\n 'capacity-exceeded',\n `Device \"${device.id}\" does not fit: the circuit already uses ${totalPins} of ${UNIFIED_PIN_CAPACITY} global pins`,\n { deviceId: device.id },\n );\n }\n\n const offset = totalPins;\n const devicePins = new Map<string, number>();\n const resolved = new Map<string, ResolvedDevicePin>();\n\n for (const [name] of entries) {\n const globalPinId = totalPins;\n totalPins += 1;\n devicePins.set(name, globalPinId);\n resolved.set(\n name,\n Object.freeze({\n name,\n deviceId: device.id,\n globalPinId,\n }),\n );\n pins.set(`${device.id}.${name}`, globalPinId);\n }\n\n allocations.set(\n device.id,\n Object.freeze({ deviceId: device.id, offset, pins: devicePins, resolved }),\n );\n }\n\n return Object.freeze({\n pins,\n devices: allocations,\n totalPins,\n capacity: UNIFIED_PIN_CAPACITY,\n });\n }\n\n /**\n * Allocates one typed slot per declared device state and creates the backing\n * `device_state_<type>` arrays.\n *\n * @throws {UnifiedIRCompilerError} when a state declaration is malformed.\n */\n allocateStates(devices: readonly DeviceConfig[]): GlobalStateMap {\n assertDeviceList(devices);\n\n interface StatePlan {\n readonly deviceId: string;\n readonly name: string;\n readonly type: ScalarType;\n readonly initial: boolean | number;\n readonly slot: number;\n }\n\n const plans: StatePlan[] = [];\n const slotsByDevice = new Map<string, Map<string, DeviceStateSlot>>();\n const plansByType = new Map<ScalarType, StatePlan[]>();\n\n for (const device of devices) {\n // Every device owns a block in the state table, even when it is empty.\n const slots = new Map<string, DeviceStateSlot>();\n slotsByDevice.set(device.id, slots);\n for (const [name, declaration] of stateEntries(device)) {\n const plan: StatePlan = {\n deviceId: device.id,\n name,\n type: declaration.type,\n initial: declaration.initial,\n slot: plans.length,\n };\n plans.push(plan);\n const typePlans = plansByType.get(plan.type);\n if (typePlans === undefined) {\n plansByType.set(plan.type, [plan]);\n } else {\n typePlans.push(plan);\n }\n }\n }\n\n const arrays = new Map<ScalarType, ArrayRef>();\n const totals = new Map<ScalarType, number>();\n for (const [type, typePlans] of plansByType) {\n const array = this.module.array(\n `device_state_${type}`,\n type,\n typePlans.map((plan) => plan.initial),\n );\n arrays.set(type, array);\n totals.set(type, typePlans.length);\n typePlans.forEach((plan, index) => {\n const slot: DeviceStateSlot = Object.freeze({\n name: plan.name,\n deviceId: plan.deviceId,\n type,\n array,\n index,\n slot: plan.slot,\n });\n slotsByDevice.get(plan.deviceId)?.set(plan.name, slot);\n });\n }\n\n const devicesMap = new Map<string, ReadonlyMap<string, DeviceStateSlot>>();\n for (const [deviceId, slots] of slotsByDevice) devicesMap.set(deviceId, slots);\n\n return Object.freeze({\n devices: devicesMap,\n arrays,\n totals,\n totalStates: plans.length,\n });\n }\n}\n\n/** First state slot ordinal of every device; used for `DeviceMetadata.stateOffset`. */\nexport function stateOffsetOf(states: GlobalStateMap, deviceId: string): number {\n let offset = 0;\n for (const [id, slots] of states.devices) {\n if (id === deviceId) return offset;\n offset += slots.size;\n }\n return offset;\n}\n\nfunction assertDeviceList(devices: readonly DeviceConfig[]): void {\n if (!Array.isArray(devices) || devices.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.devices must be a non-empty array',\n );\n }\n const ids = new Set<string>();\n for (const device of devices as readonly unknown[]) {\n if (device === null || typeof device !== 'object' || Array.isArray(device)) {\n throw new UnifiedIRCompilerError('invalid-input', 'Every device must be an object');\n }\n const { id, type, description } = device as Partial<DeviceConfig>;\n if (typeof id !== 'string' || !DEVICE_ID_PATTERN.test(id)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device id ${JSON.stringify(id)} must be an identifier ([A-Za-z_][A-Za-z0-9_]*) because it prefixes generated IR function names`,\n );\n }\n if (ids.has(id)) {\n throw new UnifiedIRCompilerError(\n 'duplicate-device',\n `Duplicate device id \"${id}\"; every device id must be unique`,\n { deviceId: id },\n );\n }\n ids.add(id);\n if (typeof type !== 'string' || type.length === 0) {\n throw new UnifiedIRCompilerError('invalid-input', `Device \"${id}\" needs a non-empty type`, {\n deviceId: id,\n });\n }\n if (description === null || typeof description !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${id}\" needs a description object with a pins map`,\n { deviceId: id },\n );\n }\n }\n}\n\nfunction pinEntries(\n device: DeviceConfig,\n): readonly (readonly [string, DevicePinDescription | undefined])[] {\n const raw: unknown = device.description.pins;\n let entries: (readonly [string, DevicePinDescription | undefined])[];\n if (raw instanceof Map) {\n entries = [...(raw as ReadonlyMap<string, DevicePinDescription>).entries()];\n } else if (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) {\n entries = Object.entries(raw as Record<string, DevicePinDescription>) as (readonly [\n string,\n DevicePinDescription | undefined,\n ])[];\n } else {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" needs description.pins as a Map or a plain object`,\n { deviceId: device.id },\n );\n }\n for (const [name, descriptor] of entries) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" declares a pin with an empty name`,\n { deviceId: device.id },\n );\n }\n if (name.includes('.')) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" pin \"${name}\" may not contain \".\": connection endpoints use \"device.pin\"`,\n { deviceId: device.id, pinName: name },\n );\n }\n if (descriptor !== undefined && (descriptor === null || typeof descriptor !== 'object')) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" pin \"${name}\" description must be an object`,\n { deviceId: device.id, pinName: name },\n );\n }\n }\n return entries;\n}\n\nfunction stateEntries(\n device: DeviceConfig,\n): readonly (readonly [string, DeviceStateDescription])[] {\n const raw: unknown = device.description.states;\n if (raw === undefined) return [];\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" needs description.states as a plain object`,\n { deviceId: device.id },\n );\n }\n return Object.entries(raw as Record<string, DeviceStateDescription>).map(\n ([name, declaration]) => {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" declares a state with an empty name`,\n { deviceId: device.id },\n );\n }\n if (declaration === null || typeof declaration !== 'object') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" state \"${name}\" must be an object with type and initial`,\n { deviceId: device.id },\n );\n }\n const type: unknown = declaration.type;\n if (typeof type !== 'string' || !(SCALAR_TYPES as readonly string[]).includes(type)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" state \"${name}\" has type ${JSON.stringify(type)}; expected one of ${SCALAR_TYPES.join(', ')}`,\n { deviceId: device.id },\n );\n }\n assertStateInitial(device.id, name, type as ScalarType, declaration.initial);\n return [name, declaration] as const;\n },\n );\n}\n\nfunction assertStateInitial(\n deviceId: string,\n name: string,\n type: ScalarType,\n initial: unknown,\n): void {\n if (type === 'bool') {\n if (typeof initial !== 'boolean') {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (bool) needs a boolean initial value`,\n { deviceId },\n );\n }\n return;\n }\n if (typeof initial !== 'number' || !Number.isFinite(initial)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (${type}) needs a finite numeric initial value`,\n { deviceId },\n );\n }\n if ((INTEGER_TYPES as readonly string[]).includes(type) && !Number.isInteger(initial)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${deviceId}\" state \"${name}\" (${type}) needs an integer initial value`,\n { deviceId },\n );\n }\n}\n","import type {\n ArrayRef,\n EntryRef,\n FunctionBuilder,\n FunctionRef,\n IRModule,\n ScalarType,\n Value,\n} from '@mica-js/ir';\nimport type { ElectricalOperations } from './electrical-operations';\nimport { stateOffsetOf } from './allocator';\nimport {\n UnifiedIRCompilerError,\n type DeviceBehaviorApi,\n type DeviceBehaviors,\n type DeviceConfig,\n type DeviceKernelRuntime,\n type DeviceMetadata,\n type DevicePinAllocation,\n type DeviceStateHandle,\n type DeviceStateSlot,\n type GlobalPinMap,\n type GlobalStateMap,\n} from './types';\n\n/** Refs the main loop calls for one device; `undefined` means \"no such phase\". */\nexport interface DeviceLoopEntry {\n readonly deviceId: string;\n readonly initialize: FunctionRef<readonly [], readonly []> | undefined;\n readonly tick: FunctionRef<readonly [], readonly []> | undefined;\n readonly update: FunctionRef<readonly [], readonly []> | undefined;\n}\n\n/** One generated device: public metadata plus the refs the main loop needs. */\nexport interface GeneratedDevice {\n readonly metadata: DeviceMetadata;\n readonly entry: DeviceLoopEntry;\n}\n\ninterface GeneratedPhase {\n readonly name: string;\n readonly ref: FunctionRef<readonly [], readonly []>;\n}\n\n/** Everything the device generator reads from the prior compilation stages. */\nexport interface DeviceGenerationContext {\n readonly module: IRModule;\n readonly pins: GlobalPinMap;\n readonly states: GlobalStateMap;\n readonly electrical: ElectricalOperations;\n}\n\n/**\n * Generates one IR function per device phase into the unified module.\n *\n * Domain operations use the shared resistive electrical network, including\n * explicit output configuration, finite drive impedance and solved sampling.\n *\n * The compiler ships no device models: every description must declare its own\n * pins, states and behaviors (or a `kernel`) before it reaches this generator.\n */\nexport class DeviceIRGenerator {\n private readonly context: DeviceGenerationContext;\n\n constructor(context: DeviceGenerationContext) {\n this.context = context;\n }\n\n /**\n * @throws {UnifiedIRCompilerError} when a behavior reaches for a pin or state\n * the paired description does not declare.\n */\n generate(device: DeviceConfig): GeneratedDevice {\n const allocation = this.context.pins.devices.get(device.id);\n if (allocation === undefined) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" has no pin allocation; allocate resources before generating IR`,\n { deviceId: device.id },\n );\n }\n const functionOffset = this.context.module.functions.length;\n const kernelResult = device.description.kernel?.({\n deviceId: device.id,\n config: device.config,\n module: this.context.module,\n bind: (builder) => this.createApi(device, allocation, builder),\n pins: [...allocation.resolved.values()].map((pin) =>\n Object.freeze({\n name: pin.name,\n globalPinId: pin.globalPinId,\n }),\n ),\n });\n const kernelRuntime =\n kernelResult !== undefined && isKernelRuntime(kernelResult) ? kernelResult : undefined;\n const behaviors =\n kernelRuntime === undefined\n ? ((kernelResult as DeviceBehaviors | undefined) ?? device.description.behaviors)\n : undefined;\n\n let initialize: GeneratedPhase | undefined;\n let tick: GeneratedPhase | undefined;\n let update: GeneratedPhase | undefined;\n if (kernelRuntime !== undefined) {\n initialize = phaseFromRef(this.context.module, device.id, kernelRuntime.initialize);\n tick = phaseFromRef(this.context.module, device.id, kernelRuntime.tick);\n update = phaseFromRef(this.context.module, device.id, kernelRuntime.update);\n } else {\n initialize = this.generatePhase(device, allocation, 'initialize', behaviors?.initialize);\n tick = this.generatePhase(device, allocation, 'tick', behaviors?.tick);\n update = this.generatePhase(device, allocation, 'update', behaviors?.update);\n }\n\n const functions: string[] = [];\n for (const phase of [initialize, tick, update]) {\n if (phase !== undefined) functions.push(phase.name);\n }\n\n const metadata: DeviceMetadata = Object.freeze({\n deviceId: device.id,\n type: device.type,\n entries: Object.freeze(\n this.context.module.functions\n .slice(functionOffset)\n .filter((fn) => fn.category === 'entry')\n .map((fn) => fn.ref as EntryRef),\n ),\n pinOffset: allocation.offset,\n stateOffset: stateOffsetOf(this.context.states, device.id),\n pins: allocation.pins,\n states: this.context.states.devices.get(device.id) ?? new Map(),\n functions: Object.freeze(functions),\n initialize: initialize?.name,\n tick: tick?.name,\n update: update?.name,\n ...(device.description.applyInputs === undefined\n ? {}\n : { applyInputs: device.description.applyInputs }),\n ...(device.description.flushOutputs === undefined\n ? {}\n : { flushOutputs: device.description.flushOutputs }),\n });\n\n return Object.freeze({\n metadata,\n entry: Object.freeze({\n deviceId: device.id,\n initialize: initialize?.ref,\n tick: tick?.ref,\n update: update?.ref,\n }),\n });\n }\n\n private generatePhase(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n phase: 'initialize' | 'tick' | 'update',\n behavior: ((api: DeviceBehaviorApi) => void) | undefined,\n ): GeneratedPhase | undefined {\n if (behavior === undefined) return undefined;\n const name = `${device.id}_${phase}`;\n const ref = this.context.module.func(name, { params: [], results: [] });\n ref.body((b) => {\n behavior(this.createApi(device, allocation, b));\n b.return([]);\n });\n return { name, ref };\n }\n\n private createApi(\n device: DeviceConfig,\n allocation: DevicePinAllocation,\n builder: FunctionBuilder<readonly []>,\n ): DeviceBehaviorApi {\n const slots = this.context.states.devices.get(device.id);\n const electrical = this.context.electrical.bindDevice(\n device.id,\n builder,\n new Map([...allocation.resolved].map(([name, pin]) => [name, pin.globalPinId])),\n );\n return Object.freeze({\n deviceId: device.id,\n builder,\n module: this.context.module,\n config: device.config,\n pins: electrical.pins,\n outputs: electrical.outputs,\n resistor: electrical.resistor,\n writeDigitalGroup: electrical.writeDigitalGroup,\n applyResistors: electrical.applyResistors,\n applyConnections: electrical.applyConnections,\n pin: electrical.pin,\n state<T extends ScalarType = ScalarType>(name: string): DeviceStateHandle<T> {\n const slot = slots?.get(name);\n if (slot === undefined) {\n throw new UnifiedIRCompilerError(\n 'state-not-found',\n `Device \"${device.id}\" has no state \"${name}\". Available: [${[...(slots?.keys() ?? [])].join(', ')}]`,\n { deviceId: device.id },\n );\n }\n return createStateHandle<T>(device.id, slot, builder);\n },\n });\n }\n}\n\nfunction createStateHandle<T extends ScalarType>(\n deviceId: string,\n slot: DeviceStateSlot,\n builder: FunctionBuilder<readonly []>,\n): DeviceStateHandle<T> {\n // The array was declared with `slot.type`, so a matching `T` is exactly the\n // array's element type; the cast only recovers that from the untied slot.\n const array = slot.array as unknown as ArrayRef<T>;\n const index = builder.const('u32', slot.index);\n return Object.freeze({\n name: slot.name,\n type: slot.type as T,\n index: slot.index,\n load(): Value<T> {\n return builder.array.load(array, index);\n },\n store(value: Value<T>): void {\n builder.array.store(array, index, value);\n },\n });\n}\n\n/** Bulk kernel results carry phase refs; behaviour hooks are plain functions. */\nfunction isKernelRuntime(\n value: DeviceBehaviors | DeviceKernelRuntime,\n): value is DeviceKernelRuntime {\n if (value === null || typeof value !== 'object') return false;\n // A kernel may own any subset of the phases (a passive sink only needs\n // `update`), so the first phase ref that is an object — not a behaviour\n // callback — decides.\n const phases: readonly (keyof DeviceKernelRuntime)[] = ['initialize', 'tick', 'update'];\n return phases.some((phase) => typeof value[phase] === 'object');\n}\n\n/** Resolves one kernel phase ref to its generated function name. */\nfunction phaseFromRef(\n module: IRModule,\n deviceId: string,\n ref: FunctionRef<readonly [], readonly []> | undefined,\n): GeneratedPhase | undefined {\n if (ref === undefined) return undefined;\n const definition = module.functions.find((fn) => fn.ref === ref);\n if (definition === undefined) {\n throw new UnifiedIRCompilerError(\n 'invalid-ir',\n `Device \"${deviceId}\" returned a kernel phase ref that is not part of the module`,\n { deviceId },\n );\n }\n return { name: definition.name, ref };\n}\n","import { propertyValueProblem, readPropertyDescriptors } from '@mica-js/core/schematic';\nimport type { PropertyValue } from '@mica-js/core/schematic';\n\nexport interface ElectricalReference {\n readonly source: string;\n}\n\nexport interface PinElectricalDescription {\n readonly drive?: {\n readonly reference: ElectricalReference;\n readonly highResistance: number;\n readonly lowResistance: number;\n readonly analogResistance?: number;\n readonly maxAbsCurrent?: number;\n };\n readonly bias?: {\n readonly reference: ElectricalReference;\n readonly upResistance: number;\n readonly downResistance: number;\n };\n readonly input?: {\n readonly reference: ElectricalReference;\n readonly low: number;\n readonly high: number;\n };\n}\n\nexport interface ResistorInitialState {\n readonly resistance: number;\n readonly enabled: boolean;\n readonly maxAbsCurrent?: number;\n}\n\nexport interface ResistorDeclaration {\n readonly pins: readonly [string, string];\n}\n\nexport interface ContactDeclaration extends ResistorDeclaration {\n readonly initial: 'open' | 'closed';\n}\n\ninterface InitializedResistor extends ResistorDeclaration, ResistorInitialState {}\n\nexport interface DeviceElectricalInitialization {\n initializeResistor(id: string, initial: ResistorInitialState): void;\n initializePin(id: string, initial: PinElectricalDescription): void;\n}\n\nexport interface ElectricalFactoryContext {\n readonly properties: Readonly<Record<string, PropertyValue>>;\n readonly electrical: DeviceElectricalInitialization;\n}\n\nexport interface ElectricalPinDeclaration {\n readonly kind: 'signal' | 'power' | 'gnd';\n readonly side?: 'left' | 'right' | 'top' | 'bottom';\n}\n\nexport interface PreparedElectricalDevice<T> {\n readonly pinDeclarations: Readonly<Record<string, ElectricalPinDeclaration>>;\n readonly properties: Readonly<Record<string, PropertyValue>>;\n readonly pins: Readonly<Record<string, PinElectricalDescription>>;\n readonly resistors: Readonly<Record<string, InitializedResistor>>;\n readonly connections: Readonly<Record<string, ContactDeclaration>>;\n readonly implementation: T;\n}\n\nexport type ElectricalDefinitionErrorCode =\n | 'electrical/invalid-definition'\n | 'electrical/invalid-parameter'\n | 'electrical/unknown-resource'\n | 'electrical/duplicate-initialization'\n | 'electrical/missing-initialization'\n | 'electrical/factory-closed';\n\nexport class ElectricalDefinitionError extends Error {\n override readonly name = 'ElectricalDefinitionError';\n constructor(\n readonly code: ElectricalDefinitionErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\n/** Resolves a JSON declaration and calls its paired synchronous factory exactly once. */\nexport function prepareElectricalDevice<T>(\n definition: unknown,\n values: Readonly<Record<string, PropertyValue>>,\n factory: (context: ElectricalFactoryContext) => T,\n): PreparedElectricalDevice<T> {\n const raw = record(definition, 'device');\n const declarations = record(raw['pins'], 'pins');\n const pinDeclarations: [string, ElectricalPinDeclaration][] = [];\n for (const [id, value] of Object.entries(declarations)) {\n resourceId(id);\n const pin = record(value, `pins.${id}`);\n rejectFields(pin, ['direction', 'role', 'electrical'], `pins.${id}`);\n if (!['signal', 'power', 'gnd'].includes(String(pin['kind']))) {\n fail('electrical/invalid-definition', `pins.${id}.kind must be signal, power or gnd`);\n }\n if (\n pin['side'] !== undefined &&\n !['left', 'right', 'top', 'bottom'].includes(String(pin['side']))\n ) {\n fail('electrical/invalid-definition', `pins.${id}.side is invalid`);\n }\n pinDeclarations.push([\n id,\n Object.freeze({\n kind: pin['kind'] as ElectricalPinDeclaration['kind'],\n ...(pin['side'] === undefined\n ? {}\n : { side: pin['side'] as NonNullable<ElectricalPinDeclaration['side']> }),\n }),\n ]);\n }\n const resistors = parseBranches(raw['resistors'], declarations, false);\n const connections = parseBranches(raw['connections'], declarations, true);\n const descriptors = readPropertyDescriptors(raw['properties']);\n const resolved: [string, PropertyValue][] = [];\n for (const [key, descriptor] of descriptors) {\n const value = Object.hasOwn(values, key) ? values[key] : descriptor.default;\n if (value === undefined) continue;\n const problem = propertyValueProblem(descriptor, value);\n if (problem !== undefined) fail('electrical/invalid-parameter', problem.message);\n resolved.push([key, freezeCopy(value)]);\n }\n const properties = Object.freeze(Object.fromEntries(resolved));\n const initializedPins = new Map<string, PinElectricalDescription>();\n const initializedResistors = new Map<string, InitializedResistor>();\n let open = true;\n const assertOpen = (): void => {\n if (!open) fail('electrical/factory-closed', 'Electrical declarations are closed');\n };\n const electrical: DeviceElectricalInitialization = Object.freeze({\n initializeResistor(id: string, initial: ResistorInitialState): void {\n assertOpen();\n const branch = resistors.get(id);\n if (branch === undefined) fail('electrical/unknown-resource', `Unknown resistor \"${id}\"`);\n if (initializedResistors.has(id)) {\n fail('electrical/duplicate-initialization', `Resistor \"${id}\" is already initialized`);\n }\n const state = record(initial, `resistor ${id}`);\n positive(state['resistance'], `resistor ${id}.resistance`);\n if (typeof state['enabled'] !== 'boolean') {\n fail('electrical/invalid-parameter', `resistor ${id}.enabled must be boolean`);\n }\n optionalCurrent(state, `resistor ${id}`);\n initializedResistors.set(\n id,\n freezeCopy({\n pins: branch.pins,\n resistance: initial.resistance,\n enabled: initial.enabled,\n ...(initial.maxAbsCurrent === undefined ? {} : { maxAbsCurrent: initial.maxAbsCurrent }),\n }),\n );\n },\n initializePin(id: string, initial: PinElectricalDescription): void {\n assertOpen();\n if (!Object.hasOwn(declarations, id)) {\n fail('electrical/unknown-resource', `Unknown pin \"${id}\"`);\n }\n if (initializedPins.has(id)) {\n fail('electrical/duplicate-initialization', `Pin \"${id}\" is already initialized`);\n }\n validatePin(initial, id);\n initializedPins.set(id, freezeCopy(initial));\n },\n });\n let implementation: T;\n try {\n implementation = factory(Object.freeze({ properties, electrical }));\n if (\n implementation !== null &&\n (typeof implementation === 'object' || typeof implementation === 'function') &&\n 'then' in implementation\n ) {\n fail('electrical/invalid-definition', 'The paired device factory must be synchronous');\n }\n } finally {\n open = false;\n }\n for (const id of resistors.keys()) {\n if (!initializedResistors.has(id)) {\n fail('electrical/missing-initialization', `Resistor \"${id}\" has no initial state`);\n }\n }\n return Object.freeze({\n pinDeclarations: Object.freeze(Object.fromEntries(pinDeclarations)),\n properties,\n pins: Object.freeze(Object.fromEntries(initializedPins)),\n resistors: Object.freeze(Object.fromEntries(initializedResistors)),\n connections: Object.freeze(Object.fromEntries(connections)) as Readonly<\n Record<string, ContactDeclaration>\n >,\n implementation,\n });\n}\n\nfunction parseBranches(\n value: unknown,\n pins: Record<string, unknown>,\n contact: boolean,\n): Map<string, ResistorDeclaration | ContactDeclaration> {\n const result = new Map<string, ResistorDeclaration | ContactDeclaration>();\n if (value === undefined) return result;\n for (const [id, item] of Object.entries(record(value, contact ? 'connections' : 'resistors'))) {\n resourceId(id);\n const branch = record(item, id);\n rejectFields(branch, ['resistance', 'adjustable', 'initialEnabled'], id);\n const endpoints = branch['pins'];\n if (\n !Array.isArray(endpoints) ||\n endpoints.length !== 2 ||\n endpoints[0] === endpoints[1] ||\n endpoints.some((pin) => typeof pin !== 'string' || !Object.hasOwn(pins, pin))\n ) {\n fail('electrical/invalid-definition', `${id}.pins must name two distinct declared pins`);\n }\n const pair: readonly [string, string] = [endpoints[0] as string, endpoints[1] as string];\n if (contact) {\n const initial = branch['initial'] ?? 'open';\n if (initial !== 'open' && initial !== 'closed') {\n fail('electrical/invalid-definition', `${id}.initial must be open or closed`);\n }\n result.set(id, freezeCopy({ pins: pair, initial }));\n } else {\n result.set(id, freezeCopy({ pins: pair }));\n }\n }\n return result;\n}\n\nfunction validatePin(value: PinElectricalDescription, id: string): void {\n const pin = record(value, `pin ${id}`);\n rejectFields(pin, ['direction', 'role', 'interpretation'], id);\n if (!['drive', 'bias', 'input'].some((key) => pin[key] !== undefined)) {\n fail('electrical/invalid-parameter', `pin ${id} needs drive, bias or input parameters`);\n }\n for (const category of ['drive', 'bias', 'input'] as const) {\n if (pin[category] === undefined) continue;\n const part = record(pin[category], `${id}.${category}`);\n const reference = record(part['reference'], `${id}.${category}.reference`);\n if (typeof reference['source'] !== 'string' || reference['source'].length === 0) {\n fail('electrical/invalid-parameter', `${id}.${category} needs an explicit source reference`);\n }\n if (category === 'drive') {\n positive(part['highResistance'], `${id}.highResistance`);\n positive(part['lowResistance'], `${id}.lowResistance`);\n if (part['analogResistance'] !== undefined)\n positive(part['analogResistance'], `${id}.analogResistance`);\n optionalCurrent(part, id);\n } else if (category === 'bias') {\n positive(part['upResistance'], `${id}.upResistance`);\n positive(part['downResistance'], `${id}.downResistance`);\n } else {\n rejectFields(part, ['interpretation'], `${id}.input`);\n const low = part['low'];\n const high = part['high'];\n if (\n typeof low !== 'number' ||\n typeof high !== 'number' ||\n !Number.isFinite(low) ||\n !Number.isFinite(high) ||\n low < 0 ||\n low >= high ||\n high > 1\n ) {\n fail('electrical/invalid-parameter', `${id} thresholds must satisfy 0 <= low < high <= 1`);\n }\n }\n }\n}\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n fail('electrical/invalid-definition', `${label} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction resourceId(id: string): void {\n if (id.length === 0) fail('electrical/invalid-definition', 'Resource IDs must not be empty');\n}\n\nfunction positive(value: unknown, label: string): void {\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n fail('electrical/invalid-parameter', `${label} must be finite and greater than zero`);\n }\n}\n\nfunction optionalCurrent(value: Record<string, unknown>, label: string): void {\n if (value['maxAbsCurrent'] !== undefined)\n positive(value['maxAbsCurrent'], `${label}.maxAbsCurrent`);\n}\n\nfunction rejectFields(\n value: Record<string, unknown>,\n fields: readonly string[],\n label: string,\n): void {\n for (const field of fields) {\n if (Object.hasOwn(value, field)) {\n fail(\n 'electrical/invalid-definition',\n `${label}.${field} is not part of the electrical declaration`,\n );\n }\n }\n}\n\nfunction freezeCopy<T>(value: T): T {\n const copy = structuredClone(value);\n const freeze = (item: unknown): void => {\n if (item === null || typeof item !== 'object') return;\n for (const child of Object.values(item)) freeze(child);\n Object.freeze(item);\n };\n freeze(copy);\n return copy;\n}\n\nfunction fail(code: ElectricalDefinitionErrorCode, message: string): never {\n throw new ElectricalDefinitionError(code, message);\n}\n","import { ElectricalDefinitionError } from '../../electrical-authoring';\nimport type {\n PinElectricalDescription,\n PreparedElectricalDevice,\n} from '../../electrical-authoring';\nimport type { ResistiveNetwork } from './resistive-solver';\n\ntype Endpoint = { readonly device: string; readonly pin: string } | { readonly source: string };\n\nexport interface AllocatedElectricalPin {\n readonly node: number;\n readonly drive?: {\n readonly high: number;\n readonly low: number;\n readonly reference: number;\n readonly analog?: { readonly resistor: number; readonly source: number };\n readonly maxAbsCurrent?: number;\n };\n readonly bias?: { readonly up: number; readonly down: number };\n readonly input?: { readonly reference: number; readonly low: number; readonly high: number };\n}\n\nexport interface AllocatedElectricalNetwork {\n readonly network: ResistiveNetwork;\n readonly pins: ReadonlyMap<string, ReadonlyMap<string, AllocatedElectricalPin>>;\n readonly resistors: ReadonlyMap<string, ReadonlyMap<string, number>>;\n readonly contacts: ReadonlyMap<string, ReadonlyMap<string, number>>;\n readonly sources: ReadonlyMap<string, number>;\n readonly currentLimits: ReadonlyMap<number, number>;\n}\n\n/** Links prepared authoring resources. Only wires union nodes; resistors never do. */\nexport function allocateElectricalNetwork(\n devices: readonly { readonly id: string; readonly prepared: PreparedElectricalDevice<unknown> }[],\n sources: Readonly<Record<string, { readonly voltage: number }>>,\n wires: readonly (readonly [Endpoint, Endpoint])[],\n): AllocatedElectricalNetwork {\n const fail = (message: string): never => {\n throw new ElectricalDefinitionError('electrical/invalid-definition', message);\n };\n const parent: number[] = [];\n const makeNode = () => {\n const node = parent.length;\n parent.push(node);\n return node;\n };\n const root = (node: number): number => {\n let current = node;\n while (parent[current] !== current) current = parent[current]!;\n while (node !== current) {\n const next = parent[node]!;\n parent[node] = current;\n node = next;\n }\n return current;\n };\n const sourceIndices = new Map<string, number>([['GND', 0]]);\n const initialSources: { node: number; voltage: number; enabled: boolean }[] = [\n { node: makeNode(), voltage: 0, enabled: true },\n ];\n for (const [id, source] of Object.entries(sources)) {\n if (!id || sourceIndices.has(id) || !Number.isFinite(source.voltage))\n fail(`Invalid or duplicate voltage source \"${id}\"`);\n sourceIndices.set(id, initialSources.length);\n initialSources.push({ node: makeNode(), voltage: source.voltage, enabled: true });\n }\n const pinNodes = new Map<string, Map<string, number>>();\n for (const device of devices) {\n if (!device.id || pinNodes.has(device.id)) fail(`Invalid or duplicate device \"${device.id}\"`);\n pinNodes.set(\n device.id,\n new Map(Object.keys(device.prepared.pinDeclarations).map((id) => [id, makeNode()])),\n );\n }\n const reference = (name: string): number =>\n sourceIndices.get(name) ?? fail(`Unknown voltage source \"${name}\"`);\n const endpoint = (item: Endpoint): number => {\n if ('source' in item) return initialSources[reference(item.source)]!.node;\n return (\n pinNodes.get(item.device)?.get(item.pin) ?? fail(`Unknown pin \"${item.device}.${item.pin}\"`)\n );\n };\n for (const [a, b] of wires) {\n const left = root(endpoint(a));\n const right = root(endpoint(b));\n if (left !== right) parent[Math.max(left, right)] = Math.min(left, right);\n }\n const nodes = new Map<number, number>();\n const compact = (node: number) => {\n const representative = root(node);\n let index = nodes.get(representative);\n if (index === undefined) {\n index = nodes.size;\n nodes.set(representative, index);\n }\n return index;\n };\n for (let node = 0; node < parent.length; node++) compact(node);\n const compiledSources = initialSources.map((source) => ({\n ...source,\n node: compact(source.node),\n }));\n const compiledResistors: { a: number; b: number; resistance: number; enabled: boolean }[] = [];\n const compiledContacts: { a: number; b: number; closed: boolean }[] = [];\n const pins = new Map<string, ReadonlyMap<string, AllocatedElectricalPin>>();\n const resistors = new Map<string, ReadonlyMap<string, number>>();\n const contacts = new Map<string, ReadonlyMap<string, number>>();\n const currentLimits = new Map<number, number>();\n const branch = (a: number, b: number, resistance: number, enabled: boolean, limit?: number) => {\n const index = compiledResistors.length;\n compiledResistors.push({ a, b, resistance, enabled });\n if (limit !== undefined) currentLimits.set(index, limit);\n return index;\n };\n const ground = compiledSources[0]!.node;\n let nodeCount = nodes.size;\n for (const device of devices) {\n const rawPins = pinNodes.get(device.id)!;\n const pin = (id: string): number =>\n compact(rawPins.get(id) ?? fail(`Unknown pin \"${device.id}.${id}\"`));\n const deviceResistors = new Map<string, number>();\n for (const [id, resistor] of Object.entries(device.prepared.resistors)) {\n deviceResistors.set(\n id,\n branch(\n pin(resistor.pins[0]),\n pin(resistor.pins[1]),\n resistor.resistance,\n resistor.enabled,\n resistor.maxAbsCurrent,\n ),\n );\n }\n resistors.set(device.id, deviceResistors);\n const deviceContacts = new Map<string, number>();\n for (const [id, contact] of Object.entries(device.prepared.connections)) {\n deviceContacts.set(id, compiledContacts.length);\n compiledContacts.push({\n a: pin(contact.pins[0]),\n b: pin(contact.pins[1]),\n closed: contact.initial === 'closed',\n });\n }\n contacts.set(device.id, deviceContacts);\n const devicePins = new Map<string, AllocatedElectricalPin>();\n for (const id of rawPins.keys()) {\n const node = pin(id);\n const description: PinElectricalDescription = Object.hasOwn(device.prepared.pins, id)\n ? device.prepared.pins[id]!\n : {};\n let drive: AllocatedElectricalPin['drive'];\n let bias: AllocatedElectricalPin['bias'];\n let input: AllocatedElectricalPin['input'];\n if (description.drive !== undefined) {\n const config = description.drive;\n const supply = reference(config.reference.source);\n const high = branch(\n node,\n compiledSources[supply]!.node,\n config.highResistance,\n false,\n config.maxAbsCurrent,\n );\n const low = branch(node, ground, config.lowResistance, false, config.maxAbsCurrent);\n let analog: NonNullable<AllocatedElectricalPin['drive']>['analog'];\n if (config.analogResistance !== undefined) {\n const source = compiledSources.length;\n // Analog setpoints are known GND-referenced sources behind a finite output resistance.\n const sourceNode = nodeCount++;\n compiledSources.push({ node: sourceNode, voltage: 0, enabled: true });\n analog = Object.freeze({\n source,\n resistor: branch(\n node,\n sourceNode,\n config.analogResistance,\n false,\n config.maxAbsCurrent,\n ),\n });\n }\n drive = Object.freeze({\n high,\n low,\n reference: supply,\n ...(analog === undefined ? {} : { analog }),\n ...(config.maxAbsCurrent === undefined ? {} : { maxAbsCurrent: config.maxAbsCurrent }),\n });\n }\n if (description.bias !== undefined) {\n const config = description.bias;\n const supply = reference(config.reference.source);\n bias = Object.freeze({\n up: branch(node, compiledSources[supply]!.node, config.upResistance, false),\n down: branch(node, ground, config.downResistance, false),\n });\n }\n if (description.input !== undefined) {\n const config = description.input;\n input = Object.freeze({\n reference: reference(config.reference.source),\n low: config.low,\n high: config.high,\n });\n }\n devicePins.set(\n id,\n Object.freeze({\n node,\n ...(drive === undefined ? {} : { drive }),\n ...(bias === undefined ? {} : { bias }),\n ...(input === undefined ? {} : { input }),\n }),\n );\n }\n pins.set(device.id, devicePins);\n }\n const network: ResistiveNetwork = Object.freeze({\n nodes: nodeCount,\n sources: Object.freeze(compiledSources.map((source) => Object.freeze(source))),\n resistors: Object.freeze(compiledResistors.map((resistor) => Object.freeze(resistor))),\n contacts: Object.freeze(compiledContacts.map((contact) => Object.freeze(contact))),\n });\n return Object.freeze({\n network,\n pins,\n resistors,\n contacts,\n sources: sourceIndices,\n currentLimits,\n });\n}\n","import type { ArrayRef, FunctionBuilder, FunctionRef, IRModule, Value } from '@mica-js/ir';\nimport type { ResistiveSolver } from './resistive-solver';\n\ntype Builder = Pick<\n FunctionBuilder<readonly []>,\n 'const' | 'int' | 'bool' | 'float' | 'convert' | 'array' | 'state'\n>;\nconst u = (b: Builder, n: number) => b.const('u32', n);\nfunction mix(b: Builder, x: Value<'u32'>): Value<'u32'> {\n x = b.int.mul(b.int.xor(x, b.int.lshr(x, u(b, 16))), u(b, 0x7feb352d));\n x = b.int.mul(b.int.xor(x, b.int.lshr(x, u(b, 15))), u(b, 0x846ca68b));\n return b.int.xor(x, b.int.lshr(x, u(b, 16)));\n}\nfunction random(b: Builder, x: Value<'u32'>): Value<'f64'> {\n return b.float.div(b.convert.intToFloat('f64', x), b.const('f64', 0x100000000));\n}\n\n/** mica-floating-v2 phase identity is hashed at build time except for the decimal episode count. */\nexport function createFloatingInput(\n module: IRModule,\n solver: ResistiveSolver,\n clock: ArrayRef<'u32'>,\n prefix: string,\n seed: number,\n deviceId: string,\n pinName: string,\n node: number,\n reference: number,\n sample: FunctionRef<readonly [], readonly ['f64']> = module.func(`${prefix}_sample`, {\n params: [],\n results: ['f64'],\n }),\n) {\n const text = JSON.stringify(['mica-floating-v2', seed, deviceId, pinName]).slice(0, -1) + ',';\n let prefixHash = 0x811c9dc5;\n for (const byte of new TextEncoder().encode(text))\n prefixHash = Math.imul(prefixHash ^ byte, 0x01000193) >>> 0;\n const count = module.state(`${prefix}_count`, 'u32', 0);\n const wasFloating = module.state(`${prefix}_floating`, 'bool', false);\n const episode = module.state(`${prefix}_episode`, 'u32', 0);\n const initialized = module.state(`${prefix}_initialized`, 'bool', false);\n const initial = module.state(`${prefix}_initial`, 'f64', 0);\n const update = module.func(`${prefix}_update`, { params: [], results: [] });\n const ready = (b: Builder) =>\n b.bool.and(\n b.array.load(solver.sourceEnabled, u(b, reference)),\n b.float.cmp('gt', b.array.load(solver.sourceVoltage, u(b, reference)), b.const('f64', 0)),\n );\n update.body((b) => {\n const floating = b.int.cmp(\n 'eq',\n b.array.load(solver.voltageState, u(b, node)),\n b.const('u8', 1),\n );\n const enter = b.block([]);\n const after = b.block([]);\n b.branch(\n b.bool.and(floating, b.bool.not(b.state.load(wasFloating))),\n { target: enter, args: [] },\n { target: after, args: [] },\n );\n b.at(enter, (b) => {\n const next = b.int.add(b.state.load(count), u(b, 1));\n b.state.store(count, next);\n let hash = u(b, prefixHash);\n let started = b.const('bool', false);\n for (const power of [\n 1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1,\n ]) {\n const digit = b.int.rem(b.int.div(next, u(b, power)), u(b, 10));\n started = b.bool.or(\n started,\n power === 1 ? b.const('bool', true) : b.int.cmp('ne', digit, u(b, 0)),\n );\n hash = b.select(\n started,\n b.int.mul(b.int.xor(hash, b.int.add(digit, u(b, 48))), u(b, 0x01000193)),\n hash,\n );\n }\n hash = b.int.mul(b.int.xor(hash, u(b, 93)), u(b, 0x01000193));\n b.state.store(episode, b.select(b.int.cmp('eq', hash, u(b, 0)), u(b, 1), hash));\n b.state.store(initialized, b.const('bool', false));\n b.jump(after, []);\n });\n b.at(after, (b) => {\n b.state.store(wasFloating, floating);\n const initialize = b.block([]);\n const done = b.block([]);\n b.branch(\n b.bool.and(floating, b.bool.and(ready(b), b.bool.not(b.state.load(initialized)))),\n { target: initialize, args: [] },\n { target: done, args: [] },\n );\n b.at(initialize, (b) => {\n let value = b.state.load(episode);\n value = b.int.xor(value, b.int.shl(value, u(b, 13)));\n value = b.int.xor(value, b.int.lshr(value, u(b, 17)));\n value = b.int.xor(value, b.int.shl(value, u(b, 5)));\n b.state.store(\n initial,\n b.float.mul(random(b, value), b.array.load(solver.sourceVoltage, u(b, reference))),\n );\n b.state.store(initialized, b.const('bool', true));\n b.jump(done, []);\n });\n b.at(done, (b) => b.return([]));\n });\n });\n sample.body((b) => {\n const active = b.block([]);\n const gated = b.block([]);\n b.branch(ready(b), { target: active, args: [] }, { target: gated, args: [] });\n b.at(gated, (b) => b.return([b.const('f64', 0)]));\n b.at(active, (b) => {\n const physical = b.block([]);\n const floating = b.block([]);\n b.branch(\n b.int.cmp('eq', b.array.load(solver.voltageState, u(b, node)), b.const('u8', 0)),\n { target: physical, args: [] },\n { target: floating, args: [] },\n );\n b.at(physical, (b) => b.return([b.array.load(solver.voltage, u(b, node))]));\n b.at(floating, (b) => {\n const value = mix(\n b,\n b.int.xor(\n mix(b, b.int.xor(b.state.load(episode), b.array.load(clock, u(b, 0)))),\n b.array.load(clock, u(b, 1)),\n ),\n );\n const noise = b.float.mul(\n b.float.sub(b.float.mul(random(b, value), b.const('f64', 2)), b.const('f64', 1)),\n b.const('f64', 0.1),\n );\n const raw = b.float.add(b.state.load(initial), noise);\n const supply = b.array.load(solver.sourceVoltage, u(b, reference));\n b.return([\n b.select(\n b.float.cmp('lt', raw, b.const('f64', 0)),\n b.const('f64', 0),\n b.select(b.float.cmp('gt', raw, supply), supply, raw),\n ),\n ]);\n });\n });\n });\n return { update, sample };\n}\n","import type {\n ArrayRef,\n FunctionBuilder,\n FunctionRef,\n IRModule,\n StateRef,\n Value,\n} from '@mica-js/ir';\nexport interface ResistiveNetwork {\n readonly nodes: number;\n readonly resistors: readonly {\n readonly a: number;\n readonly b: number;\n readonly resistance: number;\n readonly enabled: boolean;\n }[];\n readonly sources: readonly {\n readonly node: number;\n readonly voltage: number;\n readonly enabled: boolean;\n }[];\n readonly contacts: readonly {\n readonly a: number;\n readonly b: number;\n readonly closed: boolean;\n }[];\n}\nexport const RESISTIVE_FAULT = Object.freeze({\n none: 0,\n invalidParameter: 1,\n sourceConflict: 2,\n numericalFailure: 3,\n} as const);\nexport const ELECTRICAL_VALUE_STATE = Object.freeze({\n determinate: 0,\n floating: 1,\n indeterminate: 2,\n} as const);\n/** Internal IR resources. Device and host APIs must commit through validated operations. */\nexport interface ResistiveSolver {\n readonly solve: FunctionRef<readonly [], readonly []>;\n readonly resistance: ArrayRef<'f64'>;\n readonly resistorEnabled: ArrayRef<'bool'>;\n readonly sourceVoltage: ArrayRef<'f64'>;\n readonly sourceEnabled: ArrayRef<'bool'>;\n readonly contactClosed: ArrayRef<'bool'>;\n readonly voltage: ArrayRef<'f64'>;\n readonly voltageState: ArrayRef<'u8'>;\n readonly current: ArrayRef<'f64'>;\n readonly currentState: ArrayRef<'u8'>;\n readonly sourceCurrent: ArrayRef<'f64'>;\n readonly sourceCurrentState: ArrayRef<'u8'>;\n readonly contactCurrent: ArrayRef<'f64'>;\n readonly contactCurrentState: ArrayRef<'u8'>;\n readonly fault: StateRef<'u8'>;\n /** Fault origin: 0 unknown, 1 resistor, 2 source, 3 contact, 4 node. */\n readonly faultTargetKind: StateRef<'u8'>;\n readonly faultTargetIndex: StateRef<'u32'>;\n readonly factorizations: StateRef<'u32'>;\n readonly groupRebuilds: ArrayRef<'u32'>;\n readonly groupSolves: ArrayRef<'u32'>;\n readonly topologyVersion: StateRef<'u32'>;\n readonly matrixVersion: StateRef<'u32'>;\n readonly rhsVersion: StateRef<'u32'>;\n readonly invalidate: Readonly<\n Record<'topology' | 'matrix' | 'rhs', FunctionRef<readonly [], readonly []>>\n >;\n}\ntype Program = Generator<FlowStep, void, void>;\ntype FlowStep =\n | {\n readonly kind: 'when';\n readonly condition: Value<'bool'>;\n readonly emit: () => Program | void;\n }\n | {\n readonly kind: 'loop';\n readonly count: number | Value<'u32'>;\n readonly emit: (index: Value<'u32'>) => Program | void;\n }\n | {\n readonly kind: 'guard';\n readonly valid: Value<'bool'>;\n readonly fault: StateRef<'u8'>;\n readonly code: number;\n readonly onFailure?: (builder: FunctionBuilder<readonly []>) => void;\n };\n// Generators suspend authoring at block boundaries, so every IR block is fully terminated.\n// They run only at compilation, never during simulation.\nclass Flow {\n constructor(public b: FunctionBuilder<readonly []>) {}\n u(value: number): Value<'u32'> {\n return this.b.const('u32', value);\n }\n f(value: number): Value<'f64'> {\n return this.b.const('f64', value);\n }\n load<T extends 'u32' | 'u8' | 'f64' | 'bool'>(\n array: ArrayRef<T>,\n index: number | Value<'u32'>,\n ): Value<T> {\n return this.b.array.load(array, typeof index === 'number' ? this.u(index) : index);\n }\n store<T extends 'u32' | 'u8' | 'f64' | 'bool'>(\n array: ArrayRef<T>,\n index: number | Value<'u32'>,\n value: Value<T>,\n ): void {\n this.b.array.store(array, typeof index === 'number' ? this.u(index) : index, value);\n }\n abs(value: Value<'f64'>): Value<'f64'> {\n return this.b.select(\n this.b.float.cmp('lt', value, this.f(0)),\n this.b.float.sub(this.f(0), value),\n value,\n );\n }\n *when(condition: Value<'bool'>, emit: () => Program | void): Program {\n yield { kind: 'when', condition, emit };\n }\n *loop(count: number | Value<'u32'>, emit: (index: Value<'u32'>) => Program | void): Program {\n yield { kind: 'loop', count, emit };\n }\n *guard(\n valid: Value<'bool'>,\n fault: StateRef<'u8'>,\n code: number,\n onFailure?: (builder: FunctionBuilder<readonly []>) => void,\n ): Program {\n yield { kind: 'guard', valid, fault, code, ...(onFailure === undefined ? {} : { onFailure }) };\n }\n run(program: () => Program): void {\n this.advance(program(), this.b, () => {});\n }\n private advance(\n program: Program | void,\n builder: FunctionBuilder<readonly []>,\n finish: (tail: FunctionBuilder<readonly []>) => void,\n ): undefined {\n this.b = builder;\n if (program === undefined) {\n finish(this.b);\n return;\n }\n const result = program.next();\n if (result.done) {\n finish(this.b);\n return;\n }\n const step = result.value;\n const owner = this.b;\n const done = owner.block([]);\n if (step.kind === 'guard') {\n const failed = owner.block([]);\n owner.branch(step.valid, { target: done, args: [] }, { target: failed, args: [] });\n owner.at(failed, (b) => {\n b.state.store(step.fault, b.const('u8', step.code));\n step.onFailure?.(b);\n b.return([]);\n });\n } else if (step.kind === 'when') {\n const yes = owner.block([]);\n owner.branch(step.condition, { target: yes, args: [] }, { target: done, args: [] });\n owner.at(yes, (b) =>\n this.advance(step.emit(), b, (tail) => {\n tail.jump(done, []);\n }),\n );\n } else {\n const header = owner.block(['u32']);\n const body = owner.block(['u32']);\n owner.jump(header, [owner.const('u32', 0)]);\n owner.at(header, (b, [index]) => {\n b.branch(\n b.int.cmp(\n 'lt',\n index,\n typeof step.count === 'number' ? b.const('u32', step.count) : step.count,\n ),\n { target: body, args: [index] },\n { target: done, args: [] },\n );\n });\n owner.at(body, (b, [index]) =>\n this.advance(step.emit(index), b, (tail) => {\n tail.jump(header, [tail.int.add(index, tail.const('u32', 1))]);\n }),\n );\n }\n owner.at(done, (b) => this.advance(program, b, finish));\n }\n}\n/** Generates a linear solve inside the caller's unified module; no host solver callbacks. */\nexport function generateResistiveSolver(\n module: IRModule,\n network: ResistiveNetwork,\n prefix: string,\n onPublish: readonly FunctionRef<readonly [], readonly []>[] = [],\n): ResistiveSolver {\n validateNetwork(network);\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(prefix)) throw new Error('Invalid resistive solver prefix');\n const n = network.nodes;\n const matrixSize = n * n;\n const sourceNodes = new Set(network.sources.map((source) => source.node));\n const unknownNodes = Array.from({ length: n }, (_, i) => i).filter((i) => !sourceNodes.has(i));\n const singleton =\n network.contacts.length === 0 && unknownNodes.length === 1 ? unknownNodes[0] : undefined;\n const array = <T extends 'u32' | 'u8' | 'f64' | 'bool'>(\n name: string,\n type: T,\n initial: readonly (T extends 'bool' ? boolean : number)[],\n ): ArrayRef<T> => module.array(`${prefix}_${name}`, type, initial);\n const floats = (name: string, length: number) =>\n array(name, 'f64', Array<number>(Math.max(1, length)).fill(0));\n const flags = (name: string, length: number) =>\n array(name, 'bool', Array<boolean>(Math.max(1, length)).fill(false));\n const resistance = array(\n 'resistance',\n 'f64',\n network.resistors.length ? network.resistors.map((r) => r.resistance) : [1],\n );\n const resistorEnabled = array(\n 'resistor_enabled',\n 'bool',\n network.resistors.length ? network.resistors.map((r) => r.enabled) : [false],\n );\n const sourceVoltage = array(\n 'source_voltage',\n 'f64',\n network.sources.length ? network.sources.map((s) => s.voltage) : [0],\n );\n const sourceEnabled = array(\n 'source_enabled',\n 'bool',\n network.sources.length ? network.sources.map((s) => s.enabled) : [false],\n );\n const contactClosed = array(\n 'contact_closed',\n 'bool',\n network.contacts.length ? network.contacts.map((c) => c.closed) : [false],\n );\n const voltage = floats('voltage', n);\n const voltageState = array('voltage_state', 'u8', Array<number>(n).fill(1));\n const current = floats('current', network.resistors.length);\n const currentState = array(\n 'current_state',\n 'u8',\n Array<number>(Math.max(1, network.resistors.length)).fill(2),\n );\n const sourceCurrent = floats('source_current', network.sources.length);\n const sourceCurrentState = array(\n 'source_current_state',\n 'u8',\n Array<number>(Math.max(1, network.sources.length)).fill(2),\n );\n const contactCurrent = floats('contact_current', network.contacts.length);\n const contactCurrentState = array(\n 'contact_current_state',\n 'u8',\n Array<number>(Math.max(1, network.contacts.length)).fill(2),\n );\n const candidateContactCurrent = floats('candidate_contact_current', network.contacts.length);\n const candidateContactState = array(\n 'candidate_contact_state',\n 'u8',\n Array<number>(Math.max(1, network.contacts.length)).fill(2),\n );\n const contactSide = flags('contact_side', n);\n const fault = module.state(`${prefix}_fault`, 'u8', 0);\n const faultTargetKind = module.state(`${prefix}_fault_target_kind`, 'u8', 0);\n const faultTargetIndex = module.state(`${prefix}_fault_target_index`, 'u32', 0);\n const origin =\n (kind: number, index: number | Value<'u32'>) =>\n (b: FunctionBuilder<readonly []>): void => {\n b.state.store(faultTargetKind, b.const('u8', kind));\n b.state.store(faultTargetIndex, typeof index === 'number' ? b.const('u32', index) : index);\n };\n const factorizations = module.state(`${prefix}_factorizations`, 'u32', 0);\n const validFactors = module.state(`${prefix}_valid_factors`, 'bool', false);\n const topologyVersion = module.state(`${prefix}_topology_version`, 'u32', 0);\n const matrixVersion = module.state(`${prefix}_matrix_version`, 'u32', 0);\n const rhsVersion = module.state(`${prefix}_rhs_version`, 'u32', 0);\n const factoredTopology = module.state(`${prefix}_factored_topology`, 'u32', 0);\n const factoredMatrix = module.state(`${prefix}_factored_matrix`, 'u32', 0);\n const solvedRhs = module.state(`${prefix}_solved_rhs`, 'u32', 0);\n const hasSolution = module.state(`${prefix}_has_solution`, 'bool', false);\n const invalidator = (kind: 'topology' | 'matrix' | 'rhs', version: StateRef<'u32'>) => {\n const fn = module.func(`${prefix}_invalidate_${kind}`, { params: [], results: [] });\n fn.body((b) => {\n b.state.store(version, b.int.add(b.state.load(version), b.const('u32', 1)));\n b.state.store(hasSolution, b.const('bool', false));\n if (kind !== 'rhs') b.state.store(validFactors, b.const('bool', false));\n b.return([]);\n });\n return fn;\n };\n const invalidate = Object.freeze({\n topology: invalidator('topology', topologyVersion),\n matrix: invalidator('matrix', matrixVersion),\n rhs: invalidator('rhs', rhsVersion),\n });\n const label = array(\n 'label',\n 'u32',\n Array.from({ length: n }, (_, i) => i),\n );\n const permutation = array(\n 'permutation',\n 'u32',\n Array.from({ length: n }, (_, i) => i),\n );\n const known = flags('known', n);\n const reachable = flags('reachable', n);\n const anchor = floats('anchor', n);\n const assigned = flags('assigned', n);\n const conductance = floats('conductance', matrixSize);\n const system = floats('system', matrixSize);\n const factors = floats('factors', matrixSize);\n const scale = floats('scale', n);\n const rhs = floats('rhs', n);\n const work = floats('work', n);\n const candidate = floats('candidate', n);\n const candidateCurrent = floats('candidate_current', network.resistors.length);\n const candidateSourceCurrent = floats('candidate_source_current', network.sources.length);\n const candidateSourceState = array(\n 'candidate_source_state',\n 'u8',\n Array<number>(Math.max(1, network.sources.length)).fill(2),\n );\n const group = array(\n 'group',\n 'u32',\n Array.from({ length: n }, (_, i) => i),\n );\n const groupSize = array('group_size', 'u32', Array<number>(n).fill(0));\n const groupNodes = array('group_nodes', 'u32', Array<number>(matrixSize).fill(0));\n const groupDirty = flags('group_dirty', n);\n const groupSolveDirty = flags('group_solve_dirty', n);\n const groupRebuilds = array('group_rebuilds', 'u32', Array<number>(n).fill(0));\n const groupSolves = array('group_solves', 'u32', Array<number>(n).fill(0));\n const previousResistance = floats('previous_resistance', network.resistors.length);\n const previousEnabled = flags('previous_enabled', network.resistors.length);\n const previousSourceEnabled = flags('previous_source_enabled', network.sources.length);\n const factorsInitialized = module.state(`${prefix}_factors_initialized`, 'bool', false);\n const repartition = module.state(`${prefix}_repartition`, 'bool', true);\n const relaxing = module.state(`${prefix}_relaxing`, 'bool', true);\n const pivotRow = module.state(`${prefix}_pivot_row`, 'u32', 0);\n const pivotMagnitude = module.state(`${prefix}_pivot_magnitude`, 'f64', 0);\n const accumulator = module.state(`${prefix}_accumulator`, 'f64', 0);\n const magnitude = module.state(`${prefix}_magnitude`, 'f64', 0);\n const factorGeneral = module.func(`${prefix}_factor_general`, { params: [], results: [] });\n const factor =\n singleton === undefined\n ? factorGeneral\n : module.func(`${prefix}_factor`, { params: [], results: [] });\n const solve = module.func(`${prefix}_solve`, { params: [], results: [] });\n const at = (q: Flow, row: Value<'u32'>, column: Value<'u32'>) =>\n q.b.int.add(q.b.int.mul(row, q.u(n)), column);\n const addAt = (q: Flow, row: Value<'u32'>, column: Value<'u32'>, delta: Value<'f64'>) => {\n const index = at(q, row, column);\n q.store(conductance, index, q.b.float.add(q.load(conductance, index), delta));\n };\n factorGeneral.body((builder) => {\n const q = new Flow(builder);\n q.run(function* () {\n q.b.state.store(validFactors, q.b.const('bool', false));\n yield* q.loop(n, function (i) {\n q.store(label, i, i);\n q.store(known, i, q.b.const('bool', false));\n q.store(reachable, i, q.b.const('bool', false));\n });\n // Relaxation remains bounded; stable labels skip the remaining edge scans.\n q.b.state.store(relaxing, q.b.const('bool', true));\n yield* q.loop(n, function* () {\n yield* q.when(q.b.state.load(relaxing), function* () {\n q.b.state.store(relaxing, q.b.const('bool', false));\n for (const [index, contact] of network.contacts.entries()) {\n yield* q.when(q.load(contactClosed, index), function () {\n const a = q.load(label, contact.a);\n const b = q.load(label, contact.b);\n const min = q.b.select(q.b.int.cmp('lt', a, b), a, b);\n q.b.state.store(\n relaxing,\n q.b.bool.or(q.b.state.load(relaxing), q.b.int.cmp('ne', a, b)),\n );\n q.store(label, contact.a, min);\n q.store(label, contact.b, min);\n });\n }\n });\n });\n for (const [index, source] of network.sources.entries()) {\n yield* q.when(q.load(sourceEnabled, index), function () {\n const root = q.load(label, source.node);\n q.store(known, root, q.b.const('bool', true));\n q.store(reachable, root, q.b.const('bool', true));\n });\n }\n q.b.state.store(relaxing, q.b.const('bool', true));\n yield* q.loop(n, function* () {\n yield* q.when(q.b.state.load(relaxing), function* () {\n q.b.state.store(relaxing, q.b.const('bool', false));\n for (const [index, resistor] of network.resistors.entries()) {\n yield* q.when(q.load(resistorEnabled, index), function () {\n const a = q.load(label, resistor.a);\n const b = q.load(label, resistor.b);\n const ra = q.load(reachable, a);\n const rb = q.load(reachable, b);\n const connected = q.b.bool.or(ra, rb);\n q.b.state.store(\n relaxing,\n q.b.bool.or(q.b.state.load(relaxing), q.b.bool.xor(ra, rb)),\n );\n q.store(reachable, a, connected);\n q.store(reachable, b, connected);\n });\n }\n });\n });\n q.b.state.store(\n repartition,\n q.b.bool.or(\n q.b.bool.not(q.b.state.load(factorsInitialized)),\n q.b.int.cmp('ne', q.b.state.load(topologyVersion), q.b.state.load(factoredTopology)),\n ),\n );\n for (const [i] of network.sources.entries())\n q.b.state.store(\n repartition,\n q.b.bool.or(\n q.b.state.load(repartition),\n q.b.bool.xor(q.load(sourceEnabled, i), q.load(previousSourceEnabled, i)),\n ),\n );\n yield* q.loop(n, function (i) {\n q.store(group, i, i);\n q.store(groupSize, i, q.u(0));\n });\n // Fixed ideal-voltage roots separate unknown blocks. Disabled finite branches\n // remain in the conservative graph, so enabling one cannot join cached groups.\n q.b.state.store(relaxing, q.b.const('bool', true));\n yield* q.loop(n, function* () {\n yield* q.when(q.b.state.load(relaxing), function* () {\n q.b.state.store(relaxing, q.b.const('bool', false));\n for (const resistor of network.resistors) {\n const a = q.load(label, resistor.a);\n const b = q.load(label, resistor.b);\n yield* q.when(\n q.b.bool.not(q.b.bool.or(q.load(known, a), q.load(known, b))),\n function () {\n const ga = q.load(group, a);\n const gb = q.load(group, b);\n const root = q.b.select(q.b.int.cmp('lt', ga, gb), ga, gb);\n q.b.state.store(\n relaxing,\n q.b.bool.or(q.b.state.load(relaxing), q.b.int.cmp('ne', ga, gb)),\n );\n q.store(group, a, root);\n q.store(group, b, root);\n },\n );\n }\n });\n });\n yield* q.loop(n, function (i) {\n q.store(groupDirty, i, q.b.state.load(repartition));\n });\n for (const [i, resistor] of network.resistors.entries()) {\n yield* q.when(\n q.b.bool.or(\n q.b.float.cmp('ne', q.load(resistance, i), q.load(previousResistance, i)),\n q.b.bool.xor(q.load(resistorEnabled, i), q.load(previousEnabled, i)),\n ),\n function () {\n q.store(groupDirty, q.load(group, q.load(label, resistor.a)), q.b.const('bool', true));\n q.store(groupDirty, q.load(group, q.load(label, resistor.b)), q.b.const('bool', true));\n },\n );\n }\n yield* q.loop(n, function* (row) {\n yield* q.when(\n q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row))),\n function () {\n const root = q.load(group, row);\n const size = q.load(groupSize, root);\n q.store(groupNodes, at(q, root, size), row);\n q.store(groupSize, root, q.b.int.add(size, q.u(1)));\n },\n );\n });\n yield* q.loop(matrixSize, function (i) {\n q.store(conductance, i, q.f(0));\n });\n for (const [index, resistor] of network.resistors.entries()) {\n yield* q.when(q.load(resistorEnabled, index), function* () {\n const a = q.load(label, resistor.a);\n const b = q.load(label, resistor.b);\n const g = q.b.float.div(q.f(1), q.load(resistance, index));\n yield* q.guard(\n q.b.bool.and(q.b.float.isFinite(g), q.b.float.cmp('gt', g, q.f(0))),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(1, index),\n );\n yield* q.when(q.b.int.cmp('ne', a, b), function () {\n const negative = q.b.float.sub(q.f(0), g);\n addAt(q, a, a, g);\n addAt(q, b, b, g);\n addAt(q, a, b, negative);\n addAt(q, b, a, negative);\n });\n });\n }\n yield* q.loop(n, function* (row) {\n const active = q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row)));\n const diagonal = q.load(conductance, at(q, row, row));\n const divisor = q.b.select(active, diagonal, q.f(1));\n yield* q.guard(\n q.b.bool.and(q.b.float.isFinite(divisor), q.b.float.cmp('gt', divisor, q.f(0))),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(4, row),\n );\n q.store(scale, row, divisor);\n yield* q.when(q.b.bool.and(active, q.load(groupDirty, q.load(group, row))), function* () {\n yield* q.loop(n, function* (column) {\n const coefficient = q.b.select(\n q.load(known, column),\n q.f(0),\n q.b.float.div(q.load(conductance, at(q, row, column)), divisor),\n );\n yield* q.guard(\n q.b.float.isFinite(coefficient),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(4, row),\n );\n q.store(system, at(q, row, column), coefficient);\n q.store(factors, at(q, row, column), coefficient);\n });\n q.store(permutation, row, row);\n });\n });\n yield* q.loop(n, function* (root) {\n const size = q.load(groupSize, root);\n yield* q.when(\n q.b.bool.and(q.load(groupDirty, root), q.b.int.cmp('gt', size, q.u(0))),\n function* () {\n q.store(groupRebuilds, root, q.b.int.add(q.load(groupRebuilds, root), q.u(1)));\n // A scaled singleton equation already has a unit diagonal: no LU work.\n yield* q.when(q.b.int.cmp('gt', size, q.u(1)), function* () {\n yield* q.loop(size, function* (ki) {\n const k = q.load(groupNodes, at(q, root, ki));\n q.b.state.store(pivotRow, k);\n q.b.state.store(pivotMagnitude, q.f(0));\n yield* q.loop(size, function* (ri) {\n yield* q.when(q.b.int.cmp('ge', ri, ki), function* () {\n const row = q.load(groupNodes, at(q, root, ri));\n const abs = q.abs(q.load(factors, at(q, row, k)));\n yield* q.when(\n q.b.float.cmp('gt', abs, q.b.state.load(pivotMagnitude)),\n function () {\n q.b.state.store(pivotMagnitude, abs);\n q.b.state.store(pivotRow, row);\n },\n );\n });\n });\n yield* q.guard(\n q.b.float.cmp('gt', q.b.state.load(pivotMagnitude), q.f(1e-14)),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(4, k),\n );\n const selected = q.b.state.load(pivotRow);\n const old = q.load(permutation, k);\n q.store(permutation, k, q.load(permutation, selected));\n q.store(permutation, selected, old);\n yield* q.loop(size, function (ci) {\n const column = q.load(groupNodes, at(q, root, ci));\n const before = q.load(factors, at(q, k, column));\n q.store(factors, at(q, k, column), q.load(factors, at(q, selected, column)));\n q.store(factors, at(q, selected, column), before);\n });\n yield* q.loop(size, function* (ri) {\n yield* q.when(q.b.int.cmp('gt', ri, ki), function* () {\n const row = q.load(groupNodes, at(q, root, ri));\n const multiplier = q.b.float.div(\n q.load(factors, at(q, row, k)),\n q.load(factors, at(q, k, k)),\n );\n yield* q.guard(\n q.b.float.isFinite(multiplier),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(4, row),\n );\n q.store(factors, at(q, row, k), multiplier);\n yield* q.loop(size, function* (ci) {\n yield* q.when(q.b.int.cmp('gt', ci, ki), function* () {\n const column = q.load(groupNodes, at(q, root, ci));\n const value = q.b.float.sub(\n q.load(factors, at(q, row, column)),\n q.b.float.mul(multiplier, q.load(factors, at(q, k, column))),\n );\n yield* q.guard(\n q.b.float.isFinite(value),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(4, row),\n );\n q.store(factors, at(q, row, column), value);\n });\n });\n });\n });\n });\n });\n },\n );\n });\n for (const [i] of network.resistors.entries()) {\n q.store(previousResistance, i, q.load(resistance, i));\n q.store(previousEnabled, i, q.load(resistorEnabled, i));\n }\n for (const [i] of network.sources.entries())\n q.store(previousSourceEnabled, i, q.load(sourceEnabled, i));\n q.b.state.store(factorsInitialized, q.b.const('bool', true));\n q.b.state.store(factoredTopology, q.b.state.load(topologyVersion));\n q.b.state.store(factoredMatrix, q.b.state.load(matrixVersion));\n q.b.state.store(validFactors, q.b.const('bool', true));\n q.b.state.store(factorizations, q.b.int.add(q.b.state.load(factorizations), q.u(1)));\n q.b.return([]);\n });\n });\n if (singleton !== undefined) {\n const direct = module.func(`${prefix}_factor_singleton`, { params: [], results: [] });\n direct.body((builder) => {\n const q = new Flow(builder);\n q.run(function* () {\n q.b.state.store(validFactors, q.b.const('bool', false));\n for (let node = 0; node < n; node++) {\n q.store(label, node, q.u(node));\n q.store(known, node, q.b.const('bool', node !== singleton));\n q.store(reachable, node, q.b.const('bool', node !== singleton));\n q.store(group, node, q.u(node));\n q.store(groupSize, node, q.u(0));\n q.store(groupDirty, node, q.b.const('bool', node === singleton));\n q.store(scale, node, q.f(1));\n q.store(conductance, singleton * n + node, q.f(0));\n }\n for (const [i, resistor] of network.resistors.entries()) {\n yield* q.when(q.load(resistorEnabled, i), function* () {\n const g = q.b.float.div(q.f(1), q.load(resistance, i));\n yield* q.guard(\n q.b.bool.and(q.b.float.isFinite(g), q.b.float.cmp('gt', g, q.f(0))),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(1, i),\n );\n if ((resistor.a === singleton) !== (resistor.b === singleton)) {\n const other = resistor.a === singleton ? resistor.b : resistor.a;\n addAt(q, q.u(singleton), q.u(singleton), g);\n addAt(q, q.u(singleton), q.u(other), q.b.float.sub(q.f(0), g));\n q.store(reachable, singleton, q.b.const('bool', true));\n }\n });\n }\n const active = q.load(reachable, singleton);\n const divisor = q.b.select(active, q.load(conductance, singleton * n + singleton), q.f(1));\n yield* q.guard(\n q.b.bool.and(q.b.float.isFinite(divisor), q.b.float.cmp('gt', divisor, q.f(0))),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(4, singleton),\n );\n q.store(scale, singleton, divisor);\n for (let column = 0; column < n; column++)\n q.store(system, singleton * n + column, q.f(column === singleton ? 1 : 0));\n q.store(groupSize, singleton, q.b.select(active, q.u(1), q.u(0)));\n q.store(groupNodes, singleton * n, q.u(singleton));\n yield* q.when(active, function () {\n q.store(groupRebuilds, singleton, q.b.int.add(q.load(groupRebuilds, singleton), q.u(1)));\n });\n for (const [i] of network.sources.entries())\n q.store(previousSourceEnabled, i, q.load(sourceEnabled, i));\n q.b.state.store(factorsInitialized, q.b.const('bool', true));\n q.b.state.store(factoredTopology, q.b.state.load(topologyVersion));\n q.b.state.store(factoredMatrix, q.b.state.load(matrixVersion));\n q.b.state.store(validFactors, q.b.const('bool', true));\n q.b.state.store(factorizations, q.b.int.add(q.b.state.load(factorizations), q.u(1)));\n q.b.return([]);\n });\n });\n factor.body((b) => {\n let fixed = b.const('bool', true);\n for (const node of sourceNodes) {\n let enabled = b.const('bool', false);\n for (const [i, source] of network.sources.entries())\n if (source.node === node)\n enabled = b.bool.or(enabled, b.array.load(sourceEnabled, b.const('u32', i)));\n fixed = b.bool.and(fixed, enabled);\n }\n const yes = b.block([]);\n const no = b.block([]);\n b.branch(fixed, { target: yes, args: [] }, { target: no, args: [] });\n b.at(yes, (b) => {\n b.call(direct, []);\n b.return([]);\n });\n b.at(no, (b) => {\n b.call(factorGeneral, []);\n b.return([]);\n });\n });\n }\n solve.body((builder) => {\n const sameTopology = builder.int.cmp(\n 'eq',\n builder.state.load(topologyVersion),\n builder.state.load(factoredTopology),\n );\n const sameMatrix = builder.int.cmp(\n 'eq',\n builder.state.load(matrixVersion),\n builder.state.load(factoredMatrix),\n );\n const sameRhs = builder.int.cmp(\n 'eq',\n builder.state.load(rhsVersion),\n builder.state.load(solvedRhs),\n );\n const sameFactors = builder.bool.and(\n builder.state.load(validFactors),\n builder.bool.and(sameTopology, sameMatrix),\n );\n const cached = builder.bool.and(\n builder.state.load(hasSolution),\n builder.bool.and(sameFactors, sameRhs),\n );\n const done = builder.block([]);\n const dirty = builder.block([]);\n builder.branch(cached, { target: done, args: [] }, { target: dirty, args: [] });\n builder.at(done, (b) => b.return([]));\n builder.at(dirty, (builder) => {\n const q = new Flow(builder);\n q.run(function* () {\n q.b.state.store(hasSolution, q.b.const('bool', false));\n q.b.state.store(fault, q.b.const('u8', 0));\n q.b.state.store(faultTargetKind, q.b.const('u8', 0));\n const changed = q.b.bool.not(sameFactors);\n for (const [i] of network.resistors.entries()) {\n const r = q.load(resistance, i);\n yield* q.guard(\n q.b.bool.and(q.b.float.isFinite(r), q.b.float.cmp('gt', r, q.f(0))),\n fault,\n RESISTIVE_FAULT.invalidParameter,\n origin(1, i),\n );\n }\n for (const [i] of network.sources.entries()) {\n yield* q.guard(\n q.b.float.isFinite(q.load(sourceVoltage, i)),\n fault,\n RESISTIVE_FAULT.invalidParameter,\n origin(2, i),\n );\n }\n yield* q.when(changed, function () {\n q.b.call(factor, []);\n });\n yield* q.guard(\n q.b.int.cmp('eq', q.b.state.load(fault), q.b.const('u8', 0)),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n );\n yield* q.loop(n, function (i) {\n q.store(anchor, i, q.f(0));\n q.store(assigned, i, q.b.const('bool', false));\n });\n for (const [i, source] of network.sources.entries()) {\n yield* q.when(q.load(sourceEnabled, i), function* () {\n const root = q.load(label, source.node);\n const value = q.load(sourceVoltage, i);\n const compatible = q.b.bool.or(\n q.b.bool.not(q.load(assigned, root)),\n q.b.float.cmp('eq', q.load(anchor, root), value),\n );\n yield* q.guard(compatible, fault, RESISTIVE_FAULT.sourceConflict, origin(2, i));\n q.store(anchor, root, value);\n q.store(assigned, root, q.b.const('bool', true));\n });\n }\n yield* q.loop(n, function (root) {\n q.store(groupSolveDirty, root, q.b.bool.and(changed, q.load(groupDirty, root)));\n });\n yield* q.loop(n, function* (row) {\n const active = q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row)));\n q.b.state.store(accumulator, q.f(0));\n yield* q.when(active, function* () {\n yield* q.loop(n, function (column) {\n const sourceTerm = q.b.select(\n q.load(known, column),\n q.b.float.mul(\n q.b.float.div(q.load(conductance, at(q, row, column)), q.load(scale, row)),\n q.load(anchor, column),\n ),\n q.f(0),\n );\n q.b.state.store(accumulator, q.b.float.sub(q.b.state.load(accumulator), sourceTerm));\n });\n });\n const value = q.b.select(\n q.load(known, row),\n q.load(anchor, row),\n q.b.select(active, q.b.state.load(accumulator), q.f(0)),\n );\n yield* q.guard(\n q.b.float.isFinite(value),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(4, row),\n );\n yield* q.when(\n q.b.bool.and(active, q.b.float.cmp('ne', value, q.load(rhs, row))),\n function () {\n q.store(groupSolveDirty, q.load(group, row), q.b.const('bool', true));\n },\n );\n q.store(rhs, row, value);\n yield* q.when(q.b.bool.not(active), function () {\n q.store(candidate, row, value);\n });\n });\n yield* q.loop(n, function* (root) {\n const size = q.load(groupSize, root);\n yield* q.when(\n q.b.bool.and(q.load(groupSolveDirty, root), q.b.int.cmp('gt', size, q.u(0))),\n function* () {\n q.store(groupSolves, root, q.b.int.add(q.load(groupSolves, root), q.u(1)));\n yield* q.when(q.b.int.cmp('eq', size, q.u(1)), function () {\n const row = q.load(groupNodes, at(q, root, q.u(0)));\n q.store(candidate, row, q.load(rhs, row));\n });\n yield* q.when(q.b.int.cmp('gt', size, q.u(1)), function* () {\n yield* q.loop(size, function* (ri) {\n const row = q.load(groupNodes, at(q, root, ri));\n q.b.state.store(accumulator, q.load(rhs, q.load(permutation, row)));\n yield* q.loop(size, function* (ci) {\n yield* q.when(q.b.int.cmp('lt', ci, ri), function () {\n const column = q.load(groupNodes, at(q, root, ci));\n q.b.state.store(\n accumulator,\n q.b.float.sub(\n q.b.state.load(accumulator),\n q.b.float.mul(q.load(factors, at(q, row, column)), q.load(work, column)),\n ),\n );\n });\n });\n q.store(work, row, q.b.state.load(accumulator));\n });\n yield* q.loop(size, function* (reverse) {\n const ri = q.b.int.sub(q.b.int.sub(size, q.u(1)), reverse);\n const row = q.load(groupNodes, at(q, root, ri));\n q.b.state.store(accumulator, q.load(work, row));\n yield* q.loop(size, function* (ci) {\n yield* q.when(q.b.int.cmp('gt', ci, ri), function () {\n const column = q.load(groupNodes, at(q, root, ci));\n q.b.state.store(\n accumulator,\n q.b.float.sub(\n q.b.state.load(accumulator),\n q.b.float.mul(\n q.load(factors, at(q, row, column)),\n q.load(candidate, column),\n ),\n ),\n );\n });\n });\n const value = q.b.float.div(\n q.b.state.load(accumulator),\n q.load(factors, at(q, row, row)),\n );\n yield* q.guard(\n q.b.float.isFinite(value),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(4, row),\n );\n q.store(candidate, row, value);\n });\n });\n },\n );\n });\n yield* q.loop(n, function* (row) {\n yield* q.when(\n q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row))),\n function* () {\n q.b.state.store(accumulator, q.f(0));\n q.b.state.store(magnitude, q.b.float.mul(q.f(1e-10), q.abs(q.load(rhs, row))));\n yield* q.loop(n, function (column) {\n const term = q.b.float.mul(\n q.load(system, at(q, row, column)),\n q.load(candidate, column),\n );\n q.b.state.store(accumulator, q.b.float.add(q.b.state.load(accumulator), term));\n q.b.state.store(\n magnitude,\n q.b.float.add(q.b.state.load(magnitude), q.b.float.mul(q.f(1e-10), q.abs(term))),\n );\n });\n const error = q.abs(q.b.float.sub(q.b.state.load(accumulator), q.load(rhs, row)));\n const tolerance = q.b.float.add(q.f(1e-22), q.b.state.load(magnitude));\n yield* q.guard(\n q.b.bool.and(q.b.float.isFinite(error), q.b.float.cmp('le', error, tolerance)),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(4, row),\n );\n },\n );\n });\n // Currents and voltages are staged until the entire candidate snapshot is finite.\n for (const [i, resistor] of network.resistors.entries()) {\n const delta = q.b.float.sub(\n q.load(candidate, q.load(label, resistor.a)),\n q.load(candidate, q.load(label, resistor.b)),\n );\n const value = q.b.select(\n q.load(resistorEnabled, i),\n q.b.float.div(delta, q.load(resistance, i)),\n q.f(0),\n );\n yield* q.guard(\n q.b.float.isFinite(value),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(1, i),\n );\n q.store(candidateCurrent, i, value);\n }\n for (const [i, source] of network.sources.entries()) {\n const root = q.load(label, source.node);\n let unique = q.b.const('bool', true);\n for (const [j, other] of network.sources.entries()) {\n if (i === j) continue;\n unique = q.b.bool.and(\n unique,\n q.b.bool.not(\n q.b.bool.and(\n q.load(sourceEnabled, j),\n q.b.int.cmp('eq', root, q.load(label, other.node)),\n ),\n ),\n );\n }\n q.b.state.store(accumulator, q.f(0));\n for (const [j, resistor] of network.resistors.entries()) {\n const a = q.load(label, resistor.a);\n const b = q.load(label, resistor.b);\n const outward = q.b.select(\n q.b.int.cmp('eq', root, a),\n q.load(candidateCurrent, j),\n q.f(0),\n );\n const inward = q.b.select(\n q.b.int.cmp('eq', root, b),\n q.load(candidateCurrent, j),\n q.f(0),\n );\n q.b.state.store(\n accumulator,\n q.b.float.add(q.b.state.load(accumulator), q.b.float.sub(outward, inward)),\n );\n }\n const enabled = q.load(sourceEnabled, i);\n const value = q.b.select(\n q.b.bool.and(enabled, unique),\n q.b.state.load(accumulator),\n q.f(0),\n );\n yield* q.guard(\n q.b.float.isFinite(value),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(2, i),\n );\n q.store(candidateSourceCurrent, i, value);\n q.store(\n candidateSourceState,\n i,\n q.b.select(\n q.b.bool.or(q.b.bool.not(enabled), unique),\n q.b.const('u8', 0),\n q.b.const('u8', 2),\n ),\n );\n }\n // Removing a closed contact identifies its cut. KCL determines a bridge current only\n // when at least one side contains no ideal source; cycles retain a free loop current.\n for (const [i, contact] of network.contacts.entries()) {\n q.store(candidateContactCurrent, i, q.f(0));\n q.store(candidateContactState, i, q.b.const('u8', 0));\n yield* q.when(q.load(contactClosed, i), function* () {\n yield* q.loop(n, function (node) {\n q.store(contactSide, node, q.b.int.cmp('eq', node, q.u(contact.a)));\n });\n yield* q.loop(n, function* () {\n for (const [j, edge] of network.contacts.entries()) {\n if (i === j) continue;\n yield* q.when(q.load(contactClosed, j), function () {\n const connected = q.b.bool.or(\n q.load(contactSide, edge.a),\n q.load(contactSide, edge.b),\n );\n q.store(contactSide, edge.a, connected);\n q.store(contactSide, edge.b, connected);\n });\n }\n });\n const root = q.load(label, contact.a);\n let leftSource = q.b.const('bool', false);\n let rightSource = q.b.const('bool', false);\n for (const [j, source] of network.sources.entries()) {\n const same = q.b.bool.and(\n q.load(sourceEnabled, j),\n q.b.int.cmp('eq', root, q.load(label, source.node)),\n );\n leftSource = q.b.bool.or(\n leftSource,\n q.b.bool.and(same, q.load(contactSide, source.node)),\n );\n rightSource = q.b.bool.or(\n rightSource,\n q.b.bool.and(same, q.b.bool.not(q.load(contactSide, source.node))),\n );\n }\n let leftOut = q.f(0);\n let rightOut = q.f(0);\n const right = (node: number) =>\n q.b.bool.and(\n q.b.int.cmp('eq', root, q.load(label, node)),\n q.b.bool.not(q.load(contactSide, node)),\n );\n for (const [j, resistor] of network.resistors.entries()) {\n const value = q.load(candidateCurrent, j);\n const netOut = (a: Value<'bool'>, b: Value<'bool'>) =>\n q.b.float.sub(q.b.select(a, value, q.f(0)), q.b.select(b, value, q.f(0)));\n leftOut = q.b.float.add(\n leftOut,\n netOut(q.load(contactSide, resistor.a), q.load(contactSide, resistor.b)),\n );\n rightOut = q.b.float.add(rightOut, netOut(right(resistor.a), right(resistor.b)));\n }\n const unique = q.b.bool.and(\n q.b.bool.not(q.load(contactSide, contact.b)),\n q.b.bool.not(q.b.bool.and(leftSource, rightSource)),\n );\n const value = q.b.select(leftSource, rightOut, q.b.float.sub(q.f(0), leftOut));\n yield* q.guard(\n q.b.float.isFinite(value),\n fault,\n RESISTIVE_FAULT.numericalFailure,\n origin(3, i),\n );\n q.store(candidateContactCurrent, i, q.b.select(unique, value, q.f(0)));\n q.store(\n candidateContactState,\n i,\n q.b.select(unique, q.b.const('u8', 0), q.b.const('u8', 2)),\n );\n });\n }\n yield* q.loop(n, function (node) {\n const root = q.load(label, node);\n q.store(voltage, node, q.load(candidate, root));\n q.store(\n voltageState,\n node,\n q.b.select(q.load(reachable, root), q.b.const('u8', 0), q.b.const('u8', 1)),\n );\n });\n for (const [i] of network.resistors.entries()) {\n q.store(current, i, q.load(candidateCurrent, i));\n // A source-free passive component has an unknown common-mode voltage but zero\n // finite-branch current. Floating node voltages do not make that current ambiguous.\n q.store(currentState, i, q.b.const('u8', 0));\n }\n for (const [i] of network.sources.entries()) {\n q.store(sourceCurrent, i, q.load(candidateSourceCurrent, i));\n q.store(sourceCurrentState, i, q.load(candidateSourceState, i));\n }\n for (const [i] of network.contacts.entries()) {\n q.store(contactCurrent, i, q.load(candidateContactCurrent, i));\n q.store(contactCurrentState, i, q.load(candidateContactState, i));\n }\n q.b.state.store(solvedRhs, q.b.state.load(rhsVersion));\n q.b.state.store(hasSolution, q.b.const('bool', true));\n for (const observer of onPublish) q.b.call(observer, []);\n q.b.return([]);\n });\n });\n });\n return Object.freeze({\n solve,\n resistance,\n resistorEnabled,\n sourceVoltage,\n sourceEnabled,\n contactClosed,\n voltage,\n voltageState,\n current,\n currentState,\n sourceCurrent,\n sourceCurrentState,\n contactCurrent,\n contactCurrentState,\n fault,\n faultTargetKind,\n faultTargetIndex,\n factorizations,\n groupRebuilds,\n groupSolves,\n topologyVersion,\n matrixVersion,\n rhsVersion,\n invalidate,\n });\n}\nfunction validateNetwork(network: ResistiveNetwork): void {\n if (!Number.isSafeInteger(network.nodes) || network.nodes < 1)\n throw new Error('A resistive network needs a positive node count');\n const node = (index: number) => {\n if (!Number.isSafeInteger(index) || index < 0 || index >= network.nodes)\n throw new Error(`Invalid node ${index}`);\n };\n for (const resistor of network.resistors) {\n node(resistor.a);\n node(resistor.b);\n if (\n !Number.isFinite(resistor.resistance) ||\n resistor.resistance <= 0 ||\n typeof resistor.enabled !== 'boolean'\n )\n throw new Error('Invalid initial resistor state');\n }\n for (const source of network.sources) {\n node(source.node);\n if (!Number.isFinite(source.voltage) || typeof source.enabled !== 'boolean')\n throw new Error('Invalid initial source state');\n }\n for (const contact of network.contacts) {\n node(contact.a);\n node(contact.b);\n if (typeof contact.closed !== 'boolean') throw new Error('Invalid initial contact state');\n }\n}\n","import type { ArrayRef, FunctionBuilder, FunctionRef, IRModule, Value } from '@mica-js/ir';\nimport { PIN_MODE } from '../pin-space';\nimport { createFloatingInput } from './floating-input';\nimport type { AllocatedElectricalNetwork, AllocatedElectricalPin } from './electrical-network';\nimport { generateResistiveSolver, RESISTIVE_FAULT } from './resistive-solver';\nimport type { ResistiveSolver } from './resistive-solver';\nimport { UnifiedIRCompilerError } from './types';\nimport type { DeviceBehaviorApi, DevicePinHandle, DeviceResistorHandle } from './types';\n\ntype Builder = FunctionBuilder<readonly []>;\ntype DeviceBindings = Pick<\n DeviceBehaviorApi,\n | 'pins'\n | 'outputs'\n | 'pin'\n | 'resistor'\n | 'writeDigitalGroup'\n | 'applyResistors'\n | 'applyConnections'\n>;\n\nexport interface ElectricalOperations {\n readonly solver: ResistiveSolver;\n readonly ensure: FunctionRef<readonly [], readonly []>;\n readonly clock: ArrayRef<'u32'>;\n readonly timeStep: ArrayRef<'u32'>;\n readonly advanceTime: FunctionRef<readonly [], readonly []>;\n finalize(): void;\n readonly digitalSample: ArrayRef<'bool'>;\n readonly digitalIntent: ArrayRef<'bool'>;\n readonly pinIndices: ReadonlyMap<string, number>;\n bindDevice(\n deviceId: string,\n builder: Builder,\n globalIds?: ReadonlyMap<string, number>,\n ): DeviceBindings;\n}\n\n/** Compiler-owned lowering helpers; none of their private storage is given to devices. */\nexport function createElectricalOperations(\n module: IRModule,\n allocation: AllocatedElectricalNetwork,\n interpretation: 'two-state' | 'retain-in-band',\n prefix: string,\n floatingSeed = 0,\n): ElectricalOperations {\n if (!Number.isInteger(floatingSeed) || floatingSeed < 0 || floatingSeed > 0xffff_ffff)\n throw new Error('floatingSeed must be a u32');\n if (interpretation !== 'two-state' && interpretation !== 'retain-in-band')\n throw new Error('Invalid electrical interpretation');\n const inputs = module.func(`${prefix}_interpret_inputs`, { params: [], results: [] });\n const solver = generateResistiveSolver(module, allocation.network, prefix, [inputs]);\n const allPins = [...allocation.pins].flatMap(([deviceId, pins]) =>\n [...pins].map(([name, pin]) => ({ deviceId, name, pin })),\n );\n const size = Math.max(1, allPins.length);\n const mode = module.array(`${prefix}_mode`, 'u8', Array<number>(size).fill(PIN_MODE.highZ));\n const enabled = module.array(\n `${prefix}_output_enabled`,\n 'bool',\n Array<boolean>(size).fill(false),\n );\n const digital = module.array(\n `${prefix}_digital_intent`,\n 'bool',\n Array<boolean>(size).fill(false),\n );\n const digitalReady = module.array(\n `${prefix}_digital_ready`,\n 'bool',\n Array<boolean>(size).fill(false),\n );\n const voltageReady = module.array(\n `${prefix}_voltage_ready`,\n 'bool',\n Array<boolean>(size).fill(false),\n );\n const memory = module.array(`${prefix}_input_memory`, 'bool', Array<boolean>(size).fill(false));\n const sampled = module.array(\n `${prefix}_digital_sample`,\n 'bool',\n Array<boolean>(size).fill(false),\n );\n const index = (b: Builder, i: number) => b.const('u32', i);\n const badResource = (message: string): never => {\n throw new UnifiedIRCompilerError('invalid-input', message);\n };\n const running = (b: Builder, emit: (b: Builder) => undefined): undefined => {\n const body = b.block([]);\n const done = b.block([]);\n b.branch(\n b.int.cmp('eq', b.state.load(solver.fault), b.const('u8', 0)),\n { target: body, args: [] },\n { target: done, args: [] },\n );\n b.at(body, emit);\n b.at(done, (b) => b.return([]));\n };\n const checked = (\n b: Builder,\n valid: Value<'bool'>,\n target: { readonly kind: number; readonly index: Value<'u32'> },\n commit: (b: Builder) => undefined,\n ): undefined => {\n const yes = b.block([]);\n const no = b.block([]);\n b.branch(valid, { target: yes, args: [] }, { target: no, args: [] });\n b.at(yes, commit);\n b.at(no, (b) => {\n b.state.store(solver.fault, b.const('u8', RESISTIVE_FAULT.invalidParameter));\n b.state.store(solver.faultTargetKind, b.const('u8', target.kind));\n b.state.store(solver.faultTargetIndex, target.index);\n b.return([]);\n });\n };\n const complete = (\n b: Builder,\n changed: Value<'bool'>,\n kind: 'matrix' | 'topology' | 'rhs',\n otherwise: (b: Builder) => undefined = (b) => b.return([]),\n ): undefined => {\n const yes = b.block([]);\n const no = b.block([]);\n b.branch(changed, { target: yes, args: [] }, { target: no, args: [] });\n b.at(yes, (b) => {\n b.call(solver.invalidate[kind], []);\n b.return([]);\n });\n b.at(no, otherwise);\n };\n const loop = (\n b: Builder,\n count: Value<'u32'>,\n emit: (b: Builder, i: Value<'u32'>) => void,\n done: (b: Builder) => undefined,\n ): undefined => {\n const header = b.block(['u32']);\n const body = b.block(['u32']);\n const exit = b.block([]);\n b.jump(header, [b.const('u32', 0)]);\n b.at(header, (b, [i]) =>\n b.branch(b.int.cmp('lt', i, count), { target: body, args: [i] }, { target: exit, args: [] }),\n );\n b.at(body, (b, [i]) => {\n emit(b, i);\n b.jump(header, [b.int.add(i, b.const('u32', 1))]);\n });\n b.at(exit, done);\n };\n const ensure = module.func(`${prefix}_ensure`, { params: [], results: [] });\n ensure.body((b) =>\n running(b, (b) => {\n b.call(solver.solve, []);\n b.return([]);\n }),\n );\n\n const clock = module.array(`${prefix}_time`, 'u32', [0, 0]);\n const timeStep = module.array(`${prefix}_time_step`, 'u32', [1, 0]);\n const advanceTime = module.func(`${prefix}_advance_time`, { params: [], results: [] });\n const analogInputs = new Map<number, ReturnType<typeof createFloatingInput>>();\n const analogRequests = new Map<number, FunctionRef<readonly [], readonly ['f64']>>();\n // Device bodies request samplers; helper bodies must be built outside any active IR body.\n let finalized = false;\n const finalize = () => {\n if (finalized) return;\n finalized = true;\n for (const [id, sample] of analogRequests) {\n const { deviceId, name, pin } = allPins[id]!;\n analogInputs.set(\n id,\n createFloatingInput(\n module,\n solver,\n clock,\n `${prefix}_analog_${id}`,\n floatingSeed,\n deviceId,\n name,\n pin.node,\n pin.input!.reference,\n sample,\n ),\n );\n }\n advanceTime.body((b) => {\n if (analogInputs.size === 0) {\n b.return([]);\n return;\n }\n const previous = b.array.load(clock, index(b, 0));\n const low = b.int.add(previous, b.array.load(timeStep, index(b, 0)));\n const carry = b.select(b.int.cmp('lt', low, previous), index(b, 1), index(b, 0));\n const high = b.int.add(\n b.int.add(b.array.load(clock, index(b, 1)), b.array.load(timeStep, index(b, 1))),\n carry,\n );\n b.array.store(clock, index(b, 0), low);\n b.array.store(clock, index(b, 1), b.int.and(high, index(b, 0x1fffff)));\n b.return([]);\n });\n inputs.body((b) => {\n allPins.forEach(({ pin }, id) => {\n const analog = analogInputs.get(id);\n if (analog !== undefined) b.call(analog.update, []);\n if (pin.input === undefined) return;\n const ref = pin.input.reference;\n const supply = b.array.load(solver.sourceVoltage, index(b, ref));\n const value = b.array.load(solver.voltage, index(b, pin.node));\n const low = b.float.cmp('le', value, b.float.mul(supply, b.const('f64', pin.input.low)));\n const high = b.float.cmp('ge', value, b.float.mul(supply, b.const('f64', pin.input.high)));\n const ready = b.bool.and(\n b.array.load(solver.sourceEnabled, index(b, ref)),\n b.bool.and(\n b.float.cmp('gt', supply, b.const('f64', 0)),\n b.int.cmp(\n 'eq',\n b.array.load(solver.voltageState, index(b, pin.node)),\n b.const('u8', 0),\n ),\n ),\n );\n const remembered = b.array.load(memory, index(b, id));\n const next = b.select(\n low,\n b.const('bool', false),\n b.select(high, b.const('bool', true), remembered),\n );\n b.array.store(memory, index(b, id), b.select(ready, next, remembered));\n b.array.store(\n sampled,\n index(b, id),\n b.bool.and(ready, interpretation === 'two-state' ? high : next),\n );\n });\n b.return([]);\n });\n };\n\n const refresh = new Map<number, FunctionRef<readonly [], readonly ['bool']>>();\n const pinFunctions = new Map<\n number,\n {\n readonly setMode: FunctionRef<readonly ['u8'], readonly []>;\n readonly setEnabled: FunctionRef<readonly ['bool'], readonly []>;\n readonly writeDigital: FunctionRef<readonly ['bool'], readonly []>;\n readonly writeVoltage: FunctionRef<readonly ['f64'], readonly []>;\n }\n >();\n allPins.forEach(({ pin }, id) => {\n if (pin.drive === undefined) return;\n const drive = pin.drive;\n const recompute = module.func(`${prefix}_pin_${id}_refresh`, { params: [], results: ['bool'] });\n refresh.set(id, recompute);\n recompute.body((b) => {\n const at = b.const('u32', id);\n const active = b.array.load(enabled, at);\n const selection = b.array.load(mode, at);\n const is = (which: number) => b.int.cmp('eq', selection, b.const('u8', which));\n const pushPull = is(PIN_MODE.pushPull);\n const digitalActive = b.bool.and(active, b.array.load(digitalReady, at));\n const level = b.array.load(digital, at);\n const high = b.bool.and(digitalActive, b.bool.and(pushPull, level));\n const low = b.bool.and(\n digitalActive,\n b.bool.and(b.bool.or(pushPull, is(PIN_MODE.openDrain)), b.bool.not(level)),\n );\n let changed = b.const('bool', false);\n const update = (branch: number, value: Value<'bool'>) => {\n changed = b.bool.or(\n changed,\n b.bool.xor(b.array.load(solver.resistorEnabled, b.const('u32', branch)), value),\n );\n b.array.store(solver.resistorEnabled, b.const('u32', branch), value);\n };\n update(drive.high, high);\n update(drive.low, low);\n if (drive.analog !== undefined)\n update(\n drive.analog.resistor,\n b.bool.and(active, b.bool.and(is(PIN_MODE.analog), b.array.load(voltageReady, at))),\n );\n b.return([changed]);\n });\n const setMode = module.func(`${prefix}_pin_${id}_mode`, { params: ['u8'], results: [] });\n setMode.body((b, [value]) =>\n running(b, (b) => {\n b.array.store(mode, index(b, id), value);\n const [changed] = b.call(recompute, []);\n return complete(b, changed, 'matrix');\n }),\n );\n const setEnabled = module.func(`${prefix}_pin_${id}_enable`, { params: ['bool'], results: [] });\n setEnabled.body((b, [value]) =>\n running(b, (b) => {\n b.array.store(enabled, index(b, id), value);\n const [changed] = b.call(recompute, []);\n return complete(b, changed, 'matrix');\n }),\n );\n const writeDigital = module.func(`${prefix}_pin_${id}_digital`, {\n params: ['bool'],\n results: [],\n });\n writeDigital.body((b, [value]) =>\n running(b, (b) => {\n b.array.store(digital, index(b, id), value);\n b.array.store(digitalReady, index(b, id), b.const('bool', true));\n const [changed] = b.call(recompute, []);\n return complete(b, changed, 'matrix');\n }),\n );\n const writeVoltage = module.func(`${prefix}_pin_${id}_voltage`, {\n params: ['f64'],\n results: [],\n });\n writeVoltage.body((b, [value]) =>\n running(b, (b) =>\n checked(\n b,\n b.float.isFinite(value),\n { kind: 1, index: index(b, drive.analog?.resistor ?? drive.high) },\n (b) => {\n if (drive.analog === undefined) {\n b.return([]);\n return;\n }\n const at = index(b, drive.analog.source);\n const changedRhs = b.float.cmp('ne', b.array.load(solver.sourceVoltage, at), value);\n b.array.store(solver.sourceVoltage, at, value);\n b.array.store(voltageReady, index(b, id), b.const('bool', true));\n const [changedMatrix] = b.call(recompute, []);\n return complete(b, changedMatrix, 'matrix', (b) => complete(b, changedRhs, 'rhs'));\n },\n ),\n ),\n );\n pinFunctions.set(id, { setMode, setEnabled, writeDigital, writeVoltage });\n });\n const pinIds = new Map<string, Map<string, number>>();\n allPins.forEach(({ deviceId, name }, id) => {\n let pins = pinIds.get(deviceId);\n if (pins === undefined) {\n pins = new Map();\n pinIds.set(deviceId, pins);\n }\n pins.set(name, id);\n });\n for (const deviceId of allocation.pins.keys())\n if (!pinIds.has(deviceId)) pinIds.set(deviceId, new Map());\n\n const deviceBinders = new Map<\n string,\n (b: Builder, globalIds?: ReadonlyMap<string, number>) => DeviceBindings\n >();\n for (const [deviceId, ids] of pinIds) {\n const ordinaryResistors = allocation.resistors.get(deviceId)!;\n const contacts = allocation.contacts.get(deviceId)!;\n const queueSize = Math.max(1, ids.size, ordinaryResistors.size, contacts.size);\n const deviceNumber = deviceBinders.size;\n const tag = `${prefix}_device_${deviceNumber}`;\n const queueId = module.array(`${tag}_ids`, 'u32', Array<number>(queueSize).fill(0));\n const queueNumber = module.array(`${tag}_numbers`, 'f64', Array<number>(queueSize).fill(1));\n const queueBool = module.array(`${tag}_flags`, 'bool', Array<boolean>(queueSize).fill(false));\n const valid = module.state(`${tag}_valid`, 'bool', true);\n const changed = module.state(`${tag}_changed`, 'bool', false);\n const positive = (b: Builder, value: Value<'f64'>) =>\n b.bool.and(b.float.isFinite(value), b.float.cmp('gt', value, b.const('f64', 0)));\n const applyResistors = module.func(`${tag}_resistances`, { params: ['u32'], results: [] });\n applyResistors.body((b, [count]) =>\n running(b, (b) => {\n b.state.store(valid, b.const('bool', true));\n return loop(\n b,\n count,\n (b, i) => {\n const accepted = positive(b, b.array.load(queueNumber, i));\n b.state.store(\n solver.faultTargetIndex,\n b.select(accepted, b.state.load(solver.faultTargetIndex), b.array.load(queueId, i)),\n );\n b.state.store(valid, b.bool.and(b.state.load(valid), accepted));\n },\n (b) =>\n checked(\n b,\n b.state.load(valid),\n { kind: 1, index: b.state.load(solver.faultTargetIndex) },\n (b) => {\n b.state.store(changed, b.const('bool', false));\n return loop(\n b,\n count,\n (b, i) => {\n const target = b.array.load(queueId, i);\n const value = b.array.load(queueNumber, i);\n b.state.store(\n changed,\n b.bool.or(\n b.state.load(changed),\n b.float.cmp('ne', b.array.load(solver.resistance, target), value),\n ),\n );\n b.array.store(solver.resistance, target, value);\n },\n (b) => complete(b, b.state.load(changed), 'matrix'),\n );\n },\n ),\n );\n }),\n );\n const applyConnections = module.func(`${tag}_contacts`, { params: ['u32'], results: [] });\n applyConnections.body((b, [count]) =>\n running(b, (b) => {\n b.state.store(changed, b.const('bool', false));\n return loop(\n b,\n count,\n (b, i) => {\n const target = b.array.load(queueId, i);\n const value = b.array.load(queueBool, i);\n b.state.store(\n changed,\n b.bool.or(\n b.state.load(changed),\n b.bool.xor(b.array.load(solver.contactClosed, target), value),\n ),\n );\n b.array.store(solver.contactClosed, target, value);\n },\n (b) => complete(b, b.state.load(changed), 'topology'),\n );\n }),\n );\n const writeDigitalGroup = module.func(`${tag}_digital_group`, { params: ['u32'], results: [] });\n writeDigitalGroup.body((b, [count]) =>\n running(b, (b) =>\n loop(\n b,\n count,\n (b, i) => {\n const target = b.array.load(queueId, i);\n b.array.store(digital, target, b.array.load(queueBool, i));\n b.array.store(digitalReady, target, b.const('bool', true));\n },\n (b) => {\n let changed = b.const('bool', false);\n for (const id of ids.values()) {\n const recompute = refresh.get(id);\n if (recompute === undefined) continue;\n const [value] = b.call(recompute, []);\n changed = b.bool.or(changed, value);\n }\n return complete(b, changed, 'matrix');\n },\n ),\n ),\n );\n const setResistorEnabled = module.func(`${tag}_resistor_enable`, {\n params: ['u32', 'bool'],\n results: [],\n });\n setResistorEnabled.body((b, [target, value]) =>\n running(b, (b) => {\n const changed = b.bool.xor(b.array.load(solver.resistorEnabled, target), value);\n b.array.store(solver.resistorEnabled, target, value);\n return complete(b, changed, 'matrix');\n }),\n );\n const setPull = new Map<number, FunctionRef<readonly ['u8'], readonly []>>();\n for (const id of ids.values()) {\n const bias = allPins[id]!.pin.bias;\n if (bias === undefined) continue;\n const fn = module.func(`${prefix}_pin_${id}_pull`, { params: ['u8'], results: [] });\n fn.body((b, [value]) =>\n running(b, (b) => {\n const up = b.int.cmp('eq', value, b.const('u8', 1));\n const down = b.int.cmp('eq', value, b.const('u8', 2));\n const changed = b.bool.or(\n b.bool.xor(b.array.load(solver.resistorEnabled, index(b, bias.up)), up),\n b.bool.xor(b.array.load(solver.resistorEnabled, index(b, bias.down)), down),\n );\n b.array.store(solver.resistorEnabled, index(b, bias.up), up);\n b.array.store(solver.resistorEnabled, index(b, bias.down), down);\n return complete(b, changed, 'matrix');\n }),\n );\n setPull.set(id, fn);\n }\n deviceBinders.set(deviceId, (b, globalIds) => {\n const lookup = (\n names: readonly string[],\n values: readonly unknown[],\n resources: ReadonlyMap<string, number>,\n ): number[] => {\n if (\n names.length === 0 ||\n names.length !== values.length ||\n new Set(names).size !== names.length\n )\n badResource(`Invalid atomic patch for \"${deviceId}\"`);\n return names.map(\n (name) =>\n resources.get(name) ?? badResource(`Unknown electrical resource \"${deviceId}.${name}\"`),\n );\n };\n const patch = (\n targets: readonly number[],\n values: readonly Value<'f64'>[] | readonly Value<'bool'>[],\n numeric: boolean,\n fn: FunctionRef<readonly ['u32'], readonly []>,\n ): void => {\n targets.forEach((target, i) => {\n b.array.store(queueId, index(b, i), index(b, target));\n if (numeric) b.array.store(queueNumber, index(b, i), values[i] as Value<'f64'>);\n else b.array.store(queueBool, index(b, i), values[i] as Value<'bool'>);\n });\n b.call(fn, [index(b, targets.length)]);\n };\n const handles = new Map<string, DevicePinHandle>();\n for (const [name, id] of ids) {\n const description: AllocatedElectricalPin = allPins[id]!.pin;\n const functions = () =>\n pinFunctions.get(id) ?? badResource(`Pin \"${deviceId}.${name}\" has no drive capability`);\n const handle: DevicePinHandle = Object.freeze({\n name,\n globalId: globalIds?.get(name) ?? id,\n configure(selection: number): void {\n if (!Object.values(PIN_MODE).includes(selection as 0 | 1 | 2 | 3))\n badResource(`Invalid pin mode ${selection}`);\n if (selection === PIN_MODE.analog && description.drive?.analog === undefined)\n badResource(`Pin \"${deviceId}.${name}\" has no analog drive capability`);\n if (selection === PIN_MODE.highZ && description.drive === undefined) return;\n b.call(functions().setMode, [b.const('u8', selection)]);\n },\n setOutputEnabled(value: Value<'bool'>): void {\n b.call(functions().setEnabled, [value]);\n },\n setPull(selection: 'none' | 'up' | 'down'): void {\n if (!['none', 'up', 'down'].includes(selection))\n badResource(`Invalid pull ${selection}`);\n const fn =\n setPull.get(id) ??\n (selection === 'none'\n ? undefined\n : badResource(`Pin \"${deviceId}.${name}\" has no bias capability`));\n if (fn === undefined) return;\n b.call(fn, [b.const('u8', selection === 'none' ? 0 : selection === 'up' ? 1 : 2)]);\n },\n writeDigital(value: Value<'bool'>): void {\n b.call(functions().writeDigital, [value]);\n },\n writeVoltage(value: Value<'f64'>): void {\n if (description.drive?.analog === undefined)\n badResource(`Pin \"${deviceId}.${name}\" has no analog drive capability`);\n b.call(functions().writeVoltage, [value]);\n },\n sampleDigital(): Value<'bool'> {\n if (description.input === undefined)\n badResource(`Pin \"${deviceId}.${name}\" has no input capability`);\n b.call(ensure, []);\n return b.array.load(sampled, index(b, id));\n },\n sampleVoltage(): Value<'f64'> {\n if (description.input === undefined)\n badResource(`Pin \"${deviceId}.${name}\" has no input capability`);\n let sample = analogRequests.get(id);\n if (sample === undefined) {\n if (finalized)\n badResource('Analog sampling must be declared before electrical finalization');\n sample = module.func(`${prefix}_analog_${id}_sample`, {\n params: [],\n results: ['f64'],\n });\n analogRequests.set(id, sample);\n }\n b.call(ensure, []);\n return b.call(sample, [])[0];\n },\n readDrivenDigital(): Value<'bool'> {\n functions();\n return b.array.load(digital, index(b, id));\n },\n });\n handles.set(name, handle);\n }\n return Object.freeze({\n pins: Object.freeze([...handles.values()]),\n outputs: Object.freeze(\n [...handles]\n .filter(([name]) => allPins[ids.get(name)!]!.pin.drive !== undefined)\n .map(([, handle]) => handle),\n ),\n pin(name: string): DevicePinHandle {\n return handles.get(name) ?? badResource(`Unknown pin \"${deviceId}.${name}\"`);\n },\n resistor(name: string): DeviceResistorHandle {\n const target =\n ordinaryResistors.get(name) ?? badResource(`Unknown resistor \"${deviceId}.${name}\"`);\n return Object.freeze({\n setResistance(value: Value<'f64'>): void {\n patch([target], [value], true, applyResistors);\n },\n setEnabled(value: Value<'bool'>): void {\n b.call(setResistorEnabled, [index(b, target), value]);\n },\n sampleCurrent(): Value<'f64'> {\n b.call(ensure, []);\n return b.array.load(solver.current, index(b, target));\n },\n });\n },\n writeDigitalGroup(names: readonly string[], values: readonly Value<'bool'>[]): void {\n const targets = lookup(names, values, ids);\n for (const id of targets)\n if (!pinFunctions.has(id))\n badResource(`Pin \"${allPins[id]!.name}\" has no drive capability`);\n patch(targets, values, false, writeDigitalGroup);\n },\n applyResistors(names: readonly string[], values: readonly Value<'f64'>[]): void {\n patch(lookup(names, values, ordinaryResistors), values, true, applyResistors);\n },\n applyConnections(names: readonly string[], values: readonly Value<'bool'>[]): void {\n patch(lookup(names, values, contacts), values, false, applyConnections);\n },\n });\n });\n }\n return Object.freeze({\n solver,\n ensure,\n clock,\n timeStep,\n advanceTime,\n finalize,\n digitalSample: sampled,\n digitalIntent: digital,\n pinIndices: new Map(allPins.map(({ deviceId, name }, index) => [`${deviceId}.${name}`, index])),\n bindDevice(\n deviceId: string,\n builder: Builder,\n globalIds?: ReadonlyMap<string, number>,\n ): DeviceBindings {\n const bind =\n deviceBinders.get(deviceId) ?? badResource(`Unknown electrical device \"${deviceId}\"`);\n return bind(builder, globalIds);\n },\n });\n}\n","import type { IRModule } from '@mica-js/ir';\nimport { prepareElectricalDevice } from '../../electrical-authoring';\nimport { allocateElectricalNetwork } from './electrical-network';\nimport type { AllocatedElectricalNetwork } from './electrical-network';\nimport { createElectricalOperations } from './electrical-operations';\nimport type { ElectricalOperations } from './electrical-operations';\nimport { UnifiedIRCompilerError } from './types';\nimport type { CircuitCompilationOptions, CompiledCircuit, Connection, DeviceConfig } from './types';\n\nexport interface ElectricalCompilation {\n readonly devices: readonly DeviceConfig[];\n readonly allocation: AllocatedElectricalNetwork;\n readonly operations: ElectricalOperations;\n}\n\nconst circuits = new WeakMap<CompiledCircuit, ElectricalCompilation>();\nexport const electricalCompilationOf = (\n circuit: CompiledCircuit,\n): ElectricalCompilation | undefined => circuits.get(circuit);\nexport function retainElectricalCompilation(\n circuit: CompiledCircuit,\n electrical: ElectricalCompilation,\n): void {\n circuits.set(circuit, electrical);\n}\n\n/** Keeps prepared resources and solver storage out of the public compiled description. */\nexport function prepareElectricalCompilation(\n module: IRModule,\n devices: readonly DeviceConfig[],\n connections: readonly Connection[],\n options: CircuitCompilationOptions,\n): ElectricalCompilation {\n const fail = (message: string): never => {\n throw new UnifiedIRCompilerError('invalid-input', message);\n };\n if ('rails' in options) fail('Unsupported boolean rails; declare explicit voltage sources');\n if (options.interpretation !== 'two-state' && options.interpretation !== 'retain-in-band')\n fail('Resistive circuits require an explicit digital interpretation');\n if (\n options.floatingSeed !== undefined &&\n (!Number.isInteger(options.floatingSeed) ||\n options.floatingSeed < 0 ||\n options.floatingSeed > 0xffff_ffff)\n )\n fail('floatingSeed must be a u32');\n const sources = options.sources ?? {};\n if (sources === null || typeof sources !== 'object' || Array.isArray(sources))\n fail('Voltage sources must be an object');\n for (const [id, source] of Object.entries(sources)) {\n if (\n !id ||\n id === 'GND' ||\n source === null ||\n typeof source !== 'object' ||\n !Number.isFinite(source.voltage)\n )\n fail(`Invalid voltage source \"${id}\"`);\n }\n const prepared = devices.map((device) => {\n const { description } = device;\n if (typeof description.factory !== 'function')\n fail(`Device \"${device.id}\" needs a paired electrical factory`);\n const properties = device.properties === undefined ? {} : device.properties;\n if (properties === null || typeof properties !== 'object' || Array.isArray(properties))\n fail(`Invalid properties for device \"${device.id}\"`);\n const result = prepareElectricalDevice(\n {\n ...description,\n pins:\n description.pins instanceof Map ? Object.fromEntries(description.pins) : description.pins,\n },\n properties,\n description.factory!,\n );\n const implementation = result.implementation;\n if (implementation !== undefined) {\n if (\n implementation === null ||\n typeof implementation !== 'object' ||\n Array.isArray(implementation)\n )\n fail(`Device \"${device.id}\" factory must return behavior hooks or undefined`);\n for (const [name, callback] of Object.entries(implementation)) {\n if (\n !['initialize', 'tick', 'update', 'kernel', 'applyInputs', 'flushOutputs'].includes(\n name,\n ) ||\n (callback !== undefined && typeof callback !== 'function')\n )\n fail(`Invalid factory behavior \"${device.id}.${name}\"`);\n }\n }\n const phases =\n implementation === undefined\n ? description.behaviors\n : {\n ...(implementation.initialize === undefined\n ? {}\n : { initialize: implementation.initialize }),\n ...(implementation.tick === undefined ? {} : { tick: implementation.tick }),\n ...(implementation.update === undefined ? {} : { update: implementation.update }),\n };\n if (phases !== undefined) {\n for (const [phase, callback] of Object.entries(phases)) {\n if (\n !['initialize', 'tick', 'update'].includes(phase) ||\n (callback !== undefined && typeof callback !== 'function')\n )\n fail(`Invalid factory behavior \"${device.id}.${phase}\"`);\n }\n }\n const hasPhases =\n phases !== undefined && Object.values(phases).some((value) => value !== undefined);\n if (implementation !== undefined && description.behaviors !== undefined)\n fail(`Device \"${device.id}\" declares both factory and static behaviors`);\n if (implementation?.kernel !== undefined && description.kernel !== undefined)\n fail(`Device \"${device.id}\" declares two kernels`);\n const kernel = implementation?.kernel ?? description.kernel;\n if (hasPhases && kernel !== undefined)\n fail(`Device \"${device.id}\" declares both behavior hooks and a kernel`);\n return {\n id: device.id,\n prepared: result,\n device: {\n ...device,\n properties: result.properties,\n description: {\n ...description,\n ...(phases === undefined || !hasPhases ? {} : { behaviors: phases }),\n ...(kernel === undefined ? {} : { kernel }),\n ...(implementation?.applyInputs === undefined\n ? {}\n : { applyInputs: implementation.applyInputs }),\n ...(implementation?.flushOutputs === undefined\n ? {}\n : { flushOutputs: implementation.flushOutputs }),\n },\n },\n };\n });\n const endpoint = (name: string) => {\n if (name === 'GND' || Object.hasOwn(sources, name)) return { source: name };\n const dot = name.indexOf('.');\n if (dot <= 0 || dot === name.length - 1) return fail(`Unknown electrical endpoint \"${name}\"`);\n return { device: name.slice(0, dot), pin: name.slice(dot + 1) };\n };\n const allocation = allocateElectricalNetwork(\n prepared,\n sources,\n connections.map(({ from, to }) => [endpoint(from), endpoint(to)] as const),\n );\n return {\n devices: prepared.map(({ device }) => device),\n allocation,\n operations: createElectricalOperations(\n module,\n allocation,\n options.interpretation!,\n 'electrical',\n options.floatingSeed,\n ),\n };\n}\n","import type { FunctionBuilder, FunctionRef, IRModule, StateRef } from '@mica-js/ir';\nimport type { ElectricalOperations } from './electrical-operations';\nimport type { DeviceLoopEntry } from './device-gen';\n\n/** Generated entry-point names. */\nexport interface MainLoopNames {\n readonly tick: string;\n readonly initialize: string;\n readonly batch: string;\n}\n\n/** Names used when the caller does not override them. */\nexport const DEFAULT_ENTRY_POINT_NAMES: MainLoopNames = Object.freeze({\n tick: 'unified_tick',\n initialize: 'unified_initialize',\n batch: 'unified_tick_batch',\n});\n\n/** The generated main loop. */\nexport interface MainLoopOutput {\n readonly names: MainLoopNames;\n readonly initialize: FunctionRef<readonly [], readonly []>;\n readonly tick: FunctionRef<readonly [], readonly []>;\n readonly batch: FunctionRef<readonly ['u32'], readonly []>;\n readonly progress: StateRef<'u32'>;\n /** Device ids in declaration order. */\n readonly order: readonly string[];\n}\n\n/**\n * Generates the circuit entries.\n *\n * ```text\n * unified_initialize: // once, before the first tick\n * drive1_initialize()\n * sink1_initialize() // if the device has one\n *\n * unified_tick: // one simulation step\n * drive1_tick() // drivers publish their outputs\n * electrical_ensure() // solve only if the network changed\n * sink1_update() // loads observe the solved inputs\n *\n * unified_tick_batch(count): // the same step, looped inside the IR\n * for i in 0 .. count { <step> }\n * ```\n *\n * Devices run in declaration order, with all tick phases before update phases.\n * Typed electrical sampling ensures pending network changes are solved.\n */\nexport class MainLoopGenerator {\n private readonly module: IRModule;\n\n constructor(\n module: IRModule,\n private readonly electrical: ElectricalOperations,\n ) {\n this.module = module;\n }\n\n /** Generates `initialize`, `tick` and the batched tick loop. */\n generate(\n entries: readonly DeviceLoopEntry[],\n names: MainLoopNames = DEFAULT_ENTRY_POINT_NAMES,\n ): MainLoopOutput {\n const order = Object.freeze(entries.map((entry) => entry.deviceId));\n const byId = new Map(entries.map((entry) => [entry.deviceId, entry]));\n\n const electrical = this.electrical;\n electrical.finalize();\n const progress = this.module.state(`${names.tick}_completed`, 'u32', 0);\n const collect = (phase: 'initialize' | 'tick' | 'update') =>\n order.flatMap((id) => {\n const ref = byId.get(id)?.[phase];\n return ref === undefined ? [] : [ref];\n });\n const ensure = [electrical.ensure];\n const phases = [...collect('tick'), ...ensure, ...collect('update'), ...ensure];\n const emitCalls = (\n b: FunctionBuilder<readonly []>,\n calls: readonly FunctionRef<readonly [], readonly []>[],\n finish: (b: FunctionBuilder<readonly []>) => undefined,\n ): undefined => {\n const emit = (b: FunctionBuilder<readonly []>, at: number): undefined => {\n const next = b.block([]);\n const failed = b.block([]);\n b.branch(\n b.int.cmp('eq', b.state.load(electrical.solver.fault), b.const('u8', 0)),\n { target: next, args: [] },\n { target: failed, args: [] },\n );\n b.at(failed, (b) => b.return([]));\n b.at(next, (b) => {\n const call = calls[at];\n if (call === undefined) return finish(b);\n b.call(call, []);\n return emit(b, at + 1);\n });\n };\n return emit(b, 0);\n };\n const completed = (b: FunctionBuilder<readonly []>): void => {\n b.call(electrical.advanceTime, []);\n b.state.store(progress, b.int.add(b.state.load(progress), b.const('u32', 1)));\n };\n const initialize = this.module.func(names.initialize, { params: [], results: [] });\n initialize.body((b) =>\n emitCalls(b, [...collect('initialize'), ...ensure], (b) => b.return([])),\n );\n const tick = this.module.func(names.tick, { params: [], results: [] });\n tick.body((b) => {\n b.state.store(progress, b.const('u32', 0));\n return emitCalls(b, phases, (b) => {\n completed(b);\n b.return([]);\n });\n });\n const batch = this.module.func(names.batch, { params: ['u32'], results: [] });\n batch.body((b, [count]) => {\n const header = b.block(['u32']);\n const body = b.block(['u32']);\n const done = b.block([]);\n b.state.store(progress, b.const('u32', 0));\n b.jump(header, [b.const('u32', 0)]);\n b.at(header, (b, [index]) =>\n b.branch(\n b.int.cmp('lt', index, count),\n { target: body, args: [index] },\n { target: done, args: [] },\n ),\n );\n b.at(body, (b, [index]) =>\n emitCalls(b, phases, (b) => {\n completed(b);\n b.jump(header, [b.int.add(index, b.const('u32', 1))]);\n }),\n );\n b.at(done, (b) => b.return([]));\n });\n\n return Object.freeze({\n names,\n initialize,\n tick,\n batch,\n progress,\n order,\n });\n }\n}\n","import { createIRModule, validateIR } from '@mica-js/ir';\nimport type { IRModule, IRValidationOptions } from '@mica-js/ir';\nimport { createModuleValidation } from '../validation';\nimport { GlobalResourceAllocator } from './allocator';\nimport { DeviceIRGenerator } from './device-gen';\nimport {\n prepareElectricalCompilation,\n retainElectricalCompilation,\n} from './electrical-compilation';\nimport { DEFAULT_ENTRY_POINT_NAMES, MainLoopGenerator, type MainLoopNames } from './mainloop-gen';\nimport {\n UnifiedIRCompilerError,\n type CircuitCompilationInput,\n type CircuitCompilationOptions,\n type CompiledCircuit,\n type Connection,\n type DeviceConfig,\n} from './types';\n\n/**\n * Compiles several devices and their wiring into one unified IR module (U01).\n *\n * Device models are caller-supplied: every entry of `devices` carries the pins,\n * states and behaviors (or `kernel`) its type needs.\n *\n * ```ts\n * const circuit = compileCircuit({\n * devices: [\n * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },\n * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },\n * ],\n * connections: [\n * { from: 'drive1.channel0', to: 'sink1.anode' },\n * { from: 'sink1.cathode', to: 'GND' },\n * ],\n * });\n *\n * const jit = createIRJIT(circuit.module, { validation: circuit.validation });\n * jit.execute(circuit.entryPoints.refs.initialize, []);\n * jit.execute(circuit.entryPoints.refs.tick, []); // drive1 + nets + sink1\n * ```\n *\n * The pipeline is: validate the input, allocate the global pin and state\n * spaces, analyse the electrical topology, generate one function per device\n * phase, generate the resistive network solver and main loop, then validate the\n * resulting module with `validateIR`.\n *\n * @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown\n * pins, electrical conflicts, or when the generated module fails validation.\n */\nexport function compileCircuit(\n input: CircuitCompilationInput,\n options: CircuitCompilationOptions = {},\n): CompiledCircuit {\n const validated = validateInput(input);\n const { connections } = validated;\n const resolvedOptions = validateOptions(options);\n const names = resolveEntryNames(resolvedOptions);\n\n const module = createIRModule();\n const allocation = new GlobalResourceAllocator(module).allocate(validated.devices);\n const electrical = prepareElectricalCompilation(\n module,\n validated.devices,\n connections,\n resolvedOptions,\n );\n const devices = electrical.devices;\n\n const generator = new DeviceIRGenerator({\n module,\n pins: allocation.pins,\n states: allocation.states,\n electrical: electrical.operations,\n });\n const generated = devices.map((device) => generator.generate(device));\n\n assertNoNameCollisions(devices, names);\n\n const loop = new MainLoopGenerator(module, electrical.operations).generate(\n generated.map((device) => device.entry),\n names,\n );\n\n const validation = createModuleValidation(\n module,\n devices.flatMap((device) => device.description.updateResources ?? []),\n );\n if (resolvedOptions.validate !== false) validateModule(module, validation);\n\n const deviceMap = new Map(generated.map((device) => [device.metadata.deviceId, device.metadata]));\n\n const compiled = Object.freeze({\n module,\n entryPoints: Object.freeze({\n tick: loop.names.tick,\n initialize: loop.names.initialize,\n batch: loop.names.batch,\n refs: Object.freeze({\n tick: loop.tick,\n initialize: loop.initialize,\n batch: loop.batch,\n }),\n }),\n progress: loop.progress,\n pinMap: allocation.pins.pins,\n deviceMap,\n pins: allocation.pins,\n states: allocation.states,\n validation,\n executionOrder: loop.order,\n functions: Object.freeze(module.functions.map((fn) => fn.name)),\n });\n retainElectricalCompilation(compiled, electrical);\n return compiled;\n}\n\nfunction validateInput(input: unknown): {\n readonly devices: readonly DeviceConfig[];\n readonly connections: readonly Connection[];\n} {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput must be an object with devices and connections',\n );\n }\n const { devices, connections } = input as Partial<CircuitCompilationInput>;\n if (!Array.isArray(devices) || devices.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.devices must be a non-empty array',\n );\n }\n if (!Array.isArray(connections)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n 'CircuitCompilationInput.connections must be an array',\n );\n }\n return { devices, connections };\n}\n\nfunction validateOptions(options: unknown): CircuitCompilationOptions {\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw new UnifiedIRCompilerError('invalid-input', 'Compile options must be an object');\n }\n const resolved = options as CircuitCompilationOptions;\n if (resolved.validate !== undefined && typeof resolved.validate !== 'boolean') {\n throw new UnifiedIRCompilerError('invalid-input', 'options.validate must be a boolean');\n }\n return resolved;\n}\n\nfunction resolveEntryNames(options: CircuitCompilationOptions): MainLoopNames {\n const names: MainLoopNames = {\n tick: options.entryPointNames?.tick ?? DEFAULT_ENTRY_POINT_NAMES.tick,\n initialize: options.entryPointNames?.initialize ?? DEFAULT_ENTRY_POINT_NAMES.initialize,\n batch: options.entryPointNames?.batch ?? DEFAULT_ENTRY_POINT_NAMES.batch,\n };\n for (const [role, name] of Object.entries(names)) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Entry point names.${role} must be a non-empty string`,\n );\n }\n }\n if (new Set(Object.values(names)).size !== 3) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Entry point names must be distinct: ${JSON.stringify(names)}`,\n );\n }\n return Object.freeze(names);\n}\n\nfunction assertNoNameCollisions(devices: readonly DeviceConfig[], names: MainLoopNames): void {\n const reserved = new Set<string>([names.tick, names.initialize, names.batch]);\n for (const device of devices) {\n for (const phase of ['initialize', 'tick', 'update'] as const) {\n const generated = `${device.id}_${phase}`;\n if (reserved.has(generated)) {\n throw new UnifiedIRCompilerError(\n 'invalid-input',\n `Device \"${device.id}\" generates \"${generated}\", which collides with another generated function; rename the device or the entry point`,\n { deviceId: device.id },\n );\n }\n }\n }\n}\n\nfunction validateModule(module: IRModule, validation: IRValidationOptions): void {\n const result = validateIR(module, validation);\n if (result.ok) return;\n const details = result.diagnostics\n .map((entry) => `- [${entry.code}] ${entry.message} at ${entry.location.path}`)\n .join('\\n');\n throw new UnifiedIRCompilerError(\n 'invalid-ir',\n `Generated IR failed validateIR (${result.diagnostics.length} diagnostic(s)):\\n${details}`,\n );\n}\n\nexport * from './types';\nexport { GlobalResourceAllocator, stateOffsetOf } from './allocator';\nexport type { ResourceAllocation } from './allocator';\nexport { DeviceIRGenerator } from './device-gen';\nexport type { DeviceGenerationContext, DeviceLoopEntry, GeneratedDevice } from './device-gen';\nexport { DEFAULT_ENTRY_POINT_NAMES, MainLoopGenerator } from './mainloop-gen';\nexport type { MainLoopNames, MainLoopOutput } from './mainloop-gen';\n","import type { IRJITTuning } from '@mica-js/ir';\nimport type { CircuitCompilationOptions } from '../compiler';\n\n/**\n * Types of the unified circuit runtime (U02).\n *\n * `Circuit` is the host-facing facade over one compiled unified IR module: it\n * owns the engine instance, the tick counter and the private step-boundary hook\n * plumbing. Everything here is transport-neutral; no type mentions the device\n * host or the schematic editor.\n */\n\n/** Execution engine a `Circuit` runs on. */\nexport type CircuitEngine = 'jit' | 'reference';\n\n/** Electrical-solve options forwarded to `compileCircuit`. */\nexport interface CircuitElectricalOptions {\n readonly sources?: CircuitCompilationOptions['sources'];\n readonly interpretation?: CircuitCompilationOptions['interpretation'];\n readonly floatingSeed?: CircuitCompilationOptions['floatingSeed'];\n}\n\n/**\n * Options for `Circuit.create`.\n *\n * @example\n * const circuit = await Circuit.create(input, { engine: 'reference' });\n */\nexport interface CircuitRuntimeOptions {\n /** Execution engine. Defaults to `'jit'`; `'reference'` runs the interpreter. */\n readonly engine?: CircuitEngine;\n /** JIT tuning. The runtime always supplies the module's own validation grant. */\n readonly jit?: IRJITTuning;\n /**\n * Run `validateIR` over the generated module during compilation.\n * Defaults to `true`; pass `false` only for measured warm paths.\n */\n readonly validateIR?: boolean;\n /** Electrical-solve options. */\n readonly electrical?: CircuitElectricalOptions;\n /** Instance id reported to the engine. Defaults to `'unified-circuit'`. */\n readonly instanceId?: string;\n}\n\n/** Error codes raised by `CircuitError`. */\nexport type CircuitErrorCode =\n | 'invalid-options'\n | 'invalid-count'\n | 'unsupported-operation'\n | 'state-not-found'\n | 'invalid-state-value'\n | 'unresolved-device'\n | 'disposed';\n\nexport interface CircuitErrorOptions {\n readonly deviceId?: string;\n readonly stateName?: string;\n readonly cause?: unknown;\n}\n\n/**\n * Error raised while driving a `Circuit`.\n *\n * The code is stable and machine-checkable, and the message always names the\n * offending device/pin/state plus the values that would have been accepted.\n */\nexport class CircuitError extends Error {\n override readonly name = 'CircuitError';\n readonly code: CircuitErrorCode;\n readonly deviceId: string | undefined;\n readonly stateName: string | undefined;\n\n constructor(code: CircuitErrorCode, message: string, options: CircuitErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.code = code;\n this.deviceId = options.deviceId;\n this.stateName = options.stateName;\n }\n}\n","import { toNumber, type EntryRef, type FloatBits, type RuntimeScalar } from '@mica-js/ir';\nimport type { CompiledCircuit, DeviceInput, DeviceMetadata, DeviceStateSlot } from '../compiler';\nimport type { IRInterpreter } from '@mica-js/ir';\nimport { CircuitError } from './types';\n\n/**\n * Step-boundary hook plumbing shared by the runtime and the RFC 0018 host.\n *\n * RFC 0017 runs `applyInputs` before a step and `flushOutputs` after it. The io\n * objects exist only for that call: they read and write the owning device's IR\n * memory, never arbitrary circuit storage, and they close as soon as the hook\n * returns. This module is package-internal; no accessor object is exposed.\n */\nexport interface DeviceBoundary {\n /** Whether the device declared an input hook in its paired factory. */\n hasInputHook(deviceId: string): boolean;\n /** Runs the device's `applyInputs` hook against this step's deliveries. */\n deliverInputs(deviceId: string, inputs: readonly DeviceInput[]): void;\n /** Runs the device's `flushOutputs` hook; each `publish` call leaves the device. */\n publishOutputs(deviceId: string, publish: (port: string, payload: unknown) => void): void;\n}\n\nexport interface DeviceBoundaryContext {\n readonly compiled: CompiledCircuit;\n readonly jit: IRInterpreter;\n readonly execute: (entry: EntryRef, args: readonly RuntimeScalar[]) => void;\n /** Throws once the owning circuit is disposed. */\n readonly assertActive: () => void;\n}\n\nexport function createDeviceBoundary(context: DeviceBoundaryContext): DeviceBoundary {\n const metadataOf = (deviceId: string): DeviceMetadata => {\n const device = context.compiled.deviceMap.get(deviceId);\n if (device === undefined) {\n throw new CircuitError('unresolved-device', `Circuit has no device \"${deviceId}\"`, {\n deviceId,\n });\n }\n return device;\n };\n\n return {\n hasInputHook: (deviceId) => metadataOf(deviceId).applyInputs !== undefined,\n\n deliverInputs(deviceId, inputs) {\n context.assertActive();\n const device = metadataOf(deviceId);\n const hook = device.applyInputs;\n if (hook === undefined) {\n if (inputs.length === 0) return;\n throw new CircuitError(\n 'unsupported-operation',\n `Device \"${device.deviceId}\" (${device.type}) declares no applyInputs hook`,\n { deviceId },\n );\n }\n const entries = new Set(device.entries ?? []);\n const pending = new Map<string, unknown[]>();\n for (const input of inputs) {\n const values = pending.get(input.port) ?? [];\n values.push(input.payload);\n pending.set(input.port, values);\n }\n let open = true;\n const active = () => {\n context.assertActive();\n if (!open) throw new TypeError('Input IO is only valid during applyInputs');\n };\n try {\n hook({\n takeInput(port) {\n active();\n const values = pending.get(port);\n pending.delete(port);\n return values?.at(-1);\n },\n takeInputs(port) {\n active();\n const values = pending.get(port) ?? [];\n pending.delete(port);\n return Object.freeze(values);\n },\n writeState(name, value) {\n active();\n const slot = stateSlotOf(device, name);\n const accepted = coerceStateValue(device, slot, value);\n try {\n context.jit.storage.storeArray(slot.array, slot.index, accepted);\n } catch (cause) {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${name}\" (${slot.type}) rejected ${String(value)}`,\n { deviceId: device.deviceId, stateName: name, cause },\n );\n }\n },\n call(entry, args) {\n active();\n if (!entries.has(entry)) throw new TypeError('Input entry must belong to this device');\n context.execute(entry, args);\n },\n });\n } finally {\n open = false;\n }\n },\n\n publishOutputs(deviceId, publish) {\n context.assertActive();\n const device = metadataOf(deviceId);\n const hook = device.flushOutputs;\n if (hook === undefined) return;\n let open = true;\n const active = () => {\n context.assertActive();\n if (!open) throw new TypeError('Output IO is only valid during flushOutputs');\n };\n try {\n hook({\n readState(name) {\n active();\n const slot = stateSlotOf(device, name);\n const value = context.jit.storage.loadArray(slot.array, slot.index);\n return typeof value === 'object' && value !== null && 'bits' in value\n ? toNumber(value as FloatBits)\n : value;\n },\n publish(port, payload) {\n active();\n publish(port, payload);\n },\n });\n } finally {\n open = false;\n }\n },\n };\n}\n\n/** Resolves one declared state slot of `device`, or throws with every state it declares. */\nfunction stateSlotOf(device: DeviceMetadata, name: string): DeviceStateSlot {\n const slot = device.states.get(name);\n if (slot === undefined) {\n const available = [...device.states.keys()];\n throw new CircuitError(\n 'state-not-found',\n `Device \"${device.deviceId}\" (${device.type}) has no state \"${name}\". Available: ${available.length === 0 ? '(none)' : `[${available.join(', ')}]`}`,\n { deviceId: device.deviceId, stateName: name },\n );\n }\n return slot;\n}\n\n/**\n * Validates a hook-written state value against the declared scalar type.\n * Range checks stay in storage, which owns the encoding.\n */\nfunction coerceStateValue(\n device: DeviceMetadata,\n slot: DeviceStateSlot,\n value: unknown,\n): RuntimeScalar {\n if (slot.type === 'bool') {\n if (typeof value !== 'boolean') {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is bool and needs true or false, received ${String(value)}`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n return value;\n }\n if (slot.type === 'f32' || slot.type === 'f64') {\n if (typeof value === 'number' || isFloatBits(value)) return value;\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is ${slot.type} and needs a number or FloatBits`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n throw new CircuitError(\n 'invalid-state-value',\n `State \"${device.deviceId}.${slot.name}\" is ${slot.type} and needs an integer, received ${String(value)}`,\n { deviceId: device.deviceId, stateName: slot.name },\n );\n }\n return value;\n}\n\nfunction isFloatBits(value: unknown): value is FloatBits {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as { readonly type?: unknown; readonly bits?: unknown };\n return (\n (candidate.type === 'f32' || candidate.type === 'f64') && typeof candidate.bits === 'string'\n );\n}\n","import { createIRInterpreter, createIRJIT } from '@mica-js/ir';\nimport type {\n ArrayRef,\n BytesRef,\n IRInterpreter,\n IRJITTuning,\n RuntimeScalar,\n StateRef,\n} from '@mica-js/ir';\nimport { compileCircuit } from '../compiler';\nimport type {\n CircuitCompilationInput,\n CircuitCompilationOptions,\n CompiledCircuit,\n} from '../compiler';\nimport { electricalCompilationOf } from '../compiler/electrical-compilation';\nimport { createDeviceBoundary } from './bridge';\nimport type { DeviceBoundary } from './bridge';\nimport { CircuitError, type CircuitEngine, type CircuitRuntimeOptions } from './types';\n\n/** Every generated entry takes no arguments, so one frozen array is reused. */\nconst NO_ARGS: readonly RuntimeScalar[] = Object.freeze([]);\n\n/** `unified_tick_batch` takes a u32 tick count. */\nconst MAX_BATCH_TICKS = 0xffff_ffff;\n\n/** Virtual time is a JS number, so it wraps before losing integer precision. */\nconst MAX_VIRTUAL_TIME = Number.MAX_SAFE_INTEGER;\n\nconst DEFAULT_INSTANCE_ID = 'unified-circuit';\n\n/**\n * Mutable execution context. `IRExecutionContext` is readonly for callers; the\n * runtime owns this object and updates `virtualTime` in place so that `step()`\n * allocates nothing on the hot path.\n */\ninterface RuntimeContext {\n instanceId: string;\n virtualTime: number;\n}\n\n/** Declared initial value of one memory resource, replayed by `reset()`. */\ntype ResetSeed =\n | { readonly kind: 'array'; readonly ref: ArrayRef; readonly values: readonly RuntimeScalar[] }\n | { readonly kind: 'state'; readonly ref: StateRef; readonly value: RuntimeScalar }\n | {\n readonly kind: 'bytes';\n readonly ref: BytesRef<false>;\n readonly values: readonly RuntimeScalar[];\n }\n | {\n readonly kind: 'readonly-bytes';\n readonly ref: BytesRef<true>;\n readonly values: Uint8Array;\n };\n\ninterface ResolvedRuntimeOptions {\n readonly engine: CircuitEngine;\n readonly jit: IRJITTuning | undefined;\n readonly validateIR: boolean;\n readonly sources: CircuitCompilationOptions['sources'];\n readonly interpretation: CircuitCompilationOptions['interpretation'];\n readonly floatingSeed: CircuitCompilationOptions['floatingSeed'];\n readonly instanceId: string;\n}\n\n/**\n * Host-facing runtime of one compiled unified circuit (U02).\n *\n * ```ts\n * const circuit = await Circuit.create({\n * devices: [\n * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },\n * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },\n * ],\n * connections: [\n * { from: 'drive1.PA0', to: 'sink1.anode' },\n * { from: 'sink1.cathode', to: 'GND' },\n * ],\n * });\n *\n * circuit.runBatch(1_000_000); // one engine call\n * expect(circuit.tickCount).toBe(1_000_000n);\n * circuit.reset();\n * circuit.step();\n * ```\n *\n * `Circuit` owns the engine instance, the tick counter and the private\n * step-boundary hook plumbing. RFC 0017 traffic belongs to the\n * `DeviceSimulationHost`: it delivers topic inputs before a step and publishes\n * the topic outputs the device hooks report afterwards. `Circuit` itself\n * exposes no device state, pin or electrical readback.\n *\n * The compiled module keeps every device, net and the main loop in one\n * `@mica-js/ir` module, so a batch is one interpreter/JIT call for the whole\n * circuit.\n */\nexport class Circuit {\n readonly #compiled: CompiledCircuit;\n readonly #jit: IRInterpreter;\n readonly #context: RuntimeContext;\n readonly #seeds: readonly ResetSeed[];\n #tickCount = 0n;\n #virtualTime = 0;\n #disposed = false;\n\n private constructor(\n compiled: CompiledCircuit,\n jit: IRInterpreter,\n instanceId: string,\n boundary: DeviceBoundary,\n seeds: readonly ResetSeed[],\n ) {\n this.#compiled = compiled;\n this.#jit = jit;\n this.#context = { instanceId, virtualTime: 0 };\n this.#seeds = seeds;\n boundaries.set(this, boundary);\n }\n\n /**\n * Compiles `input`, builds the engine instance and runs the generated\n * `initialize` entry once.\n *\n * @throws {UnifiedIRCompilerError} when the circuit cannot be compiled.\n * @throws {CircuitError} for invalid options.\n */\n static async create(\n input: CircuitCompilationInput,\n options: CircuitRuntimeOptions = {},\n ): Promise<Circuit> {\n const resolved = resolveOptions(options);\n const compiled = compileCircuit(input, compileOptionsOf(resolved));\n const jit = createEngine(compiled, resolved);\n const boundary = createDeviceBoundary({\n compiled,\n jit,\n execute: (entry, args) => {\n circuit.#context.virtualTime = circuit.#virtualTime;\n jit.execute(entry, args, circuit.#context);\n },\n assertActive: () => {\n circuit.#assertActive();\n },\n });\n const circuit = new Circuit(\n compiled,\n jit,\n resolved.instanceId,\n boundary,\n resetSeedsOf(compiled),\n );\n // `initialize` runs once at creation; `reset()` replays the same sequence\n // after restoring every memory to its declared initial value.\n jit.execute(compiled.entryPoints.refs.initialize, NO_ARGS, circuit.#context);\n return circuit;\n }\n\n /**\n * Runs `count` ticks inside one generated loop — the throughput path.\n *\n * The whole batch is one engine call. The clock advances by completed ticks,\n * including the completed prefix of a failed batch.\n *\n * @throws {CircuitError} with code `invalid-count` unless `count` is a u32.\n */\n runBatch(count: number, dt = 1): void {\n this.#assertActive();\n if (\n typeof count !== 'number' ||\n !Number.isSafeInteger(count) ||\n count < 0 ||\n count > MAX_BATCH_TICKS\n ) {\n throw new CircuitError(\n 'invalid-count',\n `runBatch(count) needs an integer in [0, ${MAX_BATCH_TICKS}], received ${String(count)}`,\n );\n }\n this.#setTimeStep(dt);\n if (count === 0) return;\n this.#context.virtualTime = this.#virtualTime;\n this.#jit.storage.storeState(this.#compiled.progress, 0);\n try {\n this.#jit.execute(this.#compiled.entryPoints.refs.batch, [count], this.#context);\n } finally {\n this.#advance(this.#jit.storage.loadState(this.#compiled.progress), dt);\n }\n }\n\n /**\n * Advances exactly one tick — the debugging path.\n *\n * Every call is one engine entry, so prefer `runBatch` for throughput.\n */\n step(dt = 1): void {\n this.#assertActive();\n this.#setTimeStep(dt);\n this.#context.virtualTime = this.#virtualTime;\n try {\n this.#jit.execute(this.#compiled.entryPoints.refs.tick, NO_ARGS, this.#context);\n } finally {\n this.#advance(this.#jit.storage.loadState(this.#compiled.progress), dt);\n }\n }\n\n /**\n * Restores every memory to its declared initial value, re-runs `initialize`\n * and resets `tickCount` to `0n`.\n *\n * Device state written by earlier ticks is discarded, so the circuit behaves\n * exactly like a freshly created one.\n */\n reset(): void {\n this.#assertActive();\n for (const seed of this.#seeds) {\n if (seed.kind === 'state') {\n this.#jit.storage.storeState(seed.ref, seed.value);\n continue;\n }\n if (seed.kind === 'bytes') {\n for (let index = 0; index < seed.values.length; index += 1) {\n this.#jit.storage.storeBytes(\n 'u8',\n 'little',\n seed.ref,\n index,\n seed.values[index] as RuntimeScalar,\n );\n }\n continue;\n }\n if (seed.kind === 'readonly-bytes') {\n try {\n this.#jit.storage.updateBytesFromBytes(seed.ref, 0, seed.values);\n } catch {\n // Read-only memories are constants unless their device explicitly\n // grants host update access (for example MCU firmware patching).\n }\n continue;\n }\n for (let index = 0; index < seed.values.length; index += 1) {\n this.#jit.storage.storeArray(seed.ref, index, seed.values[index] as RuntimeScalar);\n }\n }\n this.#tickCount = 0n;\n this.#virtualTime = 0;\n this.#context.virtualTime = 0;\n this.#jit.execute(this.#compiled.entryPoints.refs.initialize, NO_ARGS, this.#context);\n }\n\n /** Number of ticks completed since creation or the last `reset()`. */\n get tickCount(): bigint {\n this.#assertActive();\n return this.#tickCount;\n }\n\n /** Virtual tick time completed since creation or the last `reset()`. */\n get virtualTime(): number {\n this.#assertActive();\n return this.#virtualTime;\n }\n\n /** Whether `dispose()` already ran. */\n get disposed(): boolean {\n return this.#disposed;\n }\n\n /**\n * Releases the runtime. Idempotent; every later call throws a `CircuitError`\n * with code `disposed`.\n */\n dispose(): void {\n this.#disposed = true;\n this.#tickCount = 0n;\n this.#virtualTime = 0;\n }\n\n /** @internal Shared guard of the circuit and its boundary hooks. */\n #assertActive(): void {\n if (this.#disposed) {\n throw new CircuitError(\n 'disposed',\n 'Circuit has been disposed; create a new circuit to keep simulating',\n );\n }\n }\n\n #setTimeStep(dt: number): void {\n if (!Number.isSafeInteger(dt) || dt <= 0)\n throw new CircuitError(\n 'invalid-options',\n 'Tick duration must be a positive safe integer in picoseconds',\n );\n const electrical = electricalCompilationOf(this.#compiled);\n if (electrical !== undefined) {\n this.#jit.storage.storeArray(electrical.operations.timeStep, 0, dt >>> 0);\n this.#jit.storage.storeArray(electrical.operations.timeStep, 1, Math.floor(dt / 0x100000000));\n }\n }\n\n #advance(count: number, dt: number): void {\n this.#tickCount += BigInt(count);\n const elapsed = count * dt;\n const next = this.#virtualTime + elapsed;\n this.#virtualTime = Number.isSafeInteger(next)\n ? next\n : Number(\n (BigInt(this.#virtualTime) + BigInt(count) * BigInt(dt)) %\n (BigInt(MAX_VIRTUAL_TIME) + 1n),\n );\n }\n}\n\nconst boundaries = new WeakMap<Circuit, DeviceBoundary>();\n\n/**\n * Step-boundary hooks of one circuit.\n *\n * The device simulation host is the only package-level caller: RFC 0017 traffic\n * enters through `applyInputs` and leaves through `flushOutputs`, never through\n * a device accessor. This function is deliberately absent from the package\n * entry points.\n */\nexport function deviceBoundaryOf(circuit: Circuit): DeviceBoundary {\n const boundary = boundaries.get(circuit);\n if (boundary === undefined)\n throw new CircuitError(\n 'invalid-options',\n 'Argument must be a Circuit created by Circuit.create',\n );\n return boundary;\n}\n\n/**\n * Captures the declared initial value of every scalar memory, which is what\n * `reset()` restores before the generated `initialize` runs again.\n */\nfunction resetSeedsOf(compiled: CompiledCircuit): readonly ResetSeed[] {\n const seeds: ResetSeed[] = [];\n for (const memory of compiled.module.memories) {\n if (memory.kind === 'array') {\n seeds.push({\n kind: 'array',\n ref: memory.ref as ArrayRef,\n values: memory.initial as readonly RuntimeScalar[],\n });\n } else if (memory.kind === 'state') {\n seeds.push({\n kind: 'state',\n ref: memory.ref as StateRef,\n value: memory.initial[0] as RuntimeScalar,\n });\n } else if (memory.kind === 'bytes') {\n if (memory.writable) {\n seeds.push({\n kind: 'bytes',\n ref: memory.ref as BytesRef<false>,\n values: memory.initial as readonly RuntimeScalar[],\n });\n } else {\n seeds.push({\n kind: 'readonly-bytes',\n ref: memory.ref as BytesRef<true>,\n values: Uint8Array.from(memory.initial as readonly number[]),\n });\n }\n }\n }\n return Object.freeze(seeds);\n}\n\nfunction createEngine(compiled: CompiledCircuit, options: ResolvedRuntimeOptions): IRInterpreter {\n const base = {\n validation: compiled.validation,\n // One batch can execute hundreds of millions of instructions; the default\n // step budget is tuned for single entries, not for a loop in the IR.\n maxSteps: Number.MAX_SAFE_INTEGER,\n };\n if (options.engine === 'reference') {\n return createIRInterpreter(compiled.module, base);\n }\n return createIRJIT(compiled.module, {\n ...base,\n jit: { tierUpThreshold: 0, ...options.jit },\n });\n}\n\nfunction compileOptionsOf(options: ResolvedRuntimeOptions): CircuitCompilationOptions {\n return {\n validate: options.validateIR,\n ...(options.sources === undefined ? {} : { sources: options.sources }),\n ...(options.interpretation === undefined ? {} : { interpretation: options.interpretation }),\n ...(options.floatingSeed === undefined ? {} : { floatingSeed: options.floatingSeed }),\n };\n}\n\nfunction resolveOptions(options: unknown): ResolvedRuntimeOptions {\n if (options === null || typeof options !== 'object' || Array.isArray(options)) {\n throw new CircuitError('invalid-options', 'Circuit options must be a plain object');\n }\n const candidate = options as CircuitRuntimeOptions;\n\n const engine = candidate.engine ?? 'jit';\n if (engine !== 'jit' && engine !== 'reference') {\n throw new CircuitError(\n 'invalid-options',\n `engine=${String(engine)} must be \"jit\" or \"reference\"`,\n );\n }\n\n if (candidate.validateIR !== undefined && typeof candidate.validateIR !== 'boolean') {\n throw new CircuitError('invalid-options', 'validateIR must be a boolean');\n }\n\n if (candidate.instanceId !== undefined && candidate.instanceId.length === 0) {\n throw new CircuitError('invalid-options', 'instanceId must be a non-empty string');\n }\n\n if (candidate.jit !== undefined) {\n if (\n candidate.jit === null ||\n typeof candidate.jit !== 'object' ||\n Array.isArray(candidate.jit)\n ) {\n throw new CircuitError('invalid-options', 'jit must be a JIT tuning object');\n }\n }\n\n if (candidate.electrical !== undefined) {\n const electrical = candidate.electrical;\n if (electrical === null || typeof electrical !== 'object' || Array.isArray(electrical)) {\n throw new CircuitError('invalid-options', 'electrical must be a plain object');\n }\n if ('rails' in electrical)\n throw new CircuitError(\n 'invalid-options',\n 'Boolean rails are unsupported; declare explicit voltage sources',\n );\n }\n\n return Object.freeze({\n engine,\n jit: candidate.jit,\n validateIR: candidate.validateIR ?? true,\n sources: candidate.electrical?.sources,\n interpretation: candidate.electrical?.interpretation,\n floatingSeed: candidate.electrical?.floatingSeed,\n instanceId: candidate.instanceId ?? DEFAULT_INSTANCE_ID,\n });\n}\n","import type { PayloadType } from '@mica-js/core/canvas';\nimport { deriveSchematicTopology, parseDeviceReference, symbolRole } from '@mica-js/core/schematic';\nimport type {\n DeviceReference,\n DeviceSymbolProvider,\n SchematicDocument,\n} from '@mica-js/core/schematic';\nimport type {\n CircuitCompilationInput,\n Connection,\n DeviceConfig,\n DeviceDescription,\n} from '../compiler';\nimport { Circuit } from './circuit';\nimport { CircuitError, type CircuitRuntimeOptions } from './types';\n\n/**\n * One endpoint a caller-supplied device declares to the simulation host.\n *\n * The simulator never guesses ports from a device type: the package that\n * resolves the reference states which payloads the device accepts and which it\n * publishes, in the same place it supplies the IR description.\n */\nexport interface SchematicDeviceTopic {\n readonly port: string;\n readonly direction: 'input' | 'output';\n readonly type: PayloadType;\n readonly title?: string;\n}\n\n/** Runtime behaviour of one schematic device package. */\nexport interface SchematicDeviceBinding {\n /** Device type, e.g. `'counter-ir'`. */\n readonly type: string;\n /** IR description: pins, states, factory, behaviours and boundary hooks. */\n readonly description: DeviceDescription;\n /** Instance configuration reserved for device kernels. */\n readonly config?: Readonly<Record<string, unknown>>;\n /**\n * Endpoints the simulation host exposes; absent means the device has none.\n *\n * A host routes payloads through the description's `applyInputs` /\n * `flushOutputs` hooks: topic names are host-facing, never a route into\n * device state.\n */\n readonly topics?: readonly SchematicDeviceTopic[];\n}\n\n/** Options for {@link createCircuitFromSchematic}. */\nexport interface SchematicCircuitOptions extends CircuitRuntimeOptions {\n /**\n * Symbol geometry provider — pass the same provider that authored the\n * schematic. Without it the derived topology contains no pins.\n */\n readonly devices?: DeviceSymbolProvider;\n /** Resolves a schematic device reference to its runtime description. */\n readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n /** Coordinate tolerance used when matching pins to wires. */\n readonly tolerance?: number;\n}\n\n/**\n * Compiles a schematic sheet into a circuit.\n *\n * Nets come from `deriveSchematicTopology`, so wires, junctions, labels and\n * power symbols keep their usual meaning: a net that names a rail connects\n * every member to that rail, and any other net joins its pins pairwise (the\n * compiler merges transitively).\n *\n * ```ts\n * const circuit = await createCircuitFromSchematic(schematic, {\n * devices: symbolProvider,\n * resolveDevice: (reference) => bindings.get(reference.deviceId),\n * });\n * ```\n *\n * @throws {CircuitError} with code `unresolved-device` when a component symbol\n * has no binding; `SchematicError` for malformed sheets.\n */\nexport async function createCircuitFromSchematic(\n schematic: SchematicDocument,\n options: SchematicCircuitOptions,\n): Promise<Circuit> {\n return (await createSchematicCircuit(schematic, options)).circuit;\n}\n\n/** One component symbol of a compiled schematic. */\nexport interface SchematicCircuitBinding {\n /** Symbol id as written in the schematic. */\n readonly symbolId: string;\n /** Compiler-safe device id assigned to the symbol. */\n readonly deviceId: string;\n /** Parsed `\"<packageId>:<deviceId>\"` reference. */\n readonly reference: DeviceReference;\n /** Device type from the resolved runtime binding. */\n readonly type: string;\n}\n\n/** A compiled schematic circuit plus the symbol-to-device mapping it produced. */\nexport interface SchematicCircuitResult {\n readonly circuit: Circuit;\n /** Component symbols in schematic order; non-component symbols are absent. */\n readonly bindings: readonly SchematicCircuitBinding[];\n}\n\n/** Package-internal result of lowering one schematic to a compiler input. */\nexport interface SchematicCompiledInput {\n readonly input: CircuitCompilationInput;\n readonly bindings: readonly SchematicCircuitBinding[];\n}\n\n/**\n * Lowers a schematic sheet to the netlist {@link createSchematicCircuit} compiles.\n *\n * Kept package-internal: the public factory returns the running circuit, while\n * the solver suites need the same device configs and connections without a\n * second schematic implementation.\n */\nexport function compileSchematicInput(\n schematic: SchematicDocument,\n options: SchematicCircuitOptions,\n): SchematicCompiledInput {\n if (\n schematic === null ||\n typeof schematic !== 'object' ||\n schematic.sheet === null ||\n typeof schematic.sheet !== 'object' ||\n !Array.isArray(schematic.sheet.symbols) ||\n !Array.isArray(schematic.sheet.wires) ||\n !Array.isArray(schematic.sheet.junctions)\n ) {\n throw new CircuitError(\n 'invalid-options',\n 'createSchematicCircuit needs a schematic with sheet.symbols, sheet.wires and sheet.junctions',\n );\n }\n if (options === null || typeof options !== 'object') {\n throw new CircuitError('invalid-options', 'createSchematicCircuit needs options');\n }\n const { resolveDevice, devices, tolerance } = options;\n if (typeof resolveDevice !== 'function') {\n throw new CircuitError('invalid-options', 'resolveDevice must be a function');\n }\n\n const usedIds = new Set<string>();\n const deviceIdBySymbol = new Map<string, string>();\n const deviceConfigs: DeviceConfig[] = [];\n const bindings: SchematicCircuitBinding[] = [];\n let componentCount = 0;\n\n for (const symbol of schematic.sheet.symbols) {\n if (symbolRole(symbol.device) !== 'component') continue;\n componentCount += 1;\n const reference = parseDeviceReference(symbol.device);\n const binding = reference === undefined ? undefined : resolveDevice(reference);\n if (binding === undefined) {\n throw new CircuitError(\n 'unresolved-device',\n `Symbol \"${symbol.id}\" (${symbol.device}) has no runtime device binding; resolve it in resolveDevice`,\n { deviceId: symbol.id },\n );\n }\n const deviceId = uniqueDeviceId(symbol.designator ?? symbol.id, usedIds);\n usedIds.add(deviceId);\n deviceIdBySymbol.set(symbol.id, deviceId);\n deviceConfigs.push({\n id: deviceId,\n type: binding.type,\n description: binding.description,\n ...(symbol.properties === undefined ? {} : { properties: symbol.properties }),\n ...(binding.config === undefined ? {} : { config: binding.config }),\n });\n if (reference !== undefined) {\n bindings.push({\n symbolId: symbol.id,\n deviceId,\n reference,\n type: binding.type,\n });\n }\n }\n\n const topology = deriveSchematicTopology(schematic, {\n ...(devices === undefined ? {} : { devices }),\n ...(tolerance === undefined ? {} : { tolerance }),\n });\n if (componentCount > 0 && topology.pins.length === 0) {\n throw new CircuitError(\n 'invalid-options',\n 'The derived topology has no pins; pass the DeviceSymbolProvider that authored the schematic so pins can be located',\n );\n }\n\n const railNames = new Set(['GND', ...Object.keys(options.electrical?.sources ?? {})]);\n const connections: Connection[] = [];\n\n for (const net of topology.nets) {\n const endpoints: string[] = [];\n let rail: string | undefined;\n for (const member of net.members) {\n if (member.kind === 'pin') {\n const deviceId = deviceIdBySymbol.get(member.symbolId);\n if (deviceId === undefined) {\n throw new CircuitError(\n 'unresolved-device',\n `Net \"${net.name ?? 'anonymous'}\" references pin \"${member.pinId}\" of symbol \"${member.symbolId}\", which has no runtime device`,\n { deviceId: member.symbolId },\n );\n }\n endpoints.push(`${deviceId}.${member.pinId}`);\n continue;\n }\n if (member.kind === 'power' || member.kind === 'ground') {\n rail = net.name ?? rail;\n }\n }\n if (endpoints.length === 0) continue;\n // A named net that matches a rail ties its pins to that rail; everything\n // else is joined to the first pin, which the compiler merges transitively.\n const railName = rail ?? (net.name !== null && railNames.has(net.name) ? net.name : undefined);\n if (railName !== undefined) {\n for (const endpoint of endpoints) connections.push({ from: endpoint, to: railName });\n continue;\n }\n const first = endpoints[0] as string;\n for (const endpoint of endpoints.slice(1)) connections.push({ from: first, to: endpoint });\n }\n\n const input: CircuitCompilationInput = {\n devices: Object.freeze(deviceConfigs),\n connections: Object.freeze(connections),\n };\n return Object.freeze({ input, bindings: Object.freeze(bindings) });\n}\n\n/**\n * Compiles a schematic and reports which circuit device each symbol became.\n *\n * {@link createCircuitFromSchematic} returns only the circuit; the host needs\n * the symbol-to-device mapping as well.\n */\nexport async function createSchematicCircuit(\n schematic: SchematicDocument,\n options: SchematicCircuitOptions,\n): Promise<SchematicCircuitResult> {\n const { input, bindings } = compileSchematicInput(schematic, options);\n const circuit = await Circuit.create(input, options);\n return Object.freeze({ circuit, bindings });\n}\n\n/**\n * Turns a designator or symbol id into a compiler-safe device id.\n *\n * Device ids prefix generated IR function names, so they must be identifiers.\n */\nfunction uniqueDeviceId(preferred: string, used: ReadonlySet<string>): string {\n const base = sanitizeDeviceId(preferred);\n if (!used.has(base)) return base;\n for (let suffix = 2; ; suffix += 1) {\n const candidate = `${base}_${suffix}`;\n if (!used.has(candidate)) return candidate;\n }\n}\n\nfunction sanitizeDeviceId(value: string): string {\n const cleaned = value.replace(/[^A-Za-z0-9_]/g, '_');\n if (cleaned.length === 0) return 'device';\n return /^[A-Za-z_]/.test(cleaned) ? cleaned : `d_${cleaned}`;\n}\n","import { parseSchematic } from '@mica-js/core/schematic';\nimport type { DeviceReference, DeviceSymbolProvider } from '@mica-js/core/schematic';\nimport type { SchematicDocument } from '@mica-js/core/schematic';\nimport type { CanvasBindingTarget, PayloadType } from '@mica-js/core/canvas';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport { createSchematicCircuit } from '../unified-ir/runtime';\nimport { deviceBoundaryOf } from '../unified-ir/runtime/circuit';\nimport type { DeviceBoundary } from '../unified-ir/runtime/bridge';\nimport type {\n Circuit,\n CircuitElectricalOptions,\n SchematicDeviceBinding,\n SchematicDeviceTopic,\n} from '../unified-ir/runtime';\nimport type {\n DeviceSimulationHost,\n DeviceSimTickReport,\n DeviceTopic,\n SimulationPublish,\n} from './types';\n\n/** Reads the bytes of one schematic URI; the caller resolves relative references. */\nexport interface SchematicDeviceSimulationHostOptions {\n /** Local startup configuration, not an RPC method or payload. */\n readonly electrical?: CircuitElectricalOptions;\n readonly read: (uri: string) => Promise<Uint8Array>;\n /**\n * Symbol geometry of the schematics this host loads. Pass the same provider the schematic was\n * authored with; without it the derived topology contains no pins. A factory is called when a\n * schematic loads, so a caller can read its device library first.\n */\n readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);\n /**\n * Resolves one schematic device reference to its runtime description and endpoints.\n *\n * The host ships no device models: the package that owns the devices decides which references\n * exist, what they look like and which topics they expose.\n */\n readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n}\n\ninterface LoadedDevice {\n readonly symbol: string;\n readonly deviceId: string;\n readonly designator: string;\n readonly binding: SchematicDeviceBinding;\n}\n\ninterface LoadedRuntime {\n readonly circuit: Circuit;\n readonly boundary: DeviceBoundary;\n readonly schematic: SchematicDocument;\n readonly devices: readonly LoadedDevice[];\n readonly topics: readonly DeviceTopic[];\n readonly inputs: ReadonlyMap<string, InputBinding>;\n}\n\ninterface InputBinding {\n readonly device: LoadedDevice;\n readonly topic: SchematicDeviceTopic;\n}\n\ninterface PendingDelivery {\n readonly device: LoadedDevice;\n readonly port: string;\n readonly payload: unknown;\n}\n\nconst INSTANCE_ID = 'device-simulation-host';\n\nfunction targetKey(deviceId: string, port: string): string {\n return `${deviceId}\\u0000${port}`;\n}\n\n/**\n * Value equality of two topic payloads.\n *\n * A canvas topic is a `level` unless it carries text or bytes (RFC 0017), so re-sending the value a\n * device already published only costs a widget repaint. Byte payloads compare by content because a\n * device may hand out a fresh buffer per step.\n */\nfunction samePayload(previous: unknown, next: unknown): boolean {\n if (Object.is(previous, next)) return true;\n if (previous instanceof Uint8Array && next instanceof Uint8Array) {\n if (previous.length !== next.length) return false;\n for (let index = 0; index < previous.length; index += 1) {\n if (previous[index] !== next[index]) return false;\n }\n return true;\n }\n if (typeof previous !== 'object' || previous === null) return false;\n if (typeof next !== 'object' || next === null) return false;\n const a = previous as { readonly x?: unknown; readonly y?: unknown; readonly z?: unknown };\n const b = next as { readonly x?: unknown; readonly y?: unknown; readonly z?: unknown };\n return a.x === b.x && a.y === b.y && a.z === b.z;\n}\n\nfunction isVec2d(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) return false;\n const point = value as { readonly x?: unknown; readonly y?: unknown };\n return typeof point.x === 'number' && typeof point.y === 'number';\n}\n\nfunction payloadMatches(type: PayloadType, payload: unknown): boolean {\n switch (type) {\n case 'boolean':\n return typeof payload === 'boolean';\n case 'number':\n return typeof payload === 'number';\n case 'string':\n return typeof payload === 'string';\n case 'bytes':\n case 'bytes<rgb565>':\n case 'bytes<segments>':\n return payload instanceof Uint8Array;\n case 'vec2d':\n return isVec2d(payload);\n case 'vec3d':\n return isVec2d(payload) && typeof (payload as { readonly z?: unknown }).z === 'number';\n }\n}\n\nfunction decodeSchematic(bytes: Uint8Array): SchematicDocument {\n return parseSchematic(new TextDecoder().decode(bytes));\n}\n\nfunction buildRuntime(\n circuit: Circuit,\n schematic: SchematicDocument,\n bindings: Awaited<ReturnType<typeof createSchematicCircuit>>['bindings'],\n resolveDevice: SchematicDeviceSimulationHostOptions['resolveDevice'],\n): LoadedRuntime {\n const symbols = new Map(schematic.sheet.symbols.map((symbol) => [symbol.id, symbol]));\n const devices: LoadedDevice[] = [];\n const topics: DeviceTopic[] = [];\n const inputs = new Map<string, InputBinding>();\n\n for (const binding of bindings) {\n const deviceBinding = resolveDevice(binding.reference);\n if (deviceBinding === undefined) continue;\n const symbol = symbols.get(binding.symbolId);\n const designator = symbol?.designator ?? binding.symbolId;\n const device: LoadedDevice = {\n symbol: binding.symbolId,\n deviceId: binding.deviceId,\n designator,\n binding: deviceBinding,\n };\n devices.push(device);\n for (const topic of deviceBinding.topics ?? []) {\n topics.push({\n symbol: binding.symbolId,\n designator,\n port: topic.port,\n direction: topic.direction,\n type: topic.type,\n ...(topic.title === undefined ? {} : { title: topic.title }),\n });\n if (topic.direction === 'input')\n inputs.set(targetKey(binding.symbolId, topic.port), { device, topic });\n }\n }\n\n return {\n circuit,\n boundary: deviceBoundaryOf(circuit),\n schematic,\n devices,\n topics: Object.freeze(topics),\n inputs,\n };\n}\n\n/**\n * Same-thread `DeviceSimulationHost` over a schematic compiled by the unified-IR runtime.\n *\n * The host owns the circuit: `loadSchematic` reads, parses and compiles it, `tick` advances one\n * circuit step and publishes the output topics that changed, and `deliver` queues widget payloads\n * for the next step. Device models and their endpoints come from `resolveDevice`, so the host stays\n * generic. Nothing here touches the DOM, so the sandbox guest and a Node test use the same\n * implementation.\n */\nexport function createSchematicDeviceSimulationHost(\n options: SchematicDeviceSimulationHostOptions,\n): DeviceSimulationHost {\n if (typeof options?.resolveDevice !== 'function') {\n throw new TypeError('createSchematicDeviceSimulationHost needs a resolveDevice function');\n }\n const { read, devices: symbols, resolveDevice } = options;\n const publishes = new Emitter<SimulationPublish>();\n const pending: PendingDelivery[] = [];\n /** Last payload published per endpoint, so an unchanged level topic stays silent. */\n const published = new Map<string, unknown>();\n let runtime: LoadedRuntime | undefined;\n let simTimePs = 0;\n let disposed = false;\n\n const publishOutput = (device: LoadedDevice, port: string, payload: unknown): void => {\n const topic = device.binding.topics?.find(\n (value) => value.port === port && value.direction === 'output',\n );\n if (topic === undefined)\n throw new TypeError(`Unknown output topic ${device.designator}.${port}`);\n if (!payloadMatches(topic.type, payload))\n throw new TypeError(`Invalid output payload for ${device.designator}.${port}`);\n if (!publishes.hasListeners) return;\n const key = targetKey(device.symbol, port);\n if (published.has(key) && samePayload(published.get(key), payload)) return;\n published.set(key, payload);\n publishes.fire({ target: { symbol: device.symbol, port }, payload, simTime: simTimePs });\n };\n const publishOutputs = (\n active: LoadedRuntime,\n diagnostics: NonNullable<DeviceSimTickReport['diagnostics']>[number][],\n ): void => {\n for (const device of active.devices) {\n try {\n active.boundary.publishOutputs(device.deviceId, (port, payload) =>\n publishOutput(device, port, payload),\n );\n } catch (cause) {\n diagnostics.push({\n code: 'device/output-failed',\n deviceId: device.symbol,\n message: cause instanceof Error ? cause.message : String(cause),\n });\n }\n }\n };\n\n const clearRuntime = (): void => {\n runtime?.circuit.dispose();\n runtime = undefined;\n pending.length = 0;\n published.clear();\n simTimePs = 0;\n };\n\n return {\n async loadSchematic(uri: string | undefined): Promise<void> {\n if (disposed) return;\n if (uri === undefined) {\n clearRuntime();\n return;\n }\n const bytes = await read(uri);\n const schematic = decodeSchematic(bytes);\n const symbolProvider = typeof symbols === 'function' ? symbols() : symbols;\n const compiled = await createSchematicCircuit(schematic, {\n ...(symbolProvider === undefined ? {} : { devices: symbolProvider }),\n resolveDevice,\n ...(options.electrical === undefined ? {} : { electrical: options.electrical }),\n instanceId: INSTANCE_ID,\n });\n const next = buildRuntime(compiled.circuit, schematic, compiled.bindings, resolveDevice);\n runtime?.circuit.dispose();\n pending.length = 0;\n // A fresh runtime starts from its initial state, so the first step after it publishes again.\n published.clear();\n simTimePs = 0;\n runtime = next;\n },\n\n async reset(): Promise<void> {\n if (disposed) return;\n pending.length = 0;\n published.clear();\n simTimePs = 0;\n runtime?.circuit.reset();\n },\n\n async tick(dt: number): Promise<DeviceSimTickReport> {\n if (!Number.isSafeInteger(dt) || dt <= 0) {\n throw new TypeError(\n `DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`,\n );\n }\n if (disposed) {\n return { simTime: simTimePs, executed: 0 };\n }\n const active = runtime;\n if (active === undefined) {\n simTimePs += dt;\n return { simTime: simTimePs, executed: 0 };\n }\n const queued = pending.splice(0, pending.length);\n const deliveries = new Map<LoadedDevice, { port: string; payload: unknown }[]>();\n for (const delivery of queued) {\n const values = deliveries.get(delivery.device) ?? [];\n values.push({ port: delivery.port, payload: delivery.payload });\n deliveries.set(delivery.device, values);\n }\n const diagnostics: NonNullable<DeviceSimTickReport['diagnostics']>[number][] = [];\n for (const device of active.devices) {\n const inputs = deliveries.get(device);\n if (inputs === undefined && !active.boundary.hasInputHook(device.deviceId)) continue;\n try {\n active.boundary.deliverInputs(device.deviceId, inputs ?? []);\n } catch (cause) {\n diagnostics.push({\n code: 'device/input-failed',\n deviceId: device.symbol,\n message: cause instanceof Error ? cause.message : String(cause),\n });\n }\n }\n const before = active.circuit.tickCount;\n try {\n active.circuit.runBatch(1, dt);\n } finally {\n simTimePs += dt * Number(active.circuit.tickCount - before);\n }\n publishOutputs(active, diagnostics);\n return {\n simTime: simTimePs,\n executed: Number(active.circuit.tickCount - before),\n ...(diagnostics.length === 0 ? {} : { diagnostics: Object.freeze(diagnostics) }),\n };\n },\n\n async deliver(target: CanvasBindingTarget, payload: unknown): Promise<void> {\n if (disposed) return;\n const active = runtime;\n if (active === undefined) {\n throw new Error('DeviceSimulationHost has no loaded schematic');\n }\n const binding = active.inputs.get(targetKey(target.symbol, target.port));\n if (binding === undefined) {\n throw new Error(`Unknown device input ${target.symbol}.${target.port}`);\n }\n if (!payloadMatches(binding.topic.type, payload)) {\n throw new TypeError(\n `${target.symbol}.${target.port} expects a ${binding.topic.type} payload`,\n );\n }\n const device = binding.device;\n pending.push({ device, port: target.port, payload });\n },\n\n onDidPublish: publishes.event,\n\n async getTopics(): Promise<readonly DeviceTopic[]> {\n return runtime?.topics ?? [];\n },\n\n async getSimTime(): Promise<number> {\n return simTimePs;\n },\n\n async getSchematic(): Promise<SchematicDocument | undefined> {\n return runtime?.schematic;\n },\n\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n publishes.dispose();\n clearRuntime();\n },\n };\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport { loggerService } from '@mica-js/core/logging';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { DeviceReference, DeviceSymbolProvider } from '@mica-js/core/schematic';\nimport type { CircuitElectricalOptions, SchematicDeviceBinding } from '../unified-ir/runtime';\nimport { deviceSimulationHostFileSystemService, deviceSimulationHostGuestService } from './rpc';\nimport type { DeviceSimulationHostRpc } from './rpc';\nimport { createSchematicDeviceSimulationHost } from './runtime';\n\n/**\n * Device wiring a worker script hands to {@link startDeviceSimulationHostGuest}.\n *\n * The simulator ships no device models, so every option defaults to \"knows no references\": a\n * package that owns devices bundles its own worker script and supplies these.\n */\nexport interface DeviceSimulationHostGuestOptions {\n /** Fixed electrical configuration supplied by the owning worker module. */\n readonly electrical?: CircuitElectricalOptions;\n /** Symbol geometry of the schematics this guest loads, or a factory called per load. */\n readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);\n /** Resolves a schematic device reference; when omitted every reference stays unresolved. */\n readonly resolveDevice?: (reference: DeviceReference) => SchematicDeviceBinding | undefined;\n /**\n * Awaited before the first schematic load, so a device library can be read through the host file\n * system before anything compiles. Runs at most once.\n */\n readonly prepare?: () => Promise<void>;\n /**\n * Extra ports the worker received in the first ordinary message. The RPC port comes first, so these are\n * `event.ports` from index 1 onward, in the order the caller transferred them. The first one is\n * the direct topic channel (RFC 0018): the widget guest holds the other end and talks to this\n * guest without the host relaying.\n */\n readonly ports?: readonly MessagePort[];\n}\n\n/** Running guest: where the typed services live and which ports the worker was handed. */\nexport interface DeviceSimulationHostGuest {\n /**\n * Endpoint the typed device simulation services are registered on. A worker script that owns\n * further capabilities registers them here instead of opening a second sandbox channel.\n */\n readonly rpc: RpcEndpoint;\n /** Extra startup ports, in the order the worker received them. */\n readonly ports: readonly MessagePort[];\n /** Releases the circuit and closes the endpoint. */\n dispose(): Promise<void>;\n}\n\n/**\n * Registers RFC 0018's device simulation services on a sandbox RPC port.\n *\n * A worker script obtains the port from `event.ports[0]` and calls this function; nothing else is\n * needed, because the guest is a plain module the `@mica-js/sandbox/vite` plugin bundles into a\n * self-contained script. The guest registers `deviceSimulationHostGuestService` and reads schematics\n * through `deviceSimulationHostFileSystemService`, so schematic bytes never enter the guest's own\n * message handling and every payload is a typed RPC DTO.\n */\nexport function startDeviceSimulationHostGuest(\n port: MessagePort,\n options: DeviceSimulationHostGuestOptions = {},\n): DeviceSimulationHostGuest {\n const { devices, resolveDevice, prepare, ports = [] } = options;\n const rpc = createRpc(port);\n const logger = rpc.getProxy(loggerService);\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'guest-started',\n data: [{ extraPortCount: ports.length }],\n })\n .catch(() => undefined);\n const files = rpc.getProxy(deviceSimulationHostFileSystemService);\n const host = createSchematicDeviceSimulationHost({\n async read(uri: string): Promise<Uint8Array> {\n const bytes = await files.read(uri);\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError(`DeviceSimulationHost file system returned ${typeof bytes} for ${uri}`);\n }\n return bytes;\n },\n ...(devices === undefined ? {} : { devices }),\n ...(options.electrical === undefined ? {} : { electrical: options.electrical }),\n resolveDevice: resolveDevice ?? (() => undefined),\n });\n\n let prepared: Promise<void> | undefined;\n const ensurePrepared = async (): Promise<void> => {\n if (prepare === undefined) return;\n prepared ??= prepare();\n try {\n await prepared;\n } catch (error) {\n // A failed preparation must not poison later loads: forget it so the next call retries.\n prepared = undefined;\n throw error;\n }\n };\n\n const service: DeviceSimulationHostRpc = {\n async loadSchematic(uri: string | undefined): Promise<void> {\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'load-schematic-start',\n data: [uri],\n })\n .catch(() => undefined);\n try {\n if (uri !== undefined) await ensurePrepared();\n await host.loadSchematic(uri);\n void logger\n .write({\n level: 'debug',\n scope: 'device-simulation',\n message: 'load-schematic-end',\n data: [uri],\n })\n .catch(() => undefined);\n } catch (error) {\n void logger\n .write({\n level: 'error',\n scope: 'device-simulation',\n message: 'load-schematic-failed',\n data: [uri, String(error)],\n })\n .catch(() => undefined);\n throw error;\n }\n },\n async reset(): Promise<void> {\n await ensurePrepared();\n return host.reset();\n },\n tick: (dt: number) => host.tick(dt),\n deliver: (target, payload, simTime) => host.deliver(target, payload, simTime),\n onDidPublish: (listener) => {\n const subscription = host.onDidPublish(listener);\n return () => subscription.dispose();\n },\n getTopics: () => host.getTopics(),\n getSimTime: () => host.getSimTime(),\n getSchematic: () => host.getSchematic(),\n dispose: () => host.dispose(),\n };\n\n const registration = rpc.register(deviceSimulationHostGuestService, service);\n\n // The direct topic channel registers the same contract on the extra port, so the widget guest can\n // deliver and subscribe without the host in between. It only calls `deliver` and `onDidPublish`;\n // schematic, topics and the clock stay the host's business.\n const topicPort = ports[0];\n const topicRpc = topicPort === undefined ? undefined : createRpc(topicPort);\n const topicRegistration = topicRpc?.register(deviceSimulationHostGuestService, service);\n\n let disposed = false;\n return {\n rpc,\n ports,\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n topicRegistration?.dispose();\n topicRpc?.dispose();\n registration.dispose();\n await host.dispose();\n rpc.dispose();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAcA,SAAgB,uBACd,QACA,kBAAuC,CAAC,GACnB;CACrB,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,MAAM,OAAO,WAAW;EACjC,MAAM,OAAO,GAAG;EAChB,IAAI,SAAS,KAAA,GAAW;EAExB,KAAK,MAAM,SAAS,KAAK,QAAQ;GAC/B,KAAK,MAAM,eAAe,MAAM,cAAc,MAAM,IAAI,YAAY,EAAE;GACtE,IAAI,MAAM,eAAe,KAAA,GA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