@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.8.0-rc.1",
3
+ "version": "2.8.0-rc.3",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -53,7 +53,8 @@ To get the command list, run the script with no arguments.
53
53
 
54
54
  A source that you generated from the project knowledge has switches in `config.asm`.
55
55
 
56
- - Without `--release`, the build uses the values in `config.asm`. With the default values, the program is the clean program: no copy protection, no trainers, no cheats, no crack changes, and all corrections. This program can be different from the base release. Thus `--compare` can give `FAIL`.
56
+ - Without `--release`, the build uses the values in `config.asm`. With the default values, the program is the clean program: no copy protection, no trainers, no cheats, no crack changes, no leftovers, and all corrections. This program can be different from the base release. Thus `--compare` can give `FAIL`.
57
+ - The default build leaves out the leftovers, because `LEFTOVERS` is 0. A leftover is a range that nothing uses, in a file in `leftovers/`. To build the leftovers, give `--switch LEFTOVERS=1`.
57
58
  - To build other switch values, give `--switch` for each switch, for example `--switch TRAINER=1`. `config.asm` does not change. Do not use `--define` for a switch.
58
59
  - With `--switch` and the entry `main.asm`, a source with `loader.asm` also gives its loader program with these switch values. See "Build".
59
60
  - With `--release <label>`, each switch has the value of that release. A release build does not read `config.asm`.
@@ -132,23 +133,25 @@ Assembles the source and writes the program to `--out`, or to `build/<name>.prg`
132
133
  - `diagnostics`: each item has `severity` (`error`, `warning` or `note`), `file`, `line` and `message`. `file` is relative to the source root. A file in an include folder outside the source root starts with `../`. `file` and `line` are not in an item without a location in the source.
133
134
  - `compare`: only with `--compare`. `identical` is `true` when each segment is identical. `segments` has one item for each segment of the reference program, with `start`, `end` and `result`:
134
135
  - `identical`.
135
- - `different`, with `differences` and `firstDifference`. `firstDifference` gives `address`, and the byte of the build (`built`) and of the reference (`reference`), each as `$` and two hex digits.
136
+ - `different`, with `differences` and `firstDifference`. `firstDifference` gives `address`, and the byte of the build (`built`) and of the reference (`reference`), each as `$` and two hex digits. It is the first different byte outside the leftovers that the build leaves out. When all different bytes are in these leftovers, the segment has no `firstDifference`.
136
137
  - `not covered`, with `uncovered`: the build does not hold all bytes of the segment.
137
- - `loader`: only with `--switch`, the entry `main.asm` and a `loader.asm` in the source root. It is the loader program of these switch values, with `out`, `bytes` and `sha256`. `symbolsFile` is its symbols file. `packed` gives `packedBytes` and `unpackedBytes` of the packed form. `verified` is always `false`, because no check of the loader program runs.
138
+ - A segment in `compare.segments` can also have `leftovers`. These are the leftovers that the build leaves out, where a byte is different or not in the build. Each item has `start`, `end`, `file` (the leftover file, relative to the source root) and `differences`. `differences` and `uncovered` of the segment also count these bytes.
139
+ - `loader`: only with `--switch`, the entry `main.asm` and a `loader.asm` in the source root. It is the loader program of these switch values, with `out`, `bytes` and `sha256`. `symbolsFile` is its symbols file. `packed` gives `packedBytes` and `unpackedBytes` of the packed form. `verified` is always `false`, because no check of the loader program runs. When the script cannot make the loader program, `loader` holds only `written`, which is `false`, and `reason`.
138
140
 
139
141
  Do as the result tells:
140
142
 
141
143
  - `result` is `PASS`: the program is at `out`. To run or debug the program, load the file at `out` into the emulator. A generated source with a loader is different: the build of `main.asm` does not set the entry state, and it can hold bytes for $d000-$dfff. Load the loader program in its place: `loader.program` of the generation of the source with the loader, or `loader.out` of a build with `--switch`. Test the loader program of `loader.out` before you trust it.
142
144
  - `result` is `FAIL` and `assembled` is `false`: the source has errors, and the script wrote no program. `hint` tells you to correct the source. Correct the source at the file and the line of each diagnostic. Then run `build` again.
143
145
  - `result` is `FAIL` and `assembled` is `true`: the program is not identical to the reference. The script wrote the program. Read the first difference of each segment in `compare.segments`. Without `--release`, read the section "Switches" first.
146
+ - A segment has `leftovers`: these bytes are different because the build leaves out the leftovers. They are not an error in the source. `hint` tells when all other bytes are identical. To build the leftovers, give `--switch LEFTOVERS=1`.
144
147
  - `hint` tells that `symbols` is cut: give a larger `--max-listed`, or read the symbols file for the full list.
148
+ - `loader.written` is `false`: the script wrote the program of `main.asm`, but it cannot make the loader program of these switch values. Do as `loader.reason` tells.
145
149
  - Error `not-found` names the entry: give the main source file relative to the source root.
146
150
  - Error `not-found` names an include folder: give `--include` a folder with files, relative to the source root.
147
151
  - Error `invalid-input` names an include folder: the folder is outside the project folder. Give `--include` a folder inside the project folder.
148
152
  - Error `not-found` names a release: the project knowledge has no release with that label. Record the release in the project knowledge, or give the label of a recorded release.
149
153
  - Error `not-found` tells that the knowledge has no program: put the program bytes into the project knowledge. Then use `--compare` again.
150
154
  - Error `invalid-input` names a switch: give `--switch` a switch of `config.asm`, with the value 0 or 1.
151
- - Error `invalid-input` tells you to set the switch values in `config.asm`: this build cannot make the loader program of these switch values. Set the values in `config.asm`. Then generate the source with the loader.
152
155
  - Error `invalid-input`: an option or a path is wrong. Do as `hint` tells. The script refuses `--space` without `--compare` or `--release`.
153
156
 
154
157
  The script does not keep the diagnostics or the program in the project knowledge.
@@ -6,14 +6,16 @@
6
6
  // program with the same values: the build of loader.asm in the plain form,
7
7
  // and in the packed form the pack of the build of main.asm with the build of
8
8
  // loader.asm, the copier, as generate packs it. No check of that loader runs.
9
+ // When the knowledge or the builds do not permit the pack, the build writes
10
+ // the program of main.asm and no loader program, and tells why.
9
11
 
10
12
  import { posix } from "node:path";
11
13
 
12
14
  import { BUILD_DIRECTORY, type BuildKind, buildName, CONFIG_FILE, configValues, COPIER_LINE, symbolsPath, withConfigValues } from "#src/build-name.ts";
13
- import { type AddressRange, formatC64Address } from "#src/c64.ts";
14
- import { Refusal } from "#src/errors.ts";
15
+ import { type AddressRange, formatC64RangeFields } from "#src/c64.ts";
16
+ import { isRefusal, Refusal } from "#src/errors.ts";
15
17
  import { readSourceTree, writeReported } from "#src/host-client/transfer.ts";
16
- import { openForRead } from "#src/knowledge/database.ts";
18
+ import { withRead } from "#src/knowledge/database.ts";
17
19
  import { knowledgeNames } from "#src/knowledge/names.ts";
18
20
  import { releaseImage, requireProgram } from "#src/knowledge/program.ts";
19
21
  import { currentStartScreen, listSwitches, releaseLabeled } from "#src/knowledge/read.ts";
@@ -24,7 +26,7 @@ import { EXOMIZER, findTool } from "#src/native/discover.ts";
24
26
  import { localToolContext } from "#src/native/local.ts";
25
27
  import type { AcmeParams, AssembledSymbol } from "#src/native/types.ts";
26
28
  import { listed as listedItems, OPTIONS, reply, runScript, UsageError } from "#src/script.ts";
27
- import { compareBuild, type Reference } from "#src/compare.ts";
29
+ import { compareBuild, type LeftOutLeftover, type Reference } from "#src/compare.ts";
28
30
 
29
31
  /** The loader of a generated source, which a build of main.asm with --switch also makes. */
30
32
  const LOADER_FILE = "loader.asm";
@@ -51,24 +53,36 @@ function parseSwitches(texts: readonly string[]): Map<string, 0 | 1> {
51
53
  return values;
52
54
  }
53
55
 
54
- /** The default of each switch of a generated source: the knowledge gives them, the start screen is in and the leftovers are out. */
55
- function switchDefaults(space: Space): Map<string, number> {
56
- const db = openForRead();
56
+ /** The message of a refusal of `work`, or undefined when it did not refuse: a refusal of the loader program does not stop the build of main.asm. */
57
+ function refusalOf(work: () => void): string | undefined {
57
58
  try {
58
- return new Map([[START_SCREEN_SWITCH, 1], [LEFTOVERS_SWITCH, 0], ...listSwitches(db, undefined, space).map((row) => [row.name, row.default] as const)]);
59
- } finally {
60
- db?.close();
59
+ work();
60
+ return undefined;
61
+ } catch (error) {
62
+ if (isRefusal(error)) return error.message;
63
+ throw error;
61
64
  }
62
65
  }
63
66
 
64
- /** What the packed form needs from the knowledge: the loaded ranges. Refuses a start screen of a captured stage and a segment below $0400. */
65
- function packedLoaded(leftovers: readonly AddressRange[]): AddressRange[] {
66
- const db = openForRead();
67
- try {
68
- return packedRanges(requireProgram(db).segments, leftovers, currentStartScreen(db)?.stage);
69
- } finally {
70
- db?.close();
71
- }
67
+ /**
68
+ * What a generated source needs from the knowledge of the space, in one read:
69
+ * the default of each switch (the knowledge gives them, the start screen is in
70
+ * and the leftovers are out), and for the packed form, given the leftover
71
+ * ranges of the source, the loaded ranges or why the build gets no loader (a
72
+ * start screen of a captured stage, a segment below $0400).
73
+ */
74
+ function generatedKnowledge(space: Space, leftovers: readonly AddressRange[] | undefined) {
75
+ return withRead((db) => {
76
+ const defaults = new Map<string, number>([[START_SCREEN_SWITCH, 1], [LEFTOVERS_SWITCH, 0], ...listSwitches(db, undefined, space).map((row) => [row.name, row.default] as const)]);
77
+ let loaded: AddressRange[] | undefined;
78
+ const noLoader =
79
+ leftovers === undefined
80
+ ? undefined
81
+ : refusalOf(() => {
82
+ loaded = packedRanges(requireProgram(db, space).segments, leftovers, currentStartScreen(db, space)?.stage);
83
+ });
84
+ return { defaults, loaded, noLoader };
85
+ });
72
86
  }
73
87
 
74
88
  await runScript({
@@ -97,7 +111,7 @@ await runScript({
97
111
  "max-listed": { ...OPTIONS["max-listed"], help: "list at most n symbols (default 50). The count is always given" },
98
112
  },
99
113
  notes:
100
- "Symbol values are $ and at least four hex digits. Before --compare, put the program bytes into the project knowledge. Without --release, the build has the switch values of config.asm and of --switch. With the defaults, this is the clean program, which is not the bytes of a release when a switch has a default that the base release does not have. Give a switch with --switch, not with --define: ACME stops with Symbol already defined. The loader program of --switch is not checked: loader.verified is false.",
114
+ "Symbol values are $ and at least four hex digits. Before --compare, put the program bytes into the project knowledge. Without --release, the build has the switch values of config.asm and of --switch. With the defaults, this is the clean program, which is not the bytes of a release when a switch has a default that the base release does not have. The defaults leave out the leftovers (LEFTOVERS = 0): compare.segments gives each different leftover in leftovers. Give a switch with --switch, not with --define: ACME stops with Symbol already defined. The loader program of --switch is not checked: loader.verified is false.",
101
115
  run: async (call) => {
102
116
  const [sourceRoot, entry] = [call.subject(0), call.subject(1)];
103
117
  // Read the reference before ACME runs, so a project without it stops at once.
@@ -108,8 +122,7 @@ await runScript({
108
122
  if (switches.size > 0 && label !== undefined) throw new UsageError("--switch does not work with --release: a release build has the switch values of that release");
109
123
  let releaseDefine: Record<string, number> = {};
110
124
  if (call.flag("compare") || label !== undefined) {
111
- const db = openForRead();
112
- try {
125
+ withRead((db) => {
113
126
  if (label === undefined) program = requireProgram(db, call.space);
114
127
  else {
115
128
  const release = releaseLabeled(db, label, call.space);
@@ -117,9 +130,7 @@ await runScript({
117
130
  releaseDefine = { [`${RELEASE_DEFINE}${label}`]: 1 };
118
131
  if (call.flag("compare")) program = releaseImage(db, label, call.space);
119
132
  }
120
- } finally {
121
- db?.close();
122
- }
133
+ });
123
134
  }
124
135
  const setPc = call.address("set-pc");
125
136
  const { contents, ...tree } = readSourceTree(sourceRoot, call.strings("include"));
@@ -137,23 +148,30 @@ await runScript({
137
148
  contents[config] = changed;
138
149
  tree.files[config] = { ...tree.files[config]!, size: changed.length };
139
150
  }
151
+ // With --switch, main.asm of a generated source with a loader also gives the loader program of these values.
152
+ const loaderIndex = switches.size > 0 && entry === "main.asm" ? inSource(LOADER_FILE) : -1;
153
+ // The packed form: the loaded ranges are the segments of the program without the leftover files of the source.
154
+ const packedForm = loaderIndex >= 0 && textOf(loaderIndex).split(/\r?\n/).includes(COPIER_LINE);
155
+ // The leftover files of a generated source, each with its range from its first line. A build with LEFTOVERS = 0 skips them; a release has them.
156
+ const folder = posix.join(tree.sourceDir, LEFTOVER_FOLDER);
157
+ const leftovers: LeftOutLeftover[] = tree.files.flatMap((file, index) => {
158
+ const range = posix.dirname(file.path) === folder ? leftoverRange(textOf(index)) : undefined;
159
+ return range === undefined ? [] : [{ ...range, file: `${LEFTOVER_FOLDER}/${posix.basename(file.path)}` }];
160
+ });
161
+ // A source with --switch has config.asm and no --release, so the packed form always gets this read.
162
+ const generated = label === undefined && config >= 0 ? generatedKnowledge(call.space, packedForm ? leftovers : undefined) : undefined;
140
163
  // The name of the build tells what it is: the release, or the switch values.
141
- const kind: BuildKind | undefined = label !== undefined ? { release: label } : config < 0 ? undefined : { values: configValues(textOf(config)), defaults: switchDefaults(call.space) };
164
+ const kind: BuildKind | undefined = label !== undefined ? { release: label } : generated === undefined ? undefined : { values: configValues(textOf(config)), defaults: generated.defaults };
165
+ const leftOut = kind !== undefined && "values" in kind && kind.values.get(LEFTOVERS_SWITCH) === 0 ? leftovers : [];
142
166
  const plain = call.flag("plain");
143
167
  const out = call.string("out") ?? `${BUILD_DIRECTORY}/${buildName(entry, kind, textOf(inSource(entry)))}.${plain ? "bin" : "prg"}`;
144
168
  const params: AcmeParams = { ...tree, entrySource: entry, defines: { ...releaseDefine, ...Object.fromEntries(call.strings("define").map(parseDefine)) }, ...(setPc === undefined ? {} : { setPc }) };
145
169
 
146
- // With --switch, main.asm of a generated source with a loader also gives the loader program of these values.
147
- const loaderIndex = switches.size > 0 && entry === "main.asm" ? inSource(LOADER_FILE) : -1;
148
- let loaded: AddressRange[] | undefined;
149
- if (loaderIndex >= 0 && textOf(loaderIndex).split(/\r?\n/).includes(COPIER_LINE)) {
150
- // The packed form: the loaded ranges are the segments of the program without the leftover files of the source.
151
- const folder = posix.join(tree.sourceDir, LEFTOVER_FOLDER);
152
- const leftovers = tree.files.flatMap((file, index) => (posix.dirname(file.path) === folder ? (leftoverRange(textOf(index)) ?? []) : []));
153
- loaded = packedLoaded(leftovers);
154
- // The toolkit never installs a tool: without Exomizer the build refuses by name before ACME runs.
155
- findTool(EXOMIZER);
156
- }
170
+ const loaded = generated?.loaded;
171
+ // Why the build writes no loader program.
172
+ let noLoader = generated?.noLoader;
173
+ // The toolkit never installs a tool: without Exomizer the build refuses by name before ACME runs.
174
+ if (packedForm && noLoader === undefined) findTool(EXOMIZER);
157
175
 
158
176
  const { result, attachments } = await assemble(params, contents, localToolContext());
159
177
  if (!result.assembled) return reply({ result: "FAIL", assembled: false, diagnostics: result.diagnostics }, { hint: "The source has errors, and no program was written. Correct the source at the file and the line of each diagnostic. Then run build again." });
@@ -165,7 +183,7 @@ await runScript({
165
183
 
166
184
  // The loader is made before a file is written: a refusal writes nothing.
167
185
  let loader: { program: Buffer; symbols: AssembledSymbol[]; packed?: PackedLoader } | undefined;
168
- if (loaderIndex >= 0) {
186
+ if (loaderIndex >= 0 && noLoader === undefined) {
169
187
  const copier = await assemble({ ...params, entrySource: LOADER_FILE }, contents, localToolContext());
170
188
  if (!copier.result.assembled) {
171
189
  const [first] = copier.result.diagnostics;
@@ -178,37 +196,48 @@ await runScript({
178
196
  else {
179
197
  const at = copier.result.symbols!.find((symbol) => symbol.name === COPIER_SOURCE);
180
198
  if (at?.kind !== "address") throw new Refusal("invalid-input", `${LOADER_FILE} has no label ${COPIER_SOURCE} at its copier. Generate the source with the loader again.`);
181
- checkPackedBuilds(built, copierBuild, loaded);
182
- const packed = await packLoader(built, copierBuild, { loaded, copier: at.address }, localToolContext());
183
- loader = { program: packed.program, symbols, packed };
199
+ const packedFrom = loaded;
200
+ noLoader = refusalOf(() => checkPackedBuilds(built, copierBuild, packedFrom));
201
+ if (noLoader === undefined) {
202
+ const packed = await packLoader(built, copierBuild, { loaded: packedFrom, copier: at.address }, localToolContext());
203
+ loader = { program: packed.program, symbols, packed };
204
+ }
184
205
  }
185
206
  }
186
207
 
187
208
  const written = writeReported(out, plain ? built.subarray(2) : built, { what: "--out" });
188
209
  const range = result.loadRange!;
189
- const compared = program === undefined ? undefined : compareBuild(built, program);
210
+ const compared = program === undefined ? undefined : compareBuild(built, program, leftOut);
190
211
  const symbols = listedItems(shown, call.count("max-listed")!, showSymbol, `a larger --max-listed, or read ${symbolsPath(out)}`);
191
212
  // A build that differs from its reference is a failed check.
192
213
  const different = compared !== undefined && !compared.identical;
214
+ // The bytes that differ in the leftovers that the build leaves out, and the other bytes that differ or that the build does not hold.
215
+ const inLeftovers = (compared?.segments ?? []).flatMap((segment) => segment.leftovers ?? []).reduce((sum, leftover) => sum + leftover.differences, 0);
216
+ const others = (compared?.segments ?? []).reduce((sum, segment) => sum + (segment.differences ?? 0) + (segment.uncovered ?? 0), 0) - inLeftovers;
217
+ const leftoverHint = `${inLeftovers} different ${inLeftovers === 1 ? "byte is" : "bytes are"} in leftovers that this build leaves out, because ${LEFTOVERS_SWITCH} is 0. compare.segments gives these leftovers in leftovers, each with its file. To build the leftovers, give --switch ${LEFTOVERS_SWITCH}=1.`;
193
218
  const loaderPath = `${BUILD_DIRECTORY}/${buildName(LOADER_FILE, kind)}.prg`;
194
219
  const hints = [
195
- ...(different ? ["The program is not identical to the reference program. Read compare.segments: each segment that is different gives its first difference."] : []),
196
- ...(different && label === undefined ? ["Without --release, a source with switches builds with the values of config.asm and --switch, and that program can differ from the base release. To check a release, give --release <label> with --compare."] : []),
220
+ ...(different && others > 0 ? [`The program is not identical to the reference program. Read compare.segments: each segment that is different gives its first difference${inLeftovers > 0 ? " outside the leftovers that this build leaves out" : ""}.`] : []),
221
+ ...(different && others === 0 ? ["The program is different from the reference program only in the leftovers that this build leaves out. All other bytes are identical."] : []),
222
+ ...(different && inLeftovers > 0 ? [leftoverHint] : []),
223
+ ...(different && others > 0 && label === undefined ? ["Without --release, a source with switches builds with the values of config.asm and --switch, and that program can differ from the base release. To check a release, give --release <label> with --compare."] : []),
197
224
  ...(symbols.rest === undefined ? [] : [`symbols is cut. To get all symbols, give ${symbols.rest}.`]),
198
225
  ...(loader === undefined ? [] : ["loader.out is the loader program of these switch values. No check of the loader program ran, so loader.verified is false."]),
226
+ ...(noLoader === undefined ? [] : ["The build wrote the program of main.asm, but no loader program of these switch values: loader.reason tells why."]),
199
227
  ];
200
228
  return reply({
201
229
  result: different ? "FAIL" : "PASS",
202
230
  assembled: true,
203
231
  ...written,
204
232
  ...(plain ? { plain: true } : {}),
205
- loadRange: { start: formatC64Address(range.start), end: formatC64Address(range.end), bytes: range.bytes },
233
+ loadRange: { ...formatC64RangeFields(range), bytes: range.bytes },
206
234
  symbols,
207
235
  // The symbols of the program for a test run, in symbols/ next to it.
208
236
  symbolsFile: writeReported(symbolsPath(out), symbolsFileText(shown), { what: "--out" }),
209
237
  ...(all ? {} : { unusedConstants: result.symbols!.length - shown.length }),
210
238
  diagnostics: result.diagnostics,
211
239
  ...(compared === undefined ? {} : { compare: compared }),
240
+ ...(noLoader !== undefined ? { loader: { written: false, reason: noLoader } } : {}),
212
241
  ...(loader === undefined
213
242
  ? {}
214
243
  : {
@@ -2,7 +2,7 @@
2
2
  // Host Runtime and extracts files into the project. T64 tape files and CRT
3
3
  // cartridge files are read locally: no host tool reads them.
4
4
 
5
- import { formatC64Address } from "#src/c64.ts";
5
+ import { formatC64Address, hexWord, prgOf } from "#src/c64.ts";
6
6
  import { isRefusal, Refusal } from "#src/errors.ts";
7
7
  import { DISK_BLOCK_BYTES, DISK_IMAGE_TYPES, inspectDisk, MAX_DISK_SECTORS } from "#src/host-client/tools.ts";
8
8
  import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
@@ -68,7 +68,7 @@ function tapeDirectory(image: string) {
68
68
  /** A CRT cartridge file: its header and CHIP packets, each with the PRG file name that crt writes. */
69
69
  function cartridge(image: string) {
70
70
  const crt = about(image, () => parseCrt(readProjectFile(image).bytes));
71
- const chips = crt.chips.map((chip) => ({ bank: chip.bank, address: formatC64Address(chip.address), size: chip.size, space: `bank${chip.bank}`, file: `bank${chip.bank}-${chip.address.toString(16).padStart(4, "0")}.prg` }));
71
+ const chips = crt.chips.map((chip) => ({ bank: chip.bank, address: formatC64Address(chip.address), size: chip.size, space: `bank${chip.bank}`, file: `bank${chip.bank}-${hexWord(chip.address)}.prg` }));
72
72
  return { crt, header: { name: crt.name, type: crt.type, typeName: crt.typeName, exrom: crt.exrom, game: crt.game, ...(crt.mode === undefined ? {} : { mode: crt.mode }) }, chips };
73
73
  }
74
74
 
@@ -196,7 +196,7 @@ await runScript({
196
196
  kindFor("crt", image, ["crt"]);
197
197
  const out = call.string("out")!;
198
198
  const { crt, header, chips } = cartridge(image);
199
- const files = crt.chips.map((chip, index) => writeReported(`${out}/${chips[index]!.file}`, Buffer.concat([Buffer.from([chip.address & 0xff, chip.address >> 8]), chip.data]), { what: "--out" }));
199
+ const files = crt.chips.map((chip, index) => writeReported(`${out}/${chips[index]!.file}`, prgOf(chip.address, chip.data), { what: "--out" }));
200
200
  files.push(writeReported(`${out}/crt.json`, `${JSON.stringify({ ...header, chips }, null, 2)}\n`, { what: "--out" }));
201
201
  return reply({ ...header, chips, files }, { hint: "All banks use the same addresses. Analyze each bank PRG in its own knowledge space: the field space of its chip gives the space." });
202
202
  },
@@ -3,7 +3,7 @@
3
3
  // load address; a T64 file holds a directory of PRG files. TAP files hold
4
4
  // raw pulses and go through the emulator only.
5
5
 
6
- import { formatC64Address, petsciiNameToText } from "#src/c64.ts";
6
+ import { formatC64Address, petsciiNameToText, prgOf } from "#src/c64.ts";
7
7
  import { Refusal } from "#src/errors.ts";
8
8
  import { hasSignature } from "#src/media.ts";
9
9
 
@@ -118,5 +118,5 @@ export function parseT64(bytes: Uint8Array): Tape {
118
118
 
119
119
  /** The PRG of a tape entry: its start address, then its bytes. */
120
120
  export function tapeFile(bytes: Uint8Array, entry: TapeEntry): Buffer {
121
- return Buffer.concat([Buffer.from([entry.start & 0xff, entry.start >> 8]), Buffer.from(bytes.subarray(entry.offset, entry.offset + entry.bytes))]);
121
+ return prgOf(entry.start, bytes.subarray(entry.offset, entry.offset + entry.bytes));
122
122
  }
@@ -67,7 +67,7 @@ Get the values for the commands from these places:
67
67
 
68
68
  A group folder holds one project for each version of a program. It also holds the pages that the versions share.
69
69
 
70
- - A group folder is a folder in a git repository. It holds one or more project folders. It is not a project, and it is not in a project.
70
+ - A group folder is a folder in a git repository. It holds two or more project folders. It is not a project, and it is not in a project.
71
71
  - Each project folder in the group folder is a project of the group. The label of the project is the name of its folder, for example `v1`. A project folder that holds `.git` is not a project of the group.
72
72
  - The shared pages are `README.md` and `docs/` of the group folder.
73
73
  - A page in the group folder can link to each file in the group folder. A link out of the group folder is a problem.
@@ -9,17 +9,17 @@ import { existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs
9
9
  import { basename, join, posix } from "node:path";
10
10
  import type { DatabaseSync } from "node:sqlite";
11
11
 
12
- import { formatC64Address } from "#src/c64.ts";
12
+ import { formatC64Address, formatC64RangeFields, inRanges } from "#src/c64.ts";
13
13
  import { Refusal } from "#src/errors.ts";
14
14
  import { WireFailure } from "#src/host-client/tools.ts";
15
15
  import { writeProjectFile, writeReported } from "#src/host-client/transfer.ts";
16
16
  import { conflicts } from "#src/knowledge/conflicts.ts";
17
- import { openForRead, TEXT_DIRECTORY } from "#src/knowledge/database.ts";
17
+ import { openForRead, withRead } from "#src/knowledge/database.ts";
18
18
  import { changedEvidence, type EvidenceChange } from "#src/knowledge/evidence.ts";
19
- import { programImage, type ProgramImage } from "#src/knowledge/program.ts";
19
+ import { programImage } from "#src/knowledge/program.ts";
20
20
  import { listComments, listModules, listReferences, listRegions, listSymbols, sourceRevision } from "#src/knowledge/read.ts";
21
21
  import { compareText } from "#src/knowledge/text.ts";
22
- import { groupOf, namedGroup, PROJECT_DIRECTORY, projectRoot, resolveProjectFile, resolveProjectPath, type ProjectGroup } from "#src/project.ts";
22
+ import { groupOf, KNOWLEDGE_TEXT_DIRECTORY as TEXT_DIRECTORY, namedGroup, PROJECT_DIRECTORY, projectRoot, resolveProjectFile, resolveProjectPath, type ProjectGroup } from "#src/project.ts";
23
23
  import { GENERATED_MARK, referenceStamp } from "#src/reference-pages.ts";
24
24
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
25
25
  import { checkLinks, linkPage, type Files, type LinkContext, type Names, type Problem } from "./lib/links.ts";
@@ -62,11 +62,8 @@ function generate(call: Call): Reply {
62
62
  }
63
63
  }
64
64
  const map = readSourceMap(source);
65
- const db = openForRead();
66
- let knowledge;
67
- let image: ProgramImage | undefined;
68
- try {
69
- image = programImage(db, map.space);
65
+ const { image, knowledge } = withRead((db) => {
66
+ const image = programImage(db, map.space);
70
67
  const found = conflicts(db).length;
71
68
  if (found > 0) throw new Refusal("conflict", `The knowledge has ${found} conflict${found === 1 ? "" : "s"} from a git merge. Nothing was written. Resolve the merge conflicts of the project knowledge. Then generate the source again from the knowledge, and run generate again.`);
72
69
  // A source of another revision has other lines: the links would point to the wrong code. A change in another space does not change the source.
@@ -74,7 +71,7 @@ function generate(call: Call): Reply {
74
71
  if (map.revision !== revision) {
75
72
  throw new WireFailure("invalid-input", `${map.mapPath} is from knowledge revision ${map.revision}, and the knowledge of the source is at revision ${revision}. Nothing was written. Generate the source again from the knowledge. Then run generate again.`);
76
73
  }
77
- knowledge = {
74
+ const knowledge = {
78
75
  revision,
79
76
  symbols: listSymbols(db, undefined, undefined, undefined, map.space),
80
77
  regions: listRegions(db, undefined, undefined, undefined, map.space),
@@ -82,15 +79,14 @@ function generate(call: Call): Reply {
82
79
  references: listReferences(db, undefined, undefined, undefined, map.space),
83
80
  modules: listModules(db, undefined, undefined, map.space),
84
81
  };
85
- } finally {
86
- db?.close();
87
- }
82
+ return { image, knowledge };
83
+ });
88
84
  const old = oldFiles(out, directory);
89
85
  const built = buildReference({
90
86
  out: posix.normalize(out),
91
87
  map,
92
88
  ...knowledge,
93
- ...(image === undefined ? {} : { image: { byteAt: image.byteAt, inImage: (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end) } }),
89
+ ...(image === undefined ? {} : { image: { byteAt: image.byteAt, inImage: (address: number) => inRanges(image.segments, address) } }),
94
90
  });
95
91
  for (const path of old) rmSync(join(directory, path), { force: true });
96
92
  const written = built.files.map((file) => writeReported(file.path, file.bytes, { what: "--out" }));
@@ -100,7 +96,7 @@ function generate(call: Call): Reply {
100
96
  const gaps = {
101
97
  routinesWithoutComment: listed(built.gaps.routinesWithoutComment, max, (routine) => ({ name: routine.name, address: formatC64Address(routine.address), file: routine.file })),
102
98
  modulesWithoutRoutines: listed(built.gaps.modulesWithoutRoutines, max, (module) => ({ file: module.file, start: formatC64Address(module.start), ...(module.title === undefined ? {} : { title: module.title }) })),
103
- tablesWithoutName: listed(built.gaps.tablesWithoutName, max, (table) => ({ start: formatC64Address(table.start), end: formatC64Address(table.end), type: table.type })),
99
+ tablesWithoutName: listed(built.gaps.tablesWithoutName, max, (table) => ({ ...formatC64RangeFields(table), type: table.type })),
104
100
  };
105
101
  const hints: string[] = [];
106
102
  if (image === undefined) hints.push("The knowledge has no program bytes. Thus the reference does not decode the tables and does not show the graphics. To get them, put the program bytes into the project knowledge and run generate again.");
@@ -280,15 +276,11 @@ function link(call: Call): Reply {
280
276
  /** The evidence of a project that no page names. */
281
277
  const readEvidence = (member: Member) => {
282
278
  if (evidenceRead.has(member) || unreadableKnowledge.has(member)) return;
283
- let db: DatabaseSync | undefined;
284
279
  try {
285
- db = openForRead(member.root);
286
- addEvidence(member, db);
280
+ withRead((db) => addEvidence(member, db), member.root);
287
281
  } catch (error) {
288
282
  if (!(error instanceof Refusal)) throw error;
289
283
  markUnreadable(member, error);
290
- } finally {
291
- db?.close();
292
284
  }
293
285
  };
294
286
 
@@ -71,7 +71,7 @@ const relative = (page: string, target: string) => {
71
71
  return fragment === undefined ? shown : `${shown}#${fragment}`;
72
72
  };
73
73
  /** The project path of a link target, without its fragment; undefined for a link out of the project (a URL, or a page anchor only). */
74
- export function targetPath(page: string, target: string): string | undefined {
74
+ function targetPath(page: string, target: string): string | undefined {
75
75
  if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith("#")) return undefined;
76
76
  const raw = target.split("#")[0]!;
77
77
  let path = raw;
@@ -30,7 +30,7 @@ export function proseLines(text: string): Array<{ text: string; prose: boolean }
30
30
  }
31
31
 
32
32
  /** The id that GitHub and VS Code give a heading: lower case, without punctuation, spaces as hyphens. */
33
- export function headingSlug(heading: string): string {
33
+ function headingSlug(heading: string): string {
34
34
  const text = heading
35
35
  .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
36
36
  .replace(/<[^>]+>/g, "")
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { posix } from "node:path";
7
7
 
8
- import { formatC64Address, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
8
+ import { formatC64Address, hexWord, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
9
9
  import { IO_RAM } from "#src/host-client/coverage.ts";
10
10
  import { bitmapFrame, charsetFrame, encodePng, PATTERN_PALETTES, scaleFrame, screenText, spriteSheet, type GraphicsMode } from "#src/graphics.ts";
11
11
  import { mermaidGraph, ownerOf, routineEdges, routineHeads, type GraphReference, type RoutineHead } from "#src/knowledge/graph.ts";
@@ -65,6 +65,23 @@ const hex = (address: number) => formatC64Address(address).toUpperCase();
65
65
  const range = (start: number, end: number) => (start === end ? hex(start) : `${hex(start)}-${hex(end)}`);
66
66
  const stem = (file: string) => file.replace(/\.asm$/, "");
67
67
 
68
+ /** The references with a target in [start, end], in their order in `references`: a binary search in the references sorted by target. */
69
+ function byTarget(references: readonly ReferenceRow[]): (start: number, end: number) => ReferenceRow[] {
70
+ const sorted = references.map((reference, index) => ({ reference, index })).sort((a, b) => a.reference.to - b.reference.to);
71
+ return (start, end) => {
72
+ let low = 0;
73
+ let high = sorted.length;
74
+ while (low < high) {
75
+ const middle = (low + high) >> 1;
76
+ if (sorted[middle]!.reference.to < start) low = middle + 1;
77
+ else high = middle;
78
+ }
79
+ const hits: Array<{ reference: ReferenceRow; index: number }> = [];
80
+ for (let at = low; at < sorted.length && sorted[at]!.reference.to <= end; at++) hits.push(sorted[at]!);
81
+ return hits.sort((a, b) => a.index - b.index).map((hit) => hit.reference);
82
+ };
83
+ }
84
+
68
85
  interface Entry {
69
86
  name: string;
70
87
  address: number;
@@ -115,7 +132,16 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
115
132
  for (const label of map.labels) if (!sourceNameAt.has(label.address)) sourceNameAt.set(label.address, label.name);
116
133
 
117
134
  // --- Links ------------------------------------------------------------------
118
- const rel = (page: string, target: string) => posix.relative(posix.dirname(page), target) || posix.basename(target);
135
+ const relCache = new Map<string, string>();
136
+ const rel = (page: string, target: string) => {
137
+ const key = `${page}\n${target}`;
138
+ let found = relCache.get(key);
139
+ if (found === undefined) {
140
+ found = posix.relative(posix.dirname(page), target) || posix.basename(target);
141
+ relCache.set(key, found);
142
+ }
143
+ return found;
144
+ };
119
145
  const codeOfName = (page: string, name: string) => {
120
146
  const label = map.labelOf(name);
121
147
  return label === undefined ? `\`${name}\`` : `[\`${name}\`](${rel(page, map.pathOf(label.file))}#L${label.line})`;
@@ -163,6 +189,8 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
163
189
  */
164
190
  const named = new Set(input.symbols.map((symbol) => symbol.address));
165
191
  const dataReferences = input.references.filter((reference) => !(reference.to >= IO_RAM.start && reference.to <= IO_RAM.end && input.image?.inImage(reference.to) === true && !named.has(reference.to)));
192
+ const dataReferencesTo = byTarget(dataReferences);
193
+ const referencesTo = byTarget(input.references);
166
194
  /**
167
195
  * How the source line of a reference uses a platform name, as the source writes it: "named", "indexed"
168
196
  * (name,x or name,y: the index can reach the registers after it), or undefined when the line does not
@@ -181,8 +209,8 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
181
209
  const use = platform === undefined ? undefined : new RegExp(`(?<![\\w.])${platform}(?!\\w)([^,)]*,\\s*[xXyY]\\b)?`);
182
210
  // A routine with an indexed use and a direct use shows once, as indexed.
183
211
  const owners = new Map<string, boolean>();
184
- for (const reference of dataReferences) {
185
- if (reference.kind !== kind || reference.to < start || reference.to > end) continue;
212
+ for (const reference of dataReferencesTo(start, end)) {
213
+ if (reference.kind !== kind) continue;
186
214
  const how = use === undefined ? "named" : platformUse(reference, use);
187
215
  if (how === undefined) continue;
188
216
  const name = ownerAt(reference.from)?.name ?? hex(reference.from);
@@ -224,13 +252,17 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
224
252
  symbolKinds.get(address) === "routine" || symbolKinds.get(address) === "label" || input.regions.some((region) => (region.type === "code" || region.type === "jumps") && region.start <= address && region.end >= address);
225
253
  const dispatches: GraphReference[] = [];
226
254
  for (const [table, rows] of tableEntries) {
227
- const readers = input.references.filter((reference) => TABLE_READS.includes(reference.kind) && reference.to >= table.start && reference.to <= table.end).map((reference) => reference.from);
255
+ const readers = referencesTo(table.start, table.end).filter((reference) => TABLE_READS.includes(reference.kind)).map((reference) => reference.from);
228
256
  for (const row of rows) if (row.target !== undefined && table.type !== "words" && inCode(row.target)) for (const from of new Set(readers)) dispatches.push({ from, to: row.target, kind: "table" });
229
257
  }
230
258
  const graphReferences: GraphReference[] = [...input.references, ...dispatches];
231
259
  const heads = routineHeads(input.symbols, graphReferences, (address) => sourceNameAt.get(address) ?? hex(address));
232
260
  const boundaries = input.modules.map((module) => module.start);
233
- const ownerAt = (address: number) => ownerOf(heads, boundaries, address);
261
+ const ownerCache = new Map<number, RoutineHead | undefined>();
262
+ const ownerAt = (address: number) => {
263
+ if (!ownerCache.has(address)) ownerCache.set(address, ownerOf(heads, boundaries, address));
264
+ return ownerCache.get(address);
265
+ };
234
266
  const site = (page: string, from: number) => {
235
267
  const owner = ownerAt(from);
236
268
  const named = owner === undefined ? undefined : entries.has(owner.name) ? entryOfName(page, owner.name, owner.name) : codeOfName(page, owner.name);
@@ -260,13 +292,27 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
260
292
  const write = (path: string, lines: string[]) => files.push({ path, bytes: Buffer.from(`${[header, ...lines].join("\n").replace(/\n{3,}/g, "\n\n")}\n`, "utf8") });
261
293
 
262
294
  // --- One entry --------------------------------------------------------------
295
+ const commentsAt = new Map<number, CommentRow[]>();
296
+ for (const comment of input.comments) {
297
+ const list = commentsAt.get(comment.address);
298
+ if (list === undefined) commentsAt.set(comment.address, [comment]);
299
+ else list.push(comment);
300
+ }
263
301
  const commentLines = (address: number) =>
264
- input.comments
265
- .filter((comment) => comment.address === address)
302
+ [...(commentsAt.get(address) ?? [])]
266
303
  .sort((a, b) => (a.placement === b.placement ? 0 : a.placement === "line" ? -1 : 1))
267
304
  .map((comment) => comment.text.replace(/\s*\r?\n\s*/g, " ").trim());
268
- const incoming = (entry: Entry) => dataReferences.filter((reference) => reference.to >= entry.address && reference.to <= entry.spanEnd);
269
- const outgoing = (head: RoutineHead) => input.references.filter((reference) => ownerAt(reference.from)?.address === head.address);
305
+ const incoming = (entry: Entry) => dataReferencesTo(entry.address, entry.spanEnd);
306
+ /** The references from the code of each routine, in their order in the knowledge. */
307
+ const fromHead = new Map<number, ReferenceRow[]>();
308
+ for (const reference of input.references) {
309
+ const owner = ownerAt(reference.from)?.address;
310
+ if (owner === undefined) continue;
311
+ const list = fromHead.get(owner);
312
+ if (list === undefined) fromHead.set(owner, [reference]);
313
+ else list.push(reference);
314
+ }
315
+ const outgoing = (head: RoutineHead) => fromHead.get(head.address) ?? [];
270
316
  const entryText = (page: string, entry: Entry, labels: readonly Entry[]): string[] => {
271
317
  const lines = ["", `<a id="${entry.name}"></a>`, `### ${codeOfName(page, entry.name)} \`${entry.spanEnd > entry.address ? range(entry.address, entry.spanEnd) : hex(entry.address)}\``, "", `*${entry.kind}*`];
272
318
  const comments = commentLines(entry.address);
@@ -317,7 +363,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
317
363
  for (const reference of input.references) if (reference.kind === "call" || reference.kind === "jump") entersAt.set(reference.to, [...(entersAt.get(reference.to) ?? []), reference]);
318
364
  // A pointer to code (lda #<irq_handler) is a vector: the CPU enters there from no file.
319
365
  const pointedAt = new Set(input.references.filter((reference) => reference.kind === "pointer").map((reference) => reference.to));
320
- const tableAnchor = (table: RegionRow) => entryAt.get(table.start)?.name ?? `table_${table.start.toString(16).padStart(4, "0")}`;
366
+ const tableAnchor = (table: RegionRow) => entryAt.get(table.start)?.name ?? `table_${hexWord(table.start)}`;
321
367
  function tableLink(page: string, table: RegionRow): string {
322
368
  return `[\`${entryAt.get(table.start)?.name ?? range(table.start, table.end)}\`](${rel(page, posix.join(out, "tables.md"))}#${tableAnchor(table)})`;
323
369
  }
@@ -404,7 +450,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
404
450
  lines.push("", `<a id="${tableAnchor(table)}"></a>`, `## ${name === undefined ? `\`${range(table.start, table.end)}\`` : `${codeOfName(page, name.name)} \`${range(table.start, table.end)}\``}`, "", `*${table.type}*`);
405
451
  const comments = commentLines(table.start);
406
452
  if (comments.length > 0) lines.push("", ...comments);
407
- const readers = [...new Set(input.references.filter((reference) => reference.to >= table.start && reference.to <= table.end && TABLE_READS.includes(reference.kind)).map((reference) => site(page, reference.from)))];
453
+ const readers = [...new Set(referencesTo(table.start, table.end).filter((reference) => TABLE_READS.includes(reference.kind)).map((reference) => site(page, reference.from)))];
408
454
  if (readers.length > 0) lines.push("", `- **Read by:** ${capped(readers)}`);
409
455
  const rows = tableEntries.get(table);
410
456
  if (rows === undefined) continue;
@@ -430,7 +476,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
430
476
  ];
431
477
  if (input.image === undefined && graphics.length > 0) lines.push("", "Put the program bytes into the project knowledge. Then generate the reference again to show the graphics.");
432
478
  for (const region of graphics) {
433
- const anchor = entryAt.get(region.start)?.name ?? `${region.type}_${region.start.toString(16).padStart(4, "0")}`;
479
+ const anchor = entryAt.get(region.start)?.name ?? `${region.type}_${hexWord(region.start)}`;
434
480
  const name = entryAt.get(region.start);
435
481
  lines.push("", `<a id="${anchor}"></a>`, `## ${name === undefined ? codeOfAddress(page, region.start) : pair(page, name.name, region.start)} \`${range(region.start, region.end)}\``, "", `*${region.type}*`);
436
482
  const comments = commentLines(region.start);