@henols/c64-re-tools 2.6.0-rc.3 → 2.6.0-rc.5

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 (37) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +26 -12
  3. package/skills/c64-assembler/scripts/assembler.ts +25 -13
  4. package/skills/c64-development/SKILL.md +1 -1
  5. package/skills/c64-docs/SKILL.md +4 -4
  6. package/skills/c64-docs/scripts/docs.ts +3 -3
  7. package/skills/c64-docs/scripts/lib/reference.ts +3 -3
  8. package/skills/c64-docs/scripts/lib/source-map.ts +9 -4
  9. package/skills/c64-knowledge/SKILL.md +25 -16
  10. package/skills/c64-knowledge/scripts/knowledge.ts +26 -41
  11. package/skills/c64-packer/SKILL.md +1 -1
  12. package/skills/c64-provenance/SKILL.md +11 -10
  13. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  14. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  15. package/skills/c64-reverse-engineering/SKILL.md +6 -6
  16. package/skills/c64-source/SKILL.md +46 -39
  17. package/skills/c64-source/scripts/lib/export.ts +5 -4
  18. package/skills/c64-source/scripts/lib/loader.ts +6 -6
  19. package/skills/c64-source/scripts/lib/source.ts +11 -24
  20. package/skills/c64-source/scripts/lib/stage.ts +2 -2
  21. package/skills/c64-source/scripts/source.ts +135 -68
  22. package/skills/c64-static-analysis/SKILL.md +4 -4
  23. package/skills/c64-static-analysis/scripts/static-analysis.ts +26 -33
  24. package/skills/c64-testing/SKILL.md +1 -1
  25. package/skills/c64-testing/references/scenario-format.md +1 -1
  26. package/skills/c64-unpacker/SKILL.md +2 -0
  27. package/skills/c64-unpacker/scripts/lib/loads.ts +33 -12
  28. package/skills/c64-unpacker/scripts/unpacker.ts +5 -3
  29. package/src/build-name.ts +50 -0
  30. package/src/host/vice/session.ts +6 -1
  31. package/src/knowledge/program.ts +44 -1
  32. package/src/knowledge/read.ts +3 -7
  33. package/src/knowledge/schema.ts +27 -8
  34. package/src/knowledge/text.ts +4 -2
  35. package/src/knowledge/write.ts +47 -14
  36. package/src/native/acme.ts +1 -1
  37. package/src/project.ts +13 -1
@@ -61,6 +61,7 @@ Each step has one of these kinds:
61
61
  - `{ "frames": 50 }` runs 1 to 30000 frames.
62
62
  - `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 300 } }` runs until the target. The target kinds are `address`, `memory` and `raster`. `timeoutFrames` is 1 to 30000. The default is 3000.
63
63
  - `{ "capture": "level1" }` captures a part. Only `loads` takes this step. Give each capture step a different name of 1 to 64 letters, digits, dots, underscores or hyphens.
64
+ - `{ "save": "at-call" }` writes the machine state to `<out>/at-call.vsf`. Only `loads` takes this step. A run of the program can start from this snapshot file, for example at the call of a routine of a loading stage. Give each save step a different name.
64
65
 
65
66
  An address in a step can be a name. The script refuses an unknown name before the program runs. The message gives the file and the step.
66
67
 
@@ -231,6 +232,7 @@ A segment is a block of RAM from `$0400` that the program changed after the capt
231
232
 
232
233
  - `loaded`: true when a capture has a segment.
233
234
  - `captures`: one item for each capture step, with `capture`, `out`, `files`, `removed`, `pc`, `segments`, `excluded`, `differsFromReset`, `smallChanges` and `drive`.
235
+ - `saved`: one item for each save step, with `save`, `file` and `pc`.
234
236
  - `smallChanges`: the count of changed bytes in blocks that are smaller than `--min-block`.
235
237
  - `keyWait: true`: the CPU was in the KERNAL wait for a key, at READY or at an INPUT statement.
236
238
  - `drive`: the name of the drive file, with `--drive`.
@@ -1,8 +1,10 @@
1
1
  // The loads command of c64-unpacker: one capture for each part of a
2
- // multi-load program. The steps file has action steps and capture steps; a
3
- // capture writes what the C64 side changed since the previous capture as an
4
- // image with its entry state, and with --drive the drive RAM as a PRG for
5
- // knowledge space drive8. No tool guesses where a load ends: the steps decide.
2
+ // multi-load program. The steps file has action steps, capture steps and save
3
+ // steps; a capture writes what the C64 side changed since the previous
4
+ // capture as an image with its entry state, and with --drive the drive RAM as
5
+ // a PRG for knowledge space drive8. A save writes the machine state as a
6
+ // snapshot file, which a run can start from. No tool guesses where a load
7
+ // ends: the steps decide.
6
8
 
7
9
  import { type AddressRange, COVERAGE, formatC64Address } from "#src/c64.ts";
8
10
  import { Refusal } from "#src/errors.ts";
@@ -17,9 +19,9 @@ import { entryStateFile, json, machineState, readRam, readyState, removeStaleFil
17
19
  import { FIRST_SEGMENT_ADDRESS } from "./stages.ts";
18
20
 
19
21
 
20
- export type LoadStep = ActionStep | { capture: string };
22
+ export type LoadStep = ActionStep | { capture: string } | { save: string };
21
23
 
22
- /** A capture name: letters, digits, dots, underscores or hyphens. */
24
+ /** A capture or save name: letters, digits, dots, underscores or hyphens. */
23
25
  const NAME = /^[A-Za-z0-9._-]{1,64}$/;
24
26
  /** The drive RAM of a 1541. */
25
27
  const DRIVE_RAM = 0x0800;
@@ -28,7 +30,7 @@ const KERNAL_LOAD = 0xffd5;
28
30
  /** The KERNAL loop that waits for a key at READY. or at an INPUT statement. */
29
31
  const KERNAL_KEY_WAIT = { start: 0xe5cd, end: 0xe5d5 };
30
32
 
31
- /** Reads and checks the steps file of loads: action steps with $ addresses, and capture steps with new names. */
33
+ /** Reads and checks the steps file of loads: action steps with $ addresses, and capture and save steps with new names. */
32
34
  export function readLoadSteps(path: string): LoadStep[] {
33
35
  let value: unknown;
34
36
  try {
@@ -42,9 +44,17 @@ export function readLoadSteps(path: string): LoadStep[] {
42
44
  };
43
45
  if (!Array.isArray(value) || value.length === 0) return fail("the steps are a JSON list with at least one step");
44
46
  const names = new Set<string>();
47
+ const saves = new Set<string>();
45
48
  value.forEach((step: unknown, index) => {
46
49
  const at = `step ${index + 1}`;
47
50
  if (!isObject(step)) return fail(`${at} must be an object`);
51
+ if ("save" in step) {
52
+ if (Object.keys(step).length !== 1) fail(`${at}: a save step has only save`);
53
+ if (typeof step.save !== "string" || !NAME.test(step.save)) fail(`${at}: save needs a name of 1 to 64 letters, digits, dots, underscores or hyphens`);
54
+ if (saves.has(step.save as string)) fail(`${at}: the save name ${step.save as string} is used before`);
55
+ saves.add(step.save as string);
56
+ return;
57
+ }
48
58
  if ("capture" in step) {
49
59
  if (Object.keys(step).length !== 1) fail(`${at}: a capture step has only capture`);
50
60
  if (typeof step.capture !== "string" || !NAME.test(step.capture)) fail(`${at}: capture needs a name of 1 to 64 letters, digits, dots, underscores or hyphens`);
@@ -54,14 +64,14 @@ export function readLoadSteps(path: string): LoadStep[] {
54
64
  }
55
65
  const kinds = Object.keys(step).filter((key) => (ACTION_STEP_KINDS as readonly string[]).includes(key));
56
66
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
57
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...VICE_STEP_KINDS, "capture"].join(", ")}`);
67
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...VICE_STEP_KINDS, "capture", "save"].join(", ")}`);
58
68
  // The step with its defaults filled in, as the shared schema of the action steps gives it.
59
69
  const checked = checkActionStep(kinds[0] as ActionStepKind, step, at, fail);
60
70
  // Its names resolve now: an unknown name stops the call before the emulator starts.
61
71
  checkStepNames([checked], knowledgeAt(), `--steps ${path}`, index + 1);
62
72
  (value as unknown[])[index] = checked;
63
73
  });
64
- if (names.size === 0) fail("the steps have no capture step");
74
+ if (names.size === 0 && saves.size === 0) fail("the steps have no capture step and no save step");
65
75
  return value as LoadStep[];
66
76
  }
67
77
 
@@ -149,12 +159,23 @@ export async function loads(program: string, options: { out: string; steps: Load
149
159
  }
150
160
 
151
161
  const captures: Array<Record<string, unknown>> = [];
162
+ const saved: Array<Record<string, unknown>> = [];
152
163
  for (const [index, step] of options.steps.entries()) {
164
+ if ("save" in step) {
165
+ // The machine state as a snapshot file: a run starts from it, for example at the call of a loading stage.
166
+ if ((await client.status()).state === "running") await client.execution({ action: "pause", space: "c64" });
167
+ await client.snapshot({ action: "save", name: "loads-save" });
168
+ const path = `${options.out}/${step.save}.vsf`;
169
+ const file = writeReported(path, await client.snapshotExport("loads-save"), { what: "--out" });
170
+ await client.snapshot({ action: "remove", name: "loads-save" });
171
+ saved.push({ save: step.save, file, pc: formatC64Address((await client.registersGet("c64")).pc) });
172
+ continue;
173
+ }
153
174
  if (!("capture" in step)) {
154
175
  const notReached = await runActionStep(client, step, knowledgeAt());
155
176
  if (notReached !== undefined && "runUntil" in step) {
156
177
  const reason = `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It stopped by ${notReached.stopReason} at ${formatC64Address(notReached.pc)}.`;
157
- return { output: { loaded: false, reason, captures }, failed: true };
178
+ return { output: { loaded: false, reason, captures, ...(saved.length === 0 ? {} : { saved }) }, failed: true };
158
179
  }
159
180
  continue;
160
181
  }
@@ -226,9 +247,9 @@ export async function loads(program: string, options: { out: string; steps: Load
226
247
  if (captures.length > 0 && captures.every((capture) => (capture.segments as unknown[]).length === 0)) {
227
248
  const waits = captures.some((capture) => capture.keyWait === true) ? " The C64 waited for a key at READY. or at an INPUT statement, so the load ended or did not start." : "";
228
249
  const reason = `No capture has a segment: the program changed no block of RAM from ${formatC64Address(FIRST_SEGMENT_ADDRESS)} on.${waits}`;
229
- return { output: { loaded: false, reason, captures }, failed: true };
250
+ return { output: { loaded: false, reason, captures, ...(saved.length === 0 ? {} : { saved }) }, failed: true };
230
251
  }
231
- return { output: { loaded: true, captures }, failed: false };
252
+ return { output: { loaded: true, captures, ...(saved.length === 0 ? {} : { saved }) }, failed: false };
232
253
  } finally {
233
254
  await client.close();
234
255
  }
@@ -642,7 +642,9 @@ function loaded(call: Call, { output, failed }: { output: Record<string, unknown
642
642
  if (failed) return result;
643
643
  const out = call.string("out")!;
644
644
  const drive = call.flag("drive") ? ` Put the drive RAM ${out}/<name>/drive8.prg into the project knowledge in the space drive8.` : "";
645
- return reply(result, { hint: `Put the capture ${out}/<name>/image.json of the part that you work on into the project knowledge.${drive}` });
645
+ const captures = (output.captures as unknown[]).length === 0 ? "" : `Put the capture ${out}/<name>/image.json of the part that you work on into the project knowledge.${drive}`;
646
+ const saved = output.saved === undefined ? "" : `A run of the program can start from a snapshot file ${out}/<name>.vsf.`;
647
+ return reply(result, { hint: [captures, saved].filter((text) => text !== "").join(" ") });
646
648
  }
647
649
 
648
650
  const COMMANDS: CommandSpec[] = [
@@ -702,10 +704,10 @@ const COMMANDS: CommandSpec[] = [
702
704
  },
703
705
  {
704
706
  name: "loads",
705
- summary: "Runs a multi-load program with the steps file. Each capture step {\"capture\": \"<name>\"} writes <dir>/<name>/ with image.bin, image.json, entry_state.json and a PRG for each block that the C64 side changed since the previous capture.",
707
+ summary: "Runs a multi-load program with the steps file. Each capture step {\"capture\": \"<name>\"} writes <dir>/<name>/ with image.bin, image.json, entry_state.json and a PRG for each block that the C64 side changed since the previous capture. Each save step {\"save\": \"<name>\"} writes the machine state to <dir>/<name>.vsf.",
706
708
  subjects: [{ name: "<program>", help: "a PRG, or a disk, tape or cartridge image, relative to the project folder" }],
707
709
  options: {
708
- steps: { ...STEPS, required: true, help: "action steps and capture steps (JSON)" },
710
+ steps: { ...STEPS, required: true, help: "action steps, capture steps and save steps (JSON)" },
709
711
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the folder for the captures, relative to the project folder" },
710
712
  drive: { kind: "flag", help: "also write the 2 KiB drive RAM as drive8.prg, for knowledge space drive8" },
711
713
  "min-block": { kind: "count", value: "<bytes>", min: 1, max: 0x10000, default: 64, help: "write a changed block of at least this many bytes (default 64)" },
@@ -0,0 +1,50 @@
1
+ // The name of a build: the file name tells what kind of build a program is.
2
+ // A release build is release_<label>. A build of config.asm is clean when each
3
+ // switch has its default, else custom_ with each switch that differs: its
4
+ // name when it is on, no_<name> when it is off. A build of an entry other
5
+ // than main.asm adds the entry, for example clean_loader. A source without
6
+ // config.asm and without a release keeps the name of its entry. The symbols
7
+ // of a build go into symbols/ next to the program, so the program folder
8
+ // holds only programs.
9
+
10
+ import { basename, dirname, extname, join } from "node:path";
11
+
12
+ /** The folder of the builds, relative to the project folder. Git does not keep it. */
13
+ export const BUILD_DIRECTORY = "build";
14
+
15
+ /** The file with the value of each switch. The user edits it, and generate keeps the values. */
16
+ export const CONFIG_FILE = "config.asm";
17
+
18
+ /** A value line of config.asm: NAME = 0 or NAME = 1. */
19
+ const CONFIG_VALUE = /^\s*([A-Z][A-Z0-9_]*)\s*=\s*([01])\s*(?:;.*)?$/;
20
+
21
+ /** The values of the switches in a config.asm text, by name. Lines that are not a value line are not read. */
22
+ export function configValues(text: string): Map<string, 0 | 1> {
23
+ const values = new Map<string, 0 | 1>();
24
+ for (const line of text.split(/\r?\n/)) {
25
+ const match = CONFIG_VALUE.exec(line);
26
+ if (match !== null) values.set(match[1]!, match[2] === "1" ? 1 : 0);
27
+ }
28
+ return values;
29
+ }
30
+
31
+ /** What a build is made of: a release, or the values of config.asm with the default of each switch (0 when the defaults do not have it). */
32
+ export type BuildKind = { release: string } | { values: ReadonlyMap<string, number>; defaults: ReadonlyMap<string, number> };
33
+
34
+ /** The name of a build of `entry`, without an extension. */
35
+ export function buildName(entry: string, kind: BuildKind | undefined): string {
36
+ const base = basename(entry, extname(entry));
37
+ if (kind === undefined) return base;
38
+ let type: string;
39
+ if ("release" in kind) type = `release_${kind.release}`;
40
+ else {
41
+ const changed = [...kind.values].filter(([name, value]) => value !== (kind.defaults.get(name) ?? 0)).map(([name, value]) => (value === 0 ? `no_${name}` : name).toLowerCase());
42
+ type = changed.length === 0 ? "clean" : `custom_${changed.join("_")}`;
43
+ }
44
+ return base === "main" ? type : `${type}_${base}`;
45
+ }
46
+
47
+ /** The symbols file of a program: symbols/<name>.json in the folder of the program. */
48
+ export function symbolsPath(program: string): string {
49
+ return join(dirname(program), "symbols", `${basename(program, extname(program))}.json`).split("\\").join("/");
50
+ }
@@ -1402,7 +1402,12 @@ export class ViceSession implements ViceSessionHandle {
1402
1402
  () => true,
1403
1403
  () => false,
1404
1404
  );
1405
- if (!kept) throw new WireFailure("machine-state-lost", "The emulator did not restore this snapshot file, and the machine state from before the restore is lost. Load the program again.");
1405
+ if (!kept) {
1406
+ throw new WireFailure(
1407
+ "machine-state-lost",
1408
+ "The emulator did not restore this snapshot file, and the machine state from before the restore is lost. A snapshot file restores only in the emulator version and with the machine settings that saved it. Make the snapshot again in this emulator version, and load the program again.",
1409
+ );
1410
+ }
1406
1411
  if (error instanceof WireFailure) throw error;
1407
1412
  throw new WireFailure(
1408
1413
  "invalid-input",
@@ -11,7 +11,7 @@ import { type AddressRange, COVERAGE, formatC64Address } from "../c64.ts";
11
11
 
12
12
  import { COVERAGE_KINDS, DEFAULT_SPACE, MEMORY_ROW, type CoverageKind, type Space } from "./schema.ts";
13
13
  import { coverageRuns } from "./read.ts";
14
- import { checkSpace, write, type Evidence, type WriteContext } from "./write.ts";
14
+ import { checkSpace, write, type Evidence, type OperandImage, type WriteContext } from "./write.ts";
15
15
 
16
16
  /** The 64 KiB of one space: offset n is address n. */
17
17
  const SIZE = 0x10000;
@@ -278,3 +278,46 @@ export function programCoverage(db: DatabaseSync | undefined, space: Space = DEF
278
278
  }
279
279
  return { map, selfModified };
280
280
  }
281
+
282
+ /**
283
+ * The program of each space in the knowledge that operand, patch and macro
284
+ * use writes in that space are checked against, with the platform names. A
285
+ * byte outside the segments of the program is not in it. Each program is
286
+ * read once, when a write in its space needs it.
287
+ */
288
+ export function operandImages(db: DatabaseSync, platform: ReadonlyMap<string, number>): (space: string) => OperandImage {
289
+ const images = new Map<string, OperandImage>();
290
+ return (space) => {
291
+ const known = images.get(space);
292
+ if (known !== undefined) return known;
293
+ const image = requireProgram(db, space);
294
+ const inside = (at: number) => image.segments.some((segment) => at >= segment.start && at <= segment.end);
295
+ const made: OperandImage = { byteAt: (at) => (inside(at) ? image.byteAt(at) : undefined), platform };
296
+ images.set(space, made);
297
+ return made;
298
+ };
299
+ }
300
+
301
+ /**
302
+ * The bytes of a release: the program for the base release, else the bytes
303
+ * that the knowledge keeps for the release. Undefined when the space has no
304
+ * release with this label.
305
+ */
306
+ export function releaseImage(db: DatabaseSync | undefined, label: string, space: Space = DEFAULT_SPACE): Pick<ProgramImage, "segments" | "byteAt"> | undefined {
307
+ if (db === undefined) return undefined;
308
+ const release = db.prepare("SELECT base FROM current_releases WHERE space = ? AND label = ?").get(space, label) as { base: number } | undefined;
309
+ if (release === undefined) return undefined;
310
+ if (release.base === 1) return programImage(db, space);
311
+ const rows = db.prepare("SELECT address, bytes FROM current_release_memory WHERE space = ? AND label = ? ORDER BY address").all(space, label) as Array<{ address: number; bytes: string }>;
312
+ const memory = new Uint8Array(SIZE);
313
+ const segments: AddressRange[] = [];
314
+ for (const row of rows) {
315
+ const bytes = Buffer.from(row.bytes, "hex");
316
+ memory.set(bytes, row.address);
317
+ const end = row.address + bytes.length - 1;
318
+ const last = segments.at(-1);
319
+ if (last !== undefined && last.end + 1 === row.address) last.end = end;
320
+ else segments.push({ start: row.address, end });
321
+ }
322
+ return { segments, byteAt: (address) => memory[address]! };
323
+ }
@@ -114,12 +114,10 @@ export interface SwitchRow {
114
114
  revision: string;
115
115
  }
116
116
 
117
- /** A release of the program: its project file with the SHA-256, and whether its bytes are the program of the knowledge. */
117
+ /** A release of the program, and whether its bytes are the program of the knowledge. The bytes of another release are in release_memory. */
118
118
  export interface ReleaseRow {
119
119
  space: Space;
120
120
  label: string;
121
- file: string;
122
- sha256: string;
123
121
  base: boolean;
124
122
  comment?: string;
125
123
  origin: Extract<Origin, "user" | "llm">;
@@ -201,7 +199,7 @@ export const MODULE_COLUMNS = "space, start_address, file, title, origin, valid_
201
199
  export const OPERAND_COLUMNS = "space, address, selector, symbol, offset, expression, origin, valid_from_revision";
202
200
  export const PATCH_COLUMNS = "space, start_address, end_address, switch_name, code, comment, origin, valid_from_revision";
203
201
  export const SWITCH_COLUMNS = "space, name, kind, default_value, releases, comment, origin, valid_from_revision";
204
- export const RELEASE_COLUMNS = "space, label, file, sha256, base, comment, origin, valid_from_revision";
202
+ export const RELEASE_COLUMNS = "space, label, base, comment, origin, valid_from_revision";
205
203
  export const MACRO_COLUMNS = "space, name, params, body, comment, origin, valid_from_revision";
206
204
  export const MACRO_USE_COLUMNS = "space, start_address, end_address, macro, args, origin, valid_from_revision";
207
205
  export const START_SCREEN_COLUMNS = "space, mode, screen, bitmap, charset, colours, colour, border, background, stage, call_address, colour_ram, comment, origin, valid_from_revision";
@@ -304,8 +302,6 @@ export function toRelease(row: Raw): ReleaseRow {
304
302
  const release: ReleaseRow = {
305
303
  space: row.space as Space,
306
304
  label: row.label as string,
307
- file: row.file as string,
308
- sha256: row.sha256 as string,
309
305
  base: row.base === 1,
310
306
  origin: row.origin as ReleaseRow["origin"],
311
307
  revision: row.valid_from_revision as string,
@@ -523,7 +519,7 @@ export function moduleAt(db: DatabaseSync | undefined, start: number, space: Spa
523
519
  }
524
520
 
525
521
  export function moduleWithFile(db: DatabaseSync | undefined, file: string, space: Space = DEFAULT_SPACE): ModuleRow | undefined {
526
- const row = db?.prepare(`SELECT ${MODULE_COLUMNS} FROM current_modules WHERE space = ? AND file = ?`).get(space, file) as Raw | undefined;
522
+ const row = db?.prepare(`SELECT ${MODULE_COLUMNS} FROM current_modules WHERE space = ? AND file = ? COLLATE NOCASE`).get(space, file) as Raw | undefined;
527
523
  return row === undefined ? undefined : toModule(row);
528
524
  }
529
525
 
@@ -56,8 +56,12 @@ export { OPERAND_SELECTS, type OperandSelect } from "./expression.ts";
56
56
  export const SUPPRESSION_ENTITIES = ["symbol", "region", "reference"] as const;
57
57
  export type SuppressionEntity = (typeof SUPPRESSION_ENTITIES)[number];
58
58
 
59
- /** A module file of the generated source: a plain name that ends in .asm, no directory. */
60
- export const MODULE_FILE = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,59}\.asm$/;
59
+ /**
60
+ * A module file of the generated source: a name that ends in .asm, in the
61
+ * source folder or in one folder of it, for example music/driver.asm. A folder
62
+ * name is lower case, so two modules cannot differ only in its letter case.
63
+ */
64
+ export const MODULE_FILE = /^(?:[a-z0-9_][a-z0-9_-]{0,29}\/)?[A-Za-z0-9_][A-Za-z0-9_-]{0,59}\.asm$/;
61
65
  /** A switch of the generated source: upper case, so it reads as a build option and not as a label. */
62
66
  export const SWITCH_NAME = /^[A-Z][A-Z0-9_]{1,31}$/;
63
67
  /** A release label: the switch-name form. The build of a release defines RELEASE_<label>. */
@@ -100,12 +104,17 @@ export const MEMORY_ROW = 64;
100
104
  /** Files that c64-source writes itself: no module can have these names. */
101
105
  export const GENERATED_FILES = ["main.asm", "loader.asm", "switches.asm", "config.asm", "constants.asm", "macros.asm", "start_screen.asm"] as const;
102
106
 
103
- /** The file of a range of leftovers in the generated source: leftover_xxxx.asm. */
104
- export const LEFTOVER_FILE = /^leftover_[0-9a-f]{4}\.asm$/;
107
+ /** The folder of the leftovers in the generated source: leftovers/leftover_xxxx.asm. */
108
+ export const LEFTOVER_FOLDER = "leftovers";
109
+ /** The folder of the parts of segments that no module holds: segments/segment_xxxx.asm. */
110
+ export const SEGMENT_FOLDER = "segments";
111
+ /** The folders that c64-source writes itself: no module file is in them. */
112
+ export const GENERATED_FOLDERS = [LEFTOVER_FOLDER, SEGMENT_FOLDER] as const;
105
113
 
106
114
  /** True for a generated file name in any letter case: the file systems of macOS and Windows ignore case. */
107
115
  export function isGeneratedFile(file: string): boolean {
108
- return (GENERATED_FILES as readonly string[]).includes(file.toLowerCase()) || LEFTOVER_FILE.test(file.toLowerCase());
116
+ const lower = file.toLowerCase();
117
+ return (GENERATED_FILES as readonly string[]).includes(lower) || GENERATED_FOLDERS.some((folder) => lower.startsWith(`${folder}/`));
109
118
  }
110
119
 
111
120
  /**
@@ -287,8 +296,6 @@ function createSchema(db: DatabaseSync): void {
287
296
  id TEXT PRIMARY KEY,
288
297
  space TEXT NOT NULL DEFAULT 'c64' CHECK (${SPACE_CHECK}),
289
298
  label TEXT NOT NULL CHECK (length(label) > 0),
290
- file TEXT NOT NULL CHECK (length(file) > 0),
291
- sha256 TEXT NOT NULL CHECK (length(sha256) = 64),
292
299
  base INTEGER NOT NULL CHECK (base IN (0, 1)),
293
300
  comment TEXT CHECK (comment IS NULL OR length(comment) > 0),
294
301
  origin TEXT NOT NULL CHECK (origin IN ('user', 'llm')),
@@ -356,6 +363,17 @@ function createSchema(db: DatabaseSync): void {
356
363
  valid_to_revision TEXT REFERENCES revisions (id)
357
364
  );
358
365
  CREATE INDEX memory_current ON memory (space, address) WHERE valid_to_revision IS NULL;
366
+ CREATE TABLE release_memory (
367
+ id TEXT PRIMARY KEY,
368
+ space TEXT NOT NULL DEFAULT 'c64' CHECK (${SPACE_CHECK}),
369
+ label TEXT NOT NULL CHECK (length(label) > 0),
370
+ address INTEGER NOT NULL CHECK (address BETWEEN 0 AND 65535),
371
+ bytes TEXT NOT NULL CHECK (length(bytes) BETWEEN 2 AND ${MEMORY_ROW * 2} AND length(bytes) % 2 = 0 AND address + length(bytes) / 2 <= 65536),
372
+ origin TEXT NOT NULL CHECK (origin IN ('user', 'llm')),
373
+ valid_from_revision TEXT NOT NULL REFERENCES revisions (id),
374
+ valid_to_revision TEXT REFERENCES revisions (id)
375
+ );
376
+ CREATE INDEX release_memory_current ON release_memory (space, label, address) WHERE valid_to_revision IS NULL;
359
377
  CREATE TABLE entries (
360
378
  id TEXT PRIMARY KEY,
361
379
  space TEXT NOT NULL DEFAULT 'c64' CHECK (${SPACE_CHECK}),
@@ -379,6 +397,7 @@ function createSchema(db: DatabaseSync): void {
379
397
  );
380
398
  CREATE INDEX coverage_current ON coverage (space, kind) WHERE valid_to_revision IS NULL;
381
399
  CREATE VIEW current_memory AS SELECT * FROM memory WHERE valid_to_revision IS NULL;
400
+ CREATE VIEW current_release_memory AS SELECT * FROM release_memory WHERE valid_to_revision IS NULL;
382
401
  CREATE VIEW current_entries AS SELECT * FROM entries WHERE valid_to_revision IS NULL;
383
402
  CREATE VIEW current_coverage AS SELECT * FROM coverage WHERE valid_to_revision IS NULL;
384
403
  CREATE VIEW current_symbols AS SELECT * FROM symbols WHERE valid_to_revision IS NULL;
@@ -399,7 +418,7 @@ function createSchema(db: DatabaseSync): void {
399
418
  }
400
419
 
401
420
  /** The version of the index this build makes. An index with another version is emptied and made again. */
402
- export const INDEX_VERSION = 13;
421
+ export const INDEX_VERSION = 14;
403
422
 
404
423
  function indexVersion(db: DatabaseSync): number | undefined {
405
424
  const hasMeta = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get();
@@ -166,12 +166,12 @@ export const TABLES: readonly TableSpec[] = [
166
166
  origin,
167
167
  ],
168
168
  },
169
- // The releases of the program: the file of each, and the one whose bytes are the program.
169
+ // The releases of the program, and the one whose bytes are the program. The bytes of the other releases are in release_memory.jsonl.
170
170
  {
171
171
  table: "releases",
172
172
  file: "releases.jsonl",
173
173
  sort: "label",
174
- fields: [space, field("label", "label", "text"), field("file", "file", "text"), field("sha256", "sha256", "text"), field("base", "base", "integer"), field("comment", "comment", "text", true), origin],
174
+ fields: [space, field("label", "label", "text"), field("base", "base", "integer"), field("comment", "comment", "text", true), origin],
175
175
  },
176
176
  {
177
177
  table: "macros",
@@ -209,6 +209,8 @@ export const TABLES: readonly TableSpec[] = [
209
209
  },
210
210
  // The program itself: its bytes, at most 64 to a row, so a changed byte changes one line.
211
211
  { table: "memory", file: "memory.jsonl", sort: "address", fields: [space, field("at", "address", "address"), field("bytes", "bytes", "hex"), origin] },
212
+ // The bytes of each release other than the base release, as the bytes of the program.
213
+ { table: "release_memory", file: "release_memory.jsonl", sort: "address", fields: [space, field("label", "label", "text"), field("at", "address", "address"), field("bytes", "bytes", "hex"), origin] },
212
214
  // Where the program starts, the machine state there, and the stages of its unpacker.
213
215
  {
214
216
  table: "entries",
@@ -78,7 +78,7 @@ import {
78
78
  type SwitchRow,
79
79
  type SymbolRow,
80
80
  } from "./read.ts";
81
- import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MODULE_FILE, DEFAULT_SPACE, GENERATED_FILES, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, LEFTOVERS_SWITCH, START_SCREEN_MODES, START_SCREEN_SWITCH, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, OPERAND_SELECTS, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type StartScreenMode, type SwitchKind, type SymbolKind } from "./schema.ts";
81
+ import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MEMORY_ROW, MODULE_FILE, DEFAULT_SPACE, GENERATED_FILES, GENERATED_FOLDERS, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, LEFTOVERS_SWITCH, START_SCREEN_MODES, START_SCREEN_SWITCH, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, OPERAND_SELECTS, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type StartScreenMode, type SwitchKind, type SymbolKind } from "./schema.ts";
82
82
  import { newRevisionId, rowId, sqlName } from "./text.ts";
83
83
 
84
84
  /** What a change rests on: a coverage run, a test or another project file with its SHA-256, or a note. */
@@ -281,8 +281,15 @@ export class Change {
281
281
 
282
282
  insertRelease(row: Omit<ReleaseRow, "revision">): void {
283
283
  this.#db
284
- .prepare("INSERT INTO releases (id, space, label, file, sha256, base, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
285
- .run(this.#rowId(), row.space, row.label, row.file, row.sha256, row.base ? 1 : 0, row.comment ?? null, row.origin, this.id());
284
+ .prepare("INSERT INTO releases (id, space, label, base, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
285
+ .run(this.#rowId(), row.space, row.label, row.base ? 1 : 0, row.comment ?? null, row.origin, this.id());
286
+ }
287
+
288
+ /** Bytes of a release other than the base release, as a memory row of the program holds them. */
289
+ insertReleaseMemory(row: { space: Space; label: string; address: number; bytes: string; origin: Origin }): void {
290
+ this.#db
291
+ .prepare("INSERT INTO release_memory (id, space, label, address, bytes, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
292
+ .run(this.#rowId(), row.space, row.label, row.address, row.bytes, row.origin, this.id());
286
293
  }
287
294
 
288
295
  insertStartScreen(row: Omit<StartScreenRow, "revision">): void {
@@ -751,9 +758,11 @@ type ModuleRequest = InSpace & { start: number; file: string; title?: string };
751
758
  function checkModule(request: ModuleRequest): void {
752
759
  checkSpace(request);
753
760
  checkAddress(request.start, "start");
754
- if (!MODULE_FILE.test(request.file)) throw new Refusal("invalid-input", "A module file is a name of letters, digits, underscores or hyphens (at most 60) that ends in .asm, without a directory.");
761
+ if (!MODULE_FILE.test(request.file)) {
762
+ throw new Refusal("invalid-input", "A module file is a name of letters, digits, underscores or hyphens (at most 60) that ends in .asm. It can have one folder of lower-case letters, digits, underscores or hyphens (at most 30), for example music/driver.asm.");
763
+ }
755
764
  if (isGeneratedFile(request.file)) {
756
- throw new Refusal("invalid-input", `A module cannot have the file ${request.file}, because the generated source writes ${GENERATED_FILES.join(", ")} itself, in any letter case. Give the module another file.`);
765
+ throw new Refusal("invalid-input", `A module cannot have the file ${request.file}, because the generated source writes ${GENERATED_FILES.join(", ")} and the folders ${GENERATED_FOLDERS.map((folder) => `${folder}/`).join(", ")} itself, in any letter case. Give the module another file.`);
757
766
  }
758
767
  if (request.title !== undefined && (request.title.trim().length === 0 || request.title.length > MAX_COMMENT)) throw new Refusal("invalid-input", `A module title has 1 to ${MAX_COMMENT} characters.`);
759
768
  }
@@ -1020,16 +1029,23 @@ function unswitchStep(db: DatabaseSync, change: Change, _origin: Origin, request
1020
1029
  return { current: null };
1021
1030
  }
1022
1031
 
1023
- /** A release: `file` is a project path and `sha256` the hash of its bytes, both from the caller. */
1024
- type ReleaseRequest = InSpace & { label: string; file: string; sha256: string; base?: boolean; comment?: string };
1032
+ /**
1033
+ * A release. `rows` are the bytes of a release other than the base release,
1034
+ * as memoryRows gives them: the address of each row and its bytes as hex. The
1035
+ * base release has no bytes of its own: its bytes are the program.
1036
+ */
1037
+ type ReleaseRequest = InSpace & { label: string; base?: boolean; comment?: string; rows?: ReadonlyMap<number, string> };
1025
1038
 
1026
1039
  function checkRelease(request: ReleaseRequest): void {
1027
1040
  checkSpace(request);
1028
1041
  if (typeof request.label !== "string" || !RELEASE_LABEL.test(request.label)) {
1029
1042
  throw new Refusal("invalid-input", "A release label is an upper-case letter, then 1 to 31 upper-case letters, digits or underscores, for example ORIGINAL or FIRESTAR.");
1030
1043
  }
1031
- if (typeof request.file !== "string" || request.file.trim().length === 0 || request.file.length > MAX_EVIDENCE_REF) throw new Refusal("invalid-input", `The file of a release has 1 to ${MAX_EVIDENCE_REF} characters.`);
1032
- if (!/^[0-9a-f]{64}$/.test(request.sha256)) throw new Refusal("invalid-input", "The sha256 of a release is 64 lowercase hex digits.");
1044
+ for (const [address, bytes] of request.rows ?? []) {
1045
+ if (!Number.isInteger(address) || address < 0 || address > 0xffff || !/^(?:[0-9a-f]{2})+$/.test(bytes) || bytes.length > MEMORY_ROW * 2 || address + bytes.length / 2 > 0x10000) {
1046
+ throw new Refusal("invalid-input", `The bytes of a release at ${formatC64Address(address & 0xffff)} are not a memory row.`);
1047
+ }
1048
+ }
1033
1049
  checkCommentText(request.comment, "A release comment");
1034
1050
  }
1035
1051
 
@@ -1038,7 +1054,12 @@ function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request:
1038
1054
  const existing = releaseLabeled(db, request.label, space);
1039
1055
  const base = request.base ?? existing?.base ?? false;
1040
1056
  const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
1041
- if (existing !== undefined && existing.file === request.file && existing.sha256 === request.sha256 && existing.base === base && existing.comment === comment && !confirms(existing.origin, origin)) return { current: existing };
1057
+ const held = db.prepare("SELECT id, address, bytes FROM current_release_memory WHERE space = ? AND label = ?").all(space, request.label) as Array<{ id: string; address: number; bytes: string }>;
1058
+ // A release without new bytes keeps its bytes. The base release has none: its bytes are the program.
1059
+ const wanted = base ? new Map<number, string>() : (request.rows ?? new Map(held.map((row) => [row.address, row.bytes])));
1060
+ if (!base && wanted.size === 0) throw new Refusal("invalid-input", `The release ${request.label} has no bytes. Give the file of the release.`);
1061
+ const sameBytes = held.length === wanted.size && held.every((row) => wanted.get(row.address) === row.bytes);
1062
+ if (existing !== undefined && existing.base === base && existing.comment === comment && sameBytes && !confirms(existing.origin, origin)) return { current: existing };
1042
1063
  const other = baseLabel(db, space);
1043
1064
  if (base && other !== undefined && other !== request.label) throw new Refusal("conflict", `The release ${other} is the base release. A space has one base release.`);
1044
1065
  // Every switch takes its base value from the base release: it cannot change under them.
@@ -1048,8 +1069,17 @@ function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request:
1048
1069
  }
1049
1070
  const symbol = symbolNamed(db, `${RELEASE_DEFINE}${request.label}`, space);
1050
1071
  if (symbol !== undefined) throw new Refusal("conflict", `The build of the release defines ${RELEASE_DEFINE}${request.label}, and that is the name of the symbol at ${formatC64Address(symbol.address)}. Give the release another label.`);
1051
- if (existing !== undefined) change.close("releases", "space = ? AND label = ?", space, request.label);
1052
- change.insertRelease({ space, label: request.label, file: request.file, sha256: request.sha256, base, ...(comment === undefined ? {} : { comment }), origin: origin as ReleaseRow["origin"] });
1072
+ if (existing === undefined || existing.base !== base || existing.comment !== comment || confirms(existing.origin, origin)) {
1073
+ if (existing !== undefined) change.close("releases", "space = ? AND label = ?", space, request.label);
1074
+ change.insertRelease({ space, label: request.label, base, ...(comment === undefined ? {} : { comment }), origin: origin as ReleaseRow["origin"] });
1075
+ }
1076
+ // Only the rows that changed: a changed byte changes one short line of the text.
1077
+ const kept = new Set<number>();
1078
+ for (const row of held) {
1079
+ if (wanted.get(row.address) === row.bytes) kept.add(row.address);
1080
+ else change.close("release_memory", "id = ?", row.id);
1081
+ }
1082
+ for (const [address, bytes] of [...wanted].sort(([a], [b]) => a - b)) if (!kept.has(address)) change.insertReleaseMemory({ space, label: request.label, address, bytes, origin });
1053
1083
  const current = releaseLabeled(db, request.label, space)!;
1054
1084
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
1055
1085
  }
@@ -1064,6 +1094,7 @@ function unreleaseStep(db: DatabaseSync, change: Change, _origin: Origin, reques
1064
1094
  throw new Refusal("conflict", `The release ${request.label} ${why} the switches ${switches.map((row) => row.name).join(", ")}. Change or remove them first (switch, unswitch).`);
1065
1095
  }
1066
1096
  change.close("releases", "space = ? AND label = ?", space, request.label);
1097
+ change.close("release_memory", "space = ? AND label = ?", space, request.label);
1067
1098
  return { current: null };
1068
1099
  }
1069
1100
 
@@ -1415,7 +1446,7 @@ export function removeSwitch(db: DatabaseSync, context: WriteContext, request: I
1415
1446
  return result(write(db, context, "remove-switch", (change) => unswitchStep(db, change, context.origin, request)));
1416
1447
  }
1417
1448
 
1418
- /** Writes a release of the program: its project file and the SHA-256 of it. The caller checks the file. */
1449
+ /** Writes a release of the program and its bytes. The caller reads the bytes from the file of the release, and checks the file of the base release. */
1419
1450
  export function setRelease(db: DatabaseSync, context: WriteContext, request: ReleaseRequest): WriteResult<ReleaseRow, ReleaseRow> {
1420
1451
  checkRelease(request);
1421
1452
  return result(write(db, context, "set-release", (change) => releaseStep(db, change, context.origin, request)));
@@ -1606,6 +1637,7 @@ export function applyBatch(db: DatabaseSync, context: WriteContext, operations:
1606
1637
  /** The tables of the program and the columns that make a row. */
1607
1638
  const PROGRAM_TABLES = [
1608
1639
  ["memory", "space, address, bytes, origin"],
1640
+ ["release_memory", "space, label, address, bytes, origin"],
1609
1641
  ["entries", "space, address, state, stages, origin"],
1610
1642
  ["coverage", "space, kind, start_address, end_address, origin"],
1611
1643
  ] as const;
@@ -1635,7 +1667,7 @@ const KEYS = {
1635
1667
  releases: {
1636
1668
  columns: RELEASE_COLUMNS,
1637
1669
  map: toRelease,
1638
- key: (row: ReleaseRow) => `${row.space}|${row.label}|${row.file}|${row.sha256}|${row.base}|${row.comment ?? ""}|${row.origin}`,
1670
+ key: (row: ReleaseRow) => `${row.space}|${row.label}|${row.base}|${row.comment ?? ""}|${row.origin}`,
1639
1671
  },
1640
1672
  start_screens: {
1641
1673
  columns: START_SCREEN_COLUMNS,
@@ -1736,6 +1768,7 @@ export function revert(db: DatabaseSync, context: WriteContext, request: { revis
1736
1768
  if (nowKeys.has(key(row))) continue;
1737
1769
  const values = row as never;
1738
1770
  if (table === "memory") change.insertMemory(values);
1771
+ else if (table === "release_memory") change.insertReleaseMemory(values);
1739
1772
  else if (table === "entries") change.insertEntry(values);
1740
1773
  else change.insertCoverage({ ...(values as { space: Space; kind: string; origin: Origin }), start: row.start_address as number, end: row.end_address as number });
1741
1774
  }
@@ -19,7 +19,7 @@ export function showSymbol(symbol: AssembledSymbol) {
19
19
  : { name: symbol.name, kind: "constant", value: `$${symbol.value.toString(16).padStart(4, "0")}`, used: symbol.used };
20
20
  }
21
21
 
22
- /** The text of a symbols file (--out-symbols): the symbols of a build, which c64-testing reads for the names of a program. */
22
+ /** The text of a symbols file (symbols/<build>.json next to the program): the symbols of a build, which c64-testing reads for the names of a program. */
23
23
  export const symbolsFileText = (symbols: readonly AssembledSymbol[]) => `${JSON.stringify({ symbols: symbols.map(showSymbol) }, null, 1)}\n`;
24
24
 
25
25
  const PROGRAM = "program.prg";
package/src/project.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  import { Refusal } from "./errors.ts";
8
8
  import { accessSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
9
9
  import { homedir } from "node:os";
10
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
10
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
11
11
 
12
12
  /** The folder that marks a project and holds its knowledge. */
13
13
  export const PROJECT_DIRECTORY = ".c64-re-tools";
@@ -15,6 +15,18 @@ export const PROJECT_DIRECTORY = ".c64-re-tools";
15
15
  /** The folder for machine-local scratch: saved results, batches and step files. */
16
16
  export const LOCAL_DIRECTORY = "local";
17
17
 
18
+ /** The folder in LOCAL_DIRECTORY for the reports of a generated source: its source map and the code that no run executed. */
19
+ export const GENERATED_DIRECTORY = "generated";
20
+
21
+ /**
22
+ * The folder of the reports of the source that was generated into `out`, relative
23
+ * to the project folder: .c64-re-tools/local/generated/<out>. The source folder
24
+ * then holds only source files.
25
+ */
26
+ export function generatedDirectory(out: string): string {
27
+ return posix.join(PROJECT_DIRECTORY, LOCAL_DIRECTORY, GENERATED_DIRECTORY, posix.normalize(out.split("\\").join("/")).replace(/\/+$/, ""));
28
+ }
29
+
18
30
  /** The .gitignore of LOCAL_DIRECTORY: git ignores everything in it, the .gitignore too. */
19
31
  const LOCAL_GITIGNORE = "# Machine-local scratch of c64-re-tools (saved results, batches, step files). Never committed.\n*\n";
20
32