-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathtvm-instruction-table.jsx
More file actions
4007 lines (3630 loc) · 114 KB
/
tvm-instruction-table.jsx
File metadata and controls
4007 lines (3630 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const React =
typeof globalThis !== "undefined" && globalThis.React
? globalThis.React
: (() => {
throw new Error(
"React global missing. TvmInstructionTable must run inside a React-powered environment."
);
})();
export const TvmInstructionTable = () => {
const { useCallback, useEffect, useMemo, useRef, useState } = React;
const PERSIST_KEY = "tvm-instruction-table::filters";
const SPEC_URL = "/resources/tvm/cp0.txt";
const CATEGORY_MAP = {
stack_basic: "Stack basics",
stack_complex: "Stack (complex)",
arithm_basic: "Arithmetic (basic)",
arithm_div: "Arithmetic (division)",
arithm_logical: "Arithmetic (logical)",
arithm_quiet: "Arithmetic (quiet)",
cell_build: "Cell builders",
cell_parse: "Cell parsers",
codepage: "Codepage management",
compare_int: "Comparisons (integers)",
compare_other: "Comparisons (other)",
const_data: "Constants (data)",
const_int: "Constants (integers)",
cont_basic: "Continuations (basic)",
cont_conditional: "Continuations (conditional)",
cont_create: "Continuations (creation)",
cont_dict: "Continuations (dictionary)",
cont_loops: "Continuations (loops)",
cont_registers: "Continuations (registers)",
cont_stack: "Continuations (stack)",
dict_delete: "Dictionaries (delete)",
dict_get: "Dictionaries (lookup)",
dict_mayberef: "Dictionaries (maybe ref)",
dict_min: "Dictionaries (min/max)",
dict_next: "Dictionaries (iteration)",
dict_prefix: "Dictionaries (prefix)",
dict_serial: "Dictionaries (serialization)",
dict_set: "Dictionaries (store)",
dict_set_builder: "Dictionaries (builder)",
dict_special: "Dictionaries (special)",
dict_sub: "Dictionaries (sub-dictionaries)",
app_actions: "Actions",
app_addr: "Addresses",
app_config: "Blockchain configuration",
app_crypto: "Cryptography",
app_currency: "Currency",
app_gas: "Gas & fees",
app_global: "Global variables",
app_misc: "Misc",
app_rnd: "Randomness",
app_gaslimits: "Gas limits",
app_storage: "Contract storage",
exceptions: "Exceptions & control",
debug: "Debugging",
tuple: "Tuples",
};
const CATEGORY_GROUPS = [
{
key: "stack",
label: "Stack",
patterns: [/^stack_/],
},
{
key: "continuations",
label: "Continuations & Control Flow",
patterns: [/^cont_/, /^codepage$/],
},
{
key: "arithmetic",
label: "Arithmetic & Logic",
patterns: [/^arithm_/, /^compare_/],
},
{
key: "cells",
label: "Cells & Tuples",
patterns: [/^cell_/, /^tuple$/],
},
{
key: "dictionaries",
label: "Dictionaries",
patterns: [/^dict_/],
},
{
key: "constants",
label: "Constants",
patterns: [/^const_/],
},
{
key: "crypto",
label: "Crypto",
patterns: [/^app_crypto/],
},
{
key: "applications",
label: "Blockchain",
patterns: [/^app_(?!crypto)/],
},
{
key: "exceptions",
label: "Exceptions",
patterns: [/^exceptions$/],
},
{
key: "debug",
label: "Debugging",
patterns: [/^debug$/],
}
];
const CATEGORY_GROUP_KEYS = new Set(
CATEGORY_GROUPS.map((group) => group.key)
);
function resolveCategoryGroup(categoryKey) {
const normalized = (categoryKey || "").toLowerCase();
for (const group of CATEGORY_GROUPS) {
if (
Array.isArray(group.patterns) &&
group.patterns.length > 0 &&
group.patterns.some((pattern) => pattern.test(normalized))
) {
return group;
}
}
return CATEGORY_GROUPS[CATEGORY_GROUPS.length - 1];
}
function humanizeCategoryKey(key) {
if (!key) return "Uncategorized";
if (CATEGORY_MAP[key]) return CATEGORY_MAP[key];
return key
.split(/[_\s]+/)
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(" ");
}
function formatGasDisplay(gas) {
if (Array.isArray(gas)) {
return gas.length > 0 ? gas.join(" / ") : "N/A";
}
if (typeof gas === "number") {
return gas.toLocaleString();
}
if (typeof gas === "string") {
const value = gas.trim();
if (!value) return "N/A";
return value.replace(/\//g, " / ").replace(/\s+/g, " ");
}
return "N/A";
}
function formatOperandSummary(operand) {
if (!operand) return "";
const name =
typeof operand.name === "string" && operand.name ? operand.name : "?";
const type = typeof operand.type === "string" ? operand.type : "";
const size =
typeof operand.size === "number"
? operand.size
: typeof operand.bits === "number"
? operand.bits
: undefined;
const hasRange =
operand.min_value !== undefined &&
operand.min_value !== null &&
operand.max_value !== undefined &&
operand.max_value !== null;
const range = hasRange
? ` [${operand.min_value}; ${operand.max_value}]`
: "";
const sizePart = size !== undefined ? `(${size})` : "";
return `${name}${type ? `:${type}` : ""}${sizePart}${range}`;
}
function formatInlineMarkdown(text) {
if (typeof text !== "string") return "";
const trimmed = text.trim();
if (!trimmed) return "";
const escaped = trimmed
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
const withCode = escaped.replace(/`([^`]+)`/g, (_match, code) => {
return `<code>${code}</code>`;
});
const withLinks = withCode.replace(
/\[([^\]]+)\]\((https?:[^)\s]+)\)/g,
(_match, label, url) =>
`<a href="${url}" target="_blank" rel="noreferrer">${label}</a>`
);
return withLinks.replace(/\n/g, "<br />");
}
function compareOpcodes(a, b) {
const sanitize = (value) => (value || "").replace(/[^0-9a-f]/gi, "");
const ax = Number.parseInt(sanitize(a), 16);
const bx = Number.parseInt(sanitize(b), 16);
if (!Number.isNaN(ax) && !Number.isNaN(bx) && ax !== bx) {
return ax - bx;
}
return (a || "").localeCompare(b || "");
}
// Search helpers for relevance-based filtering and sorting
function createSearchTokens(query) {
if (typeof query !== "string") return [];
return query
.toLowerCase()
.split(/\s+/)
.map((t) => t.trim())
.filter((t) => t.length >= 2); // drop 1-char tokens as too noisy
}
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function highlightMatches(text, tokens) {
if (typeof text !== "string") return text;
const safeTokens = Array.isArray(tokens)
? tokens.filter((token) => token && token.length > 0)
: [];
if (safeTokens.length === 0) return text;
const pattern = safeTokens.map(escapeRegExp).join("|");
const regex = new RegExp(`(${pattern})`, "gi");
const parts = text.split(regex);
return parts.map((part, idx) =>
idx % 2 === 1 ? (
<span key={`highlight-${idx}`} className="tvm-highlight">
{part}
</span>
) : (
part
)
);
}
function highlightHtmlContent(html, tokens) {
if (typeof html !== "string") return html || "";
const safeTokens = Array.isArray(tokens)
? tokens.filter((token) => token && token.length > 0)
: [];
if (safeTokens.length === 0) return html;
const pattern = safeTokens.map(escapeRegExp).join("|");
if (!pattern) return html;
const regex = new RegExp(`(${pattern})`, "gi");
return html
.split(/(<[^>]+>)/g)
.map((segment) => {
if (segment.startsWith("<")) return segment;
return segment.replace(regex, '<span class="tvm-highlight">$1</span>');
})
.join("");
}
function getItemSearchFields(item) {
const aliasMnemonics = Array.isArray(item.aliases)
? item.aliases
.map((alias) => (typeof alias.mnemonic === "string" ? alias.mnemonic : ""))
.filter(Boolean)
: [];
return {
mnemonic: String(item.mnemonic || "").toLowerCase(),
opcode: String(item.opcode || "").toLowerCase(),
fift: String(item.fift || "").toLowerCase(),
aliases: aliasMnemonics.map((s) => s.toLowerCase()),
};
}
function computeFieldMatchScore(field, token) {
if (!token) return null;
if (!field) return null;
if (field === token) return 0; // exact
if (field.startsWith(token)) return 3; // prefix
if (field.includes(token)) return 7; // substring
return null; // no match
}
function computeBestAliasMatchScore(aliases, token) {
if (!Array.isArray(aliases) || aliases.length === 0) return null;
let best = null;
for (const a of aliases) {
const s = computeFieldMatchScore(a, token);
if (s === 0) return 1; // alias exact slightly worse than mnemonic exact
if (s !== null) best = best === null ? s + 1 : Math.min(best, s + 1);
}
return best;
}
function itemRelevanceScore(item, tokens) {
if (!Array.isArray(tokens) || tokens.length === 0) return 1000; // neutral when no query
const { mnemonic, opcode, fift, aliases } = getItemSearchFields(item);
let total = 0;
for (const token of tokens) {
// try fields in priority order
const scores = [
computeFieldMatchScore(mnemonic, token),
computeBestAliasMatchScore(aliases, token),
computeFieldMatchScore(opcode, token) !== null
? computeFieldMatchScore(opcode, token) + 2 // de-prioritize opcode a bit
: null,
computeFieldMatchScore(fift, token) !== null
? computeFieldMatchScore(fift, token) + 5 // fift is weakest signal
: null,
].filter((s) => s !== null);
if (scores.length === 0) return Infinity; // token didn't match any field
total += Math.min(...scores);
}
return total;
}
// Build anchor ids compatible with static MDX (slug of "<opcode> <mnemonic>"")
function buildAnchorId(instruction) {
const opcodeText = String(instruction.opcode || "").trim().toLowerCase();
const titleText = `${instruction.mnemonic}`.trim().toLowerCase();
const raw = `${opcodeText} ${titleText}`.trim();
const slug = raw
.replace(/\s+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "");
return encodeURIComponent(slug);
}
function copyAnchorUrl(anchorId) {
try {
const { location, navigator } = window;
const base = location ? `${location.origin}${location.pathname}` : "";
const url = `${base}#${anchorId}`;
if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
return navigator.clipboard.writeText(url);
}
const ta = document.createElement("textarea");
ta.value = url;
ta.setAttribute("readonly", "");
ta.style.position = "absolute";
ta.style.left = "-9999px";
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
return Promise.resolve();
} catch (err) {
return Promise.reject(err);
}
}
function copyPlainText(value) {
try {
const { navigator, document } = window;
if (navigator?.clipboard?.writeText) {
return navigator.clipboard.writeText(value);
}
const ta = document.createElement("textarea");
ta.value = value;
ta.setAttribute("readonly", "");
ta.style.position = "absolute";
ta.style.left = "-9999px";
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
return Promise.resolve();
} catch (err) {
return Promise.reject(err);
}
}
function formatAliasOperands(operands) {
return Object.entries(operands)
.map(([name, value]) => `${name}=${value}`)
.join(", ");
}
function cleanAliasDescription(html) {
if (typeof html !== "string") return "";
let output = html.trim();
if (!output) return "";
output = output.replace(/^<p>/i, "").replace(/<\/p>$/i, "");
output = output.replace(/\.+$/g, "");
return output.trim();
}
function extractImplementationRefs(implementation) {
if (!Array.isArray(implementation)) return [];
return implementation
.map((item) => {
if (!item || typeof item !== "object") return null;
const file = typeof item.file === "string" ? item.file : "";
const functionName =
typeof item.function_name === "string" ? item.function_name : "";
const line = typeof item.line === "number" ? item.line : undefined;
const path = typeof item.path === "string" ? item.path : "";
if (!file && !functionName && !path) return null;
return { file, functionName, line, path };
})
.filter(Boolean);
}
function buildGitHubLineUrl(rawUrl, line) {
if (typeof rawUrl !== "string" || !rawUrl) return "";
let url = rawUrl;
const RAW_PREFIX = "https://raw.githubusercontent.com/";
if (rawUrl.startsWith(RAW_PREFIX)) {
const parts = rawUrl.slice(RAW_PREFIX.length).split("/");
if (parts.length >= 4) {
const owner = parts[0];
const repo = parts[1];
const commit = parts[2];
const filePath = parts.slice(3).join("/");
url = `https://github.com/${owner}/${repo}/blob/${commit}/${filePath}`;
} else {
url = rawUrl.replace(RAW_PREFIX, "https://github.com/");
}
}
if (typeof line === "number" && Number.isFinite(line) && line > 0) {
url = url.split("#")[0] + `#L${line}`;
}
return url;
}
function renderControlFlowSummary(controlFlow) {
if (!controlFlow || typeof controlFlow !== "object") {
return (
<p className="tvm-missing-placeholder">
Control flow details are not available.
</p>
);
}
const branches = Array.isArray(controlFlow.branches)
? controlFlow.branches.filter(Boolean)
: [];
const nobranch = Boolean(controlFlow.nobranch);
const isContinuationObject = (value) =>
Boolean(value && typeof value === "object" && typeof value.type === "string");
const formatPrimitiveValue = (value) => {
if (value === null || value === undefined) return "";
if (Array.isArray(value)) {
return value
.map((item) => formatPrimitiveValue(item))
.filter(Boolean)
.join(", ");
}
if (typeof value === "object") {
return "";
}
if (typeof value === "boolean") {
return value ? "true" : "false";
}
return String(value);
};
const describeContinuation = (node) => {
if (!isContinuationObject(node)) {
return {
typeLabel: "unknown",
valueLabel: "?",
detailLabel: "",
text: "unknown ?",
};
}
const type = String(node.type || "").toLowerCase();
let typeLabel = "unknown";
let valueLabel = "";
switch (type) {
case "variable":
typeLabel = "var";
valueLabel = typeof node.var_name === "string" ? node.var_name : "?";
break;
case "register":
typeLabel = "register";
if (typeof node.index === "number") {
valueLabel = `c${node.index}`;
} else if (typeof node.var_name === "string") {
valueLabel = `c{${node.var_name}}`;
} else {
valueLabel = "c?";
}
break;
case "cc":
typeLabel = "cc";
valueLabel = "";
break;
case "special":
typeLabel = "special";
valueLabel = typeof node.name === "string" && node.name ? node.name : "?";
break;
default:
typeLabel = node.type ? String(node.type) : "unknown";
valueLabel = "";
break;
}
const detailParts = [];
if (type === "special") {
const args = node.args && typeof node.args === "object" ? node.args : {};
Object.entries(args).forEach(([argKey, argValue]) => {
if (!isContinuationObject(argValue)) {
const formatted = formatPrimitiveValue(argValue);
if (formatted) {
detailParts.push(`${argKey}=${formatted}`);
}
}
});
}
const knownKeys = new Set(["type", "var_name", "index", "name", "args", "save"]);
Object.entries(node).forEach(([key, value]) => {
if (knownKeys.has(key)) return;
const formatted = formatPrimitiveValue(value);
if (formatted) {
detailParts.push(`${key}=${formatted}`);
}
});
const detailLabel = detailParts.length > 0 ? `(${detailParts.join(", ")})` : "";
const text = [typeLabel, valueLabel, detailLabel]
.filter(Boolean)
.join(" ")
.replace(/\s+/g, " ")
.trim();
return { typeLabel, valueLabel, detailLabel, text };
};
const gatherChildContinuations = (node) => {
if (!isContinuationObject(node)) return [];
const type = String(node.type || "").toLowerCase();
const children = [];
const saveEntries =
node.save && typeof node.save === "object"
? Object.entries(node.save).filter(([, value]) => isContinuationObject(value))
: [];
saveEntries
.sort(([aKey], [bKey]) => aKey.localeCompare(bKey))
.forEach(([slot, value]) => {
children.push({
label: String(slot),
node: value,
});
});
if (type === "special") {
const args = node.args && typeof node.args === "object" ? node.args : {};
Object.entries(args).forEach(([argKey, argValue]) => {
if (isContinuationObject(argValue)) {
children.push({
label: argKey,
node: argValue,
});
}
});
}
return children.map((child) => {
const raw = child.label ? String(child.label) : "";
const cleaned = raw.replace(/^(arg|save)\s+/i, "").trim();
return {
label: cleaned,
node: child.node,
};
});
};
const buildContinuationTree = (node, path = "root") => {
const summary = describeContinuation(node);
const children = gatherChildContinuations(node).map((child, idx) => ({
label: child.label,
tree: buildContinuationTree(child.node, `${path}.${idx}`),
}));
return { id: path, summary, children };
};
const splitEdgeLabel = (label) => {
if (!label) {
return { primary: "", secondary: "" };
}
const text = label.trim();
if (!text) {
return { primary: "", secondary: "" };
}
const tokens = text.split(/\s+/);
if (tokens.length <= 1) {
return { primary: text, secondary: "" };
}
return {
primary: tokens[0],
secondary: tokens.slice(1).join(" "),
};
};
const computeSpan = (tree) => {
if (!tree.children || tree.children.length === 0) {
tree.span = 1;
return 1;
}
let total = 0;
tree.children.forEach((child) => {
total += computeSpan(child.tree);
});
tree.span = Math.max(total, 1);
return tree.span;
};
const H_SPACING = 200;
const V_SPACING = 110;
const NODE_HEIGHT = 42;
const NODE_MIN_WIDTH = 140;
const PADDING_X = 60;
const PADDING_Y = 60;
let canvasMeasureCtx = null;
const measureNodeWidth = (summary) => {
if (typeof document !== "undefined") {
if (!canvasMeasureCtx) {
const canvas = document.createElement("canvas");
canvasMeasureCtx = canvas.getContext("2d");
}
if (canvasMeasureCtx) {
canvasMeasureCtx.font = "600 13px 'JetBrains Mono', 'Menlo', 'Monaco', monospace";
const typeText = (summary.typeLabel || "").toUpperCase();
const parts = [typeText];
if (summary.valueLabel) parts.push(summary.valueLabel);
if (summary.detailLabel) parts.push(summary.detailLabel);
const text = parts.join(" ").trim();
const metrics = canvasMeasureCtx.measureText(text || "node");
return Math.max(metrics.width + 48, NODE_MIN_WIDTH);
}
}
const fallbackLength =
(summary.typeLabel || "").length +
(summary.valueLabel || "").length +
(summary.detailLabel || "").length;
return Math.max(fallbackLength * 7 + 48, NODE_MIN_WIDTH);
};
const assignPositions = (
tree,
nodes,
nodeMap,
edges,
depth = 0,
offsetSpan = 0
) => {
const span = Math.max(tree.span || 1, 1);
const spanWidth = span * H_SPACING;
const x = PADDING_X + offsetSpan + spanWidth / 2;
const y = PADDING_Y + depth * V_SPACING;
const width = measureNodeWidth(tree.summary);
const nodeEntry = {
id: tree.id,
summary: tree.summary,
x,
y,
width,
height: NODE_HEIGHT,
};
nodes.push(nodeEntry);
nodeMap.set(tree.id, nodeEntry);
let childOffset = offsetSpan;
tree.children.forEach((child) => {
assignPositions(child.tree, nodes, nodeMap, edges, depth + 1, childOffset);
edges.push({
from: tree.id,
to: child.tree.id,
label: child.label,
});
childOffset += Math.max(child.tree.span || 1, 1) * H_SPACING;
});
};
return (
<div>
{(branches.length > 0 || !nobranch) ? (<div><b>Falls through: </b>{nobranch ? "Yes" : "No"}</div>) : null}
{branches.length > 0 ? (
<div className="tvm-control-flow-branches">
{branches.map((branch, index) => {
const rootSummary = describeContinuation(branch);
const branchType = (rootSummary.typeLabel || "").toUpperCase();
const branchTitleText = `Branch -> ${branchType}${
rootSummary.valueLabel ? ` ${rootSummary.valueLabel}` : ""
}`;
const tree = buildContinuationTree(branch, `branch-${index}`);
computeSpan(tree);
const nodes = [];
const nodeMap = new Map();
const edges = [];
assignPositions(tree, nodes, nodeMap, edges);
let minX = Infinity;
let maxX = -Infinity;
let minY = Infinity;
let maxY = -Infinity;
nodes.forEach((node) => {
minX = Math.min(minX, node.x - node.width / 2);
maxX = Math.max(maxX, node.x + node.width / 2);
minY = Math.min(minY, node.y - node.height / 2);
maxY = Math.max(maxY, node.y + node.height / 2);
});
const shiftX = Number.isFinite(minX) ? PADDING_X - minX : 0;
const shiftY = Number.isFinite(minY) ? PADDING_Y - minY : 0;
if (shiftX || shiftY) {
nodes.forEach((node) => {
node.x += shiftX;
node.y += shiftY;
});
}
const canvasWidth = Math.max(maxX - minX + PADDING_X * 2, 260);
const canvasHeight = Math.max(maxY - minY + PADDING_Y * 2, NODE_HEIGHT + PADDING_Y * 2);
const edgeLayouts = edges
.map((edge, edgeIdx) => {
const from = nodeMap.get(edge.from);
const to = nodeMap.get(edge.to);
if (!from || !to) return null;
const fromX = from.x;
const fromY = from.y + from.height / 2;
const toX = to.x;
const toY = to.y - to.height / 2;
const midY = fromY + (toY - fromY) / 2;
const path = `M ${fromX} ${fromY} C ${fromX} ${midY}, ${toX} ${midY}, ${toX} ${toY}`;
const labelX = (fromX + toX) / 2;
const labelY = midY;
const segments = splitEdgeLabel(edge.label);
const hasSecondary = Boolean(segments.secondary);
return {
id: `${edge.from}->${edge.to}-${edgeIdx}`,
path,
labelX,
labelY,
segments,
hasSecondary,
};
})
.filter(Boolean);
return (
<div key={`branch-${index}`} className="tvm-control-flow-branch">
<div className="tvm-control-flow-branch-header">
<span className="tvm-control-flow-branch-title">
{highlightMatches(branchTitleText, searchTokens)}
</span>
</div>
<div className="tvm-flow-graph-wrapper">
<div
className="tvm-flow-canvas"
style={{
width: `${canvasWidth}px`,
height: `${canvasHeight}px`,
}}
>
<svg
className="tvm-flow-canvas-svg"
width={canvasWidth}
height={canvasHeight}
viewBox={`0 0 ${canvasWidth} ${canvasHeight}`}
preserveAspectRatio="xMinYMin meet"
>
<defs>
<marker
id="tvm-flow-arrowhead"
markerWidth="8"
markerHeight="8"
refX="6"
refY="4"
orient="auto"
markerUnits="strokeWidth"
>
<path d="M1 1 L7 4 L1 7 Z" fill="currentColor" />
</marker>
</defs>
{edgeLayouts.map((edge) => (
<path
key={`edge-path-${edge.id}`}
d={edge.path}
className="tvm-flow-graph-line"
markerEnd="url(#tvm-flow-arrowhead)"
/>
))}
</svg>
{edgeLayouts.map((edge) => (
edge.segments.primary ? (
<div
key={`edge-label-${edge.id}`}
className={`tvm-flow-edge-label${
edge.hasSecondary ? ' has-secondary' : ''
}`}
style={{
left: `${edge.labelX}px`,
top: `${edge.labelY}px`,
}}
>
<span className="tvm-flow-edge-label-primary">
{highlightMatches(edge.segments.primary.toUpperCase(), searchTokens)}
</span>
{edge.segments.secondary && (
<span className="tvm-flow-edge-label-secondary">
{highlightMatches(edge.segments.secondary.toUpperCase(), searchTokens)}
</span>
)}
</div>
) : null
))}
{nodes.map((node) => (
<div
key={node.id}
className="tvm-flow-node"
style={{
left: `${node.x}px`,
top: `${node.y}px`,
}}
>
<span
className="tvm-control-flow-node-pill"
style={{ minWidth: `${node.width}px` }}
>
<span className="tvm-control-flow-node-type">
{highlightMatches(
(node.summary.typeLabel || "").toUpperCase(),
searchTokens
)}
</span>
{node.summary.valueLabel && (
<span className="tvm-control-flow-node-value">
{highlightMatches(node.summary.valueLabel, searchTokens)}
</span>
)}
{node.summary.detailLabel && (
<span className="tvm-control-flow-node-extra">
{highlightMatches(node.summary.detailLabel, searchTokens)}
</span>
)}
</span>
</div>
))}
</div>
</div>
</div>
);
})}
</div>
) : (
<p className="tvm-detail-muted">
{nobranch
? "Instruction does not modify the current continuation."
: "Control flow branches are not documented in the specification."}
</p>
)}
</div>
);
}
function renderStackEntry(entry, key, mode) {
if (!entry) return null;
if (entry.type === "conditional") {
if (mode === "compact" || mode === "detail-inline") {
return (
<span
key={key}
className="tvm-stack-pill tvm-stack-pill--conditional"
>
Conditional: {highlightMatches(String(entry.name || "?"), searchTokens)}
</span>
);
}
return (
<div key={key} className="tvm-stack-conditional">
<span className="tvm-stack-conditional-name">
Conditional: {highlightMatches(String(entry.name || "?"), searchTokens)}
</span>
{Array.isArray(entry.match) && entry.match.length > 0 ? (
entry.match.map((matchArm, idx) => (
<div
key={`${key}-match-${idx}`}
className="tvm-stack-conditional-branch"
>
<span className="tvm-stack-conditional-label">
= {highlightMatches(String(matchArm.value ?? ""), searchTokens)}
</span>
<div className="tvm-stack-conditional-values">
{Array.isArray(matchArm.stack) &&
matchArm.stack.length > 0 ? (
matchArm.stack
.slice()
.reverse()
.map((nested, nestedIdx) =>
renderStackEntry(
nested,
`${key}-match-${idx}-item-${nestedIdx}`,
"detail-inline"
)
)
) : (
<span className="tvm-stack-pill tvm-stack-pill--empty">
Empty
</span>
)}
</div>
</div>
))
) : (
<span className="tvm-stack-pill tvm-stack-pill--empty">
Empty branches
</span>
)}
{Array.isArray(entry.else) && (
<div className="tvm-stack-conditional-branch">
<span className="tvm-stack-conditional-label">else</span>
<div className="tvm-stack-conditional-values">
{entry.else.length > 0 ? (
entry.else
.slice()
.reverse()
.map((nested, nestedIdx) =>
renderStackEntry(
nested,
`${key}-else-${nestedIdx}`,
"detail-inline"
)
)
) : (
<span className="tvm-stack-pill tvm-stack-pill--empty">
Empty
</span>
)}
</div>
</div>
)}
</div>
);
}
if (entry.type === "array") {
const label = `${entry.name || "items"}[${entry.length_var ?? ""}]`;
return (
<span key={key} className="tvm-stack-pill tvm-stack-pill--array">
{highlightMatches(label, searchTokens)}
</span>
);
}
if (entry.type === "const") {
const value =
entry.value === null
? "null"
: entry.value === undefined
? "?"
: entry.value;
return (
<span key={key} className="tvm-stack-pill tvm-stack-pill--const">
{highlightMatches(String(value), searchTokens)}: {highlightMatches(
String(entry.value_type || "Const"),
searchTokens
)}
</span>
);
}
const valueTypes =
Array.isArray(entry.value_types) && entry.value_types.length > 0
? entry.value_types.join("/")
: entry.value_type || "Any";
const label = entry.name ? `${entry.name}: ${valueTypes}` : valueTypes;
return (
<span key={key} className="tvm-stack-pill tvm-stack-pill--simple">
{highlightMatches(label, searchTokens)}
</span>
);
}
function renderStackColumn(title, items, mode = "detail") {
const safeItems = Array.isArray(items) ? items : [];
const reversed = safeItems.slice().reverse();
const limit = mode === "compact" ? 4 : reversed.length;
const shown = reversed.slice(0, limit);
const truncated = mode === "compact" && reversed.length > shown.length;
return (
<div
className={`tvm-stack-column ${
mode === "compact" ? "tvm-stack-column--compact" : ""