micronona/InputInterpreter.cs
Hans-Jörg Meyer e0078538c3 Keyboard-Layout-Detection, SN76489-Sound, Text-Editor
- KeyboardLayoutDetector (KMAP-Befehl und --detect-keyboard-CLI)
  inkl. loadkeys-Integration und Persistenz im .micronona-Marker
- SN76489 PSG mit SDL-Audio-Anbindung
- Voll-Bildschirm-Texteditor (edit <file>) mit Undo, Cut/Paste,
  horizontalem Scrollen und Speicherbestätigung
- DiskManager-Erweiterungen: FindMicrononaMount, SaveKeyboardLayout,
  Dir-Listing
- ^-Glyph für die Editor-Statuszeile

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-13 22:09:57 +02:00

1524 lines
53 KiB
C#

using System.Diagnostics;
using System.Text.RegularExpressions;
// ---------------------------------------------------------------------------
// Expression bytecode
// ---------------------------------------------------------------------------
internal enum Op
{
PushConst, PushVar,
Add, Sub, Mul, Div, Mod, Negate,
CallRnd, CallPeek, CallPeekX, CallGetPixel,
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,
Cls, Locate, Color, Mode, SetChar, Inkey, Vsync,
Clear, PutPixel, For, Next
}
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 / SETCHAR)
public CompiledExpr? E3; // quaternary expression (SETCHAR)
public CompiledExpr? E4; // quinary expression (SETCHAR)
public string? PrintLiteral; // PRINT "text" — pre-extracted, no quotes
public bool SuppressNewLine; // PRINT "..."; — trailing semicolon
}
// ---------------------------------------------------------------------------
// 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 TextEditor _editor;
private readonly SortedDictionary<int, string> _program = new();
private readonly Dictionary<int, TokenizedLine> _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<int> _callStack = new();
private readonly Stack<(char var, int to, int step, int bodyPc)> _forStack = new();
private Thread? _thread;
private CancellationTokenSource _cts = new();
private readonly ManualResetEventSlim _runSignal = new(false);
private readonly SemaphoreSlim _inputSignal = new(0, 1);
// KMAP state — feeding the keyboard-layout detector from the main SDL loop.
private volatile bool _kmapActive;
private volatile bool _waitingForKmapKey;
private int? _kmapKeycode;
private char _kmapDisplayChar;
private readonly SemaphoreSlim _kmapSignal = 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;
_editor = new TextEditor(consoleHelper);
}
public bool IsRunning => _running;
public bool IsWaitingForInput => _waitingForInput;
public bool IsKmapActive => _kmapActive;
public bool IsWaitingForKmapKey => _waitingForKmapKey;
public bool IsEditorActive => _editor.IsActive;
public void EditorChar(char c) => _editor.OnChar(c);
public void EditorAction(EditorAction a) => _editor.OnAction(a);
// -----------------------------------------------------------------------
// 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 { }
try { _kmapSignal.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;
_forStack.Clear();
mem.Write(MemoryModel.IoBase + MemoryModel.REG_MODE, 0);
if (!wasRunning)
consoleHelper.Cls();
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;
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();
_forStack.Clear();
_running = true;
_runSignal.Set();
return;
}
if (cmd == "new")
{
_program.Clear(); _tokenized.Clear();
_lines = [];
_callStack.Clear();
_forStack.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.StartsWith("edit ") || cmd.StartsWith("edit\""))
{ ExecuteEditor(input.Substring("edit".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;
}
if (cmd == "kmap") { StartKmap(); return; }
int? unused = null;
ExecuteTokenized(Tokenize(input), ref unused);
}
// -----------------------------------------------------------------------
// KMAP — keyboard-layout detection inside Micronona.
// The actual work runs on a dedicated thread because the main SDL loop
// (which drives key delivery) must keep ticking.
// -----------------------------------------------------------------------
public void SubmitKmapKey(int? linuxKeycode, char displayChar = '\0')
{
if (!_waitingForKmapKey) return;
_kmapKeycode = linuxKeycode;
_kmapDisplayChar = displayChar;
_waitingForKmapKey = false;
try { _kmapSignal.Release(); } catch { }
}
private void StartKmap()
{
if (_kmapActive)
{
consoleHelper.WriteText("KMAP ALREADY RUNNING");
consoleHelper.NewLine();
return;
}
_kmapActive = true;
new Thread(RunKmap) { IsBackground = true, Name = "Kmap" }.Start();
}
private void RunKmap()
{
try
{
string? layout = KeyboardLayoutDetector.Detect(
"/usr/share/keymaps",
msg =>
{
consoleHelper.WriteText(msg);
consoleHelper.NewLine();
},
prompt =>
{
consoleHelper.WriteText(prompt + ": ");
_kmapKeycode = null;
_kmapDisplayChar = '\0';
_waitingForKmapKey = true;
try { _kmapSignal.Wait(_cts.Token); }
catch (OperationCanceledException)
{
_waitingForKmapKey = false;
return null;
}
if (_kmapDisplayChar != '\0')
consoleHelper.WriteText(_kmapDisplayChar.ToString());
consoleHelper.NewLine();
return _kmapKeycode;
});
if (layout == null)
{
consoleHelper.WriteText("KMAP CANCELLED");
consoleHelper.NewLine();
return;
}
if (diskManager.MountPath != null)
{
DiskManager.SaveKeyboardLayout(diskManager.MountPath, layout);
consoleHelper.WriteText($"SAVED: {layout}");
}
else
{
consoleHelper.WriteText($"DETECTED: {layout} (NO DISK)");
}
consoleHelper.NewLine();
KeyboardLayoutDetector.ApplyLoadkeys(layout);
}
finally
{
_waitingForKmapKey = false;
_kmapActive = false;
}
}
// -----------------------------------------------------------------------
// 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.EndsWith(";")) { t.SuppressNewLine = true; a = a.Substring(0, a.Length - 1).TrimEnd(); }
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;
}
if (lo == "cls") { t.Kw = Keyword.Cls; return t; }
if (lo.StartsWith("locate "))
{
t.Kw = Keyword.Locate;
var args = s.Substring(7).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("color "))
{
t.Kw = Keyword.Color;
var args = s.Substring(6).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("mode "))
{
t.Kw = Keyword.Mode;
try { t.E0 = CompileExpr(s.Substring(5).Trim()); }
catch { t.Kw = Keyword.Unknown; }
return t;
}
if (lo.StartsWith("setchar "))
{
t.Kw = Keyword.SetChar;
var args = s.Substring(8).Trim();
var parts = new string[5];
int start = 0;
for (int i = 0; i < 4; i++)
{
int c = args.IndexOf(',', start);
if (c < 0) { t.Kw = Keyword.Unknown; return t; }
parts[i] = args.Substring(start, c - start).Trim();
start = c + 1;
}
parts[4] = args.Substring(start).Trim();
try
{
t.E0 = CompileExpr(parts[0]);
t.E1 = CompileExpr(parts[1]);
t.E2 = CompileExpr(parts[2]);
t.E3 = CompileExpr(parts[3]);
t.E4 = CompileExpr(parts[4]);
}
catch { t.Kw = Keyword.Unknown; }
return t;
}
if (lo == "vsync") { t.Kw = Keyword.Vsync; return t; }
if (lo.StartsWith("clear "))
{
t.Kw = Keyword.Clear;
try { t.E0 = CompileExpr(s.Substring(6).Trim()); }
catch { t.Kw = Keyword.Unknown; }
return t;
}
if (lo.StartsWith("putpixel "))
{
t.Kw = Keyword.PutPixel;
var args = s.Substring(9).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("for "))
{
var args = s.Substring(4).Trim();
if (args.Length < 1 || !char.IsUpper(args[0])) { t.Kw = Keyword.Unknown; return t; }
t.Kw = Keyword.For;
t.Var = args[0];
var rest = args.Substring(1).TrimStart();
if (!rest.StartsWith("=")) { t.Kw = Keyword.Unknown; return t; }
rest = rest.Substring(1).Trim();
int toIdx = FindWord(rest, "TO");
if (toIdx < 0) { t.Kw = Keyword.Unknown; return t; }
string fromStr = rest.Substring(0, toIdx).Trim();
rest = rest.Substring(toIdx + 2).Trim();
int stepIdx = FindWord(rest, "STEP");
string toStr = stepIdx >= 0 ? rest.Substring(0, stepIdx).Trim() : rest.Trim();
string? stepStr = stepIdx >= 0 ? rest.Substring(stepIdx + 4).Trim() : null;
try
{
t.E0 = CompileExpr(fromStr);
t.E1 = CompileExpr(toStr);
if (stepStr != null) t.E2 = CompileExpr(stepStr);
}
catch { t.Kw = Keyword.Unknown; }
return t;
}
if (lo == "next" || lo.StartsWith("next "))
{
t.Kw = Keyword.Next;
if (lo.Length > 5)
{
var arg = s.Substring(5).Trim();
if (arg.Length == 1 && char.IsUpper(arg[0])) t.Var = arg[0];
else { t.Kw = Keyword.Unknown; return t; }
}
// bare NEXT: t.Var bleibt '\0' → passt auf obersten Frame
return t;
}
if (lo.StartsWith("inkey ") || lo == "inkey")
{
t.Kw = Keyword.Inkey;
var arg = s.Length > 6 ? s.Substring(6).Trim() : s.Substring(5).Trim();
if (arg.Length == 1 && char.IsUpper(arg[0])) t.Var = arg[0];
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>();
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>();
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<int> 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<int> 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<int> 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;
}
// GETPIXEL(x, y)
if (pos + 8 <= s.Length
&& (s[pos] | 0x20) == 'g'
&& (s[pos+1] | 0x20) == 'e'
&& (s[pos+2] | 0x20) == 't'
&& (s[pos+3] | 0x20) == 'p'
&& (s[pos+4] | 0x20) == 'i'
&& (s[pos+5] | 0x20) == 'x'
&& (s[pos+6] | 0x20) == 'e'
&& (s[pos+7] | 0x20) == 'l')
{
pos += 8;
SkipSpaces(s, ref pos);
if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException();
pos++;
CompileExprInto(s, ref pos, code); // x
SkipSpaces(s, ref pos);
if (pos >= s.Length || s[pos] != ',') throw new InvalidOperationException();
pos++;
CompileExprInto(s, ref pos, code); // y
SkipSpaces(s, ref pos);
if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException();
pos++;
code.Add((int)Op.CallGetPixel);
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<int> 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.CallGetPixel:
{
int y = stack[--sp];
int x = stack[--sp];
int offset = y * 320 + x;
stack[sp++] = offset < 57600 ? mem.ReadFlat(offset) : 0;
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);
if (!t.SuppressNewLine) consoleHelper.NewLine();
}
else if (t.E0 != null)
{
try { consoleHelper.WriteText(EvalExpr(t.E0).ToString()); }
catch { SyntaxError(); break; }
if (_running && !t.SuppressNewLine) consoleHelper.NewLine();
}
break;
case Keyword.End:
_running = false;
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;
case Keyword.Cls:
consoleHelper.Cls();
break;
case Keyword.Locate:
try
{
int x = EvalExpr(t.E0!); if (!_running) break;
int y = EvalExpr(t.E1!); if (!_running) break;
if (x < 0 || x >= MemoryModel.TextCols || y < 0 || y >= MemoryModel.TextRows)
{ consoleHelper.WriteText("?RANGE ERROR"); consoleHelper.NewLine(); break; }
consoleHelper.SetCursor((byte)x, (byte)y);
}
catch { SyntaxError(); }
break;
case Keyword.Color:
try
{
int fg = EvalExpr(t.E0!); if (!_running) break;
int bg = EvalExpr(t.E1!); if (!_running) break;
if (fg < 0 || fg > 255 || bg < 0 || bg > 255)
{ consoleHelper.WriteText("?RANGE ERROR"); consoleHelper.NewLine(); break; }
consoleHelper.CurrentFg = (byte)fg;
consoleHelper.CurrentBg = (byte)bg;
}
catch { SyntaxError(); }
break;
case Keyword.Mode:
try
{
int mode = EvalExpr(t.E0!); if (!_running) break;
mem.Write(MemoryModel.IoBase + MemoryModel.REG_MODE, (byte)mode);
}
catch { SyntaxError(); }
break;
case Keyword.SetChar:
try
{
int x = EvalExpr(t.E0!); if (!_running) break;
int y = EvalExpr(t.E1!); if (!_running) break;
int asc = EvalExpr(t.E2!); if (!_running) break;
int fg = EvalExpr(t.E3!); if (!_running) break;
int bg = EvalExpr(t.E4!); if (!_running) break;
if (x < 0 || x >= MemoryModel.TextCols ||
y < 0 || y >= MemoryModel.TextRows ||
asc < 0 || asc > 255 || fg < 0 || fg > 255 || bg < 0 || bg > 255)
{ consoleHelper.WriteText("?RANGE ERROR"); consoleHelper.NewLine(); break; }
consoleHelper.SetChar(x, y, (byte)asc, (byte)fg, (byte)bg);
}
catch { SyntaxError(); }
break;
case Keyword.Inkey:
{
byte key = mem.Read(MemoryModel.IoBase + MemoryModel.REG_KEY_CHAR);
_variables[t.Var - 'A'] = key;
break;
}
case Keyword.Vsync:
mem.Write(MemoryModel.IoBase + MemoryModel.REG_VSYNC, 1);
break;
case Keyword.Clear:
try
{
int color = EvalExpr(t.E0!); if (!_running) break;
mem.FillFlat(0, 57600, (byte)(color & 0xFF));
}
catch { SyntaxError(); }
break;
case Keyword.PutPixel:
try
{
int x = EvalExpr(t.E0!); if (!_running) break;
int y = EvalExpr(t.E1!); if (!_running) break;
int color = EvalExpr(t.E2!); if (!_running) break;
int offset = y * 320 + x;
if (offset < 57600)
mem.WriteFlat(offset, (byte)(color & 0xFF));
}
catch { SyntaxError(); }
break;
case Keyword.For:
{
int from = EvalExpr(t.E0!); if (!_running) break;
int to = EvalExpr(t.E1!); if (!_running) break;
int step = t.E2 != null ? EvalExpr(t.E2) : 1; if (!_running) break;
_variables[t.Var - 'A'] = from;
bool done = step > 0 ? from > to : from < to;
if (done)
{
_programCounter = FindNextPc(t.Var, _programCounter);
_skipIncrement = true;
}
else
{
_forStack.Push((t.Var, to, step, _programCounter + 1));
}
break;
}
case Keyword.Next:
{
if (_forStack.Count == 0)
{
consoleHelper.WriteText("?NEXT WITHOUT FOR"); consoleHelper.NewLine();
_running = false; break;
}
var (fVar, to, step, bodyPc) = _forStack.Peek();
if (t.Var != '\0' && t.Var != fVar)
{
consoleHelper.WriteText("?NEXT WITHOUT FOR"); consoleHelper.NewLine();
_running = false; break;
}
_variables[fVar - 'A'] += step;
bool cont = step > 0 ? _variables[fVar - 'A'] <= to : _variables[fVar - 'A'] >= to;
if (cont)
{
_programCounter = bodyPc;
_skipIncrement = true;
}
else
{
_forStack.Pop();
}
break;
}
default:
SyntaxError();
break;
}
}
// -----------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------
private static int FindWord(string s, string word)
{
string up = s.ToUpperInvariant();
int i = 0;
while (i + word.Length <= up.Length)
{
int found = up.IndexOf(word, i);
if (found < 0) return -1;
bool leftOk = found == 0 || !char.IsLetterOrDigit(up[found - 1]);
bool rightOk = found + word.Length >= up.Length || !char.IsLetterOrDigit(up[found + word.Length]);
if (leftOk && rightOk) return found;
i = found + 1;
}
return -1;
}
private int FindNextPc(char var, int fromPc)
{
int depth = 0;
for (int i = fromPc + 1; i < _lines.Length; i++)
{
var tok = _tokenized[_lines[i]];
if (tok.Kw == Keyword.For && tok.Var == var) depth++;
if (tok.Kw == Keyword.Next && (tok.Var == '\0' || tok.Var == var))
{
if (depth == 0) return i + 1;
if (tok.Var == var) depth--;
}
}
return _lines.Length;
}
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 ExecuteEditor(string args)
{
string? name = ParseFilename(args);
if (name == null) { SyntaxError(); return; }
if (diskManager.MountPath == null)
{ consoleHelper.WriteText("?NO DISK"); consoleHelper.NewLine(); return; }
_editor.Run(Path.Combine(diskManager.MountPath, name));
}
private void ExecuteExec(string args)
{
string name;
if (args.StartsWith("\""))
{
int close = args.IndexOf('"', 1);
if (close < 0) { SyntaxError(); return; }
name = args.Substring(1, close - 1).ToUpperInvariant();
}
else if (args.Length > 0 && !char.IsDigit(args[0]) && args[0] != '$')
{
name = args.Trim().ToUpperInvariant();
}
else
{
// Bare address: EXEC $1000
int addr;
try { addr = EvalExpr(CompileExpr(args)); }
catch { SyntaxError(); return; }
if (_running) cpu.Run((ushort)addr);
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);
if (ExecDecb(data, out ushort entry))
cpu.Run(entry);
}
private bool ExecDecb(byte[] data, out ushort entry)
{
entry = 0;
int pos = 0;
ushort firstLoadAddr = 0;
bool hasFirstAddr = false;
while (pos < data.Length)
{
byte type = data[pos++];
if (type == 0x01) // data block (Micronona binary marker)
{
if (pos + 4 > data.Length) break;
int len = (data[pos] << 8) | data[pos + 1]; pos += 2;
ushort addr = (ushort)((data[pos] << 8) | data[pos + 1]); pos += 2;
if (!hasFirstAddr) { firstLoadAddr = addr; hasFirstAddr = true; }
for (int i = 0; i < len && pos < data.Length; i++)
mem.Write((ushort)(addr + i), data[pos++]);
}
else if (type == 0xFF) // end block — execution address
{
if (pos + 4 > data.Length) break;
pos += 2; // skip length (always 0x0000)
ushort execAddr = (ushort)((data[pos] << 8) | data[pos + 1]);
// Fall back to first block's load address if no END addr in source.
entry = execAddr != 0 ? execAddr : firstLoadAddr;
return true;
}
else break;
}
consoleHelper.WriteText("?BAD FORMAT"); consoleHelper.NewLine();
return false;
}
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=decb");
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[] decb = File.ReadAllBytes(tmpFile);
decb[0] = 0x01;
File.WriteAllBytes(outputPath, decb);
}
finally { try { File.Delete(tmpFile); } catch { } }
}
private void SyntaxError()
{
consoleHelper.WriteText("?SYNTAX ERROR");
consoleHelper.NewLine();
}
}