@henols/c64-re-tools 2.8.0-rc.2 → 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 (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  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 +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  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 +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +10 -5
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +9 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
  47. package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +28 -68
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
@@ -3,77 +3,34 @@
3
3
  // the README of the new project.
4
4
  //
5
5
  // A range becomes free only when no run executed or read it and nothing that
6
- // stays reaches it. The reachability runs two times over the blocks of the
7
- // decoded instructions. Pass A starts at the entry and the hardware vectors:
8
- // it tells what the program can reach. Pass B also starts at each block that
9
- // a run executed, at --keep and at the patches that the export changed: it
10
- // tells what stays. Without coverage nothing becomes free by itself. While the
11
- // code that stays has a flow whose targets the knowledge does not give (an
12
- // indirect jump through a vector that the code's own immediates do not set, a
13
- // jump whose address a run wrote, or an RTS to an address that the code
14
- // pushed), code that nothing reaches is unknown: it stays.
6
+ // stays reaches it. The code reach (src/knowledge/code-reach.ts) tells which
7
+ // code is unused and which code stays. Data becomes free when no run touched
8
+ // it and nothing that stays names it. Without coverage nothing becomes free by
9
+ // itself.
15
10
 
16
- import { type AddressRange, COVERAGE, formatC64Address, pointerTableEntries, POINTER_TABLE_TYPES, type PointerTableType } from "#src/c64.ts";
11
+ import { type AddressRange, c64AddressOf, formatC64Address, formatC64Range, hexWord, inRanges, mergeRanges, POINTER_TABLE_TYPES, rangesOverlap } from "#src/c64.ts";
17
12
  import { symbolsPath } from "#src/build-name.ts";
18
13
  import { Refusal } from "#src/errors.ts";
19
- import { computedFlows, NO_FALL_THROUGH, type Root, separate, type UnresolvedFlow, vectorHigh, WRITES_A, WRITES_X, WRITES_Y } from "#src/knowledge/separate.ts";
20
- import type { RegionType } from "#src/knowledge/schema.ts";
21
- import { OPCODES } from "#src/opcodes.ts";
14
+ import { codeReach, type CodeReachInput, isTable, RAM_ACCESS } from "#src/knowledge/code-reach.ts";
15
+ import type { UnresolvedFlow } from "#src/knowledge/separate.ts";
16
+ import { INSTRUCTION_REGION_TYPES, type RegionType } from "#src/knowledge/schema.ts";
22
17
 
23
18
  /**
24
19
  * The data region types that can become free by themselves. The VIC-II reads
25
20
  * charset, sprite, bitmap and screen data without the CPU, so the coverage
26
21
  * does not show that a program uses them: only --drop makes them free.
27
22
  */
28
- export const DROPPABLE_DATA: readonly RegionType[] = ["bytes", "words", ...POINTER_TABLE_TYPES, "petscii", "workspace", "unused"];
23
+ const DROPPABLE_DATA: readonly RegionType[] = ["bytes", "words", ...POINTER_TABLE_TYPES, "petscii", "workspace", "unused"];
29
24
 
30
25
  /** The data that the VIC-II reads: a region of another type that overlaps it stays too, for example unused bytes in a bitmap. */
31
26
  const VIC_DATA: readonly RegionType[] = ["charset", "sprite", "bitmap", "screen"];
32
27
 
33
- /** Regions of code: their bytes are the blocks of the decoded instructions. */
34
- const CODE_TYPES: readonly RegionType[] = ["code", "jumps", "dual-use"];
35
-
36
28
  /** The hardware vectors $fffa-$ffff: they stay when the image holds them. */
37
29
  const VECTORS: AddressRange = { start: 0xfffa, end: 0xffff };
38
30
 
39
- /**
40
- * The coverage flags that can be a use of the RAM byte: a read or a run of the
41
- * ROM uses the ROM, not the RAM under it, so a JSR into the KERNAL keeps no byte
42
- * of the image. The I/O flags stay, as VICE gives each access at $d000-$dfff as I/O.
43
- */
44
- const RAM_ACCESS = 0xff & ~(COVERAGE.romRead | COVERAGE.romExecute);
45
-
46
- /** The I/O area: two immediates stored there are chip values, such as a timer latch, not an address. */
47
- const IO_AREA: AddressRange = { start: 0xd000, end: 0xdfff };
48
-
49
- /** The registers that a JSR gets an address in, low byte first, as the KERNAL and BASIC routines get a pointer. */
50
- const CALL_PAIRS = [
51
- ["x", "y"],
52
- ["a", "y"],
53
- ["a", "x"],
54
- ] as const;
55
-
56
- export interface DropInput {
57
- segments: readonly AddressRange[];
58
- /** 64 KiB with the baked image at its addresses. */
59
- memory: Uint8Array;
60
- entry?: number;
61
- /** The decoded instructions of the baked image: start and length. */
62
- instructions: ReadonlyMap<number, number>;
63
- coverage?: Uint8Array;
64
- regions: ReadonlyArray<{ start: number; end: number; type: RegionType }>;
65
- /** A jump or call reference of the user or the LLM resolves the flow of its instruction. */
66
- references: ReadonlyArray<{ from: number; to: number; kind: string; origin?: string }>;
67
- /** The addresses that the operand expression of an instruction names, by the address of each instruction with an operand expression; none for a constant. */
68
- operandTargets: ReadonlyMap<number, readonly number[]>;
69
- /** The ranges where the CPU sees ROM and not the RAM of the image: code does not go there, and no address points there. */
70
- rom?: readonly AddressRange[];
31
+ export interface DropInput extends CodeReachInput {
71
32
  /** The BASIC line that starts the program: RUN reads it, which no coverage from the entry shows. */
72
33
  basic?: AddressRange;
73
- /** The patch ranges whose bytes the export changed. */
74
- changed: readonly AddressRange[];
75
- keep: readonly AddressRange[];
76
- drop: readonly AddressRange[];
77
34
  routines: ReadonlyArray<{ address: number; name: string }>;
78
35
  }
79
36
 
@@ -94,277 +51,71 @@ export interface DropPlan {
94
51
  unresolved: UnresolvedFlow[];
95
52
  }
96
53
 
97
- const inside = (address: number, ranges: readonly AddressRange[]) => ranges.some((range) => address >= range.start && address <= range.end);
98
- const overlaps = (a: AddressRange, b: AddressRange) => a.start <= b.end && b.start <= a.end;
99
54
  const within = (a: AddressRange, b: AddressRange) => a.start >= b.start && a.end <= b.end;
100
- const shown = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
101
-
102
- /** The blocks of the instructions: a block ends after an instruction that does not run on, and before a gap. An instruction inside the one before stays in its block. */
103
- export function blocksOf(instructions: ReadonlyMap<number, number>, memory: Uint8Array): AddressRange[] {
104
- const blocks: AddressRange[] = [];
105
- let open = false;
106
- for (const start of [...instructions.keys()].sort((a, b) => a - b)) {
107
- const end = Math.min(0xffff, start + instructions.get(start)! - 1);
108
- const last = blocks.at(-1);
109
- if (last !== undefined && (start <= last.end || (open && start === last.end + 1))) last.end = Math.max(last.end, end);
110
- else blocks.push({ start, end });
111
- open = !NO_FALL_THROUGH.has(memory[start]!);
112
- }
113
- return blocks;
114
- }
115
-
116
- /** Joins ranges in address order that touch or overlap. */
117
- function merged(ranges: readonly AddressRange[]): AddressRange[] {
118
- const result: AddressRange[] = [];
119
- for (const range of [...ranges].sort((a, b) => a.start - b.start)) {
120
- const last = result.at(-1);
121
- if (last !== undefined && range.start <= last.end + 1) last.end = Math.max(last.end, range.end);
122
- else result.push({ ...range });
123
- }
124
- return result;
125
- }
126
-
127
- /** A place where code goes or reads: the instruction (or table) at `from`, and what it names. */
128
- interface Flow {
129
- from: number;
130
- to: number;
131
- }
132
-
133
- interface DataReference {
134
- from: number;
135
- start: number;
136
- end: number;
137
- }
138
-
139
- /**
140
- * The code flows and the data references of the instructions, the knowledge
141
- * references and the operand expressions. `indexedEnd` gives the last address
142
- * that an indexed operand can read.
143
- */
144
- function flowsOf(input: DropInput, inImage: (address: number) => boolean, indexedEnd: (operand: number) => number) {
145
- const flows: Flow[] = [];
146
- const reads: DataReference[] = [];
147
- const { memory } = input;
148
- const word = (at: number) => memory[at]! | (memory[(at + 1) & 0xffff]! << 8);
149
- const rom = (address: number) => inside(address, input.rom ?? []);
150
- // The address of a vector, a table or an RTS target in two immediates of one block: the low byte and the high byte
151
- // go into a pointer (two stores to N and N+1), into the registers of a JSR, or onto the stack (PHA high, PHA low).
152
- type Immediate = { at: number; value: number } | undefined;
153
- const registers: { a: Immediate; x: Immediate; y: Immediate } = { a: undefined, x: undefined, y: undefined };
154
- const stores = new Map<number, NonNullable<Immediate>>();
155
- const pushes: Immediate[] = [];
156
- const pair = (low: Immediate, high: Immediate) => {
157
- if (low === undefined || high === undefined) return;
158
- const target = low.value | (high.value << 8);
159
- if (!inImage(target) || rom(target)) return;
160
- flows.push({ from: low.at, to: target }, { from: low.at, to: (target + 1) & 0xffff });
161
- reads.push({ from: low.at, start: target, end: target });
162
- };
163
- const endBlock = () => {
164
- registers.a = registers.x = registers.y = undefined;
165
- stores.clear();
166
- pushes.length = 0;
167
- };
168
- let previousEnd = -2;
169
- for (const at of [...input.instructions.keys()].sort((a, b) => a - b)) {
170
- const opcode = memory[at]!;
171
- const { mnemonic, mode } = OPCODES[opcode]!;
172
- if (at > previousEnd + 1) endBlock();
173
- previousEnd = at + input.instructions.get(at)! - 1;
174
- const operand = input.instructions.get(at) === 3 ? word(at + 1) : memory[at + 1]!;
175
- // The registers: a load of an immediate that no operand expression explains, a transfer, a store, a push, a call.
176
- const loaded = mode === "imm" && !input.operandTargets.has(at) ? { at, value: operand } : undefined;
177
- if (WRITES_A.has(mnemonic) || (mode === "imp" && ["asl", "lsr", "rol", "ror"].includes(mnemonic))) registers.a = mnemonic === "lda" ? loaded : undefined;
178
- if (WRITES_X.has(mnemonic)) registers.x = mnemonic === "ldx" ? loaded : undefined;
179
- if (WRITES_Y.has(mnemonic)) registers.y = mnemonic === "ldy" ? loaded : undefined;
180
- if (mnemonic === "tax") registers.x = registers.a;
181
- if (mnemonic === "tay") registers.y = registers.a;
182
- if (mnemonic === "txa") registers.a = registers.x;
183
- if (mnemonic === "tya") registers.a = registers.y;
184
- const stored = { sta: registers.a, stx: registers.x, sty: registers.y }[mnemonic];
185
- if ((mode === "zp" || mode === "abs") && ["sta", "stx", "sty"].includes(mnemonic) && !inside(operand, [IO_AREA])) {
186
- stores.delete(operand);
187
- if (stored !== undefined) {
188
- stores.set(operand, stored);
189
- pair(stored, stores.get((operand + 1) & 0xffff));
190
- pair(stores.get((operand - 1) & 0xffff), stored);
191
- }
192
- }
193
- if (mnemonic === "pha") {
194
- pushes.push(registers.a);
195
- if (pushes.length >= 2) pair(pushes.at(-1), pushes.at(-2));
196
- }
197
- if (mnemonic === "pla") pushes.pop();
198
- if (mnemonic === "jsr") {
199
- for (const [low, high] of CALL_PAIRS) pair(registers[low], registers[high]);
200
- registers.a = registers.x = registers.y = undefined;
201
- }
202
- switch (mode) {
203
- case "rel":
204
- flows.push({ from: at, to: (at + 2 + (operand < 0x80 ? operand : operand - 0x100)) & 0xffff });
205
- break;
206
- case "ind": {
207
- const high = vectorHigh(operand);
208
- reads.push({ from: at, start: operand, end: operand }, { from: at, start: high, end: high });
209
- if (inImage(operand) && inImage(high)) flows.push({ from: at, to: memory[operand]! | (memory[high]! << 8) });
210
- break;
211
- }
212
- case "abs":
213
- case "zp":
214
- if (opcode === 0x20 || opcode === 0x4c) {
215
- if (!rom(operand)) flows.push({ from: at, to: operand });
216
- } else reads.push({ from: at, start: operand, end: operand });
217
- break;
218
- case "abx":
219
- case "aby":
220
- case "zpx":
221
- case "zpy":
222
- reads.push({ from: at, start: operand, end: indexedEnd(operand) });
223
- break;
224
- case "izx":
225
- case "izy":
226
- reads.push({ from: at, start: operand, end: (operand + 1) & 0xff });
227
- break;
228
- default:
229
- break;
230
- }
231
- if (NO_FALL_THROUGH.has(opcode)) endBlock();
232
- }
233
- for (const reference of input.references) {
234
- if (inside(reference.from, input.changed)) continue;
235
- if (reference.kind === "call" || reference.kind === "jump" || reference.kind === "pointer") flows.push({ from: reference.from, to: reference.to });
236
- reads.push({ from: reference.from, start: reference.to, end: reference.to });
237
- }
238
- for (const [at, targets] of input.operandTargets) {
239
- for (const target of targets) {
240
- flows.push({ from: at, to: target });
241
- reads.push({ from: at, start: target, end: target });
242
- }
243
- }
244
- return { flows, reads };
245
- }
246
-
247
- /** The entries of a table of addresses or of jumps. */
248
- function tableTargets(table: { start: number; end: number; type: RegionType }, memory: Uint8Array): number[] {
249
- if (table.type === "jumps") return Array.from({ length: Math.floor((table.end - table.start + 1) / 3) }, (_, index) => table.start + 3 * index);
250
- return pointerTableEntries(table as { start: number; end: number; type: PointerTableType }, (address) => memory[address]!).map((entry) => entry.target);
251
- }
252
-
253
- const isTable = (type: RegionType) => type === "jumps" || (POINTER_TABLE_TYPES as readonly string[]).includes(type);
254
55
 
255
56
  /**
256
57
  * The free ranges of the baked image, the code that a run executed and the
257
58
  * entry does not reach, and the refusals of --drop and --keep.
258
59
  */
259
60
  export function planDrops(input: DropInput): DropPlan {
260
- const inImage = (address: number) => inside(address, input.segments);
61
+ const inImage = (address: number) => inRanges(input.segments, address);
261
62
  const touched = (address: number) => input.coverage !== undefined && (input.coverage[address]! & RAM_ACCESS) !== 0;
262
- const executed = (address: number) => input.coverage !== undefined && (input.coverage[address]! & COVERAGE.ramExecute) !== 0;
263
- const regions = input.regions.flatMap((region) => input.segments.filter((segment) => overlaps(region, segment)).map((segment) => ({ start: Math.max(region.start, segment.start), end: Math.min(region.end, segment.end), type: region.type })));
264
- // The source writes a data region as data, also where the decompiler decoded instructions in it: those are no code.
265
- const instructions = new Map([...input.instructions].filter(([start, length]) => !regions.some((region) => !CODE_TYPES.includes(region.type) && start <= region.end && region.start <= start + length - 1)));
266
- const blocks = blocksOf(instructions, input.memory);
267
- // An indexed operand reads in the region that holds it, and in the next region when it is the last byte (table-1,x).
268
- // Without a region, it can read the 256 bytes from the operand.
269
- const holding = (address: number) => regions.find((region) => address >= region.start && address <= region.end);
270
- const indexedEnd = (operand: number) => {
271
- const holder = holding(operand);
272
- const next = holder === undefined || holder.end === operand ? holding((operand + 1) & 0xffff) : undefined;
273
- return next?.end ?? holder?.end ?? Math.min(0xffff, operand + 0xff);
274
- };
275
- const { flows, reads } = flowsOf({ ...input, instructions }, inImage, indexedEnd);
63
+ const reach = codeReach(input);
64
+ const { regions, blocks, flows, reads, targetsOf } = reach;
276
65
 
277
66
  for (const range of [...input.keep, ...input.drop]) {
278
67
  for (let address = range.start; address <= range.end; address++) {
279
- if (!inImage(address)) throw new Refusal("invalid-input", `${shown(range)} is not in the program: ${formatC64Address(address)} is in no segment.`);
68
+ if (!inImage(address)) throw new Refusal("invalid-input", `${formatC64Range(range)} is not in the program: ${formatC64Address(address)} is in no segment.`);
280
69
  }
281
70
  }
282
71
  for (const range of input.drop) {
283
- const kept = input.keep.find((other) => overlaps(range, other));
284
- if (kept !== undefined) throw new Refusal("invalid-input", `--drop ${shown(range)} overlaps --keep ${shown(kept)}.`);
285
- const changed = input.changed.find((other) => overlaps(range, other));
286
- if (changed !== undefined) throw new Refusal("invalid-input", `--drop ${shown(range)} overlaps the patch ${shown(changed)}, which the export changed.`);
287
- const cutBlock = blocks.find((block) => overlaps(block, range) && !within(block, range));
288
- if (cutBlock !== undefined) throw new Refusal("invalid-input", `--drop ${shown(range)} cuts the code ${shown(cutBlock)}. Give a range that holds all of it, or none of it.`);
289
- const cutData = regions.find((region) => !CODE_TYPES.includes(region.type) && overlaps(region, range) && !within(region, range));
290
- if (cutData !== undefined) throw new Refusal("invalid-input", `--drop ${shown(range)} cuts the ${cutData.type} region ${shown(cutData)}. Give a range that holds all of it, or none of it.`);
72
+ const kept = input.keep.find((other) => rangesOverlap(range, other));
73
+ if (kept !== undefined) throw new Refusal("invalid-input", `--drop ${formatC64Range(range)} overlaps --keep ${formatC64Range(kept)}.`);
74
+ const changed = input.changed.find((other) => rangesOverlap(range, other));
75
+ if (changed !== undefined) throw new Refusal("invalid-input", `--drop ${formatC64Range(range)} overlaps the patch ${formatC64Range(changed)}, which the export changed.`);
76
+ const cutBlock = blocks.find((block) => rangesOverlap(block, range) && !within(block, range));
77
+ if (cutBlock !== undefined) throw new Refusal("invalid-input", `--drop ${formatC64Range(range)} cuts the code ${formatC64Range(cutBlock)}. Give a range that holds all of it, or none of it.`);
78
+ const cutData = regions.find((region) => !INSTRUCTION_REGION_TYPES.includes(region.type) && rangesOverlap(region, range) && !within(region, range));
79
+ if (cutData !== undefined) throw new Refusal("invalid-input", `--drop ${formatC64Range(range)} cuts the ${cutData.type} region ${formatC64Range(cutData)}. Give a range that holds all of it, or none of it.`);
291
80
  }
292
-
293
- // Tables that a run read or that the knowledge names: their entries can be the only way to code, so they are roots.
294
- const tables = regions.filter((region) => isTable(region.type));
295
- const tableUsers = (table: AddressRange) => reads.filter((read) => read.start <= table.end && table.start <= read.end).map((read) => read.from);
296
- const tableRoots: Root[] = [];
297
- for (const table of tables) {
298
- const targets = tableTargets(table, input.memory);
299
- let read = false;
300
- for (let address = table.start; address <= table.end && !read; address++) read = touched(address);
301
- if (read || input.references.some((reference) => reference.to >= table.start && reference.to <= table.end)) for (const target of targets) tableRoots.push({ address: target, from: "table entry" });
302
- for (const from of tableUsers(table)) for (const target of targets) flows.push({ from, to: target });
303
- }
304
-
305
- const asRegions = (list: readonly AddressRange[]) => list.map((block) => ({ ...block, type: "code" }));
306
- const references = flows.map((flow) => ({ ...flow, kind: "jump" }));
307
- const passA = separate({ segments: [...input.segments], memory: input.memory, ...(input.entry === undefined ? {} : { entry: input.entry }), codeRegions: asRegions(blocks), references, roots: tableRoots });
308
- const rooted = passA.codeRegions.every((region) => region.reachable !== undefined);
309
- const reachable = (index: number) => !rooted || passA.codeRegions[index]!.reachable === true;
310
81
  for (const range of input.drop) {
311
- const live = blocks.findIndex((block, index) => within(block, range) && reachable(index));
312
- if (live >= 0) throw new Refusal("invalid-input", `--drop ${shown(range)} holds the code ${shown(blocks[live]!)}, which the entry or a vector reaches. Only code that nothing reaches can be dropped.`);
313
- }
314
- const ran = (block: AddressRange) => {
315
- for (let address = block.start; address <= block.end; address++) if (executed(address)) return true;
316
- return false;
317
- };
318
-
319
- // Pass B: what stays. Blocks in a --drop range are gone.
320
- const candidates = blocks.filter((block) => !input.drop.some((range) => within(block, range)));
321
- const extra: Root[] = [...tableRoots];
322
- for (const block of candidates) {
323
- if (ran(block)) extra.push({ address: block.start, from: "executed code" });
324
- else if ([...input.keep, ...input.changed].some((range) => overlaps(block, range))) extra.push({ address: block.start, from: "kept range" });
82
+ const live = blocks.findIndex((block, index) => within(block, range) && reach.reachable[index]);
83
+ if (live >= 0) throw new Refusal("invalid-input", `--drop ${formatC64Range(range)} holds the code ${formatC64Range(blocks[live]!)}, which the entry or a vector reaches. Only code that nothing reaches can be dropped.`);
325
84
  }
326
- const passB = separate({ segments: [...input.segments], memory: input.memory, ...(input.entry === undefined ? {} : { entry: input.entry }), codeRegions: asRegions(candidates), references, roots: extra });
327
- const automatic = input.coverage !== undefined && rooted;
328
- const unreachableCode = candidates.filter((_, index) => automatic && passB.codeRegions[index]!.reachable === false);
329
- // A flow that nobody resolved can go to any of that code: it stays, as unknown. Only a flow in code that stays can run.
330
- const live = candidates.filter((block) => !unreachableCode.includes(block));
331
- const unresolved =
332
- unreachableCode.length === 0
333
- ? []
334
- : computedFlows({ starts: [...instructions.keys()], memory: input.memory, inImage, coverage: input.coverage, references: input.references }).unresolved.filter((flow) => live.some((block) => flow.at >= block.start && flow.at <= block.end));
335
- const droppedCode = unresolved.length === 0 ? unreachableCode : [];
336
- const unknown = unresolved.length === 0 ? [] : merged(unreachableCode);
337
- const stays = candidates.filter((block) => !droppedCode.includes(block));
338
- const inStaying = (address: number) => stays.some((block) => address >= block.start && address <= block.end);
85
+ const staying = new Uint8Array(0x10000);
86
+ for (const block of reach.stays) staying.fill(1, block.start, block.end + 1);
87
+ const inStaying = (address: number) => staying[address] === 1;
339
88
  for (const range of input.drop) {
340
- const into = flows.find((flow) => inStaying(flow.from) && inside(flow.to, [range]));
341
- if (into !== undefined) throw new Refusal("invalid-input", `--drop ${shown(range)}: the code at ${formatC64Address(into.from)} stays and goes to ${formatC64Address(into.to)}.`);
342
- const read = reads.find((item) => inStaying(item.from) && overlaps(item, range));
343
- if (read !== undefined) throw new Refusal("invalid-input", `--drop ${shown(range)}: the code at ${formatC64Address(read.from)} stays and reads ${shown({ start: Math.max(read.start, range.start), end: Math.min(read.end, range.end) })}.`);
89
+ const into = flows.find((flow) => inStaying(flow.from) && inRanges([range], flow.to));
90
+ if (into !== undefined) throw new Refusal("invalid-input", `--drop ${formatC64Range(range)}: the code at ${formatC64Address(into.from)} stays and goes to ${formatC64Address(into.to)}.`);
91
+ const read = reads.find((item) => inStaying(item.from) && rangesOverlap(item, range));
92
+ if (read !== undefined) throw new Refusal("invalid-input", `--drop ${formatC64Range(range)}: the code at ${formatC64Address(read.from)} stays and reads ${formatC64Range({ start: Math.max(read.start, range.start), end: Math.min(read.end, range.end) })}.`);
344
93
  }
345
94
 
346
95
  // Data: a region of a droppable type that no run touched and that nothing that stays names.
347
- const gone = [...input.drop, ...droppedCode];
348
- const units = automatic
349
- ? regions.filter((region) => {
350
- if (!DROPPABLE_DATA.includes(region.type) || gone.some((range) => overlaps(range, region))) return false;
351
- if (regions.some((other) => VIC_DATA.includes(other.type) && overlaps(other, region))) return false;
352
- if ([...input.keep, ...input.changed, VECTORS, ...(input.basic === undefined ? [] : [input.basic])].some((range) => overlaps(range, region))) return false;
353
- for (let address = region.start; address <= region.end; address++) if (touched(address)) return false;
354
- return true;
355
- })
356
- : [];
96
+ const tables = [...targetsOf.keys()];
97
+ const gone = [...input.drop, ...reach.unused];
98
+ const units =
99
+ input.coverage !== undefined && reach.rooted
100
+ ? regions.filter((region) => {
101
+ if (!DROPPABLE_DATA.includes(region.type) || gone.some((range) => rangesOverlap(range, region))) return false;
102
+ if (regions.some((other) => VIC_DATA.includes(other.type) && rangesOverlap(other, region))) return false;
103
+ if ([...input.keep, ...input.changed, VECTORS, ...(input.basic === undefined ? [] : [input.basic])].some((range) => rangesOverlap(range, region))) return false;
104
+ for (let address = region.start; address <= region.end; address++) if (touched(address)) return false;
105
+ return true;
106
+ })
107
+ : [];
357
108
  const dropped = new Set(units.map((_, index) => index));
358
109
  const unitAt = (address: number) => units.findIndex((unit) => address >= unit.start && address <= unit.end);
359
110
  // A name from code that stays, or from a unit that stays, keeps the unit. Kept tables keep their entries.
360
111
  for (let grown = true; grown; ) {
361
112
  grown = false;
362
- const keeps = (from: number) => inStaying(from) || (!inside(from, gone) && (unitAt(from) < 0 || !dropped.has(unitAt(from))));
113
+ const keeps = (from: number) => inStaying(from) || (!inRanges(gone, from) && (unitAt(from) < 0 || !dropped.has(unitAt(from))));
363
114
  for (const [index, unit] of units.entries()) {
364
115
  if (!dropped.has(index)) continue;
365
116
  const named = reads.some((read) => read.start <= unit.end && unit.start <= read.end && keeps(read.from));
366
- const entry = units.some((table, other) => !dropped.has(other) && isTable(table.type) && tableTargets(table, input.memory).some((target) => target >= unit.start && target <= unit.end));
367
- const fromTable = tables.some((table) => unitAt(table.start) < 0 && tableTargets(table, input.memory).some((target) => target >= unit.start && target <= unit.end));
117
+ const entry = units.some((table, other) => !dropped.has(other) && isTable(table.type) && targetsOf.get(table)!.some((target) => target >= unit.start && target <= unit.end));
118
+ const fromTable = tables.some((table) => unitAt(table.start) < 0 && targetsOf.get(table)!.some((target) => target >= unit.start && target <= unit.end));
368
119
  if (named || entry || fromTable) {
369
120
  dropped.delete(index);
370
121
  grown = true;
@@ -375,7 +126,7 @@ export function planDrops(input: DropInput): DropPlan {
375
126
 
376
127
  const pieces = [
377
128
  ...input.drop.map((range) => ({ ...range, code: blocks.some((block) => within(block, range)), data: !blocks.some((block) => within(block, range)) || regions.some((region) => within(region, range) && !isTable(region.type) && region.type !== "code") })),
378
- ...droppedCode.map((range) => ({ ...range, code: true, data: false })),
129
+ ...reach.unused.map((range) => ({ ...range, code: true, data: false })),
379
130
  ...droppedData.map((range) => ({ ...range, code: false, data: true })),
380
131
  ].sort((a, b) => a.start - b.start);
381
132
  const free: FreeRange[] = [];
@@ -389,15 +140,15 @@ export function planDrops(input: DropInput): DropPlan {
389
140
  }
390
141
 
391
142
  const routines = [...input.routines].sort((a, b) => a.address - b.address);
392
- const unreachableExecuted = merged(blocks.filter((block, index) => rooted && passA.codeRegions[index]!.reachable === false && ran(block) && !input.drop.some((range) => within(block, range)))).map((range) => {
143
+ const unreachableExecuted = mergeRanges(blocks.filter((block, index) => !reach.reachable[index] && reach.executed[index] && !input.drop.some((range) => within(block, range)))).map((range) => {
393
144
  const routine = routines.filter((item) => item.address <= range.start).at(-1)?.name;
394
145
  return { ...range, ...(routine === undefined ? {} : { routine }) };
395
146
  });
396
- return { free, unreachableExecuted, rooted, unknown, unresolved };
147
+ return { free, unreachableExecuted, rooted: reach.rooted, unknown: reach.unknown, unresolved: reach.unresolved };
397
148
  }
398
149
 
399
150
  /** The label of a free range. */
400
- export const freeName = (range: AddressRange) => `free_${range.start.toString(16).padStart(4, "0")}`;
151
+ export const freeName = (range: AddressRange) => `free_${hexWord(range.start)}`;
401
152
 
402
153
  /** What the export does with one test file of the project. */
403
154
  export type TestRewrite = { kind: "scenario" | "run"; text: string } | { reason: string };
@@ -443,9 +194,9 @@ export function rewriteTest(text: string, name: string, symbols: ReadonlyMap<str
443
194
  if (!scenario && !run) return { reason: "it is not a scenario or a run file" };
444
195
  if (hasSnapshot(test)) return { reason: "it restores a snapshot, which is a state of the old program" };
445
196
  for (const location of locationsOf(test.steps)) {
446
- if (/^\$[0-9a-fA-F]{1,4}$/.test(location)) {
447
- const address = Number.parseInt(location.slice(1), 16);
448
- if (inside(address, free)) return { reason: `it names ${location}, which is in a free range` };
197
+ const address = c64AddressOf(location);
198
+ if (address !== undefined) {
199
+ if (inRanges(free, address)) return { reason: `it names ${location}, which is in a free range` };
449
200
  } else if (!symbols.has(location)) return { reason: `it names ${location}, which the exported program does not have` };
450
201
  }
451
202
  const side = (program: string) => ({ program: `${program}.prg`, symbols: symbolsPath(`${program}.prg`) });
@@ -513,7 +264,7 @@ export function readmeText(input: ReadmeInput): string {
513
264
  if (input.free.length === 0) lines.push("None: the export dropped nothing.");
514
265
  else {
515
266
  lines.push("The export dropped code and data that nothing uses. Each range is `$00` in the source, with a label `free_xxxx`. Use the space for new code.", "", "| Range | Bytes | Was |", "|---|---|---|");
516
- for (const range of input.free) lines.push(`| \`${shown(range)}\` | ${range.end - range.start + 1} | ${range.what} |`);
267
+ for (const range of input.free) lines.push(`| \`${formatC64Range(range)}\` | ${range.end - range.start + 1} | ${range.what} |`);
517
268
  }
518
269
  lines.push(
519
270
  "",