@henols/c64-re-tools 2.2.0-rc.6 → 2.2.0-rc.7

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.2.0-rc.6",
3
+ "version": "2.2.0-rc.7",
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",
@@ -31,7 +31,7 @@ node <skill>/scripts/assembler.ts build src main.a --out build/game.prg
31
31
  | `--include lib` | An include directory, relative to the source root. Use it again for more directories. |
32
32
  | `--define DEBUG=1` | An assembler symbol: an integer, also as `$` hex, or `true` or `false`. Use it again for more symbols. |
33
33
  | `--set-pc '$0801'` | The start address when the source does not set one. |
34
- | `--release ORIGINAL` | Build a release of the knowledge. The script defines `RELEASE_ORIGINAL=1`, so each switch has the value of that release. With `--compare`, the script compares with the file of the release. A `--define` of a switch overrides the release. |
34
+ | `--release ORIGINAL` | Build a release of the knowledge. The script defines `RELEASE_ORIGINAL=1`, so each switch has the value of that release. With `--compare`, the script compares with the file of the release. A release build does not read `config.asm`. |
35
35
  | `--compare` | Check the program byte by byte against the program in the knowledge, each segment. Put it in with `image` of the c64-knowledge skill. `--space drive8` or `--space bank0` compares with the program of that space. The script refuses `--space` without `--compare` or `--release`. |
36
36
  | `--plain` | Write only the bytes of the program, without the 2-byte load address of a PRG. `loadRange` still tells where the bytes go. |
37
37
  | `--all-symbols` | List all symbols. Without it, the list does not include the constants that the source does not use. `unusedConstants` gives their count. |
@@ -75,7 +75,7 @@ The target CPU is the 6510. The output is a C64 PRG, or the bytes only with `--p
75
75
  4. If `result` is `FAIL` and `assembled` is `false`, read `diagnostics`. Each one has a severity, a file, a line and a message. Correct the source and run the script again.
76
76
  5. To run the program, give the PRG path to the c64-emulator skill.
77
77
 
78
- The source of the c64-source skill has switches in `switches.asm`. Without an option, the build is the default build: the clean program without copy protection, trainers, cheats and crack changes, and with all corrections. This build can differ from the program in the knowledge, so `--compare` can give `FAIL`. Use `--release <label> --compare` to check the build of a release. `--define TRAINER=1` puts in the patches of the switch `TRAINER`.
78
+ The source of the c64-source skill has switches in `config.asm`. Without an option, the build uses the values in `config.asm`. With the defaults, this is the clean program without copy protection, trainers, cheats and crack changes, and with all corrections. This build can differ from the program in the knowledge, so `--compare` can give `FAIL`. Use `--release <label> --compare` to check the build of a release. To put in the patches of the switch `TRAINER`, set `TRAINER = 1` in `config.asm`. Do not use `--define` for a switch: ACME stops with `Symbol already defined`.
79
79
 
80
80
  ## Knowledge
81
81
 
@@ -53,7 +53,7 @@ await runScript({
53
53
  "max-listed": { ...OPTIONS["max-listed"], help: "list at most n symbols (default 50). The count is always given" },
54
54
  "out-symbols": { kind: "path", output: "file", value: "<file.json>", help: "write the listed symbols to this project file as {\"symbols\": [...]}: the names of the rebuild for c64-testing. Without --all-symbols, the file does not have the constants that the source does not use" },
55
55
  },
56
- notes: "Symbol values are $ and at least four hex digits. Put the program into the knowledge with knowledge.ts image of the c64-knowledge skill before --compare. Without --release and --define, the build is the default build of switches.asm: the clean program, which is not the bytes of a release when a switch has a default that the base release does not have.",
56
+ notes: "Symbol values are $ and at least four hex digits. Put the program into the knowledge with knowledge.ts image of the c64-knowledge skill before --compare. Without --release, the build has the switch values of config.asm. 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. Set a switch in config.asm, not with --define: ACME stops with Symbol already defined.",
57
57
  run: async (call) => {
58
58
  const [sourceRoot, entry] = [call.subject(0), call.subject(1)];
59
59
  const out = call.string("out")!;
@@ -127,7 +127,7 @@ A rebuilt program gets its source from the knowledge. A change is a switch and i
127
127
  7. Build with c64-assembler:
128
128
  - `--release <base label> --compare`: this build must be identical to the original.
129
129
  - The default build, with no option.
130
- - A build with `--define <SWITCH>=1` when the default build does not have the switch.
130
+ - When the default build does not have the switch: set the switch to 1 in `src/config.asm`, then build with no option. After the test, set the value back to the default if the user did not ask for the change.
131
131
  8. Test the build that has the switch:
132
132
  - Run the scenarios in `tests/` with `testing.ts test`, where the behavior must stay the same as the original.
133
133
  - Run a run file with `expect` steps that show the feature or the fix.
@@ -208,7 +208,7 @@ Then apply the joined batch with the command in `apply`.
208
208
 
209
209
  ## Modules
210
210
 
211
- A module tells the c64-source skill where a file of the generated source starts. The file runs to the next module or to the end of its segment. Each address has one module, and each file name has one module. A file name has letters, digits, underscores or hyphens, and ends in `.asm`. The c64-source skill writes `main.asm`, `loader.asm`, `switches.asm`, `constants.asm` and `macros.asm` itself. Thus a module cannot have one of these names, in upper or lower case. The title becomes the first line of the file. A `module` write without a title keeps the title that the module has. Modules have a history, and `revert` restores them.
211
+ A module tells the c64-source skill where a file of the generated source starts. The file runs to the next module or to the end of its segment. Each address has one module, and each file name has one module. A file name has letters, digits, underscores or hyphens, and ends in `.asm`. The c64-source skill writes `main.asm`, `loader.asm`, `switches.asm`, `config.asm`, `constants.asm` and `macros.asm` itself. Thus a module cannot have one of these names, in upper or lower case. The title becomes the first line of the file. A `module` write without a title keeps the title that the module has. Modules have a history, and `revert` restores them.
212
212
 
213
213
  ## Operand expressions
214
214
 
@@ -249,7 +249,7 @@ A release is a PRG or a c64-unpacker `image.json` of the program, in a folder th
249
249
 
250
250
  ### Switches
251
251
 
252
- All switches are in `switches.jsonl` of the knowledge, and the c64-source skill writes all of them to `switches.asm`. A switch has a kind, a default and the releases that have it on.
252
+ All switches are in `switches.jsonl` of the knowledge, and the c64-source skill writes all of them to `config.asm` with their defaults. A switch has a kind, a default and the releases that have it on.
253
253
 
254
254
  | Kind | What it changes | Default |
255
255
  |---|---|---|
@@ -267,7 +267,7 @@ All switches are in `switches.jsonl` of the knowledge, and the c64-source skill
267
267
  - A `switch` write without `--releases` or `--comment` keeps the releases and the comment that the switch has.
268
268
  - The script refuses a change of the base value while the switch has patches. Remove the patches first, because they hold the other state.
269
269
  - `unswitch` refuses a switch that has patches.
270
- - `switches` gives each switch with `default`, `base`, `releases`, its patches, and the defines `on` and `off`. `releases` gives each release with its define.
270
+ - `switches` gives each switch with `default`, `base`, `releases` and its patches. `releases` gives each release with its define.
271
271
 
272
272
  ### Patches
273
273
 
@@ -295,9 +295,9 @@ Rules:
295
295
 
296
296
  Build with the c64-assembler skill:
297
297
 
298
- - The default build has no options.
299
- - A release: `--release ORIGINAL`.
300
- - One switch: `--define TRAINER=1`. A define overrides the release.
298
+ - The build of `config.asm` has no options. With the defaults, this is the default build.
299
+ - A release: `--release ORIGINAL`. A release build does not read `config.asm`.
300
+ - One switch: set its value in `config.asm` of the source, for example `TRAINER = 1`.
301
301
 
302
302
  ## Macros
303
303
 
@@ -138,7 +138,7 @@ const patch = (row: PatchRow) => ({
138
138
  origin: row.origin,
139
139
  revision: row.revision,
140
140
  });
141
- /** A switch with its value in the program (`base`), the defines that put it on or off, and its patches when they are given. */
141
+ /** A switch with its value in the program (`base`), and its patches when they are given. */
142
142
  const switchRow = (row: SwitchRow, base?: string, patches?: readonly PatchRow[]) => ({
143
143
  ...spaceOf(row),
144
144
  name: row.name,
@@ -146,8 +146,6 @@ const switchRow = (row: SwitchRow, base?: string, patches?: readonly PatchRow[])
146
146
  default: row.default,
147
147
  base: baseValue(row, base),
148
148
  releases: row.releases,
149
- on: `--define ${row.name}=1`,
150
- off: `--define ${row.name}=0`,
151
149
  ...(row.comment === undefined ? {} : { comment: row.comment }),
152
150
  ...(patches === undefined ? {} : { patches: patches.map((patch) => ({ start: formatC64Address(patch.start), end: formatC64Address(patch.end) })) }),
153
151
  origin: row.origin,
@@ -78,7 +78,8 @@ When the knowledge has coverage, code that no run executed gets the line `; not
78
78
  - `main.asm` sets the address of each segment and includes the files in address order.
79
79
  - Each module in the knowledge is one file. A module starts at its address and stops at the next module or at the end of its segment. Without modules, each segment is one file, `segment_xxxx.asm`.
80
80
  - `constants.asm` holds the names of addresses outside the program, for example `EXTCOL = $d020`. The file puts the names in groups by memory area, for example zero page, VIC-II registers or CIA 1 registers. Each group is in address order. Drive code and banks have one group only. The side comment of a name tells what the address is. This text is the knowledge comment of the address. Without a comment, the text is the platform meaning. When the knowledge name is not the platform name, the platform name comes first. For an I/O mirror without a meaning, the text gives the register that the mirror repeats. Then `Used:` counts how the source uses the name. The kinds are `read`, `written`, `modified`, `called`, `jumped to`, `jumped through`, `branched to`, `pointer`, `address`, `table` and `macro argument`. `address` is an immediate operand expression. `table` is an entry in a table of addresses.
81
- - `switches.asm` holds every switch and every release of the knowledge. `main.asm` and `loader.asm` include it first. The script writes it only when the knowledge has switches or releases. For each release, a block `!ifdef RELEASE_<label>` gives each switch the value of that release. Then each switch gets its default, for example `!ifndef PROTECTION { PROTECTION = 0 }`. The switches are in groups by kind. The side comment gives the releases that have the switch on, the ranges of its patches and the comment of the switch.
81
+ - `config.asm` holds the value of each switch, for example `PROTECTION = 0`. The first value of a switch is its default. The switches are in groups by kind. The side comment gives the releases that have the switch on, the ranges of its patches and the comment of the switch. The user can change a value to 0 or 1. The next run keeps the values of the file. It adds a new switch with its default and removes a switch that the knowledge does not have.
82
+ - `switches.asm` holds every release of the knowledge. `main.asm` and `loader.asm` include it first. The script writes it only when the knowledge has switches or releases. For each release, a block `!ifdef RELEASE_<label>` gives each switch the value of that release. A build without a release reads the values from `config.asm`.
82
83
  - A label or a constant gets the name of the address in the knowledge. Without a knowledge name, it gets the platform name of the c64-memory-map skill, for example `EXTCOL` or `CHROUT`. A platform name wins over a name from an analyzer (`dxa`, `ghidra` or `heuristic`), for example `EXTCOL` over `ld020`. A `user` or `llm` name wins over a platform name. An address in the program without a name gets `l_xxxx`.
83
84
  - The source uses the names of a ROM only when the program uses that ROM. When the knowledge has coverage, a ROM is in use when a run executed code of it. A read of ROM bytes as data does not count. Without coverage, `$01` of the entry state tells which ROMs are in. When the program uses neither ROM, the zero page and pages 2 and 3 get no system names. `romNamesLeftOut` gives the ROMs that the source did not name, and the evidence. An operand expression or a macro use with such a name gets that reason.
84
85
  - `sta $d011 ; $d011: yScroll 3, rows 25, displayEnabled` is a store of an immediate to a register that the c64-memory-map skill decodes. The side comment gives the decoded value. A side comment in the knowledge replaces it.
@@ -97,7 +98,7 @@ When the knowledge has coverage, code that no run executed gets the line `; not
97
98
  - `!zone patch_PROTECTION_100e` starts a patch of the knowledge. The condition is the state that the program does not have. It is `!if TRAINER` when the base release has the switch off. It is `!if PROTECTION = 0` when the base release has it on. The block has the code of the patch and NOP to the end of the range. `else` has the original code. The labels inside the range come before the zone as `name = * + n`. Thus all builds have them.
98
99
  - Alternatives are patches of two or more switches at one range. They follow as `} else { !if FIX_B {`. A line before them stops the build with `!error` when two of them are in.
99
100
 
100
- Do not edit the generated files. The next run writes over them.
101
+ Do not edit the generated files. The next run writes over them. The values in `config.asm` are the one exception.
101
102
 
102
103
  ## Switches and macros
103
104
 
@@ -108,11 +109,13 @@ The program of the knowledge is the base release. The default build is the clean
108
109
  3. `default`: the default build must have the same length. It can change bytes only in the patches of the switches in `default.in`. These are the switches whose default is not their base value.
109
110
  4. `releases`: the script builds each release with `RELEASE_<label>=1` and compares it with the file of the release.
110
111
 
112
+ The checks use the defaults and the values of the knowledge. They do not use the values in `config.asm`. When `config.asm` has a value that is not the default, `config.notDefault` gives the switch, its value and its default.
113
+
111
114
  Build the program with the c64-assembler skill:
112
115
 
113
- - The default build: no option.
116
+ - The build of `config.asm`: no option. With the defaults, this is the default build.
114
117
  - A release: `--release ORIGINAL`.
115
- - One switch: `--define TRAINER=1`.
118
+ - One switch: set its value in `config.asm`, for example `TRAINER = 1`. Do not use `--define` for a switch. ACME stops with `Symbol already defined`, because `config.asm` also gives the switch a value.
116
119
 
117
120
  The script writes a patch only when its range is complete items of one file. A patch cannot cut an instruction. Its switch name cannot be a name of the source.
118
121
 
@@ -196,7 +199,7 @@ tests/ the tests of the project, changed for the new program
196
199
  .c64-re-tools/knowledge/ the knowledge of the new program
197
200
  ```
198
201
 
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.
202
+ - The source has no mark line, no `switches.asm` or `config.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
203
  - 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
204
  - The tests come from the JSON files in `tests/`:
202
205
  - 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.
@@ -7,7 +7,8 @@
7
7
  // expression of the knowledge is written in place of its number. A
8
8
  // patch is written as !if SWITCH { code } else { original }, with the
9
9
  // condition of the state that the program does not have, and a macro use as
10
- // one +name args line. switches.asm holds every switch and release.
10
+ // one +name args line. config.asm holds the value of each switch, and
11
+ // switches.asm the values of each release.
11
12
 
12
13
  import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
13
14
  import { WireFailure } from "#src/host-client/tools.ts";
@@ -45,7 +46,7 @@ export interface SourceInput {
45
46
  operands?: ReadonlyArray<OperandExpression & { address: number }>;
46
47
  /** Patches of the knowledge: code for a range in the state of the switch that the program does not have. */
47
48
  patches?: ReadonlyArray<{ start: number; end: number; switch: string; code: string; comment?: string }>;
48
- /** The switches of the knowledge, each with its value in the program. switches.asm holds them all. */
49
+ /** The switches of the knowledge, each with its value in the program. config.asm holds them all. */
49
50
  switches?: ReadonlyArray<SourceSwitch>;
50
51
  /** The releases of the knowledge: switches.asm gives each one its switch values. */
51
52
  releases?: ReadonlyArray<SourceRelease>;
@@ -831,7 +832,7 @@ export function switchesOf(layout: Pick<Layout, "patches">): Map<string, PatchBl
831
832
  return new Map([...switches].sort(([a], [b]) => (a < b ? -1 : 1)));
832
833
  }
833
834
 
834
- /** The groups of switches.asm, in order, with the default of each group. */
835
+ /** The groups of config.asm, in order, with the default of each group. */
835
836
  const SWITCH_GROUPS: ReadonlyArray<{ kind: SwitchKind; title: string }> = [
836
837
  { kind: "protection", title: "Copy protection: off by default" },
837
838
  { kind: "trainer", title: "Trainers: off by default" },
@@ -844,30 +845,38 @@ const SWITCH_GROUPS: ReadonlyArray<{ kind: SwitchKind; title: string }> = [
844
845
  /** True when the source has switches.asm: the knowledge has switches or releases. */
845
846
  export const hasSwitchFile = (layout: Pick<Layout, "switches" | "releases">) => layout.switches.length > 0 || layout.releases.length > 0;
846
847
 
848
+ /** The file with the value of each switch. The user edits it, and generate keeps the values. */
849
+ export const CONFIG_FILE = "config.asm";
850
+
851
+ /** A value line of config.asm: NAME = 0 or NAME = 1. */
852
+ const CONFIG_VALUE = /^\s*([A-Z][A-Z0-9_]*)\s*=\s*([01])\s*(?:;.*)?$/;
853
+
854
+ /** The values of the switches in a config.asm text, by name. Lines that are not a value line are not read. */
855
+ export function configValues(text: string): Map<string, 0 | 1> {
856
+ const values = new Map<string, 0 | 1>();
857
+ for (const line of text.split(/\r?\n/)) {
858
+ const match = CONFIG_VALUE.exec(line);
859
+ if (match !== null) values.set(match[1]!, match[2] === "1" ? 1 : 0);
860
+ }
861
+ return values;
862
+ }
863
+
847
864
  /**
848
- * switches.asm: every switch of the knowledge in one place. A release block
849
- * gives each switch the value of that release when the build defines
850
- * RELEASE_<label>; then each switch gets its default unless the build defines
851
- * it. A comment tells the releases that have the switch on, and its patches.
865
+ * config.asm: the value of each switch as a plain assignment, grouped by
866
+ * kind. Without a value, a switch has its default. A comment tells the
867
+ * releases that have the switch on, and its patches.
852
868
  */
853
- function switchesText(layout: Layout): string {
869
+ export function configText(layout: Pick<Layout, "switches" | "patches">, values: ReadonlyMap<string, number> = new Map()): string {
854
870
  const patches = switchesOf(layout);
855
871
  const out = [
856
- "; The switches of the patches. Each switch is 0 or 1.",
857
- "; The default build is the clean program: copy protection, trainers, cheats",
858
- "; and changes of a crack are off, and the fixes of the releases are on.",
859
- `; Build a release with -D${RELEASE_DEFINE}<label>=1 (c64-assembler --release <label>).`,
860
- "; Set one switch with -DNAME=0 or -DNAME=1 (c64-assembler --define NAME=1).",
872
+ "; Generated by c64-source. Edit the values here: generate keeps them.",
873
+ "; The switches of the build. Each switch is 0 or 1: change a value, then build again.",
874
+ "; The defaults give the clean program: copy protection, trainers, cheats and",
875
+ "; changes of a crack are 0, and the fixes of the releases are 1.",
876
+ "; generate adds a new switch with its default and removes a switch that the",
877
+ `; knowledge does not have. The build of a release does not read this file.`,
861
878
  ];
862
- if (layout.releases.length > 0) out.push("", "; Releases");
863
- for (const release of layout.releases) {
864
- out.push(`; ${release.label}${release.base ? " (the program of the knowledge)" : ""}: ${release.file}${release.comment === undefined ? "" : `. ${release.comment.replace(/\s*\r?\n\s*/g, " ")}`}`);
865
- out.push(`!ifdef ${RELEASE_DEFINE}${release.label} {`);
866
- for (const row of layout.switches) out.push(`${INDENT}!ifndef ${row.name} { ${row.name} = ${row.releases.includes(release.label) ? 1 : 0} }`);
867
- out.push("}");
868
- }
869
- const line = (row: SourceSwitch) => `!ifndef ${row.name} { ${row.name} = ${row.default} }`;
870
- const width = Math.max(0, ...layout.switches.map((row) => line(row).length));
879
+ const width = Math.max(0, ...layout.switches.map((row) => row.name.length));
871
880
  for (const group of SWITCH_GROUPS) {
872
881
  const rows = layout.switches.filter((row) => row.kind === group.kind);
873
882
  if (rows.length === 0) continue;
@@ -879,12 +888,36 @@ function switchesText(layout: Layout): string {
879
888
  ranges.length === 0 ? "no patch" : ranges.join(", "),
880
889
  ...(row.comment === undefined ? [] : [row.comment.replace(/\s*\r?\n\s*/g, " ")]),
881
890
  ];
882
- out.push(`${line(row).padEnd(width)} ; ${parts.join(". ")}`);
891
+ out.push(`${row.name.padEnd(width)} = ${values.get(row.name) ?? row.default} ; ${parts.join(". ")}`);
883
892
  }
884
893
  }
885
894
  return `${out.join("\n")}\n`;
886
895
  }
887
896
 
897
+ /**
898
+ * switches.asm: the releases of the knowledge. A release block gives each
899
+ * switch the value of that release when the build defines RELEASE_<label>.
900
+ * A build without a release reads the values from config.asm.
901
+ */
902
+ function switchesText(layout: Layout): string {
903
+ const out = [
904
+ "; The releases of the knowledge. config.asm holds the value of each switch.",
905
+ `; Build a release with -D${RELEASE_DEFINE}<label>=1 (c64-assembler --release <label>):`,
906
+ "; then each switch has the value of that release, and the build does not read config.asm.",
907
+ ];
908
+ for (const release of layout.releases) {
909
+ out.push("", `; ${release.label}${release.base ? " (the program of the knowledge)" : ""}: ${release.file}${release.comment === undefined ? "" : `. ${release.comment.replace(/\s*\r?\n\s*/g, " ")}`}`);
910
+ out.push(`!ifdef ${RELEASE_DEFINE}${release.label} {`);
911
+ for (const row of layout.switches) out.push(`${INDENT}${row.name} = ${row.releases.includes(release.label) ? 1 : 0}`);
912
+ out.push("}");
913
+ }
914
+ if (layout.switches.length > 0) {
915
+ const include = `!source "${CONFIG_FILE}"`;
916
+ out.push("", layout.releases.reduceRight((inner, release) => `!ifndef ${RELEASE_DEFINE}${release.label} { ${inner} }`, include));
917
+ }
918
+ return `${out.join("\n")}\n`;
919
+ }
920
+
888
921
  /** constants.asm: the names outside the image by platform area, each with what it is and how the source uses it. */
889
922
  function constantsText(layout: Layout): { text: string; labels: SourceLabel[] } {
890
923
  const { describe } = layout;
@@ -1198,6 +1231,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1198
1231
  }
1199
1232
 
1200
1233
  if (hasSwitchFile(layout)) result.files.push({ name: "switches.asm", text: switchesText(layout) });
1234
+ if (layout.switches.length > 0) result.files.push({ name: CONFIG_FILE, text: configText(layout) });
1201
1235
  const constants = constantsText(layout);
1202
1236
  result.files.push({ name: "constants.asm", text: constants.text });
1203
1237
  result.labels.push(...constants.labels);
@@ -41,7 +41,7 @@ import { knowledgeNames } from "#src/knowledge/names.ts";
41
41
  import { COPIER_SOURCE, LOADER_JUMP, loaderLimits, planLoader, rasterLine, loaderState, simulate, stopCause, VIC_DISPLAY_REGISTERS, type EntryState, type LoaderPlan } from "./lib/loader.ts";
42
42
  import { instructionWith, OPCODES } from "#src/opcodes.ts";
43
43
  import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
44
- import { entriesInData, entryOutsideImage, hasSwitchFile, layout, literalOperand, probeForms, render, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
44
+ import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasSwitchFile, layout, literalOperand, probeForms, render, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
45
45
 
46
46
  /** At most this many diagnostics or differences of one check. */
47
47
  const MAX_DIAGNOSTICS = 20;
@@ -401,9 +401,18 @@ function compareBuilds(built: Assembled, ranges: readonly AddressRange[], base:
401
401
  return outside === undefined ? { result: "fits", changedBytes: changed } : { result: "changes outside", changedBytes: changed, outside };
402
402
  }
403
403
 
404
- /** Builds the source with the defines and compares it with the build of the base release (compareBuilds). */
405
- async function checkBuild(files: Array<{ name: string; text: string }>, defines: Record<string, number>, ranges: readonly AddressRange[], base: { program: Buffer; start: number }): Promise<BuildCheck> {
406
- return compareBuilds(await assembleFiles(files, "main.asm", defines), ranges, base);
404
+ /**
405
+ * The files with config.asm at the switch values. A build takes the switches
406
+ * from config.asm: a define of a switch is an error, because config.asm also
407
+ * gives it a value. A switch without a value has its default.
408
+ */
409
+ function withValues(files: Array<{ name: string; text: string }>, laid: Pick<Layout, "switches" | "patches">, values: ReadonlyMap<string, number>): Array<{ name: string; text: string }> {
410
+ return files.map((file) => (file.name === CONFIG_FILE ? { ...file, text: configText(laid, values) } : file));
411
+ }
412
+
413
+ /** Builds the source and compares it with the build of the base release (compareBuilds). */
414
+ async function checkBuild(files: Array<{ name: string; text: string }>, ranges: readonly AddressRange[], base: { program: Buffer; start: number }): Promise<BuildCheck> {
415
+ return compareBuilds(await assembleFiles(files, "main.asm"), ranges, base);
407
416
  }
408
417
 
409
418
  /** What a build with one switch at the value that the base release does not have gives. */
@@ -412,22 +421,19 @@ type SwitchCheck = BuildCheck & {
412
421
  kind: string;
413
422
  default: number;
414
423
  base: number;
415
- define: string;
416
424
  patches: Array<{ start: string; end: string; bytes: number; insideNames?: string[] }>;
417
425
  };
418
426
 
419
427
  /** Builds the source with one switch changed from its base value; only the ranges of its patches may change. */
420
- async function checkSwitch(row: SourceSwitch, patches: PatchBlock[], files: Array<{ name: string; text: string }>, defines: Record<string, number>, base: { program: Buffer; start: number }, names: Layout["names"]): Promise<SwitchCheck> {
421
- const value = 1 - row.base;
422
- const built = await checkBuild(files, { ...defines, [row.name]: value }, patches, base);
428
+ async function checkSwitch(row: SourceSwitch, patches: PatchBlock[], files: Array<{ name: string; text: string }>, laid: Layout, baseValues: ReadonlyMap<string, number>, base: { program: Buffer; start: number }): Promise<SwitchCheck> {
429
+ const built = await checkBuild(withValues(files, laid, new Map([...baseValues, [row.name, 1 - row.base]])), patches, base);
423
430
  return {
424
431
  name: row.name,
425
432
  kind: row.kind,
426
433
  default: row.default,
427
434
  base: row.base,
428
- define: `--define ${row.name}=${value}`,
429
435
  patches: patches.map((patch) => {
430
- const inside = patch.inner.map((address) => names.get(address)!);
436
+ const inside = patch.inner.map((address) => laid.names.get(address)!);
431
437
  return { start: formatC64Address(patch.start), end: formatC64Address(patch.end), bytes: patch.end - patch.start + 1, ...(inside.length === 0 ? {} : { insideNames: inside }) };
432
438
  }),
433
439
  ...built,
@@ -633,7 +639,7 @@ interface SourceOptions {
633
639
  /** The first line of each file, or none. */
634
640
  mark?: string;
635
641
  /** The switch values of the build that must give the program. */
636
- defines: Record<string, number>;
642
+ values: ReadonlyMap<string, number>;
637
643
  /** The instructions of an earlier decode: then Ghidra does not run again. */
638
644
  decoded?: DecodedProgram;
639
645
  /** Mark the code that no run executed. Without the marks, the coverage only gives the seeds of Ghidra and the ROM use. */
@@ -645,7 +651,7 @@ interface SourceOptions {
645
651
 
646
652
  /**
647
653
  * The source of a knowledge: the layout, the rendered files and the build
648
- * with the defines. An operand expression that ACME refuses or assembles to
654
+ * with the switch values. An operand expression that ACME refuses or assembles to
649
655
  * other bytes is written as its number, and a macro use as its instructions;
650
656
  * then the source is assembled again.
651
657
  */
@@ -696,7 +702,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
696
702
  }
697
703
  // With a mark, every file starts with it.
698
704
  const { mark } = options;
699
- const marked = (list: Array<{ name: string; text: string }>) => (mark === undefined ? list : list.map((file) => ({ ...file, text: `${mark}\n${file.text}` })));
705
+ const marked = (list: Array<{ name: string; text: string }>) => (mark === undefined ? list : list.map((file) => (file.name === CONFIG_FILE ? file : { ...file, text: `${mark}\n${file.text}` })));
700
706
  const markLines = mark === undefined ? 0 : 1;
701
707
  const loaderFiles = loader === undefined ? [] : [{ name: "loader.asm", text: loader.text }];
702
708
  const numbers = new Map<number, string>();
@@ -705,7 +711,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
705
711
  if (laid.macroUses.size > 0) for (const [start, reason] of await probeUses(laid, rendered, image)) asInstructions.set(start, reason);
706
712
  if (asInstructions.size > 0) rendered = render(laid, asBytes, header, numbers, asInstructions);
707
713
  let files = marked([...rendered.files, ...loaderFiles]);
708
- let built = await assembleFiles(files, "main.asm", options.defines);
714
+ let built = await assembleFiles(withValues(files, laid, options.values), "main.asm");
709
715
  for (let round = 0; round < ROUNDS && (rendered.expressions.length > 0 || rendered.uses.length > 0); round++) {
710
716
  const blamed = blame(rendered, built, image, markLines);
711
717
  if (blamed.numbers.size === 0 && blamed.uses.size === 0) break;
@@ -713,18 +719,18 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
713
719
  for (const [start, reason] of blamed.uses) asInstructions.set(start, reason);
714
720
  rendered = render(laid, asBytes, header, numbers, asInstructions);
715
721
  files = marked([...rendered.files, ...loaderFiles]);
716
- built = await assembleFiles(files, "main.asm", options.defines);
722
+ built = await assembleFiles(withValues(files, laid, options.values), "main.asm");
717
723
  }
718
724
  return { romUse, instructions, dataOnly, laid, rendered, files, built, loader, missingEntry, loaderRefused };
719
725
  }
720
726
 
721
727
  /**
722
- * Assembles loader.asm with the defines and simulates its copies: the
728
+ * Assembles loader.asm with the switch values and simulates its copies: the
723
729
  * loader as it loads, then every copy in its order, byte by byte. A layout
724
730
  * other than the plan is a defect of the script.
725
731
  */
726
- async function buildLoader(files: Array<{ name: string; text: string }>, loader: LoaderPlan, image: ProgramImage, state: EntryState, defines: Record<string, number>): Promise<{ program: Buffer; symbols: AssembledSymbol[]; jump: number; copierSource: number; expected: (address: number) => number } | { diagnostics: Diagnostic[] }> {
727
- const loaderBuilt = await assembleFiles(files, "loader.asm", defines);
732
+ async function buildLoader(files: Array<{ name: string; text: string }>, laid: Layout, loader: LoaderPlan, image: ProgramImage, state: EntryState, values: ReadonlyMap<string, number>): Promise<{ program: Buffer; symbols: AssembledSymbol[]; jump: number; copierSource: number; expected: (address: number) => number } | { diagnostics: Diagnostic[] }> {
733
+ const loaderBuilt = await assembleFiles(withValues(files, laid, values), "loader.asm");
728
734
  if (loaderBuilt.program === undefined) return { diagnostics: loaderBuilt.diagnostics.slice(0, MAX_DIAGNOSTICS) };
729
735
  const program = loaderBuilt.program;
730
736
  const memory = new Int16Array(0x10000).fill(-1);
@@ -766,7 +772,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
766
772
  // Read the entry state before the long steps, so a bad state stops the run at once.
767
773
  const state = loaderWanted ? loaderState(image.state, "the entry state of the knowledge") : undefined;
768
774
  // Every build that is compared with the program is the build of the base release: each switch at its base value.
769
- const baseDefines = Object.fromEntries(knowledge.switches.map((row) => [row.name, row.base]));
775
+ const baseValues = new Map(knowledge.switches.map((row) => [row.name, row.base]));
770
776
  const header = [`Generated by c64-source from knowledge revision ${knowledge.revision}${space === DEFAULT_SPACE ? "" : ` in space ${space}`}.`, "Change names, comments, regions and modules in knowledge, then generate again."];
771
777
  const loaderHeader = [`Loader generated by c64-source from knowledge revision ${knowledge.revision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."];
772
778
  const { romUse, dataOnly, laid, rendered, files, built, loader, missingEntry, loaderRefused } = await buildSource(knowledge, {
@@ -774,12 +780,17 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
774
780
  entries,
775
781
  header,
776
782
  mark: GENERATED_LINE,
777
- defines: baseDefines,
783
+ values: baseValues,
778
784
  notExecutedMarks: true,
779
785
  ...(state === undefined ? {} : { state, loaderHeader }),
780
786
  });
787
+ // config.asm keeps the value of each switch that it already has: the user sets the switches there.
788
+ const configPath = resolveProjectPath(`${out}/${CONFIG_FILE}`);
789
+ const given = existsSync(configPath) ? configValues(readFileSync(configPath, "utf8")) : new Map<string, 0 | 1>();
790
+ const kept = new Map(laid.switches.flatMap((row) => (given.has(row.name) ? [[row.name, given.get(row.name)!] as const] : [])));
791
+ const notDefault = laid.switches.flatMap((row) => (kept.has(row.name) && kept.get(row.name) !== row.default ? [{ name: row.name, value: kept.get(row.name)!, default: row.default }] : []));
781
792
  const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
782
- const written: Written[] = files.map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
793
+ const written: Written[] = withValues(files, laid, kept).map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
783
794
  written.push(writeReported(`${out}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.revision, files), { what: "--out" }));
784
795
  const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
785
796
  const inData = entriesInData(entries, knowledge.regions);
@@ -801,6 +812,8 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
801
812
  out,
802
813
  files: written,
803
814
  sourceMap: `${out}/${SOURCE_MAP_FILE}`,
815
+ // The values that config.asm keeps and that are not the default: a build of the source is not the default build.
816
+ ...(notDefault.length === 0 ? {} : { config: { file: `${out}/${CONFIG_FILE}`, notDefault } }),
804
817
  revision: knowledge.revision,
805
818
  instructions: rendered.instructions,
806
819
  dataBytes: rendered.dataBytes,
@@ -857,7 +870,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
857
870
  const withPatches = switchesOf(laid);
858
871
  for (const row of laid.switches) {
859
872
  const patches = withPatches.get(row.name);
860
- if (patches !== undefined) switches.push(await checkSwitch(row, patches, files, baseDefines, baseBuild, laid.names));
873
+ if (patches !== undefined) switches.push(await checkSwitch(row, patches, files, laid, baseValues, baseBuild));
861
874
  }
862
875
  if (switches.length > 0) output.switches = switches;
863
876
  // The default build: the patches of each switch whose default is not its base value are in, and nothing else changes.
@@ -865,7 +878,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
865
878
  if (laid.switches.length > 0) {
866
879
  const changed = laid.switches.filter((row) => row.default !== row.base);
867
880
  const ranges = changed.flatMap((row) => withPatches.get(row.name) ?? []);
868
- const built = await checkBuild(files, {}, ranges, baseBuild);
881
+ const built = await checkBuild(withValues(files, laid, new Map()), ranges, baseBuild);
869
882
  output.default = { in: changed.map((row) => row.name), ...built };
870
883
  defaultFailed = built.result !== "fits";
871
884
  }
@@ -879,7 +892,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
879
892
  if (loader === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
880
893
 
881
894
  // The entry state is the state of the base release: the loader is built and checked with it.
882
- const loaderBuilt = await buildLoader(files, loader, image, state, baseDefines);
895
+ const loaderBuilt = await buildLoader(files, laid, loader, image, state, baseValues);
883
896
  if ("diagnostics" in loaderBuilt) return { output: { ...output, loader: { verified: false, reason: "loader.asm does not assemble.", diagnostics: loaderBuilt.diagnostics } }, removed, failed: true };
884
897
  const { program, jump, copierSource, expected } = loaderBuilt;
885
898
  const loaderPath = `${out}/loader.prg`;
@@ -977,8 +990,8 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
977
990
  const state = image.state === undefined || image.entry === undefined ? undefined : loaderState(image.state, "the entry state of the knowledge");
978
991
 
979
992
  // 1. The source of the knowledge must give the base release byte for byte, with every patch in it.
980
- const baseDefines = Object.fromEntries(knowledge.switches.map((row) => [row.name, row.base]));
981
- const original = await buildSource(knowledge, { space: DEFAULT_SPACE, entries: [], header: [], defines: baseDefines, notExecutedMarks: false });
993
+ const baseValues = new Map(knowledge.switches.map((row) => [row.name, row.base]));
994
+ const original = await buildSource(knowledge, { space: DEFAULT_SPACE, entries: [], header: [], values: baseValues, notExecutedMarks: false });
982
995
  const fix = "Run source.ts generate, correct the knowledge until generate gives PASS, then export again.";
983
996
  if (original.built.program === undefined) return { result: "FAIL", stage: "original", reason: `The source of the knowledge does not assemble. ${fix}`, diagnostics: original.built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
984
997
  const checked = check(original.built.program, original.built.start!, image);
@@ -996,11 +1009,10 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
996
1009
  throw new Refusal("invalid-input", `The switches ${both.map((item) => item.switch).join(" and ")} change ${formatC64Address(patch.start)}-${formatC64Address(patch.end)} in different ways, and the export puts both in. Give all but one of them the kind change with --default and the value of the base release (knowledge.ts switch), then export again.`);
997
1010
  }
998
1011
  }
999
- const exportDefines = Object.fromEntries(values);
1000
1012
  const withPatches = switchesOf(original.laid);
1001
1013
  const changedSwitches = knowledge.switches.filter((row) => values.get(row.name) !== row.base);
1002
1014
  const patchesIn = changedSwitches.flatMap((row) => withPatches.get(row.name) ?? []);
1003
- const baked = await assembleFiles(original.files, "main.asm", exportDefines);
1015
+ const baked = await assembleFiles(withValues(original.files, original.laid, values), "main.asm");
1004
1016
  const bakedCheck = compareBuilds(baked, patchesIn, { program: original.built.program, start: original.built.start! });
1005
1017
  const switches = knowledge.switches.map((row) => ({ name: row.name, kind: row.kind, base: row.base, value: values.get(row.name)! }));
1006
1018
  if (bakedCheck.result !== "fits" || baked.program === undefined) return { result: "FAIL", stage: "switches", reason: "The build with the export values of the switches does not fit. Build each switch alone with source.ts generate and correct its patches.", switches, build: bakedCheck };
@@ -1086,7 +1098,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1086
1098
  space: DEFAULT_SPACE,
1087
1099
  entries: [],
1088
1100
  header,
1089
- defines: {},
1101
+ values: new Map(),
1090
1102
  decoded: { instructions, dataOnly: decoded.dataOnly },
1091
1103
  notExecutedMarks: false,
1092
1104
  ...(state === undefined ? {} : { state, loaderHeader: [`The loader of ${name}.`, "It copies the segments into place, sets the entry state and jumps to the entry."] }),
@@ -1100,7 +1112,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1100
1112
  let loaderOutput: Record<string, unknown> | undefined;
1101
1113
  if (state !== undefined) {
1102
1114
  if (exported.loader === undefined) return { result: "FAIL", stage: "loader", reason: exported.loaderRefused ?? "The loader could not be planned." };
1103
- const loaderBuilt = await buildLoader(exported.files, exported.loader, derived.program, state, {});
1115
+ const loaderBuilt = await buildLoader(exported.files, exported.laid, exported.loader, derived.program, state, new Map());
1104
1116
  if ("diagnostics" in loaderBuilt) return { result: "FAIL", stage: "loader", reason: "loader.asm does not assemble. This is a defect of the c64-source script.", diagnostics: loaderBuilt.diagnostics };
1105
1117
  baseline = { program: loaderBuilt.program, symbols: loaderBuilt.symbols, entryFile: "loader.asm" };
1106
1118
  loaderOutput = {
@@ -88,7 +88,7 @@ export type CoverageKind = (typeof COVERAGE_KINDS)[number];
88
88
  export const MEMORY_ROW = 64;
89
89
 
90
90
  /** Files that c64-source writes itself: no module can have these names. */
91
- export const GENERATED_FILES = ["main.asm", "loader.asm", "switches.asm", "constants.asm", "macros.asm"] as const;
91
+ export const GENERATED_FILES = ["main.asm", "loader.asm", "switches.asm", "config.asm", "constants.asm", "macros.asm"] as const;
92
92
 
93
93
  /** True for a generated file name in any letter case: the file systems of macOS and Windows ignore case. */
94
94
  export function isGeneratedFile(file: string): boolean {