@turing-machine-js/machine 7.0.0-alpha.3 → 7.0.0-alpha.4
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/CHANGELOG.md +50 -0
- package/README.md +34 -1
- package/dist/classes/State.d.ts +81 -0
- package/dist/index.cjs +845 -514
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +845 -514
- package/dist/utilities/stateGraph.d.ts +91 -0
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -175,6 +175,153 @@ class Reference {
|
|
|
175
175
|
}
|
|
176
176
|
_Reference_referenceBinding = new WeakMap();
|
|
177
177
|
|
|
178
|
+
const movementDescriptionToLabel = {
|
|
179
|
+
'move caret left command': 'L',
|
|
180
|
+
'move caret right command': 'R',
|
|
181
|
+
'do not move carer': 'S',
|
|
182
|
+
};
|
|
183
|
+
const symbolCommandDescriptionToLabel = {
|
|
184
|
+
'keep symbol command': 'K',
|
|
185
|
+
'erase symbol command': 'E',
|
|
186
|
+
};
|
|
187
|
+
// Reserved characters in the encoded pattern string:
|
|
188
|
+
// '*' ASCII asterisk (U+002A) — per-cell ifOtherSymbol, matches any symbol
|
|
189
|
+
// on that tape. ASCII (not a fancier glyph like U+1F7B0) so it renders
|
|
190
|
+
// in every Mermaid environment and every monospace font. A literal `*`
|
|
191
|
+
// in the alphabet is unambiguous from the marker because it's quoted
|
|
192
|
+
// (`'*'`).
|
|
193
|
+
// 'B' the tape's blank symbol shorthand (in read patterns). A literal `B`
|
|
194
|
+
// in the alphabet is unambiguous from the marker because it's quoted
|
|
195
|
+
// (`'B'`).
|
|
196
|
+
// ',' separates per-tape cells inside one pattern
|
|
197
|
+
// '|' separates alternative patterns
|
|
198
|
+
// "'" surrounds a literal alphabet symbol — e.g. `'0'` for literal `0`,
|
|
199
|
+
// `'X'` for literal `X`. The quoting is what visually separates literal
|
|
200
|
+
// symbols from the convention markers `*` / `B` and from the write
|
|
201
|
+
// commands `K` / `E`.
|
|
202
|
+
// '\\' escape prefix — to represent any of '*', 'B', ',', '|', "'", or '\\'
|
|
203
|
+
// as a *literal* alphabet symbol *inside* the quotes (e.g. `'\''` for
|
|
204
|
+
// a literal apostrophe).
|
|
205
|
+
const IF_OTHER_MARKER = '*';
|
|
206
|
+
const BLANK_MARKER = 'B';
|
|
207
|
+
function escapeAlphabetSymbol(s) {
|
|
208
|
+
return s
|
|
209
|
+
.replace(/\\/g, '\\\\')
|
|
210
|
+
.replace(/'/g, "\\'");
|
|
211
|
+
}
|
|
212
|
+
function decodePatternDescription(description, alphabets) {
|
|
213
|
+
if (!description) {
|
|
214
|
+
return '?';
|
|
215
|
+
}
|
|
216
|
+
if (description === 'other symbol') {
|
|
217
|
+
return IF_OTHER_MARKER;
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
const patternList = JSON.parse(description);
|
|
221
|
+
return patternList
|
|
222
|
+
.map((pattern) => pattern
|
|
223
|
+
.map((s, tapeIx) => {
|
|
224
|
+
if (s === null) {
|
|
225
|
+
return IF_OTHER_MARKER;
|
|
226
|
+
}
|
|
227
|
+
if (s === alphabets[tapeIx]?.[0]) {
|
|
228
|
+
return BLANK_MARKER;
|
|
229
|
+
}
|
|
230
|
+
return `'${escapeAlphabetSymbol(s)}'`;
|
|
231
|
+
})
|
|
232
|
+
.join(','))
|
|
233
|
+
.join('|');
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
return description;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
function decodeMovement(description) {
|
|
240
|
+
if (!description) {
|
|
241
|
+
return '?';
|
|
242
|
+
}
|
|
243
|
+
return movementDescriptionToLabel[description] ?? description;
|
|
244
|
+
}
|
|
245
|
+
function splitUnescaped(s, sep) {
|
|
246
|
+
const parts = [];
|
|
247
|
+
let current = '';
|
|
248
|
+
let i = 0;
|
|
249
|
+
while (i < s.length) {
|
|
250
|
+
if (s[i] === '\\' && i + 1 < s.length) {
|
|
251
|
+
current += s[i + 1];
|
|
252
|
+
i += 2;
|
|
253
|
+
}
|
|
254
|
+
else if (s[i] === sep) {
|
|
255
|
+
parts.push(current);
|
|
256
|
+
current = '';
|
|
257
|
+
i += 1;
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
current += s[i];
|
|
261
|
+
i += 1;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
parts.push(current);
|
|
265
|
+
return parts;
|
|
266
|
+
}
|
|
267
|
+
function parsePatternString(s, alphabets) {
|
|
268
|
+
if (s === IF_OTHER_MARKER) {
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
const alternatives = splitUnescaped(s, '|');
|
|
272
|
+
return alternatives.map((alt) => {
|
|
273
|
+
const cells = splitUnescaped(alt, ',');
|
|
274
|
+
return cells.map((cell, tapeIx) => {
|
|
275
|
+
if (cell === IF_OTHER_MARKER) {
|
|
276
|
+
return null;
|
|
277
|
+
}
|
|
278
|
+
if (cell === BLANK_MARKER) {
|
|
279
|
+
return alphabets[tapeIx]?.[0] ?? cell;
|
|
280
|
+
}
|
|
281
|
+
// Literal alphabet symbols are wrapped in single quotes by
|
|
282
|
+
// `decodePatternDescription` — strip them on the way back.
|
|
283
|
+
if (cell.length >= 2 && cell.startsWith("'") && cell.endsWith("'")) {
|
|
284
|
+
return cell.slice(1, -1);
|
|
285
|
+
}
|
|
286
|
+
return cell;
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
const movementLabelToSymbol = {
|
|
291
|
+
L: movements.left,
|
|
292
|
+
R: movements.right,
|
|
293
|
+
S: movements.stay,
|
|
294
|
+
};
|
|
295
|
+
function parseMovementLabel(label) {
|
|
296
|
+
const m = movementLabelToSymbol[label];
|
|
297
|
+
if (!m) {
|
|
298
|
+
throw new Error(`unknown movement label: ${label}`);
|
|
299
|
+
}
|
|
300
|
+
return m;
|
|
301
|
+
}
|
|
302
|
+
function parseWriteSymbolLabel(label) {
|
|
303
|
+
if (label === 'K') {
|
|
304
|
+
return symbolCommands.keep;
|
|
305
|
+
}
|
|
306
|
+
if (label === 'E') {
|
|
307
|
+
return symbolCommands.erase;
|
|
308
|
+
}
|
|
309
|
+
// Literal alphabet symbols are wrapped in single quotes by
|
|
310
|
+
// `decodeWriteSymbol` — strip them on the way back.
|
|
311
|
+
if (label.length >= 2 && label.startsWith("'") && label.endsWith("'")) {
|
|
312
|
+
return label.slice(1, -1);
|
|
313
|
+
}
|
|
314
|
+
return label;
|
|
315
|
+
}
|
|
316
|
+
function decodeWriteSymbol(symbol) {
|
|
317
|
+
if (typeof symbol === 'symbol') {
|
|
318
|
+
const description = symbol.description ?? '?';
|
|
319
|
+
return symbolCommandDescriptionToLabel[description] ?? description;
|
|
320
|
+
}
|
|
321
|
+
return `'${symbol}'`;
|
|
322
|
+
}
|
|
323
|
+
// Format converters (toMermaid / fromMermaid) live in ./graphFormats.
|
|
324
|
+
|
|
178
325
|
var __classPrivateFieldSet$4 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
179
326
|
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
180
327
|
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
@@ -531,152 +678,512 @@ _TapeBlock_generateSymbolHint = { value: (patternList) => JSON.stringify(pattern
|
|
|
531
678
|
.map((pattern) => pattern
|
|
532
679
|
.map((symbol) => (symbol === ifOtherSymbol ? null : symbol)))) };
|
|
533
680
|
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
//
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
681
|
+
// Graph serialization/reconstruction for State graphs. Extracted from
|
|
682
|
+
// `classes/State.ts` (#180) so the State class stays focused on the runtime
|
|
683
|
+
// machinery (transitions, debug, halt-stack composition). Sibling-module
|
|
684
|
+
// private access to State's internals goes through the `STATE_INTERNAL`
|
|
685
|
+
// Symbol re-exported from State.ts — see the @internal JSDoc there.
|
|
686
|
+
//
|
|
687
|
+
// Public surface is preserved: `State.toGraph` and `State.fromGraph` static
|
|
688
|
+
// methods continue to exist as thin delegates to the functions in this
|
|
689
|
+
// module. New consumers (e.g. #195's planned `collectStates`) will live
|
|
690
|
+
// here too and share the BFS-walk shape with `toGraph`.
|
|
691
|
+
/**
|
|
692
|
+
* Walks the reachable graph from `initialState` and returns a serializable
|
|
693
|
+
* `Graph`. The walk is a BFS that visits each State exactly once (keyed by
|
|
694
|
+
* the State's internal id) and emits one `GraphNode` per State plus
|
|
695
|
+
* synthetic halt-marker nodes per callable-subtree frame.
|
|
696
|
+
*
|
|
697
|
+
* Round-trips losslessly with `fromGraph` in the sense that running the
|
|
698
|
+
* rebuilt machine on the same input produces the same output — but State
|
|
699
|
+
* instance identities are NOT preserved across the cycle.
|
|
700
|
+
*
|
|
701
|
+
* See `classes/State.ts` for the runtime model these graph nodes describe;
|
|
702
|
+
* see `utilities/graphFormats.ts` for the Mermaid-flavored serialization
|
|
703
|
+
* built on top of `Graph`.
|
|
704
|
+
*/
|
|
705
|
+
function toGraph(initialState, tapeBlock) {
|
|
706
|
+
const nodes = {};
|
|
707
|
+
const alphabets = tapeBlock.alphabets.map((alphabet) => alphabet.symbols);
|
|
708
|
+
// Pass 1: BFS-discover all reachable States; emit one GraphNode per State
|
|
709
|
+
// (wrapper or bare/regular). Wrappers and bares are separate nodes.
|
|
710
|
+
const visited = new Set();
|
|
711
|
+
const queue = [initialState];
|
|
712
|
+
const bareIds = new Set(); // ids referenced as a wrapper's bareStateId
|
|
713
|
+
while (queue.length > 0) {
|
|
714
|
+
const state = queue.shift();
|
|
715
|
+
const stateInternal = state[STATE_INTERNAL]();
|
|
716
|
+
if (visited.has(stateInternal.id)) {
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
visited.add(stateInternal.id);
|
|
720
|
+
if (state.isHalt) {
|
|
721
|
+
if (!(0 in nodes)) {
|
|
722
|
+
nodes[0] = {
|
|
723
|
+
id: 0,
|
|
724
|
+
name: stateInternal.name,
|
|
725
|
+
isHalt: true,
|
|
726
|
+
isHaltMarker: false,
|
|
727
|
+
isWrapper: false,
|
|
728
|
+
bareStateId: null,
|
|
729
|
+
frameId: null,
|
|
730
|
+
transitions: [],
|
|
731
|
+
overriddenHaltStateId: null,
|
|
732
|
+
tags: [...stateInternal.tags],
|
|
733
|
+
};
|
|
582
734
|
}
|
|
583
|
-
|
|
584
|
-
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
// Wrapper? Emit wrapper node + queue bare and override target.
|
|
738
|
+
if (stateInternal.overriddenHaltState !== null && stateInternal.bareState !== null) {
|
|
739
|
+
const bareState = stateInternal.bareState;
|
|
740
|
+
const overrideTarget = stateInternal.overriddenHaltState;
|
|
741
|
+
const bareInternal = bareState[STATE_INTERNAL]();
|
|
742
|
+
const overrideInternal = overrideTarget[STATE_INTERNAL]();
|
|
743
|
+
nodes[stateInternal.id] = {
|
|
744
|
+
id: stateInternal.id,
|
|
745
|
+
name: stateInternal.name, // composite name like "A(target)"
|
|
746
|
+
isHalt: false,
|
|
747
|
+
isHaltMarker: false,
|
|
748
|
+
isWrapper: true,
|
|
749
|
+
bareStateId: bareInternal.id,
|
|
750
|
+
frameId: null,
|
|
751
|
+
transitions: [],
|
|
752
|
+
overriddenHaltStateId: overrideInternal.id,
|
|
753
|
+
tags: [...stateInternal.tags],
|
|
754
|
+
};
|
|
755
|
+
bareIds.add(bareInternal.id);
|
|
756
|
+
queue.push(bareState);
|
|
757
|
+
queue.push(overrideTarget);
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
// Regular (or bare) state — build node with transitions.
|
|
761
|
+
const node = {
|
|
762
|
+
id: stateInternal.id,
|
|
763
|
+
name: stateInternal.name,
|
|
764
|
+
isHalt: false,
|
|
765
|
+
isHaltMarker: false,
|
|
766
|
+
isWrapper: false,
|
|
767
|
+
bareStateId: null,
|
|
768
|
+
frameId: null,
|
|
769
|
+
transitions: [],
|
|
770
|
+
overriddenHaltStateId: null,
|
|
771
|
+
tags: [...stateInternal.tags],
|
|
772
|
+
};
|
|
773
|
+
nodes[stateInternal.id] = node;
|
|
774
|
+
let patternIx = 0;
|
|
775
|
+
for (const [sym, { command, nextState }] of stateInternal.symbolToDataMap) {
|
|
776
|
+
let target;
|
|
777
|
+
try {
|
|
778
|
+
target = nextState instanceof State ? nextState : nextState.ref;
|
|
585
779
|
}
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
780
|
+
catch {
|
|
781
|
+
patternIx += 1;
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
const targetInternal = target[STATE_INTERNAL]();
|
|
785
|
+
node.transitions.push({
|
|
786
|
+
pattern: decodePatternDescription(sym.description, alphabets),
|
|
787
|
+
command: command.tapesCommands.map((tc) => ({
|
|
788
|
+
symbol: decodeWriteSymbol(tc.symbol),
|
|
789
|
+
movement: decodeMovement(tc.movement.description),
|
|
790
|
+
})),
|
|
791
|
+
nextStateId: targetInternal.id,
|
|
792
|
+
id: `${stateInternal.id}-${patternIx}`,
|
|
793
|
+
});
|
|
794
|
+
queue.push(target);
|
|
795
|
+
patternIx += 1;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
// Always emit real halt as a sentinel, even if no transition targets it.
|
|
799
|
+
// It anchors the `subtree -. halt .-> s0` frame-level arrow whenever a
|
|
800
|
+
// frame demand-emits one, and it's the canonical machine-halt singleton.
|
|
801
|
+
if (!(0 in nodes)) {
|
|
802
|
+
nodes[0] = {
|
|
803
|
+
id: 0,
|
|
804
|
+
name: 'halt',
|
|
805
|
+
isHalt: true,
|
|
806
|
+
isHaltMarker: false,
|
|
807
|
+
isWrapper: false,
|
|
808
|
+
bareStateId: null,
|
|
809
|
+
frameId: null,
|
|
810
|
+
transitions: [],
|
|
811
|
+
overriddenHaltStateId: null,
|
|
812
|
+
tags: [...haltState[STATE_INTERNAL]().tags],
|
|
813
|
+
};
|
|
590
814
|
}
|
|
591
|
-
|
|
592
|
-
|
|
815
|
+
// Pass 2: For each bare, compute its forward-reachable set (following
|
|
816
|
+
// transitions; stopping at halt and at wrappers — both are frame
|
|
817
|
+
// boundaries).
|
|
818
|
+
const computeReach = (startId) => {
|
|
819
|
+
const reach = new Set();
|
|
820
|
+
const stack = [startId];
|
|
821
|
+
while (stack.length > 0) {
|
|
822
|
+
const id = stack.pop();
|
|
823
|
+
if (reach.has(id)) {
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
const node = nodes[id];
|
|
827
|
+
// `nodes[id]` is always populated for `id` that the BFS reached, so
|
|
828
|
+
// a defensive `!node` check would be dead. `isHalt` / `isWrapper`
|
|
829
|
+
// are real boundaries — both stop reach-set expansion.
|
|
830
|
+
if (node.isHalt || node.isWrapper) {
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
reach.add(id);
|
|
834
|
+
for (const t of node.transitions) {
|
|
835
|
+
const target = nodes[t.nextStateId];
|
|
836
|
+
if (!target || target.isHalt || target.isWrapper) {
|
|
837
|
+
continue;
|
|
838
|
+
}
|
|
839
|
+
stack.push(t.nextStateId);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
return reach;
|
|
843
|
+
};
|
|
844
|
+
const reachByBare = new Map();
|
|
845
|
+
for (const bareId of bareIds) {
|
|
846
|
+
reachByBare.set(bareId, computeReach(bareId));
|
|
847
|
+
}
|
|
848
|
+
// Pass 3: Union-find on bare overlaps. Two bares merge if their reach
|
|
849
|
+
// sets share any state. Canonical representative = smallest bare-id in
|
|
850
|
+
// the component.
|
|
851
|
+
const ufParent = new Map();
|
|
852
|
+
// Note: no path compression. The union policy below ("smaller id always
|
|
853
|
+
// becomes root") keeps the tree flat — every union targets bares[0] as
|
|
854
|
+
// the root, so any node's parent IS the root. Walking up never exceeds
|
|
855
|
+
// one step. Path compression would be dead code under this invariant.
|
|
856
|
+
const ufFind = (id) => {
|
|
857
|
+
if (!ufParent.has(id)) {
|
|
858
|
+
ufParent.set(id, id);
|
|
859
|
+
}
|
|
860
|
+
let root = id;
|
|
861
|
+
while (ufParent.get(root) !== root) {
|
|
862
|
+
root = ufParent.get(root);
|
|
863
|
+
}
|
|
864
|
+
return root;
|
|
865
|
+
};
|
|
866
|
+
const ufUnion = (a, b) => {
|
|
867
|
+
const ra = ufFind(a);
|
|
868
|
+
const rb = ufFind(b);
|
|
869
|
+
if (ra === rb)
|
|
870
|
+
return;
|
|
871
|
+
if (ra < rb) {
|
|
872
|
+
ufParent.set(rb, ra);
|
|
873
|
+
}
|
|
874
|
+
else {
|
|
875
|
+
ufParent.set(ra, rb);
|
|
876
|
+
}
|
|
877
|
+
};
|
|
878
|
+
for (const bareId of bareIds) {
|
|
879
|
+
ufFind(bareId);
|
|
880
|
+
}
|
|
881
|
+
// For each state, collect the bares that reach it; union all bares that
|
|
882
|
+
// share a state.
|
|
883
|
+
const stateToReachingBares = new Map();
|
|
884
|
+
for (const [bareId, reachSet] of reachByBare) {
|
|
885
|
+
for (const stateId of reachSet) {
|
|
886
|
+
let bares = stateToReachingBares.get(stateId);
|
|
887
|
+
if (!bares) {
|
|
888
|
+
bares = [];
|
|
889
|
+
stateToReachingBares.set(stateId, bares);
|
|
890
|
+
}
|
|
891
|
+
bares.push(bareId);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
for (const bares of stateToReachingBares.values()) {
|
|
895
|
+
for (let i = 1; i < bares.length; i += 1) {
|
|
896
|
+
ufUnion(bares[0], bares[i]);
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
// Assign frameId to each in-reach state.
|
|
900
|
+
const frameIds = new Set();
|
|
901
|
+
for (const [stateId, bares] of stateToReachingBares) {
|
|
902
|
+
const frameId = ufFind(bares[0]);
|
|
903
|
+
nodes[stateId].frameId = frameId;
|
|
904
|
+
frameIds.add(frameId);
|
|
905
|
+
}
|
|
906
|
+
// Pass 4: Retarget halt-bound transitions for in-frame states to the
|
|
907
|
+
// frame's halt marker. Out-of-frame states (top-level dispatcher, override
|
|
908
|
+
// targets, etc.) keep their halt-bound transitions pointing at real halt.
|
|
909
|
+
for (const node of Object.values(nodes)) {
|
|
910
|
+
if (node.frameId === null) {
|
|
911
|
+
continue;
|
|
912
|
+
}
|
|
913
|
+
const haltMarkerId = -node.frameId;
|
|
914
|
+
for (const t of node.transitions) {
|
|
915
|
+
const target = nodes[t.nextStateId];
|
|
916
|
+
if (target && target.isHalt && !target.isHaltMarker) {
|
|
917
|
+
t.nextStateId = haltMarkerId;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
593
920
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
921
|
+
// Pass 5: Emit one halt marker per frame.
|
|
922
|
+
for (const frameId of frameIds) {
|
|
923
|
+
const haltMarkerId = -frameId;
|
|
924
|
+
nodes[haltMarkerId] = {
|
|
925
|
+
id: haltMarkerId,
|
|
926
|
+
name: 'halt',
|
|
927
|
+
isHalt: true,
|
|
928
|
+
isHaltMarker: true,
|
|
929
|
+
isWrapper: false,
|
|
930
|
+
bareStateId: null,
|
|
931
|
+
frameId,
|
|
932
|
+
transitions: [],
|
|
933
|
+
overriddenHaltStateId: null,
|
|
934
|
+
tags: [],
|
|
935
|
+
};
|
|
598
936
|
}
|
|
599
|
-
return
|
|
937
|
+
return { initialId: initialState[STATE_INTERNAL]().id, alphabets, nodes };
|
|
600
938
|
}
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
939
|
+
/**
|
|
940
|
+
* Inverse of `toGraph`: rebuilds a State graph (and a fresh TapeBlock with
|
|
941
|
+
* the graph's alphabets) from a serialized Graph. Round-trips with `toGraph`
|
|
942
|
+
* in the sense that running the rebuilt machine on the same input gives the
|
|
943
|
+
* same output, but the rebuilt State instances have *new* internal IDs.
|
|
944
|
+
*
|
|
945
|
+
* Under the v7 callable-subtree model (#174), graph nodes split into:
|
|
946
|
+
* - Wrapper nodes (`isWrapper: true`, no transitions) — reconstructed via
|
|
947
|
+
* `bareStates[bareStateId].withOverriddenHaltState(finalStates[overriddenHaltStateId])`.
|
|
948
|
+
* - Bare/regular nodes — constructed as normal States with transitions.
|
|
949
|
+
* - Halt + halt-marker nodes — collapse to the singleton `haltState`.
|
|
950
|
+
*/
|
|
951
|
+
function fromGraph(graph) {
|
|
952
|
+
const alphabetObjs = graph.alphabets.map((syms) => new Alphabet(syms));
|
|
953
|
+
const tapeBlock = TapeBlock.fromAlphabets(alphabetObjs);
|
|
954
|
+
const ids = Object.keys(graph.nodes).map(Number);
|
|
955
|
+
// Pass 1: pre-create a Reference for each non-halt non-halt-marker node
|
|
956
|
+
// (both wrappers and regulars). Halt and halt-marker nodes collapse to the
|
|
957
|
+
// singleton `haltState` and need no ref.
|
|
958
|
+
const refs = {};
|
|
959
|
+
for (const nodeId of ids) {
|
|
960
|
+
const node = graph.nodes[nodeId];
|
|
961
|
+
if (!node.isHalt) {
|
|
962
|
+
refs[nodeId] = new Reference();
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
// Convert a parsed pattern back to the symbol key the State expects.
|
|
966
|
+
const patternToKey = (parsed) => {
|
|
967
|
+
if (parsed === null) {
|
|
968
|
+
return ifOtherSymbol;
|
|
969
|
+
}
|
|
970
|
+
const flat = [];
|
|
971
|
+
for (const row of parsed) {
|
|
972
|
+
for (const cell of row) {
|
|
973
|
+
flat.push(cell === null ? ifOtherSymbol : cell);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return tapeBlock.symbol(flat);
|
|
977
|
+
};
|
|
978
|
+
// Pass 2: build a State for each non-wrapper non-halt non-halt-marker
|
|
979
|
+
// node. Transitions point at refs so cycles work; haltState (and halt
|
|
980
|
+
// markers, which collapse to haltState) are used directly.
|
|
981
|
+
const bareStates = {};
|
|
982
|
+
for (const nodeId of ids) {
|
|
983
|
+
const node = graph.nodes[nodeId];
|
|
984
|
+
if (node.isHalt || node.isWrapper) {
|
|
985
|
+
continue;
|
|
609
986
|
}
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
987
|
+
const stateDefinition = {};
|
|
988
|
+
for (const t of node.transitions) {
|
|
989
|
+
const key = patternToKey(parsePatternString(t.pattern, graph.alphabets));
|
|
990
|
+
const target = graph.nodes[t.nextStateId];
|
|
991
|
+
const nextState = !target || target.isHalt
|
|
992
|
+
? haltState
|
|
993
|
+
: refs[t.nextStateId];
|
|
994
|
+
stateDefinition[key] = {
|
|
995
|
+
command: t.command.map((c) => ({
|
|
996
|
+
symbol: parseWriteSymbolLabel(c.symbol),
|
|
997
|
+
movement: parseMovementLabel(c.movement),
|
|
998
|
+
})),
|
|
999
|
+
nextState,
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
// Graph-sourced names may contain `(` and `)` (composite wrapper names —
|
|
1003
|
+
// although wrappers go through a separate path below, defensive
|
|
1004
|
+
// construction here keeps the bypass uniform). Construct without a name
|
|
1005
|
+
// and assign `name` directly through the internal accessor's setter to
|
|
1006
|
+
// skip the constructor's user-facing name validation.
|
|
1007
|
+
const bare = new State(stateDefinition);
|
|
1008
|
+
bare[STATE_INTERNAL]().name = node.name;
|
|
1009
|
+
if (node.tags.length > 0) {
|
|
1010
|
+
bare.tag(...node.tags);
|
|
1011
|
+
}
|
|
1012
|
+
bareStates[nodeId] = bare;
|
|
1013
|
+
}
|
|
1014
|
+
// Pass 3: resolve every node to its final State (memoized + cycle-safe).
|
|
1015
|
+
// Wrappers compose lazily via `withOverriddenHaltState` once their bare
|
|
1016
|
+
// and override are resolved.
|
|
1017
|
+
const finalStates = {};
|
|
1018
|
+
const inProgress = new Set();
|
|
1019
|
+
const getFinal = (nodeId) => {
|
|
1020
|
+
if (finalStates[nodeId]) {
|
|
1021
|
+
return finalStates[nodeId];
|
|
1022
|
+
}
|
|
1023
|
+
const node = graph.nodes[nodeId];
|
|
1024
|
+
if (!node || node.isHalt) {
|
|
1025
|
+
finalStates[nodeId] = haltState;
|
|
1026
|
+
return haltState;
|
|
1027
|
+
}
|
|
1028
|
+
if (inProgress.has(nodeId)) {
|
|
1029
|
+
throw new Error(`override-halt cycle at state #${nodeId}`);
|
|
1030
|
+
}
|
|
1031
|
+
inProgress.add(nodeId);
|
|
1032
|
+
let state;
|
|
1033
|
+
if (node.isWrapper) {
|
|
1034
|
+
const bare = getFinal(node.bareStateId);
|
|
1035
|
+
const override = getFinal(node.overriddenHaltStateId);
|
|
1036
|
+
state = bare.withOverriddenHaltState(override);
|
|
1037
|
+
// Apply wrapper-scoped tags (#186). Tags don't leak across wrappers
|
|
1038
|
+
// sharing a bare — the wrapper instance owns its own tag set, and
|
|
1039
|
+
// engine #175 memoization returns the same instance for the same
|
|
1040
|
+
// (bare, override) pair, so this is idempotent across rebuilds.
|
|
1041
|
+
if (node.tags.length > 0) {
|
|
1042
|
+
state.tag(...node.tags);
|
|
1043
|
+
}
|
|
614
1044
|
}
|
|
615
1045
|
else {
|
|
616
|
-
|
|
617
|
-
i += 1;
|
|
1046
|
+
state = bareStates[nodeId];
|
|
618
1047
|
}
|
|
1048
|
+
inProgress.delete(nodeId);
|
|
1049
|
+
finalStates[nodeId] = state;
|
|
1050
|
+
return state;
|
|
1051
|
+
};
|
|
1052
|
+
for (const nodeId of ids) {
|
|
1053
|
+
getFinal(nodeId);
|
|
619
1054
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
1055
|
+
// Pass 4: bind each ref to the resolved final State so cross-node
|
|
1056
|
+
// transitions land on the right instance.
|
|
1057
|
+
for (const nodeId of ids) {
|
|
1058
|
+
if (!graph.nodes[nodeId].isHalt) {
|
|
1059
|
+
refs[nodeId].bind(finalStates[nodeId]);
|
|
1060
|
+
}
|
|
626
1061
|
}
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
1062
|
+
return {
|
|
1063
|
+
start: finalStates[graph.initialId],
|
|
1064
|
+
tapeBlock,
|
|
1065
|
+
states: finalStates,
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* Returns a `Map<number, {state, transitionSymbols}>` keyed by engine
|
|
1070
|
+
* `GraphNode.id`, giving downstream tooling direct access to the `State`
|
|
1071
|
+
* instance + per-pattern Symbol references for breakpoint setup (#195).
|
|
1072
|
+
*
|
|
1073
|
+
* **Positional alignment contract.** For any `GraphTransition` whose id
|
|
1074
|
+
* is `${N}-${K}`, `result.get(N)!.transitionSymbols[K]` is the Symbol
|
|
1075
|
+
* the transition fires on (reference equality, not structural). The K-th
|
|
1076
|
+
* entry is the K-th key from the source State's `#symbolToDataMap` in
|
|
1077
|
+
* insertion order, including `ifOtherSymbol` when the user wrote one.
|
|
1078
|
+
* Consumers filtering the catch-all path identity-compare against the
|
|
1079
|
+
* engine-exported `ifOtherSymbol`.
|
|
1080
|
+
*
|
|
1081
|
+
* **Unbound-`Reference` slots.** `toGraph` increments `patternIx` even
|
|
1082
|
+
* when a transition's `nextState` is an unresolved `Reference` (it
|
|
1083
|
+
* `continue`s without pushing the GraphTransition). In that case
|
|
1084
|
+
* `transitionSymbols[K]` is still set to the K-th Map key, but no
|
|
1085
|
+
* `Graph.nodes[N].transitions` entry exists with id `${N}-${K}`. Sparse
|
|
1086
|
+
* on the Graph side, dense on the `transitionSymbols` side — same
|
|
1087
|
+
* indexing.
|
|
1088
|
+
*
|
|
1089
|
+
* **Coverage.** Map keys are the State-backed subset of `graph.nodes`:
|
|
1090
|
+
* regulars + bares + wrappers + the halt singleton (id `0`). Synthetic
|
|
1091
|
+
* halt markers (id `-frameId`) are excluded — they all reach the same
|
|
1092
|
+
* `haltState` object at runtime, and the named consumer
|
|
1093
|
+
* ([machines-demo#37](https://github.com/mellonis/machines-demo/issues/37))
|
|
1094
|
+
* surfaces halt-pause via a separate UI control, not via clicks on
|
|
1095
|
+
* halt glyphs. If a future consumer needs uniform-by-id lookup, the
|
|
1096
|
+
* helper can be extended additively.
|
|
1097
|
+
*
|
|
1098
|
+
* **Halt-singleton warning.** `result.get(0)!.state === haltState` — the
|
|
1099
|
+
* process-wide halt. Toggling `.debug` on that entry affects every
|
|
1100
|
+
* machine in the runtime, not just the one this map was built from.
|
|
1101
|
+
*/
|
|
1102
|
+
function collectStates(initialState, tapeBlock) {
|
|
1103
|
+
// Anchor on toGraph's authoritative id set — it knows the canonical
|
|
1104
|
+
// ordering of wrapper/bare/regular emission and which nodes are
|
|
1105
|
+
// synthetic halt markers we have to skip. Building our own BFS would
|
|
1106
|
+
// duplicate that logic; reusing the Graph guarantees collectStates'
|
|
1107
|
+
// id keys never drift from toGraph's GraphTransition ids.
|
|
1108
|
+
const graph = toGraph(initialState, tapeBlock);
|
|
1109
|
+
// Walk the State graph to associate each State instance with its
|
|
1110
|
+
// engine id. The shape mirrors toGraph's Pass 1 — visit by id, branch
|
|
1111
|
+
// on halt / wrapper / regular — but only collects the (id → State)
|
|
1112
|
+
// mapping. Lighter than re-running the union-find passes; no
|
|
1113
|
+
// GraphNode construction.
|
|
1114
|
+
const stateById = new Map();
|
|
1115
|
+
const visited = new Set();
|
|
1116
|
+
const queue = [initialState];
|
|
1117
|
+
while (queue.length > 0) {
|
|
1118
|
+
const state = queue.shift();
|
|
1119
|
+
const internal = state[STATE_INTERNAL]();
|
|
1120
|
+
if (visited.has(internal.id))
|
|
1121
|
+
continue;
|
|
1122
|
+
visited.add(internal.id);
|
|
1123
|
+
stateById.set(internal.id, state);
|
|
1124
|
+
if (state.isHalt)
|
|
1125
|
+
continue;
|
|
1126
|
+
if (internal.bareState !== null && internal.overriddenHaltState !== null) {
|
|
1127
|
+
queue.push(internal.bareState);
|
|
1128
|
+
queue.push(internal.overriddenHaltState);
|
|
1129
|
+
continue;
|
|
1130
|
+
}
|
|
1131
|
+
for (const { nextState } of internal.symbolToDataMap.values()) {
|
|
1132
|
+
let target;
|
|
1133
|
+
try {
|
|
1134
|
+
target = nextState instanceof State ? nextState : nextState.ref;
|
|
636
1135
|
}
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
if (cell.length >= 2 && cell.startsWith("'") && cell.endsWith("'")) {
|
|
640
|
-
return cell.slice(1, -1);
|
|
1136
|
+
catch {
|
|
1137
|
+
continue; // unbound Reference — skip silently, matches toGraph
|
|
641
1138
|
}
|
|
642
|
-
|
|
643
|
-
}
|
|
644
|
-
});
|
|
645
|
-
}
|
|
646
|
-
const movementLabelToSymbol = {
|
|
647
|
-
L: movements.left,
|
|
648
|
-
R: movements.right,
|
|
649
|
-
S: movements.stay,
|
|
650
|
-
};
|
|
651
|
-
function parseMovementLabel(label) {
|
|
652
|
-
const m = movementLabelToSymbol[label];
|
|
653
|
-
if (!m) {
|
|
654
|
-
throw new Error(`unknown movement label: ${label}`);
|
|
655
|
-
}
|
|
656
|
-
return m;
|
|
657
|
-
}
|
|
658
|
-
function parseWriteSymbolLabel(label) {
|
|
659
|
-
if (label === 'K') {
|
|
660
|
-
return symbolCommands.keep;
|
|
661
|
-
}
|
|
662
|
-
if (label === 'E') {
|
|
663
|
-
return symbolCommands.erase;
|
|
664
|
-
}
|
|
665
|
-
// Literal alphabet symbols are wrapped in single quotes by
|
|
666
|
-
// `decodeWriteSymbol` — strip them on the way back.
|
|
667
|
-
if (label.length >= 2 && label.startsWith("'") && label.endsWith("'")) {
|
|
668
|
-
return label.slice(1, -1);
|
|
1139
|
+
queue.push(target);
|
|
1140
|
+
}
|
|
669
1141
|
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
1142
|
+
// Build the result by iterating graph.nodes — the authoritative id set
|
|
1143
|
+
// minus halt markers — and dispatching on node kind. The halt singleton
|
|
1144
|
+
// entry's `state` reads from `stateById` (the BFS visited haltState if
|
|
1145
|
+
// any path reached it) but falls back to the module-level singleton
|
|
1146
|
+
// for graphs whose only halt presence is the always-emitted sentinel.
|
|
1147
|
+
const result = new Map();
|
|
1148
|
+
for (const idStr of Object.keys(graph.nodes)) {
|
|
1149
|
+
const id = Number(idStr);
|
|
1150
|
+
const node = graph.nodes[id];
|
|
1151
|
+
if (node.isHaltMarker)
|
|
1152
|
+
continue; // synthetic; collapses to haltState at id 0
|
|
1153
|
+
if (node.isHalt) {
|
|
1154
|
+
// The real halt — always the engine-wide singleton. Prefer the
|
|
1155
|
+
// BFS-visited instance for identity-equality with whatever the
|
|
1156
|
+
// caller has; fall back to the module singleton when the BFS
|
|
1157
|
+
// didn't reach haltState (toGraph emits id 0 unconditionally).
|
|
1158
|
+
result.set(id, {
|
|
1159
|
+
state: stateById.get(0) ?? haltState,
|
|
1160
|
+
transitionSymbols: [],
|
|
1161
|
+
});
|
|
1162
|
+
continue;
|
|
1163
|
+
}
|
|
1164
|
+
if (node.isWrapper) {
|
|
1165
|
+
result.set(id, {
|
|
1166
|
+
state: stateById.get(id),
|
|
1167
|
+
transitionSymbols: [],
|
|
1168
|
+
});
|
|
1169
|
+
continue;
|
|
1170
|
+
}
|
|
1171
|
+
// Regular or bare State — enumerate `#symbolToDataMap.keys()` for
|
|
1172
|
+
// the patternIx alignment. The K-th key is the Symbol that
|
|
1173
|
+
// `${id}-${K}` GraphTransition fires on (positional contract).
|
|
1174
|
+
const state = stateById.get(id);
|
|
1175
|
+
const transitionSymbols = [...state[STATE_INTERNAL]().symbolToDataMap.keys()];
|
|
1176
|
+
result.set(id, { state, transitionSymbols });
|
|
676
1177
|
}
|
|
677
|
-
return
|
|
1178
|
+
return result;
|
|
678
1179
|
}
|
|
679
|
-
//
|
|
1180
|
+
// Note on the import cycle with `State.ts`: stateGraph.ts value-imports
|
|
1181
|
+
// `State`, `STATE_INTERNAL`, `haltState`, and `ifOtherSymbol`; State.ts
|
|
1182
|
+
// value-imports `toGraph` and `fromGraph` for its static-method delegates.
|
|
1183
|
+
// ESM resolves cycles via live bindings — both modules see each other's
|
|
1184
|
+
// exports as long as nothing at module-load reads a binding before its
|
|
1185
|
+
// source module finishes evaluating. All references here live inside
|
|
1186
|
+
// function bodies, so the cycle is safe.
|
|
680
1187
|
|
|
681
1188
|
var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
682
1189
|
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
@@ -694,6 +1201,28 @@ const ifOtherSymbol = Symbol('other symbol');
|
|
|
694
1201
|
// Module-private symbol used by DebugConfig setters to call State's validator
|
|
695
1202
|
// without exposing the validator on the public surface.
|
|
696
1203
|
const validateDebugFilter = Symbol('validateDebugFilter');
|
|
1204
|
+
/**
|
|
1205
|
+
* @internal
|
|
1206
|
+
*
|
|
1207
|
+
* Package-private accessor key for sibling modules in
|
|
1208
|
+
* `packages/machine/src` (e.g. `utilities/stateGraph.ts`, and the planned
|
|
1209
|
+
* `utilities/stateCollect.ts` for #195). Re-exported from this module so
|
|
1210
|
+
* sibling files can import it; intentionally NOT re-exported from the
|
|
1211
|
+
* package's public `index.ts`, so downstream consumers don't see it on
|
|
1212
|
+
* the supported surface.
|
|
1213
|
+
*
|
|
1214
|
+
* Calling `state[STATE_INTERNAL]()` returns a getter/setter view onto the
|
|
1215
|
+
* State's private fields. Reads are live (they close over `this`), so the
|
|
1216
|
+
* view stays in sync with subsequent mutations on the State. There's one
|
|
1217
|
+
* mutating setter on the view — `name` — used exclusively by
|
|
1218
|
+
* `fromGraph` to assign graph-sourced composite names (e.g. `A(target)`)
|
|
1219
|
+
* that the public name validator would reject; see the JSDoc on the
|
|
1220
|
+
* accessor itself.
|
|
1221
|
+
*
|
|
1222
|
+
* Designed in #180 with #195 in mind so its surface doesn't need to grow
|
|
1223
|
+
* when `collectStates` lands.
|
|
1224
|
+
*/
|
|
1225
|
+
const STATE_INTERNAL = Symbol('State.internal');
|
|
697
1226
|
class DebugConfig {
|
|
698
1227
|
constructor(ownerState, initial) {
|
|
699
1228
|
_DebugConfig_ownerState.set(this, void 0);
|
|
@@ -956,6 +1485,47 @@ class State {
|
|
|
956
1485
|
innerCache.set(overriddenHaltState, new WeakRef(state));
|
|
957
1486
|
return state;
|
|
958
1487
|
}
|
|
1488
|
+
/**
|
|
1489
|
+
* @internal
|
|
1490
|
+
*
|
|
1491
|
+
* Package-private getter/setter view onto this State's private fields,
|
|
1492
|
+
* for sibling modules in `packages/machine/src` (currently `stateGraph.ts`
|
|
1493
|
+
* for `toGraph` / `fromGraph`, and the planned `stateCollect.ts` for
|
|
1494
|
+
* #195's `collectStates`).
|
|
1495
|
+
*
|
|
1496
|
+
* Read access is live — the getters close over `this`, so the view
|
|
1497
|
+
* stays in sync with subsequent mutations on this State. There's a
|
|
1498
|
+
* single mutating setter on the view, `name`, which exists to let
|
|
1499
|
+
* `fromGraph` assign graph-sourced composite names (e.g. `A(target)`)
|
|
1500
|
+
* to freshly-constructed bare States. The constructor's name validator
|
|
1501
|
+
* rejects parens (reserved as wrapper-composition delimiters in
|
|
1502
|
+
* `withOverriddenHaltState`); the setter intentionally bypasses that
|
|
1503
|
+
* check because the same delimiters appear in legitimate wrapper-bare
|
|
1504
|
+
* names round-tripped through the graph.
|
|
1505
|
+
*
|
|
1506
|
+
* Returns a fresh view object on every call — cheap enough for the
|
|
1507
|
+
* BFS-once-per-build callers, and avoids holding a reference object on
|
|
1508
|
+
* every State instance. Keep this surface tight: callers should only
|
|
1509
|
+
* read what they need. Adding fields here is a deliberate decision —
|
|
1510
|
+
* each adds to the implicit contract sibling modules can rely on.
|
|
1511
|
+
*/
|
|
1512
|
+
[STATE_INTERNAL]() {
|
|
1513
|
+
// Aliasing `this` so the nested object-literal getters/setters below
|
|
1514
|
+
// can read/write the enclosing State's private fields — getters in an
|
|
1515
|
+
// object literal can't be arrow functions, so the standard arrow-
|
|
1516
|
+
// captures-`this` trick doesn't apply here.
|
|
1517
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
1518
|
+
const self = this;
|
|
1519
|
+
return {
|
|
1520
|
+
get id() { return __classPrivateFieldGet$1(self, _State_id, "f"); },
|
|
1521
|
+
get name() { return __classPrivateFieldGet$1(self, _State_name, "f"); },
|
|
1522
|
+
set name(v) { __classPrivateFieldSet$1(self, _State_name, v, "f"); },
|
|
1523
|
+
get bareState() { return __classPrivateFieldGet$1(self, _State_bareState, "f"); },
|
|
1524
|
+
get overriddenHaltState() { return __classPrivateFieldGet$1(self, _State_overriddenHaltState, "f"); },
|
|
1525
|
+
get symbolToDataMap() { return __classPrivateFieldGet$1(self, _State_symbolToDataMap, "f"); },
|
|
1526
|
+
get tags() { return __classPrivateFieldGet$1(self, _State_tags, "f"); },
|
|
1527
|
+
};
|
|
1528
|
+
}
|
|
959
1529
|
// Single-state introspection — no traversal, no tapeBlock required.
|
|
960
1530
|
// Returns id, name, halt-status, override-halt target, and the list of
|
|
961
1531
|
// transitions out of this state with decoded write/movement labels.
|
|
@@ -990,382 +1560,36 @@ class State {
|
|
|
990
1560
|
transitions,
|
|
991
1561
|
};
|
|
992
1562
|
}
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
// bare's GraphNode; `overriddenHaltStateId` points to the override
|
|
1000
|
-
// target's GraphNode.
|
|
1001
|
-
// - A bare node (`isWrapper: false`, regular shape) — the callable body.
|
|
1002
|
-
// Has the bare's transitions. Shared across all wrappers that wrap
|
|
1003
|
-
// this bare (no per-context duplication).
|
|
1004
|
-
//
|
|
1005
|
-
// Frames are computed via union-find on bare reachability: two bares whose
|
|
1006
|
-
// forward-reachable sets overlap merge into one frame. Each frame contains
|
|
1007
|
-
// its bares + body states + a single halt marker (id = `-frameId`). The
|
|
1008
|
-
// canonical `frameId` is the smallest bare-id in the component.
|
|
1009
|
-
//
|
|
1010
|
-
// Halt-bound transitions of any in-frame state are retargeted to the
|
|
1011
|
-
// frame's halt marker. The frame's `subtree -. return .-> wrapper` and
|
|
1012
|
-
// `subtree -. halt .-> s0` arrows are demand-emitted by `toMermaid` from
|
|
1013
|
-
// the frame structure; they're not stored as graph edges.
|
|
1563
|
+
/**
|
|
1564
|
+
* Walks the reachable State graph from `initialState` and returns a
|
|
1565
|
+
* serializable `Graph`. Thin delegate to `utilities/stateGraph.ts`'s
|
|
1566
|
+
* `toGraph` (extracted in #180); see that module for the BFS shape and
|
|
1567
|
+
* v7 callable-subtree emit semantics.
|
|
1568
|
+
*/
|
|
1014
1569
|
static toGraph(initialState, tapeBlock) {
|
|
1015
|
-
|
|
1016
|
-
const alphabets = tapeBlock.alphabets.map((alphabet) => alphabet.symbols);
|
|
1017
|
-
// Pass 1: BFS-discover all reachable States; emit one GraphNode per State
|
|
1018
|
-
// (wrapper or bare/regular). Wrappers and bares are separate nodes.
|
|
1019
|
-
const visited = new Set();
|
|
1020
|
-
const queue = [initialState];
|
|
1021
|
-
const bareIds = new Set(); // ids referenced as a wrapper's bareStateId
|
|
1022
|
-
while (queue.length > 0) {
|
|
1023
|
-
const state = queue.shift();
|
|
1024
|
-
if (visited.has(__classPrivateFieldGet$1(state, _State_id, "f"))) {
|
|
1025
|
-
continue;
|
|
1026
|
-
}
|
|
1027
|
-
visited.add(__classPrivateFieldGet$1(state, _State_id, "f"));
|
|
1028
|
-
if (state.isHalt) {
|
|
1029
|
-
if (!(0 in nodes)) {
|
|
1030
|
-
nodes[0] = {
|
|
1031
|
-
id: 0,
|
|
1032
|
-
name: __classPrivateFieldGet$1(state, _State_name, "f"),
|
|
1033
|
-
isHalt: true,
|
|
1034
|
-
isHaltMarker: false,
|
|
1035
|
-
isWrapper: false,
|
|
1036
|
-
bareStateId: null,
|
|
1037
|
-
frameId: null,
|
|
1038
|
-
transitions: [],
|
|
1039
|
-
overriddenHaltStateId: null,
|
|
1040
|
-
tags: [...__classPrivateFieldGet$1(state, _State_tags, "f")],
|
|
1041
|
-
};
|
|
1042
|
-
}
|
|
1043
|
-
continue;
|
|
1044
|
-
}
|
|
1045
|
-
// Wrapper? Emit wrapper node + queue bare and override target.
|
|
1046
|
-
if (__classPrivateFieldGet$1(state, _State_overriddenHaltState, "f") !== null && __classPrivateFieldGet$1(state, _State_bareState, "f") !== null) {
|
|
1047
|
-
const bareState = __classPrivateFieldGet$1(state, _State_bareState, "f");
|
|
1048
|
-
const overrideTarget = __classPrivateFieldGet$1(state, _State_overriddenHaltState, "f");
|
|
1049
|
-
nodes[__classPrivateFieldGet$1(state, _State_id, "f")] = {
|
|
1050
|
-
id: __classPrivateFieldGet$1(state, _State_id, "f"),
|
|
1051
|
-
name: __classPrivateFieldGet$1(state, _State_name, "f"), // composite name like "A(target)"
|
|
1052
|
-
isHalt: false,
|
|
1053
|
-
isHaltMarker: false,
|
|
1054
|
-
isWrapper: true,
|
|
1055
|
-
bareStateId: __classPrivateFieldGet$1(bareState, _State_id, "f"),
|
|
1056
|
-
frameId: null,
|
|
1057
|
-
transitions: [],
|
|
1058
|
-
overriddenHaltStateId: __classPrivateFieldGet$1(overrideTarget, _State_id, "f"),
|
|
1059
|
-
tags: [...__classPrivateFieldGet$1(state, _State_tags, "f")],
|
|
1060
|
-
};
|
|
1061
|
-
bareIds.add(__classPrivateFieldGet$1(bareState, _State_id, "f"));
|
|
1062
|
-
queue.push(bareState);
|
|
1063
|
-
queue.push(overrideTarget);
|
|
1064
|
-
continue;
|
|
1065
|
-
}
|
|
1066
|
-
// Regular (or bare) state — build node with transitions.
|
|
1067
|
-
const node = {
|
|
1068
|
-
id: __classPrivateFieldGet$1(state, _State_id, "f"),
|
|
1069
|
-
name: __classPrivateFieldGet$1(state, _State_name, "f"),
|
|
1070
|
-
isHalt: false,
|
|
1071
|
-
isHaltMarker: false,
|
|
1072
|
-
isWrapper: false,
|
|
1073
|
-
bareStateId: null,
|
|
1074
|
-
frameId: null,
|
|
1075
|
-
transitions: [],
|
|
1076
|
-
overriddenHaltStateId: null,
|
|
1077
|
-
tags: [...__classPrivateFieldGet$1(state, _State_tags, "f")],
|
|
1078
|
-
};
|
|
1079
|
-
nodes[__classPrivateFieldGet$1(state, _State_id, "f")] = node;
|
|
1080
|
-
let patternIx = 0;
|
|
1081
|
-
for (const [sym, { command, nextState }] of __classPrivateFieldGet$1(state, _State_symbolToDataMap, "f")) {
|
|
1082
|
-
let target;
|
|
1083
|
-
try {
|
|
1084
|
-
target = nextState instanceof _a ? nextState : nextState.ref;
|
|
1085
|
-
}
|
|
1086
|
-
catch {
|
|
1087
|
-
patternIx += 1;
|
|
1088
|
-
continue;
|
|
1089
|
-
}
|
|
1090
|
-
node.transitions.push({
|
|
1091
|
-
pattern: decodePatternDescription(sym.description, alphabets),
|
|
1092
|
-
command: command.tapesCommands.map((tc) => ({
|
|
1093
|
-
symbol: decodeWriteSymbol(tc.symbol),
|
|
1094
|
-
movement: decodeMovement(tc.movement.description),
|
|
1095
|
-
})),
|
|
1096
|
-
nextStateId: __classPrivateFieldGet$1(target, _State_id, "f"),
|
|
1097
|
-
id: `${__classPrivateFieldGet$1(state, _State_id, "f")}-${patternIx}`,
|
|
1098
|
-
});
|
|
1099
|
-
queue.push(target);
|
|
1100
|
-
patternIx += 1;
|
|
1101
|
-
}
|
|
1102
|
-
}
|
|
1103
|
-
// Always emit real halt as a sentinel, even if no transition targets it.
|
|
1104
|
-
// It anchors the `subtree -. halt .-> s0` frame-level arrow whenever a
|
|
1105
|
-
// frame demand-emits one, and it's the canonical machine-halt singleton.
|
|
1106
|
-
if (!(0 in nodes)) {
|
|
1107
|
-
nodes[0] = {
|
|
1108
|
-
id: 0,
|
|
1109
|
-
name: 'halt',
|
|
1110
|
-
isHalt: true,
|
|
1111
|
-
isHaltMarker: false,
|
|
1112
|
-
isWrapper: false,
|
|
1113
|
-
bareStateId: null,
|
|
1114
|
-
frameId: null,
|
|
1115
|
-
transitions: [],
|
|
1116
|
-
overriddenHaltStateId: null,
|
|
1117
|
-
tags: [...__classPrivateFieldGet$1(haltState, _State_tags, "f")],
|
|
1118
|
-
};
|
|
1119
|
-
}
|
|
1120
|
-
// Pass 2: For each bare, compute its forward-reachable set (following
|
|
1121
|
-
// transitions; stopping at halt and at wrappers — both are frame
|
|
1122
|
-
// boundaries).
|
|
1123
|
-
const computeReach = (startId) => {
|
|
1124
|
-
const reach = new Set();
|
|
1125
|
-
const stack = [startId];
|
|
1126
|
-
while (stack.length > 0) {
|
|
1127
|
-
const id = stack.pop();
|
|
1128
|
-
if (reach.has(id)) {
|
|
1129
|
-
continue;
|
|
1130
|
-
}
|
|
1131
|
-
const node = nodes[id];
|
|
1132
|
-
// `nodes[id]` is always populated for `id` that the BFS reached, so
|
|
1133
|
-
// a defensive `!node` check would be dead. `isHalt` / `isWrapper`
|
|
1134
|
-
// are real boundaries — both stop reach-set expansion.
|
|
1135
|
-
if (node.isHalt || node.isWrapper) {
|
|
1136
|
-
continue;
|
|
1137
|
-
}
|
|
1138
|
-
reach.add(id);
|
|
1139
|
-
for (const t of node.transitions) {
|
|
1140
|
-
const target = nodes[t.nextStateId];
|
|
1141
|
-
if (!target || target.isHalt || target.isWrapper) {
|
|
1142
|
-
continue;
|
|
1143
|
-
}
|
|
1144
|
-
stack.push(t.nextStateId);
|
|
1145
|
-
}
|
|
1146
|
-
}
|
|
1147
|
-
return reach;
|
|
1148
|
-
};
|
|
1149
|
-
const reachByBare = new Map();
|
|
1150
|
-
for (const bareId of bareIds) {
|
|
1151
|
-
reachByBare.set(bareId, computeReach(bareId));
|
|
1152
|
-
}
|
|
1153
|
-
// Pass 3: Union-find on bare overlaps. Two bares merge if their reach
|
|
1154
|
-
// sets share any state. Canonical representative = smallest bare-id in
|
|
1155
|
-
// the component.
|
|
1156
|
-
const ufParent = new Map();
|
|
1157
|
-
// Note: no path compression. The union policy below ("smaller id always
|
|
1158
|
-
// becomes root") keeps the tree flat — every union targets bares[0] as
|
|
1159
|
-
// the root, so any node's parent IS the root. Walking up never exceeds
|
|
1160
|
-
// one step. Path compression would be dead code under this invariant.
|
|
1161
|
-
const ufFind = (id) => {
|
|
1162
|
-
if (!ufParent.has(id)) {
|
|
1163
|
-
ufParent.set(id, id);
|
|
1164
|
-
}
|
|
1165
|
-
let root = id;
|
|
1166
|
-
while (ufParent.get(root) !== root) {
|
|
1167
|
-
root = ufParent.get(root);
|
|
1168
|
-
}
|
|
1169
|
-
return root;
|
|
1170
|
-
};
|
|
1171
|
-
const ufUnion = (a, b) => {
|
|
1172
|
-
const ra = ufFind(a);
|
|
1173
|
-
const rb = ufFind(b);
|
|
1174
|
-
if (ra === rb)
|
|
1175
|
-
return;
|
|
1176
|
-
if (ra < rb) {
|
|
1177
|
-
ufParent.set(rb, ra);
|
|
1178
|
-
}
|
|
1179
|
-
else {
|
|
1180
|
-
ufParent.set(ra, rb);
|
|
1181
|
-
}
|
|
1182
|
-
};
|
|
1183
|
-
for (const bareId of bareIds) {
|
|
1184
|
-
ufFind(bareId);
|
|
1185
|
-
}
|
|
1186
|
-
// For each state, collect the bares that reach it; union all bares that
|
|
1187
|
-
// share a state.
|
|
1188
|
-
const stateToReachingBares = new Map();
|
|
1189
|
-
for (const [bareId, reachSet] of reachByBare) {
|
|
1190
|
-
for (const stateId of reachSet) {
|
|
1191
|
-
let bares = stateToReachingBares.get(stateId);
|
|
1192
|
-
if (!bares) {
|
|
1193
|
-
bares = [];
|
|
1194
|
-
stateToReachingBares.set(stateId, bares);
|
|
1195
|
-
}
|
|
1196
|
-
bares.push(bareId);
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
for (const bares of stateToReachingBares.values()) {
|
|
1200
|
-
for (let i = 1; i < bares.length; i += 1) {
|
|
1201
|
-
ufUnion(bares[0], bares[i]);
|
|
1202
|
-
}
|
|
1203
|
-
}
|
|
1204
|
-
// Assign frameId to each in-reach state.
|
|
1205
|
-
const frameIds = new Set();
|
|
1206
|
-
for (const [stateId, bares] of stateToReachingBares) {
|
|
1207
|
-
const frameId = ufFind(bares[0]);
|
|
1208
|
-
nodes[stateId].frameId = frameId;
|
|
1209
|
-
frameIds.add(frameId);
|
|
1210
|
-
}
|
|
1211
|
-
// Pass 4: Retarget halt-bound transitions for in-frame states to the
|
|
1212
|
-
// frame's halt marker. Out-of-frame states (top-level dispatcher, override
|
|
1213
|
-
// targets, etc.) keep their halt-bound transitions pointing at real halt.
|
|
1214
|
-
for (const node of Object.values(nodes)) {
|
|
1215
|
-
if (node.frameId === null) {
|
|
1216
|
-
continue;
|
|
1217
|
-
}
|
|
1218
|
-
const haltMarkerId = -node.frameId;
|
|
1219
|
-
for (const t of node.transitions) {
|
|
1220
|
-
const target = nodes[t.nextStateId];
|
|
1221
|
-
if (target && target.isHalt && !target.isHaltMarker) {
|
|
1222
|
-
t.nextStateId = haltMarkerId;
|
|
1223
|
-
}
|
|
1224
|
-
}
|
|
1225
|
-
}
|
|
1226
|
-
// Pass 5: Emit one halt marker per frame.
|
|
1227
|
-
for (const frameId of frameIds) {
|
|
1228
|
-
const haltMarkerId = -frameId;
|
|
1229
|
-
nodes[haltMarkerId] = {
|
|
1230
|
-
id: haltMarkerId,
|
|
1231
|
-
name: 'halt',
|
|
1232
|
-
isHalt: true,
|
|
1233
|
-
isHaltMarker: true,
|
|
1234
|
-
isWrapper: false,
|
|
1235
|
-
bareStateId: null,
|
|
1236
|
-
frameId,
|
|
1237
|
-
transitions: [],
|
|
1238
|
-
overriddenHaltStateId: null,
|
|
1239
|
-
tags: [],
|
|
1240
|
-
};
|
|
1241
|
-
}
|
|
1242
|
-
return { initialId: __classPrivateFieldGet$1(initialState, _State_id, "f"), alphabets, nodes };
|
|
1570
|
+
return toGraph(initialState, tapeBlock);
|
|
1243
1571
|
}
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
// `bareStates[bareStateId].withOverriddenHaltState(finalStates[overriddenHaltStateId])`.
|
|
1252
|
-
// - Bare/regular nodes — constructed as normal States with transitions.
|
|
1253
|
-
// - Halt + halt-marker nodes — collapse to the singleton `haltState`.
|
|
1572
|
+
/**
|
|
1573
|
+
* Inverse of `toGraph`: rebuilds a State graph and a fresh TapeBlock
|
|
1574
|
+
* from a serialized `Graph`. Thin delegate to `utilities/stateGraph.ts`'s
|
|
1575
|
+
* `fromGraph` (extracted in #180); see that module for the
|
|
1576
|
+
* reconstruction pass shape (Reference pre-create, bare build, wrapper
|
|
1577
|
+
* resolution via `withOverriddenHaltState`, ref binding).
|
|
1578
|
+
*/
|
|
1254
1579
|
static fromGraph(graph) {
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
// Convert a parsed pattern back to the symbol key the State expects.
|
|
1269
|
-
const patternToKey = (parsed) => {
|
|
1270
|
-
if (parsed === null) {
|
|
1271
|
-
return ifOtherSymbol;
|
|
1272
|
-
}
|
|
1273
|
-
const flat = [];
|
|
1274
|
-
for (const row of parsed) {
|
|
1275
|
-
for (const cell of row) {
|
|
1276
|
-
flat.push(cell === null ? ifOtherSymbol : cell);
|
|
1277
|
-
}
|
|
1278
|
-
}
|
|
1279
|
-
return tapeBlock.symbol(flat);
|
|
1280
|
-
};
|
|
1281
|
-
// Pass 2: build a State for each non-wrapper non-halt non-halt-marker
|
|
1282
|
-
// node. Transitions point at refs so cycles work; haltState (and halt
|
|
1283
|
-
// markers, which collapse to haltState) are used directly.
|
|
1284
|
-
const bareStates = {};
|
|
1285
|
-
for (const nodeId of ids) {
|
|
1286
|
-
const node = graph.nodes[nodeId];
|
|
1287
|
-
if (node.isHalt || node.isWrapper) {
|
|
1288
|
-
continue;
|
|
1289
|
-
}
|
|
1290
|
-
const stateDefinition = {};
|
|
1291
|
-
for (const t of node.transitions) {
|
|
1292
|
-
const key = patternToKey(parsePatternString(t.pattern, graph.alphabets));
|
|
1293
|
-
const target = graph.nodes[t.nextStateId];
|
|
1294
|
-
const nextState = !target || target.isHalt
|
|
1295
|
-
? haltState
|
|
1296
|
-
: refs[t.nextStateId];
|
|
1297
|
-
stateDefinition[key] = {
|
|
1298
|
-
command: t.command.map((c) => ({
|
|
1299
|
-
symbol: parseWriteSymbolLabel(c.symbol),
|
|
1300
|
-
movement: parseMovementLabel(c.movement),
|
|
1301
|
-
})),
|
|
1302
|
-
nextState,
|
|
1303
|
-
};
|
|
1304
|
-
}
|
|
1305
|
-
// Graph-sourced names may contain `(` and `)` (composite wrapper names —
|
|
1306
|
-
// although wrappers go through a separate path below, defensive
|
|
1307
|
-
// construction here keeps the bypass uniform). Construct without a name
|
|
1308
|
-
// and assign `#name` directly to skip user-facing name validation.
|
|
1309
|
-
const bare = new _a(stateDefinition);
|
|
1310
|
-
__classPrivateFieldSet$1(bare, _State_name, node.name, "f");
|
|
1311
|
-
if (node.tags.length > 0) {
|
|
1312
|
-
bare.tag(...node.tags);
|
|
1313
|
-
}
|
|
1314
|
-
bareStates[nodeId] = bare;
|
|
1315
|
-
}
|
|
1316
|
-
// Pass 3: resolve every node to its final State (memoized + cycle-safe).
|
|
1317
|
-
// Wrappers compose lazily via `withOverriddenHaltState` once their bare
|
|
1318
|
-
// and override are resolved.
|
|
1319
|
-
const finalStates = {};
|
|
1320
|
-
const inProgress = new Set();
|
|
1321
|
-
const getFinal = (nodeId) => {
|
|
1322
|
-
if (finalStates[nodeId]) {
|
|
1323
|
-
return finalStates[nodeId];
|
|
1324
|
-
}
|
|
1325
|
-
const node = graph.nodes[nodeId];
|
|
1326
|
-
if (!node || node.isHalt) {
|
|
1327
|
-
finalStates[nodeId] = haltState;
|
|
1328
|
-
return haltState;
|
|
1329
|
-
}
|
|
1330
|
-
if (inProgress.has(nodeId)) {
|
|
1331
|
-
throw new Error(`override-halt cycle at state #${nodeId}`);
|
|
1332
|
-
}
|
|
1333
|
-
inProgress.add(nodeId);
|
|
1334
|
-
let state;
|
|
1335
|
-
if (node.isWrapper) {
|
|
1336
|
-
const bare = getFinal(node.bareStateId);
|
|
1337
|
-
const override = getFinal(node.overriddenHaltStateId);
|
|
1338
|
-
state = bare.withOverriddenHaltState(override);
|
|
1339
|
-
// Apply wrapper-scoped tags (#186). Tags don't leak across wrappers
|
|
1340
|
-
// sharing a bare — the wrapper instance owns its own tag set, and
|
|
1341
|
-
// engine #175 memoization returns the same instance for the same
|
|
1342
|
-
// (bare, override) pair, so this is idempotent across rebuilds.
|
|
1343
|
-
if (node.tags.length > 0) {
|
|
1344
|
-
state.tag(...node.tags);
|
|
1345
|
-
}
|
|
1346
|
-
}
|
|
1347
|
-
else {
|
|
1348
|
-
state = bareStates[nodeId];
|
|
1349
|
-
}
|
|
1350
|
-
inProgress.delete(nodeId);
|
|
1351
|
-
finalStates[nodeId] = state;
|
|
1352
|
-
return state;
|
|
1353
|
-
};
|
|
1354
|
-
for (const nodeId of ids) {
|
|
1355
|
-
getFinal(nodeId);
|
|
1356
|
-
}
|
|
1357
|
-
// Pass 4: bind each ref to the resolved final State so cross-node
|
|
1358
|
-
// transitions land on the right instance.
|
|
1359
|
-
for (const nodeId of ids) {
|
|
1360
|
-
if (!graph.nodes[nodeId].isHalt) {
|
|
1361
|
-
refs[nodeId].bind(finalStates[nodeId]);
|
|
1362
|
-
}
|
|
1363
|
-
}
|
|
1364
|
-
return {
|
|
1365
|
-
start: finalStates[graph.initialId],
|
|
1366
|
-
tapeBlock,
|
|
1367
|
-
states: finalStates,
|
|
1368
|
-
};
|
|
1580
|
+
return fromGraph(graph);
|
|
1581
|
+
}
|
|
1582
|
+
/**
|
|
1583
|
+
* Returns a `Map<number, {state, transitionSymbols}>` keyed by engine
|
|
1584
|
+
* `GraphNode.id`, exposing the live `State` instance + per-pattern
|
|
1585
|
+
* Symbol references for each node so downstream tooling can mutate
|
|
1586
|
+
* `state.debug` by numeric id and set per-pattern breakpoints by
|
|
1587
|
+
* `GraphTransition.id` (#195). Thin delegate to
|
|
1588
|
+
* `utilities/stateGraph.ts`'s `collectStates`; see that module for
|
|
1589
|
+
* the alignment contract, coverage rules, and halt-singleton warning.
|
|
1590
|
+
*/
|
|
1591
|
+
static collectStates(initialState, tapeBlock) {
|
|
1592
|
+
return collectStates(initialState, tapeBlock);
|
|
1369
1593
|
}
|
|
1370
1594
|
}
|
|
1371
1595
|
_a = State;
|
|
@@ -1388,7 +1612,7 @@ var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) ||
|
|
|
1388
1612
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
1389
1613
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
1390
1614
|
};
|
|
1391
|
-
var _TuringMachine_tapeBlock
|
|
1615
|
+
var _TuringMachine_tapeBlock;
|
|
1392
1616
|
// True iff `filter` matches `symbol` per the DebugConfig semantics.
|
|
1393
1617
|
// undefined / [] -> never; true -> always; symbol[] -> exact membership.
|
|
1394
1618
|
function matchFilter(filter, symbol) {
|
|
@@ -1401,7 +1625,6 @@ function matchFilter(filter, symbol) {
|
|
|
1401
1625
|
class TuringMachine {
|
|
1402
1626
|
constructor({ tapeBlock, } = {}) {
|
|
1403
1627
|
_TuringMachine_tapeBlock.set(this, void 0);
|
|
1404
|
-
_TuringMachine_stack.set(this, []);
|
|
1405
1628
|
if (!tapeBlock) {
|
|
1406
1629
|
throw new Error('invalid tapeBlock');
|
|
1407
1630
|
}
|
|
@@ -1435,7 +1658,14 @@ class TuringMachine {
|
|
|
1435
1658
|
try {
|
|
1436
1659
|
__classPrivateFieldGet(this, _TuringMachine_tapeBlock, "f")[lockSymbol].check(executionSymbol);
|
|
1437
1660
|
__classPrivateFieldGet(this, _TuringMachine_tapeBlock, "f")[lockSymbol].lock(executionSymbol);
|
|
1438
|
-
|
|
1661
|
+
// Halt-stack is run-scoped, not machine-scoped (#196). Declaring it
|
|
1662
|
+
// local makes that lifetime explicit and prevents leftover entries
|
|
1663
|
+
// from a previous `runStepByStep` call (e.g. a build-time peek that
|
|
1664
|
+
// never drained the generator) from being popped during a subsequent
|
|
1665
|
+
// halt-bound transition. Before this change `#stack` was an instance
|
|
1666
|
+
// field and accumulated one extra push per call when the same machine
|
|
1667
|
+
// was reused.
|
|
1668
|
+
const stack = [];
|
|
1439
1669
|
let state = initialState;
|
|
1440
1670
|
if (state.overriddenHaltState) {
|
|
1441
1671
|
stack.push(state.overriddenHaltState);
|
|
@@ -1510,7 +1740,7 @@ class TuringMachine {
|
|
|
1510
1740
|
}
|
|
1511
1741
|
}
|
|
1512
1742
|
}
|
|
1513
|
-
_TuringMachine_tapeBlock = new WeakMap()
|
|
1743
|
+
_TuringMachine_tapeBlock = new WeakMap();
|
|
1514
1744
|
|
|
1515
1745
|
// Format converters between a Graph (the data model produced by State.toGraph
|
|
1516
1746
|
// and consumed by State.fromGraph) and external string representations.
|
|
@@ -1553,6 +1783,79 @@ function parseMermaidId(s) {
|
|
|
1553
1783
|
function frameSubgraphId(frameId) {
|
|
1554
1784
|
return `w_${frameId}`;
|
|
1555
1785
|
}
|
|
1786
|
+
// User-controlled content (state names, tag names, alphabet symbols inside
|
|
1787
|
+
// edge labels) is interpolated into Mermaid label strings (`"..."` wrappers
|
|
1788
|
+
// on nodes, wrappers, subgraphs, and edges). Mermaid's grammar terminates
|
|
1789
|
+
// the string on a literal `"`, and labels render via HTML/foreignObject so
|
|
1790
|
+
// `<`, `>`, `&` get interpreted as markup. Statement terminators (`\n`,
|
|
1791
|
+
// `\r`), C0 controls (except `\t`), DEL, bidi controls, and lone UTF-16
|
|
1792
|
+
// surrogates are encoded as numeric entities so they can't confuse the
|
|
1793
|
+
// tokenizer or flip text direction silently (#194).
|
|
1794
|
+
//
|
|
1795
|
+
// Printable Unicode (Cyrillic, CJK, emoji, accented Latin, etc.) passes
|
|
1796
|
+
// through unchanged — a tape alphabet of Cyrillic or Brainfuck glyphs
|
|
1797
|
+
// stays readable in the emitted `.mmd`.
|
|
1798
|
+
//
|
|
1799
|
+
// Escape is applied at the leaf — to each user-supplied fragment BEFORE
|
|
1800
|
+
// it's composed into a label. Structural pieces this module emits (`<br>`
|
|
1801
|
+
// tag separator, ` ∪ ` bare-name join, `[`, `]`, `,`, `|`, `/`, ` → `,
|
|
1802
|
+
// the `callable subtree of `/`callable scope: ` prefixes) are NOT escaped;
|
|
1803
|
+
// only user-controlled content is. fromMermaid mirrors with
|
|
1804
|
+
// `unescapeMermaidLabel` on each extracted leaf AFTER structural parsing,
|
|
1805
|
+
// so a literal `<br>` inside a state name (encoded as `<br>`)
|
|
1806
|
+
// survives the tag-split and decodes back at the leaf.
|
|
1807
|
+
const MERMAID_LABEL_ESCAPE_RE = /[&"<>\n\r\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F\u202A-\u202E\u2066-\u2069\uD800-\uDFFF]/g;
|
|
1808
|
+
function escapeMermaidLabel(s) {
|
|
1809
|
+
return s.replace(MERMAID_LABEL_ESCAPE_RE, (ch) => {
|
|
1810
|
+
switch (ch) {
|
|
1811
|
+
case '&': return '&';
|
|
1812
|
+
case '"': return '"';
|
|
1813
|
+
case '<': return '<';
|
|
1814
|
+
case '>': return '>';
|
|
1815
|
+
case '\n': return ' ';
|
|
1816
|
+
case '\r': return ' ';
|
|
1817
|
+
default: return `&#${ch.charCodeAt(0)};`;
|
|
1818
|
+
}
|
|
1819
|
+
});
|
|
1820
|
+
}
|
|
1821
|
+
// Inverse of escapeMermaidLabel. Decodes the four named entities the
|
|
1822
|
+
// encoder emits (`&`, `"`, `<`, `>`) plus arbitrary
|
|
1823
|
+
// numeric entities (`&#NN;`, `&#xHH;`) — the latter to round-trip the
|
|
1824
|
+
// control / bidi / lone-surrogate cases from encode. Other named entities
|
|
1825
|
+
// pass through unchanged: fromMermaid is strict to the dialect toMermaid
|
|
1826
|
+
// emits, and a future-proof full HTML-entity decoder would muddle that.
|
|
1827
|
+
//
|
|
1828
|
+
// Replacement is single-pass: each `&...;` match is consumed once with
|
|
1829
|
+
// no re-scanning of the substitution, so nested-looking inputs like
|
|
1830
|
+
// `&quot;` (literal `"` as user text) decode to `"` not `"`.
|
|
1831
|
+
const MERMAID_LABEL_UNESCAPE_RE = /&(?:(amp|quot|lt|gt)|#(\d+)|#x([0-9a-fA-F]+));/g;
|
|
1832
|
+
function unescapeMermaidLabel(s) {
|
|
1833
|
+
return s.replace(MERMAID_LABEL_UNESCAPE_RE, (match, named, dec, hex) => {
|
|
1834
|
+
switch (named) {
|
|
1835
|
+
case 'amp': return '&';
|
|
1836
|
+
case 'quot': return '"';
|
|
1837
|
+
case 'lt': return '<';
|
|
1838
|
+
case 'gt': return '>';
|
|
1839
|
+
default: {
|
|
1840
|
+
// Code units up to U+FFFF decode via fromCharCode so lone
|
|
1841
|
+
// surrogates we encoded by UTF-16 code unit round-trip exactly.
|
|
1842
|
+
// Hand-edited supplementary code points (`😀`) use
|
|
1843
|
+
// fromCodePoint to produce the right surrogate pair — but only
|
|
1844
|
+
// when we didn't emit them ourselves, since encode runs per code
|
|
1845
|
+
// unit.
|
|
1846
|
+
if (dec !== undefined) {
|
|
1847
|
+
const n = Number.parseInt(dec, 10);
|
|
1848
|
+
return n <= 0xFFFF ? String.fromCharCode(n) : String.fromCodePoint(n);
|
|
1849
|
+
}
|
|
1850
|
+
if (hex !== undefined) {
|
|
1851
|
+
const n = Number.parseInt(hex, 16);
|
|
1852
|
+
return n <= 0xFFFF ? String.fromCharCode(n) : String.fromCodePoint(n);
|
|
1853
|
+
}
|
|
1854
|
+
return match;
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
});
|
|
1858
|
+
}
|
|
1556
1859
|
function toMermaid(graph) {
|
|
1557
1860
|
const lines = [
|
|
1558
1861
|
'flowchart TD',
|
|
@@ -1591,9 +1894,18 @@ function toMermaid(graph) {
|
|
|
1591
1894
|
// Mermaid line-break that works across renderers without `classDef`-
|
|
1592
1895
|
// pseudo-element hacks (#186).
|
|
1593
1896
|
const labelOf = (node) => {
|
|
1897
|
+
const name = escapeMermaidLabel(node.name);
|
|
1594
1898
|
if (node.tags.length === 0)
|
|
1595
|
-
return
|
|
1596
|
-
|
|
1899
|
+
return name;
|
|
1900
|
+
// Per-tag escape that ALSO encodes `,` — tags are joined with `, ` and
|
|
1901
|
+
// split on `,` in `splitLabelTags`, so a literal comma in user tag
|
|
1902
|
+
// content would be mistaken for a separator on the way back. `,` isn't
|
|
1903
|
+
// in the base escape set because it's structural in edge labels
|
|
1904
|
+
// (between per-tape cells in `writes`/`moves`), where the encode pass
|
|
1905
|
+
// happens after composition — different context, different escape.
|
|
1906
|
+
const tagFragments = node.tags
|
|
1907
|
+
.map((t) => escapeMermaidLabel(t).replace(/,/g, ','));
|
|
1908
|
+
return `${name}<br>${tagFragments.join(', ')}`;
|
|
1597
1909
|
};
|
|
1598
1910
|
// 1. Emit top-level nodes (real halt, non-wrapper regulars outside any frame).
|
|
1599
1911
|
for (const node of topLevelNodes) {
|
|
@@ -1618,7 +1930,7 @@ function toMermaid(graph) {
|
|
|
1618
1930
|
const frameBareNames = frameBares
|
|
1619
1931
|
.slice()
|
|
1620
1932
|
.sort((a, b) => a.id - b.id)
|
|
1621
|
-
.map((n) => n.name);
|
|
1933
|
+
.map((n) => escapeMermaidLabel(n.name));
|
|
1622
1934
|
const label = frameBareNames.length > 1
|
|
1623
1935
|
? `callable scope: ${frameBareNames.join(' ∪ ')}`
|
|
1624
1936
|
: `callable subtree of ${frameBareNames[0] ?? frameId}`;
|
|
@@ -1720,7 +2032,12 @@ function toMermaid(graph) {
|
|
|
1720
2032
|
const reads = alternatives.map((alt) => `[${alt}]`).join('|');
|
|
1721
2033
|
const writes = `[${t.command.map((c) => c.symbol).join(',')}]`;
|
|
1722
2034
|
const moves = `[${t.command.map((c) => c.movement).join(',')}]`;
|
|
1723
|
-
|
|
2035
|
+
// Escape the WHOLE composed label — structural separators ([, ], ,,
|
|
2036
|
+
// |, /, ' → ') are all in our safe ASCII set and pass through
|
|
2037
|
+
// unchanged; only embedded user alphabet symbols inside `'...'` get
|
|
2038
|
+
// entity-encoded. fromMermaid unescapes the captured label as the
|
|
2039
|
+
// first step before structural parsing.
|
|
2040
|
+
const label = escapeMermaidLabel(`${reads} → ${writes}/${moves}`);
|
|
1724
2041
|
lines.push(` ${mermaidIdFor(node.id)} -- "${label}" --> ${mermaidIdFor(t.nextStateId)}`);
|
|
1725
2042
|
}
|
|
1726
2043
|
}
|
|
@@ -1851,14 +2168,23 @@ const classAssignTagRegex = /^class ([sc]\d+(?:,[sc]\d+)*) tag_([A-Za-z0-9_-]+)$
|
|
|
1851
2168
|
// Labels without `<br>` have no tags. Tags are comma-joined; trimmed of
|
|
1852
2169
|
// whitespace. The `<br>` is the single source of truth for tag-name parsing —
|
|
1853
2170
|
// `class` lines are decorative-only and not consulted here.
|
|
2171
|
+
//
|
|
2172
|
+
// Mermaid-label entities (`<`, `"`, etc., #194) are decoded AFTER
|
|
2173
|
+
// structural splitting: the `<br>` separator and `,` tag delimiter survive
|
|
2174
|
+
// encode unchanged, and a user state name / tag containing a literal `<br>`
|
|
2175
|
+
// or `,` was encoded leaf-side so it can't be confused with the structural
|
|
2176
|
+
// form. Decode at the leaves recovers the original characters.
|
|
1854
2177
|
function splitLabelTags(label) {
|
|
1855
2178
|
const brIx = label.indexOf('<br>');
|
|
1856
2179
|
if (brIx < 0) {
|
|
1857
|
-
return { name: label, tags: [] };
|
|
2180
|
+
return { name: unescapeMermaidLabel(label), tags: [] };
|
|
1858
2181
|
}
|
|
1859
|
-
const name = label.slice(0, brIx);
|
|
2182
|
+
const name = unescapeMermaidLabel(label.slice(0, brIx));
|
|
1860
2183
|
const tagsStr = label.slice(brIx + '<br>'.length);
|
|
1861
|
-
const tags = tagsStr
|
|
2184
|
+
const tags = tagsStr
|
|
2185
|
+
.split(',')
|
|
2186
|
+
.map((t) => unescapeMermaidLabel(t.trim()))
|
|
2187
|
+
.filter((t) => t.length > 0);
|
|
1862
2188
|
return { name, tags };
|
|
1863
2189
|
}
|
|
1864
2190
|
function fromMermaid(text) {
|
|
@@ -2018,7 +2344,12 @@ function fromMermaid(text) {
|
|
|
2018
2344
|
const tm = line.match(labeledTransitionRegex);
|
|
2019
2345
|
if (tm) {
|
|
2020
2346
|
const fromId = parseMermaidId(tm[1]);
|
|
2021
|
-
|
|
2347
|
+
// Decode the WHOLE captured label up front (#194). Structural
|
|
2348
|
+
// separators (`[`, `]`, `,`, `|`, `/`, ` → `) are all safe ASCII
|
|
2349
|
+
// outside the escape set and pass through encode unchanged, so it's
|
|
2350
|
+
// safe to decode before structural parsing; only embedded alphabet
|
|
2351
|
+
// symbols inside `'...'` get reconstituted.
|
|
2352
|
+
const label = unescapeMermaidLabel(tm[2]);
|
|
2022
2353
|
const toId = parseMermaidId(tm[3]);
|
|
2023
2354
|
const arrowIx = label.indexOf(' → ');
|
|
2024
2355
|
if (arrowIx === -1) {
|