using System.Text.RegularExpressions; 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 SortedDictionary _program = new(); private readonly Dictionary _variables = new(); private List _lines = new(); private int _programCounter; private bool _running; private bool _waitingForInput; private char _inputVariable; private bool _skipIncrement; private readonly Stack _callStack = new(); public InputInterpreter(MemoryModel mem, ConsoleHelper consoleHelper, DiskManager diskManager) { this.mem = mem; this.consoleHelper = consoleHelper; this.diskManager = diskManager; } public bool IsRunning => _running; public bool IsWaitingForInput => _waitingForInput; public void SubmitInput(string line) { if (!_waitingForInput) return; if (int.TryParse(line.Trim(), out int val)) { _variables[_inputVariable] = val; _waitingForInput = false; _programCounter++; } else { consoleHelper.WriteText("?"); consoleHelper.NewLine(); } } public void Stop() { _running = false; consoleHelper.NewLine(); consoleHelper.WriteText("BREAK"); consoleHelper.NewLine(); } public void Tick() { if (!_running || _waitingForInput) return; if (_programCounter >= _lines.Count) { _running = false; return; } int lineNr = _lines[_programCounter]; int? gotoTarget = null; _skipIncrement = false; ExecuteStatement(_program[lineNr], ref gotoTarget); if (_waitingForInput || _skipIncrement) return; if (gotoTarget.HasValue) { int idx = _lines.IndexOf(gotoTarget.Value); if (idx == -1) { consoleHelper.WriteText($"?UNDEF'D LINE {gotoTarget.Value}"); consoleHelper.NewLine(); _running = false; } else { _programCounter = idx; } } else { _programCounter++; } } 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); else _program[lineNumber] = statement; } else { Execute(input); } } // Direktmodus: RUN, LIST, DIR und alle Statements private void Execute(string input) { Console.WriteLine("input: " + input.ToLowerInvariant()); var cmd = input.ToLowerInvariant(); if (cmd == "run") { _lines = _program.Keys.ToList(); _programCounter = 0; _callStack.Clear(); _running = true; return; } if (cmd == "new") { _program.Clear(); _lines.Clear(); _callStack.Clear(); _running = false; return; } if (cmd == "list") { if (_program.Count == 0) { consoleHelper.WriteText("(empty)"); consoleHelper.NewLine(); } else { 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 == "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; ExecuteStatement(input, ref unused); } // Ausführung eines einzelnen Statements private void ExecuteStatement(string input, ref int? gotoTarget) { var cmd = input.ToLowerInvariant(); if (cmd.StartsWith("print ") || cmd == "print") { ExecutePrint(input.Substring("print".Length).Trim()); return; } if (cmd == "end") { _running = false; return; } if (cmd.StartsWith("if ")) { ExecuteIf(input.Substring("if ".Length).Trim(), ref gotoTarget); return; } if (cmd.StartsWith("input ")) { string arg = input.Substring("input ".Length).Trim(); if (arg.Length != 1 || !char.IsUpper(arg[0])) { SyntaxError(); return; } _inputVariable = arg[0]; _waitingForInput = true; consoleHelper.WriteText("?"); consoleHelper.NewLine(); return; } if (cmd.StartsWith("let ")) { ExecuteLet(input.Substring("let ".Length).Trim()); return; } if (cmd.StartsWith("rem")) return; if (cmd.StartsWith("poke ")) { ExecutePoke(input.Substring("poke ".Length).Trim()); return; } if (cmd.StartsWith("pokex ")) { ExecutePokeX(input.Substring("pokex ".Length).Trim()); return; } if (cmd.StartsWith("gosub ")) { string arg = cmd.Substring("gosub ".Length).Trim(); if (!int.TryParse(arg, out int target)) { SyntaxError(); return; } int idx = _lines.IndexOf(target); if (idx == -1) { consoleHelper.WriteText($"?UNDEF'D LINE {target}"); consoleHelper.NewLine(); _running = false; return; } _callStack.Push(_programCounter); gotoTarget = target; return; } if (cmd == "return") { if (_callStack.Count == 0) { consoleHelper.WriteText("?RETURN WITHOUT GOSUB"); consoleHelper.NewLine(); _running = false; return; } _programCounter = _callStack.Pop() + 1; _skipIncrement = true; return; } if (cmd.StartsWith("goto ")) { string arg = cmd.Substring("goto ".Length).Trim(); if (int.TryParse(arg, out int target)) gotoTarget = target; else SyntaxError(); return; } SyntaxError(); } private void ExecuteIf(string args, ref int? gotoTarget) { int thenIdx = args.ToUpperInvariant().IndexOf(" THEN "); if (thenIdx == -1) { SyntaxError(); return; } string condition = args.Substring(0, thenIdx).Trim(); string stmt = args.Substring(thenIdx + " THEN ".Length).Trim(); if (!TryEvaluateCondition(condition, out bool result)) { SyntaxError(); return; } if (result) ExecuteStatement(stmt, ref gotoTarget); } private static readonly string[] ComparisonOps = { "<=", ">=", "<>", "<", ">", "=" }; private static readonly Random Rng = new(); private bool TryEvaluateCondition(string condition, out bool result) { result = false; foreach (var op in ComparisonOps) { int idx = condition.IndexOf(op); if (idx == -1) continue; string leftStr = condition.Substring(0, idx).Trim(); string rightStr = condition.Substring(idx + op.Length).Trim(); if (!TryEvaluate(leftStr, out int left)) return false; if (!TryEvaluate(rightStr, out int right)) return false; result = op switch { "=" => left == right, "<" => left < right, ">" => left > right, "<=" => left <= right, ">=" => left >= right, "<>" => left != right, _ => false }; return true; } return false; } private void ExecuteLet(string args) { if (args.Length < 1 || !char.IsUpper(args[0])) { SyntaxError(); return; } char varName = args[0]; var rest = args.Substring(1).TrimStart(); if (!rest.StartsWith("=")) { SyntaxError(); return; } string exprStr = rest.Substring(1).Trim(); if (!TryEvaluate(exprStr, out int value)) { SyntaxError(); return; } _variables[varName] = value; } private bool TryEvaluate(string expr, out int result) { try { int pos = 0; result = ParseExpr(expr, ref pos); SkipSpaces(expr, ref pos); return pos == expr.Length; } catch (DivideByZeroException) { consoleHelper.WriteText("?DIVISION BY ZERO"); consoleHelper.NewLine(); _running = false; result = 0; return true; // Fehlermeldung bereits ausgegeben, kein ?SYNTAX ERROR } catch { result = 0; return false; } } private int ParseExpr(string s, ref int pos) { int left = ParseTerm(s, ref pos); while (true) { SkipSpaces(s, ref pos); if (pos < s.Length && s[pos] == '+') { pos++; left += ParseTerm(s, ref pos); } else if (pos < s.Length && s[pos] == '-') { pos++; left -= ParseTerm(s, ref pos); } else break; } return left; } private int ParseTerm(string s, ref int pos) { int left = ParseFactor(s, ref pos); while (true) { SkipSpaces(s, ref pos); if (pos < s.Length && s[pos] == '*') { pos++; left *= ParseFactor(s, ref pos); } else if (pos < s.Length && s[pos] == '/') { pos++; int divisor = ParseFactor(s, ref pos); if (divisor == 0) throw new DivideByZeroException(); left /= divisor; } else if (pos + 3 <= s.Length && s.Substring(pos, 3).ToUpperInvariant() == "MOD" && (pos + 3 >= s.Length || !char.IsLetterOrDigit(s[pos + 3]))) { pos += 3; int divisor = ParseFactor(s, ref pos); if (divisor == 0) throw new DivideByZeroException(); left %= divisor; } else break; } return left; } private int ParseFactor(string s, ref int pos) { SkipSpaces(s, ref pos); if (pos >= s.Length) throw new InvalidOperationException(); if (s[pos] == '(') { pos++; int val = ParseExpr(s, ref pos); SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); pos++; return val; } if (s[pos] == '-') { pos++; return -ParseFactor(s, ref pos); } if (pos + 3 <= s.Length && s.Substring(pos, 3).ToUpperInvariant() == "RND") { pos += 3; SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException(); pos++; int n = ParseExpr(s, ref pos); SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); pos++; if (n <= 0) throw new InvalidOperationException(); return Rng.Next(n); } if (pos + 5 <= s.Length && s.Substring(pos, 5).ToUpperInvariant() == "PEEKX") { pos += 5; SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException(); pos++; int bank = ParseExpr(s, ref pos); SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != ',') throw new InvalidOperationException(); pos++; int addr = ParseExpr(s, ref pos); SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); pos++; if (bank < 0 || bank >= MemoryModel.BankCount || addr < 0 || addr >= MemoryModel.BankSize) throw new InvalidOperationException(); return mem.ReadFlat(bank * MemoryModel.BankSize + addr); } if (pos + 4 <= s.Length && s.Substring(pos, 4).ToUpperInvariant() == "PEEK") { pos += 4; SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException(); pos++; int addr = ParseExpr(s, ref pos); SkipSpaces(s, ref pos); if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); pos++; if (addr < 0 || addr > 0xFFFF) throw new InvalidOperationException(); return mem.Read((ushort)addr); } if (char.IsUpper(s[pos])) { char v = s[pos++]; if (!_variables.TryGetValue(v, out int val)) throw new InvalidOperationException(); return val; } if (s[pos] == '$') { pos++; int start = pos; while (pos < s.Length && Uri.IsHexDigit(s[pos])) pos++; if (pos == start) throw new InvalidOperationException(); return Convert.ToInt32(s.Substring(start, pos - start), 16); } if (char.IsDigit(s[pos])) { int start = pos; while (pos < s.Length && char.IsDigit(s[pos])) pos++; return int.Parse(s.Substring(start, pos - start)); } throw new InvalidOperationException(); } private static void SkipSpaces(string s, ref int pos) { while (pos < s.Length && s[pos] == ' ') pos++; } private void ExecutePoke(string args) { int comma = args.IndexOf(','); if (comma == -1) { SyntaxError(); return; } if (!TryEvaluate(args.Substring(0, comma).Trim(), out int addr)) { SyntaxError(); return; } if (!TryEvaluate(args.Substring(comma + 1).Trim(), out int value)) { SyntaxError(); return; } if (addr < 0 || addr > 0xFFFF || value < 0 || value > 255) { consoleHelper.WriteText("?RANGE ERROR"); consoleHelper.NewLine(); return; } mem.Write((ushort)addr, (byte)value); } private void ExecutePokeX(string args) { var parts = args.Split(','); if (parts.Length != 3) { SyntaxError(); return; } if (!TryEvaluate(parts[0].Trim(), out int bank)) { SyntaxError(); return; } if (!TryEvaluate(parts[1].Trim(), out int addr)) { SyntaxError(); return; } if (!TryEvaluate(parts[2].Trim(), out int value)) { SyntaxError(); return; } if (bank < 0 || bank >= MemoryModel.BankCount || addr < 0 || addr >= MemoryModel.BankSize || value < 0 || value > 255) { consoleHelper.WriteText("?RANGE ERROR"); consoleHelper.NewLine(); return; } mem.WriteFlat(bank * MemoryModel.BankSize + addr, (byte)value); } 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; } var path = Path.Combine(diskManager.MountPath, name); File.WriteAllLines(path, _program.Select(kv => $"{kv.Key} {kv.Value}")); } private void ExecuteLoad(string args) { string? name = ParseFilename(args); if (name == null) { SyntaxError(); return; } _program.Clear(); _lines.Clear(); _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); } private void SyntaxError() { consoleHelper.WriteText("?SYNTAX ERROR"); consoleHelper.NewLine(); } private void ExecutePrint(string args) { if (args.StartsWith("\"")) { int last = args.LastIndexOf('"'); if (last == 0) { SyntaxError(); return; } consoleHelper.WriteText(args.Substring(1, last - 1)); consoleHelper.NewLine(); return; } if (args.Length == 1 && char.IsUpper(args[0])) { if (!_variables.TryGetValue(args[0], out int val)) { SyntaxError(); return; } consoleHelper.WriteText(val.ToString()); consoleHelper.NewLine(); return; } SyntaxError(); } }