@henols/c64-re-tools 2.2.0-rc.1 → 2.2.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.
- package/README.md +30 -41
- package/package.json +1 -1
- package/skills/c64-assembler/SKILL.md +1 -0
- package/skills/c64-assembler/scripts/assembler.ts +2 -9
- package/skills/c64-development/SKILL.md +180 -0
- package/skills/c64-export/SKILL.md +87 -0
- package/skills/c64-provenance/scripts/lib/leftovers.ts +1 -1
- package/skills/c64-provenance/scripts/provenance.ts +1 -1
- package/skills/c64-reverse-engineering/SKILL.md +4 -0
- package/skills/c64-source/SKILL.md +88 -1
- package/skills/c64-source/scripts/lib/export.ts +471 -0
- package/skills/c64-source/scripts/source.ts +432 -64
- package/skills/c64-testing/SKILL.md +5 -3
- package/skills/c64-testing/references/scenario-format.md +34 -2
- package/skills/c64-testing/scripts/lib/runs.ts +122 -12
- package/skills/c64-testing/scripts/testing.ts +1 -1
- package/src/cli/main.ts +7 -7
- package/src/knowledge/program.ts +1 -1
- package/{skills/c64-provenance/scripts/lib → src/knowledge}/separate.ts +35 -21
- package/src/native/acme.ts +11 -0
- package/src/native/c64run.ts +1 -1
- package/src/native/discover.ts +5 -5
- package/src/native/ghidra/index.ts +5 -9
- package/src/native/status.ts +1 -1
- package/src/project.ts +25 -1
- package/src/zip.ts +89 -0
- package/tools/install-chips.sh +10 -19
- package/tools/install-dxa.sh +9 -51
- package/tools/install-ghidra.sh +6 -6
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
// The parts of an export that need no tool: which ranges of the baked program
|
|
2
|
+
// become free, how the tests of the project change for the new project, and
|
|
3
|
+
// the README of the new project.
|
|
4
|
+
//
|
|
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.
|
|
11
|
+
|
|
12
|
+
import { type AddressRange, COVERAGE, formatC64Address, pointerTableEntries, POINTER_TABLE_TYPES, type PointerTableType } from "#src/c64.ts";
|
|
13
|
+
import { Refusal } from "#src/errors.ts";
|
|
14
|
+
import { NO_FALL_THROUGH, type Root, separate } from "#src/knowledge/separate.ts";
|
|
15
|
+
import type { RegionType } from "#src/knowledge/schema.ts";
|
|
16
|
+
import { OPCODES } from "#src/opcodes.ts";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The data region types that can become free by themselves. The VIC-II reads
|
|
20
|
+
* charset, sprite, bitmap and screen data without the CPU, so the coverage
|
|
21
|
+
* does not show that a program uses them: only --drop makes them free.
|
|
22
|
+
*/
|
|
23
|
+
export const DROPPABLE_DATA: readonly RegionType[] = ["bytes", "words", ...POINTER_TABLE_TYPES, "petscii", "workspace", "unused"];
|
|
24
|
+
|
|
25
|
+
/** Regions of code: their bytes are the blocks of the decoded instructions. */
|
|
26
|
+
const CODE_TYPES: readonly RegionType[] = ["code", "jumps", "dual-use"];
|
|
27
|
+
|
|
28
|
+
/** The hardware vectors $fffa-$ffff: they stay when the image holds them. */
|
|
29
|
+
const VECTORS: AddressRange = { start: 0xfffa, end: 0xffff };
|
|
30
|
+
|
|
31
|
+
/** Two immediate operands at most this many immediates apart can be the low and high byte of one address. */
|
|
32
|
+
const PAIR_WINDOW = 4;
|
|
33
|
+
|
|
34
|
+
export interface DropInput {
|
|
35
|
+
segments: readonly AddressRange[];
|
|
36
|
+
/** 64 KiB with the baked image at its addresses. */
|
|
37
|
+
memory: Uint8Array;
|
|
38
|
+
entry?: number;
|
|
39
|
+
/** The decoded instructions of the baked image: start and length. */
|
|
40
|
+
instructions: ReadonlyMap<number, number>;
|
|
41
|
+
coverage?: Uint8Array;
|
|
42
|
+
regions: ReadonlyArray<{ start: number; end: number; type: RegionType }>;
|
|
43
|
+
references: ReadonlyArray<{ from: number; to: number; kind: string }>;
|
|
44
|
+
/** The addresses that the operand expression of an instruction names, by the address of the instruction. */
|
|
45
|
+
operandTargets: ReadonlyMap<number, readonly number[]>;
|
|
46
|
+
/** The patch ranges whose bytes the export changed. */
|
|
47
|
+
changed: readonly AddressRange[];
|
|
48
|
+
keep: readonly AddressRange[];
|
|
49
|
+
drop: readonly AddressRange[];
|
|
50
|
+
routines: ReadonlyArray<{ address: number; name: string }>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A free range: what it held. */
|
|
54
|
+
export interface FreeRange extends AddressRange {
|
|
55
|
+
what: "code" | "data" | "code and data";
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface DropPlan {
|
|
59
|
+
free: FreeRange[];
|
|
60
|
+
/** Code that a run executed and that the entry and the vectors do not reach: --drop can make it free. */
|
|
61
|
+
unreachableExecuted: Array<AddressRange & { routine?: string }>;
|
|
62
|
+
/** False when the image has no entry and no hardware vectors: then nothing is unreachable. */
|
|
63
|
+
rooted: boolean;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const inside = (address: number, ranges: readonly AddressRange[]) => ranges.some((range) => address >= range.start && address <= range.end);
|
|
67
|
+
const overlaps = (a: AddressRange, b: AddressRange) => a.start <= b.end && b.start <= a.end;
|
|
68
|
+
const within = (a: AddressRange, b: AddressRange) => a.start >= b.start && a.end <= b.end;
|
|
69
|
+
const shown = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
|
|
70
|
+
|
|
71
|
+
/** 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. */
|
|
72
|
+
export function blocksOf(instructions: ReadonlyMap<number, number>, memory: Uint8Array): AddressRange[] {
|
|
73
|
+
const blocks: AddressRange[] = [];
|
|
74
|
+
let open = false;
|
|
75
|
+
for (const start of [...instructions.keys()].sort((a, b) => a - b)) {
|
|
76
|
+
const end = Math.min(0xffff, start + instructions.get(start)! - 1);
|
|
77
|
+
const last = blocks.at(-1);
|
|
78
|
+
if (last !== undefined && (start <= last.end || (open && start === last.end + 1))) last.end = Math.max(last.end, end);
|
|
79
|
+
else blocks.push({ start, end });
|
|
80
|
+
open = !NO_FALL_THROUGH.has(memory[start]!);
|
|
81
|
+
}
|
|
82
|
+
return blocks;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Joins ranges in address order that touch or overlap. */
|
|
86
|
+
function merged(ranges: readonly AddressRange[]): AddressRange[] {
|
|
87
|
+
const result: AddressRange[] = [];
|
|
88
|
+
for (const range of [...ranges].sort((a, b) => a.start - b.start)) {
|
|
89
|
+
const last = result.at(-1);
|
|
90
|
+
if (last !== undefined && range.start <= last.end + 1) last.end = Math.max(last.end, range.end);
|
|
91
|
+
else result.push({ ...range });
|
|
92
|
+
}
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A place where code goes or reads: the instruction (or table) at `from`, and what it names. */
|
|
97
|
+
interface Flow {
|
|
98
|
+
from: number;
|
|
99
|
+
to: number;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface DataReference {
|
|
103
|
+
from: number;
|
|
104
|
+
start: number;
|
|
105
|
+
end: number;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The code flows and the data references of the instructions, the knowledge
|
|
110
|
+
* references and the operand expressions. `indexedEnd` gives the last address
|
|
111
|
+
* that an indexed operand can read.
|
|
112
|
+
*/
|
|
113
|
+
function flowsOf(input: DropInput, inImage: (address: number) => boolean, indexedEnd: (operand: number) => number) {
|
|
114
|
+
const flows: Flow[] = [];
|
|
115
|
+
const reads: DataReference[] = [];
|
|
116
|
+
const { memory } = input;
|
|
117
|
+
const word = (at: number) => memory[at]! | (memory[(at + 1) & 0xffff]! << 8);
|
|
118
|
+
const immediates: Array<{ at: number; value: number }> = [];
|
|
119
|
+
let previousEnd = -2;
|
|
120
|
+
const pairs = () => {
|
|
121
|
+
// A low byte and a high byte near each other in one block: the address of a vector, a table or an RTS target.
|
|
122
|
+
immediates.forEach((low, index) => {
|
|
123
|
+
for (let other = Math.max(0, index - PAIR_WINDOW); other <= Math.min(immediates.length - 1, index + PAIR_WINDOW); other++) {
|
|
124
|
+
if (other === index) continue;
|
|
125
|
+
const target = low.value | (immediates[other]!.value << 8);
|
|
126
|
+
if (!inImage(target)) continue;
|
|
127
|
+
flows.push({ from: low.at, to: target }, { from: low.at, to: (target + 1) & 0xffff });
|
|
128
|
+
reads.push({ from: low.at, start: target, end: target });
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
immediates.length = 0;
|
|
132
|
+
};
|
|
133
|
+
for (const at of [...input.instructions.keys()].sort((a, b) => a - b)) {
|
|
134
|
+
const opcode = memory[at]!;
|
|
135
|
+
const { mode } = OPCODES[opcode]!;
|
|
136
|
+
if (at > previousEnd + 1) pairs();
|
|
137
|
+
previousEnd = at + input.instructions.get(at)! - 1;
|
|
138
|
+
const operand = input.instructions.get(at) === 3 ? word(at + 1) : memory[at + 1]!;
|
|
139
|
+
switch (mode) {
|
|
140
|
+
case "rel":
|
|
141
|
+
flows.push({ from: at, to: (at + 2 + (operand < 0x80 ? operand : operand - 0x100)) & 0xffff });
|
|
142
|
+
break;
|
|
143
|
+
case "imm":
|
|
144
|
+
immediates.push({ at, value: operand });
|
|
145
|
+
break;
|
|
146
|
+
case "ind":
|
|
147
|
+
reads.push({ from: at, start: operand, end: (operand + 1) & 0xffff });
|
|
148
|
+
if (inImage(operand) && inImage((operand + 1) & 0xffff)) flows.push({ from: at, to: word(operand) });
|
|
149
|
+
break;
|
|
150
|
+
case "abs":
|
|
151
|
+
case "zp":
|
|
152
|
+
if (opcode === 0x20 || opcode === 0x4c) flows.push({ from: at, to: operand });
|
|
153
|
+
else reads.push({ from: at, start: operand, end: operand });
|
|
154
|
+
break;
|
|
155
|
+
case "abx":
|
|
156
|
+
case "aby":
|
|
157
|
+
case "zpx":
|
|
158
|
+
case "zpy":
|
|
159
|
+
reads.push({ from: at, start: operand, end: indexedEnd(operand) });
|
|
160
|
+
break;
|
|
161
|
+
case "izx":
|
|
162
|
+
case "izy":
|
|
163
|
+
reads.push({ from: at, start: operand, end: (operand + 1) & 0xff });
|
|
164
|
+
break;
|
|
165
|
+
default:
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
if (NO_FALL_THROUGH.has(opcode)) pairs();
|
|
169
|
+
}
|
|
170
|
+
pairs();
|
|
171
|
+
for (const reference of input.references) {
|
|
172
|
+
if (inside(reference.from, input.changed)) continue;
|
|
173
|
+
if (reference.kind === "call" || reference.kind === "jump" || reference.kind === "pointer") flows.push({ from: reference.from, to: reference.to });
|
|
174
|
+
reads.push({ from: reference.from, start: reference.to, end: reference.to });
|
|
175
|
+
}
|
|
176
|
+
for (const [at, targets] of input.operandTargets) {
|
|
177
|
+
for (const target of targets) {
|
|
178
|
+
flows.push({ from: at, to: target });
|
|
179
|
+
reads.push({ from: at, start: target, end: target });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return { flows, reads };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The entries of a table of addresses or of jumps. */
|
|
186
|
+
function tableTargets(table: { start: number; end: number; type: RegionType }, memory: Uint8Array): number[] {
|
|
187
|
+
if (table.type === "jumps") return Array.from({ length: Math.floor((table.end - table.start + 1) / 3) }, (_, index) => table.start + 3 * index);
|
|
188
|
+
return pointerTableEntries(table as { start: number; end: number; type: PointerTableType }, (address) => memory[address]!).map((entry) => entry.target);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const isTable = (type: RegionType) => type === "jumps" || (POINTER_TABLE_TYPES as readonly string[]).includes(type);
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The free ranges of the baked image, the code that a run executed and the
|
|
195
|
+
* entry does not reach, and the refusals of --drop and --keep.
|
|
196
|
+
*/
|
|
197
|
+
export function planDrops(input: DropInput): DropPlan {
|
|
198
|
+
const inImage = (address: number) => inside(address, input.segments);
|
|
199
|
+
const touched = (address: number) => input.coverage !== undefined && input.coverage[address] !== 0;
|
|
200
|
+
const executed = (address: number) => input.coverage !== undefined && (input.coverage[address]! & COVERAGE.ramExecute) !== 0;
|
|
201
|
+
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 })));
|
|
202
|
+
// The source writes a data region as data, also where Ghidra decoded instructions in it: those are no code.
|
|
203
|
+
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)));
|
|
204
|
+
const blocks = blocksOf(instructions, input.memory);
|
|
205
|
+
// An indexed operand reads in the region that holds it, and in the next region when it is the last byte (table-1,x).
|
|
206
|
+
// Without a region, it can read the 256 bytes from the operand.
|
|
207
|
+
const holding = (address: number) => regions.find((region) => address >= region.start && address <= region.end);
|
|
208
|
+
const indexedEnd = (operand: number) => {
|
|
209
|
+
const holder = holding(operand);
|
|
210
|
+
const next = holder === undefined || holder.end === operand ? holding((operand + 1) & 0xffff) : undefined;
|
|
211
|
+
return next?.end ?? holder?.end ?? Math.min(0xffff, operand + 0xff);
|
|
212
|
+
};
|
|
213
|
+
const { flows, reads } = flowsOf({ ...input, instructions }, inImage, indexedEnd);
|
|
214
|
+
|
|
215
|
+
for (const range of [...input.keep, ...input.drop]) {
|
|
216
|
+
for (let address = range.start; address <= range.end; address++) {
|
|
217
|
+
if (!inImage(address)) throw new Refusal("invalid-input", `${shown(range)} is not in the program: ${formatC64Address(address)} is in no segment.`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
for (const range of input.drop) {
|
|
221
|
+
const kept = input.keep.find((other) => overlaps(range, other));
|
|
222
|
+
if (kept !== undefined) throw new Refusal("invalid-input", `--drop ${shown(range)} overlaps --keep ${shown(kept)}.`);
|
|
223
|
+
const changed = input.changed.find((other) => overlaps(range, other));
|
|
224
|
+
if (changed !== undefined) throw new Refusal("invalid-input", `--drop ${shown(range)} overlaps the patch ${shown(changed)}, which the export changed.`);
|
|
225
|
+
const cutBlock = blocks.find((block) => overlaps(block, range) && !within(block, range));
|
|
226
|
+
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.`);
|
|
227
|
+
const cutData = regions.find((region) => !CODE_TYPES.includes(region.type) && overlaps(region, range) && !within(region, range));
|
|
228
|
+
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.`);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Tables that a run read or that the knowledge names: their entries can be the only way to code, so they are roots.
|
|
232
|
+
const tables = regions.filter((region) => isTable(region.type));
|
|
233
|
+
const tableUsers = (table: AddressRange) => reads.filter((read) => read.start <= table.end && table.start <= read.end).map((read) => read.from);
|
|
234
|
+
const tableRoots: Root[] = [];
|
|
235
|
+
for (const table of tables) {
|
|
236
|
+
const targets = tableTargets(table, input.memory);
|
|
237
|
+
let read = false;
|
|
238
|
+
for (let address = table.start; address <= table.end && !read; address++) read = touched(address);
|
|
239
|
+
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" });
|
|
240
|
+
for (const from of tableUsers(table)) for (const target of targets) flows.push({ from, to: target });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const asRegions = (list: readonly AddressRange[]) => list.map((block) => ({ ...block, type: "code" }));
|
|
244
|
+
const references = flows.map((flow) => ({ ...flow, kind: "jump" }));
|
|
245
|
+
const passA = separate({ segments: [...input.segments], memory: input.memory, ...(input.entry === undefined ? {} : { entry: input.entry }), codeRegions: asRegions(blocks), references, roots: tableRoots });
|
|
246
|
+
const rooted = passA.codeRegions.every((region) => region.reachable !== undefined);
|
|
247
|
+
const reachable = (index: number) => !rooted || passA.codeRegions[index]!.reachable === true;
|
|
248
|
+
for (const range of input.drop) {
|
|
249
|
+
const live = blocks.findIndex((block, index) => within(block, range) && reachable(index));
|
|
250
|
+
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.`);
|
|
251
|
+
}
|
|
252
|
+
const ran = (block: AddressRange) => {
|
|
253
|
+
for (let address = block.start; address <= block.end; address++) if (executed(address)) return true;
|
|
254
|
+
return false;
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
// Pass B: what stays. Blocks in a --drop range are gone.
|
|
258
|
+
const candidates = blocks.filter((block) => !input.drop.some((range) => within(block, range)));
|
|
259
|
+
const extra: Root[] = [...tableRoots];
|
|
260
|
+
for (const block of candidates) {
|
|
261
|
+
if (ran(block)) extra.push({ address: block.start, from: "executed code" });
|
|
262
|
+
else if ([...input.keep, ...input.changed].some((range) => overlaps(block, range))) extra.push({ address: block.start, from: "kept range" });
|
|
263
|
+
}
|
|
264
|
+
const passB = separate({ segments: [...input.segments], memory: input.memory, ...(input.entry === undefined ? {} : { entry: input.entry }), codeRegions: asRegions(candidates), references, roots: extra });
|
|
265
|
+
const automatic = input.coverage !== undefined && rooted;
|
|
266
|
+
const stays = candidates.filter((_, index) => !automatic || passB.codeRegions[index]!.reachable !== false);
|
|
267
|
+
const droppedCode = candidates.filter((_, index) => automatic && passB.codeRegions[index]!.reachable === false);
|
|
268
|
+
const inStaying = (address: number) => stays.some((block) => address >= block.start && address <= block.end);
|
|
269
|
+
for (const range of input.drop) {
|
|
270
|
+
const into = flows.find((flow) => inStaying(flow.from) && inside(flow.to, [range]));
|
|
271
|
+
if (into !== undefined) throw new Refusal("invalid-input", `--drop ${shown(range)}: the code at ${formatC64Address(into.from)} stays and goes to ${formatC64Address(into.to)}.`);
|
|
272
|
+
const read = reads.find((item) => inStaying(item.from) && overlaps(item, range));
|
|
273
|
+
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) })}.`);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Data: a region of a droppable type that no run touched and that nothing that stays names.
|
|
277
|
+
const gone = [...input.drop, ...droppedCode];
|
|
278
|
+
const imageStart = Math.min(...input.segments.map((segment) => segment.start));
|
|
279
|
+
const units = automatic
|
|
280
|
+
? regions.filter((region) => {
|
|
281
|
+
if (!DROPPABLE_DATA.includes(region.type) || gone.some((range) => overlaps(range, region))) return false;
|
|
282
|
+
if ([...input.keep, ...input.changed, VECTORS].some((range) => overlaps(range, region)) || (region.start <= imageStart && imageStart <= region.end)) return false;
|
|
283
|
+
for (let address = region.start; address <= region.end; address++) if (touched(address)) return false;
|
|
284
|
+
return true;
|
|
285
|
+
})
|
|
286
|
+
: [];
|
|
287
|
+
const dropped = new Set(units.map((_, index) => index));
|
|
288
|
+
const unitAt = (address: number) => units.findIndex((unit) => address >= unit.start && address <= unit.end);
|
|
289
|
+
// A name from code that stays, or from a unit that stays, keeps the unit. Kept tables keep their entries.
|
|
290
|
+
for (let grown = true; grown; ) {
|
|
291
|
+
grown = false;
|
|
292
|
+
const keeps = (from: number) => inStaying(from) || (!inside(from, gone) && (unitAt(from) < 0 || !dropped.has(unitAt(from))));
|
|
293
|
+
for (const [index, unit] of units.entries()) {
|
|
294
|
+
if (!dropped.has(index)) continue;
|
|
295
|
+
const named = reads.some((read) => read.start <= unit.end && unit.start <= read.end && keeps(read.from));
|
|
296
|
+
const entry = units.some((table, other) => !dropped.has(other) && isTable(table.type) && tableTargets(table, input.memory).some((target) => target >= unit.start && target <= unit.end));
|
|
297
|
+
const fromTable = tables.some((table) => unitAt(table.start) < 0 && tableTargets(table, input.memory).some((target) => target >= unit.start && target <= unit.end));
|
|
298
|
+
if (named || entry || fromTable) {
|
|
299
|
+
dropped.delete(index);
|
|
300
|
+
grown = true;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
const droppedData = units.filter((_, index) => dropped.has(index));
|
|
305
|
+
|
|
306
|
+
const pieces = [
|
|
307
|
+
...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") })),
|
|
308
|
+
...droppedCode.map((range) => ({ ...range, code: true, data: false })),
|
|
309
|
+
...droppedData.map((range) => ({ ...range, code: false, data: true })),
|
|
310
|
+
].sort((a, b) => a.start - b.start);
|
|
311
|
+
const free: FreeRange[] = [];
|
|
312
|
+
for (const piece of pieces) {
|
|
313
|
+
const last = free.at(-1);
|
|
314
|
+
const what = (code: boolean, data: boolean): FreeRange["what"] => (code && data ? "code and data" : code ? "code" : "data");
|
|
315
|
+
if (last !== undefined && piece.start <= last.end + 1) {
|
|
316
|
+
last.end = Math.max(last.end, piece.end);
|
|
317
|
+
last.what = what(last.what !== "data" || piece.code, last.what !== "code" || piece.data);
|
|
318
|
+
} else free.push({ start: piece.start, end: piece.end, what: what(piece.code, piece.data) });
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const routines = [...input.routines].sort((a, b) => a.address - b.address);
|
|
322
|
+
const unreachableExecuted = merged(blocks.filter((block, index) => rooted && passA.codeRegions[index]!.reachable === false && ran(block) && !input.drop.some((range) => within(block, range)))).map((range) => {
|
|
323
|
+
const routine = routines.filter((item) => item.address <= range.start).at(-1)?.name;
|
|
324
|
+
return { ...range, ...(routine === undefined ? {} : { routine }) };
|
|
325
|
+
});
|
|
326
|
+
return { free, unreachableExecuted, rooted };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** The label of a free range. */
|
|
330
|
+
export const freeName = (range: AddressRange) => `free_${range.start.toString(16).padStart(4, "0")}`;
|
|
331
|
+
|
|
332
|
+
/** What the export does with one test file of the project. */
|
|
333
|
+
export type TestRewrite = { kind: "scenario" | "run"; text: string } | { reason: string };
|
|
334
|
+
|
|
335
|
+
/** Each location that a step names: the strings of address, pc, start and end, and the names in a memory list. */
|
|
336
|
+
function locationsOf(value: unknown, found: string[] = []): string[] {
|
|
337
|
+
if (Array.isArray(value)) for (const item of value) locationsOf(item, found);
|
|
338
|
+
else if (value !== null && typeof value === "object") {
|
|
339
|
+
for (const [key, item] of Object.entries(value)) {
|
|
340
|
+
if (typeof item === "string" && ["address", "pc", "start", "end"].includes(key)) found.push(item);
|
|
341
|
+
else if (key === "memory" && Array.isArray(item)) {
|
|
342
|
+
for (const entry of item) if (typeof entry === "string") found.push(entry);
|
|
343
|
+
locationsOf(item, found);
|
|
344
|
+
} else locationsOf(item, found);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return found;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const hasSnapshot = (value: unknown): boolean =>
|
|
351
|
+
Array.isArray(value) ? value.some(hasSnapshot) : value !== null && typeof value === "object" ? Object.entries(value).some(([key, item]) => key === "snapshot" || hasSnapshot(item)) : false;
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* A scenario or a run file of the project for the new project. A scenario
|
|
355
|
+
* compares the baseline (the exported program) with the build of the new
|
|
356
|
+
* project: a step of the original side alone goes, and a step of the rebuild
|
|
357
|
+
* side alone runs on both sides. A run file runs the build. A test is left out when it restores a
|
|
358
|
+
* snapshot (a state of the old program), names something that the exported
|
|
359
|
+
* program does not have, or names an address in a free range.
|
|
360
|
+
*/
|
|
361
|
+
export function rewriteTest(text: string, name: string, symbols: ReadonlyMap<string, number>, free: readonly AddressRange[]): TestRewrite {
|
|
362
|
+
let test: Record<string, unknown>;
|
|
363
|
+
try {
|
|
364
|
+
const parsed: unknown = JSON.parse(text);
|
|
365
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return { reason: "it is not a JSON object" };
|
|
366
|
+
test = parsed as Record<string, unknown>;
|
|
367
|
+
} catch {
|
|
368
|
+
return { reason: "it is not JSON" };
|
|
369
|
+
}
|
|
370
|
+
const scenario = typeof test.original === "object" && typeof test.rebuild === "object" && Array.isArray(test.steps);
|
|
371
|
+
const run = typeof test.start === "object" && test.start !== null && Array.isArray(test.steps);
|
|
372
|
+
if (!scenario && !run) return { reason: "it is not a scenario or a run file" };
|
|
373
|
+
if (hasSnapshot(test)) return { reason: "it restores a snapshot, which is a state of the old program" };
|
|
374
|
+
for (const location of locationsOf(test.steps)) {
|
|
375
|
+
if (/^\$[0-9a-fA-F]{1,4}$/.test(location)) {
|
|
376
|
+
const address = Number.parseInt(location.slice(1), 16);
|
|
377
|
+
if (inside(address, free)) return { reason: `it names ${location}, which is in a free range` };
|
|
378
|
+
} else if (!symbols.has(location)) return { reason: `it names ${location}, which the exported program does not have` };
|
|
379
|
+
}
|
|
380
|
+
const side = (old: unknown, program: string) => ({ program: `${program}.prg`, symbols: `${program}.json`, ...(typeof old === "object" && old !== null && "videoStandard" in old ? { videoStandard: (old as { videoStandard: unknown }).videoStandard } : {}) });
|
|
381
|
+
if (scenario) {
|
|
382
|
+
// Both sides are the exported program now: a step of the original alone (for example a key for its intro) goes, and a step of the rebuild alone runs on both sides.
|
|
383
|
+
const { original, rebuild, steps, ...rest } = test;
|
|
384
|
+
const both = (steps as unknown[]).flatMap((step) => {
|
|
385
|
+
if (step === null || typeof step !== "object" || !("side" in step)) return [step];
|
|
386
|
+
const { side: only, ...action } = step as Record<string, unknown>;
|
|
387
|
+
return only === "original" ? [] : [action];
|
|
388
|
+
});
|
|
389
|
+
return { kind: "scenario", text: `${JSON.stringify({ ...rest, original: side(original, `baseline/${name}`), rebuild: side(rebuild, `build/${name}`), steps: both }, null, 2)}\n` };
|
|
390
|
+
}
|
|
391
|
+
const start = test.start as Record<string, unknown>;
|
|
392
|
+
const symbolsFile = test.symbols === undefined || test.symbols === "none" ? {} : { symbols: `build/${name}.json` };
|
|
393
|
+
return { kind: "run", text: `${JSON.stringify({ ...test, start: { ...start, program: `build/${name}.prg` }, ...symbolsFile }, null, 2)}\n` };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export interface ReadmeInput {
|
|
397
|
+
name: string;
|
|
398
|
+
project: string;
|
|
399
|
+
revision: string | null;
|
|
400
|
+
date: string;
|
|
401
|
+
/** main.asm, or loader.asm for a program that needs its entry state. */
|
|
402
|
+
entryFile: string;
|
|
403
|
+
free: readonly FreeRange[];
|
|
404
|
+
switches: ReadonlyArray<{ name: string; kind: string; value: number }>;
|
|
405
|
+
tests: { written: ReadonlyArray<{ file: string; kind: "scenario" | "run" }>; leftOut: ReadonlyArray<{ file: string; reason: string }> };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** The README of the new project: the commands first, then the free ranges, the files and where the program comes from. */
|
|
409
|
+
export function readmeText(input: ReadmeInput): string {
|
|
410
|
+
const { name } = input;
|
|
411
|
+
const lines = [
|
|
412
|
+
`# ${name}`,
|
|
413
|
+
"",
|
|
414
|
+
`The start of a new program, exported from \`${input.project}\` (knowledge revision ${input.revision ?? "none"}) on ${input.date}.`,
|
|
415
|
+
"",
|
|
416
|
+
"## Build",
|
|
417
|
+
"",
|
|
418
|
+
"With the c64-assembler skill:",
|
|
419
|
+
"",
|
|
420
|
+
"```",
|
|
421
|
+
...(input.entryFile === "main.asm"
|
|
422
|
+
? [`assembler.ts build src main.asm --out build/${name}.prg --out-symbols build/${name}.json --compare`]
|
|
423
|
+
: [`assembler.ts build src ${input.entryFile} --out build/${name}.prg --out-symbols build/${name}.json`, `assembler.ts build src main.asm --out .c64-re-tools/local/program.prg --compare`]),
|
|
424
|
+
"```",
|
|
425
|
+
"",
|
|
426
|
+
"`--compare` checks that the source gives the program in the knowledge. After a change to the source, it gives FAIL: that is correct.",
|
|
427
|
+
"",
|
|
428
|
+
"With ACME only, from the folder `src`:",
|
|
429
|
+
"",
|
|
430
|
+
"```",
|
|
431
|
+
`acme -f cbm -o ../build/${name}.prg ${input.entryFile}`,
|
|
432
|
+
"```",
|
|
433
|
+
"",
|
|
434
|
+
"## Test",
|
|
435
|
+
"",
|
|
436
|
+
];
|
|
437
|
+
if (input.tests.written.length === 0) lines.push("No tests came with the program. Write run files with `expect` steps in `tests/` (c64-development skill).");
|
|
438
|
+
else {
|
|
439
|
+
lines.push(`Build first. A scenario compares \`build/${name}.prg\` with \`baseline/${name}.prg\`, the exported program. A run file runs \`build/${name}.prg\`. Use the c64-testing skill:`, "", "```");
|
|
440
|
+
for (const test of input.tests.written) lines.push(test.kind === "run" ? `testing.ts run ${test.file} --out .c64-re-tools/local/runs/${test.file.replace(/^tests\//, "").replace(/\.json$/, "")}` : `testing.ts test ${test.file}`);
|
|
441
|
+
lines.push("```");
|
|
442
|
+
}
|
|
443
|
+
lines.push("", "## Free ranges", "");
|
|
444
|
+
if (input.free.length === 0) lines.push("None: the export dropped nothing.");
|
|
445
|
+
else {
|
|
446
|
+
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 |", "|---|---|---|");
|
|
447
|
+
for (const range of input.free) lines.push(`| \`${shown(range)}\` | ${range.end - range.start + 1} | ${range.what} |`);
|
|
448
|
+
}
|
|
449
|
+
lines.push(
|
|
450
|
+
"",
|
|
451
|
+
"## Files",
|
|
452
|
+
"",
|
|
453
|
+
`- \`src/\`: the source. You own it now: change it as you like.`,
|
|
454
|
+
`- \`baseline/${name}.prg\` and \`baseline/${name}.json\`: the exported program and its symbols, the reference of the scenarios.`,
|
|
455
|
+
"- `tests/`: the tests.",
|
|
456
|
+
"- `.c64-re-tools/knowledge/`: the names, comments and memory map of the exported program. They do not follow your changes to the source.",
|
|
457
|
+
"",
|
|
458
|
+
"## Origin",
|
|
459
|
+
"",
|
|
460
|
+
);
|
|
461
|
+
if (input.switches.length === 0) lines.push("The program had no switches.");
|
|
462
|
+
else {
|
|
463
|
+
lines.push("The switches of the rebuild are now fixed code:", "", "| Switch | Kind | Value |", "|---|---|---|");
|
|
464
|
+
for (const item of input.switches) lines.push(`| ${item.name} | ${item.kind} | ${item.value} |`);
|
|
465
|
+
}
|
|
466
|
+
if (input.tests.leftOut.length > 0) {
|
|
467
|
+
lines.push("", "Tests that the export left out:", "");
|
|
468
|
+
for (const item of input.tests.leftOut) lines.push(`- \`${item.file}\`: ${item.reason}.`);
|
|
469
|
+
}
|
|
470
|
+
return `${lines.join("\n")}\n`;
|
|
471
|
+
}
|