@henols/c64-re-tools 2.2.0-rc.2 → 2.2.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.
@@ -1,9 +1,12 @@
1
- // The links of a page written by a person. A name in backticks links to
2
- // its line in the source; the address after it links to the entry of the name
3
- // in the reference, or, for an address inside the routine or the data of the
4
- // name ("draw_room $0AAF", a place in draw_room), to the line of that address. A link that points into the source or the reference is
5
- // managed: docs.ts link writes it again when a line moves. Other links stay as the
6
- // person wrote them; docs.ts link only checks that their targets exist.
1
+ // The links of a page written by a person. A name in backticks with its
2
+ // address in backticks after it ("draw_room $09BC") is one link to the line of
3
+ // the name in the source, or, for an address inside the routine or the data of
4
+ // the name ("draw_room $0AAF", a place in draw_room), to the line of that
5
+ // address. A name without an address gets no link: the person gives the
6
+ // address only where a reader needs the code. A link that points into the
7
+ // source or the reference is managed: docs.ts link writes it again when a line
8
+ // moves. Other links stay as the person wrote them; docs.ts link only checks
9
+ // that their targets exist.
7
10
 
8
11
  import { posix } from "node:path";
9
12
 
@@ -16,8 +19,6 @@ export interface LinkContext {
16
19
  addressOf: (name: string) => number | undefined;
17
20
  /** The project path and line of the label of a name, as path#Lnn. */
18
21
  codeOf: (name: string) => string | undefined;
19
- /** The project path and anchor of the entry of a name, as path#name. */
20
- entryOf: (name: string) => string | undefined;
21
22
  /** The last address of the routine or data of a name: an address up to it is a place inside the name. */
22
23
  bodyEnd: (name: string) => number | undefined;
23
24
  /** The project path and line that writes an address, as path#Lnn. */
@@ -28,7 +29,7 @@ export interface LinkContext {
28
29
  managed: (path: string) => boolean;
29
30
  }
30
31
 
31
- export type ProblemKind = "unknown-name" | "wrong-address" | "missing-file" | "missing-anchor" | "missing-line" | "outside-project" | "stale-reference";
32
+ export type ProblemKind = "unknown-name" | "wrong-address" | "repeated-link" | "link-in-table" | "missing-file" | "missing-anchor" | "missing-line" | "outside-project" | "stale-reference";
32
33
 
33
34
  export interface Problem {
34
35
  page: string;
@@ -42,15 +43,13 @@ const NAME = String.raw`([A-Za-z_][A-Za-z0-9_]*)(\+(?:\$[0-9A-Fa-f]{1,4}|[0-9]+)
42
43
  const ADDRESS = String.raw`\$([0-9A-Fa-f]{2,4})(?:-\$[0-9A-Fa-f]{2,4})?`;
43
44
  const TICK = "`";
44
45
  /**
45
- * A name in backticks, linked or not, with an optional address in backticks
46
- * after it, linked or not. Groups: 1 the [ of a linked name, 2 the name, 3 its
47
- * offset, 4 the target of the name, 5 the space or bracket between them, 6 the
48
- * address text, 7 its start digits, 8 the target of the address.
46
+ * A name in backticks and an address in backticks after it, as text or as one
47
+ * link. Groups: 1 the [ of the link, 2 the name, 3 its offset, 4 the space
48
+ * between them, 5 the address text, 6 its start digits, 7 the target of the link.
49
49
  */
50
- const MENTION = new RegExp(
51
- String.raw`(\[)?${TICK}${NAME}${TICK}(?:\]\(([^)\s]*)\))?(?:(\s*\(\s*|\s+)\[?${TICK}(${ADDRESS})${TICK}(?:\]\(([^)\s]*)\))?)?`,
52
- "g",
53
- );
50
+ const MENTION = new RegExp(String.raw`(\[)?${TICK}${NAME}${TICK}(\s+)${TICK}(${ADDRESS})${TICK}(?:\]\(([^)\s]*)\))?`, "g");
51
+ const HEADING = /^#{1,6}\s/;
52
+ const TABLE_ROW = /^\s*\|/;
54
53
 
55
54
  const relative = (page: string, target: string) => {
56
55
  const [path, fragment] = target.split("#");
@@ -74,47 +73,48 @@ export function targetPath(page: string, target: string): string | undefined {
74
73
  export function linkPage(text: string, context: LinkContext): { text: string; changed: number; problems: Problem[] } {
75
74
  const problems: Problem[] = [];
76
75
  let changed = 0;
76
+ // The first link of each name and address in the section: a heading starts a new section.
77
+ let linkedAt = new Map<string, number>();
77
78
  const lines = proseLines(text).map((line, index) => {
78
79
  if (!line.prose) return line.text;
79
- return line.text.replace(MENTION, (whole: string, open: string | undefined, name: string, offset: string | undefined, nameTarget: string | undefined, space: string | undefined, addressText: string | undefined, digits: string | undefined, addressTarget: string | undefined, at: number, all: string) => {
80
- // "[`x`]" without a target is no link of ours: leave it.
81
- if (open !== undefined && nameTarget === undefined) return whole;
82
- const ownLink = (target: string | undefined) => target !== undefined && !context.managed(targetPath(context.page, target) ?? "");
80
+ if (HEADING.test(line.text)) linkedAt = new Map();
81
+ const inTable = TABLE_ROW.test(line.text);
82
+ return line.text.replace(MENTION, (whole: string, open: string | undefined, name: string, offset: string | undefined, space: string, addressText: string, digits: string, target: string | undefined) => {
83
+ // "[`x` `$10`]" without a target, or "`x` `$10`](y)" in a link of the person: no link of ours, leave it.
84
+ if ((open === undefined) !== (target === undefined)) return whole;
85
+ // A link to another target than the source is the person's own link: it stays as it is.
86
+ if (target !== undefined && !context.managed(targetPath(context.page, target) ?? "")) return whole;
83
87
  const address = context.addressOf(name);
84
88
  const report = (kind: ProblemKind, message: string) => problems.push({ page: context.page, line: index + 1, kind, message });
85
- // In a list "`a`/`b` `$1000`/`$1010`" the address belongs to another name: the name gets its link, the address stays as it is.
86
- const namePart = open === undefined ? `${TICK}${name}${offset ?? ""}${TICK}` : `[${TICK}${name}${offset ?? ""}${TICK}](${nameTarget})`;
87
- const listed = addressText !== undefined && (all[at - 1] === "/" || all[at + whole.length] === "/");
88
- const rest = listed ? whole.slice(namePart.length) : "";
89
- const claimed = addressText !== undefined;
90
- if (listed) addressText = digits = addressTarget = undefined;
89
+ const shown = `${TICK}${name}${offset ?? ""}${TICK}${space}${TICK}${addressText}${TICK}`;
91
90
  if (address === undefined) {
92
- // A word in backticks is no claim of a name; with an address after it, or with a link of ours, it is.
93
- if (claimed || (nameTarget !== undefined && !ownLink(nameTarget))) {
94
- report("unknown-name", `\`${name}\` is no name of the knowledge or the source. Apply the name to the knowledge, or correct the page.`);
95
- }
91
+ report("unknown-name", `\`${name}\` is no name of the knowledge or the source. Apply the name to the knowledge, or correct the page.`);
96
92
  return whole;
97
93
  }
98
94
  const delta = offset === undefined ? 0 : offset.startsWith("+$") ? Number.parseInt(offset.slice(2), 16) : Number.parseInt(offset.slice(1), 10);
99
- const given = digits === undefined ? undefined : Number.parseInt(digits, 16);
100
- const place = given !== undefined && given !== address + delta && given > address && given <= (context.bodyEnd(name) ?? address);
101
- if (given !== undefined && given !== address + delta && !place) {
95
+ const given = Number.parseInt(digits, 16);
96
+ const place = given !== address + delta && given > address && given <= (context.bodyEnd(name) ?? address);
97
+ if (given !== address + delta && !place) {
102
98
  const expected = `$${(address + delta).toString(16).toUpperCase().padStart(4, "0")}`;
103
- const holder = context.placeOf(given!);
104
- report("wrong-address", `\`${name}${offset ?? ""}\` is ${expected} in the knowledge, and the page gives ${addressText}${holder === undefined || holder === name ? "" : `, a place in \`${holder}\``}. Correct the name or the address.${digits!.length <= 2 ? ` For a value, write \`${name}\` = \`${addressText}\`.` : ""}`);
99
+ const holder = context.placeOf(given);
100
+ report("wrong-address", `\`${name}${offset ?? ""}\` is ${expected} in the knowledge, and the page gives ${addressText}${holder === undefined || holder === name ? "" : `, a place in \`${holder}\``}. Correct the name or the address.${digits.length <= 2 ? ` For a value, write \`${name}\` = \`${addressText}\`.` : ""}`);
105
101
  // A mention with a problem gets no link: the text stays as the person wrote it until it is correct.
106
102
  return whole;
107
103
  }
108
- const shownName = `${TICK}${name}${offset ?? ""}${TICK}`;
109
- const code = context.codeOf(name);
110
- const nameLink = ownLink(nameTarget) ? `[${shownName}](${nameTarget})` : code === undefined ? shownName : `[${shownName}](${relative(context.page, code)})`;
111
- let result = nameLink;
112
- if (addressText !== undefined) {
113
- const entry = place ? context.lineOf(given!) : context.entryOf(name);
114
- const shownAddress = `${TICK}${addressText}${TICK}`;
115
- result += space! + (ownLink(addressTarget) ? `[${shownAddress}](${addressTarget})` : entry === undefined ? shownAddress : `[${shownAddress}](${relative(context.page, entry)})`);
104
+ if (inTable) {
105
+ report("link-in-table", `\`${name}${offset ?? ""}\` ${addressText} is a link in a table. Write \`${name}\` without the address in the table, and link it in the text above the table.`);
106
+ return whole;
107
+ }
108
+ const key = `${name}${offset ?? ""} ${given}`;
109
+ const first = linkedAt.get(key);
110
+ if (first !== undefined) {
111
+ report("repeated-link", `\`${name}${offset ?? ""}\` ${addressText} has a link at line ${first} of this section already. Write \`${name}\` without the address here.`);
112
+ return whole;
116
113
  }
117
- result += rest;
114
+ linkedAt.set(key, index + 1);
115
+ // The name links to its line; a place inside it or a byte after it links to the line of that address.
116
+ const code = given === address ? context.codeOf(name) : (context.lineOf(given) ?? context.codeOf(name));
117
+ const result = code === undefined ? shown : `[${shown}](${relative(context.page, code)})`;
118
118
  if (result !== whole) changed++;
119
119
  return result;
120
120
  });
@@ -65,7 +65,7 @@ interface Entry {
65
65
  export function buildReference(input: ReferenceInput): { files: ReferenceFile[]; counts: Record<string, number> } {
66
66
  const { map, out } = input;
67
67
  const pieces = map.files.filter((file) => !NOT_PIECES.has(file));
68
- const pageOfFile = (file: string) => (file === "constants.asm" ? posix.join(out, "variables.md") : posix.join(out, "modules", `${stem(file)}.md`));
68
+ const pageOfFile = (file: string) => (file === "constants.asm" ? posix.join(out, "memory-map.md") : posix.join(out, "modules", `${stem(file)}.md`));
69
69
 
70
70
  // --- Names and their entries ------------------------------------------------
71
71
  const knowledgeNames = new Map(input.symbols.map((symbol) => [symbol.name, symbol]));
@@ -107,8 +107,12 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
107
107
  const entry = entries.get(name);
108
108
  return entry === undefined ? `\`${text}\`` : `[\`${text}\`](${rel(page, entry.page)}#${name})`;
109
109
  };
110
- /** A name and its address: the name to its line, the address to its entry (the convention of every page). */
111
- const pair = (page: string, name: string, address: number) => `${codeOfName(page, name)} ${entryOfName(page, name, hex(address))}`;
110
+ /** A name and its address as one link to the line of the name (the convention of every page). */
111
+ const pair = (page: string, name: string, address: number) => {
112
+ const label = map.labelOf(name);
113
+ const shown = `\`${name}\` \`${hex(address)}\``;
114
+ return label === undefined ? shown : `[${shown}](${rel(page, map.pathOf(label.file))}#L${label.line})`;
115
+ };
112
116
  const codeOfAddress = (page: string, address: number) => {
113
117
  const line = map.lineOf(address);
114
118
  return line === undefined ? `\`${hex(address)}\`` : `[\`${hex(address)}\`](${rel(page, map.pathOf(line.file))}#L${line.line})`;
@@ -129,6 +133,13 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
129
133
  return entries.has(named.name) ? entryOfName(page, named.name, shown) : codeOfName(page, named.name).replace(`\`${named.name}\``, `\`${shown}\``);
130
134
  };
131
135
  const capped = (items: string[]) => (items.length <= MAX_LISTED ? items.join(", ") : `${items.slice(0, MAX_LISTED).join(", ")} and ${items.length - MAX_LISTED} more`);
136
+ /** The routines that read or write a range, each linked to its entry. */
137
+ const ownersOf = (page: string, start: number, end: number, kind: string) =>
138
+ capped(
139
+ [...new Set(input.references.filter((reference) => reference.kind === kind && reference.to >= start && reference.to <= end).map((reference) => ownerAt(reference.from)?.name ?? hex(reference.from)))].map((name) =>
140
+ entries.has(name) ? entryOfName(page, name, name) : `\`${name}\``,
141
+ ),
142
+ );
132
143
 
133
144
  // --- The routine graph ----------------------------------------------------
134
145
  const tableReferences: GraphReference[] = [];
@@ -270,8 +281,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
270
281
  if (regions.length > 0) {
271
282
  lines.push("", "## Data", "", "| Range | Type | Name | Read by | Written by |", "|---|---|---|---|---|");
272
283
  for (const region of regions) {
273
- const into = input.references.filter((reference) => reference.to >= region.start && reference.to <= region.end);
274
- const owners = (kind: string) => capped([...new Set(into.filter((reference) => reference.kind === kind).map((reference) => ownerAt(reference.from)?.name ?? hex(reference.from)))].map((name) => (entries.has(name) ? entryOfName(page, name, name) : `\`${name}\``)));
284
+ const owners = (kind: string) => ownersOf(page, region.start, region.end, kind);
275
285
  const name = entryAt.get(region.start);
276
286
  lines.push(`| ${codeOfAddress(page, region.start)}${region.end === region.start ? "" : `-\`${hex(region.end)}\``} | ${region.type}${region.element === undefined ? "" : ` of ${region.element}`} | ${name === undefined ? "" : codeOfName(page, name.name)} | ${owners("read")} | ${owners("write")} |`);
277
287
  }
@@ -283,18 +293,6 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
283
293
  write(page, lines);
284
294
  }
285
295
 
286
- // --- Variables: the names outside the image -------------------------------
287
- {
288
- const page = posix.join(out, "variables.md");
289
- const outside = [...entries.values()].filter((entry) => map.labelOf(entry.name)?.file === "constants.asm").sort((a, b) => a.address - b.address);
290
- const inside = [...entries.values()].filter((entry) => entry.kind === "variable" && map.labelOf(entry.name)?.file !== "constants.asm").sort((a, b) => a.address - b.address);
291
- const lines = ["# Variables", "", `The names outside the image, with the routines that read and write them. Index: [the reference](${rel(page, posix.join(out, "index.md"))}).`];
292
- if (inside.length > 0) lines.push("", "Variables inside the image are on the page of their file:", "", ...inside.map((entry) => `- ${pair(page, entry.name, entry.address)}`));
293
- for (const entry of outside) lines.push(...entryText(page, entry));
294
- counts.entries += outside.length;
295
- write(page, lines);
296
- }
297
-
298
296
  // --- Tables -----------------------------------------------------------------
299
297
  {
300
298
  const page = posix.join(out, "tables.md");
@@ -358,26 +356,23 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
358
356
  // --- Memory map ---------------------------------------------------------------
359
357
  {
360
358
  const page = posix.join(out, "memory-map.md");
361
- const lines = ["# Memory map", "", `Every region of the knowledge in address order. Index: [the reference](${rel(page, posix.join(out, "index.md"))}).`, "", "| Range | Bytes | Type | Name | File |", "|---|---|---|---|---|"];
359
+ const lines = ["# Memory map", "", `Every region of the knowledge in address order, then the variables outside the program. Index: [the reference](${rel(page, posix.join(out, "index.md"))}).`, "", "## Regions", "", "| Range | Bytes | Type | Name | File |", "|---|---|---|---|---|"];
362
360
  for (const region of [...input.regions].sort((a, b) => a.start - b.start)) {
363
361
  const name = entryAt.get(region.start);
364
362
  const line = map.lineOf(region.start);
365
363
  const file = line === undefined || !pieces.includes(line.file) ? "" : `[${line.file}](${rel(page, pageOfFile(line.file))})`;
366
364
  lines.push(`| ${codeOfAddress(page, region.start)}${region.end === region.start ? "" : `-\`${hex(region.end)}\``} | ${region.end - region.start + 1} | ${region.type} | ${name === undefined ? "" : pair(page, name.name, region.start)} | ${file} |`);
367
365
  }
368
- write(page, lines);
369
- }
370
-
371
- // --- Symbols --------------------------------------------------------------------
372
- {
373
- const page = posix.join(out, "symbols.md");
374
- const lines = ["# Names", "", `Every name in alphabetical order. The name links to its line in the source, the address to its entry. Index: [the reference](${rel(page, posix.join(out, "index.md"))}).`, "", "| Name | Address | Kind |", "|---|---|---|"];
375
- const names = [...new Set([...entries.keys(), ...input.symbols.map((symbol) => symbol.name)])].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()) || a.localeCompare(b));
376
- for (const name of names) {
377
- const entry = entries.get(name);
378
- const symbol = knowledgeNames.get(name);
379
- const address = entry?.address ?? symbol!.address;
380
- lines.push(`| ${codeOfName(page, name)} | ${entryOfName(page, name, hex(address))} | ${entry?.kind ?? symbol!.kind} |`);
366
+ // The names outside the image: zero page, the stack, work areas and the chips. The module pages link to their rows.
367
+ const outside = [...entries.values()].filter((entry) => map.labelOf(entry.name)?.file === "constants.asm").sort((a, b) => a.address - b.address);
368
+ if (outside.length > 0) {
369
+ lines.push("", "## Variables outside the program", "", "| Address | Name | Comment | Read by | Written by |", "|---|---|---|---|---|");
370
+ for (const entry of outside) {
371
+ const at = `\`${entry.spanEnd > entry.address ? range(entry.address, entry.spanEnd) : hex(entry.address)}\``;
372
+ const owners = (kind: string) => ownersOf(page, entry.address, entry.spanEnd, kind);
373
+ lines.push(`| ${at} | <a id="${entry.name}"></a>${codeOfName(page, entry.name)} | ${commentLines(entry.address).join(" ").replace(/\|/g, "\\|")} | ${owners("read")} | ${owners("write")} |`);
374
+ }
375
+ counts.entries += outside.length;
381
376
  }
382
377
  write(page, lines);
383
378
  }
@@ -388,7 +383,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
388
383
  const lines = [
389
384
  "# Reference",
390
385
  "",
391
- `Generated from the knowledge and the source in [${map.directory}](${rel(page, map.directory)}). The other pages: [names](symbols.md), [variables](variables.md), [tables](tables.md), [memory map](memory-map.md) and [graphics](graphics.md).`,
386
+ `Generated from the knowledge and the source in [${map.directory}](${rel(page, map.directory)}). The other pages: [tables](tables.md), [memory map and variables](memory-map.md) and [graphics](graphics.md).`,
392
387
  "",
393
388
  "| File | Range | Title | Routines | Names |",
394
389
  "|---|---|---|---|---|",
@@ -0,0 +1,87 @@
1
+ ---
2
+ name: c64-export
3
+ description: Use this skill to export a rebuilt C64 program as the start of a new program. The export sets each switch to one value in the code. Corrections, trainers and cheats are in, and copy protection and crack changes are out. It removes code and data that nothing uses. It writes a new project folder with the source, a baseline program, the tests and a small knowledge, and a zip file of the folder. Use it for requests such as "export the project", "start a new game from this rebuild" or "make a clean package of the code". Do not use it to change the rebuild. Use c64-development for that.
4
+ ---
5
+
6
+ # c64-export
7
+
8
+ ## Purpose
9
+
10
+ Make the start of a new program from a rebuilt program. The new program is a new project. A person changes its source directly.
11
+
12
+ This skill does not change the rebuilt project or its knowledge.
13
+
14
+ ## Inputs
15
+
16
+ - A rebuilt project: `source.ts generate` of the c64-source skill gives PASS.
17
+ - The folder of the new project. It must be new or empty, and no project can hold it. Use a folder beside the project, for example `../game-new`.
18
+ - Optional: the coverage of the runs in the knowledge. Without coverage, nothing becomes free by itself.
19
+
20
+ ## Tools / execution path
21
+
22
+ This skill uses the other skills. It does not use the host runtime directly.
23
+
24
+ | Work | Skill |
25
+ |---|---|
26
+ | The export | c64-source: `source.ts export` |
27
+ | The switches and the code at an address | c64-knowledge |
28
+ | The build of the new project | c64-assembler |
29
+ | The tests of the new project | c64-testing |
30
+
31
+ ## Workflow
32
+
33
+ 1. Run `source.ts generate --out src` of c64-source. It must give PASS. If it does not, stop and complete the rebuild with the c64-reverse-engineering skill.
34
+ 2. Read the switches with `knowledge.ts switches` of c64-knowledge. Tell the user the export value of each switch:
35
+ - `fix`, `trainer` and `cheat`: 1. The code becomes a part of the new program.
36
+ - `protection` and `crack`: 0.
37
+ - `change`: its default.
38
+
39
+ If the user wants another value for a switch, change its kind or its default with `knowledge.ts switch` first.
40
+ 3. Run `source.ts export --to <folder>` of c64-source.
41
+ 4. Read `unreachableExecuted`. Each range is code that a run executed and that the entry does not get to now. For each range, find the code that calls it with c64-knowledge:
42
+ - Only code that the export removed calls it, for example a copy check: drop it.
43
+ - Code that the knowledge does not show can call it, for example through a pointer: keep it.
44
+ - If you are not sure, ask the user.
45
+ 5. To drop a range, remove the folder and the zip file of the export. Then run `source.ts export` again with `--drop '<range>'` for each range.
46
+ 6. Build the new project with c64-assembler. Give `--project <folder>`. Use the build commands in its `README.md`. The build with `--compare` must give PASS.
47
+ 7. Run each test of the new project with c64-testing. Give `--project <folder>`. Use the test commands in its `README.md`. Each test must give PASS.
48
+
49
+ ### The answer
50
+
51
+ Give the user a short answer at the end:
52
+
53
+ 1. The folder and the zip file.
54
+ 2. The value of each switch.
55
+ 3. The free ranges, with their bytes.
56
+ 4. Each test and its result, and the tests that the export left out, with the reason.
57
+ 5. The next step: the c64-development skill, path B.
58
+
59
+ ## Knowledge
60
+
61
+ Read:
62
+
63
+ - the switches, and the code at the addresses of `unreachableExecuted`.
64
+
65
+ Automatic write:
66
+
67
+ - none in the rebuilt project. The export writes the knowledge of the new project.
68
+
69
+ ## Result
70
+
71
+ A new project folder and a zip file of it. Its build is identical to its baseline, and each of its tests gives PASS.
72
+
73
+ ## Failure and conflicts
74
+
75
+ - `export` gives FAIL with `stage`: read `reason`. The c64-source skill tells what to do for each stage.
76
+ - `export` refuses the folder: give a new or empty folder outside every project. Remove a folder or a zip file of an earlier export only when this task made it.
77
+ - A test of the new project gives FAIL: the export dropped a range that the program uses. Remove the folder and the zip file. Run `export` again with `--keep` for the range, then test again.
78
+ - A skill reports `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the whole task. Give the message to the user and wait for the user. Do not make a replacement for the tool or the host runtime.
79
+
80
+ ## Handoffs
81
+
82
+ - The rebuild is not complete → c64-reverse-engineering
83
+ - The export → c64-source
84
+ - Switches and the code at an address → c64-knowledge
85
+ - The build of the new project → c64-assembler
86
+ - The tests of the new project → c64-testing
87
+ - A new feature or a fix in the new project → c64-development
@@ -8,7 +8,7 @@
8
8
 
9
9
  import { type AddressRange, basicLineText } from "#src/c64.ts";
10
10
  import { MNEMONICS } from "#src/opcodes.ts";
11
- import type { Access, Separation } from "./separate.ts";
11
+ import type { Access, Separation } from "#src/knowledge/separate.ts";
12
12
 
13
13
  export interface LeftoversInput {
14
14
  segments: AddressRange[];
@@ -47,7 +47,7 @@ import { compareReleases, identicalShare, shiftSuggestion, suggestShifts, type R
47
47
  import { findRoutine, libraryFolder, readLibrary, routineFrom, saveRoutine, suggest } from "./lib/library.ts";
48
48
  import { watchRelease, type Start } from "./lib/runtime.ts";
49
49
  import { findLeftovers } from "./lib/leftovers.ts";
50
- import { separate, type Root } from "./lib/separate.ts";
50
+ import { separate, type Root } from "#src/knowledge/separate.ts";
51
51
 
52
52
  const hexBytes = (bytes: number[]) => Buffer.from(bytes).toString("hex").replace(/(..)(?!$)/g, "$1 ");
53
53
 
@@ -186,4 +186,6 @@ A clear answer for the scope, with the durable conclusions in the project knowle
186
186
 
187
187
  All specialist skills in the table above.
188
188
 
189
- A new feature or a fix for the rebuilt program → c64-development
189
+ A new feature or a correction of the rebuilt program → c64-development
190
+
191
+ The start of a new program from the rebuilt program → c64-export
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: c64-source
3
- description: Use this skill to generate ACME source code for a C64 program from the project knowledge. The knowledge holds the program, its entry state, the coverage and the names. The script runs Ghidra for the instructions and writes the source files. It checks with ACME that the source assembles to the same bytes as the program. It can also write a loader that sets the entry state of an unpacked program. Use it to make a rebuild. Do not edit the generated files. Change the knowledge and generate again.
3
+ description: Use this skill to generate ACME source code for a C64 program from the project knowledge. The knowledge holds the program, its entry state, the coverage and the names. The script runs Ghidra for the instructions and writes the source files. It checks with ACME that the source assembles to the same bytes as the program. It can also write a loader that sets the entry state of an unpacked program. It can also export the program as the start of a new program. The export is a new project with one value for each switch and without unused code. Use it to make a rebuild. Do not edit the generated files. Change the knowledge and generate again.
4
4
  ---
5
5
 
6
6
  # c64-source
@@ -137,6 +137,88 @@ The script simulates the copies first. Then it runs `loader.prg` in the emulator
137
137
 
138
138
  The entry state is the state of the base release. Thus the script builds and checks `loader.prg` with the switch values of the base release. For a loader of the default build, build `loader.asm` with the c64-assembler skill and no option.
139
139
 
140
+ ## Export for a new application
141
+
142
+ `export` writes the program of the knowledge as the start of a new program: a new project folder and a zip file of it. A person changes the source of the new project directly. The c64-export skill gives the full procedure.
143
+
144
+ ```
145
+ node <skill>/scripts/source.ts export --to ../game-new
146
+ node <skill>/scripts/source.ts export --to ../game-new --name game --drop '$081b-$0822'
147
+ ```
148
+
149
+ | Option | Meaning |
150
+ |---|---|
151
+ | `--to ../game-new` | The folder of the new project, relative to the project folder. The folder must be new or empty, and no project can hold it. The script also writes `../game-new.zip`. |
152
+ | `--name game` | The name of `baseline/game.prg` and `build/game.prg`. The default is the name of the folder. |
153
+ | `--keep '$2000-$20ff'` | A range that stays, also when nothing uses it. Use it again for more ranges. |
154
+ | `--drop '$081b-$0822'` | A range that becomes free. Use it again for more ranges. Code that stays must not go to the range or read it. |
155
+ | `--max-listed 20` | List at most this number of items in each list. The default is 50. |
156
+
157
+ The script does these steps. It writes nothing until all the checks pass.
158
+
159
+ 1. It builds the source of the base release. The build must give the program byte by byte, with all the patches.
160
+ 2. It sets each switch to its export value:
161
+ - `fix`, `trainer` and `cheat`: 1. Trainers and cheats become a part of the new program.
162
+ - `protection` and `crack`: 0.
163
+ - `change`: its default.
164
+ 3. It builds the program with these values. This build can change bytes only in the patches.
165
+ 4. It finds the free ranges. Each free range gets the bytes $00 and the label `free_xxxx`. No address moves.
166
+ 5. It makes the source of the new program. ACME must assemble the source to the new program byte by byte. For a capture with an entry state, the script also makes `loader.asm` and simulates its copies. It does not run the loader in the emulator.
167
+ 6. It writes the new project and the zip file.
168
+
169
+ ### The free ranges
170
+
171
+ The script divides the decoded instructions into blocks. A block stops after RTS, RTI, JMP, BRK or a JAM, and before a gap. A block of code becomes free only when both of these are true:
172
+
173
+ - No run of the coverage executed it.
174
+ - No path gets to it from the entry, the hardware vectors or the code that stays. A path is a call, a jump, a branch, a reference of the knowledge or an operand expression. An entry of a table and two immediate operands that give its address are paths too.
175
+
176
+ Code that a run executed always stays. `unreachableExecuted` lists the executed code that the entry and the vectors do not get to. An example is a copy check whose call the export removed. Give its range to `--drop` to make it free.
177
+
178
+ Data becomes free only when all of these are true:
179
+
180
+ - Its region type is `bytes`, `words`, a table of addresses, `petscii`, `workspace` or `unused`.
181
+ - No run read, wrote or executed a byte of it.
182
+ - No code that stays reads it or names it, and no table that stays has an entry in it.
183
+ - It is not at the first address of the program and not at $fffa-$ffff.
184
+
185
+ The VIC-II reads `charset`, `sprite`, `bitmap` and `screen` data without the CPU, so the coverage does not show these reads. This data stays unless `--drop` names it. Bytes without a region also stay.
186
+
187
+ The entry is the entry of the knowledge. Without it, the entry is the address of the first SYS in the BASIC line of the program. Without coverage, nothing becomes free by itself. Without an entry and without the hardware vectors in the image, no code is unreachable.
188
+
189
+ ### The new project
190
+
191
+ ```
192
+ README.md the commands to build and test, the free ranges and the origin
193
+ src/ main.asm, constants.asm, macros.asm, the modules and loader.asm
194
+ baseline/<name>.prg the exported program, and baseline/<name>.json with its symbols
195
+ tests/ the tests of the project, changed for the new program
196
+ .c64-re-tools/knowledge/ the knowledge of the new program
197
+ ```
198
+
199
+ - The source has no mark line, no `switches.asm`, no patch zones and no `; not executed` lines. It keeps the names, the comments, the operand expressions and the macros. A line comment at each changed patch gives the switch, its kind, its value and the comments of the switch and the patch.
200
+ - The knowledge has one revision `export`. It holds the program, the entry and its state, the names, the comments, the regions and the modules. It has no history, analyzer names, references, operand expressions, macros, patches, switches, releases or coverage.
201
+ - The tests come from the JSON files in `tests/`:
202
+ - A scenario compares the build of the new project with the baseline. Both sides are the same program, so a step of the original side alone goes. A step of the rebuild side alone runs on both sides.
203
+ - A run file runs the build of the new project.
204
+ - Both take the names from the symbol files.
205
+ - The script leaves out a test that restores a snapshot. It also leaves out a test with a name that the new program does not have, or with an address in a free range.
206
+ - The script does not copy recordings, record files or `runs/`.
207
+ - The zip file holds the folder without `.c64-re-tools/local/`.
208
+
209
+ The result of `export`:
210
+
211
+ - `result`: `PASS` when the script wrote the new project. `FAIL` with `stage` when a check failed: `original`, `switches`, `export` or `loader`. Then the script wrote nothing.
212
+ - `to` and `zip`: the folder and the zip file.
213
+ - `switches`: each switch with `kind`, `base` and the export `value`.
214
+ - `free`: the count of free bytes, and each free range with `bytes`, `what` and `label`.
215
+ - `unreachableExecuted`: each range of executed code that the entry does not get to, with the `routine` before it and its `--drop` option.
216
+ - `knowledge`: the counts of the rows of the new knowledge.
217
+ - `tests`: the `written` tests, and the `leftOut` tests with the reason.
218
+ - `loader`: the copies, the copier, `stackByte` and `simulated: true`.
219
+ - `noCoverage` or `unrooted`: why nothing became free by itself.
220
+ - `spacesLeftOut`: the spaces that the export does not have. The export has only the space `c64`.
221
+
140
222
  ## Knowledge
141
223
 
142
224
  Read:
@@ -199,6 +281,10 @@ Do not store:
199
281
  - `loader.verified: false` with a `reason`: the script did not make the loader. The script still writes and checks the source. When no copy order or no free pages exist, or the loader needs too many copies, the reason gives the ranges. Capture the program again with fewer segments, or write the loader by hand.
200
282
  - `loader.verified: false` with `differences`: the loader ran, and `differences` gives the bytes and registers that are not equal.
201
283
  - `loader.verified: false` with `stop`: the loader did not get to its copier or to its jump. `stop` gives the address where it stopped and `port`, the value of $01. `history` gives the last 16 instructions. `cause` gives the first byte of the copier that is not equal to its byte in the loader file. If the copier ran, `cause` can also give the first byte that a copy did not write correctly.
284
+ - `export` with `stage: "original"`: the source of the knowledge does not pass. Run `generate`, and correct the knowledge until `generate` gives PASS.
285
+ - `export` with `stage: "switches"`: the build with the export values changes bytes outside the patches, or a patch does not fit. Read `build`. Correct the patches.
286
+ - `export` refuses two switches that change one range: the export puts both alternatives in. Give all but one of them the kind `change` and the default of the base release with `switch` of the c64-knowledge skill.
287
+ - `export` refuses `--drop`: read the message. It names the code that stays and goes to the range or reads it, or the code or region that the range cuts.
202
288
  - `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the task. Give the message to the user and wait for the user. The message gives the remedy. Do not make a replacement for the tool or the host runtime, for example your own disassembler or emulator script.
203
289
 
204
290
  ## Handoffs
@@ -208,3 +294,4 @@ Do not store:
208
294
  - Names, regions, comments and modules → c64-knowledge
209
295
  - Build the program → c64-assembler
210
296
  - Test the rebuild against the original → c64-testing
297
+ - The start of a new program from the rebuild → c64-export