@henols/c64-re-tools 2.4.0-rc.2 → 2.4.0-rc.4

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 (50) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +8 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +6 -16
  4. package/skills/c64-basic/SKILL.md +2 -0
  5. package/skills/c64-disk/SKILL.md +21 -4
  6. package/skills/c64-disk/scripts/disk.ts +43 -3
  7. package/skills/c64-docs/SKILL.md +2 -0
  8. package/skills/c64-docs/scripts/docs.ts +6 -6
  9. package/skills/c64-knowledge/SKILL.md +2 -0
  10. package/skills/c64-memory-map/SKILL.md +2 -0
  11. package/skills/c64-packer/SKILL.md +2 -0
  12. package/skills/c64-provenance/SKILL.md +11 -4
  13. package/skills/c64-provenance/scripts/lib/library.ts +99 -19
  14. package/skills/c64-provenance/scripts/provenance.ts +4 -3
  15. package/skills/c64-reverse-engineering/SKILL.md +3 -3
  16. package/skills/c64-source/SKILL.md +10 -2
  17. package/skills/c64-source/scripts/lib/export.ts +3 -3
  18. package/skills/c64-source/scripts/lib/source.ts +80 -24
  19. package/skills/c64-source/scripts/source.ts +49 -8
  20. package/skills/c64-static-analysis/SKILL.md +3 -1
  21. package/skills/c64-testing/SKILL.md +13 -1
  22. package/skills/c64-testing/references/recording-format.md +5 -1
  23. package/skills/c64-testing/references/scenario-format.md +5 -3
  24. package/skills/c64-testing/scripts/lib/recording.ts +32 -6
  25. package/skills/c64-testing/scripts/lib/runs.ts +13 -7
  26. package/skills/c64-testing/scripts/lib/scenario.ts +13 -6
  27. package/skills/c64-testing/scripts/testing.ts +6 -3
  28. package/skills/c64-unpacker/SKILL.md +2 -0
  29. package/src/host/server.ts +31 -6
  30. package/src/host/tools/c1541.ts +32 -8
  31. package/src/host/vice/binary-monitor.ts +19 -7
  32. package/src/host/vice/session.ts +6 -2
  33. package/src/host-client/connect.ts +12 -2
  34. package/src/host-client/tools.ts +9 -4
  35. package/src/host-client/transfer.ts +58 -4
  36. package/src/host-client/vice-session.ts +10 -3
  37. package/src/knowledge/import.ts +28 -5
  38. package/src/knowledge/write.ts +4 -0
  39. package/src/mcp/main.ts +4 -66
  40. package/src/mcp/session-source.ts +76 -0
  41. package/src/native/acme.ts +45 -12
  42. package/src/native/c64run.ts +1 -1
  43. package/src/native/types.ts +5 -2
  44. package/src/project.ts +58 -1
  45. package/src/protocol/framing.ts +15 -2
  46. package/src/protocol/messages.ts +77 -25
  47. package/src/protocol/tools.ts +33 -4
  48. package/src/protocol/vice.ts +40 -20
  49. package/src/script.ts +11 -6
  50. package/tools/c64run.c +48 -12
@@ -5,7 +5,7 @@
5
5
  // suggests its names there as an apply batch. Nothing here writes knowledge.
6
6
 
7
7
  import { createHash } from "node:crypto";
8
- import { mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
8
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
9
9
  import { dirname, join, relative, resolve, sep } from "node:path";
10
10
 
11
11
  import { Refusal } from "#src/errors.ts";
@@ -14,7 +14,7 @@ import { formatC64Address, instructionLength } from "#src/c64.ts";
14
14
  import { evaluate, identifiers, operandText } from "#src/knowledge/expression.ts";
15
15
  import type { CommentRow, OperandRow, ReferenceRow, RegionRow, SymbolRow } from "#src/knowledge/read.ts";
16
16
  import { COMMENT_PLACEMENTS, type CommentPlacement, isSemantic, OPERAND_SELECTS, type OperandSelect, REFERENCE_KINDS, type ReferenceKind, REGION_TYPES, type RegionType, SYMBOL_KINDS, type SymbolKind } from "#src/knowledge/schema.ts";
17
- import { checkOutputPath, isInside, knowledgePart, PROJECT_DIRECTORY } from "#src/project.ts";
17
+ import { checkOutputPath, isInside, knowledgePart, LOCAL_DIRECTORY, PROJECT_DIRECTORY } from "#src/project.ts";
18
18
 
19
19
  /** A routine shorter than this is not saved and not searched: its bytes occur by chance. */
20
20
  export const MIN_ROUTINE = 16;
@@ -294,8 +294,10 @@ export function parseRoutine(text: string, file: string): Routine {
294
294
  /**
295
295
  * Refuses a library folder to write that is inside the project `root`, also
296
296
  * through a symbolic link, when the output check of every script refuses it
297
- * (checkOutputPath): for example a folder in the knowledge. A folder outside
298
- * the project gets no check.
297
+ * (checkOutputPath): for example a folder in the knowledge. A new library
298
+ * folder in the project is refused too, except in .c64-re-tools/local/: the
299
+ * other projects cannot match against it. A folder outside the project gets no
300
+ * check.
299
301
  */
300
302
  function checkLibraryOutput(path: string, root: string): void {
301
303
  let existing = path;
@@ -310,6 +312,10 @@ function checkLibraryOutput(path: string, root: string): void {
310
312
  if (part !== undefined) {
311
313
  throw new Refusal("invalid-input", `--library: ${shown} is in ${part}, the knowledge of the project. Only the commands that change the project knowledge write it: a write there destroys the knowledge. Give a library folder beside the projects, for example ../library.`);
312
314
  }
315
+ // For example --library library from the folder above the projects: it names a folder in the project.
316
+ if (existing !== path && existsSync(join(base, PROJECT_DIRECTORY)) && !isInside(join(base, PROJECT_DIRECTORY, LOCAL_DIRECTORY), target)) {
317
+ throw new Refusal("invalid-input", `--library: there is no library folder ${shown} in the project folder, and a new library must not be in the project folder, because the other projects cannot match against it there. --library is relative to the project folder. Give a library folder beside the projects, for example ../library.`);
318
+ }
313
319
  checkOutputPath(shown, "folder", { root: base, what: "--library" });
314
320
  return;
315
321
  }
@@ -317,10 +323,10 @@ function checkLibraryOutput(path: string, root: string): void {
317
323
  }
318
324
 
319
325
  /**
320
- * The library folder that --library names, relative to the working directory
321
- * like --project (D71). A library is a plain folder, never a project. With
322
- * `create`, a missing folder is made; a folder inside the project must pass
323
- * the output check of every script, which refuses the knowledge.
326
+ * The library folder that --library names, relative to `cwd`: the scripts
327
+ * give the project folder, as for every path. A library is a plain folder,
328
+ * never a project. With `create`, a missing folder is made; a folder inside
329
+ * the project must pass checkLibraryOutput.
324
330
  */
325
331
  export function libraryFolder(folder: string, options: { create: boolean; cwd?: string }): string {
326
332
  if (folder.length === 0) throw new Refusal("invalid-input", "The library folder must not be empty.", { hint: "Give a library folder beside the projects, for example ../library." });
@@ -405,7 +411,8 @@ function relocated(relocation: Relocation, start: number, part: 0 | 1): number |
405
411
  /**
406
412
  * The places where the routine occurs in the image: its fixed bytes equal,
407
413
  * each relocation pointing into the routine at one shift, and the variable
408
- * bytes free. Matches do not overlap.
414
+ * bytes free. Matches can overlap: a short routine with many variable bytes
415
+ * can fit at several places close together, and each place is a candidate.
409
416
  */
410
417
  export function findRoutine(routine: Routine, image: Searched, origin = routine.from.start): Match[] {
411
418
  const length = routine.bytes.length;
@@ -442,7 +449,6 @@ export function findRoutine(routine: Routine, image: Searched, origin = routine.
442
449
  if (library !== program) differing.push({ address: start + offset, library, program, size: size as 1 | 2 });
443
450
  }
444
451
  matches.push({ routine: routine.name, start, shift: start - origin, differing });
445
- start += length - 1;
446
452
  }
447
453
  }
448
454
  return matches;
@@ -472,26 +478,95 @@ export interface Skipped {
472
478
  reason: string;
473
479
  }
474
480
 
481
+ /** A comment of the batch that names an address outside its routine: that address can be different in the program. */
482
+ export interface Check {
483
+ routine: string;
484
+ address: string;
485
+ comment: string;
486
+ outside: string[];
487
+ }
488
+
475
489
  export interface Suggestions {
476
490
  batch: BatchWrite[];
477
491
  /** Writes that the program already has. */
478
492
  known: number;
479
493
  leftOut: Skipped[];
494
+ check: Check[];
480
495
  }
481
496
 
482
497
  const semantic = (row: { origin: string }) => isSemantic(row.origin);
483
498
 
499
+ /**
500
+ * The copy of each routine that gets its names, and the copies left out. A
501
+ * routine with one match is named there. For a routine with several matches,
502
+ * the routines of the same library program that matched once give the shift:
503
+ * the nearest one below it and the nearest one above it, by their start in that
504
+ * program. A copy fits when its shift is the shift of one of these two
505
+ * neighbours: code that moved as a block keeps the shift of its neighbours, and
506
+ * at the border of a block only one side has it. The routine is named only when
507
+ * exactly one copy fits. With no neighbour, with no fitting copy, or with a
508
+ * fitting copy for each of two different neighbour shifts, no copy is named.
509
+ */
510
+ function chooseCopies(found: ReadonlyArray<{ routine: Routine; matches: Match[] }>): Array<{ chosen?: Match; leftOut: Skipped[] }> {
511
+ const show = formatC64Address;
512
+ const unique = found.filter(({ matches }) => matches.length === 1);
513
+ return found.map(({ routine, matches }) => {
514
+ if (matches.length <= 1) return { ...(matches[0] === undefined ? {} : { chosen: matches[0] }), leftOut: [] };
515
+ const beside = unique.filter((item) => item.routine !== routine && item.routine.from.program === routine.from.program);
516
+ const below = beside.filter((item) => item.routine.from.start < routine.from.start).sort((a, b) => b.routine.from.start - a.routine.from.start)[0];
517
+ const above = beside.filter((item) => item.routine.from.start > routine.from.start).sort((a, b) => a.routine.from.start - b.routine.from.start)[0];
518
+ const neighbours = [below, above].filter((item) => item !== undefined);
519
+ const copies = [...matches].sort((a, b) => a.start - b.start);
520
+ const fitting = copies.filter((match) => neighbours.some((item) => item.matches[0]!.shift === match.shift));
521
+ if (fitting.length !== 1) {
522
+ return { leftOut: copies.map((match) => ({ routine: routine.name, address: show(match.start), reason: `ambiguous: ${copies.length} copies of the routine, and the shift of no library neighbour chooses one copy` })) };
523
+ }
524
+ const chosen = fitting[0]!;
525
+ const by = neighbours.filter((item) => item.matches[0]!.shift === chosen.shift).map((item) => item.routine.name);
526
+ const reason = `another copy of the routine; the copy at ${show(chosen.start)} has the shift ${chosen.shift} of its library neighbour${by.length === 1 ? "" : "s"} ${by.join(" and ")}`;
527
+ return { chosen, leftOut: copies.filter((match) => match !== chosen).map((match) => ({ routine: routine.name, address: show(match.start), reason })) };
528
+ });
529
+ }
530
+
531
+ /** A $xxxx address in a comment: four hex digits, not more. */
532
+ const COMMENT_ADDRESS = /\$([0-9a-fA-F]{4})(?![0-9a-fA-F])/g;
533
+
534
+ /**
535
+ * The comment text in the program: each $xxxx address inside the library range
536
+ * of the routine moves by the shift, with upper-case digits when the text has
537
+ * them. The addresses outside that range stay, and are returned as `outside`.
538
+ */
539
+ function movedComment(text: string, routine: Routine, shift: number): { text: string; outside: string[] } {
540
+ const first = routine.from.start;
541
+ const last = first + routine.bytes.length - 1;
542
+ const outside = new Set<string>();
543
+ const moved = text.replace(COMMENT_ADDRESS, (whole, digits: string) => {
544
+ const value = Number.parseInt(digits, 16);
545
+ if (value < first || value > last) {
546
+ outside.add(formatC64Address(value));
547
+ return whole;
548
+ }
549
+ const shown = formatC64Address(value + shift);
550
+ return /[A-F]/.test(digits) ? shown.toUpperCase() : shown;
551
+ });
552
+ return { text: moved, outside: [...outside] };
553
+ }
554
+
484
555
  /**
485
556
  * The names, regions, comments, references and operand expressions of each
486
557
  * matched routine at its program addresses, as an apply batch. A write that
487
558
  * the program already has is counted as known. A write that would replace a
488
559
  * user or LLM row, take a name that the program uses elsewhere, undo a
489
560
  * removal, or give an operand that is not in the image, is left out with the
490
- * reason. Only the first match of a routine gets its names.
561
+ * reason. A routine with several matches gets its names at the copy that
562
+ * chooseCopies gives, or nowhere. Each $xxxx address of a comment inside the
563
+ * routine moves with it; a written comment with an address outside the routine
564
+ * is in `check`.
491
565
  */
492
566
  export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[] }>, program: ProgramKnowledge, image: Searched, platform: ReadonlyMap<string, number>): Suggestions {
493
567
  const batch: BatchWrite[] = [];
494
568
  const leftOut: Skipped[] = [];
569
+ const check: Check[] = [];
495
570
  let known = 0;
496
571
  const show = formatC64Address;
497
572
  /** The names that are at their place after the batch: written here or known. */
@@ -499,11 +574,12 @@ export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[
499
574
  const symbolsHere = new Map<number, string>();
500
575
  const regionsHere: Array<{ start: number; end: number }> = [];
501
576
 
502
- for (const { routine, matches } of found) {
503
- const [first, ...others] = [...matches].sort((a, b) => a.start - b.start);
504
- for (const other of others) leftOut.push({ routine: routine.name, address: show(other.start), reason: `a second copy of the routine; the first is at ${show(first!.start)}` });
505
- if (first === undefined) continue;
506
- const at = (offset: number) => first.start + offset;
577
+ const copies = chooseCopies(found);
578
+ for (const [index, { routine }] of found.entries()) {
579
+ const { chosen, leftOut: others } = copies[index]!;
580
+ leftOut.push(...others);
581
+ if (chosen === undefined) continue;
582
+ const at = (offset: number) => chosen.start + offset;
507
583
  const skip = (address: number, op: string, reason: string) => leftOut.push({ routine: routine.name, address: show(address), op, reason });
508
584
 
509
585
  for (const symbol of routine.symbols) {
@@ -544,9 +620,13 @@ export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[
544
620
  for (const comment of routine.comments) {
545
621
  const address = at(comment.at);
546
622
  const existing = program.commentsAt(address).find((item) => item.placement === comment.placement);
547
- if (existing?.text === comment.text) known++;
623
+ const { text, outside } = movedComment(comment.text, routine, chosen.shift);
624
+ if (existing?.text === text) known++;
548
625
  else if (existing !== undefined) skip(address, "comment", `the program has a ${comment.placement} comment there (${existing.origin})`);
549
- else batch.push({ op: "comment", address: show(address), placement: comment.placement, text: comment.text });
626
+ else {
627
+ batch.push({ op: "comment", address: show(address), placement: comment.placement, text });
628
+ if (outside.length > 0) check.push({ routine: routine.name, address: show(address), comment: text, outside });
629
+ }
550
630
  }
551
631
 
552
632
  for (const reference of routine.references) {
@@ -590,7 +670,7 @@ export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[
590
670
  });
591
671
  }
592
672
  }
593
- return { batch, known, leftOut };
673
+ return { batch, known, leftOut, check };
594
674
  }
595
675
 
596
676
  /** Why the expression is not the operand of the instruction at `address` in the image, or undefined when it is. */
@@ -522,13 +522,14 @@ function matchCommand(call: Call): unknown {
522
522
  } finally {
523
523
  db?.close();
524
524
  }
525
- const { batch, known, leftOut } = suggestions;
525
+ const { batch, known, leftOut, check } = suggestions;
526
526
  const written = writeReported(out, batch.length === 0 ? "[]\n" : `[\n${batch.map((write) => ` ${JSON.stringify(write)}`).join(",\n")}\n]\n`, { what: "--out" });
527
- const body = { ...result, batch: { ...written, writes: batch.length, known, leftOut: list(leftOut) } };
527
+ const body = { ...result, batch: { ...written, writes: batch.length, known, leftOut: list(leftOut), check: list(check) } };
528
528
  // The batch is applied by the knowledge, not by this script: the hint gives the task, not a command.
529
529
  if (matches.length === 0) return reply(body, { hint: noMatch });
530
530
  if (batch.length === 0) return reply(body, { hint: withNote(body, "The batch has no writes. The project knowledge has the names of the found routines already, or batch.leftOut tells why the script left out a write.") });
531
- return reply(body, { hint: withNote(body, `Apply the changes in ${out} to the project knowledge.`) });
531
+ const review = check.length === 0 ? "" : " First examine batch.check: each comment there gives an address outside its routine, which can be different in this program. Correct the comment text in the batch file when it is different.";
532
+ return reply(body, { hint: withNote(body, `Apply the changes in ${out} to the project knowledge.${review}`) });
532
533
  }
533
534
 
534
535
  const LIBRARY = { kind: "text", value: "<folder>", required: true, help: "the library: a plain folder of routine files beside the projects, relative to the project folder, for example ../library" } as const;
@@ -160,11 +160,11 @@ Some releases of a program have a different layout. Their code is at different a
160
160
 
161
161
  1. Make the group folder in the git repository. Do not put `.c64-re-tools/` in it.
162
162
  2. Ask the user before you move a project folder. Then move the current project into `<game>/v1/`. The project knowledge keeps its paths relative to the project folder. Thus the knowledge stays valid after the move.
163
- 3. Make a project folder for the new version, for example `<game>/v2/`. Start at stage 2 with the file of that release.
163
+ 3. Make a project folder for the new version, for example `<game>/v2/`. Start at stage 2 with the file of that release. From the group folder, give `--project v2`. In the empty folder `v2/`, give `--project .`. The first write makes the project.
164
164
  4. Keep the releases with the same layout in one version. Record them as releases with switches. For example, `v2` holds a base release and a second release from a different crack.
165
- 5. Save the routines of `v1` to the routine library in `<game>/library/`. In stage 7 of `v2`, match the program against that library. Then `v2` gets the names of `v1` for the same routines.
165
+ 5. Save the routines of `v1` to the routine library in `<game>/library/`. Give `--library ../library`, because `--library` is relative to the project folder. In stage 7 of `v2`, match the program against that library. Then `v2` gets the names of `v1` for the same routines.
166
166
  6. Use the same folders in each version, for example `src` and `docs/reference`.
167
- 7. From the group folder, give `--project v1` or `--project v2` to each script.
167
+ 7. From the group folder, give `--project v1` or `--project v2` to each script. A script can read a file of another version, for example `../v1/original/<file>`. Use this to compare the releases of two versions. Record each release only in the project of its version.
168
168
  8. Write the facts that the versions share one time, in the pages of the group folder. The pages of each version tell only how that version works.
169
169
 
170
170
  ## Knowledge
@@ -50,6 +50,8 @@ To get the command list, run the script with no arguments.
50
50
 
51
51
  - Give each path relative to the project folder. The project folder is the nearest folder at or above the working directory that holds `.c64-re-tools/`.
52
52
  - If the working directory is not in a project, give `--project <folder>` to each command. If the working directory has projects below it, the script refuses and lists them.
53
+ - In a group folder, each version of a program is a project. The script refuses the group folder and each folder in it that is not a project. Give `--project` with a project of the group, for example `--project v1`.
54
+ - A path that a command only reads can go into another project of the group, for example `../v1/original/game.prg`. The command writes only in its own project.
53
55
  - An address is `$` and 1 to 4 hex digits, for example `'$c000'` or `'$fb'`, or a name. A name is a symbol, else an analyzer name that only one analyzer gives. Put an address in single quotes in a shell.
54
56
  - A range is `<start>-<end>`, for example `'$c000-$cfff'`. In a JSON file, a range is `start` and `end`.
55
57
  - Bytes in a JSON file are hex in a field `data`, for example `"data": "a900"`.
@@ -69,7 +71,7 @@ Each flag applies only to the commands in the table. On another command, the scr
69
71
 
70
72
  | Flag | Command | Effect |
71
73
  |---|---|---|
72
- | `--out <dir>` | `generate` | The folder for the source files. It is necessary. The script writes over the files of an earlier run. It removes a generated `.asm` file that this run does not write. A run without `--loader` keeps `loader.asm` and `loader.prg` of an earlier run. |
74
+ | `--out <dir>` | `generate` | The folder for the source files. It is necessary. The script writes over the files of an earlier run. It removes a generated `.asm` file that this run does not write. A run without `--loader` keeps `loader.asm` and `loader.prg` of an earlier run. `staleLoader` tells when they are of another knowledge revision. |
73
75
  | `--entry <address>` | `generate` | An address where code starts. Give the flag again for more addresses. There is no default. |
74
76
  | `--space <space>` | `generate` | The knowledge space: `c64`, `drive8`, or `bank0` to `bank255`. The default is `c64`. The coverage, `--loader` and the platform names apply only to `c64`. |
75
77
  | `--loader` | `generate` | Also write `loader.asm` and `loader.prg`. It needs a capture in the knowledge. The default is no loader. |
@@ -114,6 +116,7 @@ To make the source better, change the project knowledge. Then generate again.
114
116
  - `patchesNotWritten`: each patch that the source does not have, with its range, `switch` and `reason`.
115
117
  - `switches`, `default`, `releases`: the checks of the switches. See "Switches and releases".
116
118
  - `loader`: the check of the loader. See "The loader".
119
+ - `staleLoader`: a run without `--loader` kept `loader.asm` and `loader.prg` of another knowledge revision. `files` gives the files. `revision` gives the revision of `loader.asm`. Without `revision`, `loader.asm` does not give one. `noEntryState: true` tells that the knowledge has no entry state for a new loader.
117
120
 
118
121
  `result` is `FAIL` for each of these:
119
122
 
@@ -141,12 +144,13 @@ Do these actions for the findings:
141
144
  | `invalid-input` that names a symbol or a module | Change that symbol or module in the project knowledge. |
142
145
  | `conflict` | The knowledge has conflicts from a git merge. Merge the open changes of the project knowledge. Then run the command again. |
143
146
  | A list with `rest` | Give a larger `--max-listed`. For `notExecuted`, read the file in `rest`. |
147
+ | `staleLoader` | The loader can copy bytes that are not the bytes of the source. Run `nextAction`, which generates with `--loader`. With `noEntryState: true`, remove the files when the build does not use them. |
144
148
 
145
149
  #### The source files
146
150
 
147
151
  - `main.asm` sets the address of each segment. It includes the files in address order.
148
152
  - Each module in the knowledge is one file. A module starts at its address. It stops at the next module or at the end of its segment. Without modules, each segment is one file, `segment_xxxx.asm`.
149
- - `constants.asm` holds the names of addresses outside the program, for example `EXTCOL = $d020`. The names are in groups by memory area, in address order. Drive code and banks have one group only.
153
+ - `constants.asm` holds the names of addresses outside the program, for example `EXTCOL = $d020`. It also holds the register names in the program, for example `RASTER = $d012`. The names are in groups by memory area, in address order. Drive code and banks have one group only.
150
154
  - The side comment of a constant is the knowledge comment of the address. Without a comment, it is the platform meaning. When the knowledge name is not the platform name, the platform name comes first. For an I/O mirror without a meaning, the comment gives the register that the mirror repeats.
151
155
  - After the side comment, `Used:` counts how the source uses the name. The kinds are `read`, `written`, `modified`, `called`, `jumped to`, `jumped through`, `branched to`, `pointer`, `address`, `table` and `macro argument`. `address` is an immediate operand expression. `table` is an entry in a table of addresses.
152
156
  - `config.asm` holds the value of each switch, for example `PROTECTION = 0`. The switches are in groups by kind. The side comment gives the releases that have the switch on, the ranges of its patches and the comment of the switch.
@@ -159,6 +163,8 @@ Do these actions for the findings:
159
163
  - A label or a constant gets the name of the address in the knowledge.
160
164
  - Without a knowledge name, it gets the platform name, for example `EXTCOL` or `CHROUT`. A platform name wins over an analyzer name (`dxa`, `ghidra` or `heuristic`), for example `EXTCOL` over `ld020`. A `user` or `llm` name wins over a platform name.
161
165
  - An address in the program without a name gets `l_xxxx`.
166
+ - A read or a write in the I/O area `$d000-$dfff` uses the register, also when the program has RAM there. For example, `lda $dd0e` is `lda CI2CRA` and `sta $d012` is `sta RASTER`. `constants.asm` has these names. An address without a platform name stays a number, for example `sta $d800,x`. The data label of the RAM stays at its data. A `user` or `llm` name of the address wins over the register.
167
+ - A platform name in an operand expression of the knowledge stays in the source. When the program has the address, `constants.asm` has the name, and the RAM there keeps its label.
162
168
  - The source uses the names of a ROM only when the program uses that ROM. With coverage, the program uses a ROM when a run executed code of it. A read of ROM bytes as data does not count. Without coverage, `$01` of the entry state tells which ROMs are in.
163
169
  - When the program uses no ROM, the zero page and pages 2 and 3 get no system names. An operand expression or a macro use with such a name gets that reason.
164
170
 
@@ -242,6 +248,7 @@ The entry state is the state of the base release. Thus the script builds and che
242
248
  - `verified: true`: the check ran `loader.prg` to its jump to the entry. There, the memory, $00/$01, the registers and the VIC-II are equal to the entry state. The raster line and the CIA values are also equal. An interrupt can run right at the entry, as in the original program.
243
249
  - `limits`: each CIA value that the loader cannot set as it was at the entry. An old capture has no CIA values. Then capture the program again at its entry point.
244
250
  - `packed`: `packedBytes` and `unpackedBytes` of the packed form.
251
+ - When the check of `loader.prg` cannot run, the script removes `loader.prg`. `loader.asm` stays. `reason` tells why the check did not run.
245
252
 
246
253
  Do these actions when `verified` is `false`:
247
254
 
@@ -250,6 +257,7 @@ Do these actions when `verified` is `false`:
250
257
  | `reason` about the copy order, the free pages or the count of copies | The reason gives the ranges. Capture the program again with fewer segments, or write the loader by hand. |
251
258
  | `reason` about the packed form | If a tool is missing, stop the task and give the message to the user. If the free ranges are too small, write the loader by hand. If the check of the unpack fails, give the reason to the user. |
252
259
  | `reason` that the source does not assemble | Correct the source first. The loader includes the source. |
260
+ | `reason` that the check of `loader.prg` did not run | Stop the task and give the reason to the user. When the user tells you that the emulator is available, run the same command again. |
253
261
  | `differences` | The loader ran. The list gives the bytes and the registers that are not equal. |
254
262
  | `stop` | The loader did not get to its copier or its jump. `stop` gives the address and `port`, the value of $01. `history` gives the last 16 instructions. `cause` gives the first byte of the copier or of a copy that is not correct. |
255
263
 
@@ -377,16 +377,16 @@ export function rewriteTest(text: string, name: string, symbols: ReadonlyMap<str
377
377
  if (inside(address, free)) return { reason: `it names ${location}, which is in a free range` };
378
378
  } else if (!symbols.has(location)) return { reason: `it names ${location}, which the exported program does not have` };
379
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 } : {}) });
380
+ const side = (program: string) => ({ program: `${program}.prg`, symbols: `${program}.json` });
381
381
  if (scenario) {
382
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;
383
+ const { original: _original, rebuild: _rebuild, steps, ...rest } = test;
384
384
  const both = (steps as unknown[]).flatMap((step) => {
385
385
  if (step === null || typeof step !== "object" || !("side" in step)) return [step];
386
386
  const { side: only, ...action } = step as Record<string, unknown>;
387
387
  return only === "original" ? [] : [action];
388
388
  });
389
- return { kind: "scenario", text: `${JSON.stringify({ ...rest, original: side(original, `baseline/${name}`), rebuild: side(rebuild, `build/${name}`), steps: both }, null, 2)}\n` };
389
+ return { kind: "scenario", text: `${JSON.stringify({ ...rest, original: side(`baseline/${name}`), rebuild: side(`build/${name}`), steps: both }, null, 2)}\n` };
390
390
  }
391
391
  const start = test.start as Record<string, unknown>;
392
392
  const symbolsFile = test.symbols === undefined || test.symbols === "none" ? {} : { symbols: `build/${name}.json` };
@@ -1,6 +1,7 @@
1
1
  // ACME source from an image, current knowledge and Ghidra's instruction
2
2
  // boundaries. The same input gives the same text. Names come from
3
- // knowledge; a target that knowledge does not name gets l_xxxx. Data is
3
+ // knowledge; a target that knowledge does not name gets l_xxxx. A read or
4
+ // write in the I/O area names the register, also where the image holds RAM. Data is
4
5
  // written by its region type. The source assembles to the same bytes: the
5
6
  // generator forces operand sizes, and writes an opcode form that ACME
6
7
  // encodes differently as bytes (see the probe in source.ts). An operand
@@ -40,6 +41,8 @@ export interface SourceInput {
40
41
  platformLeftOut?: ReadonlySet<string>;
41
42
  /** The platform area of an address, and the register that an I/O mirror repeats: constants.asm groups and describes its names with them. */
42
43
  describe?: (address: number) => { area: Area; mirrorOf?: number };
44
+ /** The I/O area: a code operand there names the register, also when the image holds RAM there. */
45
+ io?: AddressRange;
43
46
  /** What a value in a platform register means (c64-memory-map): an immediate stored to such a register gets it as a side comment. Throws for a register without a decoder. */
44
47
  decode?: (register: number, value: number) => Record<string, unknown>;
45
48
  /** Operand expressions of the knowledge, by instruction address. */
@@ -158,7 +161,7 @@ function decodedText(decoded: Record<string, unknown>): string {
158
161
  * register with a decoder, for example "$d011: yScroll 3, rows 25". A knowledge
159
162
  * side comment at the store wins.
160
163
  */
161
- function decodedStores(pieces: readonly Piece[], input: SourceInput): Array<{ address: number; placement: CommentPlacement; text: string }> {
164
+ function decodedStores(pieces: readonly Piece[], input: SourceInput, isRegister: (address: number) => boolean): Array<{ address: number; placement: CommentPlacement; text: string }> {
162
165
  if (input.decode === undefined) return [];
163
166
  const own = new Set(input.comments.filter((comment) => comment.placement === "side").map((comment) => comment.address));
164
167
  const found: Array<{ address: number; placement: CommentPlacement; text: string }> = [];
@@ -170,8 +173,8 @@ function decodedStores(pieces: readonly Piece[], input: SourceInput): Array<{ ad
170
173
  const register = STORES[store.opcode];
171
174
  if (register === undefined || LOADS[load.opcode] !== register || load.address + load.length !== store.address || own.has(store.address)) continue;
172
175
  const target = store.length === 3 ? input.byteAt(store.address + 1) | (input.byteAt(store.address + 2) << 8) : input.byteAt(store.address + 1);
173
- // A register inside the image is RAM of the program, not the register.
174
- if (input.segments.some((segment) => target >= segment.start && target <= segment.end)) continue;
176
+ // A register inside the image is RAM of the program, not the register, unless the source names the register there.
177
+ if (!isRegister(target)) continue;
175
178
  try {
176
179
  const text = decodedText(input.decode(target, input.byteAt(load.address + 1)));
177
180
  if (text !== "") found.push({ address: store.address, placement: "side", text: `${formatC64Address(target)}: ${text}` });
@@ -215,8 +218,12 @@ export interface Layout {
215
218
  pieces: Piece[];
216
219
  /** Names of addresses: inside the image a label, outside it a constant. */
217
220
  names: Map<number, string>;
218
- /** Addresses outside the image that the source names, as constants. */
221
+ /** Addresses that the source names as constants: outside the image, and the registers in `registers`. */
219
222
  constants: number[];
223
+ /** Platform names of addresses inside the image that the source writes as constants, not as labels: a name of an operand expression, and a register of the I/O area. */
224
+ registers: Map<number, string>;
225
+ /** The operand of an instruction without an expression when it is not the name of its target: a register of the I/O area, or the plain address of the I/O area. */
226
+ operandNames: Map<number, string>;
220
227
  /** How the source uses each constant: instructions by kind, and pointer table entries. */
221
228
  uses: Map<number, Map<UseKind, number>>;
222
229
  platform: NonNullable<SourceInput["platform"]>;
@@ -364,12 +371,22 @@ export function layout(input: SourceInput): Layout {
364
371
  /** Addresses outside the image without a name of their own, inside a named platform entry of more bytes: the start of that entry. */
365
372
  const insideEntry = new Map<number, number>();
366
373
  const uses = new Map<number, Map<UseKind, number>>();
367
- const count = (constant: number, kind: UseKind) => {
368
- outside.add(constant);
374
+ const tally = (constant: number, kind: UseKind) => {
369
375
  const kinds = uses.get(constant) ?? new Map<UseKind, number>();
370
376
  kinds.set(kind, (kinds.get(kind) ?? 0) + 1);
371
377
  uses.set(constant, kinds);
372
378
  };
379
+ const count = (constant: number, kind: UseKind) => {
380
+ outside.add(constant);
381
+ tally(constant, kind);
382
+ };
383
+ /** Platform names inside the image that the source writes as constants: the register, not the RAM of the program there. */
384
+ const registers = new Map<number, string>();
385
+ const register = (address: number, name: string, kind: UseKind) => {
386
+ registers.set(address, name);
387
+ tally(address, kind);
388
+ };
389
+ const inIo = (address: number) => input.io !== undefined && address >= input.io.start && address <= input.io.end;
373
390
  /** The start of the named data region that holds an address without a name of its own: the operand is written name+offset. */
374
391
  const tableStart = (address: number) => {
375
392
  if (symbols.has(address)) return undefined;
@@ -393,6 +410,30 @@ export function layout(input: SourceInput): Layout {
393
410
  const byName = new Map<string, number>();
394
411
  for (const row of input.platform ?? []) if (!byName.has(row.name)) byName.set(row.name, row.address);
395
412
  for (const symbol of input.symbols) byName.set(symbol.name, symbol.address);
413
+ /** A platform name of an expression stays as written: inside the image it is a register constant, not the label of the RAM there. */
414
+ const useName = (name: string, kind: UseKind) => {
415
+ const address = byName.get(name)!;
416
+ if (inImage(address) && platform.get(address) === name) register(address, name, kind);
417
+ else use(address, kind);
418
+ };
419
+ /**
420
+ * The operand of an instruction without an expression. A read or a write in the
421
+ * I/O area inside the image, without a knowledge name there, is the register:
422
+ * its platform name, else the plain address. The data label of the RAM there stays.
423
+ */
424
+ const operandNames = new Map<number, string>();
425
+ const useOperand = (item: InstructionItem) => {
426
+ const value = operandValue(item.address, item.opcode, input.byteAt)!;
427
+ const kind = useKind(item.opcode);
428
+ const access = kind === "read" || kind === "written" || kind === "modified";
429
+ if (!inImage(value) || symbols.has(value) || !access) return use(value, kind);
430
+ const name = registers.get(value) ?? (inIo(value) ? platform.get(value) : undefined);
431
+ if (name !== undefined) {
432
+ register(value, name, kind);
433
+ operandNames.set(item.address, name);
434
+ } else if (inIo(value)) operandNames.set(item.address, literalOperand(item.opcode, value));
435
+ else use(value, kind);
436
+ };
396
437
  const instructionAt = new Map(pieces.flatMap((piece) => piece.items.flatMap((item) => (item.kind === "instruction" ? [[item.address, item] as const] : []))));
397
438
  /** Why names of an expression are not names of the source: not known, or platform names of a ROM that the program does not use. */
398
439
  const unknownNames = (missing: readonly string[], remedy: string) => {
@@ -459,19 +500,20 @@ export function layout(input: SourceInput): Layout {
459
500
  // An immediate operand builds the address of a name; any other operand uses the address as the instruction does.
460
501
  expressions.push({ address: operand.address, text: expression, kind: mode === "imm" ? "address" : useKind(item!.opcode) });
461
502
  }
462
- for (const { text: expression, kind } of expressions) for (const name of identifiers(expression)) use(byName.get(name)!, kind);
503
+ // The names of expressions and macro args come first: a platform name there names the register for the plain operands too.
504
+ for (const { text: expression, kind } of expressions) for (const name of identifiers(expression)) useName(name, kind);
505
+ for (const candidate of candidates) for (const arg of candidate.use.args) for (const name of identifiers(arg)) useName(name, "macro argument");
463
506
  // An instruction with an expression names what the expression names, not its plain target.
464
507
  const written = new Set(expressions.map((expression) => expression.address));
465
508
  for (const piece of pieces) {
466
509
  for (const item of piece.items) {
467
510
  if (item.kind === "instruction") {
468
- if (takesAddress(OPCODES[item.opcode]!.mode) && !written.has(item.address) && !inUse.has(item.address)) use(operandValue(item.address, item.opcode, input.byteAt)!, useKind(item.opcode));
511
+ if (takesAddress(OPCODES[item.opcode]!.mode) && !written.has(item.address) && !inUse.has(item.address)) useOperand(item);
469
512
  continue;
470
513
  }
471
514
  for (const pointer of pointersOf(item, input.byteAt)) use(pointer, "table");
472
515
  }
473
516
  }
474
- for (const candidate of candidates) for (const arg of candidate.use.args) for (const name of identifiers(arg)) use(byName.get(name)!, "macro argument");
475
517
  for (const symbol of input.symbols) want(symbol.address);
476
518
  // A reference target inside a named data region without its own name is that region's name plus the offset: it makes no label.
477
519
  for (const target of input.referenceTargets) want(tableStart(target) ?? target);
@@ -488,7 +530,7 @@ export function layout(input: SourceInput): Layout {
488
530
  macrosAsInstructions.push({ start: candidate.use.start, end: candidate.use.end, macro: candidate.use.macro, reason: `The source has a label at ${formatC64Address(inside)}, inside the use.` });
489
531
  for (const item of candidate.items) {
490
532
  inUse.delete(item.address);
491
- if (takesAddress(OPCODES[item.opcode]!.mode) && !written.has(item.address)) use(operandValue(item.address, item.opcode, input.byteAt)!, useKind(item.opcode));
533
+ if (takesAddress(OPCODES[item.opcode]!.mode) && !written.has(item.address)) useOperand(item);
492
534
  }
493
535
  }
494
536
  }
@@ -506,7 +548,8 @@ export function layout(input: SourceInput): Layout {
506
548
  if (inImage(address)) namedLabels++;
507
549
  continue;
508
550
  }
509
- const named = platform.get(address);
551
+ // A platform name in the I/O area, or of a register constant, is the register: the RAM of the program there gets no label of that name.
552
+ const named = inImage(address) && (inIo(address) || registers.has(address)) ? undefined : platform.get(address);
510
553
  if (named !== undefined) {
511
554
  names.set(address, named);
512
555
  if (inImage(address)) namedLabels++;
@@ -562,9 +605,14 @@ export function layout(input: SourceInput): Layout {
562
605
  // The high byte of a vector is NMINV+1. A zero-page entry keeps zero-page instructions: its constant has two digits.
563
606
  // An address inside a table keeps its own label when the source needs one there anyway, for example as the entry.
564
607
  for (const [address, start] of insideEntry) if (!wanted.has(address)) names.set(address, `${names.get(start)!}+${address - start}`);
608
+ /** The name that the source gives a name of an expression: a register constant keeps its platform name. */
609
+ const sourceName = (name: string) => {
610
+ const address = byName.get(name)!;
611
+ return registers.get(address) === name ? name : names.get(address);
612
+ };
565
613
  /** An expression with the names of this source: a name with an offset in brackets, so an operator after it keeps its meaning. */
566
614
  const sourceText = (text: string) => replaceIdentifiers(text, (name) => {
567
- const label = names.get(byName.get(name)!)!;
615
+ const label = sourceName(name)!;
568
616
  return label.includes("+") ? `(${label})` : label;
569
617
  });
570
618
  const usesWritten = new Map<number, MacroUseBlock>();
@@ -573,7 +621,7 @@ export function layout(input: SourceInput): Layout {
573
621
  for (const { address, text } of expressions) {
574
622
  const unnamed: string[] = [];
575
623
  const written = replaceIdentifiers(text, (name) => {
576
- const label = names.get(byName.get(name)!);
624
+ const label = sourceName(name);
577
625
  if (label === undefined) unnamed.push(name);
578
626
  return label === undefined ? name : label.includes("+") ? `(${label})` : label;
579
627
  });
@@ -583,13 +631,15 @@ export function layout(input: SourceInput): Layout {
583
631
  return {
584
632
  pieces,
585
633
  names,
586
- constants: [...outside].sort((a, b) => a - b),
634
+ constants: [...outside, ...registers.keys()].sort((a, b) => a - b),
635
+ registers,
636
+ operandNames,
587
637
  uses,
588
638
  platform: input.platform ?? [],
589
639
  ...(input.describe === undefined ? {} : { describe: input.describe }),
590
640
  inImage,
591
641
  byteAt: input.byteAt,
592
- comments: [...input.comments, ...decodedStores(pieces, input)],
642
+ comments: [...input.comments, ...decodedStores(pieces, input, (address) => !inImage(address) || (registers.has(address) && !symbols.has(address)))],
593
643
  ...(input.coverage === undefined ? {} : { coverage: input.coverage }),
594
644
  generatedLabels,
595
645
  namedLabels,
@@ -800,16 +850,20 @@ function dataLines(item: DataItem, layout: Layout, breaks: Set<number>): Array<{
800
850
  /** A longer name moves only its own comment, not the columns of the file. */
801
851
  const MAX_NAME_COLUMN = 24;
802
852
 
803
- /** What an address outside the image is: the comment of the knowledge, else the platform meaning, else the register that a mirror repeats. */
804
- function describeConstant(layout: Layout, address: number): string | undefined {
805
- const comments = layout.comments.filter((comment) => comment.address === address);
853
+ /**
854
+ * What a constant is: the comment of the knowledge, else the platform meaning,
855
+ * else the register that a mirror repeats. A comment inside the image is of the
856
+ * RAM there, so a register constant has the platform meaning.
857
+ */
858
+ function describeConstant(layout: Layout, address: number, name: string): string | undefined {
859
+ const comments = layout.registers.has(address) ? [] : layout.comments.filter((comment) => comment.address === address);
806
860
  // Line comments come before the side comment, as they do in the code.
807
861
  const own = [...comments.filter((comment) => comment.placement === "line"), ...comments.filter((comment) => comment.placement === "side")];
808
862
  if (own.length > 0) return own.map((comment) => comment.text.replace(/\s*\r?\n\s*/g, " ").trim()).join(" ");
809
863
  const entry = layout.platform.find((row) => address >= row.address && address <= row.end);
810
864
  if (entry?.meaning !== undefined) {
811
865
  const platformName = address === entry.address ? entry.name : `${entry.name}+${address - entry.address}`;
812
- return platformName === layout.names.get(address) ? entry.meaning : `${platformName}: ${entry.meaning}`;
866
+ return platformName === name ? entry.meaning : `${platformName}: ${entry.meaning}`;
813
867
  }
814
868
  const mirrorOf = layout.describe?.(address).mirrorOf;
815
869
  if (mirrorOf === undefined) return undefined;
@@ -918,13 +972,14 @@ function switchesText(layout: Layout): string {
918
972
  return `${out.join("\n")}\n`;
919
973
  }
920
974
 
921
- /** constants.asm: the names outside the image by platform area, each with what it is and how the source uses it. */
975
+ /** constants.asm: the names outside the image and the register constants by platform area, each with what it is and how the source uses it. */
922
976
  function constantsText(layout: Layout): { text: string; labels: SourceLabel[] } {
923
977
  const { describe } = layout;
924
978
  const labels: SourceLabel[] = [];
925
979
  const rows = layout.constants.map((address) => {
926
- const comment = [describeConstant(layout, address), usageText(layout.uses.get(address))].filter((text) => text !== undefined).join(" ");
927
- return { address, name: layout.names.get(address)!, value: constantValue(address), comment };
980
+ const name = layout.registers.get(address) ?? layout.names.get(address)!;
981
+ const comment = [describeConstant(layout, address, name), usageText(layout.uses.get(address))].filter((text) => text !== undefined).join(" ");
982
+ return { address, name, value: constantValue(address), comment };
928
983
  });
929
984
  const nameColumn = Math.min(MAX_NAME_COLUMN, Math.max(0, ...rows.map((row) => row.name.length)));
930
985
  const valueColumn = Math.max(0, ...rows.map((row) => row.value.length));
@@ -932,6 +987,7 @@ function constantsText(layout: Layout): { text: string; labels: SourceLabel[] }
932
987
  out.push(
933
988
  describe === undefined ? "; Names of addresses outside the image." : "; Names of addresses outside the image, by memory area.",
934
989
  '; "Used" counts the instructions and table entries of this source that use the name.',
990
+ ...(layout.registers.size === 0 ? [] : ["; A name of an address inside the image names the register there, not the RAM of the program."]),
935
991
  );
936
992
  // Without platform areas the names form one group.
937
993
  if (describe === undefined && rows.length > 0) out.push("");
@@ -1205,7 +1261,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1205
1261
  out.push(withSide(`${INDENT}${instructionWith(item.opcode, written, form.suffix)}`, sides.length === 0 ? undefined : sides.join(" ")));
1206
1262
  result.expressions.push({ address: item.address, length: item.length, file: piece.file, line: out.length });
1207
1263
  } else {
1208
- const expression = takesAddress(mode) ? (layout.names.get(value) ?? literalOperand(item.opcode, value)) : literalOperand(item.opcode, value);
1264
+ const expression = takesAddress(mode) ? (layout.operandNames.get(item.address) ?? layout.names.get(value) ?? literalOperand(item.opcode, value)) : literalOperand(item.opcode, value);
1209
1265
  out.push(withSide(`${INDENT}${instructionWith(item.opcode, expression, form.suffix)}`, sides.length === 0 ? undefined : sides.join(" ")));
1210
1266
  }
1211
1267
  mapLine(item.address, item.address + item.length - 1);