@henols/c64-re-tools 2.8.0-rc.1 → 2.8.0-rc.3

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.
Files changed (120) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +7 -4
  3. package/skills/c64-assembler/scripts/assembler.ts +73 -44
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +62 -31
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +28 -18
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +144 -113
  22. package/skills/c64-source/SKILL.md +6 -1
  23. package/skills/c64-source/references/loader.md +2 -1
  24. package/skills/c64-source/scripts/lib/export.ts +54 -301
  25. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  26. package/skills/c64-source/scripts/lib/source.ts +53 -45
  27. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  28. package/skills/c64-source/scripts/source.ts +134 -294
  29. package/skills/c64-static-analysis/SKILL.md +13 -7
  30. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  31. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  32. package/skills/c64-static-analysis/scripts/lib/idioms.ts +98 -19
  33. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  34. package/skills/c64-static-analysis/scripts/static-analysis.ts +249 -147
  35. package/skills/c64-testing/SKILL.md +13 -7
  36. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  37. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  38. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  39. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  40. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  41. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  42. package/skills/c64-testing/scripts/testing.ts +32 -7
  43. package/skills/c64-unpacker/SKILL.md +9 -7
  44. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  45. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  46. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  47. package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
  48. package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
  49. package/skills/emulator/SKILL.md +1 -0
  50. package/src/c64.ts +133 -10
  51. package/src/cli/ap-sdk.ts +1 -1
  52. package/src/cli/cleanup.ts +4 -2
  53. package/src/compare.ts +36 -16
  54. package/src/errors.ts +10 -1
  55. package/src/host/main.ts +2 -1
  56. package/src/host/server.ts +7 -11
  57. package/src/host/tools/c1541.ts +9 -3
  58. package/src/host/vice/adapter.ts +20 -43
  59. package/src/host/vice/binary-monitor.ts +22 -21
  60. package/src/host/vice/process.ts +31 -40
  61. package/src/host/vice/session.ts +187 -247
  62. package/src/host/vice/text-monitor.ts +3 -3
  63. package/src/host-client/autostart.ts +1 -1
  64. package/src/host-client/connect.ts +2 -1
  65. package/src/host-client/coverage.ts +0 -3
  66. package/src/host-client/entry-state.ts +4 -11
  67. package/src/host-client/image.ts +6 -11
  68. package/src/host-client/steps.ts +13 -113
  69. package/src/host-client/tools.ts +4 -4
  70. package/src/host-client/transfer.ts +10 -0
  71. package/src/host-client/vice-session.ts +10 -6
  72. package/src/knowledge/code-reach.ts +364 -0
  73. package/src/knowledge/conflicts.ts +34 -72
  74. package/src/knowledge/database.ts +40 -28
  75. package/src/knowledge/evidence.ts +2 -2
  76. package/src/knowledge/graph.ts +3 -3
  77. package/src/knowledge/history.ts +50 -90
  78. package/src/knowledge/import.ts +28 -68
  79. package/src/knowledge/join.ts +1 -1
  80. package/src/knowledge/names.ts +12 -7
  81. package/src/knowledge/program.ts +59 -72
  82. package/src/knowledge/read.ts +104 -100
  83. package/src/knowledge/schema.ts +9 -3
  84. package/src/knowledge/separate.ts +175 -80
  85. package/src/knowledge/start-screen.ts +7 -5
  86. package/src/knowledge/text.ts +56 -33
  87. package/src/knowledge/write.ts +274 -515
  88. package/src/loader.ts +7 -25
  89. package/src/mcp/inputs.ts +3 -3
  90. package/src/mcp/server.ts +19 -38
  91. package/src/mcp/session-source.ts +2 -1
  92. package/src/mcp/tools/debug.ts +97 -24
  93. package/src/mcp/tools/execution.ts +1 -1
  94. package/src/mcp/tools/input.ts +3 -3
  95. package/src/mcp/tools/machine.ts +3 -3
  96. package/src/mcp/tools/media.ts +4 -4
  97. package/src/mcp/tools/memory.ts +13 -17
  98. package/src/mcp/tools/video.ts +11 -25
  99. package/src/native/acme.ts +3 -3
  100. package/src/native/c64run.ts +2 -1
  101. package/src/native/decompiler/analyze.ts +11 -8
  102. package/src/native/decompiler/walk.ts +3 -4
  103. package/src/native/decompiler/wasm.ts +2 -2
  104. package/src/native/discover.ts +1 -1
  105. package/src/native/dxa.ts +9 -11
  106. package/src/native/exomizer.ts +1 -1
  107. package/src/native/processes.ts +4 -1
  108. package/src/native/run.ts +3 -3
  109. package/src/native/types.ts +9 -8
  110. package/src/opcodes.ts +3 -0
  111. package/src/platform.ts +9 -10
  112. package/src/program-code.ts +151 -0
  113. package/src/project.ts +8 -5
  114. package/src/protocol/framing.ts +51 -18
  115. package/src/protocol/messages.ts +1 -11
  116. package/src/protocol/tools.ts +0 -3
  117. package/src/protocol/vice.ts +588 -773
  118. package/src/script.ts +25 -23
  119. package/src/time.ts +1 -1
  120. package/src/trace.ts +3 -2
@@ -3,7 +3,9 @@
3
3
  // from current knowledge and the coverage of the knowledge, and imports the
4
4
  // structural findings into .c64-re-tools/knowledge/.
5
5
 
6
- import { COVERAGE, formatC64Address, prgRange } from "#src/c64.ts";
6
+ import type { DatabaseSync } from "node:sqlite";
7
+
8
+ import { COVERAGE, coverageEntries, coverageSeedKinds, dxaFallThrough, executedStarts, formatC64Address, formatC64Byte, formatC64RangeFields, inRanges, prgRange, rangesOverlap, romOnlyRanges } from "#src/c64.ts";
7
9
  import { isRefusal, Refusal } from "#src/errors.ts";
8
10
  import { WireFailure } from "#src/host-client/tools.ts";
9
11
  import { writeReported } from "#src/host-client/transfer.ts";
@@ -12,21 +14,22 @@ import { analyze as analyzeWithDxa } from "#src/native/dxa.ts";
12
14
  import { analyze as analyzeWithDecompiler } from "#src/native/decompiler/analyze.ts";
13
15
  import { localToolContext } from "#src/native/local.ts";
14
16
  import { DECOMPILER_LIMITS, type RefusedSeed, type SeedReport } from "#src/native/types.ts";
15
- import { openForRead, withWrite } from "#src/knowledge/database.ts";
17
+ import { openForRead, withRead, withWrite } from "#src/knowledge/database.ts";
16
18
  import { analyzedBytes, operandImages, programCoverage, requireProgram } from "#src/knowledge/program.ts";
17
19
  import { applyBatch, type BatchOperation } from "#src/knowledge/write.ts";
18
20
  import { importFindings, lastToolVersion, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
19
21
  import { currentRevision, listMacros, listMacroUses, listPatches, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
20
- import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
21
- import { platformNames, platformNamesFor, romUseOfProgram, type RomUse } from "#src/platform.ts";
22
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
23
+ import { platformAddresses, platformNames, platformNamesFor, romUseOfProgram, type RomUse } from "#src/platform.ts";
22
24
  import { listed, OPTIONS, reply, runScript, UsageError, type Call } from "#src/script.ts";
23
- import { codeEntries, coverageConflicts, coverageEntries, coverageSeedKinds, executedStarts, imageReader, romOnlyRanges, writtenNotExecuted, explainGaps, type GapReason, type ImageByte } from "./lib/coverage.ts";
24
- import { dxaFindings, decompilerFindings, seedsFromKnowledge } from "./lib/findings.ts";
25
+ import { codeEntries, coverageConflicts, imageReader, writtenNotExecuted, explainGaps, type GapReason, type ImageByte } from "./lib/coverage.ts";
26
+ import { decidedFromKnowledge, dxaFindings, decompilerFindings, seedsFromKnowledge } from "./lib/findings.ts";
25
27
  import { findIdioms } from "./lib/idioms.ts";
26
28
  import { instructionList } from "./lib/instructions.ts";
27
29
  import { CATALOGUE, findMacroUses, type MacroCandidate } from "./lib/macros.ts";
28
30
  import { findPitfalls, type Pitfall } from "./lib/pitfalls.ts";
29
31
  import { findPointers, type PointerCandidate } from "./lib/pointers.ts";
32
+ import { flowFromExecuted, rangeFacts, type RangeFacts } from "./lib/triage.ts";
30
33
 
31
34
  /** The rest of a cut label or function list: the knowledge has all of them as analyzer names. */
32
35
  const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them as analyzer names";
@@ -38,16 +41,29 @@ const ALL_REGIONS = "a larger --max-listed. The project knowledge has all of the
38
41
  * analyzer data over executed code to classify, and macro candidates to write.
39
42
  * The envelope adds the sentence for a cut list.
40
43
  */
41
- function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }, version: { now: string | undefined; last: string | undefined; revision: string | null }, retiredReferences: number, guards: { refused: number; writtenNotExecuted: number }) {
44
+ function withHint(
45
+ body: Record<string, unknown>,
46
+ facts: {
47
+ conflicts: number;
48
+ coverageConflicts: number;
49
+ macros: { candidates: number; applied: boolean; revision: string | null | undefined };
50
+ version: { now: string | undefined; last: string | undefined; revision: string | null };
51
+ retiredReferences: number;
52
+ guards: { refused: number; writtenNotExecuted: number };
53
+ cut: Cut;
54
+ },
55
+ ) {
56
+ const { conflicts, coverageConflicts, macros, version, retiredReferences, guards, cut } = facts;
42
57
  const hints: string[] = [];
43
- if (guards.refused > 0) hints.push(`The analysis did not decode ${guards.refused} of its seeds: seeds.refused gives each one with its reason. A seed inside an instruction or in data is often a wrong routine or region in the project knowledge. Examine it in the listing, and correct the project knowledge.`);
58
+ if (cut.entryPoints.length + cut.codeStarts.length + cut.dataRanges.length > 0) hints.push(overLimitHint(cut));
59
+ if (guards.refused > 0) hints.push(`The analysis did not decode ${guards.refused} seeds in the program or of --entry: seeds.refused gives each refused seed with its reason. A seed inside an instruction or in data is often a wrong routine or region in the project knowledge. Examine it in the listing, and correct the project knowledge.`);
44
60
  if (guards.writtenNotExecuted > 0) hints.push("Each range in writtenNotExecuted is code of the analyzer on bytes that the runs wrote and never executed. Its from gives the instructions that reach it. Examine the routine that holds them: a wrong entry point leads the analyzer into data. Correct the project knowledge, and run the analysis again.");
45
61
  if (version.revision !== null && version.now !== undefined && version.last !== undefined && version.now !== version.last) {
46
62
  hints.push(`The last analysis of this program used ${version.last}. Thus a change in revision ${version.revision} can come from the new analyzer version, and not from the program or the project knowledge.`);
47
63
  }
48
64
  // A leftover is data that no reference reads: a retired reference can make one.
49
65
  if (retiredReferences > 0) hints.push("The analysis retired references. A data range that only a retired reference used can be a leftover now. Generate the source again, and examine the leftovers that changed.");
50
- if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Find the correct answer in the emulator. Then correct the project knowledge.");
66
+ if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Use access, references and reachable of each conflict. Code that a run executed is code. A range that static flow reaches and that no run executed is usually code on a branch that no run took. A range that no flow reaches and that a run read or wrote is usually data. If these facts do not decide, find the answer in the emulator. Then correct the project knowledge.");
51
67
  if (coverageConflicts > 0) hints.push("The coverage shows executed code in each range of coverageConflicts. Classify each range as code, or as dual-use when its bytes are also data, in the project knowledge.");
52
68
  if (typeof macros.revision === "string") hints.push("The project knowledge has the macro candidates now. Generate the source again.");
53
69
  else if (!macros.applied && macros.candidates > 0) hints.push("Examine idioms.candidates.macros. To write them to the project knowledge, run the analysis again with --apply-macros.");
@@ -55,6 +71,37 @@ function withHint(body: Record<string, unknown>, conflicts: number, coverageConf
55
71
  return reply(body, { hint: hints.join(" ") });
56
72
  }
57
73
 
74
+ /** The seeds over the limits of the analyzer. */
75
+ interface Cut {
76
+ analyzer: Analyzer;
77
+ entryPoints: readonly number[];
78
+ codeStarts: readonly number[];
79
+ dataRanges: ReadonlyArray<{ start: number; end: number }>;
80
+ }
81
+
82
+ /**
83
+ * What the analyzer did not get because of its limits, and why its findings
84
+ * there are not facts about the program. A routine in the knowledge or an
85
+ * --entry does not help: it is a seed too, and it puts another seed over the limit.
86
+ */
87
+ function overLimitHint(cut: Cut): string {
88
+ const span = (kind: string, ranges: ReadonlyArray<{ start: number; end: number }>) =>
89
+ ranges.length === 0 ? [] : [`${ranges.length} ${kind} from ${formatC64Address(Math.min(...ranges.map((range) => range.start)))} to ${formatC64Address(Math.max(...ranges.map((range) => range.end)))}`];
90
+ const at = (addresses: readonly number[]) => addresses.map((address) => ({ start: address, end: address }));
91
+ const parts = [...span("entry points", at(cut.entryPoints)), ...span("code starts", at(cut.codeStarts)), ...span("data ranges", cut.dataRanges)];
92
+ const decompiler = cut.analyzer === "dxa" && cut.entryPoints.length > 0 ? ` The decompiler takes the coverage starts as code starts, at most ${DECOMPILER_LIMITS.codeStarts}: use its findings at these addresses.` : "";
93
+ return `The analyzer did not get all seeds: they are over its limits (seeds.overLimit). It did not get ${parts.join(", ")}. Thus a finding or a conflict at these addresses can come from this cut, and not from the program. Do not correct the project knowledge for such a finding.${decompiler}`;
94
+ }
95
+
96
+ /**
97
+ * The refused seeds that can be a fault of the project knowledge: a routine
98
+ * outside the program can be code that the program copies there when it
99
+ * runs, so only an --entry outside the program counts.
100
+ */
101
+ function toCorrect(refused: readonly RefusedSeed[], entries: readonly number[]): number {
102
+ return refused.filter((seed) => seed.reason !== "outside-program" || entries.includes(seed.address)).length;
103
+ }
104
+
58
105
  /** A refused seed with $ addresses. */
59
106
  function showRefused(seed: RefusedSeed) {
60
107
  return { address: formatC64Address(seed.address), reason: seed.reason, ...(seed.at === undefined ? {} : { at: formatC64Address(seed.at) }) };
@@ -69,21 +116,10 @@ function seedsResult(given: Record<string, number>, overLimit: Record<string, nu
69
116
  ...given,
70
117
  ...(Object.keys(over).length === 0 ? {} : { overLimit: over }),
71
118
  ...(report.refused.length === 0 ? {} : { refused: { ...listed(report.refused, max, showRefused), byReason } }),
72
- ...(report.dataRangesLeftOut.length === 0 ? {} : { dataRangesLeftOut: listed(report.dataRangesLeftOut, max, (range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end), code: formatC64Address(range.code) })) }),
119
+ ...(report.dataRangesLeftOut.length === 0 ? {} : { dataRangesLeftOut: listed(report.dataRangesLeftOut, max, (range) => ({ ...formatC64RangeFields(range), code: formatC64Address(range.code) })) }),
73
120
  };
74
121
  }
75
122
 
76
- /** The code regions of the analyzer on bytes that the runs wrote and never executed, from the knowledge after the import. */
77
- function writtenNotExecutedOf(analyzer: Analyzer, space: string, coverage: Uint8Array | undefined) {
78
- if (coverage === undefined) return [];
79
- const db = openForRead();
80
- try {
81
- return writtenNotExecuted(db, analyzer, coverage, space);
82
- } finally {
83
- db?.close();
84
- }
85
- }
86
-
87
123
  /** A pitfall with $ addresses and what goes wrong. */
88
124
  function showPitfall(pitfall: Pitfall) {
89
125
  return {
@@ -97,7 +133,7 @@ function showPitfall(pitfall: Pitfall) {
97
133
  /** A pointer candidate with $ addresses, and the operand writes that would name it. */
98
134
  function showPointer(candidate: PointerCandidate) {
99
135
  if (candidate.kind === "sprite pointer") {
100
- return { kind: candidate.kind, at: formatC64Address(candidate.at), to: formatC64Address(candidate.to), value: `$${candidate.value.toString(16).padStart(2, "0")}`, target: formatC64Address(candidate.target), assumes: "VIC bank 0 and the screen at $0400" };
136
+ return { kind: candidate.kind, at: formatC64Address(candidate.at), to: formatC64Address(candidate.to), value: formatC64Byte(candidate.value), target: formatC64Address(candidate.target), assumes: "VIC bank 0 and the screen at $0400" };
101
137
  }
102
138
  return { kind: candidate.kind, to: formatC64Address(candidate.to), target: formatC64Address(candidate.target), low: formatC64Address(candidate.low), high: formatC64Address(candidate.high) };
103
139
  }
@@ -117,53 +153,82 @@ function showMacro(candidate: MacroCandidate) {
117
153
  * candidates that start at an address of `skip`. A macro of the catalogue that
118
154
  * the knowledge has with another body leaves its candidates out of the writes.
119
155
  */
120
- function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse, skip: ReadonlySet<number>) {
121
- const db = openForRead();
122
- try {
123
- // The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
124
- const platform = space === DEFAULT_SPACE ? new Map(platformNamesFor(romUse).map((entry) => [entry.address, entry.name])) : new Map<number, string>();
125
- const semantic = new Map(listSymbols(db, undefined, undefined, [...SEMANTIC_ORIGINS], space).map((symbol) => [symbol.address, symbol.name]));
126
- const code = listRegions(db, undefined, "code", undefined, space);
127
- const found = findMacroUses(byteAt, code, (address) => semantic.get(address) ?? platform.get(address));
128
- const named = new Set([...listSymbols(db, undefined, undefined, undefined, space).map((symbol) => symbol.address), ...listReferences(db, undefined, undefined, undefined, space).map((reference) => reference.to)]);
129
- const patches = listPatches(db, undefined, undefined, undefined, space);
130
- const uses = listMacroUses(db, undefined, undefined, undefined, space);
131
- const overlaps = (a: { start: number; end: number }, b: { start: number; end: number }) => a.start <= b.end && b.start <= a.end;
132
- const candidates: MacroCandidate[] = [];
133
- let known = 0;
134
- let leftOut = 0;
135
- for (const candidate of found) {
136
- const same = uses.find((use) => use.start === candidate.start && use.end === candidate.end && use.macro === candidate.macro && use.args.join(",") === candidate.args.join(","));
137
- if (same !== undefined) known++;
138
- else if ([...named].some((address) => address > candidate.start && address <= candidate.end) || patches.some((patch) => overlaps(patch, candidate)) || uses.some((use) => overlaps(use, candidate))) leftOut++;
139
- else candidates.push(candidate);
140
- }
141
- // A macro of the catalogue goes into the writes unless the knowledge has it; with another body, its uses stay out.
142
- const macros = new Map(listMacros(db, undefined, space).map((macro) => [macro.name, macro]));
143
- const writes: BatchOperation[] = [];
144
- const other = new Set<string>();
145
- const chosen = candidates.filter((candidate) => !skip.has(candidate.start));
146
- for (const idiom of CATALOGUE.filter((item) => chosen.some((candidate) => candidate.macro === item.name))) {
147
- const existing = macros.get(idiom.name);
148
- if (existing === undefined) writes.push({ op: "macro", space, name: idiom.name, params: [...idiom.params], body: idiom.body, comment: idiom.comment });
149
- else if (existing.params.join(",") !== idiom.params.join(",") || existing.body !== idiom.body) other.add(idiom.name);
150
- }
151
- for (const candidate of chosen) {
152
- if (other.has(candidate.macro)) continue;
153
- writes.push({ op: "use", space, start: candidate.start, end: candidate.end, macro: candidate.macro, args: candidate.args });
154
- }
155
- const notCandidates = [...skip].filter((address) => !candidates.some((candidate) => candidate.start === address)).sort((a, b) => a - b);
156
- return { candidates, known, leftOut, writes, skipped: candidates.length - chosen.length, notCandidates, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
157
- } finally {
158
- db?.close();
156
+ function macroCandidates(db: DatabaseSync | undefined, space: string, byteAt: ImageByte, romUse: RomUse, skip: ReadonlySet<number>) {
157
+ // The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
158
+ const platform = space === DEFAULT_SPACE ? new Map(platformNamesFor(romUse).map((entry) => [entry.address, entry.name])) : new Map<number, string>();
159
+ const semantic = new Map(listSymbols(db, undefined, undefined, [...SEMANTIC_ORIGINS], space).map((symbol) => [symbol.address, symbol.name]));
160
+ const code = listRegions(db, undefined, "code", undefined, space);
161
+ const found = findMacroUses(byteAt, code, (address) => semantic.get(address) ?? platform.get(address));
162
+ const named = new Set([...listSymbols(db, undefined, undefined, undefined, space).map((symbol) => symbol.address), ...listReferences(db, undefined, undefined, undefined, space).map((reference) => reference.to)]);
163
+ const patches = listPatches(db, undefined, undefined, undefined, space);
164
+ const uses = listMacroUses(db, undefined, undefined, undefined, space);
165
+ const candidates: MacroCandidate[] = [];
166
+ let known = 0;
167
+ let leftOut = 0;
168
+ for (const candidate of found) {
169
+ const same = uses.find((use) => use.start === candidate.start && use.end === candidate.end && use.macro === candidate.macro && use.args.join(",") === candidate.args.join(","));
170
+ if (same !== undefined) known++;
171
+ else if ([...named].some((address) => address > candidate.start && address <= candidate.end) || patches.some((patch) => rangesOverlap(patch, candidate)) || uses.some((use) => rangesOverlap(use, candidate))) leftOut++;
172
+ else candidates.push(candidate);
173
+ }
174
+ // A macro of the catalogue goes into the writes unless the knowledge has it; with another body, its uses stay out.
175
+ const macros = new Map(listMacros(db, undefined, space).map((macro) => [macro.name, macro]));
176
+ const writes: BatchOperation[] = [];
177
+ const other = new Set<string>();
178
+ const chosen = candidates.filter((candidate) => !skip.has(candidate.start));
179
+ for (const idiom of CATALOGUE.filter((item) => chosen.some((candidate) => candidate.macro === item.name))) {
180
+ const existing = macros.get(idiom.name);
181
+ if (existing === undefined) writes.push({ op: "macro", space, name: idiom.name, params: [...idiom.params], body: idiom.body, comment: idiom.comment });
182
+ else if (existing.params.join(",") !== idiom.params.join(",") || existing.body !== idiom.body) other.add(idiom.name);
159
183
  }
184
+ for (const candidate of chosen) {
185
+ if (other.has(candidate.macro)) continue;
186
+ writes.push({ op: "use", space, start: candidate.start, end: candidate.end, macro: candidate.macro, args: candidate.args });
187
+ }
188
+ const notCandidates = [...skip].filter((address) => !candidates.some((candidate) => candidate.start === address)).sort((a, b) => a - b);
189
+ return { candidates, known, leftOut, writes, skipped: candidates.length - chosen.length, notCandidates, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
190
+ }
191
+
192
+ /** The facts of a range with $ addresses; the references are a list that --max-listed cuts. */
193
+ function showFacts(facts: RangeFacts, max: number) {
194
+ return {
195
+ ...(facts.access === undefined ? {} : { access: facts.access }),
196
+ references: listed(facts.references, max, (reference) => ({ from: formatC64Address(reference.from), kind: reference.kind })),
197
+ ...(facts.reachable === undefined ? {} : { reachable: facts.reachable }),
198
+ };
199
+ }
200
+
201
+ /** A conflict of code and data, with the facts of its range; a conflict that evidence decided, or of a name, has no facts. */
202
+ function showConflictFacts(conflict: ImportConflict, analyzer: Analyzer, factsOf: (range: { start: number; end: number }) => RangeFacts, max: number): Record<string, unknown> {
203
+ const shown = showConflict(conflict, analyzer);
204
+ if (conflict.category === "region") return { ...shown, ...showFacts(factsOf(conflict), max) };
205
+ if (conflict.category === "symbol" && conflict.reason === "kind") return { ...shown, ...showFacts(factsOf({ start: conflict.address, end: conflict.address }), max) };
206
+ return shown;
207
+ }
208
+
209
+ /**
210
+ * The facts of the ranges of the conflicts, from the knowledge after both
211
+ * imports: the coverage, the references, and the flow from executed code
212
+ * through the program, which ends in data of the user or the LLM.
213
+ */
214
+ function conflictFacts(db: DatabaseSync | undefined, space: string, memory: Uint8Array, inImage: (address: number) => boolean, coverage: Uint8Array | undefined): (range: { start: number; end: number }) => RangeFacts {
215
+ const references = listReferences(db, undefined, undefined, undefined, space);
216
+ const data = listRegions(db, undefined, undefined, [...SEMANTIC_ORIGINS], space).filter((region) => !CODE_REGION_TYPES.includes(region.type) && region.type !== "dual-use");
217
+ const isData = (address: number) => data.some((region) => address >= region.start && address <= region.end);
218
+ const { removedReference } = decidedFromKnowledge(db, space);
219
+ // The flow is computed only when a conflict asks for it.
220
+ let flow: Set<number> | undefined;
221
+ return (range) => {
222
+ if (coverage !== undefined) flow ??= flowFromExecuted({ memory, inImage, coverage, references, isData, removedReference });
223
+ return rangeFacts(coverage, references, flow)(range);
224
+ };
160
225
  }
161
226
 
162
227
  /** One conflict: what the knowledge has, and what the analyzer found, under the analyzer's name. */
163
228
  function showConflict(conflict: ImportConflict, analyzer: Analyzer): Record<string, unknown> {
164
229
  if (conflict.category === "code-evidence") {
165
230
  return {
166
- range: { start: formatC64Address(conflict.start), end: formatC64Address(conflict.end) },
231
+ range: formatC64RangeFields(conflict),
167
232
  [analyzer]: conflict.finding,
168
233
  ...(conflict.executed === undefined ? {} : { executed: formatC64Address(conflict.executed) }),
169
234
  ...(conflict.symbol === undefined ? {} : { knowledge: { ...conflict.symbol, address: formatC64Address(conflict.symbol.address) } }),
@@ -179,7 +244,7 @@ function showConflict(conflict: ImportConflict, analyzer: Analyzer): Record<stri
179
244
  };
180
245
  }
181
246
  return {
182
- range: { start: formatC64Address(conflict.start), end: formatC64Address(conflict.end) },
247
+ range: formatC64RangeFields(conflict),
183
248
  knowledge: conflict.current,
184
249
  [analyzer]: conflict.finding,
185
250
  problem: "code and data disagree",
@@ -203,8 +268,8 @@ function record(findings: NormalizedFindings, revision: string, description: str
203
268
  }
204
269
  return {
205
270
  revision: imported.revision,
206
- changes: { names: imported.names, ...(imported.symbols.retired === 0 ? {} : { symbols: { retired: imported.symbols.retired } }), regions: imported.regions, references: imported.references },
207
- conflicts: imported.conflicts.map((conflict) => showConflict(conflict, findings.analyzer)),
271
+ changes: { names: imported.names, regions: imported.regions, references: imported.references },
272
+ conflicts: imported.conflicts,
208
273
  };
209
274
  }
210
275
 
@@ -231,65 +296,72 @@ async function analyze(call: Call): Promise<unknown> {
231
296
  const { bytes, kind: imageKind } = analyzedBytes(program);
232
297
  // The analyzer sees all bytes it gets; the coverage seeds only the program, as c64-source does.
233
298
  const byteAt = imageReader(bytes, imageKind);
234
- const inProgram: ImageByte = (address) => (program.segments.some((segment) => address >= segment.start && address <= segment.end) ? program.byteAt(address) : undefined);
299
+ const inProgram: ImageByte = (address) => (inRanges(program.segments, address) ? program.byteAt(address) : undefined);
235
300
  // With coverage, a code finding over an executed instruction start replaces the data of the other analyzer.
236
301
  const executed = coverage === undefined ? {} : { executed: (address: number) => (coverage[address]! & COVERAGE.ramExecute) !== 0 };
237
302
  const loaded = imageKind === "flat64k" ? { start: 0x0000, end: 0xffff } : prgRange(bytes);
238
303
  // The idioms read only the program: a table that runs past a segment gets no targets from the 0 bytes of the 64 KiB.
239
- const idioms = findIdioms(inProgram, { start: loaded.start, end: loaded.end }, covered);
304
+ // The regions and the removals of the user and the LLM win over the idioms.
305
+ const idioms = findIdioms(inProgram, { start: loaded.start, end: loaded.end }, covered, decidedFromKnowledge(reader, space));
240
306
 
241
307
  const revision = currentRevision(reader);
242
308
  const seeds = seedsFromKnowledge(reader, entries, space, executed.executed);
243
- // Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound:
244
- // at most DECOMPILER_LIMITS.entryPoints (1024) entry points for both analyzers, and for the decompiler at most
245
- // DECOMPILER_LIMITS.codeStarts (8192) coverage flow starts that are code in a routine. coverageSeeds gives what was used.
246
309
  const fromCoverage = coverage === undefined ? [] : coverageEntries(coverage, inProgram);
247
310
  const known = [...seeds.entryPoints, ...codeEntries(reader, byteAt, space)];
248
- // The decompiler takes the coverage as code starts without a function; DXA has one list.
249
- const kinds = analyzer === "dxa" || coverage === undefined ? { routines: fromCoverage, codeStarts: [] } : coverageSeedKinds(coverage, inProgram);
250
- const ordered = [...new Set([...known, ...idioms.entryPoints, ...kinds.routines])];
251
- seeds.entryPoints = ordered.slice(0, DECOMPILER_LIMITS.entryPoints).sort((a, b) => a - b);
252
- const allCodeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry));
253
- const codeStarts = allCodeStarts.slice(0, DECOMPILER_LIMITS.codeStarts);
254
311
  // Idiom tables and the RAM under ROM that the runs never used are data for this run too; semantic data ranges come first.
255
312
  // A range with an entry point of the knowledge or --entry in it is left out: that code stays code.
256
313
  const fromRom = coverage === undefined ? [] : romOnlyRanges(coverage, byteAt).filter((range) => !known.some((entry) => entry >= range.start && entry <= range.end));
257
314
  const dataRanges = [...seeds.dataRanges];
258
315
  for (const range of [...idioms.dataRanges, ...fromRom]) if (!dataRanges.some((seed) => range.start <= seed.end && range.end >= seed.start)) dataRanges.push(range);
259
316
  seeds.dataRanges = dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges);
317
+ // Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound:
318
+ // at most DECOMPILER_LIMITS.entryPoints (1024) entry points for both analyzers, and for the decompiler at most
319
+ // DECOMPILER_LIMITS.codeStarts (8192) coverage flow starts that are code in a routine. coverageSeeds gives what was used.
320
+ // The decompiler takes the coverage as code starts without a function. DXA has one list, without the coverage starts
321
+ // that it reaches by fall-through from another seed, for example the instruction after a JSR.
322
+ const fallThrough = (from: readonly number[]) => (coverage === undefined ? new Set<number>() : dxaFallThrough(from, coverage, inProgram, seeds.dataRanges));
323
+ const reached = analyzer === "dxa" ? fallThrough([...known, ...idioms.entryPoints, ...fromCoverage]) : new Set<number>();
324
+ const kinds = analyzer === "dxa" || coverage === undefined ? { routines: fromCoverage.filter((entry) => !reached.has(entry)), codeStarts: [] } : coverageSeedKinds(coverage, inProgram);
325
+ const ordered = [...new Set([...known, ...idioms.entryPoints, ...kinds.routines])];
326
+ seeds.entryPoints = ordered.slice(0, DECOMPILER_LIMITS.entryPoints).sort((a, b) => a - b);
327
+ const allCodeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry));
328
+ const codeStarts = allCodeStarts.slice(0, DECOMPILER_LIMITS.codeStarts);
260
329
  // The seeds over the limits of the analyzer: it never sees them.
261
- const overLimit = { entryPoints: Math.max(0, ordered.length - DECOMPILER_LIMITS.entryPoints), codeStarts: allCodeStarts.length - codeStarts.length, dataRanges: Math.max(0, dataRanges.length - DECOMPILER_LIMITS.dataRanges) };
330
+ const cut = { analyzer, entryPoints: ordered.slice(DECOMPILER_LIMITS.entryPoints), codeStarts: allCodeStarts.slice(DECOMPILER_LIMITS.codeStarts), dataRanges: dataRanges.slice(DECOMPILER_LIMITS.dataRanges) };
331
+ const overLimit = { entryPoints: cut.entryPoints.length, codeStarts: cut.codeStarts.length, dataRanges: cut.dataRanges.length };
262
332
  const romUsed = fromRom.filter((range) => seeds.dataRanges.includes(range)).length;
263
- const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry)).length;
333
+ // DXA also decodes a coverage start that it did not get, when a seed that it got reaches the start by fall-through.
334
+ const followed = analyzer === "dxa" ? fallThrough(seeds.entryPoints) : new Set<number>();
335
+ const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry) || followed.has(entry)).length;
264
336
  // Platform names are C64 names: drive code and banks get none.
265
337
  const platform = space === DEFAULT_SPACE ? platformNames() : [];
266
338
  /** The analyzer version of the last analysis of these bytes: a new version can change the findings by itself. */
267
339
  const lastVersion = reader === undefined ? undefined : lastToolVersion(reader, analyzer, bytes);
268
340
  reader?.close();
269
- /** Imports the idioms as their own revision, after the analyzer's, and gives their part of the result. */
270
- const idiomsResult = () => {
271
- const imported = withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
341
+ /** Imports the idioms as their own revision, after the analyzer's. */
342
+ const importIdioms = () => withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
343
+ /** The idioms part of a result, from the knowledge after both imports. */
344
+ const idiomsResult = (db: DatabaseSync | undefined, imported: ImportResult) => {
272
345
  // The macro candidates read the code regions after both imports.
273
- const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state), skip);
274
- // With --apply-macros, the candidates and their macros are a third revision of the LLM.
275
- const platformNamed = new Map(platformNames().map((entry) => [entry.name, entry.address]));
276
- const written = applyMacros && macros.writes.length > 0 ? withWrite((db) => applyBatch(db, { origin: "llm", description: "Macro candidates in the program", image: operandImages(db, platformNamed) }, macros.writes)) : undefined;
346
+ const macros = macroCandidates(db, space, byteAt, romUseOfProgram(coverage, program.state), skip);
347
+ // With --apply-macros, the candidates and their macros are a third revision of the LLM. It writes only macros and their uses, which the reads below do not read.
348
+ const written = applyMacros && macros.writes.length > 0 ? withWrite((write) => applyBatch(write, { origin: "llm", description: "Macro candidates in the program", image: operandImages(write, platformAddresses()) }, macros.writes)) : undefined;
277
349
  // Platform pitfalls are C64 facts: drive code and banks get none. Pitfalls and pointers read the code regions after both imports.
278
- const codeDb = openForRead();
279
- const code = listRegions(codeDb, undefined, "code", undefined, space);
350
+ const code = listRegions(db, undefined, "code", undefined, space);
280
351
  const pitfalls = space === DEFAULT_SPACE ? findPitfalls(byteAt, code) : [];
281
352
  const pointers = findPointers(byteAt, { start: loaded.start, end: loaded.end }, code, {
282
353
  platform: (address) => platform.some((entry) => address >= entry.address && address <= entry.end),
283
- sprites: listRegions(codeDb, undefined, "sprite", undefined, space),
354
+ sprites: listRegions(db, undefined, "sprite", undefined, space),
284
355
  });
285
- codeDb?.close();
356
+ const factsOf = conflictFacts(db, space, program.memory, (address) => inProgram(address) !== undefined, coverage);
286
357
  return {
358
+ factsOf,
287
359
  idioms: {
288
360
  ...idioms.counts,
289
361
  revision: imported.revision,
290
362
  changes: { regions: imported.regions, references: imported.references },
291
- conflicts: imported.conflicts.map((conflict) => showConflict(conflict, "heuristic")),
292
- ...(idioms.leftOut.length === 0 ? {} : { leftOut: listed(idioms.leftOut, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), kind: item.kind, reason: item.reason })) }),
363
+ conflicts: imported.conflicts.map((conflict) => showConflictFacts(conflict, "heuristic", factsOf, max)),
364
+ ...(idioms.leftOut.length === 0 ? {} : { leftOut: listed(idioms.leftOut, max, (item) => ({ ...formatC64RangeFields(item), kind: item.kind, reason: item.reason })) }),
293
365
  // Candidates are not knowledge: a larger --max-listed gives more of them.
294
366
  candidates: {
295
367
  dop: listed(idioms.candidates.dop, max, formatC64Address, "a larger --max-listed"),
@@ -310,21 +382,53 @@ async function analyze(call: Call): Promise<unknown> {
310
382
  };
311
383
  };
312
384
  /** The coverage part of a result: its seeds, and the analyzer data that it shows to be code. */
313
- const coverageResult = () => {
385
+ const coverageResult = (db: DatabaseSync | undefined) => {
314
386
  if (coverage === undefined) return {};
315
- const db = openForRead();
316
387
  const conflicts = coverageConflicts(db, coverage);
317
- db?.close();
318
388
  return {
319
389
  coverageSeeds: { entryPoints: fromCoverage.length, used: coverageUsed, romOnlyRanges: fromRom.length, romOnlyUsed: romUsed },
320
390
  coverageConflicts: conflicts.map(({ region, executed }) => ({
321
- range: { start: formatC64Address(region.start), end: formatC64Address(region.end) },
391
+ range: formatC64RangeFields(region),
322
392
  knowledge: { type: region.type, origin: region.origin },
323
393
  executed,
324
394
  problem: "coverage shows code",
325
395
  })),
326
396
  };
327
397
  };
398
+ /**
399
+ * The result from the knowledge after both imports: the fields of both
400
+ * analyzers around the fields that only one gives (`gaps` after the
401
+ * coverage, `tail` after the idioms), and the hint.
402
+ */
403
+ const resultOf = (
404
+ db: DatabaseSync | undefined,
405
+ run: { toolVersion: string | undefined; imported: ReturnType<typeof record>; report: SeedReport; seeds: ReturnType<typeof seedsResult>; found: ReturnType<typeof idiomsResult>; gaps?: Record<string, unknown>; tail: Record<string, unknown> },
406
+ ) => {
407
+ const runOnWritten = coverage === undefined ? [] : writtenNotExecuted(db, analyzer, coverage, space);
408
+ const { factsOf, ...found } = run.found;
409
+ const body = {
410
+ analyzer,
411
+ ...(run.toolVersion === undefined ? {} : { analyzerVersion: run.toolVersion }),
412
+ ...(space === DEFAULT_SPACE ? {} : { space }),
413
+ ...run.imported,
414
+ conflicts: run.imported.conflicts.map((conflict) => showConflictFacts(conflict, analyzer, factsOf, max)),
415
+ seeds: run.seeds,
416
+ ...coverageResult(db),
417
+ ...run.gaps,
418
+ ...(runOnWritten.length === 0 ? {} : { writtenNotExecuted: listed(runOnWritten, max, showWritten) }),
419
+ ...found,
420
+ ...run.tail,
421
+ };
422
+ return withHint(body, {
423
+ conflicts: run.imported.conflicts.length + found.idioms.conflicts.length,
424
+ coverageConflicts: body.coverageConflicts?.length ?? 0,
425
+ macros: { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision },
426
+ version: { now: run.toolVersion, last: lastVersion, revision: run.imported.revision },
427
+ retiredReferences: run.imported.changes.references.retired,
428
+ guards: { refused: toCorrect(run.report.refused, entries), writtenNotExecuted: runOnWritten.length },
429
+ cut,
430
+ });
431
+ };
328
432
  if (analyzer === "dxa") {
329
433
  const { result, attachments, seeds: report } = await analyzeWithDxa({ imageKind, ...seeds }, bytes, localToolContext());
330
434
  const listing = attachments[0]!.toString("utf8");
@@ -339,72 +443,70 @@ async function analyze(call: Call): Promise<unknown> {
339
443
  throw new WireFailure(isRefusal(error) ? error.code : "operation-failed", `The script did not write the listing to ${listingPath}: ${(error as Error).message.replace(/\.$/, "")}. ${recorded}`);
340
444
  }
341
445
  }
342
- const found = idiomsResult();
343
- const runOnWritten = writtenNotExecutedOf("dxa", space, coverage);
344
- const body = {
345
- analyzer: "dxa",
346
- ...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
347
- ...(space === DEFAULT_SPACE ? {} : { space }),
348
- ...imported,
349
- seeds: seedsResult({ entryPoints: seeds.entryPoints.length, dataRanges: seeds.dataRanges.length }, { entryPoints: overLimit.entryPoints, dataRanges: overLimit.dataRanges }, report, max),
350
- ...coverageResult(),
351
- ...(runOnWritten.length === 0 ? {} : { writtenNotExecuted: listed(runOnWritten, max, showWritten) }),
352
- ...found,
353
- coverage: result.coverage.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
354
- regions: listed(result.regions, max, (region) => ({ start: formatC64Address(region.start), end: formatC64Address(region.end), classification: region.classification }), ALL_REGIONS),
355
- labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
356
- ...(written === undefined ? {} : { listing: written }),
357
- };
358
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired, { refused: report.refused.length, writtenNotExecuted: runOnWritten.length });
446
+ const idiomsImported = importIdioms();
447
+ return withRead((db) =>
448
+ resultOf(db, {
449
+ toolVersion: result.toolVersion,
450
+ imported,
451
+ report,
452
+ seeds: seedsResult({ entryPoints: seeds.entryPoints.length, dataRanges: seeds.dataRanges.length }, { entryPoints: overLimit.entryPoints, dataRanges: overLimit.dataRanges }, report, max),
453
+ found: idiomsResult(db, idiomsImported),
454
+ tail: {
455
+ coverage: result.coverage.map(formatC64RangeFields),
456
+ regions: listed(result.regions, max, (region) => ({ ...formatC64RangeFields(region), classification: region.classification }), ALL_REGIONS),
457
+ labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
458
+ ...(written === undefined ? {} : { listing: written }),
459
+ },
460
+ }),
461
+ );
359
462
  }
360
463
 
361
464
  const { result, seeds: report } = await analyzeWithDecompiler({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
362
465
  // Executed instruction starts that the decompiler did not decode: the instruction list and the source miss them.
363
466
  const decoded = new Set(result.instructions.map((instruction) => instruction.address));
364
467
  const imported = record({ ...decompilerFindings(result), space, ...executed }, revision, "Decompiler analysis of the program", runProvenance(bytes, result.toolVersion));
365
- const found = idiomsResult();
366
- // A start inside a dual-use region is a known overlap, for example the second instruction of a BIT skip: one list cannot hold both.
367
- // Read after the idioms, which write those regions.
368
- const overlapDb = coverage === undefined ? undefined : openForRead();
369
- const overlaps = listRegions(overlapDb, undefined, "dual-use", undefined, space);
370
- overlapDb?.close();
371
- const gaps = coverage === undefined ? [] : executedStarts(coverage, inProgram).filter((address) => address >= loaded.start && address <= loaded.end && !decoded.has(address) && !overlaps.some((region) => address >= region.start && address <= region.end));
372
- const explained = explainGaps(gaps, result.instructions, report.refused, seeds.dataRanges);
373
- const runOnWritten = writtenNotExecutedOf("decompiler", space, coverage);
374
- let instructions: Record<string, unknown> | undefined;
375
- if (instructionsPath !== undefined) {
376
- const list = instructionList(result.instructions, coverage);
377
- instructions = { count: list.length, ...writeReported(instructionsPath, `${JSON.stringify(list, null, 1)}\n`, { what: "--out-instructions" }) };
378
- }
379
- const body = {
380
- analyzer: "decompiler",
381
- ...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
382
- ...(space === DEFAULT_SPACE ? {} : { space }),
383
- ...imported,
384
- seeds: seedsResult({ entryPoints: seeds.entryPoints.length, codeStarts: codeStarts.length, dataRanges: seeds.dataRanges.length }, overLimit, report, max),
385
- ...coverageResult(),
386
- ...(coverage === undefined ? {} : { coverageGaps: listed(explained, max, showGap, "a larger --max-listed") }),
387
- ...(runOnWritten.length === 0 ? {} : { writtenNotExecuted: listed(runOnWritten, max, showWritten) }),
388
- ...found,
389
- ...(instructions === undefined ? {} : { instructions }),
390
- coverage: result.coverage.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
391
- functions: listed(result.functions, max, (fn) => ({ entry: formatC64Address(fn.entry), name: fn.name }), ALL_NAMES),
392
- decompilations: result.decompilations.map((item) => ({ entry: formatC64Address(item.entry), text: item.text, ...(item.truncated ? { truncated: true } : {}) })),
393
- ...((result.notDecompiled ?? []).length === 0
394
- ? {}
395
- : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
396
- };
397
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired, { refused: report.refused.length, writtenNotExecuted: runOnWritten.length });
468
+ const idiomsImported = importIdioms();
469
+ return withRead((db) => {
470
+ const found = idiomsResult(db, idiomsImported);
471
+ // A start inside a dual-use region is a known overlap, for example the second instruction of a BIT skip: one list cannot hold both.
472
+ // Read after the idioms, which write those regions.
473
+ const overlaps = coverage === undefined ? [] : listRegions(db, undefined, "dual-use", undefined, space);
474
+ const gaps = coverage === undefined ? [] : executedStarts(coverage, inProgram).filter((address) => address >= loaded.start && address <= loaded.end && !decoded.has(address) && !inRanges(overlaps, address));
475
+ // The data ranges that the decompiler used: not the ranges that hold a seed, and only the part in the program.
476
+ const explained = explainGaps(gaps, result.instructions, report.refused, report.dataRanges);
477
+ let instructions: Record<string, unknown> | undefined;
478
+ if (instructionsPath !== undefined) {
479
+ const list = instructionList(result.instructions, coverage);
480
+ instructions = { count: list.length, ...writeReported(instructionsPath, `${JSON.stringify(list, null, 1)}\n`, { what: "--out-instructions" }) };
481
+ }
482
+ return resultOf(db, {
483
+ toolVersion: result.toolVersion,
484
+ imported,
485
+ report,
486
+ seeds: seedsResult({ entryPoints: seeds.entryPoints.length, codeStarts: codeStarts.length, dataRanges: seeds.dataRanges.length }, overLimit, report, max),
487
+ found,
488
+ gaps: coverage === undefined ? {} : { coverageGaps: listed(explained, max, showGap, "a larger --max-listed") },
489
+ tail: {
490
+ ...(instructions === undefined ? {} : { instructions }),
491
+ coverage: result.coverage.map(formatC64RangeFields),
492
+ functions: listed(result.functions, max, (fn) => ({ entry: formatC64Address(fn.entry), name: fn.name }), ALL_NAMES),
493
+ decompilations: result.decompilations.map((item) => ({ entry: formatC64Address(item.entry), text: item.text, ...(item.truncated ? { truncated: true } : {}) })),
494
+ ...((result.notDecompiled ?? []).length === 0
495
+ ? {}
496
+ : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
497
+ },
498
+ });
499
+ });
398
500
  }
399
501
 
400
502
  /** A coverage gap with $ addresses. */
401
503
  function showGap(gap: GapReason) {
402
- return { address: formatC64Address(gap.address), reason: gap.reason, ...(gap.at === undefined ? {} : { at: formatC64Address(gap.at) }), ...(gap.range === undefined ? {} : { range: { start: formatC64Address(gap.range.start), end: formatC64Address(gap.range.end) } }) };
504
+ return { address: formatC64Address(gap.address), reason: gap.reason, ...(gap.at === undefined ? {} : { at: formatC64Address(gap.at) }), ...(gap.range === undefined ? {} : { range: formatC64RangeFields(gap.range) }) };
403
505
  }
404
506
 
405
507
  /** A range of writtenNotExecuted with $ addresses. */
406
508
  function showWritten(range: { start: number; end: number; from: number[] }) {
407
- return { start: formatC64Address(range.start), end: formatC64Address(range.end), from: range.from.map(formatC64Address) };
509
+ return { ...formatC64RangeFields(range), from: range.from.map(formatC64Address) };
408
510
  }
409
511
 
410
512
  await runScript({