@henols/c64-re-tools 2.8.0-rc.1 → 2.8.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +7 -4
  3. package/skills/c64-assembler/scripts/assembler.ts +73 -44
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +62 -31
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +28 -18
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +144 -113
  22. package/skills/c64-source/SKILL.md +6 -1
  23. package/skills/c64-source/references/loader.md +2 -1
  24. package/skills/c64-source/scripts/lib/export.ts +54 -301
  25. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  26. package/skills/c64-source/scripts/lib/source.ts +53 -45
  27. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  28. package/skills/c64-source/scripts/source.ts +134 -294
  29. package/skills/c64-static-analysis/SKILL.md +13 -7
  30. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  31. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  32. package/skills/c64-static-analysis/scripts/lib/idioms.ts +98 -19
  33. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  34. package/skills/c64-static-analysis/scripts/static-analysis.ts +249 -147
  35. package/skills/c64-testing/SKILL.md +13 -7
  36. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  37. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  38. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  39. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  40. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  41. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  42. package/skills/c64-testing/scripts/testing.ts +32 -7
  43. package/skills/c64-unpacker/SKILL.md +9 -7
  44. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  45. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  46. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  47. package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
  48. package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
  49. package/skills/emulator/SKILL.md +1 -0
  50. package/src/c64.ts +133 -10
  51. package/src/cli/ap-sdk.ts +1 -1
  52. package/src/cli/cleanup.ts +4 -2
  53. package/src/compare.ts +36 -16
  54. package/src/errors.ts +10 -1
  55. package/src/host/main.ts +2 -1
  56. package/src/host/server.ts +7 -11
  57. package/src/host/tools/c1541.ts +9 -3
  58. package/src/host/vice/adapter.ts +20 -43
  59. package/src/host/vice/binary-monitor.ts +22 -21
  60. package/src/host/vice/process.ts +31 -40
  61. package/src/host/vice/session.ts +187 -247
  62. package/src/host/vice/text-monitor.ts +3 -3
  63. package/src/host-client/autostart.ts +1 -1
  64. package/src/host-client/connect.ts +2 -1
  65. package/src/host-client/coverage.ts +0 -3
  66. package/src/host-client/entry-state.ts +4 -11
  67. package/src/host-client/image.ts +6 -11
  68. package/src/host-client/steps.ts +13 -113
  69. package/src/host-client/tools.ts +4 -4
  70. package/src/host-client/transfer.ts +10 -0
  71. package/src/host-client/vice-session.ts +10 -6
  72. package/src/knowledge/code-reach.ts +364 -0
  73. package/src/knowledge/conflicts.ts +34 -72
  74. package/src/knowledge/database.ts +40 -28
  75. package/src/knowledge/evidence.ts +2 -2
  76. package/src/knowledge/graph.ts +3 -3
  77. package/src/knowledge/history.ts +50 -90
  78. package/src/knowledge/import.ts +28 -68
  79. package/src/knowledge/join.ts +1 -1
  80. package/src/knowledge/names.ts +12 -7
  81. package/src/knowledge/program.ts +59 -72
  82. package/src/knowledge/read.ts +104 -100
  83. package/src/knowledge/schema.ts +9 -3
  84. package/src/knowledge/separate.ts +175 -80
  85. package/src/knowledge/start-screen.ts +7 -5
  86. package/src/knowledge/text.ts +56 -33
  87. package/src/knowledge/write.ts +274 -515
  88. package/src/loader.ts +7 -25
  89. package/src/mcp/inputs.ts +3 -3
  90. package/src/mcp/server.ts +19 -38
  91. package/src/mcp/session-source.ts +2 -1
  92. package/src/mcp/tools/debug.ts +97 -24
  93. package/src/mcp/tools/execution.ts +1 -1
  94. package/src/mcp/tools/input.ts +3 -3
  95. package/src/mcp/tools/machine.ts +3 -3
  96. package/src/mcp/tools/media.ts +4 -4
  97. package/src/mcp/tools/memory.ts +13 -17
  98. package/src/mcp/tools/video.ts +11 -25
  99. package/src/native/acme.ts +3 -3
  100. package/src/native/c64run.ts +2 -1
  101. package/src/native/decompiler/analyze.ts +11 -8
  102. package/src/native/decompiler/walk.ts +3 -4
  103. package/src/native/decompiler/wasm.ts +2 -2
  104. package/src/native/discover.ts +1 -1
  105. package/src/native/dxa.ts +9 -11
  106. package/src/native/exomizer.ts +1 -1
  107. package/src/native/processes.ts +4 -1
  108. package/src/native/run.ts +3 -3
  109. package/src/native/types.ts +9 -8
  110. package/src/opcodes.ts +3 -0
  111. package/src/platform.ts +9 -10
  112. package/src/program-code.ts +151 -0
  113. package/src/project.ts +8 -5
  114. package/src/protocol/framing.ts +51 -18
  115. package/src/protocol/messages.ts +1 -11
  116. package/src/protocol/tools.ts +0 -3
  117. package/src/protocol/vice.ts +588 -773
  118. package/src/script.ts +25 -23
  119. package/src/time.ts +1 -1
  120. package/src/trace.ts +3 -2
@@ -19,7 +19,7 @@ import { readFileSync } from "node:fs";
19
19
  import { fileURLToPath } from "node:url";
20
20
 
21
21
  import { COPIER_LINE } from "#src/build-name.ts";
22
- import { type AddressRange, formatC64Address, formatC64Byte } from "#src/c64.ts";
22
+ import { type AddressRange, formatC64Address, formatC64Byte, formatC64Range, hexWord, rangesOverlap, subtract, underRom } from "#src/c64.ts";
23
23
  import { Refusal } from "#src/errors.ts";
24
24
  import { parseEntryState } from "#src/host-client/entry-state.ts";
25
25
  import { isRomFont, startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
@@ -145,7 +145,6 @@ export function loaderLimits(plan: { cia?: CiaPlan; colourLimit?: string }): str
145
145
  return [...cia, ...(plan.colourLimit === undefined ? [] : [plan.colourLimit])];
146
146
  }
147
147
 
148
- export { LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
149
148
  /** The file of the start screen in the generated source. */
150
149
  export const START_SCREEN_FILE = "start_screen.asm";
151
150
  /** The code of the start screen: the same for each program. loader.asm sets its values. */
@@ -234,27 +233,12 @@ const COPIER_PAGES = [
234
233
  ...Array.from({ length: 0x20 }, (_, index) => 0xe000 + index * 0x100),
235
234
  ];
236
235
 
237
- const overlaps = (a: AddressRange, b: AddressRange) => a.start <= b.end && b.start <= a.end;
238
- const show = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
239
-
240
- /** Parts of `range` that no range in `holes` covers. */
241
- export function subtract(range: AddressRange, holes: AddressRange[]): AddressRange[] {
242
- let pieces = [range];
243
- for (const hole of holes) {
244
- pieces = pieces.flatMap((piece) => {
245
- if (!overlaps(piece, hole)) return [piece];
246
- return [...(hole.start > piece.start ? [{ start: piece.start, end: hole.start - 1 }] : []), ...(hole.end < piece.end ? [{ start: hole.end + 1, end: piece.end }] : [])];
247
- });
248
- }
249
- return pieces;
250
- }
251
-
252
236
  /** Orders the copies so that no copy writes over the source of a later one; undefined when they form a cycle. */
253
237
  export function copyOrder(copies: Array<Omit<Copy, "backward">>): number[] | undefined {
254
238
  const order: number[] = [];
255
239
  const done = new Set<number>();
256
240
  while (order.length < copies.length) {
257
- const next = copies.findIndex((copy, index) => !done.has(index) && copies.every((other, at) => at === index || done.has(at) || !overlaps(copy.target, other.source)));
241
+ const next = copies.findIndex((copy, index) => !done.has(index) && copies.every((other, at) => at === index || done.has(at) || !rangesOverlap(copy.target, other.source)));
258
242
  if (next < 0) return undefined;
259
243
  order.push(next);
260
244
  done.add(next);
@@ -275,9 +259,6 @@ export function simulate(memory: Int16Array, copies: Copy[], expected: (address:
275
259
  return undefined;
276
260
  }
277
261
 
278
- /** True when a read of the address with $01 = $37, as RUN leaves it, gives a ROM byte. */
279
- const underRom = (address: number) => (address >= 0xa000 && address <= 0xbfff) || address >= 0xe000;
280
-
281
262
  /**
282
263
  * Why a loader stopped before its jump, from the RAM after the stop: the first
283
264
  * byte of the moved copier that is not the byte of the loader file, else, when
@@ -430,7 +411,7 @@ export function ciaSection(state: EntryState): { ops: Op[]; plan: CiaPlan } | un
430
411
  // The high byte loads the counter of a stopped timer too.
431
412
  loads.push(lda(latch & 0xff), sta(base + at), lda(latch >> 8), sta(base + at + 1));
432
413
  plan.counterAtJump = latch;
433
- limits.push(`${name} is stopped with the counter $${counter.toString(16).padStart(4, "0")} and the latch $${latch.toString(16).padStart(4, "0")}: a stopped CIA timer loads its latch, so the counter is the latch.`);
414
+ limits.push(`${name} is stopped with the counter ${formatC64Address(counter)} and the latch ${formatC64Address(latch)}: a stopped CIA timer loads its latch, so the counter is the latch.`);
434
415
  }
435
416
  const mask = chip.interruptMask;
436
417
  if (mask !== KERNAL_MASKS[index]) {
@@ -440,7 +421,7 @@ export function ciaSection(state: EntryState): { ops: Op[]; plan: CiaPlan } | un
440
421
  }
441
422
  if (touched) acks.push({ text: `lda ${formatC64Address(base + 0x0d)}`, bytes: 3, cycles: 4 });
442
423
  const flags = chip.registers[0x0d]! & 0x1f;
443
- if (flags !== 0) limits.push(`CIA ${id} has the interrupt flags $${flags.toString(16).padStart(2, "0")} at the entry: only an event sets a flag, so the loader cannot.`);
424
+ if (flags !== 0) limits.push(`CIA ${id} has the interrupt flags ${formatC64Byte(flags)} at the entry: only an event sets a flag, so the loader cannot.`);
444
425
  });
445
426
  if (loads.length === 0 && disable.length === 0) return { ops: [], plan: { timers, masks: [state.cia[0].interruptMask, state.cia[1].interruptMask], limits } };
446
427
  // The cycles from each start write to the entry: what follows it here, and the tail.
@@ -450,7 +431,7 @@ export function ciaSection(state: EntryState): { ops: Op[]; plan: CiaPlan } | un
450
431
  if (!item.system) return item.counter;
451
432
  const load = item.counter + followers + TAIL_CYCLES - CIA_START_DELAY;
452
433
  if (load <= 0xffff) return load;
453
- limits.push(`${item.name} counts from $${item.counter.toString(16).padStart(4, "0")} at the entry: the loader cannot start it so near $ffff without an underflow, so the counter differs.`);
434
+ limits.push(`${item.name} counts from ${formatC64Address(item.counter)} at the entry: the loader cannot start it so near $ffff without an underflow, so the counter differs.`);
454
435
  delete item.plan.counterAtJump;
455
436
  return item.counter;
456
437
  });
@@ -489,19 +470,19 @@ function checkStartScreen(input: LoaderInput): StartScreenPlan | undefined {
489
470
  }
490
471
  for (const { what, range } of startScreenRanges(row)) {
491
472
  const inside = input.segments.some((segment) => range.start >= segment.start && range.end <= segment.end);
492
- if (!inside) throw new WireFailure("invalid-input", `The start screen part ${what} (${show(range)}) is not in one segment of the program. The start screen must be in memory at the entry: capture it with the program, or correct the start screen in the knowledge.`);
473
+ if (!inside) throw new WireFailure("invalid-input", `The start screen part ${what} (${formatC64Range(range)}) is not in one segment of the program. The start screen must be in memory at the entry: capture it with the program, or correct the start screen in the knowledge.`);
493
474
  }
494
475
  return startScreenPlan(row);
495
476
  }
496
477
 
497
- /** The settings that loader.asm includes: switches.asm, else config.asm for a start screen, else none. */
498
- function settingsLines(input: LoaderInput): string[] {
478
+ /** The settings that loader.asm and the show stage include: switches.asm, else config.asm for a start screen, else none. */
479
+ export function settingsLines(input: Pick<LoaderInput, "switches" | "config">): string[] {
499
480
  if (input.switches === true) return ['!source "switches.asm"'];
500
481
  return input.config === true ? ['!source "config.asm"'] : [];
501
482
  }
502
483
 
503
484
  /** The label of a block: its first byte and the byte after it in the loader file, and its first address where it runs. */
504
- const blockLabel = (start: number, part: "from" | "end" | "to") => `loader_${part}_${start.toString(16).padStart(4, "0")}`;
485
+ const blockLabel = (start: number, part: "from" | "end" | "to") => `loader_${part}_${hexWord(start)}`;
505
486
  const plus = (label: string, offset: number) => (offset === 0 ? label : `${label}+${offset}`);
506
487
 
507
488
  /** A block of the loader: a segment with its files, or bytes of pages 0-3. */
@@ -529,7 +510,7 @@ function byteLines(range: AddressRange, bytes: (address: number) => number): str
529
510
  */
530
511
  export function planLoader(input: LoaderInput): LoaderPlan {
531
512
  const { colourRam } = input.state;
532
- if (colourRam === undefined) return { ...planForm(input, undefined)!, colourLimit: "The entry state has no colour RAM, so the loader does not set it. Capture the program again at its entry point to get it." };
513
+ if (colourRam === undefined) return { ...planForm(input, undefined)!, colourLimit: "The entry state has no colour RAM, so the loader does not set it. The colour RAM of a capture of a crack is the state of the crack." };
533
514
  // The colours take 1000 bytes of free RAM and make the loader larger: a plan that has no room for them is made without them.
534
515
  try {
535
516
  const plan = planForm(input, colourRam);
@@ -539,7 +520,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
539
520
  }
540
521
  return {
541
522
  ...planForm(input, undefined)!,
542
- colourLimit: `The loader has no room for the ${COLOURS} colours of the colour RAM in ${COLOUR_AREAS.map(show).join(" or ")} outside the segments, the loader and its copier, so it does not set the colour RAM. The program starts with the colours that the loader leaves there.`,
523
+ colourLimit: `The loader has no room for the ${COLOURS} colours of the colour RAM in ${COLOUR_AREAS.map(formatC64Range).join(" or ")} outside the segments, the loader and its copier, so it does not set the colour RAM. The program starts with the colours that the loader leaves there.`,
543
524
  };
544
525
  }
545
526
 
@@ -551,9 +532,9 @@ function planForm(input: LoaderInput, colours: Uint8Array | undefined): LoaderPl
551
532
  const copierPages = copierBytes >> 8;
552
533
  // What the copies write: each segment without $00/$01, which the loader sets last, and pages $0002-$03ff where no segment is.
553
534
  const blocks: Block[] = [];
554
- for (const segment of input.segments) blocks.push({ what: `segment ${show(segment)}`, range: segment, files: segment.files, pseudo: segment.start, bytes: input.byteAt });
535
+ for (const segment of input.segments) blocks.push({ what: `segment ${formatC64Range(segment)}`, range: segment, files: segment.files, pseudo: segment.start, bytes: input.byteAt });
555
536
  for (const part of subtract({ start: 0x0002, end: 0x03ff }, input.segments)) {
556
- blocks.push({ what: `entry state ${show(part)}`, range: part, pseudo: part.start, bytes: (address) => state.pages[address]! });
537
+ blocks.push({ what: `entry state ${formatC64Range(part)}`, range: part, pseudo: part.start, bytes: (address) => state.pages[address]! });
557
538
  }
558
539
  blocks.sort((a, b) => a.range.start - b.range.start);
559
540
 
@@ -590,19 +571,19 @@ function planForm(input: LoaderInput, colours: Uint8Array | undefined): LoaderPl
590
571
 
591
572
  const order = copyOrder(plain);
592
573
  if (order === undefined) {
593
- const clashing = plain.filter((copy) => plain.some((other) => other !== copy && overlaps(copy.target, other.source))).map((copy) => `${copy.what} (packed at ${show(copy.source)})`);
574
+ const clashing = plain.filter((copy) => plain.some((other) => other !== copy && rangesOverlap(copy.target, other.source))).map((copy) => `${copy.what} (packed at ${formatC64Range(copy.source)})`);
594
575
  throw new WireFailure("invalid-input", `No copy order exists: each of these copies writes over the packed bytes of another one: ${clashing.join(", ")}. Give this reason to the user.`);
595
576
  }
596
577
  const loaded = { start: LOAD, end };
597
578
  const areas = copierAreas(state.port);
598
579
  const copier = COPIER_PAGES.find((page) => {
599
580
  const pages = { start: page, end: page + copierBytes - 1 };
600
- return areas.some((area) => pages.start >= area.start && pages.end <= area.end) && !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
581
+ return areas.some((area) => pages.start >= area.start && pages.end <= area.end) && !rangesOverlap(pages, loaded) && plain.every((copy) => !rangesOverlap(pages, copy.target));
601
582
  });
602
583
  if (copier === undefined) {
603
584
  if (colours !== undefined) return undefined;
604
585
  const count = copierPages === 2 ? "two" : "three";
605
- 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(", ")}.`);
586
+ throw new WireFailure("invalid-input", `No ${count} free pages exist for the copier in ${areas.map(formatC64Range).join(" or ")} outside the loader (${formatC64Range(loaded)}) and the targets: ${plain.map((copy) => formatC64Range(copy.target)).join(", ")}.`);
606
587
  }
607
588
  let colourRange: AddressRange | undefined;
608
589
  if (colours !== undefined) {
@@ -618,7 +599,7 @@ function planForm(input: LoaderInput, colours: Uint8Array | undefined): LoaderPl
618
599
  }
619
600
  const copies: Copy[] = order.map((index) => {
620
601
  const copy = plain[index]!;
621
- return { ...copy, backward: copy.target.start > copy.source.start && overlaps(copy.target, copy.source) };
602
+ return { ...copy, backward: copy.target.start > copy.source.start && rangesOverlap(copy.target, copy.source) };
622
603
  });
623
604
  const copyBlocks = order.map((index) => blockOf[index]!);
624
605
 
@@ -717,9 +698,15 @@ export function copierAreas(port: readonly [number, number]): AddressRange[] {
717
698
  if (rom.basic) return [{ start: 0x0400, end: 0x9fff }, { start: 0xc000, end: 0xcfff }];
718
699
  return [{ start: 0x0400, end: 0xcfff }, ...(rom.kernal ? [] : [{ start: 0xe000, end: BELOW_VECTORS }])];
719
700
  }
720
- /** The free ranges that a refusal of the packed form names. */
701
+ /** The free ranges that a refusal names. */
721
702
  const SHOWN_FREE = 8;
722
703
 
704
+ /** The largest free ranges with their sizes, for a refusal: at most SHOWN_FREE of them, or none. */
705
+ export function largestFree(ranges: readonly AddressRange[]): string {
706
+ const shown = [...ranges].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
707
+ return shown.length === 0 ? "none" : shown.map((range) => `${formatC64Range(range)} (${range.end - range.start + 1} bytes)`).join(", ");
708
+ }
709
+
723
710
  /**
724
711
  * The packed form of the loader, for an image too large for one loader file:
725
712
  * Exomizer packs the build of main.asm (from $0400) and the build of
@@ -741,7 +728,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
741
728
  const range = { start: Math.max(block.range.start, 0x0002), end: Math.min(block.range.end, 0x03ff) };
742
729
  if (range.start > range.end) return [];
743
730
  const cut = range.start !== block.range.start || range.end !== block.range.end;
744
- return [{ what: cut ? `${block.what}, part ${show(range)}` : block.what, range, bytes: block.bytes }];
731
+ return [{ what: cut ? `${block.what}, part ${formatC64Range(range)}` : block.what, range, bytes: block.bytes }];
745
732
  });
746
733
  const lowBytes = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
747
734
  const areas = copierAreas(state.port);
@@ -749,15 +736,11 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
749
736
  const copierFree = areas.flatMap((area) => subtract(area, input.segments));
750
737
  const placed = placePacked(copierFree, free, low, codeSize);
751
738
  if ("refusal" in placed) {
752
- const largest = (ranges: AddressRange[]) => {
753
- const shown = [...ranges].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
754
- return shown.length === 0 ? "none" : shown.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
755
- };
756
- 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)}.`;
739
+ const ranges = placed.refusal === "copies" ? `The largest free ranges for pages 0-3: ${largestFree(free)}.` : `The largest free ranges for the copier: ${largestFree(copierFree)}. The largest free ranges for pages 0-3: ${largestFree(free)}.`;
757
740
  const why =
758
741
  placed.refusal === "copies"
759
- ? `A packed loader needs more than ${MAX_PACKED_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
760
- : `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.`}`;
742
+ ? `A packed loader needs more than ${TABLE_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
743
+ : `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(formatC64Range).join(" or ")}, and ${lowBytes} more free bytes for pages 0-3 in ${formatC64Range(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.`}`;
761
744
  throw new WireFailure("invalid-input", `${tooLarge} ${why} ${ranges} Give this reason to the user.`);
762
745
  }
763
746
  const { copier, pieces } = placed;
@@ -808,7 +791,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
808
791
  const within = { start: Math.max(segment.start, start), end: Math.min(segment.end, end) };
809
792
  if (within.start > within.end) continue;
810
793
  for (const range of subtract(within, used)) {
811
- parts.push({ range, text: [`; The bytes of the image at ${show(range)}, so the build of this file does not change them`, `* = ${formatC64Address(range.start)}`, ...byteLines(range, input.byteAt)] });
794
+ parts.push({ range, text: [`; The bytes of the image at ${formatC64Range(range)}, so the build of this file does not change them`, `* = ${formatC64Address(range.start)}`, ...byteLines(range, input.byteAt)] });
812
795
  }
813
796
  }
814
797
  parts.sort((a, b) => a.range.start - b.range.start);
@@ -828,9 +811,6 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
828
811
  };
829
812
  }
830
813
 
831
- /** The copy table of the packed form: X indexes it, so it fits in 256 bytes. */
832
- const MAX_PACKED_COPIES = Math.floor((256 - 2) / COPY_ENTRY);
833
-
834
814
  /** A piece of pages 0-3 in the packed form: its target and where the copier reads it. */
835
815
  export interface Piece {
836
816
  what: string;
@@ -863,7 +843,7 @@ export function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: s
863
843
  const count = Math.min(block.range.end - next + 1, length(target));
864
844
  const part = { start: next, end: next + count - 1 };
865
845
  const cut = part.start !== block.range.start || part.end !== block.range.end;
866
- pieces.push({ what: cut ? `${block.what}, bytes ${show(part)}` : block.what, target: part, at: target.start, bytes: block.bytes });
846
+ pieces.push({ what: cut ? `${block.what}, bytes ${formatC64Range(part)}` : block.what, target: part, at: target.start, bytes: block.bytes });
867
847
  target.start += count;
868
848
  next += count;
869
849
  rest -= count;
@@ -881,7 +861,7 @@ export function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: s
881
861
  function placePacked(copierFree: AddressRange[], free: AddressRange[], low: Parameters<typeof placePieces>[1], codeSize: number): { copier: number; pieces: Piece[] } | { refusal: "room" | "copies" } {
882
862
  const candidates = [...COPIER_PAGES, ...copierFree.map((range) => range.start)];
883
863
  // 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.
884
- for (let copies = Math.max(low.length, 1); copies <= MAX_PACKED_COPIES; ) {
864
+ for (let copies = Math.max(low.length, 1); copies <= TABLE_COPIES; ) {
885
865
  const size = codeSize + COPY_ENTRY * copies + 2;
886
866
  let best: { copier: number; pieces: Piece[]; span: number } | undefined;
887
867
  for (const copier of candidates) {
@@ -14,11 +14,11 @@
14
14
  // each release has it, the default build does not, and the loader never
15
15
  // loads it.
16
16
 
17
- import { CONFIG_FILE, configValues } from "#src/build-name.ts";
18
- import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
17
+ import { CONFIG_FILE } from "#src/build-name.ts";
18
+ import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, formatC64Range, hexByte, hexWord, inRanges, POINTER_TABLE_TYPES, pointerEntryText, pointerTableEntries, type PointerTableType, splitEntryByte } from "#src/c64.ts";
19
19
  import { WireFailure } from "#src/host-client/tools.ts";
20
20
  import { identifiers, operandText, replaceIdentifiers, type OperandExpression } from "#src/knowledge/expression.ts";
21
- import { type CommentPlacement, isAnalyzer, isGeneratedFile, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, SEGMENT_FOLDER, RELEASE_DEFINE, START_SCREEN_SWITCH, type Origin, type RegionType, type SwitchKind } from "#src/knowledge/schema.ts";
21
+ import { type CommentPlacement, INSTRUCTION_REGION_TYPES, isAnalyzer, isGeneratedFile, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, SEGMENT_FOLDER, RELEASE_DEFINE, START_SCREEN_SWITCH, type Origin, type RegionType, type SwitchKind } from "#src/knowledge/schema.ts";
22
22
  import type { Area } from "#src/platform.ts";
23
23
  import { hasZeroPageForm, instructionWith, labelProblem, MODE_LENGTH, OPCODES, takesAddress, USE_KINDS, useKind, type UseKind } from "#src/opcodes.ts";
24
24
 
@@ -136,7 +136,6 @@ export interface OperandAsNumber {
136
136
  reason: string;
137
137
  }
138
138
 
139
- const CODE_TYPES: readonly RegionType[] = ["code", "jumps", "dual-use"];
140
139
  const BYTES_PER_LINE = 8;
141
140
  const WORDS_PER_LINE = 4;
142
141
  const CHARS_PER_LINE = 32;
@@ -285,24 +284,39 @@ function operandValue(address: number, opcode: number, byteAt: (address: number)
285
284
  */
286
285
  export function entriesInData<R extends { start: number; end: number; type: RegionType }>(entries: readonly number[], regions: readonly R[]): Array<{ entry: number; region: R }> {
287
286
  return entries.flatMap((entry) => {
288
- const region = regions.find((row) => entry >= row.start && entry <= row.end && !CODE_TYPES.includes(row.type));
287
+ const region = regions.find((row) => entry >= row.start && entry <= row.end && !INSTRUCTION_REGION_TYPES.includes(row.type));
289
288
  return region === undefined ? [] : [{ entry, region }];
290
289
  });
291
290
  }
292
291
 
293
292
  /** Why an image without its entry fails: the image does not hold the program. Undefined when the entry is in a segment, or the image has no entry. */
294
293
  export function entryOutsideImage(entry: number | undefined, segments: readonly AddressRange[]): string | undefined {
295
- if (entry === undefined || segments.some((segment) => entry >= segment.start && entry <= segment.end)) return undefined;
294
+ if (entry === undefined || inRanges(segments, entry)) return undefined;
296
295
  return `The entry ${formatC64Address(entry)} is in no segment of the image: the image does not hold the program. Capture the program again, so that a segment holds the entry.`;
297
296
  }
298
297
 
298
+ /**
299
+ * regions.find for each address as one index: the first region whose span
300
+ * holds the address. It is filled from the last region to the first, so the
301
+ * first one wins. `span` gives the part of a region that counts, or undefined
302
+ * to leave the region out.
303
+ */
304
+ function regionFinder<R extends AddressRange>(regions: readonly R[], span: (region: R) => AddressRange | undefined = (region) => region): (address: number) => R | undefined {
305
+ const first = new Int32Array(0x10000).fill(-1);
306
+ for (let index = regions.length - 1; index >= 0; index--) {
307
+ const part = span(regions[index]!);
308
+ if (part !== undefined) first.fill(index, part.start, part.end + 1);
309
+ }
310
+ return (address) => regions[first[address] ?? -1];
311
+ }
312
+
299
313
  /** Splits the segments into pieces at module starts and lays out instructions and data. */
300
314
  export function layout(input: SourceInput): Layout {
301
- const inImage = (address: number) => input.segments.some((segment) => address >= segment.start && address <= segment.end);
302
- const regionAt = (address: number) => input.regions.find((region) => address >= region.start && address <= region.end);
315
+ const inImage = (address: number) => inRanges(input.segments, address);
316
+ const regionAt = regionFinder(input.regions);
303
317
  const isData = (address: number) => {
304
318
  const region = regionAt(address);
305
- return region !== undefined && !CODE_TYPES.includes(region.type);
319
+ return region !== undefined && !INSTRUCTION_REGION_TYPES.includes(region.type);
306
320
  };
307
321
 
308
322
  for (const module of input.modules) {
@@ -318,7 +332,6 @@ export function layout(input: SourceInput): Layout {
318
332
  const cuts = new Set([...patches, ...macroUses, ...leftovers].flatMap((range) => [range.start, range.end + 1]));
319
333
 
320
334
  const pieces: Piece[] = [];
321
- const hex = (address: number) => address.toString(16).padStart(4, "0");
322
335
  for (const segment of input.segments) {
323
336
  const inside = (address: number) => address > segment.start && address <= segment.end;
324
337
  // A range of leftovers is one file: a module that starts in it goes on after it.
@@ -328,16 +341,16 @@ export function layout(input: SourceInput): Layout {
328
341
  for (let index = 0; index + 1 < bounds.length; index++) {
329
342
  const start = bounds[index]!;
330
343
  const end = bounds[index + 1]! - 1;
331
- const segmentTitle = `Segment ${formatC64Address(segment.start)}-${formatC64Address(segment.end)}`;
344
+ const segmentTitle = `Segment ${formatC64Range(segment)}`;
332
345
  if (leftovers.some((range) => range.start === start)) {
333
- pieces.push({ start, end, file: `${LEFTOVER_FOLDER}/leftover_${hex(start)}.asm`, title: `Leftovers ${formatC64Address(start)}-${formatC64Address(end)}: ${end - start + 1} bytes that nothing uses. Only LEFTOVERS = 1 builds them.`, segmentStart: index === 0, leftover: true, items: [] });
346
+ pieces.push({ start, end, file: `${LEFTOVER_FOLDER}/leftover_${hexWord(start)}.asm`, title: `Leftovers ${formatC64Range({ start, end })}: ${end - start + 1} bytes that nothing uses. Only LEFTOVERS = 1 builds them.`, segmentStart: index === 0, leftover: true, items: [] });
334
347
  continue;
335
348
  }
336
349
  // A module that leftovers cut goes on in a file of its own after them, in its folder: <module>_xxxx.asm.
337
350
  const module = modules.find((row) => row.start === start);
338
351
  const holder = module ?? modules.filter((row) => row.start >= segment.start && row.start < start).at(-1);
339
352
  const title = (text: string | undefined) => text?.replace(/\s*\r?\n\s*/g, " ");
340
- const file = module?.file ?? (holder === undefined ? `${SEGMENT_FOLDER}/segment_${hex(start)}.asm` : `${holder.file.replace(/\.asm$/i, "")}_${hex(start)}.asm`);
353
+ const file = module?.file ?? (holder === undefined ? `${SEGMENT_FOLDER}/segment_${hexWord(start)}.asm` : `${holder.file.replace(/\.asm$/i, "")}_${hexWord(start)}.asm`);
341
354
  const named = module === undefined && holder !== undefined ? `${title(holder.title) ?? holder.file}, from ${formatC64Address(start)}` : title(module?.title);
342
355
  pieces.push({ start, end, file, title: named ?? segmentTitle, segmentStart: index === 0, leftover: false, items: [] });
343
356
  }
@@ -354,7 +367,7 @@ export function layout(input: SourceInput): Layout {
354
367
  let address = piece.start;
355
368
  while (address <= piece.end) {
356
369
  const region = regionAt(address);
357
- const codeRegion = region !== undefined && CODE_TYPES.includes(region.type);
370
+ const codeRegion = region !== undefined && INSTRUCTION_REGION_TYPES.includes(region.type);
358
371
  const length = input.instructions.get(address);
359
372
  const opcode = input.byteAt(address);
360
373
  const fits =
@@ -414,10 +427,12 @@ export function layout(input: SourceInput): Layout {
414
427
  tally(address, kind);
415
428
  };
416
429
  const inIo = (address: number) => input.io !== undefined && address >= input.io.start && address <= input.io.end;
430
+ /** The data region that holds an address after its first byte. */
431
+ const tableRegion = regionFinder(input.regions, (row) => (INSTRUCTION_REGION_TYPES.includes(row.type) ? undefined : { start: row.start + 1, end: row.end }));
417
432
  /** The start of the named data region that holds an address without a name of its own: the operand is written name+offset. */
418
433
  const tableStart = (address: number) => {
419
434
  if (symbols.has(address)) return undefined;
420
- const region = input.regions.find((row) => address > row.start && address <= row.end && !CODE_TYPES.includes(row.type) && row.type !== "dual-use");
435
+ const region = tableRegion(address);
421
436
  return region !== undefined && symbols.has(region.start) ? region.start : undefined;
422
437
  };
423
438
  const use = (address: number, kind: UseKind) => {
@@ -588,7 +603,7 @@ export function layout(input: SourceInput): Layout {
588
603
  if (inImage(address)) namedLabels++;
589
604
  continue;
590
605
  }
591
- let name = `l_${address.toString(16).padStart(4, "0")}`;
606
+ let name = `l_${hexWord(address)}`;
592
607
  while (taken.has(name)) name = `${name}_`;
593
608
  taken.add(name);
594
609
  names.set(address, name);
@@ -608,7 +623,7 @@ export function layout(input: SourceInput): Layout {
608
623
  }
609
624
  const known = blocks.get(patch.start);
610
625
  if (known !== undefined) {
611
- if (known.end !== patch.end) refuse(`The range overlaps the patch of ${known.alternatives[0]!.switch} at ${formatC64Address(known.start)}-${formatC64Address(known.end)}: alternatives have the same range.`);
626
+ if (known.end !== patch.end) refuse(`The range overlaps the patch of ${known.alternatives[0]!.switch} at ${formatC64Range(known)}: alternatives have the same range.`);
612
627
  else known.alternatives.push({ switch: patch.switch, code: patch.code, ...(patch.comment === undefined ? {} : { comment: patch.comment }), base: owner.base });
613
628
  continue;
614
629
  }
@@ -691,18 +706,13 @@ export function layout(input: SourceInput): Layout {
691
706
  };
692
707
  }
693
708
 
694
- /** The pointer region types: a table of addresses, or of addresses minus 1 for RTS. */
695
- const POINTER_TYPES: ReadonlyArray<DataItem["type"]> = POINTER_TABLE_TYPES;
696
- const isPointerTable = (region: Region): region is Region & { type: PointerTableType } => (POINTER_TABLE_TYPES as readonly string[]).includes(region.type);
697
-
698
- /** The pairs of a pointer table: the address of each low and high byte, and the target it names. */
699
- function pairsOf(region: Region, byteAt: (address: number) => number): Array<{ low: number; high: number; target: number }> {
700
- return isPointerTable(region) ? pointerTableEntries(region, byteAt) : [];
701
- }
709
+ /** A data item of a pointer table: a table of addresses, or of addresses minus 1 for RTS. The type of a data item with a region is the type of the region. */
710
+ type PointerItem = DataItem & { region: Region & { type: PointerTableType } };
711
+ const isPointerTable = (item: DataItem): item is PointerItem => item.region !== undefined && (POINTER_TABLE_TYPES as readonly string[]).includes(item.type);
702
712
 
703
713
  function pointersOf(item: DataItem, byteAt: (address: number) => number): number[] {
704
- if (item.region === undefined || !POINTER_TYPES.includes(item.type)) return [];
705
- return pairsOf(item.region, byteAt)
714
+ if (!isPointerTable(item)) return [];
715
+ return pointerTableEntries(item.region, byteAt)
706
716
  .filter((pair) => (pair.low >= item.start && pair.low <= item.end) || (pair.high >= item.start && pair.high <= item.end))
707
717
  .map((pair) => pair.target);
708
718
  }
@@ -715,13 +725,13 @@ export interface InstructionForm {
715
725
  }
716
726
 
717
727
  /** The operand size suffix: +2 forces an absolute operand below $0100, +1 a zero-page operand that is a label of the image. */
718
- export function formOf(layout: Pick<Layout, "inImage" | "byteAt">, item: InstructionItem): InstructionForm {
728
+ function formOf(layout: Pick<Layout, "inImage" | "byteAt">, item: InstructionItem): InstructionForm {
719
729
  const { mnemonic, mode } = OPCODES[item.opcode]!;
720
730
  const value = takesAddress(mode) ? operandValue(item.address, item.opcode, layout.byteAt)! : 0;
721
731
  let suffix = "";
722
732
  if ((mode === "abs" || mode === "abx" || mode === "aby") && value < 0x100 && hasZeroPageForm(mnemonic, mode)) suffix = "+2";
723
733
  if ((mode === "zp" || mode === "zpx" || mode === "zpy") && layout.inImage(value)) suffix = "+1";
724
- return { key: `${item.opcode.toString(16).padStart(2, "0")}${suffix}`, opcode: item.opcode, suffix };
734
+ return { key: `${hexByte(item.opcode)}${suffix}`, opcode: item.opcode, suffix };
725
735
  }
726
736
 
727
737
  /** The plain number of an operand: what the probe assembles, and what a comment shows. */
@@ -779,14 +789,12 @@ function cellsOf(item: DataItem, layout: Layout, breaks: Set<number>): Cell[] {
779
789
  const { byteAt } = layout;
780
790
  const cells: Cell[] = [];
781
791
  const name = (address: number) => layout.names.get(address);
782
- const expression = (target: number) => name(target) ?? formatC64Address(target);
783
- const rtsExpression = (target: number) => (name(target) === undefined ? formatC64Address((target - 1) & 0xffff) : `${name(target)}-1`);
784
792
  const byteCell = (address: number, text = formatC64Byte(byteAt(address))): Cell => ({ address, length: 1, directive: "!byte", text });
785
793
 
786
- if (item.region !== undefined && POINTER_TYPES.includes(item.type)) {
794
+ if (isPointerTable(item)) {
787
795
  const rts = item.type === "rts-addresses" || item.type === "rts-addresses-split";
788
796
  const split = item.type === "addresses-split" || item.type === "rts-addresses-split";
789
- const pairs = pairsOf(item.region, byteAt);
797
+ const pairs = pointerTableEntries(item.region, byteAt);
790
798
  const partOf = new Map<number, { pair: (typeof pairs)[number]; high: boolean }>();
791
799
  for (const pair of pairs) {
792
800
  partOf.set(pair.low, { pair, high: false });
@@ -798,14 +806,14 @@ function cellsOf(item: DataItem, layout: Layout, breaks: Set<number>): Cell[] {
798
806
  cells.push(byteCell(address));
799
807
  continue;
800
808
  }
801
- const text = rts ? rtsExpression(part.pair.target) : expression(part.pair.target);
809
+ const text = pointerEntryText(part.pair.target, rts, name);
802
810
  const whole = !split && !part.high && address + 1 <= item.end && !breaks.has(address + 1);
803
811
  if (whole) {
804
812
  cells.push({ address, length: 2, directive: "!word", text });
805
813
  address++;
806
814
  continue;
807
815
  }
808
- cells.push(byteCell(address, `${part.high ? ">" : "<"}${/^[$A-Za-z_.0-9]+$/.test(text) ? text : `(${text})`}`));
816
+ cells.push(byteCell(address, splitEntryByte(text, part.high)));
809
817
  }
810
818
  return cells;
811
819
  }
@@ -937,8 +945,6 @@ export const hasSwitchFile = (layout: Pick<Layout, "switches" | "releases" | "le
937
945
  /** True when the source has config.asm: the knowledge has switches or a start screen, or the source has leftovers. */
938
946
  export const hasConfigFile = (layout: Pick<Layout, "switches" | "startScreen" | "leftovers">) => layout.switches.length > 0 || layout.startScreen || layout.leftovers.length > 0;
939
947
 
940
- export { CONFIG_FILE, configValues };
941
-
942
948
  /**
943
949
  * config.asm: the value of each switch as a plain assignment, grouped by
944
950
  * kind. Without a value, a switch has its default. A comment tells the
@@ -960,7 +966,7 @@ export function configText(layout: Pick<Layout, "switches" | "patches" | "startS
960
966
  if (rows.length === 0) continue;
961
967
  out.push("", `; ${group.title}`);
962
968
  for (const row of rows) {
963
- const ranges = (patches.get(row.name) ?? []).map((patch) => `${formatC64Address(patch.start)}-${formatC64Address(patch.end)}`);
969
+ const ranges = (patches.get(row.name) ?? []).map((patch) => `${formatC64Range(patch)}`);
964
970
  const parts = [
965
971
  row.releases.length === 0 ? "on in no release" : `on in ${row.releases.join(", ")}`,
966
972
  ranges.length === 0 ? "no patch" : ranges.join(", "),
@@ -1034,7 +1040,7 @@ function constantsText(layout: Layout): { text: string; labels: SourceLabel[] }
1034
1040
  const next = describe?.(row.address).area;
1035
1041
  if (next !== undefined && next.start !== area?.start) {
1036
1042
  area = next;
1037
- out.push("", `; ${area.name[0]!.toUpperCase()}${area.name.slice(1)} ${formatC64Address(area.start)}-${formatC64Address(area.end)}`);
1043
+ out.push("", `; ${area.name[0]!.toUpperCase()}${area.name.slice(1)} ${formatC64Range(area)}`);
1038
1044
  if (area.meaning !== undefined) out.push(`; ${area.meaning}`);
1039
1045
  }
1040
1046
  const line = `${row.name.padEnd(nameColumn)} = ${row.value.padEnd(valueColumn)}`;
@@ -1124,8 +1130,8 @@ const patchCondition = (alternative: PatchAlternative) => (alternative.base ===
1124
1130
  */
1125
1131
  function patchOpening(patch: PatchBlock): string[] {
1126
1132
  const bytes = patch.end - patch.start + 1;
1127
- const range = `${formatC64Address(patch.start)}-${formatC64Address(patch.end)}`;
1128
- const out = [`!zone patch_${patch.alternatives[0]!.switch}_${patch.start.toString(16).padStart(4, "0")} {`, ".patch_start"];
1133
+ const range = `${formatC64Range(patch)}`;
1134
+ const out = [`!zone patch_${patch.alternatives[0]!.switch}_${hexWord(patch.start)} {`, ".patch_start"];
1129
1135
  patch.alternatives.forEach((first, index) => {
1130
1136
  for (const second of patch.alternatives.slice(index + 1)) {
1131
1137
  out.push(`!if ${patchCondition(first)} { !if ${patchCondition(second)} { !error "${first.switch} and ${second.switch} change ${range}: turn on one of them." } }`);
@@ -1195,7 +1201,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1195
1201
  const notExecuted = { instructions: 0, ranges: [] as AddressRange[] };
1196
1202
 
1197
1203
  for (const piece of layout.pieces) {
1198
- const out: string[] = [`; ${piece.title}`, `; ${formatC64Address(piece.start)}-${formatC64Address(piece.end)}`, ""];
1204
+ const out: string[] = [`; ${piece.title}`, `; ${formatC64Range(piece)}`, ""];
1199
1205
  /** True while the instructions before have not executed: they form one range. */
1200
1206
  let running = false;
1201
1207
  /** The line of the mark of the open range of instructions that did not execute. */
@@ -1216,7 +1222,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1216
1222
  }
1217
1223
  // The mark gives the range, so a reader finds it in the full list.
1218
1224
  const range = notExecuted.ranges.at(-1)!;
1219
- out[markLine] = `; not executed ${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
1225
+ out[markLine] = `; not executed ${formatC64Range(range)}`;
1220
1226
  notExecuted.instructions += count;
1221
1227
  }
1222
1228
  running = !executed;
@@ -1257,8 +1263,10 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1257
1263
  const macroUse = item.kind === "instruction" && !asInstructions.has(item.address) ? layout.macroUses.get(item.address) : undefined;
1258
1264
  if (macroUse !== undefined) {
1259
1265
  head(macroUse.start);
1260
- const count = piece.items.filter((other) => other.kind === "instruction" && other.address >= macroUse.start && other.address <= macroUse.end).length;
1261
- mark(macroUse.start, macroUse.end, count);
1266
+ // Each instruction of the use has its own coverage: a run can execute the first and not the next.
1267
+ for (const inner of piece.items) {
1268
+ if (inner.kind === "instruction" && inner.address >= macroUse.start && inner.address <= macroUse.end) mark(inner.address, inner.address + inner.length - 1, 1);
1269
+ }
1262
1270
  // The comments inside the use go to its side comment, as for the bytes of an instruction.
1263
1271
  const sides: string[] = [];
1264
1272
  for (let address = macroUse.start; address <= macroUse.end; address++) {
@@ -8,10 +8,10 @@
8
8
  // key or a fire button, stops the interrupts of the stage, sets the CIAs as
9
9
  // RUN leaves them, copies the stash back and starts the loader.
10
10
 
11
- import { type AddressRange, formatC64Address, formatC64Byte } from "#src/c64.ts";
11
+ import { type AddressRange, formatC64Address, formatC64Byte, formatC64Range, hexWord, mergeRanges, rangesOverlap, subtract } from "#src/c64.ts";
12
12
  import { WireFailure } from "#src/host-client/tools.ts";
13
13
  import type { StartScreenRow } from "#src/knowledge/read.ts";
14
- import { placePieces, START_SCREEN_FILE, startScreenValues, subtract, type StartScreenPlan } from "./loader.ts";
14
+ import { largestFree, placePieces, START_SCREEN_FILE, startScreenValues, type StartScreenPlan } from "./loader.ts";
15
15
 
16
16
  /** Bytes at an address. */
17
17
  export interface StagePart {
@@ -55,7 +55,7 @@ export const STAGE_CODE_END = "c64_source_stage_code_end";
55
55
  /** The label of the colour RAM of the capture in the show code. */
56
56
  export const STAGE_COLOURS = "c64_source_stage_colours";
57
57
  /** The label of a part of the stage: its first byte and the byte after it. */
58
- export const stageLabel = (start: number, part: "from" | "end") => `stage_${part}_${start.toString(16).padStart(4, "0")}`;
58
+ const stageLabel = (start: number, part: "from" | "end") => `stage_${part}_${hexWord(start)}`;
59
59
 
60
60
  /** One copy of the stash: the length, where it is read and where it is written. */
61
61
  const COPY_ENTRY = 6;
@@ -68,23 +68,9 @@ const CODE_AREAS: readonly AddressRange[] = [
68
68
  ];
69
69
  /** The RAM that the stash can use: the copy runs with all RAM in, and not on the hardware vectors. */
70
70
  const STASH_AREA: AddressRange = { start: 0x0400, end: 0xfff9 };
71
- /** The free ranges that a refusal names. */
72
- const SHOWN_FREE = 8;
73
71
 
74
- const show = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
75
72
  const rangeOf = (part: StagePart): AddressRange => ({ start: part.start, end: part.start + part.body.length - 1 });
76
73
 
77
- /** The ranges in address order, with each run of touching or overlapping ranges as one. */
78
- function merged(ranges: readonly AddressRange[]): AddressRange[] {
79
- const out: AddressRange[] = [];
80
- for (const range of [...ranges].sort((a, b) => a.start - b.start)) {
81
- const last = out.at(-1);
82
- if (last !== undefined && range.start <= last.end + 1) last.end = Math.max(last.end, range.end);
83
- else out.push({ ...range });
84
- }
85
- return out;
86
- }
87
-
88
74
  /** The byte of the parts at an address; the last part that holds it wins. */
89
75
  function byteOf(parts: readonly StagePart[], address: number): number {
90
76
  for (let index = parts.length - 1; index >= 0; index--) {
@@ -100,14 +86,12 @@ function byteOf(parts: readonly StagePart[], address: number): number {
100
86
  * ranges. Refuses by name when the memory is too small.
101
87
  */
102
88
  export function planStage(input: StageInput): StagePlan {
103
- const used = merged([...input.inner.map(rangeOf), ...input.stage.map(rangeOf)]);
89
+ const used = mergeRanges([...input.inner.map(rangeOf), ...input.stage.map(rangeOf)]);
104
90
  const free = subtract(STASH_AREA, used);
105
- const covered = merged(input.inner.map(rangeOf)).flatMap((inner) => input.stage.map(rangeOf).flatMap((part) => (part.start <= inner.end && inner.start <= part.end ? [{ start: Math.max(part.start, inner.start), end: Math.min(part.end, inner.end) }] : [])));
106
- const stashed = merged(covered).map((range) => ({ what: `the loader at ${show(range)}`, range, bytes: (address: number) => byteOf(input.inner, address) }));
91
+ const covered = mergeRanges(input.inner.map(rangeOf)).flatMap((inner) => input.stage.map(rangeOf).flatMap((part) => (rangesOverlap(part, inner) ? [{ start: Math.max(part.start, inner.start), end: Math.min(part.end, inner.end) }] : [])));
92
+ const stashed = mergeRanges(covered).map((range) => ({ what: `the loader at ${formatC64Range(range)}`, range, bytes: (address: number) => byteOf(input.inner, address) }));
107
93
  const refuse = (why: string): never => {
108
- const largest = [...free].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
109
- const ranges = largest.length === 0 ? "none" : largest.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
110
- throw new WireFailure("invalid-input", `${why} The largest free ranges outside the loader and the bytes of the stage: ${ranges}. Capture the stage with less memory, so that its program holds only the start screen and the routine of the call.`);
94
+ throw new WireFailure("invalid-input", `${why} The largest free ranges outside the loader and the bytes of the stage: ${largestFree(free)}. Capture the stage with less memory, so that its program holds only the start screen and the routine of the call.`);
111
95
  };
112
96
  for (let copies = Math.max(stashed.length, 1); copies <= MAX_COPIES; ) {
113
97
  const size = input.codeSize + COPY_ENTRY * copies + 2;
@@ -245,7 +229,7 @@ export function stageText(input: StageInput, code: number, stash: StagePlan["sta
245
229
  ` jmp ${formatC64Address(input.innerStart)}`,
246
230
  ".count !word 0",
247
231
  ".table",
248
- ...stash.map((item) => ` !word ${item.target.end - item.target.start + 1}, ${formatC64Address(item.at)}, ${formatC64Address(item.target.start)} ; ${show(item.target)} of the loader`),
232
+ ...stash.map((item) => ` !word ${item.target.end - item.target.start + 1}, ${formatC64Address(item.at)}, ${formatC64Address(item.target.start)} ; ${formatC64Range(item.target)} of the loader`),
249
233
  " !word 0",
250
234
  "}",
251
235
  ...(input.colourRam === undefined ? [] : [`; The colour RAM of the capture of ${row.stage}.`, STAGE_COLOURS, ...byteLines({ start: 0, body: input.colourRam })]),
@@ -253,7 +237,7 @@ export function stageText(input: StageInput, code: number, stash: StagePlan["sta
253
237
  ];
254
238
  // Each part at its own address: the code is in a free range, so no part overlaps it, and the build never runs past $ffff.
255
239
  for (const part of input.stage) {
256
- lines.push("", `; ${row.stage} ${show(rangeOf(part))}`, `* = ${formatC64Address(part.start)}`, stageLabel(part.start, "from"), ...byteLines(part), stageLabel(part.start, "end"));
240
+ lines.push("", `; ${row.stage} ${formatC64Range(rangeOf(part))}`, `* = ${formatC64Address(part.start)}`, stageLabel(part.start, "from"), ...byteLines(part), stageLabel(part.start, "end"));
257
241
  }
258
242
  return `${lines.join("\n")}\n`;
259
243
  }