@henols/c64-re-tools 2.1.8 → 2.2.0-rc.2

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.
@@ -11,12 +11,15 @@ import { transaction } from "./database.ts";
11
11
  import { labelProblem, MNEMONICS } from "../opcodes.ts";
12
12
  import { checkExpression, evaluate, identifiers, operandText, replaceIdentifiers } from "./expression.ts";
13
13
  import {
14
+ baseValue,
14
15
  COMMENT_COLUMNS,
15
16
  commentsAt,
16
17
  currentRevision,
17
18
  listMacroUses,
18
19
  listOperands,
19
20
  listPatches,
21
+ listReleases,
22
+ listSwitches,
20
23
  listText,
21
24
  MACRO_COLUMNS,
22
25
  MACRO_USE_COLUMNS,
@@ -33,6 +36,10 @@ import {
33
36
  referencesFrom,
34
37
  REGION_COLUMNS,
35
38
  regionsOverlapping,
39
+ RELEASE_COLUMNS,
40
+ releaseLabeled,
41
+ SWITCH_COLUMNS,
42
+ switchNamed,
36
43
  coverageRuns,
37
44
  resolveRevision,
38
45
  SUPPRESSION_COLUMNS,
@@ -48,7 +55,9 @@ import {
48
55
  toPatch,
49
56
  toReference,
50
57
  toRegion,
58
+ toRelease,
51
59
  toSuppression,
60
+ toSwitch,
52
61
  toSymbol,
53
62
  type CommentRow,
54
63
  type CoverageRun,
@@ -59,10 +68,12 @@ import {
59
68
  type PatchRow,
60
69
  type ReferenceRow,
61
70
  type RegionRow,
71
+ type ReleaseRow,
62
72
  type SuppressionRow,
73
+ type SwitchRow,
63
74
  type SymbolRow,
64
75
  } from "./read.ts";
65
- import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MODULE_FILE, DEFAULT_SPACE, GENERATED_FILES, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, SWITCH_NAME, NO_ELEMENT_TYPES, OPERAND_SELECTS, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type SymbolKind } from "./schema.ts";
76
+ import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MODULE_FILE, DEFAULT_SPACE, GENERATED_FILES, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, OPERAND_SELECTS, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type SwitchKind, type SymbolKind } from "./schema.ts";
66
77
  import { newRevisionId, rowId, sqlName } from "./text.ts";
67
78
 
68
79
  /** What a change rests on: a coverage run, a test or another project file with its SHA-256, or a note. */
@@ -257,6 +268,18 @@ export class Change {
257
268
  .run(this.#rowId(), row.space, row.start, row.end, row.switch, row.code, row.comment ?? null, row.origin, this.id());
258
269
  }
259
270
 
271
+ insertSwitch(row: Omit<SwitchRow, "revision">): void {
272
+ this.#db
273
+ .prepare("INSERT INTO switches (id, space, name, kind, default_value, releases, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
274
+ .run(this.#rowId(), row.space, row.name, row.kind, row.default, listText(row.releases), row.comment ?? null, row.origin, this.id());
275
+ }
276
+
277
+ insertRelease(row: Omit<ReleaseRow, "revision">): void {
278
+ this.#db
279
+ .prepare("INSERT INTO releases (id, space, label, file, sha256, base, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
280
+ .run(this.#rowId(), row.space, row.label, row.file, row.sha256, row.base ? 1 : 0, row.comment ?? null, row.origin, this.id());
281
+ }
282
+
260
283
  insertMacro(row: Omit<MacroRow, "revision">): void {
261
284
  this.#db
262
285
  .prepare("INSERT INTO macros (id, space, name, params, body, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
@@ -298,7 +321,8 @@ export class Change {
298
321
  /** A conflict in words: its rule, its space and the addresses of its rows. */
299
322
  function describe(conflict: Conflict): string {
300
323
  const place = (entry: ConflictRow) => {
301
- if (entry.entity === "macro") return entry.row.name;
324
+ if (entry.entity === "macro" || entry.entity === "switch") return entry.row.name;
325
+ if (entry.entity === "release") return entry.row.label;
302
326
  const row = entry.row as { address?: number; start?: number; end?: number; from?: number };
303
327
  if (row.address !== undefined) return formatC64Address(row.address);
304
328
  if (row.from !== undefined && entry.entity === "reference") return formatC64Address(row.from);
@@ -407,8 +431,9 @@ function renameStep(db: DatabaseSync, change: Change, origin: Origin, request: S
407
431
  if (owner !== undefined && owner.address !== request.address) {
408
432
  throw new Refusal("conflict", `The name ${request.name} already belongs to ${formatC64Address(owner.address)}. Rename or remove that symbol first.`);
409
433
  }
410
- const [patch] = listPatches(db, undefined, request.name, undefined, space);
411
- if (patch !== undefined) throw new Refusal("conflict", `${request.name} is the switch of the patch at ${formatC64Address(patch.start)}-${formatC64Address(patch.end)}. Give the symbol another name.`);
434
+ if (switchNamed(db, request.name, space) !== undefined) throw new Refusal("conflict", `${request.name} is the name of a switch. Give the symbol another name.`);
435
+ const release = request.name.startsWith(RELEASE_DEFINE) ? releaseLabeled(db, request.name.slice(RELEASE_DEFINE.length), space) : undefined;
436
+ if (release !== undefined) throw new Refusal("conflict", `${request.name} builds the release ${release.label}. Give the symbol another name.`);
412
437
  if (existing !== undefined) change.close("symbols", "space = ? AND address = ?", space, request.address);
413
438
  change.insertSymbol({ space, address: request.address, name: request.name, kind, origin });
414
439
  if (existing !== undefined && existing.name !== request.name) {
@@ -777,11 +802,15 @@ function checkInImage(image: OperandImage, start: number, end: number, what: str
777
802
 
778
803
  type PatchRequest = InSpace & { start: number; end: number; switch: string; code: string; comment?: string };
779
804
 
805
+ function checkSwitchName(name: unknown, what = "A switch name"): void {
806
+ if (typeof name !== "string" || !SWITCH_NAME.test(name)) {
807
+ throw new Refusal("invalid-input", `${what} is an upper-case letter, then 1 to 31 upper-case letters, digits or underscores, for example PROTECTION.`);
808
+ }
809
+ }
810
+
780
811
  function checkPatch(request: PatchRequest): void {
781
812
  checkRange(request);
782
- if (typeof request.switch !== "string" || !SWITCH_NAME.test(request.switch)) {
783
- throw new Refusal("invalid-input", "A switch name is an upper-case letter, then 1 to 31 upper-case letters, digits or underscores, for example CRACK.");
784
- }
813
+ checkSwitchName(request.switch, "The switch of a patch");
785
814
  if (typeof request.code !== "string" || request.code.length > MAX_CODE) throw new Refusal("invalid-input", `Patch code has at most ${MAX_CODE} characters; empty code fills the range with NOP.`);
786
815
  checkBraces(request.code, "The patch code");
787
816
  checkCommentText(request.comment, "A patch comment");
@@ -837,34 +866,183 @@ function patchStep(db: DatabaseSync, change: Change, context: ChangeContext & {
837
866
  if (least !== undefined && least > length) {
838
867
  throw new Refusal("invalid-input", `The patch code is at least ${least} bytes, and the range ${range} has ${length}. Make the code shorter, or make the range larger.`);
839
868
  }
840
- const symbol = symbolNamed(db, request.switch, space);
841
- if (symbol !== undefined) throw new Refusal("conflict", `The switch name ${request.switch} is the name of the symbol at ${formatC64Address(symbol.address)}. Give the switch another name.`);
842
- if (space === DEFAULT_SPACE && context.image.platform.has(request.switch)) throw new Refusal("conflict", `The switch name ${request.switch} is a C64 platform name. Give the switch another name.`);
843
- // A write at the start of a patch of the same switch changes that patch; every other patch that it overlaps is a conflict.
844
- const other = patchesOverlapping(db, request.start, request.end, space).find((row) => row.start !== request.start || row.switch !== request.switch);
869
+ const owner = switchNamed(db, request.switch, space);
870
+ if (owner === undefined) throw new Refusal("not-found", `There is no switch ${request.switch}. Write it first (switch ${request.switch} --kind <kind> --releases <labels>).`);
871
+ // A write at the start of a patch of the same switch changes that patch. Another switch can have the same range: an alternative.
872
+ const mine = (row: PatchRow) => row.start === request.start && row.switch === request.switch;
873
+ const other = patchesOverlapping(db, request.start, request.end, space).find((row) => !mine(row) && (row.start !== request.start || row.end !== request.end || row.switch === request.switch));
845
874
  if (other !== undefined) {
846
- throw new Refusal("conflict", `The patch ${range} of ${request.switch} overlaps the patch of ${other.switch} at ${formatC64Address(other.start)}-${formatC64Address(other.end)}. A patch cannot overlap another patch, and only a patch of the same switch at the same start replaces it. Change or remove that patch first (unpatch).`);
875
+ throw new Refusal(
876
+ "conflict",
877
+ `The patch ${range} of ${request.switch} overlaps the patch of ${other.switch} at ${formatC64Address(other.start)}-${formatC64Address(other.end)}. Patches of different switches can have the same range, as alternatives; no other overlap is allowed. Change or remove that patch first (unpatch).`,
878
+ );
847
879
  }
848
880
  const [use] = macroUsesOverlapping(db, request.start, request.end, space);
849
881
  if (use !== undefined) {
850
882
  throw new Refusal("conflict", `The patch ${range} overlaps the use of the macro ${use.macro} at ${formatC64Address(use.start)}-${formatC64Address(use.end)}. Remove that use first (unuse).`);
851
883
  }
852
- const existing = patchesOverlapping(db, request.start, request.start, space).find((row) => row.start === request.start);
884
+ const find = () => patchesOverlapping(db, request.start, request.start, space).find(mine);
885
+ const existing = find();
853
886
  const code = request.code.trimEnd();
854
887
  // A patch write without a comment keeps the comment it has, as a module keeps its title.
855
888
  const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
856
889
  const origin = context.origin as PatchRow["origin"];
857
- if (existing !== undefined && existing.end === request.end && existing.switch === request.switch && existing.code === code && existing.comment === comment && !confirms(existing.origin, origin)) return { current: existing };
858
- if (existing !== undefined) change.close("patches", "space = ? AND start_address = ?", space, request.start);
890
+ if (existing !== undefined && existing.end === request.end && existing.code === code && existing.comment === comment && !confirms(existing.origin, origin)) return { current: existing };
891
+ if (existing !== undefined) change.close("patches", "space = ? AND start_address = ? AND switch_name = ?", space, request.start, request.switch);
859
892
  change.insertPatch({ space, start: request.start, end: request.end, switch: request.switch, code, ...(comment === undefined ? {} : { comment }), origin });
860
- const current = patchesOverlapping(db, request.start, request.start, space).find((row) => row.start === request.start)!;
893
+ checkAlternatives(db, space, [owner]);
894
+ const current = find()!;
895
+ return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
896
+ }
897
+
898
+ function unpatchStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace & { start: number; switch?: string }): Step<null> {
899
+ const space = spaceOf(request);
900
+ const found = patchesOverlapping(db, request.start, request.start, space).filter((row) => row.start === request.start && (request.switch === undefined || row.switch === request.switch));
901
+ if (found.length === 0) throw new Refusal("not-found", `No patch${request.switch === undefined ? "" : ` of ${request.switch}`} starts at ${formatC64Address(request.start)}.`);
902
+ if (found.length > 1) throw new Refusal("invalid-input", `The patches of ${found.map((row) => row.switch).join(", ")} start at ${formatC64Address(request.start)}. Give the switch of the patch to remove.`);
903
+ change.close("patches", "space = ? AND start_address = ? AND switch_name = ?", space, request.start, found[0]!.switch);
904
+ return { current: null };
905
+ }
906
+
907
+ /** The label of the base release of a space: its bytes are the program of the knowledge. */
908
+ function baseLabel(db: DatabaseSync, space: Space): string | undefined {
909
+ return listReleases(db, undefined, space).find((release) => release.base)?.label;
910
+ }
911
+
912
+ /**
913
+ * Refuses alternatives that are both on in the default build: a patch is on
914
+ * when its switch does not have its base value. Two patches of one range can
915
+ * not both be on, so the default build must choose one.
916
+ */
917
+ function checkAlternatives(db: DatabaseSync, space: Space, changed: readonly SwitchRow[]): void {
918
+ const base = baseLabel(db, space);
919
+ const switches = new Map(listSwitches(db, undefined, space).map((row) => [row.name, row]));
920
+ const names = new Set(changed.map((row) => row.name));
921
+ const ranges = new Map<string, PatchRow[]>();
922
+ for (const patch of listPatches(db, undefined, undefined, undefined, space)) ranges.set(`${patch.start}-${patch.end}`, [...(ranges.get(`${patch.start}-${patch.end}`) ?? []), patch]);
923
+ for (const patches of ranges.values()) {
924
+ if (patches.length < 2 || !patches.some((patch) => names.has(patch.switch))) continue;
925
+ const on = patches.filter((patch) => {
926
+ const owner = switches.get(patch.switch)!;
927
+ return owner.default !== baseValue(owner, base);
928
+ });
929
+ if (on.length < 2) continue;
930
+ const range = `${formatC64Address(patches[0]!.start)}-${formatC64Address(patches[0]!.end)}`;
931
+ throw new Refusal(
932
+ "conflict",
933
+ `The switches ${on.map((patch) => patch.switch).join(" and ")} have alternative patches at ${range}, and the default build puts in both of them. Give one of the switches the default of the base release (switch <name> --default).`,
934
+ );
935
+ }
936
+ }
937
+
938
+ type SwitchRequest = InSpace & { name: string; kind: SwitchKind; default?: 0 | 1; releases?: string[]; comment?: string };
939
+
940
+ function checkSwitch(request: SwitchRequest): void {
941
+ checkSpace(request);
942
+ checkSwitchName(request.name);
943
+ if (request.name.startsWith(RELEASE_DEFINE)) throw new Refusal("invalid-input", `A switch name does not start with ${RELEASE_DEFINE}: the build of a release defines ${RELEASE_DEFINE}<label>.`);
944
+ checkOneOf(SWITCH_KINDS, request.kind, "kind");
945
+ if (request.default !== undefined && request.default !== 0 && request.default !== 1) throw new Refusal("invalid-input", "default must be 0 or 1.");
946
+ if (OFF_KINDS.includes(request.kind) && request.default === 1) {
947
+ throw new Refusal("invalid-input", `A ${request.kind} switch is off in the default build: the default build is the clean program. Build a release, or define the switch, to put it in.`);
948
+ }
949
+ for (const label of request.releases ?? []) if (typeof label !== "string" || !RELEASE_LABEL.test(label)) throw new Refusal("invalid-input", `${JSON.stringify(label)} is not a release label.`);
950
+ checkCommentText(request.comment, "A switch comment");
951
+ }
952
+
953
+ /** The default of a switch: a fix is on, the kinds of OFF_KINDS are off, and a change needs one. */
954
+ function defaultOf(request: SwitchRequest, existing: SwitchRow | undefined): 0 | 1 {
955
+ if (request.default !== undefined) return request.default;
956
+ if (existing !== undefined && existing.kind === request.kind) return existing.default;
957
+ if (request.kind === "fix") return 1;
958
+ if (OFF_KINDS.includes(request.kind)) return 0;
959
+ throw new Refusal("invalid-input", `A ${request.kind} switch needs a default: give --default 0 or --default 1.`);
960
+ }
961
+
962
+ function switchStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: OperandImage }, request: SwitchRequest): Step<SwitchRow, SwitchRow> {
963
+ const space = spaceOf(request);
964
+ const base = baseLabel(db, space);
965
+ if (base === undefined) throw new Refusal("not-found", "The knowledge has no base release. Record the release whose bytes are the program first (release <label> --file <file> --base).");
966
+ const existing = switchNamed(db, request.name, space);
967
+ const releases = [...new Set(request.releases ?? existing?.releases ?? [])].sort();
968
+ for (const label of releases) if (releaseLabeled(db, label, space) === undefined) throw new Refusal("not-found", `There is no release ${label}. Record it first (release ${label} --file <file>).`);
969
+ const value = defaultOf(request, existing);
970
+ const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
971
+ const origin = context.origin as SwitchRow["origin"];
972
+ if (existing !== undefined && existing.kind === request.kind && existing.default === value && listText(existing.releases) === listText(releases) && existing.comment === comment && !confirms(existing.origin, origin)) return { current: existing };
973
+ const symbol = symbolNamed(db, request.name, space);
974
+ if (symbol !== undefined) throw new Refusal("conflict", `The switch name ${request.name} is the name of the symbol at ${formatC64Address(symbol.address)}. Give the switch another name.`);
975
+ if (space === DEFAULT_SPACE && context.image?.platform.has(request.name)) throw new Refusal("conflict", `The switch name ${request.name} is a C64 platform name. Give the switch another name.`);
976
+ // The patches hold the code of the value that the base release does not have: that value cannot change under them.
977
+ if (existing !== undefined && baseValue(existing, base) !== baseValue({ releases }, base)) {
978
+ const patches = listPatches(db, undefined, request.name, undefined, space);
979
+ if (patches.length > 0) {
980
+ throw new Refusal(
981
+ "conflict",
982
+ `The switch ${request.name} has patches at ${patches.map((row) => formatC64Address(row.start)).join(", ")}, and this write changes whether the base release ${base} has it on. The patches would then hold the wrong state. Remove them first (unpatch), then write them again.`,
983
+ );
984
+ }
985
+ }
986
+ if (existing !== undefined) change.close("switches", "space = ? AND name = ?", space, request.name);
987
+ change.insertSwitch({ space, name: request.name, kind: request.kind, default: value, releases, ...(comment === undefined ? {} : { comment }), origin });
988
+ const current = switchNamed(db, request.name, space)!;
989
+ checkAlternatives(db, space, [current]);
861
990
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
862
991
  }
863
992
 
864
- function unpatchStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace & { start: number }): Step<null> {
993
+ function unswitchStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace & { name: string }): Step<null> {
865
994
  const space = spaceOf(request);
866
- if (!patchesOverlapping(db, request.start, request.start, space).some((row) => row.start === request.start)) throw new Refusal("not-found", `No patch starts at ${formatC64Address(request.start)}.`);
867
- change.close("patches", "space = ? AND start_address = ?", space, request.start);
995
+ if (switchNamed(db, request.name, space) === undefined) throw new Refusal("not-found", `There is no switch ${request.name}.`);
996
+ const patches = listPatches(db, undefined, request.name, undefined, space);
997
+ if (patches.length > 0) throw new Refusal("conflict", `The switch ${request.name} has patches at ${patches.map((row) => formatC64Address(row.start)).join(", ")}. Remove them first (unpatch).`);
998
+ change.close("switches", "space = ? AND name = ?", space, request.name);
999
+ return { current: null };
1000
+ }
1001
+
1002
+ /** A release: `file` is a project path and `sha256` the hash of its bytes, both from the caller. */
1003
+ type ReleaseRequest = InSpace & { label: string; file: string; sha256: string; base?: boolean; comment?: string };
1004
+
1005
+ function checkRelease(request: ReleaseRequest): void {
1006
+ checkSpace(request);
1007
+ if (typeof request.label !== "string" || !RELEASE_LABEL.test(request.label)) {
1008
+ throw new Refusal("invalid-input", "A release label is an upper-case letter, then 1 to 31 upper-case letters, digits or underscores, for example ORIGINAL or FIRESTAR.");
1009
+ }
1010
+ if (typeof request.file !== "string" || request.file.trim().length === 0 || request.file.length > MAX_EVIDENCE_REF) throw new Refusal("invalid-input", `The file of a release has 1 to ${MAX_EVIDENCE_REF} characters.`);
1011
+ if (!/^[0-9a-f]{64}$/.test(request.sha256)) throw new Refusal("invalid-input", "The sha256 of a release is 64 lowercase hex digits.");
1012
+ checkCommentText(request.comment, "A release comment");
1013
+ }
1014
+
1015
+ function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request: ReleaseRequest): Step<ReleaseRow, ReleaseRow> {
1016
+ const space = spaceOf(request);
1017
+ const existing = releaseLabeled(db, request.label, space);
1018
+ const base = request.base ?? existing?.base ?? false;
1019
+ const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
1020
+ if (existing !== undefined && existing.file === request.file && existing.sha256 === request.sha256 && existing.base === base && existing.comment === comment && !confirms(existing.origin, origin)) return { current: existing };
1021
+ const other = baseLabel(db, space);
1022
+ if (base && other !== undefined && other !== request.label) throw new Refusal("conflict", `The release ${other} is the base release. A space has one base release.`);
1023
+ // Every switch takes its base value from the base release: it cannot change under them.
1024
+ if ((existing?.base ?? false) !== base) {
1025
+ const switches = listSwitches(db, undefined, space);
1026
+ if (switches.length > 0) throw new Refusal("conflict", `The base release decides the state of the program for the switches ${switches.map((row) => row.name).join(", ")}. Remove them first (unswitch) to change the base release.`);
1027
+ }
1028
+ const symbol = symbolNamed(db, `${RELEASE_DEFINE}${request.label}`, space);
1029
+ if (symbol !== undefined) throw new Refusal("conflict", `The build of the release defines ${RELEASE_DEFINE}${request.label}, and that is the name of the symbol at ${formatC64Address(symbol.address)}. Give the release another label.`);
1030
+ if (existing !== undefined) change.close("releases", "space = ? AND label = ?", space, request.label);
1031
+ change.insertRelease({ space, label: request.label, file: request.file, sha256: request.sha256, base, ...(comment === undefined ? {} : { comment }), origin: origin as ReleaseRow["origin"] });
1032
+ const current = releaseLabeled(db, request.label, space)!;
1033
+ return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
1034
+ }
1035
+
1036
+ function unreleaseStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace & { label: string }): Step<null> {
1037
+ const space = spaceOf(request);
1038
+ const existing = releaseLabeled(db, request.label, space);
1039
+ if (existing === undefined) throw new Refusal("not-found", `There is no release ${request.label}.`);
1040
+ const switches = listSwitches(db, undefined, space).filter((row) => existing.base || row.releases.includes(request.label));
1041
+ if (switches.length > 0) {
1042
+ const why = existing.base ? "decides the state of the program for" : "is named by";
1043
+ throw new Refusal("conflict", `The release ${request.label} ${why} the switches ${switches.map((row) => row.name).join(", ")}. Change or remove them first (switch, unswitch).`);
1044
+ }
1045
+ change.close("releases", "space = ? AND label = ?", space, request.label);
868
1046
  return { current: null };
869
1047
  }
870
1048
 
@@ -1069,21 +1247,45 @@ export function removeOperand(db: DatabaseSync, context: WriteContext, request:
1069
1247
  }
1070
1248
 
1071
1249
  /**
1072
- * Writes code that replaces [start, end] when the build defines the switch
1073
- *, after a check that the range is in the image and overlaps no other
1074
- * patch or macro use.
1250
+ * Writes code that replaces [start, end] when its switch does not have its
1251
+ * base value, after a check that the switch exists, the range is in the image,
1252
+ * and it overlaps no macro use and no patch other than an alternative.
1075
1253
  */
1076
1254
  export function setPatch(db: DatabaseSync, context: WriteContext, request: PatchRequest): WriteResult<PatchRow, PatchRow> {
1077
1255
  checkPatch(request);
1078
1256
  return result(write(db, context, "set-patch", (change) => patchStep(db, change, context, request)));
1079
1257
  }
1080
1258
 
1081
- export function removePatch(db: DatabaseSync, context: WriteContext, request: InSpace & { start: number }): WriteResult<null> {
1259
+ export function removePatch(db: DatabaseSync, context: WriteContext, request: InSpace & { start: number; switch?: string }): WriteResult<null> {
1082
1260
  checkSpace(request);
1083
1261
  checkAddress(request.start, "start");
1262
+ if (request.switch !== undefined) checkSwitchName(request.switch);
1084
1263
  return result(write(db, context, "remove-patch", (change) => unpatchStep(db, change, context.origin, request)));
1085
1264
  }
1086
1265
 
1266
+ /** Writes a switch: its kind, its default and the releases that have it on. The knowledge needs a base release first. */
1267
+ export function setSwitch(db: DatabaseSync, context: WriteContext, request: SwitchRequest): WriteResult<SwitchRow, SwitchRow> {
1268
+ checkSwitch(request);
1269
+ return result(write(db, context, "set-switch", (change) => switchStep(db, change, context, request)));
1270
+ }
1271
+
1272
+ export function removeSwitch(db: DatabaseSync, context: WriteContext, request: InSpace & { name: string }): WriteResult<null> {
1273
+ checkSpace(request);
1274
+ checkSwitchName(request.name);
1275
+ return result(write(db, context, "remove-switch", (change) => unswitchStep(db, change, context.origin, request)));
1276
+ }
1277
+
1278
+ /** Writes a release of the program: its project file and the SHA-256 of it. The caller checks the file. */
1279
+ export function setRelease(db: DatabaseSync, context: WriteContext, request: ReleaseRequest): WriteResult<ReleaseRow, ReleaseRow> {
1280
+ checkRelease(request);
1281
+ return result(write(db, context, "set-release", (change) => releaseStep(db, change, context.origin, request)));
1282
+ }
1283
+
1284
+ export function removeRelease(db: DatabaseSync, context: WriteContext, request: InSpace & { label: string }): WriteResult<null> {
1285
+ checkSpace(request);
1286
+ return result(write(db, context, "remove-release", (change) => unreleaseStep(db, change, context.origin, request)));
1287
+ }
1288
+
1087
1289
  /** Writes a macro of the generated source. */
1088
1290
  export function setMacro(db: DatabaseSync, context: WriteContext, request: MacroRequest): WriteResult<MacroRow, MacroRow> {
1089
1291
  checkMacro(request);
@@ -1123,7 +1325,7 @@ export type BatchOperation =
1123
1325
  | ({ op: "operand" } & OperandRequest)
1124
1326
  | ({ op: "unoperand" } & AddressRequest)
1125
1327
  | ({ op: "patch" } & PatchRequest)
1126
- | ({ op: "unpatch" } & InSpace & { start: number })
1328
+ | ({ op: "unpatch" } & InSpace & { start: number; switch?: string })
1127
1329
  | ({ op: "macro" } & MacroRequest)
1128
1330
  | ({ op: "unmacro" } & InSpace & { name: string })
1129
1331
  | ({ op: "use" } & MacroUseRequest)
@@ -1175,6 +1377,9 @@ export function applyBatch(db: DatabaseSync, context: WriteContext, operations:
1175
1377
  case "patch":
1176
1378
  return checkPatch(operation);
1177
1379
  case "unpatch":
1380
+ if (operation.switch !== undefined) checkSwitchName(operation.switch);
1381
+ checkSpace(operation);
1382
+ return checkAddress(operation.start, "start");
1178
1383
  case "unuse":
1179
1384
  checkSpace(operation);
1180
1385
  return checkAddress(operation.start, "start");
@@ -1271,6 +1476,16 @@ const KEYS = {
1271
1476
  map: toPatch,
1272
1477
  key: (row: PatchRow) => `${row.space}|${row.start}|${row.end}|${row.switch}|${row.code}|${row.comment ?? ""}|${row.origin}`,
1273
1478
  },
1479
+ switches: {
1480
+ columns: SWITCH_COLUMNS,
1481
+ map: toSwitch,
1482
+ key: (row: SwitchRow) => `${row.space}|${row.name}|${row.kind}|${row.default}|${listText(row.releases)}|${row.comment ?? ""}|${row.origin}`,
1483
+ },
1484
+ releases: {
1485
+ columns: RELEASE_COLUMNS,
1486
+ map: toRelease,
1487
+ key: (row: ReleaseRow) => `${row.space}|${row.label}|${row.file}|${row.sha256}|${row.base}|${row.comment ?? ""}|${row.origin}`,
1488
+ },
1274
1489
  macros: { columns: MACRO_COLUMNS, map: toMacro, key: (row: MacroRow) => `${row.space}|${row.name}|${listText(row.params)}|${row.body}|${row.comment ?? ""}|${row.origin}` },
1275
1490
  macro_uses: { columns: MACRO_USE_COLUMNS, map: toMacroUse, key: (row: MacroUseRow) => `${row.space}|${row.start}|${row.end}|${row.macro}|${listText(row.args)}|${row.origin}` },
1276
1491
  suppressions: {
@@ -1328,6 +1543,14 @@ export function revert(db: DatabaseSync, context: WriteContext, request: { revis
1328
1543
  change.insertMacro(spec.map(row as never) as MacroRow);
1329
1544
  continue;
1330
1545
  }
1546
+ if (table === "switches") {
1547
+ change.insertSwitch(spec.map(row as never) as SwitchRow);
1548
+ continue;
1549
+ }
1550
+ if (table === "releases") {
1551
+ change.insertRelease(spec.map(row as never) as ReleaseRow);
1552
+ continue;
1553
+ }
1331
1554
  if (table === "macro_uses") {
1332
1555
  change.insertMacroUse(spec.map(row as never) as MacroUseRow);
1333
1556
  continue;
@@ -127,7 +127,7 @@ export class C64RunSession {
127
127
  if (error instanceof WireFailure && /no ROM/.test(error.message)) {
128
128
  throw new WireFailure(
129
129
  "installation-incomplete",
130
- `${error.message}. c64run needs the C64 ROMs kernal-901227-03.bin, basic-901226-01.bin and chargen-901225-01.bin: set C64RT_C64_ROMS to a folder with them (the C64 folder of VICE has them). ${INSTALL_STEPS}`,
130
+ `${error.message}. c64run needs the C64 ROMs kernal-901227-03.bin, basic-901226-01.bin and chargen-901225-01.bin. ${INSTALL_STEPS}`,
131
131
  );
132
132
  }
133
133
  throw error;
@@ -7,8 +7,8 @@ import { isAbsolute, join, posix, win32 } from "node:path";
7
7
 
8
8
  import { WireFailure } from "../protocol/messages.ts";
9
9
 
10
- /** Where the user finds the install steps of the native tools for each system. */
11
- export const INSTALL_STEPS = "Steps for each system: https://github.com/henols/c64-re-tools/blob/main/docs/install-tools.md. In the dev container of c64-re-tools, restart the container: each start installs the tools of the toolkit version.";
10
+ /** The remedy for a missing native tool: the dev container of c64-re-tools installs every one. */
11
+ export const INSTALL_STEPS = "The dev container of c64-re-tools installs it at each start: restart the container, or rebuild it. Without that dev container, set it up as https://github.com/henols/c64-re-tools#dev-container tells.";
12
12
 
13
13
  export interface ToolSpec {
14
14
  /** Human name, for messages. */
@@ -28,7 +28,7 @@ export const ACME: ToolSpec = {
28
28
  envVar: "C64RT_ACME",
29
29
  binaries: ["acme"],
30
30
  where: "on this machine",
31
- remedy: `Install the ACME cross-assembler on the machine that runs the skill scripts so that acme is on PATH, or set C64RT_ACME to its full path. ${INSTALL_STEPS}`,
31
+ remedy: INSTALL_STEPS,
32
32
  };
33
33
 
34
34
  export const C1541: ToolSpec = {
@@ -52,7 +52,7 @@ export const DXA: ToolSpec = {
52
52
  envVar: "C64RT_DXA",
53
53
  binaries: ["dxa"],
54
54
  where: "on this machine",
55
- remedy: `Install dxa 0.1.5 on the machine that runs the skill scripts so that dxa is on PATH, or set C64RT_DXA to its full path. ${INSTALL_STEPS}`,
55
+ remedy: INSTALL_STEPS,
56
56
  };
57
57
 
58
58
  export const C64RUN: ToolSpec = {
@@ -60,7 +60,7 @@ export const C64RUN: ToolSpec = {
60
60
  envVar: "C64RT_C64RUN",
61
61
  binaries: ["c64run"],
62
62
  where: "on this machine",
63
- remedy: `Install c64run (the replay core of c64-testing, with its C64 ROMs) on the machine that runs the skill scripts so that c64run is on PATH, or set C64RT_C64RUN to its full path. ${INSTALL_STEPS}`,
63
+ remedy: INSTALL_STEPS,
64
64
  };
65
65
 
66
66
  export const VICE: ToolSpec = {
@@ -21,10 +21,6 @@ export const GHIDRA_LANGUAGE = "C64RT_6510:LE:16:nmos";
21
21
  export const LANGUAGE_DIRECTORY = fileURLToPath(new URL("./language/", import.meta.url));
22
22
  export const SCRIPT_DIRECTORY = fileURLToPath(new URL("./scripts/", import.meta.url));
23
23
 
24
- const REMEDY =
25
- "Install Ghidra on the machine that runs the skill scripts and set C64RT_GHIDRA to its installation directory " +
26
- `(the directory that holds support/analyzeHeadless), or put analyzeHeadless on PATH. ${INSTALL_STEPS}`;
27
-
28
24
  export interface GhidraInstallation {
29
25
  /** The installation directory. */
30
26
  root: string;
@@ -46,12 +42,12 @@ function installationAt(root: string, source: string): GhidraInstallation {
46
42
  if (!isExecutableFile(analyzeHeadless)) throw new Refusal("operation-failed", "no analyzeHeadless");
47
43
  properties = readFileSync(join(root, "Ghidra", "application.properties"), "utf8");
48
44
  } catch {
49
- throw new WireFailure("installation-incomplete", `${source} does not point to a Ghidra installation. ${REMEDY}`);
45
+ throw new WireFailure("installation-incomplete", `${source} does not point to a Ghidra installation. ${INSTALL_STEPS}`);
50
46
  }
51
47
  const value = (key: string) => new RegExp(`^${key.replace(/\./g, "\\.")}=(.*)$`, "m").exec(properties)?.[1]?.trim();
52
48
  const version = value("application.version");
53
49
  const release = value("application.release.name");
54
- if (version === undefined || release === undefined) throw new WireFailure("installation-incomplete", `The Ghidra installation at ${source} has no version. ${REMEDY}`);
50
+ if (version === undefined || release === undefined) throw new WireFailure("installation-incomplete", `The Ghidra installation at ${source} has no version. ${INSTALL_STEPS}`);
55
51
  const javaMin = value("application.java.min");
56
52
  return { root, analyzeHeadless, settingsName: `ghidra_${version}_${release}`, version, ...(javaMin === undefined || javaMin === "" ? {} : { javaMin }) };
57
53
  }
@@ -65,12 +61,12 @@ export function ghidraVersion(ghidra: GhidraInstallation): string {
65
61
  export function findGhidra(env: NodeJS.ProcessEnv = process.env): GhidraInstallation {
66
62
  const configured = env.C64RT_GHIDRA;
67
63
  if (configured !== undefined && configured !== "") {
68
- if (!isAbsolute(configured)) throw new WireFailure("installation-incomplete", `C64RT_GHIDRA on this machine is not an absolute path. ${REMEDY}`);
64
+ if (!isAbsolute(configured)) throw new WireFailure("installation-incomplete", `C64RT_GHIDRA on this machine is not an absolute path. ${INSTALL_STEPS}`);
69
65
  return installationAt(configured, "C64RT_GHIDRA");
70
66
  }
71
67
  const found = findOnPath(["analyzeHeadless"], env, [LAUNCHER_SUFFIX]);
72
68
  if (found !== undefined) return installationAt(resolve(dirname(realpathSync(found)), ".."), "analyzeHeadless on PATH");
73
- throw new WireFailure("installation-incomplete", `Ghidra is not installed on this machine. ${REMEDY}`);
69
+ throw new WireFailure("installation-incomplete", `Ghidra is not installed on this machine. ${INSTALL_STEPS}`);
74
70
  }
75
71
 
76
72
  /**
@@ -135,7 +131,7 @@ export function noJdk(ghidra: GhidraInstallation): WireFailure {
135
131
  const java = ghidra.javaMin === undefined ? "a JDK" : `JDK ${ghidra.javaMin} or later`;
136
132
  return new WireFailure(
137
133
  "installation-incomplete",
138
- `${ghidraVersion(ghidra)} found no Java that it can use. It needs ${java}. Install it on the machine that runs the skill scripts and put its java on PATH, or set JAVA_HOME to it. ${INSTALL_STEPS}`,
134
+ `${ghidraVersion(ghidra)} found no Java that it can use. It needs ${java}. ${INSTALL_STEPS}`,
139
135
  );
140
136
  }
141
137
 
@@ -114,7 +114,7 @@ export async function probeC64run(context: ToolContext): Promise<ToolStatus> {
114
114
  context,
115
115
  (output) => {
116
116
  const missing = /^roms=missing (.*)$/m.exec(output)?.[1];
117
- return missing === undefined ? undefined : `It has no C64 ROMs: ${missing}. Set C64RT_C64_ROMS to a folder with kernal-901227-03.bin, basic-901226-01.bin and chargen-901225-01.bin (the C64 folder of VICE has them). ${INSTALL_STEPS}`;
117
+ return missing === undefined ? undefined : `It has no C64 ROMs: ${missing}. ${INSTALL_STEPS}`;
118
118
  },
119
119
  );
120
120
  } catch (error) {
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env bash
2
2
  # Builds c64run, the replay core of c64-testing: floooh/chips c64.h at a pinned
3
3
  # commit with the line-command harness c64run.c next to this script. Installs
4
- # $PREFIX/bin/c64run and the three C64 ROMs that it loads to
5
- # $PREFIX/share/c64-re-tools/roms (PREFIX: /usr/local). Debian, Ubuntu, macOS.
4
+ # /usr/local/bin/c64run and the three C64 ROMs that it loads to
5
+ # /usr/local/share/c64-re-tools/roms. install-container.sh runs it as root,
6
+ # with a C compiler and curl.
6
7
 
7
8
  set -Eeuo pipefail
8
9
 
@@ -17,7 +18,7 @@ ROMS=(
17
18
  "basic.901226-01.bin basic-901226-01.bin 89878cea0a268734696de11c4bae593eaaa506465d2029d619c0e0cbccdfa62d"
18
19
  "characters.901225-01.bin chargen-901225-01.bin fd0d53b8480e86163ac98998976c72cc58d5dd8eb824ed7b829774e74213b420"
19
20
  )
20
- PREFIX="${PREFIX:-/usr/local}"
21
+ PREFIX="/usr/local"
21
22
  HERE="$(cd "$(dirname "$0")" && pwd)"
22
23
 
23
24
  fail() {
@@ -25,20 +26,10 @@ fail() {
25
26
  exit 1
26
27
  }
27
28
 
28
- if [[ "$(id -u)" -eq 0 || -w "${PREFIX}" ]]; then SUDO=""; else SUDO="sudo"; fi
29
-
30
- CC="${CC:-$(command -v gcc || command -v cc || true)}"
31
- if [[ -z "${CC}" ]] || ! command -v curl >/dev/null 2>&1; then
32
- command -v apt-get >/dev/null 2>&1 || fail "a C compiler and curl are needed."
33
- ${SUDO} apt-get update
34
- ${SUDO} apt-get install -y --no-install-recommends build-essential ca-certificates curl
35
- CC=gcc
36
- fi
29
+ [[ "$(id -u)" -eq 0 ]] || fail "run as root."
37
30
 
38
31
  check() {
39
- local sum
40
- if command -v sha256sum >/dev/null 2>&1; then sum="$(sha256sum "$2" | cut -d' ' -f1)"; else sum="$(shasum -a 256 "$2" | cut -d' ' -f1)"; fi
41
- [[ "${sum}" == "$1" ]]
32
+ [[ "$(sha256sum "$2" | cut -d' ' -f1)" == "$1" ]]
42
33
  }
43
34
 
44
35
  BUILD_DIR="$(mktemp -d -t c64run-build-XXXXXXXX)"
@@ -55,12 +46,12 @@ for rom in "${ROMS[@]}"; do
55
46
  check "${sha}" "${BUILD_DIR}/roms/${name}" || fail "the ROM ${name} has the wrong checksum."
56
47
  done
57
48
 
58
- "${CC}" -O2 -Wall -Wno-unused-function -DCHIPS_COMMIT="\"${CHIPS_COMMIT:0:12}\"" \
49
+ gcc -O2 -Wall -Wno-unused-function -DCHIPS_COMMIT="\"${CHIPS_COMMIT:0:12}\"" \
59
50
  -I "${BUILD_DIR}/chips-${CHIPS_COMMIT}" -o "${BUILD_DIR}/c64run" "${HERE}/c64run.c"
60
51
  started="$(printf 'init %s\nquit\n' "${BUILD_DIR}/roms" | "${BUILD_DIR}/c64run")"
61
52
  [[ "${started}" == ok*pc=fce2* ]] || fail "the compiled c64run does not reach the reset vector: ${started}"
62
53
 
63
- ${SUDO} install -d -m 0755 "${PREFIX}/bin" "${PREFIX}/share/c64-re-tools/roms"
64
- ${SUDO} install -m 0755 "${BUILD_DIR}/c64run" "${PREFIX}/bin/c64run"
65
- ${SUDO} install -m 0644 "${BUILD_DIR}"/roms/*.bin "${PREFIX}/share/c64-re-tools/roms/"
54
+ install -d -m 0755 "${PREFIX}/bin" "${PREFIX}/share/c64-re-tools/roms"
55
+ install -m 0755 "${BUILD_DIR}/c64run" "${PREFIX}/bin/c64run"
56
+ install -m 0644 "${BUILD_DIR}"/roms/*.bin "${PREFIX}/share/c64-re-tools/roms/"
66
57
  echo "c64run (chips ${CHIPS_COMMIT:0:12}) is installed in ${PREFIX}/bin/c64run, its ROMs in ${PREFIX}/share/c64-re-tools/roms."