@henols/c64-re-tools 2.2.0-rc.1 → 2.2.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,11 +10,11 @@
10
10
  // FAIL.
11
11
 
12
12
  import { createHash } from "node:crypto";
13
- import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
14
- import { join } from "node:path";
13
+ import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
14
+ import { basename, join, relative, sep } from "node:path";
15
15
 
16
16
  import { Refusal } from "#src/errors.ts";
17
- import { type AddressRange, coverageSeedKinds, formatC64Address, textToPetscii } from "#src/c64.ts";
17
+ import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
18
18
  import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
19
19
  import { readImage, type Image } from "#src/host-client/image.ts";
20
20
  import { readProjectFile } from "#src/host-client/transfer.ts";
@@ -22,21 +22,25 @@ import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
22
22
  import { writeReported, type Written } from "#src/host-client/transfer.ts";
23
23
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
24
24
  import { conflicts } from "#src/knowledge/conflicts.ts";
25
- import { openForRead } from "#src/knowledge/database.ts";
25
+ import { openForRead, withWrite } from "#src/knowledge/database.ts";
26
26
  import { identifiers } from "#src/knowledge/expression.ts";
27
- import { analyzedBytes, programCoverage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
28
- import { ANALYZER_NAME_ORDER, baseValue, currentRevision, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
29
- import { CODE_REGION_TYPES, DEFAULT_SPACE, RELEASE_DEFINE, type Space } from "#src/knowledge/schema.ts";
30
- import { assemble } from "#src/native/acme.ts";
27
+ import { analyzedBytes, memoryRows, programCoverage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
28
+ import { ANALYZER_NAME_ORDER, baseValue, currentRevision, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
29
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, RELEASE_DEFINE, type Space } from "#src/knowledge/schema.ts";
30
+ import { subtract, write } from "#src/knowledge/write.ts";
31
+ import { assemble, symbolsFileText } from "#src/native/acme.ts";
31
32
  import { analyze } from "#src/native/ghidra/analyze.ts";
32
33
  import { localToolContext } from "#src/native/local.ts";
33
34
  import { GHIDRA_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
34
35
  import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romUseOfProgram } from "#src/platform.ts";
35
- import { resolveProjectPath } from "#src/project.ts";
36
+ import { ensureLocal, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRoot, resolveProjectPath } from "#src/project.ts";
37
+ import { isoCet } from "#src/time.ts";
38
+ import { zipFiles } from "#src/zip.ts";
36
39
  import { listed, OPTIONS, runScript, UsageError, type Call } from "#src/script.ts";
37
40
  import { knowledgeNames } from "#src/knowledge/names.ts";
38
41
  import { COPIER_SOURCE, LOADER_JUMP, loaderLimits, planLoader, rasterLine, loaderState, simulate, stopCause, VIC_DISPLAY_REGISTERS, type EntryState, type LoaderPlan } from "./lib/loader.ts";
39
42
  import { instructionWith, OPCODES } from "#src/opcodes.ts";
43
+ import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
40
44
  import { entriesInData, entryOutsideImage, hasSwitchFile, layout, literalOperand, probeForms, render, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
41
45
 
42
46
  /** At most this many diagnostics or differences of one check. */
@@ -86,6 +90,9 @@ function readKnowledge(space: Space, analyzerNames = false) {
86
90
  }
87
91
  }
88
92
 
93
+ /** The knowledge of one space that a source is made from. */
94
+ type SourceKnowledge = ReturnType<typeof readKnowledge>;
95
+
89
96
  /**
90
97
  * The names of the user and the LLM, and for each address without one the
91
98
  * first analyzer name in the order heuristic, Ghidra, DXA. An analyzer
@@ -114,7 +121,7 @@ function withAnalyzerNames(symbols: SymbolRow[], second: SymbolRow[]): SymbolRow
114
121
  * is in the source. A program without a seed has no known code: it is data
115
122
  * only, and Ghidra does not run.
116
123
  */
117
- async function decode(image: ProgramImage, knowledge: ReturnType<typeof readKnowledge>, entries: number[], coverage: Uint8Array | undefined): Promise<{ instructions: Map<number, number>; dataOnly: boolean }> {
124
+ async function decode(image: ProgramImage, knowledge: Pick<SourceKnowledge, "routines" | "regions">, entries: number[], coverage: Uint8Array | undefined): Promise<{ instructions: Map<number, number>; dataOnly: boolean }> {
118
125
  const inImage = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
119
126
  const seeds = new Set<number>([...(image.entry === undefined ? [] : [image.entry]), ...entries]);
120
127
  for (const address of knowledge.routines) seeds.add(address);
@@ -362,14 +369,15 @@ interface BuildCheck {
362
369
  diagnostics?: Diagnostic[];
363
370
  }
364
371
 
372
+ /** What ACME gives for a source: the program, or the diagnostics. */
373
+ type Assembled = Awaited<ReturnType<typeof assembleFiles>>;
374
+
365
375
  /**
366
- * Builds the source with the defines and compares it with the build of the
367
- * base release: only the ranges may change, and the program keeps its start
368
- * and length. A patch longer than its range, or two alternatives together,
369
- * stop ACME with !error.
376
+ * Compares a build with the build of the base release: only the ranges may
377
+ * change, and the program keeps its start and length. A patch longer than its
378
+ * range, or two alternatives together, stop ACME with !error.
370
379
  */
371
- async function checkBuild(files: Array<{ name: string; text: string }>, defines: Record<string, number>, ranges: readonly AddressRange[], base: { program: Buffer; start: number }): Promise<BuildCheck> {
372
- const built = await assembleFiles(files, "main.asm", defines);
380
+ function compareBuilds(built: Assembled, ranges: readonly AddressRange[], base: { program: Buffer; start: number }): BuildCheck {
373
381
  if (built.program === undefined) {
374
382
  const overflow = built.diagnostics.flatMap((diagnostic) => {
375
383
  const found = /The patch \S+ at (\$[0-9a-f]{4}) has .*|\S+ and \S+ change (\$[0-9a-f]{4})-\$[0-9a-f]{4}: turn on one of them\./.exec(diagnostic.message);
@@ -393,6 +401,11 @@ async function checkBuild(files: Array<{ name: string; text: string }>, defines:
393
401
  return outside === undefined ? { result: "fits", changedBytes: changed } : { result: "changes outside", changedBytes: changed, outside };
394
402
  }
395
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);
407
+ }
408
+
396
409
  /** What a build with one switch at the value that the base release does not have gives. */
397
410
  type SwitchCheck = BuildCheck & {
398
411
  name: string;
@@ -608,26 +621,41 @@ function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boole
608
621
  return removed;
609
622
  }
610
623
 
611
- async function generate(call: Call): Promise<{ output: Record<string, unknown>; failed: boolean; removed: string[] }> {
612
- const out = call.string("out")!;
613
- const entries = call.addresses("entry");
614
- const max = call.count("max-listed")!;
615
- const space = call.space;
616
- const loaderWanted = call.flag("loader");
617
- if (space !== DEFAULT_SPACE && loaderWanted) throw new UsageError("--loader works only in space c64");
618
- const knowledge = readKnowledge(space, call.flag("analyzer-names"));
624
+ /** The instructions that Ghidra decoded, and whether the program has known code. */
625
+ type DecodedProgram = Awaited<ReturnType<typeof decode>>;
626
+
627
+ /** How buildSource makes and checks the source of a knowledge. */
628
+ interface SourceOptions {
629
+ space: Space;
630
+ /** More entry points for Ghidra. */
631
+ entries: number[];
632
+ header: string[];
633
+ /** The first line of each file, or none. */
634
+ mark?: string;
635
+ /** The switch values of the build that must give the program. */
636
+ defines: Record<string, number>;
637
+ /** The instructions of an earlier decode: then Ghidra does not run again. */
638
+ decoded?: DecodedProgram;
639
+ /** Mark the code that no run executed. Without the marks, the coverage only gives the seeds of Ghidra and the ROM use. */
640
+ notExecutedMarks: boolean;
641
+ /** With an entry state, the loader is planned too. */
642
+ state?: EntryState;
643
+ loaderHeader?: string[];
644
+ }
645
+
646
+ /**
647
+ * 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
649
+ * other bytes is written as its number, and a macro use as its instructions;
650
+ * then the source is assembled again.
651
+ */
652
+ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
653
+ const { space } = options;
619
654
  const image = knowledge.program;
620
655
  const coverage = knowledge.coverage;
621
- if (loaderWanted && (image.state === undefined || image.entry === undefined)) {
622
- throw new Refusal("not-found", "--loader needs the entry and the entry state of a c64-unpacker capture in the knowledge: put the capture in with knowledge.ts image <image.json>");
623
- }
624
- // Read the entry state before the long steps, so a bad state stops the run at once.
625
- const state = loaderWanted ? loaderState(image.state, "the entry state of the knowledge") : undefined;
626
656
  const romUse = romUseOfProgram(coverage, image.state);
627
657
  const platform = platformNamesFor(romUse);
628
- const { instructions, dataOnly } = await decode(image, knowledge, entries, coverage);
629
- // Every build that is compared with the program is the build of the base release: each switch at its base value.
630
- const baseDefines = Object.fromEntries(knowledge.switches.map((row) => [row.name, row.base]));
658
+ const { instructions, dataOnly } = options.decoded ?? (await decode(image, knowledge, options.entries, coverage));
631
659
  const laid = layout({
632
660
  segments: image.segments,
633
661
  byteAt: image.byteAt,
@@ -644,48 +672,112 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
644
672
  releases: knowledge.releases.map((release) => ({ label: release.label, file: release.file, base: release.base, ...(release.comment === undefined ? {} : { comment: release.comment }) })),
645
673
  macros: knowledge.macros,
646
674
  macroUses: knowledge.macroUses,
647
- ...(coverage === undefined ? {} : { coverage }),
675
+ ...(coverage === undefined || !options.notExecutedMarks ? {} : { coverage }),
648
676
  // The platform names are C64 names: drive code and banks get none. A ROM that the program does not use gives none.
649
677
  ...(space === DEFAULT_SPACE ? { platform, platformLeftOut: leftOutNames(platform), describe: describeAddress, decode: decodeRegister } : {}),
650
678
  });
651
679
  const asBytes = await probe(laid);
652
- 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."];
680
+ const { header } = options;
653
681
  let loader: LoaderPlan | undefined;
654
682
  // An image without its entry has no program: the source is still written and checked, but the run fails.
655
683
  const missingEntry = entryOutsideImage(image.entry, image.segments);
656
684
  // A loader that cannot be planned does not stop the source: the source is written and checked, and the result says why.
685
+ const { state } = options;
657
686
  let loaderRefused: string | undefined = state === undefined ? undefined : missingEntry;
658
687
  if (state !== undefined && missingEntry === undefined) {
659
688
  const segments = image.segments.map((segment) => ({ ...segment, files: laid.pieces.filter((piece) => piece.start >= segment.start && piece.start <= segment.end).map((piece) => piece.file) }));
660
689
  try {
661
690
  const entryName = laid.names.get(image.entry!);
662
- loader = planLoader({ segments, byteAt: image.byteAt, state, entry: image.entry!, ...(entryName === undefined ? {} : { entryName }), switches: hasSwitchFile(laid), macros: laid.macros.length > 0, header: [`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."] });
691
+ loader = planLoader({ segments, byteAt: image.byteAt, state, entry: image.entry!, ...(entryName === undefined ? {} : { entryName }), switches: hasSwitchFile(laid), macros: laid.macros.length > 0, header: options.loaderHeader ?? [] });
663
692
  } catch (error) {
664
693
  if (!(error instanceof WireFailure)) throw error;
665
694
  loaderRefused = error.message;
666
695
  }
667
696
  }
668
- // Every generated file starts with the mark, so a later run knows its own files and removes the ones it does not write again.
669
- const marked = (list: Array<{ name: string; text: string }>) => list.map((file) => ({ ...file, text: `${GENERATED_MARK}. Do not edit: change the knowledge and generate again.\n${file.text}` }));
697
+ // With a mark, every file starts with it.
698
+ const { mark } = options;
699
+ const marked = (list: Array<{ name: string; text: string }>) => (mark === undefined ? list : list.map((file) => ({ ...file, text: `${mark}\n${file.text}` })));
700
+ const markLines = mark === undefined ? 0 : 1;
670
701
  const loaderFiles = loader === undefined ? [] : [{ name: "loader.asm", text: loader.text }];
671
- // An operand expression that ACME refuses, or assembles to other bytes, is written as its number, and a macro use as its
672
- // instructions; then the source is assembled again.
673
702
  const numbers = new Map<number, string>();
674
703
  const asInstructions = new Map<number, string>();
675
704
  let rendered = render(laid, asBytes, header, numbers, asInstructions);
676
705
  if (laid.macroUses.size > 0) for (const [start, reason] of await probeUses(laid, rendered, image)) asInstructions.set(start, reason);
677
706
  if (asInstructions.size > 0) rendered = render(laid, asBytes, header, numbers, asInstructions);
678
707
  let files = marked([...rendered.files, ...loaderFiles]);
679
- let built = await assembleFiles(files, "main.asm", baseDefines);
708
+ let built = await assembleFiles(files, "main.asm", options.defines);
680
709
  for (let round = 0; round < ROUNDS && (rendered.expressions.length > 0 || rendered.uses.length > 0); round++) {
681
- const blamed = blame(rendered, built, image, 1);
710
+ const blamed = blame(rendered, built, image, markLines);
682
711
  if (blamed.numbers.size === 0 && blamed.uses.size === 0) break;
683
712
  for (const [address, reason] of blamed.numbers) numbers.set(address, reason);
684
713
  for (const [start, reason] of blamed.uses) asInstructions.set(start, reason);
685
714
  rendered = render(laid, asBytes, header, numbers, asInstructions);
686
715
  files = marked([...rendered.files, ...loaderFiles]);
687
- built = await assembleFiles(files, "main.asm", baseDefines);
716
+ built = await assembleFiles(files, "main.asm", options.defines);
717
+ }
718
+ return { romUse, instructions, dataOnly, laid, rendered, files, built, loader, missingEntry, loaderRefused };
719
+ }
720
+
721
+ /**
722
+ * Assembles loader.asm with the defines and simulates its copies: the
723
+ * loader as it loads, then every copy in its order, byte by byte. A layout
724
+ * other than the plan is a defect of the script.
725
+ */
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);
728
+ if (loaderBuilt.program === undefined) return { diagnostics: loaderBuilt.diagnostics.slice(0, MAX_DIAGNOSTICS) };
729
+ const program = loaderBuilt.program;
730
+ const memory = new Int16Array(0x10000).fill(-1);
731
+ program.subarray(2).forEach((byte, offset) => (memory[loaderBuilt.start! + offset] = byte));
732
+ const expected = (address: number) => (image.segments.some((segment) => address >= segment.start && address <= segment.end) ? image.byteAt(address) : state.pages[address]!);
733
+ const wrongPacking = loader.blocks.find((block) => {
734
+ for (let address = block.range.start; address <= block.range.end; address++) if (memory[block.packedAt + address - block.range.start] !== block.bytes(address)) return true;
735
+ return false;
736
+ });
737
+ if (loaderBuilt.start !== 0x0801 || loaderBuilt.start + program.length - 3 !== loader.end || wrongPacking !== undefined) {
738
+ throw new WireFailure("operation-failed", `The assembled loader does not have the planned layout${wrongPacking === undefined ? "" : ` (${wrongPacking.what})`}. This is a defect of the c64-source script.`);
739
+ }
740
+ const symbolValue = (name: string) => {
741
+ const symbol = loaderBuilt.symbols?.find((item) => item.name === name);
742
+ if (symbol === undefined) throw new WireFailure("operation-failed", `The assembled loader has no ${name} label. This is a defect of the c64-source script.`);
743
+ return symbol.kind === "address" ? symbol.address : symbol.value;
744
+ };
745
+ const jump = symbolValue(LOADER_JUMP);
746
+ const wrong = simulate(memory, loader.copies, expected);
747
+ if (wrong !== undefined) throw new WireFailure("operation-failed", `The simulated loader writes a wrong byte at ${formatC64Address(wrong)}. This is a defect of the c64-source script.`);
748
+ return { program, symbols: loaderBuilt.symbols ?? [], jump, copierSource: symbolValue(COPIER_SOURCE), expected };
749
+ }
750
+
751
+ /** The first line of each file that generate writes. */
752
+ const GENERATED_LINE = `${GENERATED_MARK}. Do not edit: change the knowledge and generate again.`;
753
+
754
+ async function generate(call: Call): Promise<{ output: Record<string, unknown>; failed: boolean; removed: string[] }> {
755
+ const out = call.string("out")!;
756
+ const entries = call.addresses("entry");
757
+ const max = call.count("max-listed")!;
758
+ const space = call.space;
759
+ const loaderWanted = call.flag("loader");
760
+ if (space !== DEFAULT_SPACE && loaderWanted) throw new UsageError("--loader works only in space c64");
761
+ const knowledge = readKnowledge(space, call.flag("analyzer-names"));
762
+ const image = knowledge.program;
763
+ if (loaderWanted && (image.state === undefined || image.entry === undefined)) {
764
+ throw new Refusal("not-found", "--loader needs the entry and the entry state of a c64-unpacker capture in the knowledge: put the capture in with knowledge.ts image <image.json>");
688
765
  }
766
+ // Read the entry state before the long steps, so a bad state stops the run at once.
767
+ const state = loaderWanted ? loaderState(image.state, "the entry state of the knowledge") : undefined;
768
+ // 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]));
770
+ 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
+ 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
+ const { romUse, dataOnly, laid, rendered, files, built, loader, missingEntry, loaderRefused } = await buildSource(knowledge, {
773
+ space,
774
+ entries,
775
+ header,
776
+ mark: GENERATED_LINE,
777
+ defines: baseDefines,
778
+ notExecutedMarks: true,
779
+ ...(state === undefined ? {} : { state, loaderHeader }),
780
+ });
689
781
  const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
690
782
  const written: Written[] = files.map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
691
783
  written.push(writeReported(`${out}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.revision, files), { what: "--out" }));
@@ -787,30 +879,11 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
787
879
  if (loader === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
788
880
 
789
881
  // The entry state is the state of the base release: the loader is built and checked with it.
790
- const loaderBuilt = await assembleFiles(files, "loader.asm", baseDefines);
791
- if (loaderBuilt.program === undefined) return { output: { ...output, loader: { verified: false, reason: "loader.asm does not assemble.", diagnostics: loaderBuilt.diagnostics.slice(0, MAX_DIAGNOSTICS) } }, removed, failed: true };
792
- const program = loaderBuilt.program;
793
- // The simulation: the loader in memory as it loads, then every copy in its order, byte by byte.
794
- const memory = new Int16Array(0x10000).fill(-1);
795
- program.subarray(2).forEach((byte, offset) => (memory[loaderBuilt.start! + offset] = byte));
796
- const expected = (address: number) => (image.segments.some((segment) => address >= segment.start && address <= segment.end) ? image.byteAt(address) : state.pages[address]!);
797
- const wrongPacking = loader.blocks.find((block) => {
798
- for (let address = block.range.start; address <= block.range.end; address++) if (memory[block.packedAt + address - block.range.start] !== block.bytes(address)) return true;
799
- return false;
800
- });
801
- if (loaderBuilt.start !== 0x0801 || loaderBuilt.start + program.length - 3 !== loader.end || wrongPacking !== undefined) {
802
- throw new WireFailure("operation-failed", `The assembled loader does not have the planned layout${wrongPacking === undefined ? "" : ` (${wrongPacking.what})`}. This is a defect of the c64-source script.`);
803
- }
804
- const jumpSymbol = loaderBuilt.symbols?.find((symbol) => symbol.name === LOADER_JUMP);
805
- if (jumpSymbol === undefined) throw new WireFailure("operation-failed", `The assembled loader has no ${LOADER_JUMP} label. This is a defect of the c64-source script.`);
806
- const jump = jumpSymbol.kind === "address" ? jumpSymbol.address : jumpSymbol.value;
807
- const wrong = simulate(memory, loader.copies, expected);
808
- if (wrong !== undefined) throw new WireFailure("operation-failed", `The simulated loader writes a wrong byte at ${formatC64Address(wrong)}. This is a defect of the c64-source script.`);
882
+ const loaderBuilt = await buildLoader(files, loader, image, state, baseDefines);
883
+ if ("diagnostics" in loaderBuilt) return { output: { ...output, loader: { verified: false, reason: "loader.asm does not assemble.", diagnostics: loaderBuilt.diagnostics } }, removed, failed: true };
884
+ const { program, jump, copierSource, expected } = loaderBuilt;
809
885
  const loaderPath = `${out}/loader.prg`;
810
886
  written.push(writeReported(loaderPath, program, { what: "--out" }));
811
- const copierSymbol = loaderBuilt.symbols?.find((symbol) => symbol.name === COPIER_SOURCE);
812
- if (copierSymbol === undefined) throw new WireFailure("operation-failed", `The assembled loader has no ${COPIER_SOURCE} label. This is a defect of the c64-source script.`);
813
- const copierSource = copierSymbol.kind === "address" ? copierSymbol.address : copierSymbol.value;
814
887
  const ran = await runLoader(loaderPath, program, loader, image, state, jump, copierSource, expected);
815
888
  output.loader = {
816
889
  program: loaderPath,
@@ -824,6 +897,288 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
824
897
  return { output, removed, failed: !ran.verified || sourceFailed };
825
898
  }
826
899
 
900
+ /** The value of a switch in an export: fixes, trainers and cheats are in; protection and crack changes are out; a change keeps its default. */
901
+ function exportValue(row: SourceSwitch): 0 | 1 {
902
+ if (row.kind === "change") return row.default;
903
+ return row.kind === "fix" || row.kind === "trainer" || row.kind === "cheat" ? 1 : 0;
904
+ }
905
+
906
+ const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
907
+
908
+ /** The entry of a PRG without one in the knowledge: the address of the first SYS of its BASIC line, when the image holds it. */
909
+ function basicEntry(image: ProgramImage): number | undefined {
910
+ const first = image.segments[0];
911
+ if (first === undefined) return undefined;
912
+ const tokenized = parseTokenized(Uint8Array.from([first.start & 0xff, first.start >> 8, ...image.memory.subarray(first.start, first.end + 1)]));
913
+ if ("reason" in tokenized) return undefined;
914
+ const sys = findHandoffs(tokenized.lines).find((handoff) => handoff.kind === "sys" && "address" in handoff);
915
+ const address = sys !== undefined && "address" in sys ? sys.address : undefined;
916
+ return address !== undefined && image.segments.some((segment) => address >= segment.start && address <= segment.end) ? address : undefined;
917
+ }
918
+
919
+ /** The parts of a region outside the holes. A part that is not the whole region has no element size: its length need not be a multiple of it. */
920
+ function clipped<R extends { start: number; end: number; element?: number }>(region: R, holes: readonly AddressRange[]): R[] {
921
+ return subtract(region, [...holes]).map((piece) => {
922
+ if (piece.start === region.start && piece.end === region.end) return region;
923
+ const part = { ...region, ...piece };
924
+ delete part.element;
925
+ return part;
926
+ });
927
+ }
928
+
929
+ /** The regions that decide the memory map: the user and LLM regions, and the parts of analyzer regions outside them. */
930
+ function effectiveRegions(regions: SourceKnowledge["regions"]): SourceKnowledge["regions"] {
931
+ const semantic = regions.filter((region) => isSemantic(region.origin));
932
+ const holes = semantic.map((region) => ({ start: region.start, end: region.end }));
933
+ return [...semantic, ...regions.filter((region) => !isSemantic(region.origin)).flatMap((region) => clipped(region, holes))].sort((a, b) => a.start - b.start);
934
+ }
935
+
936
+ /** Every file in a folder with its path in it, with / between the parts, in path order. `skip` leaves out a folder by its path. */
937
+ function filesIn(root: string, skip: (path: string) => boolean, folder = ""): Array<{ path: string; bytes: Buffer }> {
938
+ const found: Array<{ path: string; bytes: Buffer }> = [];
939
+ for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
940
+ const path = folder === "" ? entry.name : `${folder}/${entry.name}`;
941
+ if (entry.isDirectory()) {
942
+ if (!skip(path)) found.push(...filesIn(root, skip, path));
943
+ } else if (entry.isFile()) found.push({ path, bytes: readFileSync(join(root, path)) });
944
+ }
945
+ return found.sort((a, b) => (a.path < b.path ? -1 : 1));
946
+ }
947
+
948
+ /**
949
+ * export: the program of the knowledge as the start of a new program, in a
950
+ * new project folder and a zip file of it. Every switch is fixed at its export
951
+ * value, code and data that nothing uses become free ($00), the source has no
952
+ * mark, no switches and no not-executed marks, and the knowledge keeps the
953
+ * program, the entry, the names, the comments and the memory map. Nothing is
954
+ * written until every check passes.
955
+ */
956
+ async function exportProject(call: Call): Promise<Record<string, unknown>> {
957
+ const project = projectRoot();
958
+ const { root: to, zip } = newProjectFolder(call.string("to")!, project);
959
+ const name = call.string("name") ?? basename(to);
960
+ if (!NAME_PATTERN.test(name)) throw new UsageError(`--name ${name}: a name has letters, digits, dots, underscores and hyphens, and starts with a letter or a digit. Give --name`);
961
+ const keep = call.ranges("keep");
962
+ const drop = call.ranges("drop");
963
+ const max = call.count("max-listed")!;
964
+ const shownRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
965
+ const fromProject = (path: string) => relative(project, path).split(sep).join("/");
966
+
967
+ const db = openForRead();
968
+ const spacesLeftOut = (() => {
969
+ try {
970
+ return listSpaces(db).filter((space) => space !== DEFAULT_SPACE);
971
+ } finally {
972
+ db?.close();
973
+ }
974
+ })();
975
+ const knowledge = readKnowledge(DEFAULT_SPACE);
976
+ const image = knowledge.program;
977
+ const state = image.state === undefined || image.entry === undefined ? undefined : loaderState(image.state, "the entry state of the knowledge");
978
+
979
+ // 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 });
982
+ const fix = "Run source.ts generate, correct the knowledge until generate gives PASS, then export again.";
983
+ 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
+ const checked = check(original.built.program, original.built.start!, image);
985
+ if (!checked.identical) return { result: "FAIL", stage: "original", reason: `The source of the knowledge does not assemble to the program. ${fix}`, check: checked };
986
+ if (original.missingEntry !== undefined) return { result: "FAIL", stage: "original", reason: original.missingEntry };
987
+ if (original.laid.patchesNotWritten.length > 0) {
988
+ return { result: "FAIL", stage: "original", reason: `The source cannot write every patch. ${fix}`, patchesNotWritten: listed(original.laid.patchesNotWritten, max, (item) => ({ ...shownRange(item), switch: item.switch, reason: item.reason })) };
989
+ }
990
+
991
+ // 2. Each switch at its export value. Two alternatives of one range cannot both be in.
992
+ const values = new Map(knowledge.switches.map((row) => [row.name, exportValue(row)]));
993
+ for (const patch of original.laid.patches.values()) {
994
+ const both = patch.alternatives.filter((alternative) => values.get(alternative.switch) !== alternative.base);
995
+ if (both.length > 1) {
996
+ 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
+ }
998
+ }
999
+ const exportDefines = Object.fromEntries(values);
1000
+ const withPatches = switchesOf(original.laid);
1001
+ const changedSwitches = knowledge.switches.filter((row) => values.get(row.name) !== row.base);
1002
+ const patchesIn = changedSwitches.flatMap((row) => withPatches.get(row.name) ?? []);
1003
+ const baked = await assembleFiles(original.files, "main.asm", exportDefines);
1004
+ const bakedCheck = compareBuilds(baked, patchesIn, { program: original.built.program, start: original.built.start! });
1005
+ const switches = knowledge.switches.map((row) => ({ name: row.name, kind: row.kind, base: row.base, value: values.get(row.name)! }));
1006
+ 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 };
1007
+
1008
+ // 3. The baked image: the bytes of that build in the segments of the program.
1009
+ const memory = Uint8Array.from(image.memory);
1010
+ for (const segment of image.segments) for (let address = segment.start; address <= segment.end; address++) memory[address] = baked.program[2 + address - baked.start!]!;
1011
+ const changed = patchesIn.filter((patch) => {
1012
+ for (let address = patch.start; address <= patch.end; address++) if (memory[address] !== image.byteAt(address)) return true;
1013
+ return false;
1014
+ });
1015
+ const bakedImage: ProgramImage = { space: DEFAULT_SPACE, segments: image.segments, memory, byteAt: (address) => memory[address]!, ...(image.entry === undefined ? {} : { entry: image.entry }), ...(image.state === undefined ? {} : { state: image.state }) };
1016
+ const decoded = await decode(bakedImage, knowledge, [], knowledge.coverage);
1017
+
1018
+ // 4. The free ranges.
1019
+ const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
1020
+ const operandTargets = new Map<number, number[]>();
1021
+ for (const operand of knowledge.operands) {
1022
+ const names = operand.symbol !== undefined ? [operand.symbol] : identifiers(operand.expression ?? "");
1023
+ const targets = names.flatMap((item) => (addressOf.has(item) ? [(addressOf.get(item)! + (operand.symbol !== undefined ? operand.offset : 0)) & 0xffff] : []));
1024
+ if (targets.length > 0) operandTargets.set(operand.address, targets);
1025
+ }
1026
+ const regions = effectiveRegions(knowledge.regions);
1027
+ const entry = image.entry ?? basicEntry(image);
1028
+ const plan = planDrops({
1029
+ segments: image.segments,
1030
+ memory,
1031
+ ...(entry === undefined ? {} : { entry }),
1032
+ instructions: decoded.instructions,
1033
+ ...(knowledge.coverage === undefined ? {} : { coverage: knowledge.coverage }),
1034
+ regions,
1035
+ references: knowledge.references,
1036
+ operandTargets,
1037
+ changed,
1038
+ keep,
1039
+ drop,
1040
+ routines: knowledge.symbols.filter((symbol) => symbol.kind === "routine"),
1041
+ });
1042
+ const free = plan.free;
1043
+ const inFree = (address: number) => free.some((range) => address >= range.start && address <= range.end);
1044
+ const overlapsAny = (start: number, end: number, ranges: readonly AddressRange[]) => ranges.some((range) => start <= range.end && range.start <= end);
1045
+ for (const range of free) memory.fill(0, range.start, range.end + 1);
1046
+
1047
+ // 5. The knowledge of the export: the baked program with the free ranges, without patches, switches and releases.
1048
+ const revision = knowledge.revision ?? "";
1049
+ const taken = new Set(knowledge.symbols.map((symbol) => symbol.name));
1050
+ const freeSymbols = free.filter((range) => !taken.has(freeName(range))).map((range) => ({ space: DEFAULT_SPACE, address: range.start, name: freeName(range), kind: "label" as const, origin: "llm" as const, revision }));
1051
+ const lineComments = new Map<number, string>();
1052
+ for (const range of free) lineComments.set(range.start, `Free: ${range.end - range.start + 1} bytes of ${range.what} that nothing uses. The export made them $00.`);
1053
+ for (const row of changedSwitches) {
1054
+ for (const patch of withPatches.get(row.name) ?? []) {
1055
+ if (!changed.includes(patch)) continue;
1056
+ const alternative = patch.alternatives.find((item) => item.switch === row.name);
1057
+ const text = [`${row.name} (${row.kind}) is ${values.get(row.name)} in the export.`, row.comment, alternative?.comment].filter((part) => part !== undefined && part !== "").join(" ");
1058
+ lineComments.set(patch.start, lineComments.has(patch.start) ? `${lineComments.get(patch.start)} ${text}` : text);
1059
+ }
1060
+ }
1061
+ const keptComments = knowledge.comments.filter((comment) => !inFree(comment.address));
1062
+ const comments = [
1063
+ ...keptComments.map((comment) => (comment.placement === "line" && lineComments.has(comment.address) ? { ...comment, text: `${comment.text} ${lineComments.get(comment.address)}` } : comment)),
1064
+ ...[...lineComments].filter(([address]) => !keptComments.some((comment) => comment.placement === "line" && comment.address === address)).map(([address, text]) => ({ space: DEFAULT_SPACE, address, placement: "line" as const, text, origin: "llm" as const, revision })),
1065
+ ].sort((a, b) => a.address - b.address);
1066
+ const freeHoles = free.map((range) => ({ start: range.start, end: range.end }));
1067
+ const clip = <R extends { start: number; end: number; element?: number }>(region: R): R[] => clipped(region, freeHoles);
1068
+ const exportRegions = [...regions.flatMap(clip), ...free.map((range) => ({ space: DEFAULT_SPACE, start: range.start, end: range.end, type: "unused" as const, origin: "llm" as const, revision }))].sort((a, b) => a.start - b.start);
1069
+ const derived: SourceKnowledge = {
1070
+ ...knowledge,
1071
+ program: { ...bakedImage, byteAt: (address) => memory[address]! },
1072
+ symbols: [...knowledge.symbols.filter((symbol) => !inFree(symbol.address)), ...freeSymbols].sort((a, b) => a.address - b.address),
1073
+ routines: knowledge.routines.filter((address) => !inFree(address)),
1074
+ regions: [...knowledge.regions.flatMap(clip), ...exportRegions.filter((region) => region.type === "unused" && free.some((range) => range.start === region.start))],
1075
+ comments,
1076
+ references: knowledge.references.filter((reference) => !inFree(reference.from) && !inFree(reference.to) && !overlapsAny(reference.from, reference.from, changed)),
1077
+ operands: knowledge.operands.filter((operand) => !inFree(operand.address) && !overlapsAny(operand.address, operand.address, changed)),
1078
+ macroUses: knowledge.macroUses.filter((use) => !overlapsAny(use.start, use.end, [...changed, ...free])),
1079
+ patches: [],
1080
+ switches: [],
1081
+ releases: [],
1082
+ };
1083
+ const instructions = new Map([...decoded.instructions].filter(([address, length]) => !overlapsAny(address, address + length - 1, free)));
1084
+ const header = [`${name}: the start of a new program, exported from ${basename(project)} at knowledge revision ${knowledge.revision}.`, "You own this source: change it as you like."];
1085
+ const exported = await buildSource(derived, {
1086
+ space: DEFAULT_SPACE,
1087
+ entries: [],
1088
+ header,
1089
+ defines: {},
1090
+ decoded: { instructions, dataOnly: decoded.dataOnly },
1091
+ notExecutedMarks: false,
1092
+ ...(state === undefined ? {} : { state, loaderHeader: [`The loader of ${name}.`, "It copies the segments into place, sets the entry state and jumps to the entry."] }),
1093
+ });
1094
+ if (exported.built.program === undefined) return { result: "FAIL", stage: "export", reason: "The source of the export does not assemble. This is a defect of the c64-source script.", diagnostics: exported.built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
1095
+ const exportCheck = check(exported.built.program, exported.built.start!, derived.program);
1096
+ if (!exportCheck.identical) return { result: "FAIL", stage: "export", reason: "The source of the export does not assemble to the exported program. This is a defect of the c64-source script.", check: exportCheck };
1097
+
1098
+ // 6. The loader of a capture: planned and simulated. The tests of the new project run it.
1099
+ let baseline = { program: exported.built.program, symbols: exported.built.symbols ?? [], entryFile: "main.asm" };
1100
+ let loaderOutput: Record<string, unknown> | undefined;
1101
+ if (state !== undefined) {
1102
+ 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, {});
1104
+ 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
+ baseline = { program: loaderBuilt.program, symbols: loaderBuilt.symbols, entryFile: "loader.asm" };
1106
+ loaderOutput = {
1107
+ copies: exported.loader.copies.map((copy) => ({ what: copy.what, to: `${formatC64Address(copy.target.start)}-${formatC64Address(copy.target.end)}` })),
1108
+ copier: formatC64Address(exported.loader.copier),
1109
+ stackByte: formatC64Address(exported.loader.stackByte),
1110
+ simulated: true,
1111
+ ...(loaderLimits(exported.loader).length === 0 ? {} : { limits: loaderLimits(exported.loader) }),
1112
+ };
1113
+ }
1114
+ const shownSymbols = baseline.symbols.filter((symbol) => symbol.kind === "address" || symbol.used);
1115
+
1116
+ // 7. The tests of the project, changed for the new project.
1117
+ const testsFolder = join(project, "tests");
1118
+ const testFiles = existsSync(testsFolder) ? readdirSync(testsFolder, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name).sort() : [];
1119
+ const symbolMap = new Map(shownSymbols.map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
1120
+ const tests: Array<{ file: string; kind: "scenario" | "run"; text: string }> = [];
1121
+ const testsLeftOut: Array<{ file: string; reason: string }> = [];
1122
+ for (const file of testFiles) {
1123
+ const rewritten = rewriteTest(readFileSync(join(testsFolder, file), "utf8"), name, symbolMap, free);
1124
+ if ("reason" in rewritten) testsLeftOut.push({ file: `tests/${file}`, reason: rewritten.reason });
1125
+ else tests.push({ file: `tests/${file}`, kind: rewritten.kind, text: rewritten.text });
1126
+ }
1127
+
1128
+ // 8. Write the new project, then the zip of it. The knowledge goes first: withWrite tries it in memory before it makes the folder.
1129
+ const memoryRowsOf = memoryRows(derived.program.segments, derived.program.byteAt);
1130
+ const kept = { symbols: derived.symbols.length, comments: comments.length, regions: exportRegions.length, modules: knowledge.modules.length };
1131
+ withWrite(
1132
+ (index) =>
1133
+ write(index, { origin: "llm", description: `Export of ${basename(project)} at knowledge revision ${knowledge.revision}` }, "export", (change) => {
1134
+ for (const [address, bytes] of [...memoryRowsOf].sort(([a], [b]) => a - b)) change.insertMemory({ space: DEFAULT_SPACE, address, bytes, origin: "llm" });
1135
+ if (image.entry !== undefined) change.insertEntry({ space: DEFAULT_SPACE, address: image.entry, state: image.state === undefined ? null : JSON.stringify(image.state), stages: null, origin: "llm" });
1136
+ for (const { revision: _revision, ...symbol } of derived.symbols) change.insertSymbol(symbol);
1137
+ for (const { revision: _revision, ...comment } of comments) change.insertComment(comment);
1138
+ for (const { revision: _revision, ...region } of exportRegions) change.insertRegion(region);
1139
+ for (const { revision: _revision, ...module } of knowledge.modules) change.insertModule(module);
1140
+ }),
1141
+ to,
1142
+ );
1143
+ const put = (path: string, data: Uint8Array | string) => writeReported(path, data, { root: to, what: "--to" });
1144
+ const files: Written[] = [];
1145
+ files.push(
1146
+ put(
1147
+ "README.md",
1148
+ readmeText({ name, project: basename(project), revision: knowledge.revision, date: isoCet().slice(0, 10), entryFile: baseline.entryFile, free, switches, tests: { written: tests.map(({ file, kind }) => ({ file, kind })), leftOut: testsLeftOut } }),
1149
+ ),
1150
+ );
1151
+ for (const file of exported.files) files.push(put(`src/${file.name}`, file.text));
1152
+ files.push(put(`baseline/${name}.prg`, baseline.program), put(`baseline/${name}.json`, symbolsFileText(shownSymbols)));
1153
+ for (const test of tests) files.push(put(test.file, test.text));
1154
+ ensureLocal(to);
1155
+ const folder = basename(to);
1156
+ const archive = zipFiles(filesIn(to, (path) => path === `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}`).map((file) => ({ path: `${folder}/${file.path}`, bytes: file.bytes })));
1157
+ writeFileSync(zip, archive);
1158
+ const zipWritten: Written = { out: fromProject(zip), bytes: archive.length, sha256: createHash("sha256").update(archive).digest("hex") };
1159
+
1160
+ const freeBytes = free.reduce((sum, range) => sum + range.end - range.start + 1, 0);
1161
+ return {
1162
+ result: "PASS",
1163
+ to: fromProject(to),
1164
+ zip: zipWritten,
1165
+ source: { project: basename(project), revision: knowledge.revision },
1166
+ files: listed(files.map((file) => ({ ...file, out: fromProject(join(to, file.out)) })), max, (file) => file, "the folder of the new project"),
1167
+ switches,
1168
+ check: exportCheck,
1169
+ ...(loaderOutput === undefined ? {} : { loader: loaderOutput }),
1170
+ ...(plan.rooted ? {} : { unrooted: "The knowledge has no entry, the program has no BASIC line with SYS, and the image does not hold the hardware vectors. Thus no code is unreachable, and nothing became free by itself." }),
1171
+ ...(knowledge.coverage === undefined ? { noCoverage: "The knowledge has no coverage, so nothing became free by itself. Only --drop makes a range free." } : {}),
1172
+ free: { bytes: freeBytes, ...listed(free, max, (range) => ({ ...shownRange(range), bytes: range.end - range.start + 1, what: range.what, label: freeName(range) })) },
1173
+ unreachableExecuted: listed(plan.unreachableExecuted, max, (range) => ({ ...shownRange(range), ...(range.routine === undefined ? {} : { routine: range.routine }), drop: `--drop '${formatC64Address(range.start)}-${formatC64Address(range.end)}'` })),
1174
+ knowledge: kept,
1175
+ tests: { written: tests.map((test) => test.file), leftOut: listed(testsLeftOut, max, (item) => item) },
1176
+ ...(spacesLeftOut.length === 0 ? {} : { spacesLeftOut }),
1177
+ ...(exported.rendered.operandsAsNumbers.length === 0 ? {} : { operandsAsNumbers: listed(exported.rendered.operandsAsNumbers, max, (item) => ({ address: formatC64Address(item.address), expression: item.expression, reason: item.reason })) }),
1178
+ ...(exported.rendered.macrosAsInstructions.length === 0 ? {} : { macrosAsInstructions: listed(exported.rendered.macrosAsInstructions, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), macro: item.macro, reason: item.reason })) }),
1179
+ };
1180
+ }
1181
+
827
1182
  await runScript({
828
1183
  name: "source",
829
1184
  summary: "Generates ACME source from the program and the knowledge, and checks with ACME that it assembles to the program byte by byte.",
@@ -849,5 +1204,18 @@ await runScript({
849
1204
  return { result: failed ? "FAIL" : "PASS", ...output, ...(gone.length === 0 ? {} : { removed: gone }) };
850
1205
  },
851
1206
  },
1207
+ {
1208
+ name: "export",
1209
+ summary: "Writes the program of the knowledge as the start of a new program: a new project folder with the source, a baseline program, the tests and a slim knowledge, and a zip file of the folder. Each switch is fixed at its export value, and code and data that nothing uses become free. result is PASS when the export is written, else FAIL with the stage that failed.",
1210
+ options: {
1211
+ to: { kind: "text", value: "<folder>", required: true, help: "the folder of the new project, relative to the project folder, for example ../game-new. It must be new or empty, and outside every project. The zip file is <folder>.zip beside it" },
1212
+ name: { kind: "text", value: "<name>", help: "the name of the program files baseline/<name>.prg and build/<name>.prg. The default is the name of the folder" },
1213
+ keep: { ...OPTIONS.range, multiple: true, help: "a range that stays, also when nothing uses it" },
1214
+ drop: { ...OPTIONS.range, multiple: true, help: "a range that becomes free: code that the entry does not reach (see unreachableExecuted), or data. Nothing that stays may go to it or read it" },
1215
+ "max-listed": OPTIONS["max-listed"],
1216
+ },
1217
+ notes: "Fixes, trainers and cheats are in, protection and crack changes are out, and a change keeps its default. Code becomes free only when no run executed it and nothing reaches it; data only when no run touched it and nothing names it. Charset, sprite, bitmap and screen data stay unless --drop names them. Addresses do not move: a free range is $00 with a label free_xxxx. The export needs coverage in the knowledge to make ranges free by itself.",
1218
+ run: (call) => exportProject(call),
1219
+ },
852
1220
  ],
853
1221
  });