using System.Diagnostics; using System.Text.RegularExpressions; // --------------------------------------------------------------------------- // Expression bytecode // --------------------------------------------------------------------------- internal enum Op { PushConst, PushVar, Add, Sub, Mul, Div, Mod, Negate, CallRnd, CallPeek, CallPeekX, CmpEq, CmpLt, CmpGt, CmpLe, CmpGe, CmpNe } internal sealed class CompiledExpr { public readonly int[] Code; public readonly string Source; public CompiledExpr(int[] code, string source) { Code = code; Source = source; } } // --------------------------------------------------------------------------- // Token types for pre-compiled BASIC lines // --------------------------------------------------------------------------- internal enum Keyword { Unknown, Print, Let, Goto, Gosub, Return, If, Input, Poke, PokeX, Rem, End } internal sealed class TokenizedLine { public Keyword Kw; public char Var; public int LineTarget; public TokenizedLine? ThenLine; public CompiledExpr? E0; // primary expression public CompiledExpr? E1; // secondary expression public CompiledExpr? E2; // tertiary expression (POKEX) public string? PrintLiteral; // PRINT "text" — pre-extracted, no quotes } // --------------------------------------------------------------------------- // Interpreter // --------------------------------------------------------------------------- internal class InputInterpreter { private static readonly Regex LineNumberPattern = new(@"^\s*(\d+)\s+(.*)$"); private readonly MemoryModel mem; private readonly ConsoleHelper consoleHelper; private readonly DiskManager diskManager; private readonly Cpu6809 cpu; private readonly SortedDictionary _program = new(); private readonly Dictionary _tokenized = new(); private readonly int[] _variables = new int[26]; // A=0 … Z=25 private int[] _lines = []; private int _programCounter; private volatile bool _running; private volatile bool _waitingForInput; private char _inputVariable; private bool _skipIncrement; private readonly Stack _callStack = new(); private Thread? _thread; private CancellationTokenSource _cts = new(); private readonly ManualResetEventSlim _runSignal = new(false); private readonly SemaphoreSlim _inputSignal = new(0, 1); // Perf measurement private long _perfExecute; private long _perfGoto; private long _perfCount; private const long PerfInterval = 100_000; // XorShift32 RNG private uint _rng = (uint)Environment.TickCount; private int FastRnd(int n) { _rng ^= _rng << 13; _rng ^= _rng >> 17; _rng ^= _rng << 5; return (int)((_rng & 0x7FFFFFFFu) % (uint)n); } public InputInterpreter(MemoryModel mem, ConsoleHelper consoleHelper, DiskManager diskManager, Cpu6809 cpu) { this.mem = mem; this.consoleHelper = consoleHelper; this.diskManager = diskManager; this.cpu = cpu; } public bool IsRunning => _running; public bool IsWaitingForInput => _waitingForInput; // ----------------------------------------------------------------------- // Thread management // ----------------------------------------------------------------------- public void StartThread() { _thread = new Thread(RunLoop) { IsBackground = true, Name = "BasicInterpreter" }; _thread.Start(); } public void StopThread() { _running = false; _cts.Cancel(); try { _runSignal.Set(); } catch { } try { _inputSignal.Release(); } catch { } _thread?.Join(); } private void RunLoop() { try { while (true) { _runSignal.Wait(_cts.Token); _runSignal.Reset(); while (_running && !_cts.IsCancellationRequested) { if (_waitingForInput) { _inputSignal.Wait(_cts.Token); continue; } Tick(); } } } catch (OperationCanceledException) { } } // ----------------------------------------------------------------------- // Input handling // ----------------------------------------------------------------------- public void SubmitInput(string line) { if (!_waitingForInput) return; if (int.TryParse(line.Trim(), out int val)) { _variables[_inputVariable - 'A'] = val; _waitingForInput = false; _programCounter++; _inputSignal.Release(); } else { consoleHelper.WriteText("?"); consoleHelper.NewLine(); } } public void Stop() { bool wasRunning = _running; _running = false; if (!wasRunning) mem.Write(MemoryModel.IoBase + MemoryModel.REG_MODE, 0); if (_waitingForInput) { _waitingForInput = false; try { _inputSignal.Release(); } catch { } } consoleHelper.NewLine(); consoleHelper.WriteText("BREAK"); consoleHelper.NewLine(); } // ----------------------------------------------------------------------- // Execution tick // ----------------------------------------------------------------------- private void Tick() { if (!_running) return; if (_programCounter >= _lines.Length) { _running = false; mem.Write(MemoryModel.IoBase + MemoryModel.REG_MODE, 0); return; } int lineNr = _lines[_programCounter]; int? gotoTarget = null; _skipIncrement = false; long t0 = Stopwatch.GetTimestamp(); ExecuteTokenized(_tokenized[lineNr], ref gotoTarget); long t1 = Stopwatch.GetTimestamp(); if (_waitingForInput || _skipIncrement) return; if (gotoTarget.HasValue) { int idx = Array.BinarySearch(_lines, gotoTarget.Value); if (idx < 0) { consoleHelper.WriteText($"?UNDEF'D LINE {gotoTarget.Value}"); consoleHelper.NewLine(); _running = false; } else { _programCounter = idx; } } else { _programCounter++; } long t2 = Stopwatch.GetTimestamp(); _perfExecute += t1 - t0; _perfGoto += t2 - t1; _perfCount++; if (_perfCount == PerfInterval) { double f = Stopwatch.Frequency / 1e9; double exec = _perfExecute / f / PerfInterval; double gotol = _perfGoto / f / PerfInterval; double totalSec = (_perfExecute + _perfGoto) / (double)Stopwatch.Frequency; Console.WriteLine($"[PERF] exec={exec:F1}ns goto={gotol:F1}ns total={exec+gotol:F1}ns ({PerfInterval/totalSec:N0} ticks/s)"); _perfExecute = _perfGoto = _perfCount = 0; } } // ----------------------------------------------------------------------- // Direct-mode dispatcher // ----------------------------------------------------------------------- public void InterpretInput(string input) { input = input.Trim(); if (string.IsNullOrEmpty(input)) return; var match = LineNumberPattern.Match(input); if (match.Success) { int lineNumber = int.Parse(match.Groups[1].Value); string statement = match.Groups[2].Value.Trim(); if (string.IsNullOrWhiteSpace(statement)) { _program.Remove(lineNumber); _tokenized.Remove(lineNumber); } else { _program[lineNumber] = statement; _tokenized[lineNumber] = Tokenize(statement); } } else { Execute(input); } } private void Execute(string input) { var cmd = input.ToLowerInvariant(); if (cmd == "run") { _lines = _program.Keys.ToArray(); _programCounter = 0; _callStack.Clear(); _running = true; _runSignal.Set(); return; } if (cmd == "new") { _program.Clear(); _tokenized.Clear(); _lines = []; _callStack.Clear(); _running = false; consoleHelper.WriteText("OK"); consoleHelper.NewLine(); return; } if (cmd == "list") { foreach (var (lineNumber, statement) in _program) { consoleHelper.WriteText($"{lineNumber} {statement}"); consoleHelper.NewLine(); } return; } if (cmd.StartsWith("save ") || cmd.StartsWith("save\"")) { ExecuteSave(input.Substring("save".Length).Trim()); return; } if (cmd.StartsWith("load ") || cmd.StartsWith("load\"")) { ExecuteLoad(input.Substring("load".Length).Trim()); return; } if (cmd.StartsWith("exec ") || cmd.StartsWith("exec\"")) { ExecuteExec(input.Substring("exec".Length).Trim()); return; } if (cmd.StartsWith("asm ") || cmd.StartsWith("asm\"")) { ExecuteAsm(input.Substring("asm".Length).Trim()); return; } if (cmd.StartsWith("del ") || cmd.StartsWith("del\"")) { ExecuteDelFile(input.Substring("del".Length).Trim()); return; } if (cmd == "dir") { var (error, files) = diskManager.Dir(); if (error != null) { consoleHelper.WriteText($"Error: {error}"); consoleHelper.NewLine(); } else if (files is not null) foreach (var file in files) { consoleHelper.WriteText(file.Name); consoleHelper.NewLine(); } return; } int? unused = null; ExecuteTokenized(Tokenize(input), ref unused); } // ----------------------------------------------------------------------- // Tokenizer — runs once at line entry; compiles expressions to bytecode // ----------------------------------------------------------------------- private static TokenizedLine Tokenize(string raw) { var t = new TokenizedLine(); var s = raw.Trim(); if (s.Length == 0) return t; var lo = s.ToLowerInvariant(); if (lo == "end") { t.Kw = Keyword.End; return t; } if (lo == "return") { t.Kw = Keyword.Return; return t; } if (lo.StartsWith("rem")) { t.Kw = Keyword.Rem; return t; } if (lo == "print" || lo.StartsWith("print ")) { t.Kw = Keyword.Print; string a = s.Length > 5 ? s.Substring(5).Trim() : ""; if (a.StartsWith("\"")) { int last = a.LastIndexOf('"'); if (last <= 0) { t.Kw = Keyword.Unknown; return t; } t.PrintLiteral = a.Substring(1, last - 1); } else if (a.Length > 0) { try { t.E0 = CompileExpr(a); } catch { t.Kw = Keyword.Unknown; } } return t; } if (lo.StartsWith("let ")) { t.Kw = Keyword.Let; var args = s.Substring(4).Trim(); if (args.Length >= 1 && char.IsUpper(args[0])) { t.Var = args[0]; var rest = args.Substring(1).TrimStart(); if (rest.StartsWith("=")) try { t.E0 = CompileExpr(rest.Substring(1).Trim()); } catch { t.Kw = Keyword.Unknown; } else t.Kw = Keyword.Unknown; } else t.Kw = Keyword.Unknown; return t; } if (lo.StartsWith("pokex ")) { t.Kw = Keyword.PokeX; var args = s.Substring(6).Trim(); int c1 = args.IndexOf(','); if (c1 < 0) { t.Kw = Keyword.Unknown; return t; } int c2 = args.IndexOf(',', c1 + 1); if (c2 < 0) { t.Kw = Keyword.Unknown; return t; } try { t.E0 = CompileExpr(args.Substring(0, c1 ).Trim()); t.E1 = CompileExpr(args.Substring(c1 + 1, c2 - c1 - 1).Trim()); t.E2 = CompileExpr(args.Substring(c2 + 1 ).Trim()); } catch { t.Kw = Keyword.Unknown; } return t; } if (lo.StartsWith("poke ")) { t.Kw = Keyword.Poke; var args = s.Substring(5).Trim(); int comma = args.IndexOf(','); if (comma < 0) { t.Kw = Keyword.Unknown; return t; } try { t.E0 = CompileExpr(args.Substring(0, comma ).Trim()); t.E1 = CompileExpr(args.Substring(comma + 1 ).Trim()); } catch { t.Kw = Keyword.Unknown; } return t; } if (lo.StartsWith("goto ")) { t.Kw = Keyword.Goto; if (int.TryParse(lo.Substring(5).Trim(), out int target)) t.LineTarget = target; else t.Kw = Keyword.Unknown; return t; } if (lo.StartsWith("gosub ")) { t.Kw = Keyword.Gosub; if (int.TryParse(lo.Substring(6).Trim(), out int target)) t.LineTarget = target; else t.Kw = Keyword.Unknown; return t; } if (lo.StartsWith("input ")) { t.Kw = Keyword.Input; var arg = s.Substring(6).Trim(); if (arg.Length == 1 && char.IsUpper(arg[0])) t.Var = arg[0]; else t.Kw = Keyword.Unknown; return t; } if (lo.StartsWith("if ")) { t.Kw = Keyword.If; var args = s.Substring(3).Trim(); int thenIdx = args.ToUpperInvariant().IndexOf(" THEN "); if (thenIdx >= 0) { try { t.E0 = CompileCondition(args.Substring(0, thenIdx).Trim()); } catch { t.Kw = Keyword.Unknown; return t; } t.ThenLine = Tokenize(args.Substring(thenIdx + 6).Trim()); } else t.Kw = Keyword.Unknown; return t; } return t; // Unknown → SyntaxError at runtime } // ----------------------------------------------------------------------- // Expression compiler // ----------------------------------------------------------------------- private static CompiledExpr CompileExpr(string expr) { var code = new List(); int pos = 0; CompileExprInto(expr, ref pos, code); SkipSpaces(expr, ref pos); if (pos != expr.Length) throw new InvalidOperationException($"Trailing chars in: {expr}"); return new CompiledExpr(code.ToArray(), expr); } private static CompiledExpr CompileCondition(string cond) { // Two-char operators must precede their single-char prefixes in the list. string[] ops = { "<=", ">=", "<>", "<", ">", "=" }; foreach (var op in ops) { int idx = cond.IndexOf(op); if (idx < 0) continue; string left = cond.Substring(0, idx).Trim(); string right = cond.Substring(idx + op.Length).Trim(); var code = new List(); int lp = 0, rp = 0; CompileExprInto(left, ref lp, code); CompileExprInto(right, ref rp, code); code.Add((int)(op switch { "=" => Op.CmpEq, "<" => Op.CmpLt, ">" => Op.CmpGt, "<=" => Op.CmpLe, ">=" => Op.CmpGe, "<>" => Op.CmpNe, _ => Op.CmpEq })); return new CompiledExpr(code.ToArray(), cond); } throw new InvalidOperationException($"No comparison operator in: {cond}"); } private static void CompileExprInto(string s, ref int pos, List code) { CompileTermInto(s, ref pos, code); while (true) { SkipSpaces(s, ref pos); if (pos < s.Length && s[pos] == '+') { pos++; CompileTermInto(s, ref pos, code); code.Add((int)Op.Add); } else if (pos < s.Length && s[pos] == '-') { pos++; CompileTermInto(s, ref pos, code); code.Add((int)Op.Sub); } else break; } } private static void CompileTermInto(string s, ref int pos, List code) { CompileFactorInto(s, ref pos, code); while (true) { SkipSpaces(s, ref pos); if (pos < s.Length && s[pos] == '*') { pos++; CompileFactorInto(s, ref pos, code); code.Add((int)Op.Mul); } else if (pos < s.Length && s[pos] == '/') { pos++; CompileFactorInto(s, ref pos, code); code.Add((int)Op.Div); } else if (pos + 3 <= s.Length && (s[pos] | 0x20) == 'm' && (s[pos+1] | 0x20) == 'o' && (s[pos+2] | 0x20) == 'd' && (pos + 3 >= s.Length || !char.IsLetterOrDigit(s[pos+3]))) { pos += 3; CompileFactorInto(s, ref pos, code); code.Add((int)Op.Mod); } else break; } } private static void CompileFactorInto(string s, ref int pos, List code) { SkipSpaces(s, ref pos); if (pos >= s.Length) throw new InvalidOperationException(); if (s[pos] == '(') { pos++; CompileExprInto(s, ref pos, code); SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); pos++; return; } if (s[pos] == '-') { pos++; CompileFactorInto(s, ref pos, code); code.Add((int)Op.Negate); return; } // RND(n) if (pos + 3 <= s.Length && (s[pos] | 0x20) == 'r' && (s[pos+1] | 0x20) == 'n' && (s[pos+2] | 0x20) == 'd') { pos += 3; SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException(); pos++; CompileExprInto(s, ref pos, code); SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); pos++; code.Add((int)Op.CallRnd); return; } // PEEKX(bank, addr) — must precede PEEK if (pos + 5 <= s.Length && (s[pos] | 0x20) == 'p' && (s[pos+1] | 0x20) == 'e' && (s[pos+2] | 0x20) == 'e' && (s[pos+3] | 0x20) == 'k' && (s[pos+4] | 0x20) == 'x') { pos += 5; SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException(); pos++; CompileExprInto(s, ref pos, code); // bank SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != ',') throw new InvalidOperationException(); pos++; CompileExprInto(s, ref pos, code); // addr SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); pos++; code.Add((int)Op.CallPeekX); return; } // PEEK(addr) if (pos + 4 <= s.Length && (s[pos] | 0x20) == 'p' && (s[pos+1] | 0x20) == 'e' && (s[pos+2] | 0x20) == 'e' && (s[pos+3] | 0x20) == 'k') { pos += 4; SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException(); pos++; CompileExprInto(s, ref pos, code); SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); pos++; code.Add((int)Op.CallPeek); return; } // Variable (single uppercase letter) — emit 0-based index (A=0 … Z=25) if (char.IsUpper(s[pos])) { code.Add((int)Op.PushVar); code.Add(s[pos++] - 'A'); return; } // Hex literal $XX if (s[pos] == '$') { pos++; if (pos >= s.Length || !IsHexChar(s[pos])) throw new InvalidOperationException(); int val = 0; while (pos < s.Length && IsHexChar(s[pos])) val = val * 16 + HexVal(s[pos++]); code.Add((int)Op.PushConst); code.Add(val); return; } // Decimal literal if (char.IsDigit(s[pos])) { int val = 0; while (pos < s.Length && char.IsDigit(s[pos])) val = val * 10 + (s[pos++] - '0'); code.Add((int)Op.PushConst); code.Add(val); return; } throw new InvalidOperationException($"Unexpected char '{s[pos]}' in: {s}"); } // ----------------------------------------------------------------------- // Stack-based evaluator — no heap allocations, no string operations // ----------------------------------------------------------------------- private int EvalExpr(CompiledExpr expr) { Span stack = stackalloc int[32]; int sp = 0; int[] code = expr.Code; int pc = 0; while (pc < code.Length) { switch ((Op)code[pc++]) { case Op.PushConst: stack[sp++] = code[pc++]; break; case Op.PushVar: stack[sp++] = _variables[code[pc++]]; break; case Op.Add: { int b = stack[--sp]; stack[sp-1] += b; break; } case Op.Sub: { int b = stack[--sp]; stack[sp-1] -= b; break; } case Op.Mul: { int b = stack[--sp]; stack[sp-1] *= b; break; } case Op.Div: { int b = stack[--sp]; if (b == 0) { consoleHelper.WriteText("?DIVISION BY ZERO"); consoleHelper.NewLine(); _running = false; return 0; } stack[sp-1] /= b; break; } case Op.Mod: { int b = stack[--sp]; if (b == 0) { consoleHelper.WriteText("?DIVISION BY ZERO"); consoleHelper.NewLine(); _running = false; return 0; } stack[sp-1] %= b; break; } case Op.Negate: stack[sp-1] = -stack[sp-1]; break; case Op.CallRnd: stack[sp-1] = FastRnd(stack[sp-1]); break; case Op.CallPeek: stack[sp-1] = mem.Read((ushort)stack[sp-1]); break; case Op.CallPeekX: { int addr = stack[--sp]; int bank = stack[--sp]; if (bank < 0 || bank >= MemoryModel.BankCount || addr < 0 || addr >= MemoryModel.BankSize) { consoleHelper.WriteText($"?RANGE ERROR in {expr.Source}"); consoleHelper.NewLine(); _running = false; return 0; } stack[sp++] = mem.ReadFlat(bank * MemoryModel.BankSize + addr); break; } case Op.CmpEq: { int b = stack[--sp]; stack[sp-1] = stack[sp-1] == b ? 1 : 0; break; } case Op.CmpLt: { int b = stack[--sp]; stack[sp-1] = stack[sp-1] < b ? 1 : 0; break; } case Op.CmpGt: { int b = stack[--sp]; stack[sp-1] = stack[sp-1] > b ? 1 : 0; break; } case Op.CmpLe: { int b = stack[--sp]; stack[sp-1] = stack[sp-1] <= b ? 1 : 0; break; } case Op.CmpGe: { int b = stack[--sp]; stack[sp-1] = stack[sp-1] >= b ? 1 : 0; break; } case Op.CmpNe: { int b = stack[--sp]; stack[sp-1] = stack[sp-1] != b ? 1 : 0; break; } } } return sp > 0 ? stack[sp - 1] : 0; } // ----------------------------------------------------------------------- // Statement executor — switch on pre-compiled keyword, EvalExpr for exprs // ----------------------------------------------------------------------- private void ExecuteTokenized(TokenizedLine t, ref int? gotoTarget) { switch (t.Kw) { case Keyword.Print: if (t.PrintLiteral != null) { consoleHelper.WriteText(t.PrintLiteral); consoleHelper.NewLine(); } else if (t.E0 != null) { try { consoleHelper.WriteText(EvalExpr(t.E0).ToString()); } catch { SyntaxError(); break; } if (_running) consoleHelper.NewLine(); } break; case Keyword.End: _running = false; mem.Write(MemoryModel.IoBase + MemoryModel.REG_MODE, 0); break; case Keyword.Rem: break; case Keyword.Let: try { _variables[t.Var - 'A'] = EvalExpr(t.E0!); } catch { SyntaxError(); } break; case Keyword.Poke: try { int addr = EvalExpr(t.E0!); if (!_running) break; int val = EvalExpr(t.E1!); if (!_running) break; if (addr < 0 || addr > 0xFFFF || val < 0 || val > 255) { consoleHelper.WriteText("?RANGE ERROR"); consoleHelper.NewLine(); break; } mem.Write((ushort)addr, (byte)val); } catch { SyntaxError(); } break; case Keyword.PokeX: try { int bank = EvalExpr(t.E0!); if (!_running) break; int addr = EvalExpr(t.E1!); if (!_running) break; int val = EvalExpr(t.E2!); if (!_running) break; if (bank < 0 || bank >= MemoryModel.BankCount || addr < 0 || addr >= MemoryModel.BankSize || val < 0 || val > 255) { consoleHelper.WriteText("?RANGE ERROR"); consoleHelper.NewLine(); break; } mem.WriteFlat(bank * MemoryModel.BankSize + addr, (byte)val); } catch { SyntaxError(); } break; case Keyword.Goto: gotoTarget = t.LineTarget; break; case Keyword.Gosub: if (Array.BinarySearch(_lines, t.LineTarget) < 0) { consoleHelper.WriteText($"?UNDEF'D LINE {t.LineTarget}"); consoleHelper.NewLine(); _running = false; break; } _callStack.Push(_programCounter); gotoTarget = t.LineTarget; break; case Keyword.Return: if (_callStack.Count == 0) { consoleHelper.WriteText("?RETURN WITHOUT GOSUB"); consoleHelper.NewLine(); _running = false; break; } _programCounter = _callStack.Pop() + 1; _skipIncrement = true; break; case Keyword.Input: _inputVariable = t.Var; _waitingForInput = true; consoleHelper.WriteText("?"); consoleHelper.NewLine(); break; case Keyword.If: try { if (EvalExpr(t.E0!) != 0 && t.ThenLine != null) ExecuteTokenized(t.ThenLine, ref gotoTarget); } catch { SyntaxError(); } break; default: SyntaxError(); break; } } // ----------------------------------------------------------------------- // Helpers // ----------------------------------------------------------------------- private static void SkipSpaces(string s, ref int pos) { while (pos < s.Length && s[pos] == ' ') pos++; } private static bool IsHexChar(char c) => (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); private static int HexVal(char c) => c <= '9' ? c - '0' : (c | 0x20) - 'a' + 10; // ----------------------------------------------------------------------- // Disk / file commands // ----------------------------------------------------------------------- private string? ParseFilename(string args) { string name = args.Trim('"', ' ').ToUpperInvariant(); if (name.Length == 0 || name.Length > 12 || name.Contains('/') || name.Contains('\\')) return null; return name; } private void ExecuteSave(string args) { string? name = ParseFilename(args); if (name == null) { SyntaxError(); return; } if (diskManager.MountPath == null) { consoleHelper.WriteText("?NO DISK"); consoleHelper.NewLine(); return; } File.WriteAllLines(Path.Combine(diskManager.MountPath, name), _program.Select(kv => $"{kv.Key} {kv.Value}")); consoleHelper.WriteText("OK"); consoleHelper.NewLine(); } private void ExecuteLoad(string args) { string? name = ParseFilename(args); if (name == null) { SyntaxError(); return; } _program.Clear(); _tokenized.Clear(); _lines = []; _callStack.Clear(); _running = false; if (diskManager.MountPath == null) { consoleHelper.WriteText("?NO DISK"); consoleHelper.NewLine(); return; } var path = Path.Combine(diskManager.MountPath, name); if (!File.Exists(path)) { consoleHelper.WriteText("?FILE NOT FOUND"); consoleHelper.NewLine(); return; } foreach (var line in File.ReadAllLines(path)) InterpretInput(line); consoleHelper.WriteText("OK"); consoleHelper.NewLine(); } private void ExecuteDelFile(string args) { string? name = ParseFilename(args); if (name == null) { SyntaxError(); return; } if (diskManager.MountPath == null) { consoleHelper.WriteText("?NO DISK"); consoleHelper.NewLine(); return; } var path = Path.Combine(diskManager.MountPath, name); if (!File.Exists(path)) { consoleHelper.WriteText("?FILE NOT FOUND"); consoleHelper.NewLine(); return; } File.Delete(path); consoleHelper.WriteText("OK"); consoleHelper.NewLine(); } private void ExecuteExec(string args) { if (args.StartsWith("\"")) { int close = args.IndexOf('"', 1); if (close < 0) { SyntaxError(); return; } string name = args.Substring(1, close - 1).ToUpperInvariant(); string rest = args.Substring(close + 1).TrimStart(); if (!rest.StartsWith(",")) { SyntaxError(); return; } int addr; try { addr = EvalExpr(CompileExpr(rest.Substring(1).Trim())); } catch { SyntaxError(); return; } if (!_running) return; if (diskManager.MountPath == null) { consoleHelper.WriteText("?NO DISK"); consoleHelper.NewLine(); return; } var path = Path.Combine(diskManager.MountPath, name); if (!File.Exists(path)) { consoleHelper.WriteText("?FILE NOT FOUND"); consoleHelper.NewLine(); return; } byte[] data = File.ReadAllBytes(path); int start = (data.Length > 0 && data[0] == 0x01) ? 1 : 0; for (int i = start; i < data.Length; i++) mem.Write((ushort)(addr + i - start), data[i]); cpu.Run((ushort)addr); } else { int addr; try { addr = EvalExpr(CompileExpr(args)); } catch { SyntaxError(); return; } if (_running) cpu.Run((ushort)addr); } } private void ExecuteAsm(string args) { string? name = ParseFilename(args); if (name == null) { SyntaxError(); return; } if (diskManager.MountPath == null) { consoleHelper.WriteText("?NO DISK"); consoleHelper.NewLine(); return; } { var psi = new System.Diagnostics.ProcessStartInfo { FileName = "which", Arguments = "lwasm", RedirectStandardOutput = true, RedirectStandardError = true }; var p = System.Diagnostics.Process.Start(psi)!; p.WaitForExit(); if (p.ExitCode != 0) { consoleHelper.WriteText("?LWASM NOT FOUND"); consoleHelper.NewLine(); return; } } var inputPath = Path.Combine(diskManager.MountPath, name); if (!File.Exists(inputPath)) { consoleHelper.WriteText("?FILE NOT FOUND"); consoleHelper.NewLine(); return; } string baseName = Path.GetFileNameWithoutExtension(name); if (baseName.Length + 4 > 12) baseName = baseName[..(12 - 4)]; string outputName = baseName + ".BIN"; var outputPath = Path.Combine(diskManager.MountPath, outputName); string tmpFile = Path.GetTempFileName(); try { var psi = new System.Diagnostics.ProcessStartInfo { FileName = "lwasm", RedirectStandardError = true }; psi.ArgumentList.Add("--format=raw"); psi.ArgumentList.Add("-9"); psi.ArgumentList.Add("-o"); psi.ArgumentList.Add(tmpFile); psi.ArgumentList.Add(inputPath); var p = System.Diagnostics.Process.Start(psi)!; string stderr = p.StandardError.ReadToEnd(); p.WaitForExit(); if (p.ExitCode != 0) { foreach (var line in stderr.Split('\n', StringSplitOptions.RemoveEmptyEntries)) { consoleHelper.WriteText(line); consoleHelper.NewLine(); } return; } byte[] raw = File.ReadAllBytes(tmpFile); byte[] output = new byte[raw.Length + 1]; output[0] = 0x01; raw.CopyTo(output, 1); File.WriteAllBytes(outputPath, output); } finally { try { File.Delete(tmpFile); } catch { } } } private void SyntaxError() { consoleHelper.WriteText("?SYNTAX ERROR"); consoleHelper.NewLine(); } }