using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using MoonSharp.Interpreter;
using LogiBoardToolBox.Core.Onboard;
namespace LogiBoardToolBox.Core.Macros;
/// Bounded partial evaluation of deterministic Lua syntax. Host state and RNG are never sampled.
public static class LuaMacroImport
{
private const int MaximumTableEntries = 65536;
public static CompiledMacro ConvertForFirmware(string source, int triggerButton, int physicalButtonIndex,
OnboardCapabilities capabilities, CancellationToken cancellationToken = default)
{
if (!capabilities.SupportsNativeLua) throw Unsupported("设备未声明运行时随机等待和实体键条件扩展");
if (triggerButton is < 1 or > 5) throw new ArgumentOutOfRangeException(nameof(triggerButton));
if (physicalButtonIndex < 0 || physicalButtonIndex >= capabilities.ButtonCount) throw new ArgumentOutOfRangeException(nameof(physicalButtonIndex));
cancellationToken.ThrowIfCancellationRequested(); LuaSourceFile.ValidateSource(source);
var statements = new Parser(source, cancellationToken).Parse();
try { _ = new Script(CoreModules.Preset_HardSandbox).LoadString(source, codeFriendlyName: "onboard-import.lua"); }
catch (SyntaxErrorException error) { throw new FormatException("Lua 语法无效:" + error.DecoratedMessage, error); }
var conversion = new Compiler(statements, triggerButton, MacroRepeat.Once, cancellationToken, (ushort)(1 << physicalButtonIndex)).Run();
return MacroCompiler.CompileNativeLua(conversion.Script, capabilities);
}
public static MacroProgram ConvertToMacro(string source, int triggerButton = 1, MacroRepeat repeat = MacroRepeat.Once) => Convert(source, triggerButton, repeat).CompileProgram();
public static string ConvertToScript(string source, int triggerButton = 1, MacroRepeat repeat = MacroRepeat.Once) => Convert(source, triggerButton, repeat).Script;
public static LuaOnboardConversion Convert(string source, int triggerButton = 1, MacroRepeat repeat = MacroRepeat.Once, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrWhiteSpace(source)) throw new FormatException("Lua 脚本不能为空。");
LuaSourceFile.ValidateSource(source);
if (triggerButton is < 1 or > 5) throw new ArgumentOutOfRangeException(nameof(triggerButton));
if (!Enum.IsDefined(repeat)) throw new ArgumentOutOfRangeException(nameof(repeat));
if (LuaMacroExport.TryRestore(source, triggerButton, repeat, out var restored)) return restored;
var statements = new Parser(source, cancellationToken).Parse();
try { _ = new Script(CoreModules.Preset_HardSandbox).LoadString(source, codeFriendlyName: "onboard-import.lua"); }
catch (SyntaxErrorException error) { throw new FormatException("Lua 语法无效:" + error.DecoratedMessage, error); }
cancellationToken.ThrowIfCancellationRequested();
return new Compiler(statements, triggerButton, repeat, cancellationToken).Run();
}
private static NotSupportedException Unsupported(string detail) => new("Lua 板载转换:" + detail + "。原始 Lua 可在软件层运行;未写入鼠标。");
private abstract record Expr;
private sealed record Literal(object? Value) : Expr;
private sealed record Name(string Value) : Expr;
private sealed record Grouped(Expr Value) : Expr;
private sealed record Index(Expr Target, Expr Key) : Expr;
private sealed record Unary(string Op, Expr Value) : Expr;
private sealed record Binary(string Op, Expr Left, Expr Right) : Expr;
private sealed record Call(Expr Target, List Arguments) : Expr;
private sealed record TableExpr(List<(Expr? Key, Expr Value)> Fields) : Expr;
private sealed record FunctionExpr(List Parameters, List Body) : Expr;
private abstract record Stmt;
private sealed record Assign(List Targets, List Values, bool Local) : Stmt;
private sealed record Invoke(Call Call) : Stmt;
private sealed record Def(Expr Target, FunctionExpr Function, bool Local) : Stmt;
private sealed record If(List<(Expr Condition, List Body)> Arms, List Else) : Stmt;
private sealed record For(string Name, Expr Start, Expr End, Expr Step, List Body) : Stmt;
private sealed record Each(List Names, List Iterators, List Body) : Stmt;
private sealed record While(Expr Condition, List Body, bool Until) : Stmt;
private sealed record Block(List Body) : Stmt;
private sealed record Return(List Values) : Stmt;
private sealed record Break : Stmt;
private sealed class ReturnFlow(object?[] values) : Exception { public object?[] Values { get; } = values; }
private sealed class BreakFlow : Exception;
private sealed class ContinuousLoopFlow : Exception;
private sealed class Cell(object? value) { public object? Value = value; public bool Persistent; }
private sealed class Scope
{
private readonly Scope? parent;
public Scope Environment { get; }
public Scope(Scope? parent = null) { this.parent = parent; Environment = parent?.Environment ?? this; }
public Dictionary Cells { get; } = new(StringComparer.Ordinal);
public Cell? Find(string name) => Cells.GetValueOrDefault(name) ?? parent?.Find(name);
public Cell Declare(string name, object? value) { var cell = new Cell(value); Cells[name] = cell; return cell; }
public Dictionary VisibleCells() { var cells = parent?.VisibleCells() ?? new Dictionary(StringComparer.Ordinal); foreach (var pair in Cells) cells[pair.Key] = pair.Value; return cells; }
public Scope Capture()
{
var scope = new Scope(Environment);
void Copy(Scope frame) { if (ReferenceEquals(frame, Environment)) return; if (frame.parent is not null) Copy(frame.parent); foreach (var pair in frame.Cells) scope.Cells[pair.Key] = pair.Value; }
Copy(this); return scope;
}
}
private sealed record FunctionValue(FunctionExpr Definition, Scope Closure);
private sealed record Native(string Name);
private sealed record Iterator(TableValue Table, bool Pairs);
private sealed class TableValue
{
public Dictionary