rk86 2.0.31 → 2.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/rk86.js +573 -185
package/README.md CHANGED
@@ -44,15 +44,15 @@ bunx rk86 --online CHESS.GAM # открыть файл в онлайн-э
44
44
  ## Онлайн-режим (`--online`)
45
45
 
46
46
  Загружает локальный файл на одноразовый relay-сервер
47
- ([rk86.ea.deno.net](https://rk86.ea.deno.net)) и открывает
47
+ ([rk86.vercel.app](https://rk86.vercel.app)) и открывает
48
48
  [rk86.ru](https://rk86.ru) в браузере с `?run=<URL>`. Файл живёт на сервере
49
- 60 секунд (TTL в Deno KV), затем удаляется автоматически. Удобно когда нужно
49
+ 60 секунд (TTL в MongoDB), затем удаляется автоматически. Удобно когда нужно
50
50
  быстро поделиться `.rk`/`.gam` или показать программу без публикации в
51
51
  каталог.
52
52
 
53
53
  ```bash
54
54
  bunx rk86 --online CHESS.GAM
55
- # https://rk86.ru/index.html?run=https%3A%2F%2Frk86.ea.deno.net%2Ffile%2FCHESS.GAM%3F<id>
55
+ # https://rk86.ru/index.html?run=https%3A%2F%2Frk86.vercel.app%2Ffile%2FCHESS.GAM%3F<id>
56
56
  ```
57
57
 
58
58
  ## Безголовый режим (headless) и автотесты
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rk86",
3
- "version": "2.0.31",
3
+ "version": "2.0.33",
4
4
  "description": "Эмулятор Радио-86РК (Intel 8080) для терминала",
5
5
  "bin": {
6
6
  "rk86": "rk86.js"
package/rk86.js CHANGED
@@ -5,12 +5,14 @@ class AsmError extends Error {
5
5
  line;
6
6
  column;
7
7
  source;
8
- constructor(message, line, source, column = 1) {
8
+ file;
9
+ constructor(message, line, source, column = 1, file) {
9
10
  super(message);
10
11
  this.name = "AsmError";
11
12
  this.line = line;
12
13
  this.source = source;
13
14
  this.column = column;
15
+ this.file = file;
14
16
  }
15
17
  }
16
18
  function firstNonSpaceCol(s) {
@@ -151,64 +153,99 @@ var INVERT_JUMP = {
151
153
  "<>": "JZ"
152
154
  };
153
155
  var VALID_PROC_REGS = new Set(["PSW", "B", "D", "H"]);
154
- function popsAndRet(regs, orig) {
156
+ function popsAndRet(regs, orig, file) {
155
157
  const out = [];
156
158
  for (let k = regs.length - 1;k >= 0; k--) {
157
- out.push({ text: ` POP ${regs[k]}`, orig });
159
+ out.push({ text: ` POP ${regs[k]}`, orig, file });
158
160
  }
159
- out.push({ text: ` RET`, orig });
161
+ out.push({ text: ` RET`, orig, file });
160
162
  return out;
161
163
  }
162
- function preprocess(source) {
164
+ function preprocess(source, opts) {
165
+ const ctx = {
166
+ counter: { n: 0 },
167
+ procCounter: { n: 0 },
168
+ includeStack: opts?.file ? [opts.file] : [],
169
+ readInclude: opts?.readInclude
170
+ };
171
+ return preprocessImpl(source, opts?.file, ctx);
172
+ }
173
+ function preprocessImpl(source, file, ctx) {
163
174
  const lines = source.split(`
164
175
  `);
165
176
  const out = [];
166
177
  const stack = [];
167
- let counter = 0;
168
- let procCounter = 0;
169
178
  let proc = null;
170
179
  for (let i = 0;i < lines.length; i++) {
171
180
  const line = lines[i];
172
181
  const orig = i + 1;
173
182
  const bare = stripComment(line).trim();
183
+ const incMatch = bare.match(/^\.?include\s+(.+)$/i);
184
+ if (incMatch) {
185
+ const arg = incMatch[1].trim();
186
+ const m1 = arg.match(/^"([^"]*)"$/);
187
+ const m2 = arg.match(/^'([^']*)'$/);
188
+ const path = m1?.[1] ?? m2?.[1];
189
+ if (path === undefined) {
190
+ throw new AsmError('include requires a quoted filename, e.g. include "foo.inc"', orig, line, firstNonSpaceCol(line), file);
191
+ }
192
+ if (!ctx.readInclude) {
193
+ throw new AsmError("include is not supported in this environment", orig, line, firstNonSpaceCol(line), file);
194
+ }
195
+ let result;
196
+ try {
197
+ result = ctx.readInclude(path, file);
198
+ } catch (e) {
199
+ throw new AsmError(`cannot read include "${path}": ${e.message}`, orig, line, firstNonSpaceCol(line), file);
200
+ }
201
+ if (ctx.includeStack.includes(result.resolvedFile)) {
202
+ const chain = [...ctx.includeStack, result.resolvedFile].join(" -> ");
203
+ throw new AsmError(`circular include: ${chain}`, orig, line, firstNonSpaceCol(line), file);
204
+ }
205
+ ctx.includeStack.push(result.resolvedFile);
206
+ const nested = preprocessImpl(result.source, result.resolvedFile, ctx);
207
+ ctx.includeStack.pop();
208
+ out.push(...nested);
209
+ continue;
210
+ }
174
211
  const ifMatch = bare.match(/^\.?if\s+(\S+)\s*$/i);
175
212
  if (ifMatch) {
176
213
  const cond = ifMatch[1].toUpperCase();
177
214
  const jmp = INVERT_JUMP[cond];
178
215
  if (!jmp) {
179
- throw new AsmError(`unknown .if condition: ${ifMatch[1]}`, orig, line, firstNonSpaceCol(line));
216
+ throw new AsmError(`unknown .if condition: ${ifMatch[1]}`, orig, line, firstNonSpaceCol(line), file);
180
217
  }
181
- const id = counter++;
218
+ const id = ctx.counter.n++;
182
219
  stack.push({ id, sawElse: false, line: orig, source: line });
183
- out.push({ text: ` ${jmp} @_if_${id}_else`, orig });
220
+ out.push({ text: ` ${jmp} @_if_${id}_else`, orig, file });
184
221
  continue;
185
222
  }
186
223
  if (/^\.?else\s*$/i.test(bare)) {
187
224
  const top = stack[stack.length - 1];
188
225
  if (!top) {
189
- throw new AsmError(".else without .if", orig, line, firstNonSpaceCol(line));
226
+ throw new AsmError(".else without .if", orig, line, firstNonSpaceCol(line), file);
190
227
  }
191
228
  if (top.sawElse) {
192
- throw new AsmError("duplicate .else", orig, line, firstNonSpaceCol(line));
229
+ throw new AsmError("duplicate .else", orig, line, firstNonSpaceCol(line), file);
193
230
  }
194
231
  top.sawElse = true;
195
- out.push({ text: ` JMP @_if_${top.id}_exit`, orig });
196
- out.push({ text: `@_if_${top.id}_else:`, orig });
232
+ out.push({ text: ` JMP @_if_${top.id}_exit`, orig, file });
233
+ out.push({ text: `@_if_${top.id}_else:`, orig, file });
197
234
  continue;
198
235
  }
199
236
  if (/^\.?endif\s*$/i.test(bare)) {
200
237
  const top = stack.pop();
201
238
  if (!top) {
202
- throw new AsmError(".endif without .if", orig, line, firstNonSpaceCol(line));
239
+ throw new AsmError(".endif without .if", orig, line, firstNonSpaceCol(line), file);
203
240
  }
204
241
  const suffix = top.sawElse ? "exit" : "else";
205
- out.push({ text: `@_if_${top.id}_${suffix}:`, orig });
242
+ out.push({ text: `@_if_${top.id}_${suffix}:`, orig, file });
206
243
  continue;
207
244
  }
208
245
  const procMatch = bare.match(/^([A-Za-z_]\w*):?\s+\.?proc\b\s*(.*)$/i);
209
246
  if (procMatch && !ALL_MNEMONICS.has(procMatch[1].toUpperCase())) {
210
247
  if (proc) {
211
- throw new AsmError("nested .proc not allowed", orig, line, firstNonSpaceCol(line));
248
+ throw new AsmError("nested .proc not allowed", orig, line, firstNonSpaceCol(line), file);
212
249
  }
213
250
  const name = procMatch[1];
214
251
  const regsRaw = procMatch[2].trim();
@@ -219,12 +256,12 @@ function preprocess(source) {
219
256
  continue;
220
257
  const up = r.toUpperCase();
221
258
  if (!VALID_PROC_REGS.has(up)) {
222
- throw new AsmError(`invalid .proc register: ${r} (expected PSW, B, D, or H)`, orig, line, firstNonSpaceCol(line));
259
+ throw new AsmError(`invalid .proc register: ${r} (expected PSW, B, D, or H)`, orig, line, firstNonSpaceCol(line), file);
223
260
  }
224
261
  regs.push(up);
225
262
  }
226
263
  }
227
- const id = procCounter++;
264
+ const id = ctx.procCounter.n++;
228
265
  proc = {
229
266
  regs,
230
267
  line: orig,
@@ -232,46 +269,46 @@ function preprocess(source) {
232
269
  exitLabel: `__proc_${id}_exit`,
233
270
  returnUsed: false
234
271
  };
235
- out.push({ text: `${name}:`, orig });
272
+ out.push({ text: `${name}:`, orig, file });
236
273
  for (const r of regs) {
237
- out.push({ text: ` PUSH ${r}`, orig });
274
+ out.push({ text: ` PUSH ${r}`, orig, file });
238
275
  }
239
276
  continue;
240
277
  }
241
278
  if (/^\.proc(\s|$)/i.test(bare) || /^proc\s+\S/i.test(bare)) {
242
- throw new AsmError(".proc requires a label", orig, line, firstNonSpaceCol(line));
279
+ throw new AsmError(".proc requires a label", orig, line, firstNonSpaceCol(line), file);
243
280
  }
244
281
  if (/^\.?endp\s*$/i.test(bare)) {
245
282
  if (!proc) {
246
- throw new AsmError(".endp without .proc", orig, line, firstNonSpaceCol(line));
283
+ throw new AsmError(".endp without .proc", orig, line, firstNonSpaceCol(line), file);
247
284
  }
248
285
  if (proc.returnUsed) {
249
- out.push({ text: `${proc.exitLabel}:`, orig });
286
+ out.push({ text: `${proc.exitLabel}:`, orig, file });
250
287
  }
251
- out.push(...popsAndRet(proc.regs, orig));
288
+ out.push(...popsAndRet(proc.regs, orig, file));
252
289
  proc = null;
253
290
  continue;
254
291
  }
255
292
  if (/^\.?return\s*$/i.test(bare)) {
256
293
  if (!proc) {
257
- throw new AsmError(".return outside .proc", orig, line, firstNonSpaceCol(line));
294
+ throw new AsmError(".return outside .proc", orig, line, firstNonSpaceCol(line), file);
258
295
  }
259
296
  if (proc.regs.length === 0) {
260
- out.push({ text: ` RET`, orig });
297
+ out.push({ text: ` RET`, orig, file });
261
298
  } else {
262
299
  proc.returnUsed = true;
263
- out.push({ text: ` JMP ${proc.exitLabel}`, orig });
300
+ out.push({ text: ` JMP ${proc.exitLabel}`, orig, file });
264
301
  }
265
302
  continue;
266
303
  }
267
- out.push({ text: line, orig });
304
+ out.push({ text: line, orig, file });
268
305
  }
269
306
  if (stack.length) {
270
307
  const top = stack[stack.length - 1];
271
- throw new AsmError(".if without .endif", top.line, top.source, firstNonSpaceCol(top.source));
308
+ throw new AsmError(".if without .endif", top.line, top.source, firstNonSpaceCol(top.source), file);
272
309
  }
273
310
  if (proc) {
274
- throw new AsmError(".proc without .endp", proc.line, proc.source, firstNonSpaceCol(proc.source));
311
+ throw new AsmError(".proc without .endp", proc.line, proc.source, firstNonSpaceCol(proc.source), file);
275
312
  }
276
313
  return out;
277
314
  }
@@ -285,6 +322,10 @@ function splitStatements(line) {
285
322
  for (let i = 0;i + 2 < src.length; i++) {
286
323
  const c = src[i];
287
324
  if (inQ) {
325
+ if (c === "\\" && i + 1 < src.length) {
326
+ i++;
327
+ continue;
328
+ }
288
329
  if (c === qc)
289
330
  inQ = false;
290
331
  continue;
@@ -294,7 +335,7 @@ function splitStatements(line) {
294
335
  qc = c;
295
336
  continue;
296
337
  }
297
- if (c !== " " || src[i + 1] !== "/" || src[i + 2] !== " ")
338
+ if (c !== " " || src[i + 1] !== "/" && src[i + 1] !== "\\" || src[i + 2] !== " ")
298
339
  continue;
299
340
  let j = i + 3;
300
341
  while (j < src.length && src[j] === " ")
@@ -349,12 +390,45 @@ function instrSize(m) {
349
390
  return 3;
350
391
  throw new Error(`unknown mnemonic: ${m}`);
351
392
  }
393
+ var STRING_ESCAPES = {
394
+ "\\": 92,
395
+ '"': 34,
396
+ "'": 39,
397
+ n: 10,
398
+ r: 13,
399
+ t: 9,
400
+ "0": 0
401
+ };
402
+ function decodeString(text) {
403
+ const body = text.slice(1, -1);
404
+ const out = [];
405
+ for (let i = 0;i < body.length; i++) {
406
+ const c = body[i];
407
+ if (c === "\\") {
408
+ if (i + 1 >= body.length)
409
+ throw new Error("dangling '\\' in string");
410
+ const nxt = body[i + 1];
411
+ if (!(nxt in STRING_ESCAPES)) {
412
+ throw new Error(`unknown escape sequence '\\${nxt}'`);
413
+ }
414
+ out.push(STRING_ESCAPES[nxt]);
415
+ i++;
416
+ } else {
417
+ out.push(c.charCodeAt(0));
418
+ }
419
+ }
420
+ return out;
421
+ }
352
422
  function stripComment(line) {
353
423
  let inQ = false;
354
424
  let qc = "";
355
425
  for (let i = 0;i < line.length; i++) {
356
426
  const c = line[i];
357
427
  if (inQ) {
428
+ if (c === "\\" && i + 1 < line.length) {
429
+ i++;
430
+ continue;
431
+ }
358
432
  if (c === qc)
359
433
  inQ = false;
360
434
  } else if (c === '"' || c === "'") {
@@ -370,9 +444,15 @@ function splitOperands(s) {
370
444
  let current = "";
371
445
  let inQ = false;
372
446
  let qc = "";
373
- for (const c of s) {
447
+ for (let i = 0;i < s.length; i++) {
448
+ const c = s[i];
374
449
  if (inQ) {
375
450
  current += c;
451
+ if (c === "\\" && i + 1 < s.length) {
452
+ current += s[i + 1];
453
+ i++;
454
+ continue;
455
+ }
376
456
  if (c === qc)
377
457
  inQ = false;
378
458
  } else if (c === '"' || c === "'") {
@@ -448,6 +528,15 @@ function tokenizeExpr(expr) {
448
528
  i++;
449
529
  continue;
450
530
  }
531
+ if (c === "'" && i + 3 < expr.length && expr[i + 1] === "\\" && expr[i + 3] === "'") {
532
+ const esc = expr[i + 2];
533
+ if (!(esc in STRING_ESCAPES)) {
534
+ throw new Error(`unknown escape sequence '\\${esc}'`);
535
+ }
536
+ tokens.push({ kind: "num", val: STRING_ESCAPES[esc] });
537
+ i += 4;
538
+ continue;
539
+ }
451
540
  if (c === "'" && i + 2 < expr.length && expr[i + 2] === "'") {
452
541
  tokens.push({ kind: "num", val: expr.charCodeAt(i + 1) });
453
542
  i += 3;
@@ -480,13 +569,17 @@ function tokenizeExpr(expr) {
480
569
  }
481
570
  if (/[0-9]/.test(c)) {
482
571
  let j = i;
483
- while (j < expr.length && /[0-9A-Fa-f]/.test(expr[j]))
484
- j++;
485
- if (j < expr.length && /[hH]/.test(expr[j])) {
486
- tokens.push({ kind: "num", val: parseInt(expr.slice(i, j), 16) });
572
+ while (j < expr.length && /[0-9A-Za-z_]/.test(expr[j]))
487
573
  j++;
574
+ const text = expr.slice(i, j);
575
+ if (/^[0-9A-Fa-f]+[hH]$/.test(text)) {
576
+ tokens.push({ kind: "num", val: parseInt(text.slice(0, -1), 16) });
577
+ } else if (/^[0-9]+$/.test(text)) {
578
+ tokens.push({ kind: "num", val: parseInt(text, 10) });
579
+ } else if (/^[0-9A-Fa-f]+$/.test(text)) {
580
+ throw new Error(`invalid number: ${text} (missing 'h' suffix?)`);
488
581
  } else {
489
- tokens.push({ kind: "num", val: parseInt(expr.slice(i, j), 10) });
582
+ throw new Error(`invalid number: ${text}`);
490
583
  }
491
584
  i = j;
492
585
  continue;
@@ -652,57 +745,128 @@ function evalExpr(expr, symbols, pc = 0, lastLabel = "") {
652
745
  throw new Error(`unexpected token: ${tokens[pos].val}`);
653
746
  return result;
654
747
  }
748
+ function expectOps(m, ops, n) {
749
+ if (ops.length !== n) {
750
+ throw new Error(`${m} takes ${n} operand${n === 1 ? "" : "s"}, got ${ops.length}`);
751
+ }
752
+ }
753
+ function reg8(m, op) {
754
+ const r = REG8[op.toUpperCase()];
755
+ if (r === undefined) {
756
+ throw new Error(`${m}: invalid register '${op}' (expected B C D E H L M A)`);
757
+ }
758
+ return r;
759
+ }
760
+ function regPair(m, op, allowed) {
761
+ const names = Object.keys(allowed).join(" ");
762
+ const r = allowed[op.toUpperCase()];
763
+ if (r === undefined) {
764
+ throw new Error(`${m}: invalid register pair '${op}' (expected ${names})`);
765
+ }
766
+ return r;
767
+ }
768
+ function imm8(m, v) {
769
+ const neg = v >= 65280 && v <= 65535;
770
+ if (v < -128 || v > 255 && !neg) {
771
+ throw new Error(`${m}: 8-bit value out of range: ${v}`);
772
+ }
773
+ return v & 255;
774
+ }
775
+ function imm16(m, v) {
776
+ if (v < -32768 || v > 65535) {
777
+ throw new Error(`${m}: 16-bit value out of range: ${v}`);
778
+ }
779
+ return [v & 255, v >> 8 & 255];
780
+ }
781
+ var LDAX_STAX_PAIRS = { B: 0, D: 1 };
655
782
  function encode(m, ops, symbols, pc = 0, lastLabel = "") {
656
- if (m in IMPLIED)
783
+ if (m in IMPLIED) {
784
+ expectOps(m, ops, 0);
657
785
  return [IMPLIED[m]];
658
- if (m in ALU_REG)
659
- return [ALU_REG[m] | REG8[ops[0].toUpperCase()]];
660
- if (m in ALU_IMM)
661
- return [ALU_IMM[m], evalExpr(ops[0], symbols, pc, lastLabel) & 255];
786
+ }
787
+ if (m in ALU_REG) {
788
+ expectOps(m, ops, 1);
789
+ return [ALU_REG[m] | reg8(m, ops[0])];
790
+ }
791
+ if (m in ALU_IMM) {
792
+ expectOps(m, ops, 1);
793
+ return [ALU_IMM[m], imm8(m, evalExpr(ops[0], symbols, pc, lastLabel))];
794
+ }
662
795
  if (m in ADDR16) {
663
- const v = evalExpr(ops[0], symbols, pc, lastLabel);
664
- return [ADDR16[m], v & 255, v >> 8 & 255];
796
+ expectOps(m, ops, 1);
797
+ const [lo, hi] = imm16(m, evalExpr(ops[0], symbols, pc, lastLabel));
798
+ return [ADDR16[m], lo, hi];
665
799
  }
666
- if (m === "MOV")
800
+ if (m === "MOV") {
801
+ expectOps(m, ops, 2);
802
+ const dst = reg8(m, ops[0]);
803
+ const src = reg8(m, ops[1]);
804
+ if (dst === 6 && src === 6) {
805
+ throw new Error("MOV M,M is not a valid instruction (encodes to HLT)");
806
+ }
807
+ return [64 | dst << 3 | src];
808
+ }
809
+ if (m === "MVI") {
810
+ expectOps(m, ops, 2);
667
811
  return [
668
- 64 | REG8[ops[0].toUpperCase()] << 3 | REG8[ops[1].toUpperCase()]
812
+ 6 | reg8(m, ops[0]) << 3,
813
+ imm8(m, evalExpr(ops[1], symbols, pc, lastLabel))
669
814
  ];
670
- if (m === "MVI") {
671
- const v = evalExpr(ops[1], symbols, pc, lastLabel);
672
- return [6 | REG8[ops[0].toUpperCase()] << 3, v & 255];
673
815
  }
674
- if (m === "INR")
675
- return [4 | REG8[ops[0].toUpperCase()] << 3];
676
- if (m === "DCR")
677
- return [5 | REG8[ops[0].toUpperCase()] << 3];
816
+ if (m === "INR") {
817
+ expectOps(m, ops, 1);
818
+ return [4 | reg8(m, ops[0]) << 3];
819
+ }
820
+ if (m === "DCR") {
821
+ expectOps(m, ops, 1);
822
+ return [5 | reg8(m, ops[0]) << 3];
823
+ }
678
824
  if (m === "LXI") {
679
- const v = evalExpr(ops[1], symbols, pc, lastLabel);
680
- return [
681
- 1 | REG_PAIR[ops[0].toUpperCase()] << 4,
682
- v & 255,
683
- v >> 8 & 255
684
- ];
825
+ expectOps(m, ops, 2);
826
+ const [lo, hi] = imm16(m, evalExpr(ops[1], symbols, pc, lastLabel));
827
+ return [1 | regPair(m, ops[0], REG_PAIR) << 4, lo, hi];
828
+ }
829
+ if (m === "DAD") {
830
+ expectOps(m, ops, 1);
831
+ return [9 | regPair(m, ops[0], REG_PAIR) << 4];
832
+ }
833
+ if (m === "INX") {
834
+ expectOps(m, ops, 1);
835
+ return [3 | regPair(m, ops[0], REG_PAIR) << 4];
836
+ }
837
+ if (m === "DCX") {
838
+ expectOps(m, ops, 1);
839
+ return [11 | regPair(m, ops[0], REG_PAIR) << 4];
840
+ }
841
+ if (m === "PUSH") {
842
+ expectOps(m, ops, 1);
843
+ return [197 | regPair(m, ops[0], REG_PAIR_PUSH) << 4];
844
+ }
845
+ if (m === "POP") {
846
+ expectOps(m, ops, 1);
847
+ return [193 | regPair(m, ops[0], REG_PAIR_PUSH) << 4];
848
+ }
849
+ if (m === "LDAX") {
850
+ expectOps(m, ops, 1);
851
+ return [10 | regPair(m, ops[0], LDAX_STAX_PAIRS) << 4];
852
+ }
853
+ if (m === "STAX") {
854
+ expectOps(m, ops, 1);
855
+ return [2 | regPair(m, ops[0], LDAX_STAX_PAIRS) << 4];
856
+ }
857
+ if (m === "IN") {
858
+ expectOps(m, ops, 1);
859
+ return [219, imm8(m, evalExpr(ops[0], symbols, pc, lastLabel))];
860
+ }
861
+ if (m === "OUT") {
862
+ expectOps(m, ops, 1);
863
+ return [211, imm8(m, evalExpr(ops[0], symbols, pc, lastLabel))];
685
864
  }
686
- if (m === "DAD")
687
- return [9 | REG_PAIR[ops[0].toUpperCase()] << 4];
688
- if (m === "INX")
689
- return [3 | REG_PAIR[ops[0].toUpperCase()] << 4];
690
- if (m === "DCX")
691
- return [11 | REG_PAIR[ops[0].toUpperCase()] << 4];
692
- if (m === "PUSH")
693
- return [197 | REG_PAIR_PUSH[ops[0].toUpperCase()] << 4];
694
- if (m === "POP")
695
- return [193 | REG_PAIR_PUSH[ops[0].toUpperCase()] << 4];
696
- if (m === "LDAX")
697
- return [10 | REG_PAIR[ops[0].toUpperCase()] << 4];
698
- if (m === "STAX")
699
- return [2 | REG_PAIR[ops[0].toUpperCase()] << 4];
700
- if (m === "IN")
701
- return [219, evalExpr(ops[0], symbols, pc, lastLabel) & 255];
702
- if (m === "OUT")
703
- return [211, evalExpr(ops[0], symbols, pc, lastLabel) & 255];
704
865
  if (m === "RST") {
866
+ expectOps(m, ops, 1);
705
867
  const n = evalExpr(ops[0], symbols, pc, lastLabel);
868
+ if (n < 0 || n > 7)
869
+ throw new Error(`RST: vector out of range 0..7: ${n}`);
706
870
  return [199 | n << 3];
707
871
  }
708
872
  throw new Error(`cannot encode: ${m} ${ops.join(", ")}`);
@@ -710,11 +874,12 @@ function encode(m, ops, symbols, pc = 0, lastLabel = "") {
710
874
  function dbBytes(operands, symbols, pc = 0, lastLabel = "") {
711
875
  const out = [];
712
876
  for (const op of operands) {
713
- if (op.startsWith('"') && op.endsWith('"') || op.startsWith("'") && op.endsWith("'")) {
714
- for (const ch of op.slice(1, -1))
715
- out.push(ch.charCodeAt(0));
877
+ const addr = pc + out.length;
878
+ if (op.startsWith('"') && op.endsWith('"') && op.length >= 2 || op.startsWith("'") && op.endsWith("'") && op.length >= 2) {
879
+ for (const b of decodeString(op))
880
+ out.push(b);
716
881
  } else {
717
- out.push(evalExpr(op, symbols, pc, lastLabel) & 255);
882
+ out.push(evalExpr(op, symbols, addr, lastLabel) & 255);
718
883
  }
719
884
  }
720
885
  return out;
@@ -722,7 +887,7 @@ function dbBytes(operands, symbols, pc = 0, lastLabel = "") {
722
887
  function dwBytes(operands, symbols, pc = 0, lastLabel = "") {
723
888
  const out = [];
724
889
  for (const op of operands) {
725
- const v = evalExpr(op, symbols, pc, lastLabel) & 65535;
890
+ const v = evalExpr(op, symbols, pc + out.length, lastLabel) & 65535;
726
891
  out.push(v & 255, v >> 8 & 255);
727
892
  }
728
893
  return out;
@@ -748,22 +913,22 @@ function countDs(operands, symbols, pc = 0, lastLabel = "") {
748
913
  function countDb(operands) {
749
914
  let n = 0;
750
915
  for (const op of operands) {
751
- if (op.startsWith('"') && op.endsWith('"') || op.startsWith("'") && op.endsWith("'"))
752
- n += op.length - 2;
916
+ if (op.startsWith('"') && op.endsWith('"') && op.length >= 2 || op.startsWith("'") && op.endsWith("'") && op.length >= 2)
917
+ n += decodeString(op).length;
753
918
  else
754
919
  n++;
755
920
  }
756
921
  return n;
757
922
  }
758
- function asm(source) {
759
- const pp = preprocess(source);
923
+ function asm(source, opts) {
924
+ const pp = preprocess(source, opts);
760
925
  const symbols = new Map;
761
926
  const pending = [];
762
927
  let pc = 0;
763
928
  let lastLabel = "";
764
929
  let ended = false;
765
930
  for (let idx = 0;idx < pp.length && !ended; idx++) {
766
- const { text: line, orig } = pp[idx];
931
+ const { text: line, orig, file } = pp[idx];
767
932
  try {
768
933
  for (const stmt of splitStatements(line)) {
769
934
  const parts = parseLine(stmt);
@@ -777,9 +942,10 @@ function asm(source) {
777
942
  lastLabel = parts.label;
778
943
  }
779
944
  if (parts.isEqu) {
780
- tryDefineEqu(symbols, pending, labelName, parts.operands[0], pc, lastLabel, orig, line);
945
+ tryDefineEqu(symbols, pending, labelName, parts.operands[0], pc, lastLabel, orig, line, file);
781
946
  continue;
782
947
  }
948
+ ensureSymbolFree(symbols, pending, labelName, orig, line, file);
783
949
  symbols.set(labelName.toUpperCase(), pc);
784
950
  }
785
951
  if (!parts.mnemonic)
@@ -814,7 +980,7 @@ function asm(source) {
814
980
  } catch (e) {
815
981
  if (e instanceof AsmError)
816
982
  throw e;
817
- throw new AsmError(e.message, orig, line, firstNonSpaceCol(line));
983
+ throw new AsmError(e.message, orig, line, firstNonSpaceCol(line), file);
818
984
  }
819
985
  }
820
986
  resolvePendingEqus(symbols, pending);
@@ -824,7 +990,7 @@ function asm(source) {
824
990
  let lastLabel2 = "";
825
991
  let endedPass2 = false;
826
992
  for (let idx = 0;idx < pp.length && !endedPass2; idx++) {
827
- const { text: line, orig } = pp[idx];
993
+ const { text: line, orig, file } = pp[idx];
828
994
  try {
829
995
  for (const stmt of splitStatements(line)) {
830
996
  const parts = parseLine(stmt);
@@ -870,7 +1036,7 @@ function asm(source) {
870
1036
  } catch (e) {
871
1037
  if (e instanceof AsmError)
872
1038
  throw e;
873
- throw new AsmError(e.message, orig, line, firstNonSpaceCol(line));
1039
+ throw new AsmError(e.message, orig, line, firstNonSpaceCol(line), file);
874
1040
  }
875
1041
  }
876
1042
  if (current && current.data.length) {
@@ -882,12 +1048,19 @@ function asm(source) {
882
1048
  function isUnknownSymbolErr(e) {
883
1049
  return e instanceof Error && /^unknown symbol:/.test(e.message);
884
1050
  }
885
- function tryDefineEqu(symbols, pending, name, expr, pc, lastLabel, orig, line) {
1051
+ function ensureSymbolFree(symbols, pending, name, orig, line, file) {
1052
+ const upper = name.toUpperCase();
1053
+ if (symbols.has(upper) || pending.some((p) => p.name.toUpperCase() === upper)) {
1054
+ throw new AsmError(`duplicate symbol: ${name}`, orig, line, firstNonSpaceCol(line), file);
1055
+ }
1056
+ }
1057
+ function tryDefineEqu(symbols, pending, name, expr, pc, lastLabel, orig, line, file) {
1058
+ ensureSymbolFree(symbols, pending, name, orig, line, file);
886
1059
  try {
887
1060
  symbols.set(name.toUpperCase(), evalExpr(expr, symbols, pc, lastLabel));
888
1061
  } catch (e) {
889
1062
  if (isUnknownSymbolErr(e)) {
890
- pending.push({ name, expr, pc, lastLabel, orig, line });
1063
+ pending.push({ name, expr, pc, lastLabel, orig, line, file });
891
1064
  } else {
892
1065
  throw e;
893
1066
  }
@@ -905,7 +1078,7 @@ function resolvePendingEqus(symbols, pending) {
905
1078
  if (isUnknownSymbolErr(e)) {
906
1079
  next.push(p);
907
1080
  } else {
908
- throw new AsmError(e.message, p.orig, p.line, firstNonSpaceCol(p.line));
1081
+ throw new AsmError(e.message, p.orig, p.line, firstNonSpaceCol(p.line), p.file);
909
1082
  }
910
1083
  }
911
1084
  }
@@ -914,7 +1087,7 @@ function resolvePendingEqus(symbols, pending) {
914
1087
  try {
915
1088
  evalExpr(p.expr, symbols, p.pc, p.lastLabel);
916
1089
  } catch (e) {
917
- throw new AsmError(e.message, p.orig, p.line, firstNonSpaceCol(p.line));
1090
+ throw new AsmError(e.message, p.orig, p.line, firstNonSpaceCol(p.line), p.file);
918
1091
  }
919
1092
  return;
920
1093
  }
@@ -933,7 +1106,7 @@ import { basename } from "path";
933
1106
  // packages/rk86/package.json
934
1107
  var package_default = {
935
1108
  name: "rk86",
936
- version: "2.0.30",
1109
+ version: "2.0.33",
937
1110
  description: "\u042D\u043C\u0443\u043B\u044F\u0442\u043E\u0440 \u0420\u0430\u0434\u0438\u043E-86\u0420\u041A (Intel 8080) \u0434\u043B\u044F \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430",
938
1111
  bin: {
939
1112
  rk86: "rk86.js"
@@ -1898,7 +2071,10 @@ var parse = (binary) => {
1898
2071
  };
1899
2072
  var convert_hex_to_binary = function(text) {
1900
2073
  const lines = text.split(`
1901
- `).filter((line) => line.trim().length).filter((line) => !line.startsWith(";") && !line.startsWith("#"));
2074
+ `).filter((line) => line.trim().length).filter((line) => {
2075
+ const c = line.trim()[0];
2076
+ return c !== ";" && c !== "#" && c !== "!";
2077
+ });
1902
2078
  const image = [];
1903
2079
  for (const line of lines) {
1904
2080
  const hex_line = line.slice(5).trim();
@@ -2087,9 +2263,9 @@ function create(array, width = 16) {
2087
2263
  }
2088
2264
  return v;
2089
2265
  }
2090
- function parse2(hex2) {
2266
+ function parse2(hex) {
2091
2267
  const array = [];
2092
- for (let [label, line] of Object.entries(hex2)) {
2268
+ for (let [label, line] of Object.entries(hex)) {
2093
2269
  const address = parseInt(label.slice(1), 16);
2094
2270
  const line_values = line.split(" ").map((value) => parseInt(value, 16));
2095
2271
  for (let j = 0;j < line_values.length; j++) {
@@ -2099,6 +2275,124 @@ function parse2(hex2) {
2099
2275
  return array;
2100
2276
  }
2101
2277
 
2278
+ // src/lib/core/rk86_profile.ts
2279
+ var CLASSIC_PROFILE_NAME = "RK86_CLASSIC";
2280
+ var PERIPHERAL_WINDOW = 8192;
2281
+ var PERIPHERAL_WINDOWS = [8192, 4096, 2048, 1024, 512, 256];
2282
+ var PERIPHERAL_WINDOW_LABEL = "\u041E\u043A\u043D\u043E \u043F\u0435\u0440\u0438\u0444\u0435\u0440\u0438\u0438";
2283
+ function peripheralWindowLabel(window) {
2284
+ return window >= 1024 ? `${window / 1024} \u041A\u0411` : `${window} \u0431\u0430\u0439\u0442`;
2285
+ }
2286
+ function peripheralWindowMask(window) {
2287
+ return 65536 - window & 65535;
2288
+ }
2289
+ var RK86_CLASSIC = Object.freeze({
2290
+ name: CLASSIC_PROFILE_NAME,
2291
+ ram_end: 32767,
2292
+ rom_start: 57344,
2293
+ boot_address: 63488,
2294
+ keyboard_ppi_base: 32768,
2295
+ crtc_base: 49152,
2296
+ dma_base: 57344,
2297
+ peripheral_window: PERIPHERAL_WINDOW
2298
+ });
2299
+ var PROFILE_ADDRESS_FIELDS = ["ram_end", "rom_start", "boot_address", "keyboard_ppi_base", "crtc_base", "dma_base"];
2300
+ var PROFILE_FIELD_LABELS = {
2301
+ ram_end: "\u041E\u0417\u0423 \u0434\u043E",
2302
+ rom_start: "\u041F\u0417\u0423 \u043E\u0442",
2303
+ boot_address: "\u0410\u0434\u0440\u0435\u0441 \u0437\u0430\u043F\u0443\u0441\u043A\u0430",
2304
+ keyboard_ppi_base: "\u041F\u041F\u0418 \u043A\u043B\u0430\u0432\u0438\u0430\u0442\u0443\u0440\u044B (\u0412\u041255)",
2305
+ crtc_base: "\u041A\u043E\u043D\u0442\u0440\u043E\u043B\u043B\u0435\u0440 \u044D\u043A\u0440\u0430\u043D\u0430 (\u0412\u041375)",
2306
+ dma_base: "\u041A\u043E\u043D\u0442\u0440\u043E\u043B\u043B\u0435\u0440 \u041F\u0414\u041F (\u0412\u042257)"
2307
+ };
2308
+ function exportProfile(profile) {
2309
+ const h16 = (n) => "0x" + n.toString(16).toUpperCase().padStart(4, "0");
2310
+ const result = { name: profile.name };
2311
+ for (const field of PROFILE_ADDRESS_FIELDS)
2312
+ result[field] = h16(profile[field]);
2313
+ result.peripheral_window = h16(profile.peripheral_window);
2314
+ return result;
2315
+ }
2316
+ function profilesEqual(a, b) {
2317
+ return a.name === b.name && a.peripheral_window === b.peripheral_window && PROFILE_ADDRESS_FIELDS.every((field) => a[field] === b[field]);
2318
+ }
2319
+ var is16bit = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 65535;
2320
+ function validateProfile(profile) {
2321
+ const errors = [];
2322
+ const name = typeof profile.name === "string" ? profile.name.trim() : "";
2323
+ if (!name)
2324
+ errors.push("\u0438\u043C\u044F \u043F\u0440\u043E\u0444\u0438\u043B\u044F \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C");
2325
+ else if (name.length > 32)
2326
+ errors.push("\u0438\u043C\u044F \u043F\u0440\u043E\u0444\u0438\u043B\u044F \u0434\u043B\u0438\u043D\u043D\u0435\u0435 32 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432");
2327
+ for (const field of PROFILE_ADDRESS_FIELDS) {
2328
+ if (!is16bit(profile[field]))
2329
+ errors.push(`${PROFILE_FIELD_LABELS[field]}: \u0430\u0434\u0440\u0435\u0441 \u0434\u043E\u043B\u0436\u0435\u043D \u0431\u044B\u0442\u044C \u0432 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\u0435 0000-FFFF`);
2330
+ }
2331
+ if (!PERIPHERAL_WINDOWS.includes(profile.peripheral_window)) {
2332
+ errors.push(`${PERIPHERAL_WINDOW_LABEL}: \u0440\u0430\u0437\u043C\u0435\u0440 \u0434\u043E\u043B\u0436\u0435\u043D \u0431\u044B\u0442\u044C \u043E\u0434\u043D\u0438\u043C \u0438\u0437 ${PERIPHERAL_WINDOWS.map(peripheralWindowLabel).join(", ")}`);
2333
+ }
2334
+ if (errors.length)
2335
+ return errors;
2336
+ const window = profile.peripheral_window;
2337
+ const windowHex = window.toString(16).toUpperCase();
2338
+ if (profile.ram_end >= profile.rom_start)
2339
+ errors.push("\u041E\u0417\u0423 \u0434\u043E\u043B\u0436\u043D\u043E \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u0440\u0430\u043D\u044C\u0448\u0435 \u043D\u0430\u0447\u0430\u043B\u0430 \u041F\u0417\u0423");
2340
+ if (profile.boot_address < profile.rom_start)
2341
+ errors.push("\u0430\u0434\u0440\u0435\u0441 \u0437\u0430\u043F\u0443\u0441\u043A\u0430 \u0434\u043E\u043B\u0436\u0435\u043D \u043B\u0435\u0436\u0430\u0442\u044C \u0432 \u041F\u0417\u0423");
2342
+ const bases = ["keyboard_ppi_base", "crtc_base", "dma_base"];
2343
+ for (const field of bases) {
2344
+ const base = profile[field];
2345
+ const label = PROFILE_FIELD_LABELS[field];
2346
+ if (base % window !== 0)
2347
+ errors.push(`${label}: \u0431\u0430\u0437\u0430 \u0434\u043E\u043B\u0436\u043D\u0430 \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u0430 ${windowHex}`);
2348
+ if (base <= profile.ram_end)
2349
+ errors.push(`${label}: \u043E\u043A\u043D\u043E \u043F\u0435\u0440\u0438\u0444\u0435\u0440\u0438\u0438 \u043F\u0435\u0440\u0435\u0441\u0435\u043A\u0430\u0435\u0442\u0441\u044F \u0441 \u041E\u0417\u0423`);
2350
+ }
2351
+ for (let i = 0;i < bases.length; i++) {
2352
+ for (let j = i + 1;j < bases.length; j++) {
2353
+ if (profile[bases[i]] === profile[bases[j]]) {
2354
+ errors.push(`${PROFILE_FIELD_LABELS[bases[i]]} \u0438 ${PROFILE_FIELD_LABELS[bases[j]]}: \u043E\u0434\u0438\u043D\u0430\u043A\u043E\u0432\u0430\u044F \u0431\u0430\u0437\u0430`);
2355
+ }
2356
+ }
2357
+ }
2358
+ return errors;
2359
+ }
2360
+ function normalizeProfile(raw) {
2361
+ if (!raw || typeof raw !== "object")
2362
+ return null;
2363
+ const source = raw;
2364
+ if (typeof source.name !== "string")
2365
+ return null;
2366
+ const profile = { name: source.name.trim() };
2367
+ for (const field of PROFILE_ADDRESS_FIELDS) {
2368
+ const value = source[field];
2369
+ let number;
2370
+ if (typeof value === "number")
2371
+ number = value;
2372
+ else if (typeof value === "string" && /^(0x)?[0-9a-f]{1,4}$/i.test(value.trim())) {
2373
+ number = parseInt(value.trim().replace(/^0x/i, ""), 16);
2374
+ } else if (field === "boot_address" && value === undefined) {
2375
+ number = RK86_CLASSIC.boot_address;
2376
+ } else
2377
+ return null;
2378
+ if (!is16bit(number))
2379
+ return null;
2380
+ profile[field] = number;
2381
+ }
2382
+ const window = source.peripheral_window;
2383
+ if (window === undefined)
2384
+ profile.peripheral_window = PERIPHERAL_WINDOW;
2385
+ else if (typeof window === "number")
2386
+ profile.peripheral_window = window;
2387
+ else if (typeof window === "string" && /^(0x)?[0-9a-f]{1,5}$/i.test(window.trim())) {
2388
+ profile.peripheral_window = parseInt(window.trim().replace(/^0x/i, ""), 16);
2389
+ } else
2390
+ return null;
2391
+ if (!Number.isInteger(profile.peripheral_window) || profile.peripheral_window <= 0)
2392
+ return null;
2393
+ return profile;
2394
+ }
2395
+
2102
2396
  // src/lib/core/rk86_memory.ts
2103
2397
  class Memory {
2104
2398
  buf = [];
@@ -2125,11 +2419,45 @@ class Memory {
2125
2419
  last_access_address = 0;
2126
2420
  last_access_operation = undefined;
2127
2421
  tracer = null;
2128
- constructor(machine) {
2422
+ profile = RK86_CLASSIC;
2423
+ peripheral_window_mask = 57344;
2424
+ ppi_mask = 57347;
2425
+ crtc_mask = 57345;
2426
+ dma_mask = 57359;
2427
+ on_profile_changed = null;
2428
+ ppi_port_a = 0;
2429
+ ppi_port_b = 0;
2430
+ ppi_port_c = 0;
2431
+ ppi_control = 0;
2432
+ crtc_parameter = 0;
2433
+ crtc_command = 0;
2434
+ dma_ch0_address = 0;
2435
+ dma_ch0_count = 0;
2436
+ dma_mode = 0;
2437
+ constructor(machine, profile = RK86_CLASSIC) {
2129
2438
  this.machine = machine;
2439
+ this.set_profile(profile);
2130
2440
  this.init();
2131
2441
  this.invalidate_access_variables();
2132
2442
  }
2443
+ set_profile(profile) {
2444
+ this.profile = profile;
2445
+ const window_mask = peripheralWindowMask(profile.peripheral_window);
2446
+ this.peripheral_window_mask = window_mask;
2447
+ this.ppi_mask = window_mask | 3;
2448
+ this.crtc_mask = window_mask | 1;
2449
+ this.dma_mask = window_mask | 15;
2450
+ this.ppi_port_a = profile.keyboard_ppi_base | 0;
2451
+ this.ppi_port_b = profile.keyboard_ppi_base | 1;
2452
+ this.ppi_port_c = profile.keyboard_ppi_base | 2;
2453
+ this.ppi_control = profile.keyboard_ppi_base | 3;
2454
+ this.crtc_parameter = profile.crtc_base | 0;
2455
+ this.crtc_command = profile.crtc_base | 1;
2456
+ this.dma_ch0_address = profile.dma_base | 4;
2457
+ this.dma_ch0_count = profile.dma_base | 5;
2458
+ this.dma_mode = profile.dma_base | 8;
2459
+ this.on_profile_changed?.(profile);
2460
+ }
2133
2461
  init() {
2134
2462
  this.buf = new Array(65536).fill(0);
2135
2463
  this.vg75_c001_00_cmd = 0;
@@ -2152,7 +2480,7 @@ class Memory {
2152
2480
  this.video_screen_cursor_y = 0;
2153
2481
  }
2154
2482
  zero_ram() {
2155
- for (let i = 0;i < 32768; ++i)
2483
+ for (let i = 0;i <= this.profile.ram_end; ++i)
2156
2484
  this.buf[i] = 0;
2157
2485
  }
2158
2486
  snapshot(from, sz) {
@@ -2224,27 +2552,27 @@ class Memory {
2224
2552
  this.last_access_address = addr;
2225
2553
  this.last_access_operation = "read";
2226
2554
  this.tracer?.("read", addr);
2227
- const ppi_reg = addr & 57347;
2228
- const vg75_reg = addr & 57345;
2229
- if (ppi_reg === 32770)
2555
+ const ppi_reg = addr & this.ppi_mask;
2556
+ const vg75_reg = addr & this.crtc_mask;
2557
+ if (ppi_reg === this.ppi_port_c)
2230
2558
  return this.machine.keyboard.modifiers;
2231
- if (ppi_reg === 32769) {
2559
+ if (ppi_reg === this.ppi_port_b) {
2232
2560
  const keyboard_state = this.machine.keyboard.state;
2233
2561
  let ch = 255;
2234
- const kbd_scanline = ~this.buf[32768];
2562
+ const kbd_scanline = ~this.buf[this.ppi_port_a];
2235
2563
  for (let i = 0;i < 8; i++)
2236
2564
  if (1 << i & kbd_scanline)
2237
2565
  ch &= keyboard_state[i];
2238
2566
  return ch;
2239
2567
  }
2240
- if (vg75_reg === 49153) {
2568
+ if (vg75_reg === this.crtc_command) {
2241
2569
  const ticks = this.machine.runner.total_ticks;
2242
2570
  const FRAME = 35600;
2243
2571
  const VRTC_ON = 3560;
2244
2572
  const vrtc = ticks % FRAME >= FRAME - VRTC_ON ? 32 : 0;
2245
2573
  return vrtc | (this.machine.screen.light_pen_active ? 16 : 0);
2246
2574
  }
2247
- if (vg75_reg === 49152) {
2575
+ if (vg75_reg === this.crtc_parameter) {
2248
2576
  if (this.vg75_c001_60_cmd === 1) {
2249
2577
  this.vg75_c001_60_cmd = 2;
2250
2578
  return this.machine.screen.light_pen_x;
@@ -2268,12 +2596,12 @@ class Memory {
2268
2596
  this.last_access_address = addr;
2269
2597
  this.last_access_operation = "write";
2270
2598
  this.tracer?.("write", addr);
2271
- if (addr < 63488)
2599
+ if (addr < this.profile.rom_start)
2272
2600
  this.buf[addr] = byte;
2273
- const ppi_reg = addr & 57347;
2274
- const vg75_reg = addr & 57345;
2275
- const vt57_reg = addr & 57359;
2276
- if (ppi_reg === 32771) {
2601
+ const ppi_reg = addr & this.ppi_mask;
2602
+ const vg75_reg = addr & this.crtc_mask;
2603
+ const vt57_reg = addr & this.dma_mask;
2604
+ if (ppi_reg === this.ppi_control) {
2277
2605
  if (byte & 128) {} else {
2278
2606
  const bit = byte >> 1 & 3;
2279
2607
  const value = byte & 1;
@@ -2282,20 +2610,20 @@ class Memory {
2282
2610
  }
2283
2611
  return;
2284
2612
  }
2285
- if (vg75_reg === 49153 && byte === 39)
2613
+ if (vg75_reg === this.crtc_command && byte === 39)
2286
2614
  return;
2287
- if (vg75_reg === 49153 && byte === 224)
2615
+ if (vg75_reg === this.crtc_command && byte === 224)
2288
2616
  return;
2289
- if (vg75_reg === 49153 && byte === 128) {
2617
+ if (vg75_reg === this.crtc_command && byte === 128) {
2290
2618
  this.vg75_c001_80_cmd = 1;
2291
2619
  return;
2292
2620
  }
2293
- if (vg75_reg === 49152 && this.vg75_c001_80_cmd === 1) {
2621
+ if (vg75_reg === this.crtc_parameter && this.vg75_c001_80_cmd === 1) {
2294
2622
  this.vg75_c001_80_cmd += 1;
2295
2623
  this.cursor_x_buf = byte + 1;
2296
2624
  return;
2297
2625
  }
2298
- if (vg75_reg === 49152 && this.vg75_c001_80_cmd === 2) {
2626
+ if (vg75_reg === this.crtc_parameter && this.vg75_c001_80_cmd === 2) {
2299
2627
  this.cursor_y_buf = byte + 1;
2300
2628
  this.machine.screen.set_cursor(this.cursor_x_buf - 1, this.cursor_y_buf - 1);
2301
2629
  this.video_screen_cursor_x = this.cursor_x_buf;
@@ -2303,32 +2631,33 @@ class Memory {
2303
2631
  this.vg75_c001_80_cmd = 0;
2304
2632
  return;
2305
2633
  }
2306
- if (vg75_reg === 49153 && byte === 96) {
2634
+ if (vg75_reg === this.crtc_command && byte === 96) {
2307
2635
  if (this.machine.screen.light_pen_active)
2308
2636
  this.vg75_c001_60_cmd = 1;
2309
2637
  return;
2310
2638
  }
2311
- if (vg75_reg === 49153 && byte === 0) {
2639
+ if (vg75_reg === this.crtc_command && byte === 0) {
2312
2640
  this.vg75_c001_00_cmd = 1;
2313
2641
  return;
2314
2642
  }
2315
- if (vg75_reg === 49152 && this.vg75_c001_00_cmd === 1) {
2643
+ if (vg75_reg === this.crtc_parameter && this.vg75_c001_00_cmd === 1) {
2316
2644
  this.video_screen_size_x_buf = (byte & 127) + 1;
2317
2645
  this.vg75_c001_00_cmd += 1;
2318
2646
  return;
2319
2647
  }
2320
- if (vg75_reg === 49152 && this.vg75_c001_00_cmd === 2) {
2648
+ if (vg75_reg === this.crtc_parameter && this.vg75_c001_00_cmd === 2) {
2321
2649
  this.video_screen_size_y_buf = (byte & 63) + 1;
2650
+ this.machine.screen.vrtc_rows = (byte >> 6 & 3) + 1;
2322
2651
  this.vg75_c001_00_cmd += 1;
2323
2652
  return;
2324
2653
  }
2325
- if (vg75_reg === 49152 && this.vg75_c001_00_cmd === 3) {
2654
+ if (vg75_reg === this.crtc_parameter && this.vg75_c001_00_cmd === 3) {
2326
2655
  this.machine.screen.set_char_height((byte & 15) + 1);
2327
2656
  this.machine.screen.underline_scanline = byte >> 4 & 15;
2328
2657
  this.vg75_c001_00_cmd += 1;
2329
2658
  return;
2330
2659
  }
2331
- if (vg75_reg === 49152 && this.vg75_c001_00_cmd === 4) {
2660
+ if (vg75_reg === this.crtc_parameter && this.vg75_c001_00_cmd === 4) {
2332
2661
  this.vg75_c001_00_cmd = 0;
2333
2662
  if (this.video_screen_size_x_buf && this.video_screen_size_y_buf) {
2334
2663
  this.video_screen_size_x = this.video_screen_size_x_buf;
@@ -2336,30 +2665,31 @@ class Memory {
2336
2665
  this.machine.screen.set_geometry(this.video_screen_size_x, this.video_screen_size_y);
2337
2666
  }
2338
2667
  this.machine.screen.transparent_attr = (byte & 64) === 0;
2668
+ this.machine.screen.hrtc_chars = ((byte & 15) + 1) * 2;
2339
2669
  return;
2340
2670
  }
2341
- if (vt57_reg === 57352 && byte === 128) {
2671
+ if (vt57_reg === this.dma_mode && byte === 128) {
2342
2672
  this.ik57_e008_80_cmd = 1;
2343
2673
  this.ik57_ff = 0;
2344
2674
  this.tape_8002_as_output = 1;
2345
2675
  return;
2346
2676
  }
2347
- if (vt57_reg === 57348 && this.ik57_e008_80_cmd === 1) {
2677
+ if (vt57_reg === this.dma_ch0_address && this.ik57_e008_80_cmd === 1) {
2348
2678
  this.video_memory_base_buf = byte;
2349
2679
  this.ik57_e008_80_cmd += 1;
2350
2680
  return;
2351
2681
  }
2352
- if (vt57_reg === 57348 && this.ik57_e008_80_cmd === 2) {
2682
+ if (vt57_reg === this.dma_ch0_address && this.ik57_e008_80_cmd === 2) {
2353
2683
  this.video_memory_base_buf |= byte << 8;
2354
2684
  this.ik57_e008_80_cmd += 1;
2355
2685
  return;
2356
2686
  }
2357
- if (vt57_reg === 57349 && this.ik57_e008_80_cmd === 3) {
2687
+ if (vt57_reg === this.dma_ch0_count && this.ik57_e008_80_cmd === 3) {
2358
2688
  this.video_memory_size_buf = byte;
2359
2689
  this.ik57_e008_80_cmd += 1;
2360
2690
  return;
2361
2691
  }
2362
- if (vt57_reg === 57349 && this.ik57_e008_80_cmd === 4) {
2692
+ if (vt57_reg === this.dma_ch0_count && this.ik57_e008_80_cmd === 4) {
2363
2693
  this.video_memory_size_buf = ((this.video_memory_size_buf | byte << 8) & 16383) + 1;
2364
2694
  this.ik57_e008_80_cmd = 0;
2365
2695
  this.video_memory_base = this.video_memory_base_buf;
@@ -2367,11 +2697,11 @@ class Memory {
2367
2697
  this.machine.screen.set_video_memory(this.video_memory_base);
2368
2698
  return;
2369
2699
  }
2370
- if (vt57_reg === 57352 && byte === 164) {
2700
+ if (vt57_reg === this.dma_mode && byte === 164) {
2371
2701
  this.tape_8002_as_output = 0;
2372
2702
  return;
2373
2703
  }
2374
- if (vt57_reg === 57348 && this.ik57_e008_80_cmd === 0) {
2704
+ if (vt57_reg === this.dma_ch0_address && this.ik57_e008_80_cmd === 0) {
2375
2705
  if (this.ik57_ff === 0) {
2376
2706
  this.video_memory_base_buf = this.video_memory_base & 65280 | byte;
2377
2707
  this.ik57_ff = 1;
@@ -2383,7 +2713,7 @@ class Memory {
2383
2713
  }
2384
2714
  return;
2385
2715
  }
2386
- if (vt57_reg === 57349 && this.ik57_e008_80_cmd === 0) {
2716
+ if (vt57_reg === this.dma_ch0_count && this.ik57_e008_80_cmd === 0) {
2387
2717
  if (this.ik57_ff === 0) {
2388
2718
  this.video_memory_size_buf = byte;
2389
2719
  this.ik57_ff = 1;
@@ -2394,7 +2724,7 @@ class Memory {
2394
2724
  }
2395
2725
  return;
2396
2726
  }
2397
- if (ppi_reg === 32770) {
2727
+ if (ppi_reg === this.ppi_port_c) {
2398
2728
  if (this.tape_8002_as_output) {
2399
2729
  this.tape_write_bit(byte & 1);
2400
2730
  }
@@ -2423,45 +2753,39 @@ class Runner {
2423
2753
  stc_streak = 0;
2424
2754
  tracer = null;
2425
2755
  last_instructions = [];
2426
- previous_batch_time = 0;
2427
2756
  total_ticks = 0;
2428
- last_iff_raise_ticks = 0;
2757
+ total_instructions = 0;
2429
2758
  last_iff = 0;
2430
2759
  sound = null;
2431
2760
  sound_factory;
2432
2761
  instructions_per_millisecond = 0;
2433
2762
  ticks_per_millisecond = 0;
2434
2763
  FREQ = 1780000;
2435
- TICK_PER_MS;
2436
2764
  execute_timer;
2437
2765
  machine;
2766
+ BATCH_TICKS;
2767
+ TICKS_PER_WALL_MS;
2438
2768
  constructor(machine) {
2439
2769
  this.machine = machine;
2440
- this.TICK_PER_MS = this.FREQ / 100;
2770
+ this.BATCH_TICKS = this.FREQ / 100;
2771
+ this.TICKS_PER_WALL_MS = this.FREQ / 1000;
2441
2772
  this.machine.io.interrupt = (iff) => this.interrupt(iff);
2442
- this.machine.cpu.jump(63488);
2773
+ this.machine.cpu.jump(this.machine.memory.profile.boot_address);
2443
2774
  }
2444
2775
  interrupt(iff) {
2445
2776
  if (!this.sound || this.turbo)
2446
2777
  return;
2447
2778
  if (this.last_iff == iff)
2448
2779
  return;
2449
- if (this.last_iff == 0 && iff == 1) {
2450
- this.last_iff_raise_ticks = this.total_ticks;
2451
- }
2452
- if (this.last_iff == 1 && iff == 0) {
2453
- const tone_ticks = this.total_ticks - this.last_iff_raise_ticks;
2454
- const tone = this.FREQ / (tone_ticks * 2);
2455
- const duration = 1 / tone;
2456
- this.sound.play(tone, duration);
2457
- }
2458
2780
  this.last_iff = iff;
2781
+ this.sound.out(iff, this.total_ticks);
2459
2782
  }
2460
2783
  init_sound(enabled) {
2461
2784
  if (enabled && this.sound == null && this.sound_factory) {
2462
2785
  this.sound = this.sound_factory();
2463
2786
  this.machine.log("\u0437\u0432\u0443\u043A \u0432\u043A\u043B\u044E\u0447\u0435\u043D");
2464
2787
  } else if (!enabled) {
2788
+ this.sound?.done?.();
2465
2789
  this.sound = null;
2466
2790
  this.machine.log("\u0437\u0432\u0443\u043A \u0432\u044B\u043A\u043B\u044E\u0447\u0435\u043D");
2467
2791
  }
@@ -2471,28 +2795,46 @@ class Runner {
2471
2795
  if (options.turbo !== undefined)
2472
2796
  this.turbo = options.turbo;
2473
2797
  clearTimeout(this.execute_timer);
2474
- const turbo = this.turbo;
2475
- const bursts = turbo ? 100 : 1;
2476
- for (let burst = 0;burst < bursts; burst++) {
2477
- if (this.paused)
2478
- break;
2479
- let batch_ticks = 0;
2480
- let batch_instructions = 0;
2481
- while (batch_ticks < this.TICK_PER_MS) {
2798
+ const QUANTUM_BUDGET_MS = 5;
2799
+ const TURBO_BUDGET_MS = 50;
2800
+ const MAX_DT_MS = 100;
2801
+ const PAUSED_TICK_MS = 50;
2802
+ const PERF_WINDOW_MS = 500;
2803
+ let next_batch_boundary = this.total_ticks + this.BATCH_TICKS;
2804
+ let last_call_time = performance.now();
2805
+ let perf_window_start_wall = last_call_time;
2806
+ let perf_window_start_instructions = this.total_instructions;
2807
+ let perf_window_start_ticks = this.total_ticks;
2808
+ const tick = () => {
2809
+ if (this.paused) {
2810
+ last_call_time = performance.now();
2811
+ perf_window_start_wall = last_call_time;
2812
+ perf_window_start_instructions = this.total_instructions;
2813
+ perf_window_start_ticks = this.total_ticks;
2814
+ next_batch_boundary = this.total_ticks + this.BATCH_TICKS;
2815
+ this.execute_timer = setTimeout(tick, PAUSED_TICK_MS);
2816
+ return;
2817
+ }
2818
+ const call_start = performance.now();
2819
+ const dt_ms = Math.min(call_start - last_call_time, MAX_DT_MS);
2820
+ last_call_time = call_start;
2821
+ const target_total = this.turbo ? Number.POSITIVE_INFINITY : this.total_ticks + dt_ms * this.TICKS_PER_WALL_MS;
2822
+ const deadline = call_start + (this.turbo ? TURBO_BUDGET_MS : QUANTUM_BUDGET_MS);
2823
+ let terminated = false;
2824
+ while (!this.paused && !terminated && this.total_ticks < target_total && performance.now() < deadline) {
2482
2825
  if (this.tracer) {
2483
2826
  this.tracer("before");
2484
2827
  if (this.paused)
2485
2828
  break;
2486
2829
  }
2487
2830
  this.last_instructions.push(this.machine.cpu.pc);
2488
- if (this.last_instructions.length > 5) {
2831
+ if (this.last_instructions.length > 5)
2489
2832
  this.last_instructions.shift();
2490
- }
2491
2833
  const opcode_pc = this.machine.cpu.pc;
2492
2834
  this.machine.memory.invalidate_access_variables();
2493
2835
  const instruction_ticks = this.machine.cpu.instruction();
2494
- batch_ticks += instruction_ticks;
2495
2836
  this.total_ticks += instruction_ticks;
2837
+ this.total_instructions += 1;
2496
2838
  if (this.hardware_id_enabled) {
2497
2839
  if (this.machine.memory.read_raw(opcode_pc) === 55) {
2498
2840
  if (++this.stc_streak >= 4) {
@@ -2511,7 +2853,6 @@ class Runner {
2511
2853
  if (this.machine.ui.visualizer_visible && this.machine.ui.on_visualizer_hit) {
2512
2854
  this.machine.ui.on_visualizer_hit(this.machine.memory.read_raw(this.machine.cpu.pc));
2513
2855
  }
2514
- batch_instructions += 1;
2515
2856
  if (terminate_address !== undefined && this.machine.cpu.pc === terminate_address) {
2516
2857
  on_terminate?.();
2517
2858
  return;
@@ -2521,19 +2862,28 @@ class Runner {
2521
2862
  on_terminate?.();
2522
2863
  return;
2523
2864
  }
2524
- if (on_halt && on_halt())
2525
- return;
2865
+ if (on_halt && on_halt()) {
2866
+ terminated = true;
2867
+ break;
2868
+ }
2869
+ }
2870
+ if (this.total_ticks >= next_batch_boundary) {
2871
+ this.machine.screen.tick_cursor(this.total_ticks, this.FREQ * (this.machine.screen.cursor_rate / 1000));
2872
+ on_batch_complete?.();
2873
+ next_batch_boundary += this.BATCH_TICKS;
2526
2874
  }
2527
2875
  }
2528
- const now = performance.now();
2529
- const elapsed = now - this.previous_batch_time;
2530
- this.previous_batch_time = now;
2531
- this.instructions_per_millisecond = batch_instructions / elapsed;
2532
- this.ticks_per_millisecond = batch_ticks / elapsed;
2533
- this.machine.screen.tick_cursor(this.total_ticks, this.FREQ * (this.machine.screen.cursor_rate / 1000));
2534
- on_batch_complete?.();
2535
- }
2536
- this.execute_timer = setTimeout(() => this.execute(options), turbo ? 0 : 10);
2876
+ const window_elapsed = performance.now() - perf_window_start_wall;
2877
+ if (window_elapsed >= PERF_WINDOW_MS) {
2878
+ this.instructions_per_millisecond = (this.total_instructions - perf_window_start_instructions) / window_elapsed;
2879
+ this.ticks_per_millisecond = (this.total_ticks - perf_window_start_ticks) / window_elapsed;
2880
+ perf_window_start_wall = performance.now();
2881
+ perf_window_start_instructions = this.total_instructions;
2882
+ perf_window_start_ticks = this.total_ticks;
2883
+ }
2884
+ this.execute_timer = setTimeout(tick, 0);
2885
+ };
2886
+ tick();
2537
2887
  }
2538
2888
  pause() {
2539
2889
  this.paused = true;
@@ -2542,7 +2892,7 @@ class Runner {
2542
2892
  this.paused = false;
2543
2893
  }
2544
2894
  reset() {
2545
- this.machine.cpu.jump(63488);
2895
+ this.machine.cpu.jump(this.machine.memory.profile.boot_address);
2546
2896
  this.machine.keyboard.reset();
2547
2897
  }
2548
2898
  fire_hardware_id() {
@@ -2556,7 +2906,8 @@ class Runner {
2556
2906
 
2557
2907
  // src/lib/core/rk86_screen.ts
2558
2908
  class Screen {
2559
- static #update_rate = 40;
2909
+ static CHAR_CLOCK_HZ = 8000000 / 6;
2910
+ static #IDLE_RENDER_MS = 40;
2560
2911
  machine;
2561
2912
  cursor_rate;
2562
2913
  scale_x;
@@ -2576,6 +2927,9 @@ class Screen {
2576
2927
  underline_scanline = 7;
2577
2928
  color_mode = DEFAULT_COLOR_MODE;
2578
2929
  ready = false;
2930
+ hrtc_chars = 8;
2931
+ vrtc_rows = 1;
2932
+ render_mode = "vg75";
2579
2933
  renderer;
2580
2934
  constructor(machine) {
2581
2935
  this.machine = machine;
@@ -2630,7 +2984,16 @@ class Screen {
2630
2984
  start(renderer) {
2631
2985
  this.renderer = renderer;
2632
2986
  this.renderer.connect(this.machine);
2633
- this.render_loop();
2987
+ this.schedule_next_render();
2988
+ }
2989
+ set_render_mode(mode) {
2990
+ if (this.render_mode === mode)
2991
+ return;
2992
+ this.render_mode = mode;
2993
+ }
2994
+ frame_period_ms() {
2995
+ const chars = (this.width + this.hrtc_chars) * (this.height + this.vrtc_rows) * this.char_height;
2996
+ return 1000 * chars / Screen.CHAR_CLOCK_HZ;
2634
2997
  }
2635
2998
  last_flip_ticks = 0;
2636
2999
  tick_cursor(total_ticks, ticks_per_flip) {
@@ -2644,10 +3007,21 @@ class Screen {
2644
3007
  this.last_flip_ticks += ticks_per_flip;
2645
3008
  }
2646
3009
  }
2647
- render_loop() {
3010
+ render_loop = () => {
2648
3011
  if (this.ready)
2649
3012
  this.renderer.update();
2650
- setTimeout(() => this.render_loop(), Screen.#update_rate);
3013
+ this.schedule_next_render();
3014
+ };
3015
+ schedule_next_render() {
3016
+ if (!this.ready) {
3017
+ setTimeout(this.render_loop, Screen.#IDLE_RENDER_MS);
3018
+ return;
3019
+ }
3020
+ if (this.render_mode === "monitor" && typeof requestAnimationFrame !== "undefined") {
3021
+ requestAnimationFrame(this.render_loop);
3022
+ return;
3023
+ }
3024
+ setTimeout(this.render_loop, this.frame_period_ms());
2651
3025
  }
2652
3026
  last_width = -1;
2653
3027
  last_height = -1;
@@ -2694,11 +3068,12 @@ function rk86_snapshot(machine, version) {
2694
3068
  const snapshot = {
2695
3069
  id: "rk86",
2696
3070
  created: new Date().toISOString(),
2697
- format: "1",
3071
+ format: "2",
2698
3072
  emulator: "rk86.ru",
2699
3073
  version,
2700
3074
  start: h16(0),
2701
3075
  end: h16(65535),
3076
+ profile: exportProfile(memory.profile),
2702
3077
  boot: { keyboard: [] },
2703
3078
  cpu: cpu.export(),
2704
3079
  keyboard: keyboard.export(),
@@ -2715,6 +3090,19 @@ function rk86_snapshot_restore(snapshot, machine, keys_injector) {
2715
3090
  if (!machine)
2716
3091
  return false;
2717
3092
  const { screen, cpu, memory, keyboard } = machine;
3093
+ let profile = RK86_CLASSIC;
3094
+ if (json.profile !== undefined) {
3095
+ const parsed = normalizeProfile(json.profile);
3096
+ const errors = parsed ? validateProfile(parsed) : ["\u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u0442\u044C \u043F\u0440\u043E\u0444\u0438\u043B\u044C"];
3097
+ if (parsed && errors.length === 0)
3098
+ profile = parsed;
3099
+ else {
3100
+ machine.log?.(`\u043F\u0440\u043E\u0444\u0438\u043B\u044C \u0432 \u0441\u043D\u0430\u043F\u0448\u043E\u0442\u0435 \u043F\u0440\u043E\u0438\u0433\u043D\u043E\u0440\u0438\u0440\u043E\u0432\u0430\u043D: ${errors.join("; ")}`);
3101
+ profile = memory.profile;
3102
+ }
3103
+ }
3104
+ if (!profilesEqual(profile, memory.profile))
3105
+ memory.set_profile(profile);
2718
3106
  cpu.import(json.cpu);
2719
3107
  keyboard.import(json.keyboard);
2720
3108
  screen.import(json.screen);
@@ -2831,7 +3219,7 @@ class Tape {
2831
3219
  }
2832
3220
 
2833
3221
  // src/lib/terminal/rk86_terminal.ts
2834
- var UPLOAD_SERVER = "https://rk86.ea.deno.net";
3222
+ var UPLOAD_SERVER = "https://rk86.vercel.app";
2835
3223
  var charMap = {
2836
3224
  0: " ",
2837
3225
  1: "\u2598",
@@ -3226,11 +3614,11 @@ function setupKeyboard(keyboard) {
3226
3614
  }
3227
3615
  if (data.length === 1 && data >= "\x01" && data <= "\x1A" && data !== "\b" && data !== "\t" && data !== `
3228
3616
  ` && data !== "\r") {
3229
- const code2 = `Key${String.fromCharCode(data.charCodeAt(0) + 64)}`;
3617
+ const code = `Key${String.fromCharCode(data.charCodeAt(0) + 64)}`;
3230
3618
  keyboard.onkeydown("ControlLeft");
3231
- keyboard.onkeydown(code2);
3619
+ keyboard.onkeydown(code);
3232
3620
  setTimeout(() => {
3233
- keyboard.onkeyup(code2);
3621
+ keyboard.onkeyup(code);
3234
3622
  keyboard.onkeyup("ControlLeft");
3235
3623
  }, 50);
3236
3624
  return;
@@ -3396,8 +3784,8 @@ async function main() {
3396
3784
  const colorMode = COLOR_MODES[colorIdx];
3397
3785
  let inputSeq = arg(args, "--input");
3398
3786
  if (goViaMonitor !== undefined) {
3399
- const hex2 = goViaMonitor.toString(16).toUpperCase();
3400
- const keys = [...hex2].map((c) => c >= "0" && c <= "9" ? `Digit${c}` : `Key${c}`);
3787
+ const hex = goViaMonitor.toString(16).toUpperCase();
3788
+ const keys = [...hex].map((c) => c >= "0" && c <= "9" ? `Digit${c}` : `Key${c}`);
3401
3789
  const gSeq = ["KeyG", ...keys, "Enter"].join(",");
3402
3790
  inputSeq = inputSeq ? `${inputSeq},${gSeq}` : gSeq;
3403
3791
  }
@@ -3408,7 +3796,7 @@ async function main() {
3408
3796
  font: rk86_font_image(),
3409
3797
  keyboard,
3410
3798
  io,
3411
- log: (...args2) => console.log(...args2)
3799
+ log: (...args) => console.log(...args)
3412
3800
  };
3413
3801
  const machine = machineBuilder;
3414
3802
  machine.ui = new TerminalUI;
@@ -3439,7 +3827,7 @@ async function main() {
3439
3827
  for (const section of sections) {
3440
3828
  const data = section.data;
3441
3829
  for (let i = 0;i < data.length; i++) {
3442
- machine.memory.write(section.start + i, data[i]);
3830
+ machine.memory.write_raw(section.start + i, data[i]);
3443
3831
  }
3444
3832
  const name = section.name ? ` [${section.name}]` : "";
3445
3833
  lines.push(`${hex16(section.start)}-${hex16(section.end)}${name} (${data.length} \u0431\u0430\u0439\u0442)`);