@mica-js/simulator 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,3 @@
1
1
  # @mica-js/simulator
2
2
 
3
3
  在虚拟时钟上运行电路与原理图器件。`@mica-js/simulator` 提供统一 IR 的 `Circuit`,以及用于原理图集成的 `DeviceSimulationHost`;`@mica-js/simulator/sandbox` 提供沙箱宿主接入。本包不内建任何具体器件模型,器件定义由调用方提供。
4
-
5
- **迁移提示:**新电路代码使用 `Circuit.create()` 的统一 IR 路径;`createDeviceSimExecutor()` + `createCircuitHost()` 调度器路径仅为现有原理图/画布集成维护,不早于 1.0 移除。旧版 API 与迁移步骤见 [迁移指南](./docs/MIGRATION.md)。
package/dist/index.d.ts CHANGED
@@ -129,11 +129,6 @@ export declare interface CircuitCompilationInput {
129
129
  export declare interface CircuitCompilationOptions {
130
130
  /** Named fixed-level rails; merged over `GND`/`VCC`/`VDD`. */
131
131
  readonly rails?: Readonly<Record<string, boolean>>;
132
- /**
133
- * Accept nets with more than one driver pin and solve them as a wired-OR.
134
- * Defaults to `false`, which reports a `driver-conflict` instead.
135
- */
136
- readonly allowMultiDriver?: boolean;
137
132
  /** Runs `validateIR` over the generated module. Defaults to `true`. */
138
133
  readonly validate?: boolean;
139
134
  /** Overrides for the generated entry-point names. */
@@ -161,11 +156,6 @@ export declare interface CircuitDeviceSimulationHostOptions {
161
156
 
162
157
  /** Electrical-solve options forwarded to `compileCircuit`. */
163
158
  export declare interface CircuitElectricalOptions {
164
- /**
165
- * Accept nets with more than one driver and solve them as a wired-OR.
166
- * Defaults to `false`, which reports a `driver-conflict` at compile time.
167
- */
168
- readonly allowMultiDriver?: boolean;
169
159
  /** Named fixed-level rails; merged over `GND`/`VCC`/`VDD`. */
170
160
  readonly rails?: Readonly<Record<string, boolean>>;
171
161
  }
@@ -176,7 +166,7 @@ export declare interface CircuitElectricalOptions {
176
166
  * `Circuit` is the host-facing facade over one compiled unified IR module: it
177
167
  * owns the engine instance, exposes typed per-device accessors and keeps the
178
168
  * tick counter. Everything here is transport-neutral; no type mentions the
179
- * scheduler, the device host or the schematic editor.
169
+ * device host or the schematic editor.
180
170
  */
181
171
  /** Execution engine a `Circuit` runs on. */
182
172
  export declare type CircuitEngine = 'jit' | 'reference';
@@ -238,7 +228,7 @@ export declare interface CompilationDiagnostic {
238
228
  }
239
229
 
240
230
  /** Diagnostic codes produced by the compiler's electrical analysis. */
241
- export declare type CompilationDiagnosticCode = 'driver-conflict' | 'power-short' | 'rail-conflict' | 'floating-net';
231
+ export declare type CompilationDiagnosticCode = 'power-short' | 'rail-conflict' | 'floating-net';
242
232
 
243
233
  declare type CompilationDiagnosticSeverity = 'error' | 'warning';
244
234
 
@@ -429,8 +419,8 @@ export declare function createSchematicDeviceSimulationHost(options: SchematicDe
429
419
  /** Rails every circuit understands without declaring them. */
430
420
  export declare const DEFAULT_RAILS: Readonly<Record<string, boolean>>;
431
421
 
432
- /** Global pin addresses reserved per device (one 32-pin port). */
433
- export declare const DEVICE_PIN_STRIDE = 32;
422
+ /** Global pin addresses one device may own; enough for the largest packages. */
423
+ export declare const DEVICE_PIN_STRIDE = 512;
434
424
 
435
425
  /**
436
426
  * What every device accessor offers, whatever its type.
@@ -963,8 +953,8 @@ export declare interface SimulationPublish {
963
953
  */
964
954
  export declare function startDeviceSimulationHostGuest(port: MessagePort, options?: DeviceSimulationHostGuestOptions): DeviceSimulationHostGuest;
965
955
 
966
- /** Global pin addresses available to one circuit (8 devices x 32 pins). */
967
- export declare const UNIFIED_PIN_CAPACITY = 256;
956
+ /** Global pin addresses available to one circuit (8 devices x 512 pins). */
957
+ export declare const UNIFIED_PIN_CAPACITY = 4096;
968
958
 
969
959
  /** Error raised while compiling a circuit. */
970
960
  export declare class UnifiedIRCompilerError extends Error {
@@ -978,7 +968,7 @@ export declare class UnifiedIRCompilerError extends Error {
978
968
  }
979
969
 
980
970
  /** Error codes raised by {@link UnifiedIRCompilerError}. */
981
- export declare type UnifiedIRCompilerErrorCode = 'invalid-input' | 'duplicate-device' | 'unknown-device' | 'pin-not-found' | 'state-not-found' | 'invalid-connection' | 'capacity-exceeded' | 'unsupported-device' | 'driver-conflict' | 'power-short' | 'rail-conflict' | 'invalid-ir';
971
+ export declare type UnifiedIRCompilerErrorCode = 'invalid-input' | 'duplicate-device' | 'unknown-device' | 'pin-not-found' | 'state-not-found' | 'invalid-connection' | 'capacity-exceeded' | 'unsupported-device' | 'power-short' | 'rail-conflict' | 'invalid-ir';
982
972
 
983
973
  export declare interface UnifiedIRCompilerErrorOptions {
984
974
  readonly deviceId?: string;
package/dist/index.js CHANGED
@@ -53,13 +53,14 @@ function createModuleValidation(module, updateResources = []) {
53
53
  *
54
54
  * Every device of a circuit shares one global pin address space, so the
55
55
  * compiler and every device kernel must agree on the capacity, the per-device
56
- * stride and the meaning of a `pin_mode` slot. The values are part of the
57
- * generated module's memory layout and must stay stable across releases.
56
+ * stride and the meaning of a `pin_mode` slot. Capacity and stride are limits
57
+ * checked at allocation time; the shared pin memories are sized to the pins a
58
+ * circuit actually declares, so a larger ceiling costs no runtime memory.
58
59
  */
59
- /** Global pin addresses available to one circuit (8 devices x 32 pins). */
60
- var UNIFIED_PIN_CAPACITY = 256;
61
- /** Global pin addresses reserved per device (one 32-pin port). */
62
- var DEVICE_PIN_STRIDE = 32;
60
+ /** Global pin addresses available to one circuit (8 devices x 512 pins). */
61
+ var UNIFIED_PIN_CAPACITY = 4096;
62
+ /** Global pin addresses one device may own; enough for the largest packages. */
63
+ var DEVICE_PIN_STRIDE = 512;
63
64
  /** Values stored in the global `pin_mode` array. */
64
65
  var PIN_MODE = Object.freeze({
65
66
  highZ: 0,
@@ -97,7 +98,7 @@ var DEVICE_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
97
98
  * ids: 0 = drive1.PA0 1 = drive1.PA1 2 = sink1.anode 3 = sink1.cathode
98
99
  * |<-- drive1 -->| |<----------- sink1 ----------->|
99
100
  *
100
- * pin_mode[256] u8 pin_output[256] bool pin_input[256] bool
101
+ * pin_mode[n] u8 pin_output[n] bool pin_input[n] bool (n = totalPins)
101
102
  * device_state_bool[n] / device_state_u32[m] / ... (one array per used type)
102
103
  * ```
103
104
  *
@@ -113,10 +114,10 @@ var GlobalResourceAllocator = class {
113
114
  }
114
115
  /** Allocates the shared pin memories, the pin space and the state space. */
115
116
  allocate(devices) {
116
- const memory = createPinMemory(this.module);
117
+ const pins = this.allocatePins(devices);
117
118
  return Object.freeze({
118
- memory,
119
- pins: this.allocatePins(devices),
119
+ memory: createPinMemory(this.module, Math.max(1, pins.totalPins)),
120
+ pins,
120
121
  states: this.allocateStates(devices)
121
122
  });
122
123
  }
@@ -134,8 +135,8 @@ var GlobalResourceAllocator = class {
134
135
  const allocations = /* @__PURE__ */ new Map();
135
136
  for (const device of devices) {
136
137
  const entries = pinEntries(device);
137
- if (entries.length > 32) throw new UnifiedIRCompilerError("capacity-exceeded", `Device "${device.id}" declares ${entries.length} pins; one device may own at most 32`, { deviceId: device.id });
138
- if (totalPins + entries.length > 256) throw new UnifiedIRCompilerError("capacity-exceeded", `Device "${device.id}" does not fit: the circuit already uses ${totalPins} of 256 global pins`, { deviceId: device.id });
138
+ if (entries.length > 512) throw new UnifiedIRCompilerError("capacity-exceeded", `Device "${device.id}" declares ${entries.length} pins; one device may own at most 512`, { deviceId: device.id });
139
+ if (totalPins + entries.length > 4096) throw new UnifiedIRCompilerError("capacity-exceeded", `Device "${device.id}" does not fit: the circuit already uses ${totalPins} of ${UNIFIED_PIN_CAPACITY} global pins`, { deviceId: device.id });
139
140
  const offset = totalPins;
140
141
  const devicePins = /* @__PURE__ */ new Map();
141
142
  const resolved = /* @__PURE__ */ new Map();
@@ -166,7 +167,7 @@ var GlobalResourceAllocator = class {
166
167
  pins,
167
168
  devices: allocations,
168
169
  totalPins,
169
- capacity: 256
170
+ capacity: UNIFIED_PIN_CAPACITY
170
171
  });
171
172
  }
172
173
  /**
@@ -225,12 +226,18 @@ var GlobalResourceAllocator = class {
225
226
  });
226
227
  }
227
228
  };
228
- /** Declares the three pin memories shared by every device and net solver. */
229
- function createPinMemory(module) {
229
+ /**
230
+ * Declares the three pin memories shared by every device and net solver.
231
+ *
232
+ * The memories are sized to the pins the circuit declares, never to
233
+ * {@link UNIFIED_PIN_CAPACITY}: the capacity only bounds how many pins a
234
+ * circuit may have, so a large ceiling costs neither memory nor setup time.
235
+ */
236
+ function createPinMemory(module, capacity = UNIFIED_PIN_CAPACITY) {
230
237
  return Object.freeze({
231
- mode: module.array("pin_mode", "u8", Array.from({ length: 256 }, () => PIN_MODE.highZ)),
232
- output: module.array("pin_output", "bool", Array.from({ length: 256 }, () => false)),
233
- input: module.array("pin_input", "bool", Array.from({ length: 256 }, () => false))
238
+ mode: module.array("pin_mode", "u8", Array.from({ length: capacity }, () => PIN_MODE.highZ)),
239
+ output: module.array("pin_output", "bool", Array.from({ length: capacity }, () => false)),
240
+ input: module.array("pin_input", "bool", Array.from({ length: capacity }, () => false))
234
241
  });
235
242
  }
236
243
  /** First state slot ordinal of every device; used for `DeviceMetadata.stateOffset`. */
@@ -701,8 +708,7 @@ var MainLoopGenerator = class {
701
708
  /**
702
709
  * Generates the electrical solve, one `solve_net_<id>` function per net.
703
710
  *
704
- * Single driver — the only shape v1 compiles without `allowMultiDriver` — is a
705
- * branch-free path:
711
+ * Each net solves as a branch-free function. One driver is the common shape:
706
712
  *
707
713
  * ```text
708
714
  * solve_net_0:
@@ -714,7 +720,7 @@ var MainLoopGenerator = class {
714
720
  *
715
721
  * Only a push-pull driver holds its net; high-z, open-drain and analog modes
716
722
  * leave it floating. A driver-less net loads the constant of its rail, or
717
- * `false` when it is truly floating.
723
+ * `false` when it is truly floating. Several drivers OR into a wired-OR level.
718
724
  */
719
725
  var ElectricalSolverGenerator = class {
720
726
  context;
@@ -747,8 +753,8 @@ var ElectricalSolverGenerator = class {
747
753
  /**
748
754
  * Folds the drivers of one net into the level its sinks observe.
749
755
  *
750
- * A single driver yields `mode == push-pull && output`; several drivers (only
751
- * reachable with `allowMultiDriver`) are OR-ed into a wired-OR level.
756
+ * A single driver yields `mode == push-pull && output`; several drivers are
757
+ * OR-ed into a wired-OR level.
752
758
  */
753
759
  combineDrivers(b, drivers) {
754
760
  let driven;
@@ -778,18 +784,16 @@ var DEFAULT_RAILS = Object.freeze({
778
784
  * 2. a union-find pass collapses them into electrical nets (connected components);
779
785
  * 3. each net gets an id in first-appearance order and is split into drivers,
780
786
  * loads and sinks;
781
- * 4. electrical conflicts (several drivers, a driver against a rail, two rails
782
- * of opposite level) become diagnostics instead of silently wrong IR.
787
+ * 4. electrical conflicts (a driver against a rail, two rails of opposite
788
+ * level) become diagnostics instead of silently wrong IR.
783
789
  *
784
- * The v1 electrical model supports one driver per net. `allowMultiDriver`
785
- * accepts more and the solver then emits a wired-OR instead of failing.
790
+ * Several drivers on one net are legal and solved as a wired-OR, which is what
791
+ * a bidirectional pin fighting a switch looks like on a bench.
786
792
  */
787
793
  var NetworkTopologyAnalyzer = class {
788
794
  rails;
789
- allowMultiDriver;
790
795
  constructor(options = {}) {
791
796
  this.rails = new Map([...Object.entries(DEFAULT_RAILS), ...Object.entries(options.rails ?? {})]);
792
- this.allowMultiDriver = options.allowMultiDriver ?? false;
793
797
  }
794
798
  /**
795
799
  * @throws {UnifiedIRCompilerError} when a connection is malformed, names an
@@ -875,10 +879,6 @@ var NetworkTopologyAnalyzer = class {
875
879
  const endpoints = [...rails.map((rail) => rail.name), ...pins.map((pin) => pin.endpoint)];
876
880
  const levels = new Set(rails.map((rail) => rail.level));
877
881
  if (rails.length > 1 && levels.size > 1) diagnostics.push(diagnostic("rail-conflict", "error", `Net ${netId} ties rails ${rails.map((rail) => rail.name).join(" and ")} with opposite levels`, netId, endpoints));
878
- if (drivers.length > 1) {
879
- const names = drivers.map((driver) => driver.endpoint).join(", ");
880
- diagnostics.push(diagnostic("driver-conflict", this.allowMultiDriver ? "warning" : "error", this.allowMultiDriver ? `Net ${netId} has ${drivers.length} drivers (${names}); solving them as a wired-OR` : `Net ${netId} has ${drivers.length} drivers (${names}); v1 supports one driver per net (set allowMultiDriver to solve them as a wired-OR)`, netId, endpoints));
881
- }
882
882
  if (drivers.length > 0 && rails.length > 0) diagnostics.push(diagnostic("power-short", "error", `Net ${netId} shorts rail ${rails[0]?.name ?? "?"} against driver ${drivers[0]?.endpoint ?? "?"}`, netId, endpoints));
883
883
  if (drivers.length === 0 && rails.length === 0) diagnostics.push(diagnostic("floating-net", "warning", `Net ${netId} has no driver and no rail; its loads read a constant low`, netId, endpoints));
884
884
  const source = drivers.length > 0 ? "driver" : rails.length > 0 ? "rail" : "floating";
@@ -942,9 +942,7 @@ function assertNoElectricalErrors(netlist) {
942
942
  });
943
943
  }
944
944
  function mapErrorCode(code) {
945
- if (code === "driver-conflict") return "driver-conflict";
946
- if (code === "rail-conflict") return "rail-conflict";
947
- return "power-short";
945
+ return code === "rail-conflict" ? "rail-conflict" : "power-short";
948
946
  }
949
947
  function diagnostic(code, severity, message, netId, endpoints) {
950
948
  return Object.freeze({
@@ -1034,10 +1032,7 @@ function compileCircuit(input, options = {}) {
1034
1032
  const names = resolveEntryNames(resolvedOptions);
1035
1033
  const module = createIRModule();
1036
1034
  const allocation = new GlobalResourceAllocator(module).allocate(devices);
1037
- const netlist = new NetworkTopologyAnalyzer({
1038
- ...resolvedOptions.rails === void 0 ? {} : { rails: resolvedOptions.rails },
1039
- ...resolvedOptions.allowMultiDriver === void 0 ? {} : { allowMultiDriver: resolvedOptions.allowMultiDriver }
1040
- }).analyze(connections, allocation.pins);
1035
+ const netlist = new NetworkTopologyAnalyzer({ ...resolvedOptions.rails === void 0 ? {} : { rails: resolvedOptions.rails } }).analyze(connections, allocation.pins);
1041
1036
  assertNoElectricalErrors(netlist);
1042
1037
  const generator = new DeviceIRGenerator({
1043
1038
  module,
@@ -1092,7 +1087,6 @@ function validateOptions(options) {
1092
1087
  if (options === null || typeof options !== "object" || Array.isArray(options)) throw new UnifiedIRCompilerError("invalid-input", "Compile options must be an object");
1093
1088
  const resolved = options;
1094
1089
  if (resolved.validate !== void 0 && typeof resolved.validate !== "boolean") throw new UnifiedIRCompilerError("invalid-input", "options.validate must be a boolean");
1095
- if (resolved.allowMultiDriver !== void 0 && typeof resolved.allowMultiDriver !== "boolean") throw new UnifiedIRCompilerError("invalid-input", "options.allowMultiDriver must be a boolean");
1096
1090
  if (resolved.rails !== void 0) {
1097
1091
  if (resolved.rails === null || typeof resolved.rails !== "object" || Array.isArray(resolved.rails)) throw new UnifiedIRCompilerError("invalid-input", "options.rails must be a plain object");
1098
1092
  for (const [name, level] of Object.entries(resolved.rails)) if (name.length === 0 || typeof level !== "boolean") throw new UnifiedIRCompilerError("invalid-input", `options.rails["${name}"] must be a boolean`);
@@ -1565,7 +1559,6 @@ function createEngine(compiled, options) {
1565
1559
  function compileOptionsOf(options) {
1566
1560
  return {
1567
1561
  validate: options.validateIR,
1568
- allowMultiDriver: options.allowMultiDriver,
1569
1562
  ...options.rails === void 0 ? {} : { rails: options.rails }
1570
1563
  };
1571
1564
  }
@@ -1579,22 +1572,16 @@ function resolveOptions(options) {
1579
1572
  if (candidate.jit !== void 0) {
1580
1573
  if (candidate.jit === null || typeof candidate.jit !== "object" || Array.isArray(candidate.jit)) throw new CircuitError("invalid-options", "jit must be a JIT tuning object");
1581
1574
  }
1582
- let allowMultiDriver = false;
1583
1575
  let rails;
1584
1576
  if (candidate.electrical !== void 0) {
1585
1577
  const electrical = candidate.electrical;
1586
1578
  if (electrical === null || typeof electrical !== "object" || Array.isArray(electrical)) throw new CircuitError("invalid-options", "electrical must be a plain object");
1587
- if (electrical.allowMultiDriver !== void 0) {
1588
- if (typeof electrical.allowMultiDriver !== "boolean") throw new CircuitError("invalid-options", "electrical.allowMultiDriver must be a boolean");
1589
- allowMultiDriver = electrical.allowMultiDriver;
1590
- }
1591
1579
  rails = electrical.rails;
1592
1580
  }
1593
1581
  return Object.freeze({
1594
1582
  engine,
1595
1583
  jit: candidate.jit,
1596
1584
  validateIR: candidate.validateIR ?? true,
1597
- allowMultiDriver,
1598
1585
  rails,
1599
1586
  instanceId: candidate.instanceId ?? DEFAULT_INSTANCE_ID
1600
1587
  });