@mica-js/simulator 2.5.2 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -125,26 +125,13 @@ function prepareTopology(nodes, pinEdges) {
125
125
  let floatingComponents = 0;
126
126
  const blocks = [];
127
127
  const edgeBlocks = [];
128
- const nodeComponents = new Array(nodes.length);
129
- const nodeUniform = new Array(nodes.length);
130
- let componentIndex = 0;
131
128
  for (const component of groups.values()) {
132
- let reference;
133
129
  let floating = true;
134
- let uniform = 1;
135
- for (const node of component.nodes) {
136
- const potential = nodes[node].reference;
137
- if (potential === void 0) continue;
130
+ for (const node of component.nodes) if (nodes[node].reference !== void 0) {
138
131
  floating = false;
139
- if (reference === void 0) reference = potential;
140
- else if (potential !== reference) uniform = 0;
132
+ break;
141
133
  }
142
134
  if (floating) floatingComponents++;
143
- for (const node of component.nodes) {
144
- nodeComponents[node] = componentIndex;
145
- nodeUniform[node] = uniform;
146
- }
147
- componentIndex++;
148
135
  for (const block of solveBlocks(component, nodes)) {
149
136
  const index = blocks.length;
150
137
  blocks.push(prepareBlock(block));
@@ -155,9 +142,7 @@ function prepareTopology(nodes, pinEdges) {
155
142
  blocks,
156
143
  edgeBlocks,
157
144
  components: groups.size,
158
- floatingComponents,
159
- nodeComponents,
160
- nodeUniform
145
+ floatingComponents
161
146
  };
162
147
  }
163
148
  var cleanZero = (value) => value === 0 ? 0 : value;
@@ -545,9 +530,6 @@ function createElectricalNetwork(inputPins, inputNets) {
545
530
  let seenStamp = 0;
546
531
  /** Only the matrix partition is out of date; component arrays and buckets stay valid. */
547
532
  let blocksStale = false;
548
- /** Component arrays are copied before a local update mutates them, because admitted
549
- * topology snapshots keep referencing the arrays they were created with. */
550
- let componentArraysOwned = false;
551
533
  const syncDegrees = (previous, next) => {
552
534
  for (const edge of previous) if (next.indexOf(edge) === -1) {
553
535
  nodeDegree[edge.from] = nodeDegree[edge.from] - 1;
@@ -576,6 +558,9 @@ function createElectricalNetwork(inputPins, inputNets) {
576
558
  const changedSlots = [];
577
559
  /** Admitted leaf shapes per pin slot; a pin normally alternates between two references. */
578
560
  const leafPlans = new Array(pins.length);
561
+ /** Last topology check for the single-slot entry, independent of intent identity. */
562
+ const leafEpochs = new Int32Array(pins.length);
563
+ let leafEpoch = 1;
579
564
  const leafSlots = [];
580
565
  const leafIntents = [];
581
566
  const leafEdges = [];
@@ -624,7 +609,7 @@ function createElectricalNetwork(inputPins, inputNets) {
624
609
  * A replay therefore commits precomputed samples instead of re-deriving voltages, levels
625
610
  * and canonical samples on every publication.
626
611
  */
627
- const leafPlan = (slot, branch, target, edges) => {
612
+ const leafPlan = (slot, intent, branch, target, edges) => {
628
613
  const node = pinNodes[slot];
629
614
  const nodePins = nodeSlots[node];
630
615
  const voltage = nodes[target].reference;
@@ -638,27 +623,32 @@ function createElectricalNetwork(inputPins, inputNets) {
638
623
  planPins.push(pinned);
639
624
  samples.push(sampleFor(voltage, pinLevel(pinned, voltage)));
640
625
  }
641
- return Object.freeze({
626
+ return {
627
+ intent,
642
628
  targetPin: branch.to,
643
629
  resistance: branch.resistance,
644
630
  target,
645
631
  edges,
632
+ edgeHash: hashEdges(slot, edges),
646
633
  node,
647
634
  voltage,
648
635
  slots: Object.freeze(slots),
649
636
  pins: Object.freeze(planPins),
650
637
  samples: Object.freeze(samples)
651
- });
638
+ };
652
639
  };
653
- const admitLeaf = (slot, branch, target, edges) => {
654
- const plan = leafPlan(slot, branch, target, edges);
640
+ const admitLeaf = (slot, intent, branch, target, edges) => {
641
+ const plan = leafPlan(slot, intent, branch, target, edges);
655
642
  const plans = leafPlans[slot];
656
643
  if (plans === void 0) {
657
644
  leafPlans[slot] = [plan];
658
645
  statistics.leafPlans++;
659
646
  return;
660
647
  }
661
- for (const existing of plans) if (existing.targetPin === branch.to && existing.resistance === branch.resistance) return;
648
+ for (const existing of plans) if (existing.targetPin === branch.to && existing.resistance === branch.resistance) {
649
+ existing.intent = intent;
650
+ return;
651
+ }
662
652
  if (plans.length < 2) plans.push(plan);
663
653
  else plans[plans.length - 1] = plan;
664
654
  statistics.leafPlans++;
@@ -666,23 +656,32 @@ function createElectricalNetwork(inputPins, inputNets) {
666
656
  const flushAdmissions = () => {
667
657
  for (let index = 0; index < pendingAdmissions.length; index++) {
668
658
  const admission = pendingAdmissions[index];
669
- admitLeaf(admission.slot, admission.branch, admission.target, admission.edges);
659
+ admitLeaf(admission.slot, admission.intent, admission.branch, admission.target, admission.edges);
670
660
  }
671
661
  pendingAdmissions.length = 0;
672
662
  };
673
663
  const matchLeaf = (slot, intent) => {
674
- if (prepared === void 0 || intent.length !== 1) return void 0;
664
+ if (prepared === void 0) return void 0;
675
665
  const plans = leafPlans[slot];
676
666
  if (plans === void 0) return void 0;
677
667
  const previous = pinEdges[slot];
678
668
  if (previous.length !== 1 || nodes[previous[0].to].reference === void 0) return void 0;
679
669
  const from = pinNodes[slot];
680
670
  if (nodeDegree[from] !== 1 || nodes[from].reference !== void 0) return void 0;
671
+ const p0 = plans[0];
672
+ if (p0.intent === intent) return nodes[p0.target].reference === void 0 ? void 0 : p0;
673
+ if (plans.length > 1) {
674
+ const p1 = plans[1];
675
+ if (p1.intent === intent) return nodes[p1.target].reference === void 0 ? void 0 : p1;
676
+ }
677
+ if (intent.length !== 1) return void 0;
681
678
  const branch = intent[0];
682
679
  for (let index = 0; index < plans.length; index++) {
683
680
  const plan = plans[index];
684
681
  if (plan.targetPin !== branch.to || plan.resistance !== branch.resistance) continue;
685
- return nodes[plan.target].reference === void 0 ? void 0 : plan;
682
+ if (nodes[plan.target].reference === void 0) return void 0;
683
+ plan.intent = intent;
684
+ return plan;
686
685
  }
687
686
  };
688
687
  /**
@@ -697,30 +696,82 @@ function createElectricalNetwork(inputPins, inputNets) {
697
696
  }
698
697
  list[position] = slot;
699
698
  };
699
+ const commitLeafEdges = (slot, target, voltage, intent, edges, precomputedHash) => {
700
+ const previousTarget = pinEdges[slot][0].to;
701
+ if (previousTarget !== target) {
702
+ nodeDegree[previousTarget] = nodeDegree[previousTarget] - 1;
703
+ nodeDegree[target] = nodeDegree[target] + 1;
704
+ }
705
+ publishedVoltages[pinNodes[slot]] = voltage;
706
+ intents[slot] = intent;
707
+ pinEdges[slot] = edges;
708
+ if (precomputedHash !== void 0) {
709
+ const previous = pinHashes[slot];
710
+ if (precomputedHash !== previous) {
711
+ pinHashes[slot] = precomputedHash;
712
+ topologyHash += precomputedHash - previous;
713
+ topologySpread ^= previous ^ precomputedHash;
714
+ }
715
+ } else setPinHash(slot, edges);
716
+ };
717
+ const finishLeaf = () => {
718
+ blocksStale = true;
719
+ statistics.solves++;
720
+ statistics.leafPropagations++;
721
+ };
722
+ /**
723
+ * Once the single dirty slot is admitted, the whole batch is known to be valid.
724
+ * The plan visits one node's pins in board order, so no staging or merging is needed.
725
+ */
726
+ const applySingleLeaf = (slot, intent, plan) => {
727
+ const { node, target, voltage } = plan;
728
+ let result = emptySlots;
729
+ if (publishedVoltages[node] !== voltage) {
730
+ const planPins = plan.pins;
731
+ const planSamples = plan.samples;
732
+ if (planPins.length === 1) {
733
+ const pin = planPins[0];
734
+ const sample = planSamples[0];
735
+ if (pin.sample !== sample) {
736
+ pin.sample = sample;
737
+ result = plan.slots;
738
+ }
739
+ } else {
740
+ let all = true;
741
+ let changed = 0;
742
+ for (let index = 0; index < planPins.length; index++) {
743
+ const pin = planPins[index];
744
+ const sample = planSamples[index];
745
+ if (pin.sample === sample) {
746
+ all = false;
747
+ continue;
748
+ }
749
+ pin.sample = sample;
750
+ changedSlots[changed++] = plan.slots[index];
751
+ }
752
+ if (all) result = plan.slots;
753
+ else if (changed !== 0) {
754
+ changedSlots.length = changed;
755
+ result = changedSlots;
756
+ }
757
+ }
758
+ }
759
+ commitLeafEdges(slot, target, voltage, intent, plan.edges, plan.edgeHash);
760
+ finishLeaf();
761
+ return result;
762
+ };
700
763
  /**
701
764
  * Publishes the accepted leaf batch: every pin on a touched node gets the reference
702
765
  * voltage, samples are committed as one batch, then intents, edges and degrees follow.
703
766
  * No pin, sample, intent or degree changes before the whole batch is accepted.
704
767
  */
705
768
  const applyLeaf = (count) => {
706
- if (!componentArraysOwned) {
707
- prepared = {
708
- ...prepared,
709
- nodeComponents: prepared.nodeComponents.slice(),
710
- nodeUniform: prepared.nodeUniform.slice()
711
- };
712
- componentArraysOwned = true;
713
- }
714
- const nodeComponents = prepared.nodeComponents;
715
- const nodeUniform = prepared.nodeUniform;
716
769
  changedSlots.length = 0;
717
770
  pendingPins.length = 0;
718
771
  pendingSamples.length = 0;
719
772
  for (let position = 0; position < count; position++) {
720
773
  const node = pinNodes[leafSlots[position]];
721
774
  const target = leafTargets[position];
722
- nodeComponents[node] = nodeComponents[target];
723
- nodeUniform[node] = nodeUniform[target];
724
775
  const plan = leafPayloads[position];
725
776
  if (plan !== void 0) {
726
777
  if (publishedVoltages[node] === plan.voltage) continue;
@@ -754,21 +805,31 @@ function createElectricalNetwork(inputPins, inputNets) {
754
805
  for (let position = 0; position < count; position++) {
755
806
  const slot = leafSlots[position];
756
807
  const target = leafTargets[position];
757
- const previousTarget = pinEdges[slot][0].to;
758
- publishedVoltages[pinNodes[slot]] = nodes[target].reference;
759
- if (previousTarget !== target) {
760
- nodeDegree[previousTarget] = nodeDegree[previousTarget] - 1;
761
- nodeDegree[target] = nodeDegree[target] + 1;
762
- }
763
- intents[slot] = leafIntents[position];
764
- const edges = leafEdges[position];
765
- pinEdges[slot] = edges;
766
- setPinHash(slot, edges);
808
+ commitLeafEdges(slot, target, nodes[target].reference, leafIntents[position], leafEdges[position], leafPayloads[position]?.edgeHash);
767
809
  }
768
- blocksStale = true;
769
- statistics.solves++;
770
- statistics.leafPropagations++;
810
+ finishLeaf();
771
811
  };
812
+ function solveSlot(slot) {
813
+ const plans = leafPlans[slot];
814
+ if (plans !== void 0) {
815
+ const intent = pins[slot].intent;
816
+ if (intent !== intents[slot]) {
817
+ if (leafEpochs[slot] === leafEpoch) {
818
+ const first = plans[0];
819
+ const plan = first.intent === intent ? first : plans[1];
820
+ if (plan?.intent === intent) return applySingleLeaf(slot, intent, plan);
821
+ }
822
+ const plan = matchLeaf(slot, intent);
823
+ if (plan !== void 0) {
824
+ leafEpochs[slot] = leafEpoch;
825
+ return applySingleLeaf(slot, intent, plan);
826
+ }
827
+ }
828
+ }
829
+ inputSlots[0] = slot;
830
+ inputSlots.length = 1;
831
+ return runSolve(inputSlots);
832
+ }
772
833
  return {
773
834
  get stats() {
774
835
  return Object.freeze({ ...statistics });
@@ -780,7 +841,9 @@ function createElectricalNetwork(inputPins, inputNets) {
780
841
  for (let position = 0; position < changed.length; position++) published.push(pins[changed[position]]);
781
842
  return Object.freeze(published);
782
843
  },
844
+ solveSlot,
783
845
  solveSlots(changedSlotNumbers) {
846
+ if (typeof changedSlotNumbers === "number") return solveSlot(changedSlotNumbers);
784
847
  if (changedSlotNumbers === void 0) return runSolve(void 0);
785
848
  const reusable = changedSlotNumbers instanceof Set || Array.isArray(changedSlotNumbers) || ArrayBuffer.isView(changedSlotNumbers) && Symbol.iterator in changedSlotNumbers;
786
849
  if (!reusable) {
@@ -836,6 +899,10 @@ function createElectricalNetwork(inputPins, inputNets) {
836
899
  * every pin. Returns the changed slots in ascending board order.
837
900
  */
838
901
  function runSolve(input) {
902
+ if (++leafEpoch === 2147483647) {
903
+ leafEpochs.fill(0);
904
+ leafEpoch = 1;
905
+ }
839
906
  const initial = prepared === void 0;
840
907
  pendingAdmissions.length = 0;
841
908
  if (prepared !== void 0 && !blocksStale && input !== void 0 && input.length === 0) {
@@ -914,6 +981,7 @@ function createElectricalNetwork(inputPins, inputNets) {
914
981
  if (leafSwitch && !leafShape) leafSwitch = false;
915
982
  if (leafShape && intent.length === 1 && edges[0] !== previous[0]) pendingAdmissions.push({
916
983
  slot: index,
984
+ intent,
917
985
  branch: intent[0],
918
986
  target: edges[0].to,
919
987
  edges
@@ -1131,7 +1199,6 @@ function createElectricalNetwork(inputPins, inputNets) {
1131
1199
  for (const [index, block] of dirtyBlocks) topology.blocks[index] = block;
1132
1200
  }
1133
1201
  prepared = topology;
1134
- componentArraysOwned = false;
1135
1202
  blocksStale = false;
1136
1203
  if (topologyChanged) {
1137
1204
  const admitted = restored !== void 0 && topology === restored.topology ? restored : {
@@ -1951,6 +2018,25 @@ function standalone(code, cause, phase) {
1951
2018
  //#endregion
1952
2019
  //#region src/runtime/instance.ts
1953
2020
  var EMPTY_MESSAGES = Object.freeze([]);
2021
+ var jitModels = /* @__PURE__ */ new WeakMap();
2022
+ /** Retain the binding identity when adapters reuse the same immutable function table. */
2023
+ function bindJitFunctions(base, functions) {
2024
+ if (functions.length === 0) return base;
2025
+ let models = jitModels.get(base);
2026
+ const cached = models?.get(functions);
2027
+ if (cached !== void 0) return cached;
2028
+ const model = validateDeviceIR({
2029
+ ...base,
2030
+ declarations: base.declarations.concat(functions)
2031
+ });
2032
+ for (const declaration of model.declarations.slice(base.declarations.length)) if (declaration.kind !== "function") throw new TypeError("Expected JIT function declaration");
2033
+ if (models === void 0) {
2034
+ models = /* @__PURE__ */ new WeakMap();
2035
+ jitModels.set(base, models);
2036
+ }
2037
+ models.set(functions, model);
2038
+ return model;
2039
+ }
1954
2040
  /** Membership test without allocating: every key of `next` is already in `previous`. */
1955
2041
  function hasEvery(previous, next) {
1956
2042
  for (const slot of next.keys()) if (!previous.has(slot)) return false;
@@ -1976,6 +2062,70 @@ function createContext(owner, board) {
1976
2062
  loadBytes: (name, bytes, ...offset) => owner.loadBytes(name, bytes, offset.length ? offset[0] : 0)
1977
2063
  });
1978
2064
  }
2065
+ /**
2066
+ * State map whose scalar direct-bank writes are synced lazily on read.
2067
+ *
2068
+ * Direct JIT writes update `stateValues` and invalidate `stateSlots` at every boundary,
2069
+ * while no observer or host reads `instance.states` until a reaction, observation,
2070
+ * fallback or external query accesses it. Deferring the string-keyed `Map.set` calls
2071
+ * until an actual read removes redundant map updates across resident GPIO edges while
2072
+ * keeping `instance.states` an exact `Map<string, unknown>` at every read site.
2073
+ */
2074
+ var StateMirrorMap = class extends Map {
2075
+ names = [];
2076
+ bankValues = [];
2077
+ dirty = /* @__PURE__ */ new Int32Array(0);
2078
+ pending = false;
2079
+ bindDirectBank(names, values) {
2080
+ this.names = names;
2081
+ this.bankValues = values;
2082
+ this.dirty = new Int32Array(Math.ceil(names.length / 32));
2083
+ }
2084
+ markDirectDirty(word, bits) {
2085
+ this.dirty[word] |= bits;
2086
+ this.pending = true;
2087
+ }
2088
+ flush() {
2089
+ if (!this.pending) return;
2090
+ this.pending = false;
2091
+ const { names, bankValues, dirty } = this;
2092
+ for (let word = 0; word < dirty.length; word++) {
2093
+ let bits = dirty[word];
2094
+ if (bits === 0) continue;
2095
+ dirty[word] = 0;
2096
+ const base = word << 5;
2097
+ while (bits !== 0) {
2098
+ const index = base + 31 - Math.clz32(bits & -bits);
2099
+ super.set(names[index], bankValues[index]);
2100
+ bits &= bits - 1;
2101
+ }
2102
+ }
2103
+ }
2104
+ get(key) {
2105
+ if (this.pending) this.flush();
2106
+ return super.get(key);
2107
+ }
2108
+ set(key, value) {
2109
+ if (this.pending) this.flush();
2110
+ return super.set(key, value);
2111
+ }
2112
+ entries() {
2113
+ if (this.pending) this.flush();
2114
+ return super.entries();
2115
+ }
2116
+ values() {
2117
+ if (this.pending) this.flush();
2118
+ return super.values();
2119
+ }
2120
+ forEach(callbackfn, thisArg) {
2121
+ if (this.pending) this.flush();
2122
+ super.forEach(callbackfn, thisArg);
2123
+ }
2124
+ [Symbol.iterator]() {
2125
+ if (this.pending) this.flush();
2126
+ return super[Symbol.iterator]();
2127
+ }
2128
+ };
1979
2129
  var Instance = class {
1980
2130
  board;
1981
2131
  entry;
@@ -1983,7 +2133,7 @@ var Instance = class {
1983
2133
  declarations = /* @__PURE__ */ new Map();
1984
2134
  props = /* @__PURE__ */ new Map();
1985
2135
  constants = /* @__PURE__ */ new Map();
1986
- states = /* @__PURE__ */ new Map();
2136
+ states = new StateMirrorMap();
1987
2137
  directBank;
1988
2138
  memories = /* @__PURE__ */ new Map();
1989
2139
  memoryViews = /* @__PURE__ */ new Map();
@@ -2011,10 +2161,13 @@ var Instance = class {
2011
2161
  staticObservations = /* @__PURE__ */ new WeakMap();
2012
2162
  resistorIntents = /* @__PURE__ */ new Map();
2013
2163
  sampleEntries = /* @__PURE__ */ new Map();
2164
+ intentEntries = /* @__PURE__ */ new Map();
2014
2165
  stateSlots = /* @__PURE__ */ new Map();
2015
2166
  /** Per-instance handles for the fixed resources a resumable process body binds. */
2016
2167
  resourceHandles = /* @__PURE__ */ new Map();
2017
2168
  memoryPlans = /* @__PURE__ */ new Map();
2169
+ /** 按 memory 维护的代码代际;只有 code region 内写入才递增。 */
2170
+ codeVersions = /* @__PURE__ */ new Map();
2018
2171
  observationFrames = /* @__PURE__ */ new WeakMap();
2019
2172
  evaluating = /* @__PURE__ */ new Set();
2020
2173
  random;
@@ -2045,11 +2198,7 @@ var Instance = class {
2045
2198
  return this.readSample(ref);
2046
2199
  },
2047
2200
  intent: (pin, value) => {
2048
- const target = this.pin(pin);
2049
- if (target.intent === value) return;
2050
- target.intent = value;
2051
- board.dirtyElectricalSlots.add(board.electricalSlot(target));
2052
- board.electricalDirty = true;
2201
+ this.writeIntent(pin, value);
2053
2202
  },
2054
2203
  resistor: (pin, resistance) => {
2055
2204
  const r = electricalNumber(resistance);
@@ -2074,7 +2223,7 @@ var Instance = class {
2074
2223
  if (size === 1) plan.bytes[at] = n;
2075
2224
  else if (size === 2) plan.view.setUint16(at, n, kind.endsWith("le"));
2076
2225
  else plan.view.setUint32(at, n, kind.endsWith("le"));
2077
- this.memoryChangedPlan(plan);
2226
+ this.memoryChangedPlan(plan, at, size);
2078
2227
  },
2079
2228
  copyBytes: (memory, offset, length) => {
2080
2229
  this.track(this.memoryResources, String(memory));
@@ -2252,6 +2401,24 @@ var Instance = class {
2252
2401
  if (!pin) throw new TypeError(`Unknown pin ${String(ref)}`);
2253
2402
  return pin;
2254
2403
  }
2404
+ /** Shared by the generic host and direct JIT, which needs to know whether to publish. */
2405
+ writeIntent(ref, value) {
2406
+ const name = typeof ref === "string" ? ref : String(ref);
2407
+ const board = this.board;
2408
+ let entry = this.intentEntries.get(name);
2409
+ if (entry === void 0) {
2410
+ const pin = this.pin(name);
2411
+ entry = {
2412
+ pin,
2413
+ slot: board.electricalSlot(pin)
2414
+ };
2415
+ this.intentEntries.set(name, entry);
2416
+ }
2417
+ if (entry.pin.intent === value) return false;
2418
+ entry.pin.intent = value;
2419
+ board.markElectricalDirty(entry.slot);
2420
+ return true;
2421
+ }
2255
2422
  /**
2256
2423
  * One frozen, reusable intent value per (pin, resistance); intents are immutable. The
2257
2424
  * outer map is keyed by pin name and the inner one by resistance, so the hot path builds
@@ -2306,14 +2473,40 @@ var Instance = class {
2306
2473
  const declaration = this.declarations.get(name);
2307
2474
  return declaration.type.kind === "number" || declaration.type.kind === "bool";
2308
2475
  });
2476
+ const frozenNames = Object.freeze(stateNames);
2477
+ const stateValues = stateNames.map((name) => this.states.get(name));
2478
+ this.states.bindDirectBank(frozenNames, stateValues);
2309
2479
  this.directBank = {
2310
- stateNames: Object.freeze(stateNames),
2480
+ stateNames: frozenNames,
2481
+ stateSlots: Object.freeze(stateNames.map((name) => this.stateResources.get(name))),
2311
2482
  states: new Map(stateNames.map((name, index) => [name, index])),
2312
- stateValues: stateNames.map((name) => this.states.get(name))
2483
+ stateValues
2313
2484
  };
2314
2485
  }
2315
2486
  return this.directBank;
2316
2487
  }
2488
+ /** Direct scalar writes are already in the numeric bank. Commit the mirror and version. */
2489
+ commitDirectStates(dirty) {
2490
+ const { stateSlots } = this.directBank;
2491
+ const states = this.states;
2492
+ const board = this.board;
2493
+ let wrote = false;
2494
+ for (let word = 0; word < dirty.length; word++) {
2495
+ let bits = dirty[word];
2496
+ if (bits === 0) continue;
2497
+ dirty[word] = 0;
2498
+ wrote = true;
2499
+ states.markDirectDirty(word, bits);
2500
+ const base = word << 5;
2501
+ while (bits !== 0) {
2502
+ const slot = stateSlots[base + 31 - Math.clz32(bits & -bits)];
2503
+ if (slot.subscribers.size === 0) slot.version++;
2504
+ else board.invalidate(slot);
2505
+ bits &= bits - 1;
2506
+ }
2507
+ }
2508
+ return wrote;
2509
+ }
2317
2510
  writeState(name, value, slot) {
2318
2511
  const captured = snapshot(value);
2319
2512
  this.states.set(name, captured);
@@ -2346,23 +2539,88 @@ var Instance = class {
2346
2539
  }
2347
2540
  return plan;
2348
2541
  }
2349
- memoryChanged(name) {
2350
- this.memoryChangedSlot(name, this.memoryPlan(name).slot);
2542
+ codeVersion(name) {
2543
+ return this.codeVersions.get(name) ?? 0;
2544
+ }
2545
+ intersectsCodeRegion(region, offset, size) {
2546
+ if (offset === void 0 || size === void 0) return true;
2547
+ return offset < region.size && offset + size > 0;
2548
+ }
2549
+ hasCodeRegion(name, offset, size) {
2550
+ for (const jit of this.jits) {
2551
+ if (!jit.active) continue;
2552
+ for (const region of jit.codeRegions) if (region.memory === name && this.intersectsCodeRegion(region, offset, size)) return true;
2553
+ }
2554
+ return false;
2555
+ }
2556
+ addMetadataChange(state, change) {
2557
+ const pending = state.pending;
2558
+ let end = change.offset + change.length;
2559
+ let start = change.offset;
2560
+ for (let index = 0; index < pending.length;) {
2561
+ const current = pending[index];
2562
+ const currentEnd = current.offset + current.length;
2563
+ if (change.offset <= currentEnd && current.offset <= end) {
2564
+ start = Math.min(start, current.offset);
2565
+ end = Math.max(end, currentEnd);
2566
+ pending.splice(index, 1);
2567
+ } else index++;
2568
+ }
2569
+ pending.push({
2570
+ memory: change.memory,
2571
+ offset: start,
2572
+ length: end - start
2573
+ });
2574
+ }
2575
+ markMetadataChanged(jit, name, offset, size) {
2576
+ if (!jit.metadata) return;
2577
+ for (const state of jit.metadata.regions.values()) {
2578
+ const region = state.region;
2579
+ if (region.memory !== name) continue;
2580
+ if (state.appliedVersion === -1) continue;
2581
+ if (name === jit.options.code) state.dirty = true;
2582
+ if (!this.intersectsCodeRegion(region, offset, size)) continue;
2583
+ state.dirty = true;
2584
+ const start = offset === void 0 ? 0 : Math.max(0, offset);
2585
+ const end = offset === void 0 ? region.size : Math.min(region.size, offset + (size ?? 0));
2586
+ if (end > start) this.addMetadataChange(state, {
2587
+ memory: name,
2588
+ offset: start,
2589
+ length: end - start
2590
+ });
2591
+ }
2592
+ }
2593
+ memoryChanged(name, offset, size) {
2594
+ this.memoryChangedSlot(name, this.memoryPlan(name).slot, offset, size);
2351
2595
  }
2352
- memoryChangedPlan(plan) {
2353
- this.memoryChangedSlot(plan.name, plan.slot);
2596
+ memoryChangedPlan(plan, offset, size) {
2597
+ this.memoryChangedSlot(plan.name, plan.slot, offset, size);
2354
2598
  }
2355
- memoryChangedSlot(name, slot) {
2599
+ memoryChangedSlot(name, slot, offset, size) {
2356
2600
  this.board.invalidate(slot);
2357
- for (const jit of this.jits) if (jit.options.code === name) {
2358
- jit.cache.clear();
2359
- jit.revision++;
2360
- jit.directPrograms.clear();
2361
- jit.directProgramRevision = -1;
2362
- jit.directSkip = void 0;
2363
- jit.directMisses = 0;
2364
- if (jit.direct?.frame.resume) jit.direct.frame.stopAfterInstruction = true;
2365
- else jit.direct = void 0;
2601
+ if (this.hasCodeRegion(name, offset, size)) this.codeVersions.set(name, this.codeVersion(name) + 1);
2602
+ for (const jit of this.jits) {
2603
+ let affected = false;
2604
+ for (const region of jit.codeRegions) if (region.memory === name && this.intersectsCodeRegion(region, offset, size)) {
2605
+ affected = true;
2606
+ break;
2607
+ }
2608
+ if (!affected) continue;
2609
+ this.markMetadataChanged(jit, name, offset, size);
2610
+ if (jit.options.code === name) {
2611
+ jit.cache.clear();
2612
+ jit.cacheMemories.clear();
2613
+ jit.revision++;
2614
+ jit.directPrograms.clear();
2615
+ jit.directProgramRevision = -1;
2616
+ jit.directSkip = void 0;
2617
+ jit.directMisses.clear();
2618
+ if (jit.direct?.frame.resume) jit.direct.frame.stopAfterInstruction = true;
2619
+ else jit.direct = void 0;
2620
+ } else if (jit.cacheMemories.has(name)) {
2621
+ for (const [pc, instruction] of jit.cache) if (instruction.codeRegion?.memory === name) jit.cache.delete(pc);
2622
+ jit.cacheMemories.delete(name);
2623
+ }
2366
2624
  }
2367
2625
  }
2368
2626
  /**
@@ -2414,8 +2672,7 @@ var Instance = class {
2414
2672
  const current = resolve();
2415
2673
  if (current.intent === value) return;
2416
2674
  current.intent = value;
2417
- this.board.dirtyElectricalSlots.add(slot);
2418
- this.board.electricalDirty = true;
2675
+ this.board.markElectricalDirty(slot);
2419
2676
  },
2420
2677
  resistor: (resistance) => {
2421
2678
  const r = electricalNumber(resistance);
@@ -2457,7 +2714,7 @@ var Instance = class {
2457
2714
  if (size === 1) current.bytes[at] = n;
2458
2715
  else if (size === 2) current.view.setUint16(at, n, little);
2459
2716
  else current.view.setUint32(at, n, little);
2460
- this.memoryChangedSlot(name, current.slot);
2717
+ this.memoryChangedSlot(name, current.slot, at, size);
2461
2718
  };
2462
2719
  return Object.freeze({
2463
2720
  load8: (offset) => read(1, false, offset),
@@ -2656,13 +2913,140 @@ var Instance = class {
2656
2913
  value: captured
2657
2914
  });
2658
2915
  }
2916
+ captureCodeRegions(options) {
2917
+ const primaryMemory = this.memories.get(options.code);
2918
+ const primary = Object.freeze({
2919
+ memory: options.code,
2920
+ base: 0,
2921
+ size: primaryMemory.length
2922
+ });
2923
+ const additional = [];
2924
+ if (Object.hasOwn(options, "codeRegions")) {
2925
+ if (!Array.isArray(options.codeRegions)) throw new TypeError("codeRegions must be an array");
2926
+ for (const item of options.codeRegions) {
2927
+ dataObject(item, [
2928
+ "memory",
2929
+ "base",
2930
+ "size"
2931
+ ]);
2932
+ const memory = identity(item.memory);
2933
+ const base = nonnegative(item.base, "code region base");
2934
+ const size = nonnegative(item.size, "code region size");
2935
+ if (size === 0) throw new RangeError("Code region size must be positive");
2936
+ const length = this.memories.get(memory)?.length;
2937
+ if (length === void 0) throw this.board.error("INVALID_BINDING", "Unknown code region memory", this);
2938
+ if (size > length) throw this.board.error("INVALID_BINDING", "Code region exceeds memory", this);
2939
+ if (base > Number.MAX_SAFE_INTEGER - size) throw this.board.error("INVALID_BINDING", "Code region range is not a safe integer", this);
2940
+ const region = Object.freeze({
2941
+ memory,
2942
+ base,
2943
+ size
2944
+ });
2945
+ for (const existing of [primary, ...additional]) if (region.base < existing.base + existing.size && existing.base < region.base + region.size) throw this.board.error("INVALID_BINDING", "Code regions overlap", this);
2946
+ additional.push(region);
2947
+ }
2948
+ }
2949
+ return {
2950
+ all: Object.freeze([primary, ...additional]),
2951
+ additional: Object.freeze(additional)
2952
+ };
2953
+ }
2954
+ capturePolling(items, region) {
2955
+ const polling = /* @__PURE__ */ new Map();
2956
+ if (!Array.isArray(items)) throw new TypeError("polling must be an array");
2957
+ for (const item of items) {
2958
+ dataObject(item, [
2959
+ "pc",
2960
+ "predicate",
2961
+ "consume",
2962
+ "wait"
2963
+ ]);
2964
+ const pc = finite(item.pc, "polling pc");
2965
+ if (region !== void 0 && (pc < region.base || pc >= region.base + region.size)) throw this.board.error("INVALID_BINDING", "Polling pc is outside its code region", this);
2966
+ const predicate = identity(item.predicate);
2967
+ const declaration = this.declarations.get(predicate);
2968
+ if (polling.has(pc) || declaration?.kind !== "function" || !declaration.pure || declaration.params.length || declaration.returns?.kind !== "bool") throw this.board.error("INVALID_BINDING", "Invalid polling declaration", this);
2969
+ let consume;
2970
+ if (Object.hasOwn(item, "consume")) {
2971
+ consume = identity(item.consume);
2972
+ const fn = this.declarations.get(consume);
2973
+ if (fn?.kind !== "function" || fn.params.length !== 0 || fn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling consume function", this);
2974
+ }
2975
+ let wait;
2976
+ if (Object.hasOwn(item, "wait")) {
2977
+ dataObject(item.wait, ["delay", "advance"]);
2978
+ const delay = identity(item.wait.delay);
2979
+ const advance = identity(item.wait.advance);
2980
+ const delayFn = this.declarations.get(delay);
2981
+ const advanceFn = this.declarations.get(advance);
2982
+ if (delayFn?.kind !== "function" || !delayFn.pure || delayFn.params.length !== 0 || delayFn.returns?.kind !== "number" || advanceFn?.kind !== "function" || advanceFn.params.length !== 1 || advanceFn.params[0].type.kind !== "number" || advanceFn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling wait functions", this);
2983
+ wait = Object.freeze({
2984
+ delay,
2985
+ advance
2986
+ });
2987
+ }
2988
+ polling.set(pc, Object.freeze({
2989
+ predicate,
2990
+ ...consume === void 0 ? {} : { consume },
2991
+ ...wait === void 0 ? {} : { wait }
2992
+ }));
2993
+ }
2994
+ return polling;
2995
+ }
2996
+ captureMetadataDelays(value, region) {
2997
+ if (!(value instanceof Map)) throw new TypeError("codeMetadata delays must be a Map");
2998
+ const delays = /* @__PURE__ */ new Map();
2999
+ for (const [key, item] of value) {
3000
+ const pc = finite(key, "delay pc");
3001
+ if (pc < region.base || pc >= region.base + region.size) throw this.board.error("INVALID_BINDING", "Delay pc is outside its code region", this);
3002
+ dataObject(item, [
3003
+ "counter",
3004
+ "cycles",
3005
+ "pending"
3006
+ ]);
3007
+ const counter = identity(item.counter);
3008
+ const cycles = integer(item.cycles, "delay cycles");
3009
+ if (cycles <= 0) throw new RangeError("Delay cycles must be positive");
3010
+ let pending;
3011
+ if (Object.hasOwn(item, "pending")) {
3012
+ dataObject(item.pending, [
3013
+ "state",
3014
+ "period",
3015
+ "active"
3016
+ ]);
3017
+ pending = Object.freeze({
3018
+ state: identity(item.pending.state),
3019
+ period: identity(item.pending.period),
3020
+ active: identity(item.pending.active)
3021
+ });
3022
+ }
3023
+ delays.set(pc, Object.freeze({
3024
+ counter,
3025
+ cycles,
3026
+ ...pending ? { pending } : {}
3027
+ }));
3028
+ }
3029
+ return delays;
3030
+ }
3031
+ /** Validate and copy provider output; caller applies it atomically. */
3032
+ captureCodeMetadata(region, value) {
3033
+ dataObject(value, ["polling", "delays"]);
3034
+ if (!Object.hasOwn(value, "polling") || !Object.hasOwn(value, "delays")) throw new TypeError("codeMetadata must contain polling and delays");
3035
+ return {
3036
+ polling: this.capturePolling(value.polling, region),
3037
+ delays: this.captureMetadataDelays(value.delays, region)
3038
+ };
3039
+ }
2659
3040
  attach(options) {
2660
3041
  this.assertCallAllowed();
2661
3042
  if (this.board.phase !== "initialize" || this.board.current !== this) throw this.board.error("INVALID_CALL_STATE", "attachJit is initialization-only", this);
2662
3043
  dataObject(options, [
2663
3044
  "entry",
2664
3045
  "code",
3046
+ "codeRegions",
3047
+ "codeMetadata",
2665
3048
  "pc",
3049
+ "functions",
2666
3050
  "beforeInstruction",
2667
3051
  "polling",
2668
3052
  "delays",
@@ -2673,59 +3057,66 @@ var Instance = class {
2673
3057
  identity(options.pc);
2674
3058
  if (this.jits.some((jit) => jit.active && jit.options.entry === options.entry)) throw this.board.error("INVALID_BINDING", "Duplicate JIT entry", this);
2675
3059
  if (!this.memories.has(options.code) || this.declarations.get(options.pc)?.kind !== "state" || this.declarations.get(options.pc).type.kind !== "number" || typeof options.translate !== "function") throw this.board.error("INVALID_BINDING", "Invalid JIT binding", this);
3060
+ const codeRegions = this.captureCodeRegions(options);
3061
+ if (Object.hasOwn(options, "codeMetadata")) {
3062
+ if (typeof options.codeMetadata !== "function") throw this.board.error("INVALID_BINDING", "Invalid codeMetadata provider", this);
3063
+ if (Object.hasOwn(options, "polling") || Object.hasOwn(options, "delays")) throw this.board.error("INVALID_BINDING", "codeMetadata is mutually exclusive with static polling/delays", this);
3064
+ }
2676
3065
  if (options.beforeInstruction !== void 0) {
2677
3066
  dataObject(options.beforeInstruction, ["when", "call"]);
2678
3067
  const condition = this.declarations.get(options.beforeInstruction.when), fn = this.declarations.get(options.beforeInstruction.call);
2679
3068
  if (!condition || !["state", "derived"].includes(condition.kind) || !("type" in condition) || condition.type.kind !== "bool" || fn?.kind !== "function" || fn.params.length || fn.returns) throw this.board.error("INVALID_BINDING", "Invalid instruction hook", this);
2680
3069
  } else if (Object.hasOwn(options, "beforeInstruction")) throw new TypeError("Invalid beforeInstruction");
2681
- const polling = /* @__PURE__ */ new Map();
2682
- if (Object.hasOwn(options, "polling")) {
2683
- if (!Array.isArray(options.polling)) throw new TypeError("polling must be an array");
2684
- for (const item of options.polling) {
2685
- dataObject(item, [
2686
- "pc",
2687
- "predicate",
2688
- "consume",
2689
- "wait"
2690
- ]);
2691
- const pc = finite(item.pc, "polling pc");
2692
- const predicate = identity(item.predicate);
2693
- const declaration = this.declarations.get(predicate);
2694
- if (polling.has(pc) || declaration?.kind !== "function" || !declaration.pure || declaration.params.length || declaration.returns?.kind !== "bool") throw this.board.error("INVALID_BINDING", "Invalid polling declaration", this);
2695
- let consume;
2696
- if (Object.hasOwn(item, "consume")) {
2697
- consume = identity(item.consume);
2698
- const fn = this.declarations.get(consume);
2699
- if (fn?.kind !== "function" || fn.params.length !== 0 || fn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling consume function", this);
2700
- }
2701
- let wait;
2702
- if (Object.hasOwn(item, "wait")) {
2703
- dataObject(item.wait, ["delay", "advance"]);
2704
- const delay = identity(item.wait.delay);
2705
- const advance = identity(item.wait.advance);
2706
- const delayFn = this.declarations.get(delay);
2707
- const advanceFn = this.declarations.get(advance);
2708
- if (delayFn?.kind !== "function" || !delayFn.pure || delayFn.params.length !== 0 || delayFn.returns?.kind !== "number" || advanceFn?.kind !== "function" || advanceFn.params.length !== 1 || advanceFn.params[0].type.kind !== "number" || advanceFn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling wait functions", this);
2709
- wait = Object.freeze({
2710
- delay,
2711
- advance
2712
- });
3070
+ const polling = Object.hasOwn(options, "polling") ? this.capturePolling(options.polling) : /* @__PURE__ */ new Map();
3071
+ if (Object.hasOwn(options, "delays") && !(options.delays instanceof Map)) throw new TypeError("delays must be a Map");
3072
+ const metadata = Object.hasOwn(options, "codeMetadata") ? {
3073
+ regions: new Map(codeRegions.all.map((region) => [region, {
3074
+ region,
3075
+ appliedVersion: -1,
3076
+ dirty: false,
3077
+ pending: [],
3078
+ polling: /* @__PURE__ */ new Map(),
3079
+ delays: /* @__PURE__ */ new Map()
3080
+ }])),
3081
+ polling: /* @__PURE__ */ new Map(),
3082
+ delays: /* @__PURE__ */ new Map()
3083
+ } : void 0;
3084
+ const base = this.entry.model;
3085
+ const emit = options.functions;
3086
+ if (Object.hasOwn(options, "functions") && typeof emit !== "function") throw new TypeError("functions must be a JIT function builder callback");
3087
+ let model = base;
3088
+ let functions;
3089
+ let host = this.host;
3090
+ if (emit) {
3091
+ const declarations = emit(base);
3092
+ acceptSync(declarations);
3093
+ if (!Array.isArray(declarations)) throw new TypeError("Expected JIT function declarations");
3094
+ model = bindJitFunctions(base, declarations);
3095
+ const local = /* @__PURE__ */ new Map();
3096
+ for (const declaration of model.declarations.slice(base.declarations.length)) if (declaration.kind === "function") local.set(declaration.name, declaration);
3097
+ functions = local;
3098
+ host = {
3099
+ ...this.host,
3100
+ call: (name, args) => {
3101
+ const fn = local.get(name);
3102
+ return fn ? body(fn.body)(host, args) : this.invoke(name, args);
2713
3103
  }
2714
- polling.set(pc, Object.freeze({
2715
- predicate,
2716
- ...consume === void 0 ? {} : { consume },
2717
- ...wait === void 0 ? {} : { wait }
2718
- }));
2719
- }
3104
+ };
2720
3105
  }
2721
- if (Object.hasOwn(options, "delays") && !(options.delays instanceof Map)) throw new TypeError("delays must be a Map");
2722
3106
  const jit = {
2723
3107
  instance: this,
3108
+ model,
3109
+ host,
3110
+ ...functions === void 0 ? {} : { functions },
2724
3111
  options: Object.freeze({
2725
3112
  ...options,
3113
+ ...options.codeRegions === void 0 ? {} : { codeRegions: codeRegions.additional },
2726
3114
  ...options.beforeInstruction ? { beforeInstruction: Object.freeze({ ...options.beforeInstruction }) } : {}
2727
3115
  }),
3116
+ codeRegions: codeRegions.all,
2728
3117
  cache: /* @__PURE__ */ new Map(),
3118
+ cacheMemories: /* @__PURE__ */ new Set(),
3119
+ metadata,
2729
3120
  polling,
2730
3121
  delays: options.delays ?? /* @__PURE__ */ new Map(),
2731
3122
  revision: 0,
@@ -2738,7 +3129,7 @@ var Instance = class {
2738
3129
  directProgramRevision: -1,
2739
3130
  direct: void 0,
2740
3131
  directSkip: void 0,
2741
- directMisses: 0,
3132
+ directMisses: /* @__PURE__ */ new Map(),
2742
3133
  pollReads: void 0,
2743
3134
  currentPc: void 0,
2744
3135
  automaticPolling: false,
@@ -2761,8 +3152,10 @@ var Instance = class {
2761
3152
  jit.pollingToken++;
2762
3153
  this.board.waitingJits.delete(jit);
2763
3154
  jit.cache.clear();
3155
+ jit.cacheMemories.clear();
2764
3156
  jit.directPrograms.clear();
2765
3157
  jit.direct = void 0;
3158
+ jit.directMisses.clear();
2766
3159
  jit.pollReads = void 0;
2767
3160
  } };
2768
3161
  this.resources.push(disposable);
@@ -2771,12 +3164,12 @@ var Instance = class {
2771
3164
  loadBytes(name, bytes, offset) {
2772
3165
  this.assertCallAllowed();
2773
3166
  if (this.board.phase !== "idle" && !(this.board.phase === "initialize" && this.board.current === this)) throw this.board.error("INVALID_CALL_STATE", "Code loading is not allowed in this phase", this);
2774
- if (typeof name !== "string" || !this.jits.some((jit) => jit.active && jit.options.code === name)) throw this.board.error("INVALID_BINDING", "Memory is not bound as code", this);
3167
+ if (typeof name !== "string" || !this.jits.some((jit) => jit.active && jit.codeRegions.some((region) => region.memory === name))) throw this.board.error("INVALID_BINDING", "Memory is not bound as code", this);
2775
3168
  if (!(bytes instanceof Uint8Array)) throw new TypeError("Code must be Uint8Array");
2776
3169
  const memory = this.memory(name), at = range(memory, offset, bytes.length);
2777
3170
  if (bytes.length) {
2778
3171
  memory.set(bytes.slice(), at);
2779
- this.memoryChanged(name);
3172
+ this.memoryChanged(name, at, bytes.length);
2780
3173
  }
2781
3174
  }
2782
3175
  source(path) {
@@ -2869,7 +3262,12 @@ function isPollingInstruction(body, pc, pcName) {
2869
3262
  //#endregion
2870
3263
  //#region src/runtime/jit.ts
2871
3264
  /** Large programs dispatch through shards; small ones stay on the faster monolithic form. */
2872
- var DIRECT_SHARD_SIZE = 8;
3265
+ var DIRECT_SHARD_SIZE = 32;
3266
+ function syncJitCall(jit, name) {
3267
+ const step = jit.host.call(name, []).next();
3268
+ if (!step.done) throw new TypeError("Unexpected suspension in synchronous function");
3269
+ return step.value;
3270
+ }
2873
3271
  /**
2874
3272
  * Program size above which whole-program rebuilds are amortized instead of immediate.
2875
3273
  *
@@ -2882,15 +3280,18 @@ var DIRECT_SHARD_SIZE = 8;
2882
3280
  var DIRECT_REBUILD_LINEAR_LIMIT = 16;
2883
3281
  /** Stride floor once a program exceeds `DIRECT_REBUILD_LINEAR_LIMIT`. */
2884
3282
  var DIRECT_REBUILD_MIN_BLOCKS = 64;
2885
- /** A PC that keeps falling back buys an early rebuild instead of waiting out a full stride. */
2886
- var DIRECT_REBUILD_PATIENCE = 512;
3283
+ /** A repeatedly visited translated PC can force a rebuild before the append-only stride. */
3284
+ var DIRECT_REBUILD_PATIENCE = 4;
3285
+ function directRebuildStride(compiled) {
3286
+ return compiled < DIRECT_REBUILD_LINEAR_LIMIT ? 1 : Math.max(DIRECT_REBUILD_MIN_BLOCKS, compiled);
3287
+ }
2887
3288
  var barriers = /* @__PURE__ */ new WeakMap();
2888
3289
  function directBarriers(jit) {
2889
3290
  let entry = barriers.get(jit);
2890
3291
  if (entry === void 0) {
2891
3292
  entry = {
2892
- stateMask: [],
2893
- memoryMask: []
3293
+ stateMask: /* @__PURE__ */ new Int32Array(0),
3294
+ memoryMask: /* @__PURE__ */ new Int32Array(0)
2894
3295
  };
2895
3296
  barriers.set(jit, entry);
2896
3297
  }
@@ -2907,6 +3308,129 @@ function directStats(jit) {
2907
3308
  directStopped: 0
2908
3309
  };
2909
3310
  }
3311
+ /** Region that supplies bytes for a logical PC; undefined means the service-PC fallback. */
3312
+ function codeRegionFor(jit, pc) {
3313
+ for (const region of jit.codeRegions) if (pc >= region.base && pc < region.base + region.size) return region;
3314
+ }
3315
+ /** Additional regions stay on the interpreter; only the primary memory feeds direct programs. */
3316
+ function directCodeInstruction(jit, instruction) {
3317
+ const region = instruction.codeRegion;
3318
+ return region === void 0 || region.memory === jit.options.code;
3319
+ }
3320
+ function effectivePolling(jit) {
3321
+ return jit.metadata?.polling ?? jit.polling;
3322
+ }
3323
+ function effectiveDelays(jit) {
3324
+ return jit.metadata?.delays ?? jit.delays;
3325
+ }
3326
+ /** Aliases of the primary memory must refresh together before a direct program is built. */
3327
+ function primaryCodeRegions(jit) {
3328
+ return jit.codeRegions.filter((region) => region.memory === jit.options.code);
3329
+ }
3330
+ /**
3331
+ * Lazily (re)build code-derived metadata for the requested regions. Provider calls never
3332
+ * happen from attach/store; this runs inside the translate phase immediately before the
3333
+ * polling/direct/translate decision that needs it.
3334
+ */
3335
+ function ensureMetadata(board, jit, regions) {
3336
+ const metadata = jit.metadata;
3337
+ const provider = jit.options.codeMetadata;
3338
+ if (metadata === void 0 || provider === void 0) return;
3339
+ const needed = [];
3340
+ const seen = /* @__PURE__ */ new Set();
3341
+ for (const region of regions) {
3342
+ const state = metadata.regions.get(region);
3343
+ if (state === void 0 || seen.has(state)) continue;
3344
+ seen.add(state);
3345
+ const version = jit.instance.codeVersion(region.memory);
3346
+ if (state.appliedVersion === version && state.pending.length === 0 && !state.dirty) continue;
3347
+ const changes = state.appliedVersion === -1 ? [Object.freeze({
3348
+ memory: region.memory,
3349
+ offset: 0,
3350
+ length: region.size
3351
+ })] : state.pending.map((change) => Object.freeze({ ...change }));
3352
+ needed.push({
3353
+ state,
3354
+ changes,
3355
+ version
3356
+ });
3357
+ }
3358
+ if (needed.length === 0) return;
3359
+ const prior = board.phase;
3360
+ board.phase = "translate";
3361
+ const prepared = [];
3362
+ try {
3363
+ for (const item of needed) {
3364
+ const { region } = item.state;
3365
+ const memory = jit.instance.memory(region.memory);
3366
+ const bytes = region.size >= memory.length ? memory : memory.subarray(0, region.size);
3367
+ let valid = true;
3368
+ try {
3369
+ const code = bytesView(bytes, () => {
3370
+ if (!valid) throw board.error("OBJECT_DISPOSED", "Metadata view expired", jit.instance);
3371
+ });
3372
+ const view = Object.freeze({
3373
+ memory: region.memory,
3374
+ base: region.base,
3375
+ size: region.size,
3376
+ codeVersion: item.version,
3377
+ code
3378
+ });
3379
+ const result = provider(Object.freeze({
3380
+ region: view,
3381
+ changes: Object.freeze(item.changes.slice())
3382
+ }));
3383
+ acceptSync(result);
3384
+ const captured = jit.instance.captureCodeMetadata(region, result);
3385
+ prepared.push({
3386
+ state: item.state,
3387
+ version: item.version,
3388
+ polling: captured.polling,
3389
+ delays: captured.delays
3390
+ });
3391
+ } finally {
3392
+ valid = false;
3393
+ }
3394
+ }
3395
+ let primary = false;
3396
+ for (const item of prepared) {
3397
+ item.state.appliedVersion = item.version;
3398
+ item.state.dirty = false;
3399
+ item.state.pending.length = 0;
3400
+ item.state.polling.clear();
3401
+ for (const [pc, binding] of item.polling) item.state.polling.set(pc, binding);
3402
+ item.state.delays.clear();
3403
+ for (const [pc, delay] of item.delays) item.state.delays.set(pc, delay);
3404
+ if (item.state.region.memory === jit.options.code) primary = true;
3405
+ }
3406
+ metadata.polling.clear();
3407
+ metadata.delays.clear();
3408
+ for (const state of metadata.regions.values()) {
3409
+ for (const [pc, binding] of state.polling) metadata.polling.set(pc, binding);
3410
+ for (const [pc, delay] of state.delays) metadata.delays.set(pc, delay);
3411
+ }
3412
+ if (primary) {
3413
+ jit.directPrograms.clear();
3414
+ jit.directProgramRevision = -1;
3415
+ jit.directSkip = void 0;
3416
+ if (!jit.direct?.frame.resume) {
3417
+ jit.direct = void 0;
3418
+ jit.directRevision = -1;
3419
+ }
3420
+ }
3421
+ } catch (cause) {
3422
+ throw board.wrap(cause, "JIT_FAILED", "translate", jit.instance);
3423
+ } finally {
3424
+ board.phase = prior;
3425
+ }
3426
+ }
3427
+ function ensureMetadataForPc(board, jit, pc) {
3428
+ if (jit.metadata === void 0) return;
3429
+ const region = codeRegionFor(jit, pc) ?? jit.codeRegions[0];
3430
+ const needed = [region];
3431
+ if (board.execution === "throughput" && board.jits.length === 1 && region.memory === jit.options.code) needed.push(...primaryCodeRegions(jit));
3432
+ ensureMetadata(board, jit, needed);
3433
+ }
2910
3434
  /** Publish the current guard sets into the masks the compiled blocks test at entry. */
2911
3435
  function syncDirectBarriers(jit) {
2912
3436
  const entry = directBarriers(jit);
@@ -2969,9 +3493,7 @@ function directHost(board, instance, frame) {
2969
3493
  },
2970
3494
  intent: (pin, value) => {
2971
3495
  publishTime();
2972
- const changed = instance.pin(pin).intent !== value;
2973
- instance.host.intent(pin, value);
2974
- if (changed) frame.publishPending = true;
3496
+ if (instance.writeIntent(pin, value)) frame.publishPending = true;
2975
3497
  },
2976
3498
  resistor: (pin, resistance) => {
2977
3499
  publishTime();
@@ -3004,51 +3526,126 @@ function directLayout(jit) {
3004
3526
  const memories = new Map(memoryNames.map((name, index) => [name, index]));
3005
3527
  const memoryBanks = memoryNames.map((name) => instance.memory(name));
3006
3528
  const memoryViews = memoryBanks.map((memory) => new DataView(memory.buffer, memory.byteOffset, memory.byteLength));
3529
+ const pinNames = [...instance.pins.keys()];
3530
+ const pins = new Map(pinNames.map((name, index) => [name, index]));
3531
+ const pinObjects = pinNames.map((name) => instance.pin(name));
3532
+ const pinElectricalSlots = Int32Array.from(pinObjects, (pin) => instance.board.electricalSlot(pin));
3007
3533
  jit.directLayout = {
3008
3534
  ...bank,
3009
3535
  memoryNames: Object.freeze(memoryNames),
3010
3536
  memories,
3011
3537
  memoryBanks: Object.freeze(memoryBanks),
3012
- memoryViews: Object.freeze(memoryViews)
3538
+ memoryViews: Object.freeze(memoryViews),
3539
+ pinNames: Object.freeze(pinNames),
3540
+ pins,
3541
+ pinObjects: Object.freeze(pinObjects),
3542
+ pinElectricalSlots
3013
3543
  };
3014
3544
  return jit.directLayout;
3015
3545
  }
3016
- function createDirectFrame(board, instance, layout, program, barrier) {
3546
+ function flushDirect(board, instance, layout, frame) {
3547
+ board.time = frame.time;
3548
+ frame.publishPending = false;
3549
+ let wrote = instance.commitDirectStates(frame.stateDirty);
3550
+ for (let word = 0; word < frame.memoryDirty.length; word++) {
3551
+ let bits = frame.memoryDirty[word];
3552
+ if (bits === 0) continue;
3553
+ frame.memoryDirty[word] = 0;
3554
+ while (bits !== 0) {
3555
+ const slot = word * 32 + 31 - Math.clz32(bits & -bits);
3556
+ instance.memoryChanged(layout.memoryNames[slot]);
3557
+ bits &= bits - 1;
3558
+ wrote = true;
3559
+ }
3560
+ }
3561
+ return wrote;
3562
+ }
3563
+ function createDirectFrame(board, jit, layout, program, barrier) {
3564
+ const instance = jit.instance;
3565
+ const { pinObjects, pinNames, pinElectricalSlots } = layout;
3017
3566
  const frame = {
3018
3567
  states: layout.stateValues,
3019
3568
  memories: [...layout.memoryBanks],
3020
3569
  memoryViews: layout.memoryViews,
3570
+ pins: pinObjects,
3571
+ resistors: [],
3021
3572
  locals: new Array(program.localCount),
3022
- stateDirty: new Array(Math.ceil(layout.stateNames.length / 32)).fill(0),
3023
- memoryDirty: new Array(Math.ceil(layout.memoryNames.length / 32)).fill(0),
3573
+ stateDirty: new Int32Array(Math.ceil(layout.stateNames.length / 32)),
3574
+ memoryDirty: new Int32Array(Math.ceil(layout.memoryNames.length / 32)),
3024
3575
  time: board.time,
3025
3576
  due: board.time,
3026
- resume: 0
3577
+ resume: 0,
3578
+ stopAfterInstruction: false,
3579
+ boundarySettled: false
3580
+ };
3581
+ frame.writePinIntent = (pinIndex, value) => {
3582
+ if (!Object.hasOwn(instance, "writeIntent")) {
3583
+ const pin = pinObjects[pinIndex];
3584
+ if (pin.intent === value) return;
3585
+ pin.intent = value;
3586
+ instance.board.markElectricalDirty(pinElectricalSlots[pinIndex]);
3587
+ frame.publishPending = true;
3588
+ return;
3589
+ }
3590
+ board.time = frame.time;
3591
+ if (instance.writeIntent(pinNames[pinIndex], value)) frame.publishPending = true;
3027
3592
  };
3028
3593
  frame.host = directHost(board, instance, frame);
3594
+ if (jit.metadata === void 0) {
3595
+ frame.publishCheckpoint = () => {
3596
+ flushDirect(board, instance, layout, frame);
3597
+ board.boundary();
3598
+ if (jit.directProgramRevision === -1 || !board.canContinueDirect(jit, frame.due)) {
3599
+ frame.boundarySettled = true;
3600
+ return false;
3601
+ }
3602
+ board.current = instance;
3603
+ return true;
3604
+ };
3605
+ if (jit.options.beforeInstruction === void 0) {
3606
+ const pcIndex = layout.states.get(jit.options.pc);
3607
+ frame.finishCheckpoint = (deadline, emptySuffix) => {
3608
+ if (emptySuffix) board.time = frame.time;
3609
+ else flushDirect(board, instance, layout, frame);
3610
+ board.boundary();
3611
+ const direct = jit.direct;
3612
+ const nextPc = frame.states[pcIndex];
3613
+ if (jit.directProgramRevision === -1 || direct?.frame !== frame || !direct.pcs.has(nextPc) || jit.directSkip === nextPc || jit.directRevision !== jit.revision && jit.revision - jit.directRevision >= directRebuildStride(direct.pcs.size) || frame.time >= deadline || board.events.time < deadline || !emptySuffix && !board.canContinueDirect(jit, frame.time)) {
3614
+ frame.boundarySettled = true;
3615
+ return false;
3616
+ }
3617
+ if (jit.directObserverRevision !== instance.observerRevision) refreshDirectGuards(jit);
3618
+ frame.stopAfterInstruction = false;
3619
+ board.current = instance;
3620
+ return true;
3621
+ };
3622
+ }
3623
+ }
3029
3624
  frame.blockedStates = barrier.stateMask;
3030
3625
  frame.blockedMemories = barrier.memoryMask;
3031
3626
  return frame;
3032
3627
  }
3033
3628
  function runDirect(board, jit, hookReads) {
3034
3629
  const instance = jit.instance;
3035
- const pending = Boolean(jit.direct?.frame.resume);
3630
+ let pending = Boolean(jit.direct?.frame.resume);
3036
3631
  if (!pending) {
3037
3632
  const pc = finite(instance.states.get(jit.options.pc), "pc");
3038
- if (board.execution !== "throughput" || board.jits.length !== 1 || jit.polling.has(pc) || jit.cache.get(pc)?.polling) return false;
3633
+ const region = codeRegionFor(jit, pc);
3634
+ if (board.execution !== "throughput" || board.jits.length !== 1 || region !== void 0 && region.memory !== jit.options.code || effectivePolling(jit).has(pc) || jit.cache.get(pc)?.polling) return false;
3039
3635
  refreshDirectGuards(jit, hookReads);
3040
3636
  if (jit.directSkip === pc) return false;
3041
3637
  if (jit.directRevision !== jit.revision) {
3042
3638
  const compiled = jit.direct?.pcs.size ?? 0;
3043
3639
  const stale = jit.revision - jit.directRevision;
3044
- const stride = compiled < DIRECT_REBUILD_LINEAR_LIMIT ? 1 : Math.max(DIRECT_REBUILD_MIN_BLOCKS, compiled);
3640
+ const stride = directRebuildStride(compiled);
3045
3641
  const covered = jit.direct?.pcs.has(pc) === true;
3046
- if (!(jit.direct === void 0 || stale >= stride || !covered && jit.directMisses >= DIRECT_REBUILD_PATIENCE)) {
3642
+ const misses = covered ? 0 : jit.directMisses.get(pc) ?? 0;
3643
+ if (!(jit.direct === void 0 || stale >= stride || misses >= DIRECT_REBUILD_PATIENCE)) {
3047
3644
  if (!covered) {
3048
3645
  const stats = directStats(jit);
3049
3646
  stats.directCalls++;
3050
3647
  stats.directFallbacks++;
3051
- jit.directMisses += 1;
3648
+ if (jit.cache.has(pc)) jit.directMisses.set(pc, misses + 1);
3052
3649
  return false;
3053
3650
  }
3054
3651
  } else {
@@ -3058,10 +3655,10 @@ function runDirect(board, jit, hookReads) {
3058
3655
  jit.directProgramRevision = jit.revision;
3059
3656
  }
3060
3657
  const layout = directLayout(jit);
3061
- const instructions = [...jit.cache.values()].filter((instruction) => !instruction.polling && !jit.polling.has(instruction.pc));
3658
+ const instructions = [...jit.cache.values()].filter((instruction) => !instruction.polling && !effectivePolling(jit).has(instruction.pc) && directCodeInstruction(jit, instruction));
3062
3659
  /** Declared busy-wait heads fold their remaining rounds inside the emitted body. */
3063
3660
  const delayLoops = /* @__PURE__ */ new Map();
3064
- for (const [headPc, delay] of jit.delays) {
3661
+ for (const [headPc, delay] of effectiveDelays(jit)) {
3065
3662
  const counter = layout.states.get(delay.counter);
3066
3663
  if (counter === void 0) continue;
3067
3664
  const pending = delay.pending === void 0 ? void 0 : {
@@ -3084,36 +3681,39 @@ function runDirect(board, jit, hookReads) {
3084
3681
  jit.direct = cached;
3085
3682
  jit.directRevision = jit.revision;
3086
3683
  } else {
3087
- const { states, memories } = layout;
3684
+ const { states, memories, pins } = layout;
3088
3685
  const cache = jit.directCache ??= compileDirectJit.createCache();
3089
3686
  const program = compileDirectJit(instructions, {
3090
3687
  states,
3091
3688
  memories,
3689
+ pins,
3092
3690
  pc: {
3093
3691
  name: jit.options.pc,
3094
3692
  index: states.get(jit.options.pc)
3095
3693
  },
3096
3694
  host: true,
3695
+ ...jit.functions === void 0 ? {} : { functions: jit.functions },
3097
3696
  split: true,
3098
3697
  shardSize: DIRECT_SHARD_SIZE,
3099
3698
  delayLoops
3100
3699
  }, cache);
3101
3700
  jit.directRevision = jit.revision;
3102
- jit.directMisses = 0;
3701
+ jit.directMisses.clear();
3103
3702
  const stats = directStats(jit);
3104
3703
  stats.directShards = program?.shards ?? 0;
3105
3704
  if (program) stats.directCompiles++;
3106
3705
  const barrier = directBarriers(jit);
3107
3706
  barrier.stateIndex = states;
3108
3707
  barrier.memoryIndex = memories;
3109
- barrier.stateMask.length = Math.ceil(layout.stateNames.length / 32);
3110
- barrier.memoryMask.length = Math.ceil(layout.memoryNames.length / 32);
3708
+ const stateMaskWords = Math.ceil(layout.stateNames.length / 32);
3709
+ const memoryMaskWords = Math.ceil(layout.memoryNames.length / 32);
3710
+ if (barrier.stateMask.length !== stateMaskWords) barrier.stateMask = new Int32Array(stateMaskWords);
3711
+ if (barrier.memoryMask.length !== memoryMaskWords) barrier.memoryMask = new Int32Array(memoryMaskWords);
3111
3712
  syncDirectBarriers(jit);
3112
3713
  jit.direct = program ? {
3113
3714
  program,
3114
3715
  pcs: new Set(program.pcs),
3115
- revision: jit.revision,
3116
- frame: createDirectFrame(board, instance, layout, program, barrier)
3716
+ frame: createDirectFrame(board, jit, layout, program, barrier)
3117
3717
  } : void 0;
3118
3718
  if (!jit.direct) jit.directPrograms.delete(key);
3119
3719
  else jit.directPrograms.set(key, jit.direct);
@@ -3124,67 +3724,65 @@ function runDirect(board, jit, hookReads) {
3124
3724
  }
3125
3725
  const direct = jit.direct;
3126
3726
  const frame = direct.frame;
3127
- if (pending) frame.stopAfterInstruction = true;
3128
- frame.time = board.time;
3129
- frame.stateDirty.fill(0);
3130
- frame.memoryDirty.fill(0);
3131
- const start = board.time;
3132
- let reason;
3133
- let wrote = false;
3134
- const stats = directStats(jit);
3135
- stats.directCalls++;
3136
- try {
3137
- reason = direct.program.run(frame, Math.min(board.executionEnd, board.events.time));
3138
- } finally {
3139
- board.time = frame.time;
3140
- frame.publishPending = false;
3141
- const layout = jit.directLayout;
3142
- for (let word = 0; word < frame.stateDirty.length; word++) {
3143
- let bits = frame.stateDirty[word];
3144
- while (bits !== 0) {
3145
- const slot = word * 32 + 31 - Math.clz32(bits & -bits);
3146
- instance.host.write(layout.stateNames[slot], frame.states[slot]);
3147
- bits &= bits - 1;
3148
- wrote = true;
3727
+ const layout = jit.directLayout;
3728
+ for (;;) {
3729
+ if (pending) frame.stopAfterInstruction = true;
3730
+ frame.time = board.time;
3731
+ const start = board.time;
3732
+ let reason;
3733
+ let wrote;
3734
+ const stats = directStats(jit);
3735
+ stats.directCalls++;
3736
+ try {
3737
+ reason = direct.program.run(frame, Math.min(board.executionEnd, board.events.time));
3738
+ } finally {
3739
+ wrote = flushDirect(board, instance, layout, frame);
3740
+ }
3741
+ if (frame.boundarySettled) frame.boundarySettled = false;
3742
+ else if (reason !== "fallback" || wrote || board.time !== start) board.boundary();
3743
+ if (reason === "fallback") {
3744
+ const nextPc = finite(instance.states.get(jit.options.pc), "pc");
3745
+ if (!(effectivePolling(jit).has(nextPc) || jit.cache.get(nextPc)?.polling)) {
3746
+ stats.directFallbacks++;
3747
+ jit.directSkip = nextPc;
3149
3748
  }
3150
- }
3151
- for (let word = 0; word < frame.memoryDirty.length; word++) {
3152
- let bits = frame.memoryDirty[word];
3153
- while (bits !== 0) {
3154
- const slot = word * 32 + 31 - Math.clz32(bits & -bits);
3155
- instance.memoryChanged(layout.memoryNames[slot]);
3156
- bits &= bits - 1;
3157
- wrote = true;
3749
+ if (!wrote && board.time === start && board.time < board.executionEnd) return false;
3750
+ } else if (reason === "stopped") {
3751
+ stats.directStopped++;
3752
+ jit.stopped = true;
3753
+ return true;
3754
+ } else if (reason === "invalidated") {
3755
+ frame.stopAfterInstruction = false;
3756
+ if (jit.directProgramRevision === -1 && frame.resume === 0) {
3757
+ jit.direct = void 0;
3758
+ jit.directRevision = -1;
3759
+ }
3760
+ } else stats.directDeadlines++;
3761
+ if (frame.resume) {
3762
+ const wake = Math.max(frame.due, board.time);
3763
+ if (jit.metadata === void 0 && board.canContinueDirect(jit, wake)) {
3764
+ board.time = wake;
3765
+ board.current = instance;
3766
+ pending = true;
3767
+ continue;
3768
+ }
3769
+ if (wake > board.time) {
3770
+ board.events.push(wake, () => board.queueJit(jit));
3771
+ return true;
3158
3772
  }
3159
3773
  }
3160
- }
3161
- if (reason !== "fallback" || wrote || board.time !== start) board.boundary();
3162
- if (reason === "fallback") {
3163
- const nextPc = finite(instance.states.get(jit.options.pc), "pc");
3164
- if (!(jit.polling.has(nextPc) || jit.cache.get(nextPc)?.polling)) {
3165
- stats.directFallbacks++;
3166
- jit.directSkip = nextPc;
3167
- }
3168
- if (board.time === start && board.time < board.executionEnd) return false;
3169
- } else if (reason === "stopped") {
3170
- stats.directStopped++;
3171
- jit.stopped = true;
3774
+ board.queueJit(jit);
3172
3775
  return true;
3173
- } else if (reason === "invalidated") {
3174
- frame.stopAfterInstruction = false;
3175
- if (direct.revision !== jit.revision) {
3176
- jit.direct = void 0;
3177
- jit.directRevision = -1;
3178
- }
3179
- } else stats.directDeadlines++;
3180
- if (frame.resume && frame.due > board.time) board.events.push(frame.due, () => board.queueJit(jit));
3181
- else board.queueJit(jit);
3182
- return true;
3776
+ }
3183
3777
  }
3184
- function pollingDependencies(jit, dependencies) {
3778
+ function pollingDependencies(jit, dependencies, pc) {
3185
3779
  const result = new Map(dependencies);
3186
3780
  const instance = jit.instance;
3187
- for (const slot of [instance.stateResources.get(jit.options.pc), instance.memoryResources.get(jit.options.code)]) result.set(slot, slot.version);
3781
+ const pcSlot = instance.stateResources.get(jit.options.pc);
3782
+ result.set(pcSlot, pcSlot.version);
3783
+ const memory = (pc === void 0 ? void 0 : codeRegionFor(jit, pc))?.memory ?? jit.options.code;
3784
+ const slot = instance.memoryResources.get(memory);
3785
+ result.set(slot, slot.version);
3188
3786
  return result;
3189
3787
  }
3190
3788
  /** Park a polling JIT and, when requested, schedule the next device time event. */
@@ -3224,7 +3822,7 @@ function jitSignal(board, jit, signal) {
3224
3822
  return true;
3225
3823
  }
3226
3824
  if (signal.kind === "waitUntil") {
3227
- const checked = jit.instance.evaluate(() => jit.instance.syncCall(signal.predicate));
3825
+ const checked = jit.instance.evaluate(() => syncJitCall(jit, signal.predicate));
3228
3826
  if (checked.value === true) return false;
3229
3827
  jit.predicate = signal.predicate;
3230
3828
  jit.pollingWait = false;
@@ -3245,7 +3843,7 @@ function jitSignal(board, jit, signal) {
3245
3843
  jit.instance.host.write(jit.options.pc, signal.pc);
3246
3844
  jit.execution = void 0;
3247
3845
  const polling = jit.automaticPolling && duration > 0 && signal.pc === jit.currentPc && jit.pollReads;
3248
- const dependencies = polling ? pollingDependencies(jit, polling) : void 0;
3846
+ const dependencies = polling ? pollingDependencies(jit, polling, jit.currentPc) : void 0;
3249
3847
  jit.automaticPolling = false;
3250
3848
  jit.pollReads = void 0;
3251
3849
  board.boundary();
@@ -3268,6 +3866,7 @@ function runJit(board, jit) {
3268
3866
  jit.queued = false;
3269
3867
  if (!jit.active || jit.stopped) return;
3270
3868
  board.current = jit.instance;
3869
+ if (jit.metadata !== void 0) ensureMetadataForPc(board, jit, finite(jit.instance.states.get(jit.options.pc), "pc"));
3271
3870
  if (jit.direct?.frame.resume) {
3272
3871
  runDirect(board, jit);
3273
3872
  return;
@@ -3281,7 +3880,7 @@ function runJit(board, jit) {
3281
3880
  if (hook) {
3282
3881
  const kind = jit.instance.declarations.get(hook.when).kind;
3283
3882
  const priorPc = jit.instance.states.get(jit.options.pc);
3284
- const checked = board.execution === "throughput" && (board.jits.length === 1 || jit.polling.has(priorPc)) ? jit.instance.evaluate(() => jit.instance.read(kind, hook.when)) : void 0;
3883
+ const checked = board.execution === "throughput" && (board.jits.length === 1 || effectivePolling(jit).has(priorPc)) ? jit.instance.evaluate(() => jit.instance.read(kind, hook.when)) : void 0;
3285
3884
  const handled = (checked ? checked.value : jit.instance.read(kind, hook.when)) === true;
3286
3885
  if (handled) {
3287
3886
  const execution = jit.instance.invoke(hook.call);
@@ -3297,7 +3896,7 @@ function runJit(board, jit) {
3297
3896
  }
3298
3897
  const pc = finite(jit.instance.states.get(jit.options.pc), "pc");
3299
3898
  if (board.execution === "throughput") {
3300
- const declaration = jit.polling.get(pc);
3899
+ const declaration = effectivePolling(jit).get(pc);
3301
3900
  if (declaration) {
3302
3901
  const checked = jit.instance.evaluate(() => jit.instance.syncCall(declaration.predicate));
3303
3902
  if (checked.value !== true) {
@@ -3305,7 +3904,7 @@ function runJit(board, jit) {
3305
3904
  let duration = 0;
3306
3905
  const wait = declaration.wait;
3307
3906
  if (wait) duration = time(jit.instance.evaluate(() => jit.instance.syncCall(wait.delay), dependencies).value);
3308
- waitForPolling(board, jit, pollingDependencies(jit, dependencies), duration, wait?.advance);
3907
+ waitForPolling(board, jit, pollingDependencies(jit, dependencies, pc), duration, wait?.advance);
3309
3908
  return;
3310
3909
  }
3311
3910
  if (declaration.consume) jit.instance.syncCall(declaration.consume);
@@ -3318,28 +3917,43 @@ function runJit(board, jit) {
3318
3917
  board.phase = "translate";
3319
3918
  let valid = true;
3320
3919
  try {
3321
- const code = bytesView(jit.instance.memory(jit.options.code), () => {
3920
+ const codeRegion = codeRegionFor(jit, pc);
3921
+ const codeMemory = codeRegion?.memory ?? jit.options.code;
3922
+ const memory = jit.instance.memory(codeMemory);
3923
+ const bytes = codeRegion === void 0 || codeRegion.size >= memory.length ? memory : memory.subarray(0, codeRegion.size);
3924
+ const code = bytesView(bytes, () => {
3322
3925
  if (!valid) throw board.error("OBJECT_DISPOSED", "Translation view expired", jit.instance);
3323
3926
  });
3324
3927
  const result = jit.options.translate(Object.freeze({
3325
3928
  pc,
3326
- code
3327
- }), createJitBlockBuilder({ device: jit.instance.entry.model }));
3929
+ code,
3930
+ codeBase: codeRegion?.base ?? 0,
3931
+ codeVersion: jit.instance.codeVersion(codeMemory)
3932
+ }), createJitBlockBuilder({ device: jit.model }));
3328
3933
  acceptSync(result);
3329
- const block = validateBoundBlockIR(result, jit.instance.entry.model);
3934
+ const block = validateBoundBlockIR(result, jit.model);
3330
3935
  if (block.instructions[0]?.pc !== pc) throw new TypeError("Translated first pc does not match");
3331
- const instructions = block.instructions.map((instruction) => ({
3332
- pc: instruction.pc,
3333
- nextPc: instruction.nextPc,
3334
- body: instruction.body,
3335
- polling: isPollingInstruction(instruction.body, instruction.pc, jit.options.pc),
3336
- execute: body(instruction.body)
3337
- }));
3936
+ const instructions = block.instructions.map((instruction) => {
3937
+ const region = codeRegionFor(jit, instruction.pc);
3938
+ return {
3939
+ pc: instruction.pc,
3940
+ nextPc: instruction.nextPc,
3941
+ body: instruction.body,
3942
+ polling: isPollingInstruction(instruction.body, instruction.pc, jit.options.pc),
3943
+ execute: body(instruction.body),
3944
+ codeRegion: region
3945
+ };
3946
+ });
3947
+ if (instructions.some((entry) => jit.direct?.pcs.has(entry.pc))) {
3948
+ jit.direct = void 0;
3949
+ jit.directPrograms.clear();
3950
+ }
3338
3951
  for (let index = instructions.length - 1; index >= 0; index--) {
3339
3952
  const entry = instructions[index];
3340
3953
  jit.cache.set(entry.pc, entry);
3954
+ jit.cacheMemories.add(entry.codeRegion?.memory ?? jit.options.code);
3341
3955
  }
3342
- jit.revision++;
3956
+ if (instructions.some((entry) => entry.codeRegion === void 0 || entry.codeRegion.memory === jit.options.code)) jit.revision++;
3343
3957
  jit.directSkip = void 0;
3344
3958
  instruction = instructions[0];
3345
3959
  } catch (cause) {
@@ -3353,7 +3967,7 @@ function runJit(board, jit) {
3353
3967
  jit.automaticPolling = board.execution === "throughput" && board.jits.length === 1 && instruction.polling && !hookPending && (!hook || hookReads !== void 0);
3354
3968
  jit.pollReads = hookReads;
3355
3969
  jit.instance.host.write(jit.options.pc, instruction.nextPc);
3356
- jit.execution = instruction.execute(jit.instance.host);
3970
+ jit.execution = instruction.execute(jit.host);
3357
3971
  }
3358
3972
  for (;;) {
3359
3973
  const step = jit.automaticPolling ? (() => {
@@ -3415,8 +4029,8 @@ var BoardRuntime = class {
3415
4029
  status = "ready";
3416
4030
  phase = "assembly";
3417
4031
  current;
3418
- electricalDirty = true;
3419
- /** Dirty electrical slots: the publish plan maps them straight onto sample slots. */
4032
+ /** -1: clean; -2: initial solve or multiple dirty slots; otherwise the only dirty slot. */
4033
+ pendingElectricalSlot = -2;
3420
4034
  dirtyElectricalSlots = /* @__PURE__ */ new Set();
3421
4035
  observations = new ActivationQueue();
3422
4036
  reactionBatch = [];
@@ -3773,7 +4387,7 @@ var BoardRuntime = class {
3773
4387
  }
3774
4388
  }
3775
4389
  /**
3776
- * Fail-closed admission for staying inside generated code after a publication checkpoint.
4390
+ * Fail-closed admission for resuming generated code without a scheduler round trip.
3777
4391
  * The JIT must be the only direct owner, all same-time scheduler stages must be empty,
3778
4392
  * and no event may be due through the requested horizon. The target time is exclusive:
3779
4393
  * code must not resume at `executionEnd`.
@@ -3790,11 +4404,29 @@ var BoardRuntime = class {
3790
4404
  electricalSlot(pin) {
3791
4405
  return this.electricalSlots.get(pin);
3792
4406
  }
4407
+ markElectricalDirty(slot) {
4408
+ const pending = this.pendingElectricalSlot;
4409
+ if (pending === slot) return;
4410
+ if (pending === -1) {
4411
+ this.pendingElectricalSlot = slot;
4412
+ return;
4413
+ }
4414
+ if (pending >= 0) {
4415
+ this.dirtyElectricalSlots.add(pending);
4416
+ this.pendingElectricalSlot = -2;
4417
+ }
4418
+ this.dirtyElectricalSlots.add(slot);
4419
+ }
4420
+ /** Dirty slot count for diagnostics, not used by the publication path. */
4421
+ get dirtyElectricalCount() {
4422
+ return this.pendingElectricalSlot >= 0 ? 1 : this.dirtyElectricalSlots.size;
4423
+ }
3793
4424
  publish() {
3794
- if (!this.electricalDirty) return;
3795
- const changed = this.network.solveSlots(this.dirtyElectricalSlots);
3796
- this.dirtyElectricalSlots.clear();
3797
- this.electricalDirty = false;
4425
+ const pending = this.pendingElectricalSlot;
4426
+ if (pending === -1) return;
4427
+ const changed = pending >= 0 ? this.network.solveSlot(pending) : this.network.solveSlots(this.dirtyElectricalSlots);
4428
+ if (pending === -2) this.dirtyElectricalSlots.clear();
4429
+ this.pendingElectricalSlot = -1;
3798
4430
  for (let index = 0; index < changed.length; index++) this.invalidate(this.sampleSlotsBySlot[changed[index]]);
3799
4431
  }
3800
4432
  bindObservation(observation, path) {
@@ -3951,7 +4583,7 @@ var BoardRuntime = class {
3951
4583
  }
3952
4584
  boundary() {
3953
4585
  for (;;) {
3954
- this.publish();
4586
+ if (this.pendingElectricalSlot !== -1) this.publish();
3955
4587
  if (!this.observations.size) return;
3956
4588
  const reactions = this.reactionBatch;
3957
4589
  reactions.length = 0;
@@ -4201,7 +4833,7 @@ var BoardRuntime = class {
4201
4833
  if (remainder) this.events.push(time(this.time + (jit.pollingPeriod - remainder)), () => this.queueJit(jit));
4202
4834
  else this.queueJit(jit);
4203
4835
  } else if (jit.predicate) {
4204
- const checked = jit.instance.evaluate(() => jit.instance.syncCall(jit.predicate));
4836
+ const checked = jit.instance.evaluate(() => syncJitCall(jit, jit.predicate));
4205
4837
  jit.dependencies = checked.dependencies;
4206
4838
  if (checked.value === true) {
4207
4839
  delete jit.predicate;