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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +12 -7
  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 +10 -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 +142 -41
  47. package/skills/c64-unpacker/scripts/unpacker.ts +85 -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 +43 -71
  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
@@ -2,42 +2,42 @@
2
2
  // .c64-re-tools/knowledge/; .c64-re-tools/local/knowledge.db is an index
3
3
  // that is made again from the text when the text changed.
4
4
 
5
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
6
- import { DatabaseSync } from "node:sqlite";
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { DatabaseSync, type StatementSync } from "node:sqlite";
7
7
  import { join } from "node:path";
8
8
 
9
9
  import { Refusal } from "../errors.ts";
10
- import { ensureLocal, LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRoot } from "../project.ts";
10
+ import { ensureLocal, KNOWLEDGE_INDEX_FILE, KNOWLEDGE_TEXT_DIRECTORY, LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRoot } from "../project.ts";
11
11
  import { ensureSchema } from "./schema.ts";
12
- import { compareText, loadText, readText, REVISIONS_FILE, revisionsText, sha256, sqlName, TABLES, tableText, writeAtomic } from "./text.ts";
12
+ import { compareText, knowledgeFiles, loadText, readText, REVISIONS_FILE, revisionsText, sha256, sqlName, TABLES, tableText, writeAtomic } from "./text.ts";
13
13
 
14
- export const KNOWLEDGE_DIRECTORY = PROJECT_DIRECTORY;
15
- /** The folder of the committed knowledge text. */
16
- export const TEXT_DIRECTORY = "knowledge";
17
- /** The index file in .c64-re-tools/local/. */
18
- export const INDEX_FILE = "knowledge.db";
19
14
  /** Git keeps the lines of both sides when two computers changed the same knowledge file. */
20
15
  // eol=lf: with core.autocrlf (the Windows default) git would check the files out with CRLF, so two computers would hold other bytes.
21
16
  export const GIT_ATTRIBUTES = "# The knowledge of c64-re-tools: git keeps the lines of both sides of a merge, with LF line ends on every system.\n*.jsonl merge=union text eol=lf\n.gitattributes text eol=lf\n";
22
17
 
23
18
  /** The folder of the knowledge text: .c64-re-tools/knowledge/. */
24
19
  export function textPath(root: string = projectRoot()): string {
25
- return join(root, KNOWLEDGE_DIRECTORY, TEXT_DIRECTORY);
20
+ return join(root, PROJECT_DIRECTORY, KNOWLEDGE_TEXT_DIRECTORY);
26
21
  }
27
22
 
28
23
  /** The index: .c64-re-tools/local/knowledge.db. */
29
24
  export function indexPath(root: string = projectRoot()): string {
30
- return join(root, KNOWLEDGE_DIRECTORY, LOCAL_DIRECTORY, INDEX_FILE);
25
+ return join(root, PROJECT_DIRECTORY, LOCAL_DIRECTORY, KNOWLEDGE_INDEX_FILE);
31
26
  }
32
27
 
33
- /** Refuses a project that has only the knowledge.db of an older c64-re-tools. */
34
- function refuseOldLayout(root: string): void {
35
- if (!existsSync(textPath(root)) && existsSync(join(root, KNOWLEDGE_DIRECTORY, INDEX_FILE))) {
36
- throw new Refusal(
37
- "unsupported-schema",
38
- `${KNOWLEDGE_DIRECTORY}/${INDEX_FILE} is the knowledge of an older c64-re-tools. This c64-re-tools keeps the knowledge as text in ${KNOWLEDGE_DIRECTORY}/${TEXT_DIRECTORY}/. Convert it one time with distribution/convert-knowledge.ts of the c64-re-tools source repository.`,
39
- );
40
- }
28
+ /** The prepared statements of each database by their SQL: a query that runs again is not prepared again. */
29
+ const statements = new WeakMap<DatabaseSync, Map<string, StatementSync>>();
30
+
31
+ /** The statement of `sql` on `db`, prepared once for each database; undefined without a database. */
32
+ export function prepare(db: DatabaseSync, sql: string): StatementSync;
33
+ export function prepare(db: DatabaseSync | undefined, sql: string): StatementSync | undefined;
34
+ export function prepare(db: DatabaseSync | undefined, sql: string): StatementSync | undefined {
35
+ if (db === undefined) return undefined;
36
+ let known = statements.get(db);
37
+ if (known === undefined) statements.set(db, (known = new Map()));
38
+ let statement = known.get(sql);
39
+ if (statement === undefined) known.set(sql, (statement = db.prepare(sql)));
40
+ return statement;
41
41
  }
42
42
 
43
43
  function configure(db: DatabaseSync): void {
@@ -51,7 +51,7 @@ function open(path: string, readOnly: boolean): DatabaseSync {
51
51
  configure(db);
52
52
  db.prepare("SELECT count(*) FROM sqlite_master").get();
53
53
  } catch (error) {
54
- throw new Refusal("invalid-database", `${KNOWLEDGE_DIRECTORY}/${LOCAL_DIRECTORY}/${INDEX_FILE} is not a readable SQLite database: ${(error as Error).message} Delete it: it is made again from the knowledge text.`);
54
+ throw new Refusal("invalid-database", `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/${KNOWLEDGE_INDEX_FILE} is not a readable SQLite database: ${(error as Error).message} Delete it: it is made again from the knowledge text.`);
55
55
  }
56
56
  return db;
57
57
  }
@@ -90,6 +90,12 @@ function textHashes(files: ReadonlyMap<string, { sha256: string }>): Record<stri
90
90
  return Object.fromEntries([...files].map(([name, file]): [string, string] => [name, file.sha256]).sort(([a], [b]) => compareText(a, b)));
91
91
  }
92
92
 
93
+ /** The SHA-256 of each knowledge file of the project, by file name: the bytes only, without the text of the rows. */
94
+ function currentHashes(root: string): Record<string, string> {
95
+ const directory = textPath(root);
96
+ return Object.fromEntries(knowledgeFiles(directory).map((name) => [name, sha256(readFileSync(join(directory, name)))]));
97
+ }
98
+
93
99
  const sameHashes = (a: Record<string, string>, b: Record<string, string>) => JSON.stringify(Object.entries(a).sort()) === JSON.stringify(Object.entries(b).sort());
94
100
 
95
101
  /**
@@ -98,14 +104,13 @@ const sameHashes = (a: Record<string, string>, b: Record<string, string>) => JSO
98
104
  * transaction, so two processes never make the index at the same time.
99
105
  */
100
106
  function freshen(db: DatabaseSync, root: string): void {
107
+ if (sameHashes(currentHashes(root), storedHashes(db))) return;
101
108
  const files = readText(textPath(root));
102
- const hashes = textHashes(files);
103
- if (sameHashes(hashes, storedHashes(db))) return;
104
109
  db.exec("DELETE FROM evidence");
105
110
  for (const spec of TABLES) db.exec(`DELETE FROM ${sqlName(spec.table)}`);
106
111
  db.exec("DELETE FROM revisions");
107
112
  loadText(db, files);
108
- storeHashes(db, hashes);
113
+ storeHashes(db, textHashes(files));
109
114
  }
110
115
 
111
116
  /** The project of each index opened for a write: its writes go to the text too. */
@@ -117,18 +122,27 @@ const projects = new WeakMap<DatabaseSync, string>();
117
122
  * knowledge text: that reads as empty knowledge, and a read creates nothing.
118
123
  */
119
124
  export function openForRead(root: string = projectRoot()): DatabaseSync | undefined {
120
- refuseOldLayout(root);
121
125
  if (!existsSync(textPath(root))) return undefined;
122
126
  const index = openIndex(root);
123
127
  try {
124
128
  // The lock is taken only when the text changed: a read does not wait for a long write that keeps the index fresh.
125
- if (!sameHashes(textHashes(readText(textPath(root))), storedHashes(index))) transaction(index, () => freshen(index, root));
129
+ if (!sameHashes(currentHashes(root), storedHashes(index))) transaction(index, () => freshen(index, root));
126
130
  } finally {
127
131
  index.close();
128
132
  }
129
133
  return open(indexPath(root), true);
130
134
  }
131
135
 
136
+ /** Runs `work` on the knowledge opened for a read (undefined when the project has none), and closes it. */
137
+ export function withRead<T>(work: (db: DatabaseSync | undefined) => T, root: string = projectRoot()): T {
138
+ const db = openForRead(root);
139
+ try {
140
+ return work(db);
141
+ } finally {
142
+ db?.close();
143
+ }
144
+ }
145
+
132
146
  /**
133
147
  * Opens the project's knowledge for a write: it creates
134
148
  * .c64-re-tools/knowledge/ with its .gitattributes when needed, and the index.
@@ -136,7 +150,6 @@ export function openForRead(root: string = projectRoot()): DatabaseSync | undefi
136
150
  * files.
137
151
  */
138
152
  export function openForWrite(root: string = projectRoot()): DatabaseSync {
139
- refuseOldLayout(root);
140
153
  mkdirSync(textPath(root), { recursive: true });
141
154
  const attributes = join(textPath(root), ".gitattributes");
142
155
  if (!existsSync(attributes)) writeFileSync(attributes, GIT_ATTRIBUTES);
@@ -158,7 +171,6 @@ export function openForWrite(root: string = projectRoot()): DatabaseSync {
158
171
  * nothing outside the database it gets.
159
172
  */
160
173
  export function withWrite<T>(work: (db: DatabaseSync) => T, root: string = projectRoot()): T {
161
- refuseOldLayout(root);
162
174
  if (!existsSync(textPath(root))) {
163
175
  const trial = new DatabaseSync(":memory:");
164
176
  try {
@@ -196,7 +208,7 @@ function writeText(db: DatabaseSync, root: string, before: string): void {
196
208
  };
197
209
  write(REVISIONS_FILE, revisionsText(db));
198
210
  for (const spec of TABLES) {
199
- const changed = db.prepare(`SELECT 1 FROM ${sqlName(spec.table)} WHERE valid_from_revision > ? OR valid_to_revision > ? LIMIT 1`).get(before, before);
211
+ const changed = prepare(db, `SELECT 1 FROM ${sqlName(spec.table)} WHERE valid_from_revision > ? OR valid_to_revision > ? LIMIT 1`).get(before, before);
200
212
  if (changed !== undefined) write(spec.file, tableText(db, spec));
201
213
  }
202
214
  storeHashes(db, hashes);
@@ -2,12 +2,12 @@
2
2
  // is now. A revision keeps the SHA-256 of each file that it rests on, so a
3
3
  // file that is gone or that changed since then shows here.
4
4
 
5
- import { createHash } from "node:crypto";
6
5
  import { readFileSync } from "node:fs";
7
6
  import type { DatabaseSync } from "node:sqlite";
8
7
 
9
8
  import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, resolveProjectFile } from "../project.ts";
10
9
  import { coverageRuns } from "./read.ts";
10
+ import { sha256 } from "./text.ts";
11
11
 
12
12
  /** A file of the evidence that is not as the knowledge gives it: missing, or with other bytes. */
13
13
  export interface EvidenceChange {
@@ -21,7 +21,7 @@ export interface EvidenceChange {
21
21
  /** The SHA-256 of a project file, or undefined when it is not there. */
22
22
  function fileHash(root: string, path: string): string | undefined {
23
23
  try {
24
- return createHash("sha256").update(readFileSync(resolveProjectFile(path, root))).digest("hex");
24
+ return sha256(readFileSync(resolveProjectFile(path, root)));
25
25
  } catch {
26
26
  return undefined;
27
27
  }
@@ -3,8 +3,8 @@
3
3
  // graph as a mermaid flowchart. The callers give the rows, so the graph needs
4
4
  // no database and the documentation and the knowledge script draw one graph.
5
5
 
6
- import { formatC64Address } from "../c64.ts";
7
- import type { ReferenceKind, SymbolKind } from "./schema.ts";
6
+ import { formatC64Address, hexWord, type ReferenceKind } from "../c64.ts";
7
+ import type { SymbolKind } from "./schema.ts";
8
8
 
9
9
  /** How one routine reaches another: a call, a jump, or an entry of a table of addresses. */
10
10
  export type EdgeKind = "call" | "jump" | "table";
@@ -92,7 +92,7 @@ const ARROWS: Record<EdgeKind, string> = { call: "-->", table: "==>", jump: "-.-
92
92
  export function mermaidGraph(heads: readonly RoutineHead[], edges: readonly GraphEdge[], own: ReadonlySet<number> = new Set()): string {
93
93
  const used = new Set(edges.flatMap((edge) => [edge.from, edge.to]));
94
94
  for (const address of own) used.add(address);
95
- const id = (address: number) => `n${address.toString(16).padStart(4, "0")}`;
95
+ const id = (address: number) => `n${hexWord(address)}`;
96
96
  const lines = ["flowchart LR"];
97
97
  for (const head of heads) {
98
98
  if (!used.has(head.address)) continue;
@@ -5,34 +5,10 @@ import type { DatabaseSync } from "node:sqlite";
5
5
 
6
6
  import { Refusal } from "../errors.ts";
7
7
  import {
8
- COMMENT_COLUMNS,
9
- MACRO_COLUMNS,
10
- MACRO_USE_COLUMNS,
11
- MODULE_COLUMNS,
12
- OPERAND_COLUMNS,
13
- PATCH_COLUMNS,
14
- REFERENCE_COLUMNS,
15
- RELEASE_COLUMNS,
16
- SWITCH_COLUMNS,
17
- REGION_COLUMNS,
8
+ FACTS,
18
9
  resolveRevision,
19
- SUPPRESSION_COLUMNS,
20
- SYMBOL_COLUMNS,
21
- toComment,
22
- toMacro,
23
- toMacroUse,
24
- toModule,
25
- toOperand,
26
- toPatch,
27
- toReference,
28
- toRelease,
29
- toStartScreen,
30
- START_SCREEN_COLUMNS,
31
- toSwitch,
32
- toRegion,
33
- toSuppression,
34
- toSymbol,
35
10
  type CommentRow,
11
+ type Fact,
36
12
  type MacroRow,
37
13
  type MacroUseRow,
38
14
  type ModuleRow,
@@ -47,7 +23,7 @@ import {
47
23
  type SymbolRow,
48
24
  } from "./read.ts";
49
25
  import { DEFAULT_SPACE, type CoverageKind, type EvidenceKind, type Origin, type Space } from "./schema.ts";
50
- import { compareText, NO_REVISION } from "./text.ts";
26
+ import { compareText, NO_REVISION, sqlName } from "./text.ts";
51
27
  import type { Evidence } from "./write.ts";
52
28
 
53
29
  export interface Revision {
@@ -144,32 +120,27 @@ function bySequence(a: HistoryEntry, b: HistoryEntry): number {
144
120
  return compareText(a.from, b.from) || compareText(a.to ?? "~", b.to ?? "~");
145
121
  }
146
122
 
123
+ /** The rows of each fact table that concern an address: each ? of the condition is the address. */
124
+ const AT_ADDRESS: ReadonlyArray<[Fact, string]> = [
125
+ [FACTS.symbols, "address = ?"],
126
+ [FACTS.analyzer_names, "address = ?"],
127
+ [FACTS.regions, "start_address <= ? AND end_address >= ?"],
128
+ [FACTS.comments, "address = ?"],
129
+ [FACTS.references, "(from_address = ? OR to_address = ?)"],
130
+ [FACTS.suppressions, "((start_address <= ? AND end_address >= ?) OR to_address = ?)"],
131
+ [FACTS.modules, "start_address = ?"],
132
+ [FACTS.operands, "address = ?"],
133
+ [FACTS.patches, "start_address <= ? AND end_address >= ?"],
134
+ [FACTS.macro_uses, "start_address <= ? AND end_address >= ?"],
135
+ ];
136
+
147
137
  /** Every row, current or closed, that concerns one address of a space, oldest first. */
148
138
  export function historyAt(db: DatabaseSync | undefined, address: number, space: Space = DEFAULT_SPACE): HistoryEntry[] {
149
139
  if (db === undefined) return [];
150
- const validity = ", valid_to_revision";
151
140
  const entries: HistoryEntry[] = [];
152
- for (const raw of db.prepare(`SELECT ${SYMBOL_COLUMNS}${validity} FROM symbols WHERE space = ? AND address = ?`).all(space, address) as Raw[]) entries.push(entry("symbol", toSymbol(raw), raw));
153
- for (const raw of db.prepare(`SELECT ${SYMBOL_COLUMNS}${validity} FROM analyzer_names WHERE space = ? AND address = ?`).all(space, address) as Raw[]) entries.push(entry("analyzer-name", toSymbol(raw), raw));
154
- for (const raw of db.prepare(`SELECT ${REGION_COLUMNS}${validity} FROM regions WHERE space = ? AND start_address <= ? AND end_address >= ?`).all(space, address, address) as Raw[]) {
155
- entries.push(entry("region", toRegion(raw), raw));
156
- }
157
- for (const raw of db.prepare(`SELECT ${COMMENT_COLUMNS}${validity} FROM comments WHERE space = ? AND address = ?`).all(space, address) as Raw[]) entries.push(entry("comment", toComment(raw), raw));
158
- for (const raw of db.prepare(`SELECT ${REFERENCE_COLUMNS}${validity} FROM "references" WHERE space = ? AND (from_address = ? OR to_address = ?)`).all(space, address, address) as Raw[]) {
159
- entries.push(entry("reference", toReference(raw), raw));
160
- }
161
- for (const raw of db
162
- .prepare(`SELECT ${SUPPRESSION_COLUMNS}${validity} FROM suppressions WHERE space = ? AND ((start_address <= ? AND end_address >= ?) OR to_address = ?)`)
163
- .all(space, address, address, address) as Raw[]) {
164
- entries.push(entry("suppression", toSuppression(raw), raw));
165
- }
166
- for (const raw of db.prepare(`SELECT ${MODULE_COLUMNS}${validity} FROM modules WHERE space = ? AND start_address = ?`).all(space, address) as Raw[]) entries.push(entry("module", toModule(raw), raw));
167
- for (const raw of db.prepare(`SELECT ${OPERAND_COLUMNS}${validity} FROM operands WHERE space = ? AND address = ?`).all(space, address) as Raw[]) entries.push(entry("operand", toOperand(raw), raw));
168
- for (const raw of db.prepare(`SELECT ${PATCH_COLUMNS}${validity} FROM patches WHERE space = ? AND start_address <= ? AND end_address >= ?`).all(space, address, address) as Raw[]) {
169
- entries.push(entry("patch", toPatch(raw), raw));
170
- }
171
- for (const raw of db.prepare(`SELECT ${MACRO_USE_COLUMNS}${validity} FROM macro_uses WHERE space = ? AND start_address <= ? AND end_address >= ?`).all(space, address, address) as Raw[]) {
172
- entries.push(entry("macro-use", toMacroUse(raw), raw));
141
+ for (const [fact, where] of AT_ADDRESS) {
142
+ const raws = db.prepare(`SELECT ${fact.columns}, valid_to_revision FROM ${sqlName(fact.table)} WHERE space = ? AND ${where}`).all(space, ...Array.from(where.matchAll(/\?/g), () => address)) as Raw[];
143
+ for (const raw of raws) entries.push(entry(fact.entity, fact.map(raw), raw));
173
144
  }
174
145
  return entries.sort(bySequence);
175
146
  }
@@ -177,24 +148,24 @@ export function historyAt(db: DatabaseSync | undefined, address: number, space:
177
148
  /** Every row of a macro with this name, and every use of it, oldest first. */
178
149
  export function historyOfMacro(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): HistoryEntry[] {
179
150
  if (db === undefined) return [];
180
- const macros = (db.prepare(`SELECT ${MACRO_COLUMNS}, valid_to_revision FROM macros WHERE space = ? AND name = ?`).all(space, name) as Raw[]).map((raw) => entry("macro", toMacro(raw), raw));
181
- const uses = (db.prepare(`SELECT ${MACRO_USE_COLUMNS}, valid_to_revision FROM macro_uses WHERE space = ? AND macro = ?`).all(space, name) as Raw[]).map((raw) => entry("macro-use", toMacroUse(raw), raw));
151
+ const macros = (db.prepare(`SELECT ${FACTS.macros.columns}, valid_to_revision FROM macros WHERE space = ? AND name = ?`).all(space, name) as Raw[]).map((raw) => entry("macro", FACTS.macros.map(raw), raw));
152
+ const uses = (db.prepare(`SELECT ${FACTS.macro_uses.columns}, valid_to_revision FROM macro_uses WHERE space = ? AND macro = ?`).all(space, name) as Raw[]).map((raw) => entry("macro-use", FACTS.macro_uses.map(raw), raw));
182
153
  return [...macros, ...uses].sort(bySequence);
183
154
  }
184
155
 
185
156
  /** Every row of a switch with this name and every patch of it, oldest first. */
186
157
  export function historyOfSwitch(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): HistoryEntry[] {
187
158
  if (db === undefined) return [];
188
- const switches = (db.prepare(`SELECT ${SWITCH_COLUMNS}, valid_to_revision FROM switches WHERE space = ? AND name = ?`).all(space, name) as Raw[]).map((raw) => entry("switch", toSwitch(raw), raw));
189
- const patches = (db.prepare(`SELECT ${PATCH_COLUMNS}, valid_to_revision FROM patches WHERE space = ? AND switch_name = ?`).all(space, name) as Raw[]).map((raw) => entry("patch", toPatch(raw), raw));
159
+ const switches = (db.prepare(`SELECT ${FACTS.switches.columns}, valid_to_revision FROM switches WHERE space = ? AND name = ?`).all(space, name) as Raw[]).map((raw) => entry("switch", FACTS.switches.map(raw), raw));
160
+ const patches = (db.prepare(`SELECT ${FACTS.patches.columns}, valid_to_revision FROM patches WHERE space = ? AND switch_name = ?`).all(space, name) as Raw[]).map((raw) => entry("patch", FACTS.patches.map(raw), raw));
190
161
  return [...switches, ...patches].sort(bySequence);
191
162
  }
192
163
 
193
164
  /** Every symbol row of a space that ever had this name, oldest first: a name can move between addresses. */
194
165
  export function historyNamed(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): HistoryEntry[] {
195
166
  if (db === undefined) return [];
196
- return (db.prepare(`SELECT ${SYMBOL_COLUMNS}, valid_to_revision FROM symbols WHERE space = ? AND name = ?`).all(space, name) as Raw[])
197
- .map((raw) => entry("symbol", toSymbol(raw), raw))
167
+ return (db.prepare(`SELECT ${FACTS.symbols.columns}, valid_to_revision FROM symbols WHERE space = ? AND name = ?`).all(space, name) as Raw[])
168
+ .map((raw) => entry("symbol", FACTS.symbols.map(raw), raw))
198
169
  .sort(bySequence);
199
170
  }
200
171
 
@@ -265,45 +236,34 @@ export function revision(db: DatabaseSync | undefined, text: string): RevisionCh
265
236
  if (id === NO_REVISION) return { revision: { id: NO_REVISION, operation: "none", description: "The knowledge before every revision. It is empty." }, added: [], closed: [] };
266
237
  const raw = db?.prepare("SELECT * FROM revisions WHERE id = ?").get(id) as Raw | undefined;
267
238
  if (db === undefined || raw === undefined) throw new Refusal("not-found", `There is no revision ${id}.`);
268
- const tables = [
269
- ["symbol", "symbols", SYMBOL_COLUMNS, toSymbol],
270
- ["analyzer-name", "analyzer_names", SYMBOL_COLUMNS, toSymbol],
271
- ["region", "regions", REGION_COLUMNS, toRegion],
272
- ["comment", "comments", COMMENT_COLUMNS, toComment],
273
- ["reference", '"references"', REFERENCE_COLUMNS, toReference],
274
- ["suppression", "suppressions", SUPPRESSION_COLUMNS, toSuppression],
275
- ["module", "modules", MODULE_COLUMNS, toModule],
276
- ["operand", "operands", OPERAND_COLUMNS, toOperand],
277
- ["patch", "patches", PATCH_COLUMNS, toPatch],
278
- ["switch", "switches", SWITCH_COLUMNS, toSwitch],
279
- ["release", "releases", RELEASE_COLUMNS, toRelease],
280
- ["start-screen", "start_screens", START_SCREEN_COLUMNS, toStartScreen],
281
- ["macro", "macros", MACRO_COLUMNS, toMacro],
282
- ["macro-use", "macro_uses", MACRO_USE_COLUMNS, toMacroUse],
283
- ] as const;
284
- // The program: its memory, its entry and its coverage.
285
- const program = [
286
- ["memory", "memory", "space, address, length(bytes) / 2 AS bytes, origin, valid_from_revision", (row: Raw): MemoryRow => ({ space: row.space as Space, address: row.address as number, bytes: row.bytes as number, origin: row.origin as Origin, revision: row.valid_from_revision as string })],
287
- [
288
- "entry",
289
- "entries",
290
- "space, address, state IS NOT NULL AS has_state, json_array_length(coalesce(stages, '[]')) AS stage_count, origin, valid_from_revision",
291
- (row: Raw): EntryRow => ({ space: row.space as Space, address: row.address as number, state: row.has_state === 1, stages: row.stage_count as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
292
- ],
293
- [
294
- "coverage",
295
- "coverage",
296
- "space, map, kind, length(ranges) - length(replace(ranges, ' ', '')) + 1 AS ranges, origin, valid_from_revision",
297
- (row: Raw): CoverageRow => ({ space: row.space as Space, map: row.map as string, kind: row.kind as CoverageKind, ranges: row.ranges as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
298
- ],
299
- ] as const;
239
+ // The facts, then the program: its memory, its entry and its coverage.
240
+ const program: Fact[] = [
241
+ {
242
+ table: "memory",
243
+ entity: "memory",
244
+ columns: "space, address, length(bytes) / 2 AS bytes, origin, valid_from_revision",
245
+ map: (row: Raw): MemoryRow => ({ space: row.space as Space, address: row.address as number, bytes: row.bytes as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
246
+ },
247
+ {
248
+ table: "entries",
249
+ entity: "entry",
250
+ columns: "space, address, state IS NOT NULL AS has_state, json_array_length(coalesce(stages, '[]')) AS stage_count, origin, valid_from_revision",
251
+ map: (row: Raw): EntryRow => ({ space: row.space as Space, address: row.address as number, state: row.has_state === 1, stages: row.stage_count as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
252
+ },
253
+ {
254
+ table: "coverage",
255
+ entity: "coverage",
256
+ columns: "space, map, kind, length(ranges) - length(replace(ranges, ' ', '')) + 1 AS ranges, origin, valid_from_revision",
257
+ map: (row: Raw): CoverageRow => ({ space: row.space as Space, map: row.map as string, kind: row.kind as CoverageKind, ranges: row.ranges as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
258
+ },
259
+ ];
300
260
  const added: HistoryEntry[] = [];
301
261
  const closed: HistoryEntry[] = [];
302
- for (const [entity, table, columns, map] of [...tables, ...program]) {
303
- for (const row of db.prepare(`SELECT ${columns}, valid_to_revision FROM ${table} WHERE valid_from_revision = ?`).all(id) as Raw[]) {
262
+ for (const { entity, table, columns, map } of [...Object.values(FACTS), ...program]) {
263
+ for (const row of db.prepare(`SELECT ${columns}, valid_to_revision FROM ${sqlName(table)} WHERE valid_from_revision = ?`).all(id) as Raw[]) {
304
264
  added.push(entry(entity, map(row), row));
305
265
  }
306
- for (const row of db.prepare(`SELECT ${columns}, valid_to_revision FROM ${table} WHERE valid_to_revision = ?`).all(id) as Raw[]) {
266
+ for (const row of db.prepare(`SELECT ${columns}, valid_to_revision FROM ${sqlName(table)} WHERE valid_to_revision = ?`).all(id) as Raw[]) {
307
267
  closed.push(entry(entity, map(row), row));
308
268
  }
309
269
  }