@henols/c64-re-tools 2.6.0-rc.9 → 2.7.0-rc.1

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 (79) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +7 -7
  3. package/skills/c64-assembler/scripts/assembler.ts +4 -3
  4. package/skills/c64-basic/SKILL.md +1 -1
  5. package/skills/c64-development/SKILL.md +7 -7
  6. package/skills/c64-disk/SKILL.md +13 -13
  7. package/skills/c64-docs/SKILL.md +25 -10
  8. package/skills/c64-docs/references/page-types.md +11 -11
  9. package/skills/c64-docs/references/style.md +21 -0
  10. package/skills/c64-docs/scripts/docs.ts +78 -18
  11. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  12. package/skills/c64-docs/scripts/lib/reference.ts +117 -31
  13. package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
  14. package/skills/c64-knowledge/SKILL.md +15 -14
  15. package/skills/c64-knowledge/scripts/knowledge.ts +17 -10
  16. package/skills/c64-memory-map/SKILL.md +1 -1
  17. package/skills/c64-packer/SKILL.md +1 -1
  18. package/skills/c64-provenance/SKILL.md +5 -4
  19. package/skills/c64-provenance/scripts/lib/compare.ts +1 -1
  20. package/skills/c64-reverse-engineering/SKILL.md +26 -11
  21. package/skills/c64-source/SKILL.md +18 -15
  22. package/skills/c64-source/scripts/lib/export.ts +20 -8
  23. package/skills/c64-source/scripts/lib/loader.ts +51 -28
  24. package/skills/c64-source/scripts/lib/source.ts +27 -20
  25. package/skills/c64-source/scripts/source.ts +68 -53
  26. package/skills/c64-static-analysis/SKILL.md +24 -22
  27. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  28. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  29. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  30. package/skills/c64-static-analysis/scripts/static-analysis.ts +36 -27
  31. package/skills/c64-testing/SKILL.md +32 -24
  32. package/skills/c64-testing/references/recording-format.md +15 -9
  33. package/skills/c64-testing/references/scenario-format.md +9 -7
  34. package/skills/c64-testing/scripts/lib/recording.ts +214 -49
  35. package/skills/c64-testing/scripts/lib/replay.ts +45 -19
  36. package/skills/c64-testing/scripts/lib/runs.ts +7 -2
  37. package/skills/c64-testing/scripts/lib/scenario.ts +31 -31
  38. package/skills/c64-testing/scripts/testing.ts +37 -16
  39. package/skills/c64-unpacker/SKILL.md +16 -14
  40. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  41. package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
  42. package/src/build-name.ts +9 -4
  43. package/src/c64.ts +1 -1
  44. package/src/host/main.ts +2 -2
  45. package/src/host/server.ts +3 -1
  46. package/src/host/tools/index.ts +1 -1
  47. package/src/host/vice/process.ts +34 -17
  48. package/src/host/vice/session.ts +55 -27
  49. package/src/host-client/steps.ts +4 -1
  50. package/src/host-client/tools.ts +1 -1
  51. package/src/knowledge/evidence.ts +66 -0
  52. package/src/knowledge/history.ts +5 -5
  53. package/src/knowledge/import.ts +12 -5
  54. package/src/knowledge/program.ts +81 -33
  55. package/src/knowledge/read.ts +3 -3
  56. package/src/knowledge/schema.ts +7 -7
  57. package/src/knowledge/separate.ts +2 -2
  58. package/src/knowledge/start-screen.ts +2 -0
  59. package/src/knowledge/text.ts +28 -3
  60. package/src/knowledge/write.ts +7 -7
  61. package/src/mcp/tools/debug.ts +23 -21
  62. package/src/mcp/tools/memory.ts +12 -9
  63. package/src/native/c64run.ts +7 -4
  64. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  65. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  66. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  67. package/src/native/types.ts +25 -25
  68. package/src/opcodes.ts +1 -1
  69. package/src/project.ts +1 -1
  70. package/src/reference-pages.ts +64 -0
  71. package/src/script.ts +2 -2
  72. package/tools/c64run.c +151 -5
  73. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  74. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  75. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  76. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  77. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  78. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  79. /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
@@ -16,11 +16,14 @@
16
16
  import { readFileSync } from "node:fs";
17
17
  import { fileURLToPath } from "node:url";
18
18
 
19
+ import { COPIER_LINE } from "#src/build-name.ts";
19
20
  import { type AddressRange, formatC64Address, formatC64Byte, prgRange } from "#src/c64.ts";
20
21
  import { compareBuild, mergedPrograms } from "#src/compare.ts";
21
22
  import { Refusal } from "#src/errors.ts";
22
23
  import { parseEntryState } from "#src/host-client/entry-state.ts";
23
24
  import { isRomFont, startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
25
+ import { LOADER_JUMP } from "#src/knowledge/start-screen.ts";
26
+ import { romUseOfPort } from "#src/platform.ts";
24
27
  import { WireFailure } from "#src/host-client/tools.ts";
25
28
  import { pack } from "#src/native/exomizer.ts";
26
29
  import type { ToolContext } from "#src/native/run.ts";
@@ -137,9 +140,7 @@ export function loaderLimits(plan: { cia?: CiaPlan }): string[] {
137
140
  return plan.cia.limits;
138
141
  }
139
142
 
140
- /** The label of the loader's jump to the entry, in ACME's symbol list. */
141
- export const LOADER_JUMP = "c64_source_loader_jump";
142
- export { START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
143
+ export { LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
143
144
  /** The file of the start screen in the generated source. */
144
145
  export const START_SCREEN_FILE = "start_screen.asm";
145
146
  /** The code of the start screen: the same for each program. loader.asm sets its values. */
@@ -216,11 +217,12 @@ const COPY_ENTRY = 7;
216
217
  const TABLE_COPIES = Math.floor((256 - 2) / COPY_ENTRY);
217
218
  /** A loader that loads into $d000 or higher would write the I/O area. */
218
219
  const LOAD_LIMIT = 0xcfff;
219
- const COPIER_PAGES = [...Array.from({ length: 15 }, (_, index) => 0xc000 + index * 0x100), ...Array.from({ length: 0x9b }, (_, index) => 0x9e00 - index * 0x100)];
220
- /** The areas where the copier can run: RAM that no ROM and no I/O hides when $01 is $34 or $35, above the screen at $0400. */
221
- const COPIER_AREAS: readonly AddressRange[] = [
222
- { start: 0x0400, end: 0x9fff },
223
- { start: 0xc000, end: 0xcfff },
220
+ /** The pages where the plain copier can start, the first one that is free: then the RAM that a ROM can hide, as copierAreas allows. */
221
+ const COPIER_PAGES = [
222
+ ...Array.from({ length: 15 }, (_, index) => 0xc000 + index * 0x100),
223
+ ...Array.from({ length: 0x9b }, (_, index) => 0x9e00 - index * 0x100),
224
+ ...Array.from({ length: 0x20 }, (_, index) => 0xa000 + index * 0x100),
225
+ ...Array.from({ length: 0x20 }, (_, index) => 0xe000 + index * 0x100),
224
226
  ];
225
227
 
226
228
  const overlaps = (a: AddressRange, b: AddressRange) => a.start <= b.end && b.start <= a.end;
@@ -564,13 +566,14 @@ export function planLoader(input: LoaderInput): LoaderPlan {
564
566
  throw new WireFailure("invalid-input", `No copy order exists: each of these copies writes over the packed bytes of another one: ${clashing.join(", ")}. Write the loader by hand.`);
565
567
  }
566
568
  const loaded = { start: LOAD, end };
569
+ const areas = copierAreas(state.port);
567
570
  const copier = COPIER_PAGES.find((page) => {
568
571
  const pages = { start: page, end: page + copierBytes - 1 };
569
- return COPIER_AREAS.some((area) => pages.start >= area.start && pages.end <= area.end) && !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
572
+ return areas.some((area) => pages.start >= area.start && pages.end <= area.end) && !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
570
573
  });
571
574
  if (copier === undefined) {
572
575
  const count = copierPages === 2 ? "two" : "three";
573
- throw new WireFailure("invalid-input", `No ${count} free pages exist for the copier in $0400-$9fff or $c000-$cfff outside the loader (${show(loaded)}) and the targets: ${plain.map((copy) => show(copy.target)).join(", ")}.`);
576
+ throw new WireFailure("invalid-input", `No ${count} free pages exist for the copier in ${areas.map(show).join(" or ")} outside the loader (${show(loaded)}) and the targets: ${plain.map((copy) => show(copy.target)).join(", ")}.`);
574
577
  }
575
578
  const copies: Copy[] = order.map((index) => {
576
579
  const copy = plain[index]!;
@@ -640,11 +643,21 @@ export function planLoader(input: LoaderInput): LoaderPlan {
640
643
  };
641
644
  }
642
645
 
643
- /** Where the packed form puts its copier with the bytes of pages 0-3: the copier sets $01 to $35 and to the entry's value, so it is not under a ROM or the I/O area. */
644
- const PACKED_AREAS: readonly AddressRange[] = [
645
- { start: 0x0400, end: 0x9fff },
646
- { start: 0xc000, end: 0xcfff },
647
- ];
646
+ /** The hardware vectors at $fffa-$ffff: the copier and the pieces of pages 0-3 stay below them. */
647
+ const BELOW_VECTORS = 0xfff9;
648
+ /** Where the packed form puts the bytes of pages 0-3: the copier reads them with all RAM visible ($01 = $34). */
649
+ const PIECE_AREA: AddressRange = { start: 0x0400, end: BELOW_VECTORS };
650
+
651
+ /**
652
+ * Where a loader puts its copier: the copier sets $01 to $35 and then to the
653
+ * entry's value, so it is in RAM that both show. A port bit that is an input
654
+ * reads 1.
655
+ */
656
+ export function copierAreas(port: readonly [number, number]): AddressRange[] {
657
+ const rom = romUseOfPort((port[1] | ~port[0]) & 0x07);
658
+ if (rom.basic) return [{ start: 0x0400, end: 0x9fff }, { start: 0xc000, end: 0xcfff }];
659
+ return [{ start: 0x0400, end: 0xcfff }, ...(rom.kernal ? [] : [{ start: 0xe000, end: BELOW_VECTORS }])];
660
+ }
648
661
  /** The free ranges that a refusal of the packed form names. */
649
662
  const SHOWN_FREE = 8;
650
663
 
@@ -658,8 +671,10 @@ const SHOWN_FREE = 8;
658
671
  * writes them after the unpack. Between its ranges, loader.asm holds the
659
672
  * bytes of the image, so its build does not change a segment.
660
673
  */
661
- function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, codeSize: number, screen: StartScreenPlan | undefined, tooLarge: string): LoaderPlan {
674
+ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, copierCode: number, screen: StartScreenPlan | undefined, tooLarge: string): LoaderPlan {
662
675
  const { state } = input;
676
+ // The packed copier starts with SEI, as the stub of the plain form does: an interrupt in the copies would go through the vectors in RAM.
677
+ const codeSize = copierCode + 1;
663
678
  // The parts below $0400 without $00/$01, which the loader sets last.
664
679
  const low = blocks.flatMap((block) => {
665
680
  const range = { start: Math.max(block.range.start, 0x0002), end: Math.min(block.range.end, 0x03ff) };
@@ -668,16 +683,21 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
668
683
  return [{ what: cut ? `${block.what}, part ${show(range)}` : block.what, range, bytes: block.bytes }];
669
684
  });
670
685
  const lowBytes = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
671
- const free = PACKED_AREAS.flatMap((area) => subtract(area, input.segments));
672
- const placed = placePacked(free, low, codeSize);
686
+ const areas = copierAreas(state.port);
687
+ const free = subtract(PIECE_AREA, input.segments);
688
+ const copierFree = areas.flatMap((area) => subtract(area, input.segments));
689
+ const placed = placePacked(copierFree, free, low, codeSize);
673
690
  if ("refusal" in placed) {
674
- const largest = [...free].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
675
- const ranges = largest.length === 0 ? "none" : largest.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
691
+ const largest = (ranges: AddressRange[]) => {
692
+ const shown = [...ranges].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
693
+ return shown.length === 0 ? "none" : shown.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
694
+ };
695
+ const ranges = placed.refusal === "copies" ? `The largest free ranges for pages 0-3: ${largest(free)}.` : `The largest free ranges for the copier: ${largest(copierFree)}. The largest free ranges for pages 0-3: ${largest(free)}.`;
676
696
  const why =
677
697
  placed.refusal === "copies"
678
698
  ? `A packed loader needs more than ${MAX_PACKED_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
679
- : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier, and ${lowBytes} more free bytes for pages 0-3, in $0400-$9fff or $c000-$cfff outside the segments.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
680
- throw new WireFailure("invalid-input", `${tooLarge} ${why} The largest free ranges there: ${ranges}. Write the loader by hand.`);
699
+ : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier in ${areas.map(show).join(" or ")}, and ${lowBytes} more free bytes for pages 0-3 in ${show(PIECE_AREA)}, outside the segments. The copier runs with $01 = $35 and then with the $01 of the entry, so it is in RAM that both show.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
700
+ throw new WireFailure("invalid-input", `${tooLarge} ${why} ${ranges} Write the loader by hand.`);
681
701
  }
682
702
  const { copier, pieces } = placed;
683
703
  const copierEnd = copier + codeSize + COPY_ENTRY * pieces.length + 2 - 1;
@@ -691,6 +711,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
691
711
  "; The image is too large for one loader file, so this is the packed form. Exomizer packs the",
692
712
  `; build of main.asm and the build of this file into the loader program, with --entry '${formatC64Address(copier)}' and --exit-memory '$34'.`,
693
713
  "; The unpacker of Exomizer uses the zero page and $0334-$03ff, so the copier writes pages $0002-$03ff after the unpack.",
714
+ COPIER_LINE,
694
715
  "",
695
716
  "!cpu 6510",
696
717
  ...settingsLines(input),
@@ -702,6 +723,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
702
723
  `; The copier runs at ${formatC64Address(copier)}. The flags pass through ${formatC64Address(stackByte)}, the free stack byte below the stack pointer.`,
703
724
  `* = ${formatC64Address(copier)}`,
704
725
  COPIER_SOURCE,
726
+ " sei",
705
727
  // The entry by its address: main.asm, which has its label, is not in this build.
706
728
  ...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`, screen !== undefined),
707
729
  ];
@@ -786,19 +808,19 @@ export function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: s
786
808
 
787
809
  /**
788
810
  * Where the packed form puts its copier and the pieces of pages 0-3: the copier
789
- * in one free range, a free page of the plain copier first, else the start of a
811
+ * in one range of copierFree, a free page of the plain copier first, else the start of a
790
812
  * free range. The placement with the fewest pieces wins, then the one with the
791
813
  * shortest build of loader.asm.
792
814
  */
793
- function placePacked(free: AddressRange[], low: Parameters<typeof placePieces>[1], codeSize: number): { copier: number; pieces: Piece[] } | { refusal: "room" | "copies" } {
794
- const candidates = [...COPIER_PAGES, ...free.map((range) => range.start)];
815
+ function placePacked(copierFree: AddressRange[], free: AddressRange[], low: Parameters<typeof placePieces>[1], codeSize: number): { copier: number; pieces: Piece[] } | { refusal: "room" | "copies" } {
816
+ const candidates = [...COPIER_PAGES, ...copierFree.map((range) => range.start)];
795
817
  // The table has one entry per piece: a split can make the copier larger, so the room for the table grows until it holds every piece.
796
818
  for (let copies = Math.max(low.length, 1); copies <= MAX_PACKED_COPIES; ) {
797
819
  const size = codeSize + COPY_ENTRY * copies + 2;
798
820
  let best: { copier: number; pieces: Piece[]; span: number } | undefined;
799
821
  for (const copier of candidates) {
800
822
  const range = { start: copier, end: copier + size - 1 };
801
- if (!free.some((area) => range.start >= area.start && range.end <= area.end)) continue;
823
+ if (!copierFree.some((area) => range.start >= area.start && range.end <= area.end)) continue;
802
824
  // A piece goes to the start of its range: a range below the copier adds its whole length to the build.
803
825
  const distance = (other: AddressRange) => (other.end < range.start ? range.start - other.start : other.start - range.end);
804
826
  const pieces = placePieces(free.flatMap((area) => subtract(area, [range])), low, distance);
@@ -934,10 +956,11 @@ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stac
934
956
  // The CIA part runs after the raster wait: the wait ends its whole lines earlier, so the entry comes in its line.
935
957
  ...vicLines(state, Math.floor((cia?.ops.reduce((sum, op) => sum + op.cycles, 0) ?? 0) / LINE_CYCLES)),
936
958
  ...(cia === undefined ? [] : cia.ops.map((op) => ` ${op.text}`)),
937
- ` lda #${formatC64Byte(port0)}`,
938
- " sta $00",
959
+ // $01 before $00: with the port bits still outputs, $01 shows no ROM that the port of the entry does not show.
939
960
  ` lda #${formatC64Byte(port1)}`,
940
961
  " sta $01",
962
+ ` lda #${formatC64Byte(port0)}`,
963
+ " sta $00",
941
964
  ` ldx #${formatC64Byte((state.sp - 1) & 0xff)}`,
942
965
  " txs",
943
966
  ` lda #${formatC64Byte(state.flags)}`,
@@ -1,4 +1,4 @@
1
- // ACME source from an image, current knowledge and Ghidra's instruction
1
+ // ACME source from an image, current knowledge and the decompiler's instruction
2
2
  // boundaries. The same input gives the same text. Names come from
3
3
  // knowledge; a target that knowledge does not name gets l_xxxx. A read or
4
4
  // write in the I/O area names the register, also where the image holds RAM. Data is
@@ -6,7 +6,7 @@
6
6
  // generator forces operand sizes, and writes an opcode form that ACME
7
7
  // encodes differently as bytes (see the probe in source.ts). An operand
8
8
  // expression of the knowledge is written in place of its number. A
9
- // patch is written as !if SWITCH { code } else { original }, with the
9
+ // patch is written as !if SWITCH { code } else { base code }, with the
10
10
  // condition of the state that the program does not have, and a macro use as
11
11
  // one +name args line. config.asm holds the value of each switch, and
12
12
  // switches.asm the values of each release. A range of leftovers (bytes that
@@ -30,7 +30,7 @@ export interface SourceInput {
30
30
  /** The image byte at an address inside a segment. */
31
31
  byteAt: (address: number) => number;
32
32
  entry?: number;
33
- /** Where Ghidra decoded an instruction, with its length. */
33
+ /** Where the decompiler decoded an instruction, with its length. */
34
34
  instructions: ReadonlyMap<number, number>;
35
35
  /** Without an origin, a symbol counts as a user or LLM name. */
36
36
  symbols: ReadonlyArray<{ address: number; name: string; origin?: Origin }>;
@@ -204,7 +204,7 @@ interface DataItem {
204
204
  kind: "data";
205
205
  start: number;
206
206
  end: number;
207
- /** The region type, or unclassified. In a code region, bytes that Ghidra did not decode. */
207
+ /** The region type, or unclassified. In a code region, bytes that the decompiler did not decode. */
208
208
  type: RegionType | "unclassified" | "undecoded";
209
209
  region?: Region;
210
210
  }
@@ -280,7 +280,7 @@ function operandValue(address: number, opcode: number, byteAt: (address: number)
280
280
 
281
281
  /**
282
282
  * Each entry point inside a data region of the knowledge, with that region.
283
- * A data region wins over an entry: Ghidra does not decode there,
283
+ * A data region wins over an entry: the decompiler does not decode there,
284
284
  * and the source has data there. A code region in the knowledge changes that.
285
285
  */
286
286
  export function entriesInData<R extends { start: number; end: number; type: RegionType }>(entries: readonly number[], regions: readonly R[]): Array<{ entry: number; region: R }> {
@@ -528,7 +528,11 @@ export function layout(input: SourceInput): Layout {
528
528
  expressions.push({ address: operand.address, text: expression, kind: mode === "imm" ? "address" : useKind(item!.opcode) });
529
529
  }
530
530
  // The names of expressions and macro args come first: a platform name there names the register for the plain operands too.
531
- for (const { text: expression, kind } of expressions) for (const name of identifiers(expression)) useName(name, kind);
531
+ // An expression inside a written use names nothing: the macro line names only its args.
532
+ const useExpression = ({ text, kind }: { text: string; kind: UseKind }) => {
533
+ for (const name of identifiers(text)) useName(name, kind);
534
+ };
535
+ for (const expression of expressions) if (!inUse.has(expression.address)) useExpression(expression);
532
536
  for (const candidate of candidates) for (const arg of candidate.use.args) for (const name of identifiers(arg)) useName(name, "macro argument");
533
537
  // An instruction with an expression names what the expression names, not its plain target.
534
538
  const written = new Set(expressions.map((expression) => expression.address));
@@ -557,20 +561,12 @@ export function layout(input: SourceInput): Layout {
557
561
  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.` });
558
562
  for (const item of candidate.items) {
559
563
  inUse.delete(item.address);
560
- if (takesAddress(OPCODES[item.opcode]!.mode) && !written.has(item.address)) useOperand(item);
564
+ const expression = expressions.find((each) => each.address === item.address);
565
+ if (expression !== undefined) useExpression(expression);
566
+ else if (takesAddress(OPCODES[item.opcode]!.mode)) useOperand(item);
561
567
  }
562
568
  }
563
569
  }
564
- // A macro line also uses the addresses that its instructions name besides its args, for example the high byte
565
- // CUTHI of +mov16 CUTLO: a name of the source counts that use too. The args count as macro argument above.
566
- for (const candidate of accepted) {
567
- const argAddresses = new Set(candidate.use.args.flatMap((arg) => identifiers(arg)).map((name) => byName.get(name)));
568
- for (const item of candidate.items) {
569
- if (!takesAddress(OPCODES[item.opcode]!.mode)) continue;
570
- const value = operandValue(item.address, item.opcode, input.byteAt)!;
571
- if (!argAddresses.has(value) && uses.has(value)) tally(value, useKind(item.opcode));
572
- }
573
- }
574
570
 
575
571
  const names = new Map<number, string>();
576
572
  const taken = new Set([...knowledgeNames, ...platform.values()]);
@@ -1106,13 +1102,24 @@ function macrosText(layout: Layout): { text: string; lines: Map<string, { first:
1106
1102
  return { text: `${out.join("\n")}\n`, lines };
1107
1103
  }
1108
1104
 
1105
+ /** The bytes of patch code from `start` so far: after a byte at $ffff, ACME sets * to $0000. */
1106
+ const patchLength = (start: string) => `((* - ${start}) & $ffff)`;
1107
+ const LENGTH = patchLength(".patch_start");
1108
+
1109
+ /** The source of one patch of a captured stage on its own: the names of the stage, the code, and NOP to the end of its range. */
1110
+ export function stagePatchText(names: ReadonlyArray<{ name: string; address: number }>, patch: { start: number; end: number; code: string }): string {
1111
+ const start = formatC64Address(patch.start);
1112
+ const lines = ["!cpu 6510", ...names.map((symbol) => `${symbol.name} = ${formatC64Address(symbol.address)}`), `* = ${start}`, ...patch.code.split(/\r?\n/)];
1113
+ return `${[...lines, `!fill ${patch.end - patch.start + 1} - ${patchLength(start)}, $ea`].join("\n")}\n`;
1114
+ }
1115
+
1109
1116
  /** The condition that puts in the code of a switch: the switch has the value that the program does not have. */
1110
1117
  const patchCondition = (alternative: PatchAlternative) => (alternative.base === 0 ? alternative.switch : `${alternative.switch} = 0`);
1111
1118
 
1112
1119
  /**
1113
1120
  * The lines that open a patch: its zone, a guard that stops two alternatives
1114
1121
  * together, then for each switch its condition, its code and the guard that
1115
- * stops code longer than the range. The original code follows in the last
1122
+ * stops code longer than the range. The code of the base release follows in the last
1116
1123
  * else; the patch closes with closingBraces.
1117
1124
  */
1118
1125
  function patchOpening(patch: PatchBlock): string[] {
@@ -1132,7 +1139,7 @@ function patchOpening(patch: PatchBlock): string[] {
1132
1139
  `${INDENT}; ${alternative.switch} ${state}: ${bytes} byte${bytes === 1 ? "" : "s"} at ${range}, NOP after the code`,
1133
1140
  ...comment,
1134
1141
  ...(alternative.code === "" ? [] : alternative.code.split(/\r?\n/)),
1135
- `${INDENT}!if * - .patch_start > ${bytes} { !error "The patch ${alternative.switch} at ${formatC64Address(patch.start)} has ", * - .patch_start, " bytes; the range has ${bytes}." } else { !fill ${bytes} - (* - .patch_start), $ea }`,
1142
+ `${INDENT}!if ${LENGTH} > ${bytes} { !error "The patch ${alternative.switch} at ${formatC64Address(patch.start)} has ", ${LENGTH}, " bytes; the range has ${bytes}." } else { !fill ${bytes} - ${LENGTH}, $ea }`,
1136
1143
  );
1137
1144
  });
1138
1145
  out.push("} else {");
@@ -1193,7 +1200,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1193
1200
  let running = false;
1194
1201
  /** The line of the mark of the open range of instructions that did not execute. */
1195
1202
  let markLine = 0;
1196
- /** The open patch: its labels are defined before it, so the original code writes none. */
1203
+ /** The open patch: its labels are defined before it, so the code of the base release writes none. */
1197
1204
  let patch: PatchBlock | undefined;
1198
1205
  /** The last address of the macro use just written: its instructions are in the use line. */
1199
1206
  let useEnd = -1;