@henols/c64-re-tools 2.8.0-rc.2 → 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 (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  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 +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  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 +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +10 -5
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +9 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
  47. package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +28 -68
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
@@ -12,28 +12,31 @@
12
12
  import { createHash } from "node:crypto";
13
13
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
14
14
  import { basename, dirname, join, relative, sep } from "node:path";
15
+ import type { DatabaseSync } from "node:sqlite";
15
16
 
16
17
  import { isRefusal, Refusal } from "#src/errors.ts";
17
18
  import { PACKAGE } from "#src/package.ts";
18
- import { BUILD_DIRECTORY, buildName, symbolsPath } from "#src/build-name.ts";
19
- import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
19
+ import { BUILD_DIRECTORY, buildName, CONFIG_FILE, configValues, symbolsPath } from "#src/build-name.ts";
20
+ import { type AddressRange, formatC64Address, formatC64Byte, formatC64Range, formatC64RangeFields, hexWord, inRanges, mergeRanges, rangesOverlap, subtract, textToPetscii } from "#src/c64.ts";
20
21
  import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
21
22
  import { IO_RAM } from "#src/host-client/coverage.ts";
22
- import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
23
+ import { WireFailure } from "#src/host-client/tools.ts";
23
24
  import { writeReported, type Written } from "#src/host-client/transfer.ts";
24
- import { ViceSessionClient } from "#src/host-client/vice-session.ts";
25
+ import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
25
26
  import { conflicts } from "#src/knowledge/conflicts.ts";
26
- import { openForRead, withWrite } from "#src/knowledge/database.ts";
27
+ import { withRead, withWrite } from "#src/knowledge/database.ts";
27
28
  import { identifiers } from "#src/knowledge/expression.ts";
28
- import { analyzedBytes, memoryRows, programCoverage, releaseImage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
29
- import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, sourceRevision, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
30
- import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
31
- import { subtract, write } from "#src/knowledge/write.ts";
29
+ import { clipped, codeKnowledge, effectiveRegions } from "#src/knowledge/code-reach.ts";
30
+ import { memoryRows, releaseImage, type ProgramImage } from "#src/knowledge/program.ts";
31
+ import { ANALYZER_NAME_ORDER, baseValue, currentRevision, sourceRevision, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listReleases, listSpaces, listSwitches, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
32
+ import { DEFAULT_SPACE, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
33
+ import { write } from "#src/knowledge/write.ts";
32
34
  import { assemble, symbolsFileText } from "#src/native/acme.ts";
33
- import { analyze } from "#src/native/decompiler/analyze.ts";
35
+ import { PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
36
+ import { decodeProgram, leftoverInput, reachInput } from "#src/program-code.ts";
34
37
  import { localToolContext } from "#src/native/local.ts";
35
- import { DECOMPILER_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
36
- import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romRanges, romUseOfProgram } from "#src/platform.ts";
38
+ import type { AssembledSymbol, Diagnostic } from "#src/native/types.ts";
39
+ import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romUseOfProgram } from "#src/platform.ts";
37
40
  import { ensureLocal, generatedDirectory, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
38
41
  import { generatedReferences } from "#src/reference-pages.ts";
39
42
  import { isoCet } from "#src/time.ts";
@@ -42,17 +45,15 @@ import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply }
42
45
  import { knowledgeNames } from "#src/knowledge/names.ts";
43
46
  import { COPIER_SOURCE, leftoverRange, loaderSymbols, packLoader, packParts, type PackedLoader } from "#src/loader.ts";
44
47
  import {
45
- LOADER_JUMP,
46
48
  loaderLimits,
47
49
  planLoader,
48
50
  startScreenPlan,
49
51
  rasterLine,
50
52
  loaderState,
53
+ settingsLines,
51
54
  simulate,
52
55
  START_SCREEN_CODE,
53
- START_SCREEN_CONTINUE,
54
56
  START_SCREEN_FILE,
55
- START_SCREEN_WAIT,
56
57
  stopCause,
57
58
  VIC_DISPLAY_REGISTERS,
58
59
  type EntryState,
@@ -60,11 +61,11 @@ import {
60
61
  type StartScreenPlan,
61
62
  } from "./lib/loader.ts";
62
63
  import { instructionWith, OPCODES } from "#src/opcodes.ts";
63
- import { capturedColourRam } from "#src/knowledge/start-screen.ts";
64
+ import { capturedColourRam, LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
64
65
  import { planStage, STAGE_CODE_END, STAGE_FILE, STAGE_START, stageParts, stageText, type StageInput, type StagePart, type StagePlan } from "./lib/stage.ts";
65
66
  import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
66
67
  import type { UnresolvedFlow } from "#src/knowledge/separate.ts";
67
- import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, stagePatchText, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
68
+ import { configText, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, stagePatchText, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
68
69
 
69
70
  /** At most this many diagnostics or differences of one check. */
70
71
  const MAX_DIAGNOSTICS = 20;
@@ -77,52 +78,38 @@ const DATA_ONLY = "The knowledge has no entry, routine, code region or executed
77
78
 
78
79
  /** The copies of a full 64 KiB take about 140 frames. */
79
80
  const LOADER_FRAMES = 1500;
80
- /** CPU cycles of one PAL frame: 312 lines of 63 cycles. */
81
- const PAL_FRAME_CYCLES = 312 * 63;
82
81
 
83
82
  /** The knowledge of one space that the source uses, read once. With `analyzerNames`, an address without a name takes its first analyzer name. */
84
83
  function readKnowledge(space: Space, analyzerNames = false) {
85
- const db = openForRead();
86
- try {
87
- // With conflicts from a git merge, the source would depend on which of two rows comes first.
88
- const found = conflicts(db).length;
89
- if (found > 0) throw new Refusal("conflict", `The knowledge has ${found} conflict${found === 1 ? "" : "s"} from a git merge. Merge the open changes of the project knowledge. Then run the command again.`);
90
- const symbols = listSymbols(db, undefined, undefined, undefined, space);
91
- const second = listAnalyzerNames(db, undefined, undefined, undefined, space);
92
- const releases = listReleases(db, undefined, space);
93
- const base = releases.find((release) => release.base)?.label;
94
- const startScreen = space === DEFAULT_SPACE ? currentStartScreen(db, space) : undefined;
95
- return {
96
- revision: currentRevision(db),
97
- // The source and its loader hold the program of this space and the stage of its start screen: a change elsewhere does not change them.
98
- sourceRevision: sourceRevision(db, space),
99
- program: requireProgram(db, space),
100
- // The coverage of the space: a run of the C64, or of a captured stage that coverage put into that space.
101
- coverage: programCoverage(db, space)?.map,
102
- symbols: analyzerNames ? withAnalyzerNames(symbols, second) : symbols,
103
- // Analyzer routines are entry points for the decode, also without --analyzer-names.
104
- routines: [...symbols, ...second].filter((symbol) => symbol.kind === "routine").map((symbol) => symbol.address),
105
- regions: listRegions(db, undefined, undefined, undefined, space),
106
- comments: listComments(db, undefined, undefined, space),
107
- modules: listModules(db, undefined, undefined, space),
108
- references: listReferences(db, undefined, undefined, undefined, space),
109
- operands: listOperands(db, undefined, undefined, space),
110
- patches: listPatches(db, undefined, undefined, undefined, space),
111
- switches: listSwitches(db, undefined, space).map((row): SourceSwitch => ({ name: row.name, kind: row.kind, default: row.default, base: baseValue(row, base), releases: row.releases, ...(row.comment === undefined ? {} : { comment: row.comment }) })),
112
- // Each release with its bytes: the check builds it and compares the build with them.
113
- releases: releases.map((release) => ({ ...release, image: releaseImage(db, release.label, space)! })),
114
- macros: listMacros(db, undefined, space),
115
- macroUses: listMacroUses(db, undefined, undefined, undefined, space),
116
- // The start screen is of the C64 program: the loader shows it.
117
- startScreen,
118
- };
119
- } finally {
120
- db?.close();
121
- }
84
+ return withRead((db) => knowledgeOf(db, space, analyzerNames));
85
+ }
86
+
87
+ /** readKnowledge on a knowledge that is open already. */
88
+ function knowledgeOf(db: DatabaseSync | undefined, space: Space, analyzerNames = false) {
89
+ // With conflicts from a git merge, the source would depend on which of two rows comes first.
90
+ const found = conflicts(db).length;
91
+ if (found > 0) throw new Refusal("conflict", `The knowledge has ${found} conflict${found === 1 ? "" : "s"} from a git merge. Merge the open changes of the project knowledge. Then run the command again.`);
92
+ const code = codeKnowledge(db, space);
93
+ const releases = listReleases(db, undefined, space);
94
+ const base = releases.find((release) => release.base)?.label;
95
+ return {
96
+ revision: currentRevision(db),
97
+ // The source and its loader hold the program of this space and the stage of its start screen: a change elsewhere does not change them.
98
+ sourceRevision: sourceRevision(db, space),
99
+ ...code,
100
+ symbols: analyzerNames ? withAnalyzerNames(code.symbols, listAnalyzerNames(db, undefined, undefined, undefined, space)) : code.symbols,
101
+ comments: listComments(db, undefined, undefined, space),
102
+ modules: listModules(db, undefined, undefined, space),
103
+ switches: listSwitches(db, undefined, space).map((row): SourceSwitch => ({ name: row.name, kind: row.kind, default: row.default, base: baseValue(row, base), releases: row.releases, ...(row.comment === undefined ? {} : { comment: row.comment }) })),
104
+ // Each release with its bytes: the check builds it and compares the build with them.
105
+ releases: releases.map((release) => ({ ...release, image: releaseImage(db, release.label, space)! })),
106
+ macros: listMacros(db, undefined, space),
107
+ macroUses: listMacroUses(db, undefined, undefined, undefined, space),
108
+ };
122
109
  }
123
110
 
124
111
  /** The knowledge of one space that a source is made from. */
125
- type SourceKnowledge = ReturnType<typeof readKnowledge>;
112
+ type SourceKnowledge = ReturnType<typeof knowledgeOf>;
126
113
 
127
114
  /**
128
115
  * The names of the user and the LLM, and for each address without one the
@@ -145,62 +132,6 @@ function withAnalyzerNames(symbols: SymbolRow[], second: SymbolRow[]): SymbolRow
145
132
  return [...symbols, ...added].sort((a, b) => a.address - b.address);
146
133
  }
147
134
 
148
- /** Where the CPU sees ROM in the image (romRanges): the entry, the routines, the code regions and `entries` stay code. */
149
- function romOf(image: ProgramImage, knowledge: Pick<SourceKnowledge, "routines" | "regions">, entries: readonly number[], coverage: Uint8Array | undefined): AddressRange[] {
150
- const inImage = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
151
- const code = knowledge.regions.filter((region) => CODE_REGION_TYPES.includes(region.type) || region.type === "dual-use").map((region) => region.start);
152
- const known = [...(image.entry === undefined ? [] : [image.entry]), ...entries, ...knowledge.routines, ...code];
153
- return romRanges(coverage, image.state, (address) => (inImage(address) ? image.byteAt(address) : undefined), known);
154
- }
155
-
156
- /**
157
- * The decompiler's instruction starts and lengths inside the image, seeded from the
158
- * entry, from knowledge of any origin, and from the coverage: a run's flow
159
- * starts, also after a JSR, so code that an analyzer does not reach by itself
160
- * is in the source. A program without a seed has no known code: it is data
161
- * only, and the decompiler does not run.
162
- */
163
- async function decode(image: ProgramImage, knowledge: Pick<SourceKnowledge, "routines" | "regions">, entries: number[], coverage: Uint8Array | undefined): Promise<{ instructions: Map<number, number>; dataOnly: boolean }> {
164
- const inImage = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
165
- const seeds = new Set<number>([...(image.entry === undefined ? [] : [image.entry]), ...entries]);
166
- for (const address of knowledge.routines) seeds.add(address);
167
- const flows = coverage === undefined ? { routines: [], codeStarts: [] } : coverageSeedKinds(coverage, (address) => (image.segments.some((segment) => address >= segment.start && address <= segment.end) ? image.byteAt(address) : undefined));
168
- for (const address of flows.routines) seeds.add(address);
169
- for (const region of knowledge.regions) {
170
- if (CODE_REGION_TYPES.includes(region.type)) seeds.add(region.start);
171
- if (region.type === "jumps") for (let at = region.start; at + 2 <= region.end; at += 3) seeds.add(at);
172
- }
173
- const entryPoints = [...seeds].filter(inImage).sort((a, b) => a - b);
174
- if (entryPoints.length === 0) {
175
- // An entry in no segment is a capture fault: the image is data only, and the result says entryOutside.
176
- return { instructions: new Map(), dataOnly: image.entry === undefined || inImage(image.entry) };
177
- }
178
- const dataRanges = knowledge.regions
179
- .filter((region) => !CODE_REGION_TYPES.includes(region.type) && region.type !== "dual-use")
180
- .flatMap((region) => image.segments.filter((segment) => region.start <= segment.end && segment.start <= region.end).map((segment) => ({ start: Math.max(region.start, segment.start), end: Math.min(region.end, segment.end) })));
181
- // A JSR into ROM runs the ROM: the RAM bytes of the image under it are data, not the code of the call.
182
- for (const range of romOf(image, knowledge, entries, coverage)) if (!dataRanges.some((data) => range.start <= data.end && data.start <= range.end)) dataRanges.push(range);
183
- const { result } = await analyze(
184
- {
185
- imageKind: analyzedBytes(image).kind,
186
- entryPoints: entryPoints.slice(0, DECOMPILER_LIMITS.entryPoints),
187
- codeStarts: flows.codeStarts.filter((address) => !seeds.has(address)).slice(0, DECOMPILER_LIMITS.codeStarts),
188
- dataRanges: dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges),
189
- labels: [],
190
- decompile: [],
191
- },
192
- analyzedBytes(image).bytes,
193
- localToolContext(),
194
- );
195
- const instructions = new Map<number, number>();
196
- for (const instruction of result.instructions) {
197
- const bytes = Buffer.from(instruction.bytes, "hex");
198
- const inside = Array.from({ length: bytes.length }, (_, offset) => instruction.address + offset).every((address, offset) => inImage(address) && image.byteAt(address) === bytes[offset]);
199
- if (inside) instructions.set(instruction.address, bytes.length);
200
- }
201
- return { instructions, dataOnly: false };
202
- }
203
-
204
135
  /** Assembles files given as text with ACME; the program or the diagnostics. */
205
136
  async function assembleFiles(
206
137
  files: Array<{ name: string; text: string }>,
@@ -299,7 +230,7 @@ async function probeUses(laid: Layout, rendered: Rendered, image: ProgramImage):
299
230
  const labels = new Map<string, number>();
300
231
  for (const [address, name] of laid.names) if (laid.inImage(address)) labels.set(name, address);
301
232
  const used = [...new Set(uses.flatMap((use) => use.args.flatMap((arg) => identifiers(arg))))].filter((name) => labels.has(name)).sort();
302
- const lines = ["!cpu 6510", '!source "constants.asm"', '!source "macros.asm"', ...used.map((name) => `${name} = ${labels.get(name)! < 0x100 ? `$${labels.get(name)!.toString(16).padStart(2, "0")}` : formatC64Address(labels.get(name)!)}`), `* = ${formatC64Address(PROBE_BASE)}`];
233
+ const lines = ["!cpu 6510", '!source "constants.asm"', '!source "macros.asm"', ...used.map((name) => `${name} = ${labels.get(name)! < 0x100 ? formatC64Byte(labels.get(name)!) : formatC64Address(labels.get(name)!)}`), `* = ${formatC64Address(PROBE_BASE)}`];
303
234
  const lineOf = new Map<string, number>();
304
235
  uses.forEach((use, index) => {
305
236
  lines.push(`!pseudopc ${formatC64Address(use.start)} {`, ` +${use.macro}${use.args.length === 0 ? "" : ` ${use.args.join(", ")}`}`);
@@ -364,7 +295,7 @@ function blame(rendered: Rendered, built: Awaited<ReturnType<typeof assembleFile
364
295
  }
365
296
  if (uses.size > 0) return { numbers: blamed, uses };
366
297
  const word = (at: (address: number) => number, item: Rendered["expressions"][number]) => (item.length === 3 ? at(item.address + 1) | (at(item.address + 2) << 8) : at(item.address + 1));
367
- const show = (value: number, length: number) => `$${value.toString(16).padStart(length === 3 ? 4 : 2, "0")}`;
298
+ const show = (value: number, length: number) => (length === 3 ? formatC64Address(value) : formatC64Byte(value));
368
299
  for (const item of rendered.expressions) {
369
300
  if (item.address + item.length - 1 > end || item.address < built.start!) continue;
370
301
  const assembled = word((address) => built.program![2 + address - built.start!]!, item);
@@ -386,7 +317,7 @@ interface SegmentCheck {
386
317
  function check(program: Buffer, start: number, image: Pick<ProgramImage, "segments" | "byteAt">): { identical: boolean; segments: SegmentCheck[] } {
387
318
  const end = start + program.length - 3;
388
319
  const segments = image.segments.map((segment): SegmentCheck => {
389
- const shown = { start: formatC64Address(segment.start), end: formatC64Address(segment.end) };
320
+ const shown = formatC64RangeFields(segment);
390
321
  if (segment.start < start || segment.end > end) return { ...shown, result: "not covered" };
391
322
  let differences = 0;
392
323
  let first: SegmentCheck["firstDifference"];
@@ -427,7 +358,6 @@ function compareBuilds(built: Assembled, ranges: readonly AddressRange[], base:
427
358
  if (overflow.length > 0) return { result: "overflow", overflow };
428
359
  return { result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
429
360
  }
430
- const inside = (address: number) => ranges.some((range) => address >= range.start && address <= range.end);
431
361
  let changed = 0;
432
362
  let outside: BuildCheck["outside"];
433
363
  const end = Math.max(base.start + base.program.length, built.start! + built.program.length) - 2;
@@ -436,7 +366,7 @@ function compareBuilds(built: Assembled, ranges: readonly AddressRange[], base:
436
366
  const now = at(built.program, built.start!);
437
367
  const before = at(base.program, base.start);
438
368
  if (now === before) continue;
439
- if (inside(address)) changed++;
369
+ if (inRanges(ranges, address)) changed++;
440
370
  else outside = { count: (outside?.count ?? 0) + 1, first: outside?.first ?? { address: formatC64Address(address), built: now, base: before } };
441
371
  }
442
372
  return outside === undefined ? { result: "fits", changedBytes: changed } : { result: "changes outside", changedBytes: changed, outside };
@@ -451,11 +381,6 @@ function withValues(files: Array<{ name: string; text: string }>, laid: Pick<Lay
451
381
  return files.map((file) => (file.name === CONFIG_FILE ? { ...file, text: configText(laid, values) } : file));
452
382
  }
453
383
 
454
- /** Builds the source and compares it with the build of the base release (compareBuilds). */
455
- async function checkBuild(files: Array<{ name: string; text: string }>, ranges: readonly AddressRange[], base: { program: Buffer; start: number }): Promise<BuildCheck> {
456
- return compareBuilds(await assembleFiles(files, "main.asm"), ranges, base);
457
- }
458
-
459
384
  /** What a build with one switch at the value that the base release does not have gives. */
460
385
  type SwitchCheck = BuildCheck & {
461
386
  name: string;
@@ -467,7 +392,7 @@ type SwitchCheck = BuildCheck & {
467
392
 
468
393
  /** Builds the source with one switch changed from its base value; only the ranges of its patches may change. */
469
394
  async function checkSwitch(row: SourceSwitch, patches: PatchBlock[], files: Array<{ name: string; text: string }>, laid: Layout, baseValues: ReadonlyMap<string, number>, base: { program: Buffer; start: number }): Promise<SwitchCheck> {
470
- const built = await checkBuild(withValues(files, laid, new Map([...baseValues, [row.name, 1 - row.base]])), patches, base);
395
+ const built = compareBuilds(await assembleFiles(withValues(files, laid, new Map([...baseValues, [row.name, 1 - row.base]])), "main.asm"), patches, base);
471
396
  return {
472
397
  name: row.name,
473
398
  kind: row.kind,
@@ -475,7 +400,7 @@ async function checkSwitch(row: SourceSwitch, patches: PatchBlock[], files: Arra
475
400
  base: row.base,
476
401
  patches: patches.map((patch) => {
477
402
  const inside = patch.inner.map((address) => laid.names.get(address)!);
478
- return { start: formatC64Address(patch.start), end: formatC64Address(patch.end), bytes: patch.end - patch.start + 1, ...(inside.length === 0 ? {} : { insideNames: inside }) };
403
+ return { ...formatC64RangeFields(patch), bytes: patch.end - patch.start + 1, ...(inside.length === 0 ? {} : { insideNames: inside }) };
479
404
  }),
480
405
  ...built,
481
406
  };
@@ -501,7 +426,7 @@ interface ReleaseCheck {
501
426
  async function checkRelease(release: ReleaseRow & { image: Pick<ProgramImage, "segments" | "byteAt"> }, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
502
427
  const shown = { label: release.label, base: release.base, define: `--define ${RELEASE_DEFINE}${release.label}=1` };
503
428
  const { image } = release;
504
- const missing = program.segments.flatMap((segment) => subtract(segment, [...image.segments])).map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) }));
429
+ const missing = program.segments.flatMap((segment) => subtract(segment, [...image.segments])).map(formatC64RangeFields);
505
430
  const notInRelease = missing.length === 0 ? {} : { notInRelease: missing };
506
431
  const built = await assembleFiles(files, "main.asm", { [`${RELEASE_DEFINE}${release.label}`]: 1 });
507
432
  if (built.program === undefined) return { ...shown, result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS), ...notInRelease };
@@ -509,22 +434,6 @@ async function checkRelease(release: ReleaseRow & { image: Pick<ProgramImage, "s
509
434
  return { ...shown, result: checked.identical ? "identical" : "different", ...(checked.identical ? {} : { segments: checked.segments.filter((segment) => segment.result !== "identical") }), ...notInRelease };
510
435
  }
511
436
 
512
- /** Reads RAM in parts. */
513
- async function readRam(client: ViceSessionClient, start: number, size: number): Promise<Buffer> {
514
- const parts: Buffer[] = [];
515
- for (let at = start; at < start + size; at += MAX_MEMORY_READ) {
516
- parts.push(Buffer.from((await client.memoryRead({ address: at, size: Math.min(MAX_MEMORY_READ, start + size - at), space: "c64", view: "ram" })).data, "hex"));
517
- }
518
- return Buffer.concat(parts);
519
- }
520
-
521
- /** Runs the loader in the emulator to the entry and compares memory, $00/$01 and the registers with the entry state. */
522
- /**
523
- * Runs the loader in the emulator to its jump to the entry and compares the
524
- * machine with the entry state there. At the jump, every byte and register is
525
- * set and no interrupt has run since the PLP: the 6502 takes one only after
526
- * the JMP, as the program can take one right at its entry.
527
- */
528
437
  /** What the check of the loader gives. `stop`: why the loader did not get to its copier or its jump. */
529
438
  interface LoaderRun {
530
439
  verified: boolean;
@@ -552,9 +461,22 @@ interface LoaderRunPlan {
552
461
  copierFrames: number;
553
462
  }
554
463
 
464
+ /**
465
+ * Runs the loader in the emulator to its jump to the entry and compares the
466
+ * machine with the entry state there. At the jump, every byte and register is
467
+ * set and no interrupt has run since the PLP: the 6502 takes one only after
468
+ * the JMP, as the program can take one right at its entry.
469
+ */
555
470
  async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state: EntryState, run: LoaderRunPlan, expected: (address: number) => number): Promise<LoaderRun> {
556
471
  const { jump, copierSource, fileByte } = run;
557
472
  const client = await ViceSessionClient.open({ videoStandard: "pal" });
473
+ const readRam = (address: number, size: number) => readMemoryInParts(client, address, size, "ram");
474
+ /** The first colour of the colour RAM that is not `wanted`, as a difference. */
475
+ const colourDifference = async (wanted: Uint8Array): Promise<string | undefined> => {
476
+ const colours = Buffer.from((await client.ioRead(0xd800, wanted.length)).data, "hex");
477
+ const wrong = wanted.findIndex((value, offset) => (colours[offset]! & 0x0f) !== value);
478
+ return wrong < 0 ? undefined : `the colour RAM has ${colours[wrong]! & 0x0f} at ${formatC64Address(0xd800 + wrong)}, not ${wanted[wrong]}`;
479
+ };
558
480
  try {
559
481
  await client.reset({ mode: "hard", run: false });
560
482
  if (!(await autostartLoaded(client, path, program))) return { verified: false, differences: ["The loader was not in memory after autostart."] };
@@ -562,12 +484,11 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
562
484
  // A stop before the copier or the jump gives $01, the last instructions and the first byte that is not as planned.
563
485
  // Before the show stage moves on, the copier is not in place yet: then the stop has no cause from it.
564
486
  const stopped = async (pc: number, copied: boolean, what: string, loaderRan = true): Promise<LoaderRun> => {
565
- const ram = await readRam(client, 0x0000, 0x10000);
487
+ const ram = await readRam(0x0000, 0x10000);
566
488
  const port = Buffer.from((await client.memoryRead({ address: 0x0001, size: 1, space: "c64", view: "cpu" })).data, "hex")[0]!;
567
489
  const history = (await client.cpuHistory({ limit: STOP_HISTORY, space: "c64" })).entries.map((entry) => `${formatC64Address(entry.address)} ${entry.text}`);
568
490
  const cause = loaderRan ? stopCause(ram, plan, copierSource, fileByte, copied, expected) : undefined;
569
- const port01 = `$${port.toString(16).padStart(2, "0")}`;
570
- return { verified: false, differences: [`The loader did not get to ${what}; it stopped at ${formatC64Address(pc)}.`], stop: { pc: formatC64Address(pc), port: port01, ...(cause === undefined ? {} : { cause }), history } };
491
+ return { verified: false, differences: [`The loader did not get to ${what}; it stopped at ${formatC64Address(pc)}.`], stop: { pc: formatC64Address(pc), port: formatC64Byte(port), ...(cause === undefined ? {} : { cause }), history } };
571
492
  };
572
493
  // The start screen waits for a key or a fire button. Not each VICE can press a key of the keyboard matrix,
573
494
  // so the check lets it wait, then sets the PC to the code after the wait.
@@ -584,21 +505,18 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
584
505
  const shown: Array<[number, number]> = [[0x11, wanted.d011], [0x15, 0], [0x16, wanted.d016], [0x18, wanted.d018], [0x20, wanted.border], [0x21, wanted.background]];
585
506
  for (const [register, value] of shown) {
586
507
  const mask = VIC_DISPLAY_REGISTERS.find((item) => item.register === register)!.mask;
587
- if ((vic[register]! & mask) !== (value & mask)) screenDifferences.push(`the start screen has ${formatC64Address(0xd000 + register)} = $${(vic[register]! & mask).toString(16).padStart(2, "0")}, not $${(value & mask).toString(16).padStart(2, "0")}`);
508
+ if ((vic[register]! & mask) !== (value & mask)) screenDifferences.push(`the start screen has ${formatC64Address(0xd000 + register)} = ${formatC64Byte(vic[register]! & mask)}, not ${formatC64Byte(value & mask)}`);
588
509
  }
589
510
  if (bank !== wanted.bank) screenDifferences.push(`the start screen is in VIC bank ${bank}, not ${wanted.bank}`);
590
511
  // The bytes of the screen of a stage: the first wrong byte of each part.
591
512
  for (const part of parts) {
592
- const ram = await readRam(client, part.start, part.body.length);
513
+ const ram = await readRam(part.start, part.body.length);
593
514
  const wrong = part.body.findIndex((byte, offset) => ram[offset] !== byte);
594
- if (wrong >= 0) screenDifferences.push(`the stage has $${ram[wrong]!.toString(16).padStart(2, "0")} at ${formatC64Address(part.start + wrong)}, not $${part.body[wrong]!.toString(16).padStart(2, "0")}`);
515
+ if (wrong >= 0) screenDifferences.push(`the stage has ${formatC64Byte(ram[wrong]!)} at ${formatC64Address(part.start + wrong)}, not ${formatC64Byte(part.body[wrong]!)}`);
595
516
  }
596
517
  // The colour RAM of a captured stage: the first wrong colour.
597
- if (colourRam !== undefined) {
598
- const colours = Buffer.from((await client.ioRead(0xd800, colourRam.length)).data, "hex");
599
- const wrong = colourRam.findIndex((value, offset) => (colours[offset]! & 0x0f) !== value);
600
- if (wrong >= 0) screenDifferences.push(`the colour RAM has ${colours[wrong]! & 0x0f} at ${formatC64Address(0xd800 + wrong)}, not ${colourRam[wrong]}`);
601
- }
518
+ const screenColours = colourRam === undefined ? undefined : await colourDifference(colourRam);
519
+ if (screenColours !== undefined) screenDifferences.push(screenColours);
602
520
  screen = { shown: screenDifferences.length === before, waits: !held.reached, ...labels, ...(run.stage === undefined ? {} : { stage: run.stage.name }) };
603
521
  if (held.reached) screenDifferences.push(`the start screen did not wait: it got to ${labels.continue} without a key or a fire button`);
604
522
  if (!held.reached) await client.registersSet("c64", { pc: at.continue });
@@ -617,15 +535,14 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
617
535
  }
618
536
  const atJump = await client.runUntil({ target: { kind: "address", address: jump, space: "c64" }, timeoutFrames: LOADER_FRAMES });
619
537
  if (!atJump.reached) return await stopped(atJump.pc, true, `its jump to the entry at ${formatC64Address(jump)}`);
620
- const memory = await readRam(client, 0x0000, 0x10000);
538
+ const memory = await readRam(0x0000, 0x10000);
621
539
  if (memory[jump] !== 0x4c || (memory[jump + 1]! | (memory[jump + 2]! << 8)) !== state.pc) {
622
540
  return { verified: false, differences: [`The instruction at ${formatC64Address(jump)} is not JMP ${formatC64Address(state.pc)}.`] };
623
541
  }
624
542
  const port = Buffer.from((await client.memoryRead({ address: 0x0000, size: 2, space: "c64", view: "cpu" })).data, "hex");
625
543
  const registers = await client.registersGet("c64");
626
544
  const differences: string[] = [];
627
- const byte = (value: number) => `$${value.toString(16).padStart(2, "0")}`;
628
- const differ = (what: string, got: number, wanted: number) => got !== wanted && differences.push(`${what} is ${byte(got)}, not ${byte(wanted)}`);
545
+ const differ = (what: string, got: number, wanted: number) => got !== wanted && differences.push(`${what} is ${formatC64Byte(got)}, not ${formatC64Byte(wanted)}`);
629
546
  // The leftovers are not loaded: only the loaded ranges have the bytes of the build.
630
547
  for (const part of plan.loaded) {
631
548
  for (let address = Math.max(part.start, 2); address <= part.end; address++) differ(formatC64Address(address), memory[address]!, expected(address));
@@ -648,17 +565,12 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
648
565
  const wanted = rasterLine(state.vic.registers);
649
566
  if (line !== wanted && line !== wanted + 1) differences.push(`the raster line is ${line}, not ${wanted}`);
650
567
  }
651
- if (plan.colours !== undefined && state.colourRam !== undefined) {
652
- // The colour RAM: the first wrong colour.
653
- const colours = Buffer.from((await client.ioRead(0xd800, state.colourRam.length)).data, "hex");
654
- const wrong = state.colourRam.findIndex((value, offset) => (colours[offset]! & 0x0f) !== value);
655
- if (wrong >= 0) differences.push(`the colour RAM has ${colours[wrong]! & 0x0f} at ${formatC64Address(0xd800 + wrong)}, not ${state.colourRam[wrong]}`);
656
- }
568
+ const colourWrong = plan.colours === undefined || state.colourRam === undefined ? undefined : await colourDifference(state.colourRam);
569
+ if (colourWrong !== undefined) differences.push(colourWrong);
657
570
  if (plan.cia !== undefined) {
658
571
  // The CIA timers: at the jump a running timer is 3 cycles, the JMP, before its value at the entry.
659
572
  const chips = (await client.cia("both")).chips;
660
- const word = (value: number) => `$${value.toString(16).padStart(4, "0")}`;
661
- const differWord = (what: string, got: number, wanted: number) => got !== wanted && differences.push(`${what} is ${word(got)}, not ${word(wanted)}`);
573
+ const differWord = (what: string, got: number, wanted: number) => got !== wanted && differences.push(`${what} is ${formatC64Address(got)}, not ${formatC64Address(wanted)}`);
662
574
  for (const timer of plan.cia.timers) {
663
575
  const chip = chips[timer.cia - 1]!;
664
576
  const name = `CIA ${timer.cia} timer ${timer.timer}`;
@@ -694,7 +606,7 @@ const SOURCE_MAP_FILE = "source-map.json";
694
606
  */
695
607
  function sourceMapText(rendered: Rendered, space: string, revision: string | null, files: ReadonlyArray<{ name: string }>): string {
696
608
  const labels = rendered.labels.map((label) => JSON.stringify({ address: formatC64Address(label.address), name: label.name, file: label.file, line: label.line + 1 }));
697
- const items = rendered.items.map((item) => JSON.stringify({ start: formatC64Address(item.start), end: formatC64Address(item.end), file: item.file, line: item.line + 1 }));
609
+ const items = rendered.items.map((item) => JSON.stringify({ ...formatC64RangeFields(item), file: item.file, line: item.line + 1 }));
698
610
  const head = JSON.stringify({ space, revision, files: files.map((file) => file.name) }).slice(0, -1);
699
611
  return `${head},\n"labels": [\n${labels.join(",\n")}\n],\n"items": [\n${items.join(",\n")}\n]}\n`;
700
612
  }
@@ -806,7 +718,7 @@ function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boole
806
718
  }
807
719
 
808
720
  /** The instructions that the decompiler decoded, and whether the program has known code. */
809
- type DecodedProgram = Awaited<ReturnType<typeof decode>>;
721
+ type DecodedProgram = Awaited<ReturnType<typeof decodeProgram>>;
810
722
 
811
723
  /** How buildSource makes and checks the source of a knowledge. */
812
724
  interface SourceOptions {
@@ -845,7 +757,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
845
757
  const coverage = knowledge.coverage;
846
758
  const romUse = romUseOfProgram(coverage, image.state);
847
759
  const platform = platformNamesFor(romUse);
848
- const { instructions, dataOnly } = options.decoded ?? (await decode(image, knowledge, options.entries, coverage));
760
+ const { instructions, dataOnly } = options.decoded ?? (await decodeProgram(image, knowledge, options.entries, coverage));
849
761
  const leftoverPlan = options.leftovers === true && !dataOnly ? leftoversOf(knowledge, instructions) : { ranges: [], unknown: [], unresolved: [] };
850
762
  const leftovers = leftoverPlan.ranges;
851
763
  const laid = layout({
@@ -978,7 +890,7 @@ async function buildLoader(
978
890
  // The plain form also copies the colours of the colour RAM to a free range, where the copier reads them.
979
891
  const colours = loader.colours;
980
892
  const expected = (address: number) =>
981
- loader.loaded.some((part) => address >= part.start && address <= part.end)
893
+ inRanges(loader.loaded, address)
982
894
  ? main.program[2 + address - main.start]!
983
895
  : colours !== undefined && address >= colours.start && address <= colours.end
984
896
  ? state.colourRam![address - colours.start]!
@@ -1022,7 +934,7 @@ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; co
1022
934
  const length = patch.end - patch.start + 1;
1023
935
  const built = await assembleFiles([{ name: "patch.asm", text: stagePatchText(knowledge.symbols, patch) }], "patch.asm");
1024
936
  if (built.program === undefined || built.start !== patch.start || built.program.length - 2 !== length) {
1025
- throw new Refusal("invalid-input", `The patch of ${patch.switch} at ${formatC64Address(patch.start)}-${formatC64Address(patch.end)} in ${stage} does not assemble to ${length} bytes: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ") || "it is longer than its range"}. Correct the patch in the project knowledge.`);
937
+ throw new Refusal("invalid-input", `The patch of ${patch.switch} at ${formatC64Range(patch)} in ${stage} does not assemble to ${length} bytes: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ") || "it is longer than its range"}. Correct the patch in the project knowledge.`);
1026
938
  }
1027
939
  memory.set(built.program.subarray(2), patch.start);
1028
940
  }
@@ -1034,16 +946,11 @@ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; co
1034
946
  }
1035
947
  // The call is the entry of the stage: what it does not reach and its run did not touch stays out.
1036
948
  const called = { ...knowledge, program: { ...image, entry: row.call } };
1037
- const { instructions } = await decode(called.program, called, [row.call], knowledge.coverage);
949
+ const { instructions } = await decodeProgram(called.program, called, [row.call], knowledge.coverage);
1038
950
  const free = leftoversOf(called, instructions, screen).ranges;
1039
951
  ranges = [...screen, ...image.segments.flatMap((segment) => subtract(segment, free))];
1040
952
  }
1041
- const parts: AddressRange[] = [];
1042
- for (const range of ranges.map((item) => ({ start: Math.max(item.start, 0x0400), end: item.end })).filter((item) => item.start <= item.end).sort((a, b) => a.start - b.start)) {
1043
- const last = parts.at(-1);
1044
- if (last !== undefined && range.start <= last.end + 1) last.end = Math.max(last.end, range.end);
1045
- else parts.push({ ...range });
1046
- }
953
+ const parts = mergeRanges(ranges.map((item) => ({ start: Math.max(item.start, 0x0400), end: item.end })).filter((item) => item.start <= item.end));
1047
954
  return { parts: parts.map((range) => ({ start: range.start, body: memory.slice(range.start, range.end + 1) })), ...(colourRam === undefined ? {} : { colourRam }) };
1048
955
  }
1049
956
 
@@ -1080,7 +987,7 @@ async function buildStage(files: Array<{ name: string; text: string }>, laid: La
1080
987
  ...(colourRam === undefined ? {} : { colourRam }),
1081
988
  row,
1082
989
  plan: screen,
1083
- settings: hasSwitchFile(laid) ? ['!source "switches.asm"'] : hasConfigFile(laid) ? ['!source "config.asm"'] : [],
990
+ settings: settingsLines({ switches: hasSwitchFile(laid), config: hasConfigFile(laid) }),
1084
991
  header,
1085
992
  codeSize: 0,
1086
993
  };
@@ -1116,6 +1023,26 @@ async function buildStage(files: Array<{ name: string; text: string }>, laid: La
1116
1023
  return { program: packed.program, text: `${mark}\n${plan.text}`, symbols: built.symbols, plan, parts: stage, ...(colourRam === undefined ? {} : { colourRam }), packed, wait: built.label(START_SCREEN_WAIT), continue: built.label(START_SCREEN_CONTINUE), screen };
1117
1024
  }
1118
1025
 
1026
+ /** An operand expression that the source writes as a number, as a result lists it. */
1027
+ const shownOperand = (item: Rendered["operandsAsNumbers"][number]) => ({ address: formatC64Address(item.address), expression: item.expression, reason: item.reason });
1028
+ /** A macro use that the source writes as its instructions, as a result lists it. */
1029
+ const shownMacro = (item: Rendered["macrosAsInstructions"][number]) => ({ ...formatC64RangeFields(item), macro: item.macro, reason: item.reason });
1030
+ /** A patch that the source cannot write, as a result lists it. */
1031
+ const shownPatch = (item: Layout["patchesNotWritten"][number]) => ({ ...formatC64RangeFields(item), switch: item.switch, reason: item.reason });
1032
+
1033
+ /** The copies, the copier and the stack byte of a loader, as a result shows them. */
1034
+ const loaderPlaces = (loader: LoaderPlan) => ({
1035
+ copies: loader.copies.map((copy) => ({ what: copy.what, to: formatC64Range(copy.target) })),
1036
+ copier: formatC64Address(loader.copier),
1037
+ stackByte: formatC64Address(loader.stackByte),
1038
+ });
1039
+
1040
+ /** What the loader cannot set as it was at the entry; nothing when it sets all. */
1041
+ function limitsOf(loader: LoaderPlan): { limits?: string[] } {
1042
+ const limits = loaderLimits(loader);
1043
+ return limits.length === 0 ? {} : { limits };
1044
+ }
1045
+
1119
1046
  /** The first line of each file that generate writes. */
1120
1047
  const GENERATED_LINE = `${GENERATED_MARK}. Do not edit: change the knowledge and generate again.`;
1121
1048
 
@@ -1170,19 +1097,18 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1170
1097
  const staleReference = generatedReferences(projectRoot())
1171
1098
  .filter((reference) => reference.mapPath === `${reports}/${SOURCE_MAP_FILE}` && reference.revision !== knowledge.sourceRevision)
1172
1099
  .map((reference) => ({ folder: reference.folder, revision: reference.revision }));
1173
- const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
1174
1100
  const inData = entriesInData(entries, knowledge.regions);
1175
1101
  // Each range of code that no run executed, with the file of the source that holds it and the routine before it, as a report groups them.
1176
1102
  const routines = knowledge.symbols.filter((symbol) => symbol.kind === "routine").sort((a, b) => a.address - b.address);
1177
1103
  const placeRange = (range: AddressRange) => {
1178
1104
  const file = laid.pieces.find((piece) => range.start >= piece.start && range.start <= piece.end)?.file;
1179
1105
  const routine = routines.filter((symbol) => symbol.address <= range.start).at(-1)?.name;
1180
- return { ...showRange(range), ...(file === undefined ? {} : { file }), ...(routine === undefined ? {} : { routine }) };
1106
+ return { ...formatC64RangeFields(range), ...(file === undefined ? {} : { file }), ...(routine === undefined ? {} : { routine }) };
1181
1107
  };
1182
1108
  // The leftovers that changed since the earlier run: the default build and the loader now leave out other bytes.
1183
1109
  const added = earlier === undefined ? [] : outside(laid.leftovers, earlier);
1184
1110
  const dropped = earlier === undefined ? [] : outside(earlier, laid.leftovers);
1185
- const changed = added.length + dropped.length === 0 ? undefined : { added: added.map(showRange), removed: dropped.map(showRange) };
1111
+ const changed = added.length + dropped.length === 0 ? undefined : { added: added.map(formatC64RangeFields), removed: dropped.map(formatC64RangeFields) };
1186
1112
 
1187
1113
  const output: Record<string, unknown> = {
1188
1114
  out,
@@ -1205,7 +1131,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1205
1131
  // An --entry in a data region decodes nothing: the result says so, and a code region in the knowledge changes it.
1206
1132
  ...(inData.length === 0
1207
1133
  ? {}
1208
- : { entriesInData: inData.map(({ entry, region }) => ({ entry: formatC64Address(entry), region: { ...showRange(region), type: region.type }, origin: region.origin })) }),
1134
+ : { entriesInData: inData.map(({ entry, region }) => ({ entry: formatC64Address(entry), region: { ...formatC64RangeFields(region), type: region.type }, origin: region.origin })) }),
1209
1135
  ...(rendered.asBytes.length === 0
1210
1136
  ? {}
1211
1137
  : { asBytes: listed(rendered.asBytes, max, (item) => ({ address: formatC64Address(item.address), instruction: item.text })) }),
@@ -1222,26 +1148,26 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1222
1148
  : changed === undefined
1223
1149
  ? {}
1224
1150
  : { leftovers: { bytes: 0, changed } }
1225
- : { leftovers: { bytes: laid.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0), ...listed(laid.leftovers, max, (range) => ({ ...showRange(range), bytes: range.end - range.start + 1, file: `${LEFTOVER_FOLDER}/leftover_${range.start.toString(16).padStart(4, "0")}.asm` })), ...(changed === undefined ? {} : { changed }) } }),
1151
+ : { leftovers: { bytes: laid.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0), ...listed(laid.leftovers, max, (range) => ({ ...formatC64RangeFields(range), bytes: range.end - range.start + 1, file: `${LEFTOVER_FOLDER}/leftover_${hexWord(range.start)}.asm` })), ...(changed === undefined ? {} : { changed }) } }),
1226
1152
  ...(unknownCode.unknown.length === 0 ? {} : { unknownCode: showUnknown(unknownCode, max) }),
1227
1153
  ...(rendered.expressions.length === 0 && rendered.operandsAsNumbers.length === 0 ? {} : { operandExpressions: rendered.expressions.length }),
1228
1154
  ...(rendered.operandsAsNumbers.length === 0
1229
1155
  ? {}
1230
1156
  : {
1231
- operandsAsNumbers: listed(rendered.operandsAsNumbers, max, (item) => ({ address: formatC64Address(item.address), expression: item.expression, reason: item.reason })),
1157
+ operandsAsNumbers: listed(rendered.operandsAsNumbers, max, shownOperand),
1232
1158
  }),
1233
1159
  ...(rendered.uses.length === 0 && rendered.macrosAsInstructions.length === 0 ? {} : { macroUses: rendered.uses.length }),
1234
1160
  // A macro use that the source writes as its instructions does not fail the run: the source stays identical.
1235
1161
  ...(rendered.macrosAsInstructions.length === 0
1236
1162
  ? {}
1237
1163
  : {
1238
- macrosAsInstructions: listed(rendered.macrosAsInstructions, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), macro: item.macro, reason: item.reason })),
1164
+ macrosAsInstructions: listed(rendered.macrosAsInstructions, max, shownMacro),
1239
1165
  }),
1240
1166
  // A patch that the source cannot write fails the run: the switch would miss a part.
1241
1167
  ...(laid.patchesNotWritten.length === 0
1242
1168
  ? {}
1243
1169
  : {
1244
- patchesNotWritten: listed(laid.patchesNotWritten, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), switch: item.switch, reason: item.reason })),
1170
+ patchesNotWritten: listed(laid.patchesNotWritten, max, shownPatch),
1245
1171
  }),
1246
1172
  };
1247
1173
  // The loader program is a build: it goes to the build folder. A loader program of an earlier run stays when this run checks no new one.
@@ -1274,7 +1200,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1274
1200
  const changed = laid.switches.filter((row) => row.default !== row.base);
1275
1201
  // The default build also leaves out the leftovers.
1276
1202
  const ranges = [...changed.flatMap((row) => withPatches.get(row.name) ?? []), ...laid.leftovers];
1277
- const built = await checkBuild(withValues(files, laid, new Map()), ranges, baseBuild);
1203
+ const built = compareBuilds(await assembleFiles(withValues(files, laid, new Map()), "main.asm"), ranges, baseBuild);
1278
1204
  output.default = { in: changed.map((row) => row.name), ...built };
1279
1205
  defaultFailed = built.result !== "fits";
1280
1206
  }
@@ -1362,17 +1288,14 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1362
1288
  space: stageRow!.stage,
1363
1289
  code: formatC64Address(stage.plan.code),
1364
1290
  bytes: stage.parts.reduce((sum, part) => sum + part.body.length, 0),
1365
- stash: stage.plan.stash.map((item) => ({ from: formatC64Address(item.at), to: `${formatC64Address(item.target.start)}-${formatC64Address(item.target.end)}` })),
1291
+ stash: stage.plan.stash.map((item) => ({ from: formatC64Address(item.at), to: formatC64Range(item.target) })),
1366
1292
  packedBytes: stage.packed.packedBytes,
1367
1293
  unpackedBytes: stage.packed.unpackedBytes,
1368
1294
  },
1369
1295
  }),
1370
- copies: loader.copies.map((copy) => ({ what: copy.what, to: `${formatC64Address(copy.target.start)}-${formatC64Address(copy.target.end)}` })),
1371
- copier: formatC64Address(loader.copier),
1372
- stackByte: formatC64Address(loader.stackByte),
1296
+ ...loaderPlaces(loader),
1373
1297
  ...ran,
1374
- // What the loader cannot set as it was at the entry.
1375
- ...(loaderLimits(loader).length === 0 ? {} : { limits: loaderLimits(loader) }),
1298
+ ...limitsOf(loader),
1376
1299
  };
1377
1300
  return { output, removed, failed: !ran.verified || sourceFailed };
1378
1301
  }
@@ -1385,46 +1308,6 @@ function exportValue(row: SourceSwitch): 0 | 1 {
1385
1308
 
1386
1309
  const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1387
1310
 
1388
- /**
1389
- * The BASIC line that starts a PRG: its bytes, and the address of its first
1390
- * SYS when the image holds it (the entry of a PRG without one in the
1391
- * knowledge). Undefined when the first segment holds no BASIC line with a SYS.
1392
- */
1393
- function basicStart(image: ProgramImage): { line: AddressRange; entry?: number } | undefined {
1394
- const first = image.segments[0];
1395
- if (first === undefined) return undefined;
1396
- const tokenized = parseTokenized(Uint8Array.from([first.start & 0xff, first.start >> 8, ...image.memory.subarray(first.start, first.end + 1)]));
1397
- if ("reason" in tokenized) return undefined;
1398
- const sys = findHandoffs(tokenized.lines).find((handoff) => handoff.kind === "sys");
1399
- if (sys === undefined) return undefined;
1400
- const line = { start: first.start, end: Math.min(first.end, tokenized.basicEnd - 1) };
1401
- const address = "address" in sys ? sys.address : undefined;
1402
- return address !== undefined && image.segments.some((segment) => address >= segment.start && address <= segment.end) ? { line, entry: address } : { line };
1403
- }
1404
-
1405
- /** The parts of a region outside the holes. A part that is not the whole region has no element size: its length need not be a multiple of it. */
1406
- function clipped<R extends { start: number; end: number; element?: number }>(region: R, holes: readonly AddressRange[]): R[] {
1407
- return subtract(region, [...holes]).map((piece) => {
1408
- if (piece.start === region.start && piece.end === region.end) return region;
1409
- const part = { ...region, ...piece };
1410
- delete part.element;
1411
- return part;
1412
- });
1413
- }
1414
-
1415
- /** The regions that decide the memory map: the user and LLM regions, and the parts of analyzer regions outside them. */
1416
- function effectiveRegions(regions: SourceKnowledge["regions"]): SourceKnowledge["regions"] {
1417
- const semantic = regions.filter((region) => isSemantic(region.origin));
1418
- const holes = semantic.map((region) => ({ start: region.start, end: region.end }));
1419
- return [...semantic, ...regions.filter((region) => !isSemantic(region.origin)).flatMap((region) => clipped(region, holes))].sort((a, b) => a.start - b.start);
1420
- }
1421
-
1422
- /** The names and the four-digit hex addresses that the code of a patch has: a switch can go to them, so they stay. */
1423
- function patchTargets(code: string, addressOf: ReadonlyMap<string, number>): number[] {
1424
- const words = code.replace(/;.*$/gm, "").match(/\$[0-9a-fA-F]{4}\b|[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
1425
- return words.flatMap((word) => (word.startsWith("$") ? [Number.parseInt(word.slice(1), 16)] : addressOf.has(word) ? [addressOf.get(word)!] : []));
1426
- }
1427
-
1428
1311
  /**
1429
1312
  * The free ranges of a program: code that no run executed and that nothing
1430
1313
  * reaches, and data that no run touched and that nothing names (planDrops).
@@ -1432,34 +1315,12 @@ function patchTargets(code: string, addressOf: ReadonlyMap<string, number>): num
1432
1315
  * `instructions` are of the build that the ranges are free in.
1433
1316
  */
1434
1317
  function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions: ReadonlyMap<number, number>, ranges: { changed: readonly AddressRange[]; keep: readonly AddressRange[]; drop: readonly AddressRange[] }) {
1435
- const image = knowledge.program;
1436
- const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
1437
- const operandTargets = new Map<number, number[]>();
1438
- for (const operand of knowledge.operands) {
1439
- const names = operand.symbol !== undefined ? [operand.symbol] : identifiers(operand.expression ?? "");
1440
- const targets = names.flatMap((item) => (addressOf.has(item) ? [(addressOf.get(item)! + (operand.symbol !== undefined ? operand.offset : 0)) & 0xffff] : []));
1441
- operandTargets.set(operand.address, targets);
1442
- }
1443
- const basic = basicStart(image);
1444
- const entry = image.entry ?? basic?.entry;
1445
- return planDrops({
1446
- segments: image.segments,
1447
- memory,
1448
- ...(entry === undefined ? {} : { entry }),
1449
- instructions,
1450
- ...(knowledge.coverage === undefined ? {} : { coverage: knowledge.coverage }),
1451
- regions: effectiveRegions(knowledge.regions),
1452
- references: knowledge.references,
1453
- operandTargets,
1454
- rom: romOf(image, knowledge, [], knowledge.coverage),
1455
- ...(basic === undefined ? {} : { basic: basic.line }),
1456
- changed: [...ranges.changed],
1457
- keep: [...ranges.keep],
1458
- drop: [...ranges.drop],
1459
- routines: knowledge.symbols.filter((symbol) => symbol.kind === "routine"),
1460
- });
1318
+ return planDrops({ ...reachInput(knowledge, memory, instructions, ranges), routines: routinesOf(knowledge) });
1461
1319
  }
1462
1320
 
1321
+ /** The routine names of the source: they name the code that a run executed and that the entry does not reach. */
1322
+ const routinesOf = (knowledge: SourceKnowledge) => knowledge.symbols.filter((symbol) => symbol.kind === "routine");
1323
+
1463
1324
  /**
1464
1325
  * The leftovers of generate: the free ranges of the program as it is. The
1465
1326
  * start screen in the program, the patches, the macro uses, what the code of a
@@ -1467,17 +1328,10 @@ function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions
1467
1328
  * LEFTOVERS = 0.
1468
1329
  */
1469
1330
  function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<number, number>, kept: readonly AddressRange[] = []): UnknownCode & { ranges: AddressRange[] } {
1470
- const image = knowledge.program;
1471
- const inImage = (range: AddressRange) => image.segments.some((segment) => range.start >= segment.start && range.end <= segment.end);
1472
- const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
1473
- const screenParts = knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
1474
- const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
1475
- const keep = [...screenParts, ...kept, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
1476
- const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
1477
- const plan = freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] });
1331
+ const plan = planDrops({ ...leftoverInput(knowledge, instructions, kept), routines: routinesOf(knowledge) });
1478
1332
  const free = plan.free.map((range) => ({ start: range.start, end: range.end }));
1479
1333
  // A macro use in code that nothing uses goes with that code. A leftover never cuts a use in two: its edge stops at the use.
1480
- const cut = (range: AddressRange) => knowledge.macroUses.filter((use) => use.start <= range.end && range.start <= use.end && (use.start < range.start || use.end > range.end));
1334
+ const cut = (range: AddressRange) => knowledge.macroUses.filter((use) => rangesOverlap(use, range) && (use.start < range.start || use.end > range.end));
1481
1335
  return { ranges: free.flatMap((range) => subtract(range, cut(range))), unknown: plan.unknown, unresolved: plan.unresolved };
1482
1336
  }
1483
1337
 
@@ -1490,7 +1344,7 @@ interface UnknownCode {
1490
1344
  /** The unknown code of a result: its ranges, and the flows whose targets the knowledge does not give. */
1491
1345
  function showUnknown(code: UnknownCode, max: number) {
1492
1346
  return {
1493
- ...listed(code.unknown, max, (range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end), bytes: range.end - range.start + 1 })),
1347
+ ...listed(code.unknown, max, (range) => ({ ...formatC64RangeFields(range), bytes: range.end - range.start + 1 })),
1494
1348
  unresolved: listed(code.unresolved, max, (flow) => ({ at: formatC64Address(flow.at), kind: flow.kind })),
1495
1349
  };
1496
1350
  }
@@ -1525,18 +1379,9 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1525
1379
  const given = call.ranges("keep");
1526
1380
  const drop = call.ranges("drop");
1527
1381
  const max = call.count("max-listed")!;
1528
- const shownRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
1529
1382
  const fromProject = (path: string) => relative(project, path).split(sep).join("/");
1530
1383
 
1531
- const db = openForRead();
1532
- const spacesLeftOut = (() => {
1533
- try {
1534
- return listSpaces(db).filter((space) => space !== DEFAULT_SPACE);
1535
- } finally {
1536
- db?.close();
1537
- }
1538
- })();
1539
- const read = readKnowledge(DEFAULT_SPACE);
1384
+ const { spacesLeftOut, read } = withRead((db) => ({ spacesLeftOut: listSpaces(db).filter((space) => space !== DEFAULT_SPACE), read: knowledgeOf(db, DEFAULT_SPACE) }));
1540
1385
  // The export has only the space c64: a start screen of a captured stage stays out with that space.
1541
1386
  const stageLeftOut = read.startScreen?.stage;
1542
1387
  const knowledge = stageLeftOut === undefined ? read : { ...read, startScreen: undefined };
@@ -1554,7 +1399,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1554
1399
  if (!checked.identical) return { result: "FAIL", stage: "base", reason: "The source of the knowledge does not assemble to the program.", check: checked };
1555
1400
  if (baseSource.missingEntry !== undefined) return { result: "FAIL", stage: "base", reason: baseSource.missingEntry };
1556
1401
  if (baseSource.laid.patchesNotWritten.length > 0) {
1557
- return { result: "FAIL", stage: "base", reason: "The source cannot write every patch.", patchesNotWritten: listed(baseSource.laid.patchesNotWritten, max, (item) => ({ ...shownRange(item), switch: item.switch, reason: item.reason })) };
1402
+ return { result: "FAIL", stage: "base", reason: "The source cannot write every patch.", patchesNotWritten: listed(baseSource.laid.patchesNotWritten, max, shownPatch) };
1558
1403
  }
1559
1404
 
1560
1405
  // 2. Each switch at its export value. Two alternatives of one range cannot both be in.
@@ -1562,7 +1407,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1562
1407
  for (const patch of baseSource.laid.patches.values()) {
1563
1408
  const both = patch.alternatives.filter((alternative) => values.get(alternative.switch) !== alternative.base);
1564
1409
  if (both.length > 1) {
1565
- throw new Refusal("invalid-input", `The switches ${both.map((item) => item.switch).join(" and ")} change ${formatC64Address(patch.start)}-${formatC64Address(patch.end)} in different ways, and the export puts both in. In the project knowledge, give all but one of them the kind change, with the default of the base release. Then export again.`);
1410
+ throw new Refusal("invalid-input", `The switches ${both.map((item) => item.switch).join(" and ")} change ${formatC64Range(patch)} in different ways, and the export puts both in. In the project knowledge, give all but one of them the kind change, with the default of the base release. Then export again.`);
1566
1411
  }
1567
1412
  }
1568
1413
  const withPatches = switchesOf(baseSource.laid);
@@ -1581,13 +1426,14 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1581
1426
  return false;
1582
1427
  });
1583
1428
  const bakedImage: ProgramImage = { space: DEFAULT_SPACE, segments: image.segments, memory, byteAt: (address) => memory[address]!, ...(image.entry === undefined ? {} : { entry: image.entry }), ...(image.state === undefined ? {} : { state: image.state }) };
1584
- const decoded = await decode(bakedImage, knowledge, [], knowledge.coverage);
1429
+ // Without a changed byte, the baked image is the image: the decode of the base source holds.
1430
+ const decoded = changed.length === 0 ? { instructions: baseSource.instructions, dataOnly: baseSource.dataOnly } : await decodeProgram(bakedImage, knowledge, [], knowledge.coverage);
1585
1431
 
1586
1432
  // 4. The free ranges.
1587
1433
  const regions = effectiveRegions(knowledge.regions);
1588
1434
  const plan = freeRanges(knowledge, memory, decoded.instructions, { changed, keep, drop });
1589
1435
  const free = plan.free;
1590
- const inFree = (address: number) => free.some((range) => address >= range.start && address <= range.end);
1436
+ const inFree = (address: number) => inRanges(free, address);
1591
1437
  const overlapsAny = (start: number, end: number, ranges: readonly AddressRange[]) => ranges.some((range) => start <= range.end && range.start <= end);
1592
1438
  for (const range of free) memory.fill(0, range.start, range.end + 1);
1593
1439
 
@@ -1652,13 +1498,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1652
1498
  const loaderBuilt = await buildLoader(exported.files, exported.laid, exported.loader, exported.loaderMain!, state, new Map());
1653
1499
  if ("diagnostics" in loaderBuilt) return { result: "FAIL", stage: "loader", reason: "loader.asm does not assemble. This is a defect of the script.", diagnostics: loaderBuilt.diagnostics };
1654
1500
  baseline = { program: loaderBuilt.program, symbols: loaderBuilt.symbols, entryFile: "loader.asm" };
1655
- loaderOutput = {
1656
- copies: exported.loader.copies.map((copy) => ({ what: copy.what, to: `${formatC64Address(copy.target.start)}-${formatC64Address(copy.target.end)}` })),
1657
- copier: formatC64Address(exported.loader.copier),
1658
- stackByte: formatC64Address(exported.loader.stackByte),
1659
- simulated: true,
1660
- ...(loaderLimits(exported.loader).length === 0 ? {} : { limits: loaderLimits(exported.loader) }),
1661
- };
1501
+ loaderOutput = { ...loaderPlaces(exported.loader), simulated: true, ...limitsOf(exported.loader) };
1662
1502
  }
1663
1503
  const shownSymbols = baseline.symbols.filter((symbol) => symbol.kind === "address" || symbol.used);
1664
1504
 
@@ -1722,15 +1562,15 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1722
1562
  ...(loaderOutput === undefined ? {} : { loader: loaderOutput }),
1723
1563
  ...(plan.rooted ? {} : { unrooted: "The knowledge has no entry, the program has no BASIC line with SYS, and the image does not hold the hardware vectors. Thus no code is unreachable, and nothing became free by itself." }),
1724
1564
  ...(knowledge.coverage === undefined ? { noCoverage: "The knowledge has no coverage, so nothing became free by itself. Only --drop makes a range free." } : {}),
1725
- free: { bytes: freeBytes, ...listed(free, max, (range) => ({ ...shownRange(range), bytes: range.end - range.start + 1, what: range.what, label: freeName(range) })) },
1726
- unreachableExecuted: listed(plan.unreachableExecuted, max, (range) => ({ ...shownRange(range), ...(range.routine === undefined ? {} : { routine: range.routine }), drop: `--drop '${formatC64Address(range.start)}-${formatC64Address(range.end)}'` })),
1565
+ free: { bytes: freeBytes, ...listed(free, max, (range) => ({ ...formatC64RangeFields(range), bytes: range.end - range.start + 1, what: range.what, label: freeName(range) })) },
1566
+ unreachableExecuted: listed(plan.unreachableExecuted, max, (range) => ({ ...formatC64RangeFields(range), ...(range.routine === undefined ? {} : { routine: range.routine }), drop: `--drop '${formatC64Range(range)}'` })),
1727
1567
  ...(plan.unknown.length === 0 ? {} : { unknownCode: showUnknown(plan, max) }),
1728
1568
  knowledge: kept,
1729
1569
  tests: { written: tests.map((test) => test.file), leftOut: listed(testsLeftOut, max, (item) => item) },
1730
1570
  ...(spacesLeftOut.length === 0 ? {} : { spacesLeftOut }),
1731
1571
  ...(stageLeftOut === undefined ? {} : { startScreenLeftOut: `The start screen is of the captured stage in ${stageLeftOut}, and the export has only the space c64.` }),
1732
- ...(exported.rendered.operandsAsNumbers.length === 0 ? {} : { operandsAsNumbers: listed(exported.rendered.operandsAsNumbers, max, (item) => ({ address: formatC64Address(item.address), expression: item.expression, reason: item.reason })) }),
1733
- ...(exported.rendered.macrosAsInstructions.length === 0 ? {} : { macrosAsInstructions: listed(exported.rendered.macrosAsInstructions, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), macro: item.macro, reason: item.reason })) }),
1572
+ ...(exported.rendered.operandsAsNumbers.length === 0 ? {} : { operandsAsNumbers: listed(exported.rendered.operandsAsNumbers, max, shownOperand) }),
1573
+ ...(exported.rendered.macrosAsInstructions.length === 0 ? {} : { macrosAsInstructions: listed(exported.rendered.macrosAsInstructions, max, shownMacro) }),
1734
1574
  };
1735
1575
  }
1736
1576
 
@@ -1740,7 +1580,7 @@ function isCut(list: unknown): boolean {
1740
1580
  }
1741
1581
 
1742
1582
  /** The same generate command line again, for the run after a change of the knowledge. */
1743
- function generateAgain(call: Call, loader = call.flag("loader")): string {
1583
+ function generateAgain(call: Call, loader: boolean): string {
1744
1584
  const max = call.count("max-listed")!;
1745
1585
  return call.next(
1746
1586
  "generate",