Browse Source

chore: format source code

nuskey8 1 month ago
parent
commit
ec7842f885
44 changed files with 459 additions and 543 deletions
  1. 5 10
      sandbox/ConsoleApp1/Program.cs
  2. 0 1
      sandbox/ConsoleApp2/Program.cs
  3. 2 6
      sandbox/JitTest/Program.cs
  4. 18 20
      src/Lua/CodeAnalysis/Compilation/Dump.cs
  5. 11 11
      src/Lua/CodeAnalysis/Compilation/Function.cs
  6. 1 2
      src/Lua/CodeAnalysis/Compilation/Parser.cs
  7. 9 11
      src/Lua/CodeAnalysis/Compilation/Scanner.cs
  8. 1 1
      src/Lua/CodeAnalysis/Syntax/Parser.cs
  9. 2 5
      src/Lua/IO/ConsoleStandardIO.cs
  10. 1 1
      src/Lua/Internal/BitFlags.cs
  11. 1 2
      src/Lua/Internal/CancellationExtensions.cs
  12. 1 1
      src/Lua/Internal/CompilerServices/AsyncMethodBuilderAttribute.cs
  13. 1 1
      src/Lua/Internal/Constants.cs
  14. 13 22
      src/Lua/Internal/CoroutineCore.cs
  15. 1 2
      src/Lua/Internal/EnumerableEx.cs
  16. 37 38
      src/Lua/Internal/LuaDebug.cs
  17. 3 10
      src/Lua/Internal/LuaGlobalState.cs
  18. 4 1
      src/Lua/Internal/MathEx.cs
  19. 1 1
      src/Lua/LuaCoroutine.cs
  20. 0 2
      src/Lua/LuaFunction.cs
  21. 4 6
      src/Lua/LuaFunctionExecutionContext.cs
  22. 0 3
      src/Lua/LuaModule.cs
  23. 3 16
      src/Lua/LuaState.cs
  24. 1 2
      src/Lua/LuaTable.cs
  25. 0 3
      src/Lua/LuaThreadExtensions.cs
  26. 1 1
      src/Lua/LuaUserData.cs
  27. 0 1
      src/Lua/Platforms/LuaPlatform.cs
  28. 4 1
      src/Lua/Runtime/CSharpClosure.cs
  29. 1 1
      src/Lua/Runtime/CallStackFrame.cs
  30. 177 176
      src/Lua/Runtime/Instruction.cs
  31. 4 1
      src/Lua/Runtime/LuaStack.cs
  32. 1 3
      src/Lua/Runtime/LuaVirtualMachine.Markers.cs
  33. 29 22
      src/Lua/Runtime/LuaVirtualMachine.cs
  34. 18 36
      src/Lua/Runtime/Metamethods.cs
  35. 1 2
      src/Lua/Runtime/Prototype.cs
  36. 5 8
      src/Lua/Runtime/Tracebacks.cs
  37. 0 1
      src/Lua/Standard/BasicLibrary.cs
  38. 0 1
      src/Lua/Standard/BitwiseLibrary.cs
  39. 9 13
      src/Lua/Standard/DebugLibrary.cs
  40. 0 1
      src/Lua/Standard/FileHandle.cs
  41. 0 3
      src/Lua/Standard/Internal/IOHelper.cs
  42. 89 89
      src/Lua/Standard/Internal/MatchState.cs
  43. 0 2
      src/Lua/Standard/OpenLibsExtensions.cs
  44. 0 3
      src/Lua/Standard/TableLibrary.cs

+ 5 - 10
sandbox/ConsoleApp1/Program.cs

@@ -1,11 +1,9 @@
 using System.Runtime.CompilerServices;
+using System.Text;
+using System.Text.RegularExpressions;
 using Lua.Runtime;
 using Lua;
 using Lua.Standard;
-using System.Text.RegularExpressions;
-using System;
-using System.IO;
-using System.Text;
 
 var state = LuaState.Create();
 state.OpenStandardLibraries();
@@ -20,9 +18,7 @@ try
 {
     source = File.ReadAllText(GetAbsolutePath("test.lua"));
 
-
-    //Console.WriteLine("Source Code " + new string('-', 50));
-
+    // Console.WriteLine("Source Code " + new string('-', 50));
     // Console.WriteLine(source);
 
     var closure = state.Load(source, "@test.lua");
@@ -31,7 +27,8 @@ try
 
     Console.WriteLine("Output " + new string('-', 50));
 
-    //Console.Read();
+    // Console.Read();
+
     var timer = new System.Diagnostics.Stopwatch();
     timer.Start();
     for (var i = 0; i < 1000; i++)
@@ -45,7 +42,6 @@ try
         }
     }
 
-
     // Console.WriteLine("Result " + new string('-', 50));
     // using var results = state.RootAccess.ReadTopValues(count);
     // for (var i = 0; i < count; i++)
@@ -61,7 +57,6 @@ catch (Exception ex)
     {
         Console.WriteLine("CompileError " + new string('-', 50));
         Console.WriteLine(RustLikeExceptionHook.OnCatch(source, luaCompileException));
-        ;
         Console.WriteLine(new string('-', 55));
     }
 

+ 0 - 1
sandbox/ConsoleApp2/Program.cs

@@ -1,7 +1,6 @@
 using Lua.Runtime;
 using Lua;
 using Lua.Standard;
-using System;
 
 var state = LuaState.Create();
 state.OpenStandardLibraries();

+ 2 - 6
sandbox/JitTest/Program.cs

@@ -1,7 +1,4 @@
-// See https://aka.ms/new-console-template for more information
-
-
-using System.Reflection;
+using System.Reflection;
 using System.Runtime.CompilerServices;
 using JitInspect;
 using Lua;
@@ -45,8 +42,7 @@ var method = typeof(LuaVirtualMachine).GetMethod("MoveNext", BindingFlags.Static
 using var disassembler = JitDisassembler.Create();
 var nextJitText = disassembler.Disassemble(method, new() { PrintInstructionAddresses = true });
 File.WriteAllText(newJIitPath, nextJitText);
-//Console.WriteLine("New:" + nextJitText.Split("\n")[^1]);
-
+// Console.WriteLine("New:" + nextJitText.Split("\n")[^1]);
 
 static string GetThisDirectoryName([CallerFilePath] string callerFilePath = "")
 {

+ 18 - 20
src/Lua/CodeAnalysis/Compilation/Dump.cs

@@ -15,7 +15,6 @@ namespace Lua.CodeAnalysis.Compilation;
 unsafe struct Header
 {
     public static ReadOnlySpan<byte> LuaSignature => "\eLua"u8;
-
     public static ReadOnlySpan<byte> LuaTail => [0x19, 0x93, 0x0d, 0x0a, 0x1a, 0x0a];
 
     public fixed byte Signature[4];
@@ -127,17 +126,17 @@ unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEndian)
 
     void DumpFunction(Prototype prototype)
     {
-        WriteInt(prototype.LineDefined); //4
-        WriteInt(prototype.LastLineDefined); //4
-        WriteByte((byte)prototype.ParameterCount); //1
-        WriteByte((byte)prototype.MaxStackSize); //1
-        WriteByte((byte)(prototype.HasVariableArguments ? 1 : 0)); //1
-        WriteIntSpanWithLength(MemoryMarshal.Cast<Instruction, int>(prototype.Code)); //4
-        WriteConstants(prototype.Constants); //4
-        WritePrototypes(prototype.ChildPrototypes); //4
-        WriteUpValues(prototype.UpValues); //4
-
-        //Debug
+        WriteInt(prototype.LineDefined); // 4
+        WriteInt(prototype.LastLineDefined); // 4
+        WriteByte((byte)prototype.ParameterCount); // 1
+        WriteByte((byte)prototype.MaxStackSize); // 1
+        WriteByte((byte)(prototype.HasVariableArguments ? 1 : 0)); // 1
+        WriteIntSpanWithLength(MemoryMarshal.Cast<Instruction, int>(prototype.Code)); // 4
+        WriteConstants(prototype.Constants); // 4
+        WritePrototypes(prototype.ChildPrototypes); // 4
+        WriteUpValues(prototype.UpValues); // 4
+
+        // Debug
         WriteString(prototype.ChunkName);
         WriteIntSpanWithLength(prototype.LineInfo);
         WriteLocalVariables(prototype.LocalVariables);
@@ -179,7 +178,6 @@ unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEndian)
         WriteLong(l);
     }
 
-
     void WriteIntSpanWithLength(ReadOnlySpan<int> v)
     {
         WriteInt(v.Length);
@@ -387,11 +385,11 @@ unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<char> name,
 
     Prototype UnDumpFunction()
     {
-        var lineDefined = ReadInt(); //4
-        var lastLineDefined = ReadInt(); //4
-        var parameterCount = ReadByte(); //1
-        var maxStackSize = ReadByte(); //1
-        var isVarArg = ReadByte() == 1; //1
+        var lineDefined = ReadInt(); // 4
+        var lastLineDefined = ReadInt(); // 4
+        var parameterCount = ReadByte(); // 1
+        var maxStackSize = ReadByte(); // 1
+        var isVarArg = ReadByte() == 1; // 1
         var codeLength = ReadInt();
         var code = new Instruction[codeLength];
         ReadInToIntSpan(MemoryMarshal.Cast<Instruction, int>(code));
@@ -399,7 +397,7 @@ unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<char> name,
         var prototypes = ReadPrototypes();
         var upValues = ReadUpValues();
 
-        //Debug
+        // Debug
         var source = ReadString();
         var lineInfoLength = ReadInt();
         var lineInfo = new int[lineInfoLength];
@@ -444,7 +442,7 @@ unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<char> name,
 
             var l = ReadByte();
             Debug.Assert(l == 0);
-            var chars = len <= 128 ? stackalloc char[len*2] : (charArrayPooled = ArrayPool<char>.Shared.Rent(len * 2));
+            var chars = len <= 128 ? stackalloc char[len * 2] : (charArrayPooled = ArrayPool<char>.Shared.Rent(len * 2));
             var count = Encoding.UTF8.GetChars(span, chars);
             return internPool.Intern(chars[..count]);
         }

+ 11 - 11
src/Lua/CodeAnalysis/Compilation/Function.cs

@@ -776,19 +776,19 @@ class Function : IPoolNode<Function>
                 break;
             case Kind.Indexed:
                 FreeRegister(e.Index);
-            {
-                if (e.TableType == Kind.Local)
-                {
-                    FreeRegister(e.Table);
-                    e.Kind = Kind.Relocatable;
-                    e.Info = EncodeABC(OpCode.GetTable, 0, e.Table, e.Index);
-                }
-                else
                 {
-                    e.Kind = Kind.Relocatable;
-                    e.Info = EncodeABC(OpCode.GetTabUp, 0, e.Table, e.Index);
+                    if (e.TableType == Kind.Local)
+                    {
+                        FreeRegister(e.Table);
+                        e.Kind = Kind.Relocatable;
+                        e.Info = EncodeABC(OpCode.GetTable, 0, e.Table, e.Index);
+                    }
+                    else
+                    {
+                        e.Kind = Kind.Relocatable;
+                        e.Info = EncodeABC(OpCode.GetTabUp, 0, e.Table, e.Index);
+                    }
                 }
-            }
                 break;
             case Kind.VarArg:
             case Kind.Call:

+ 1 - 2
src/Lua/CodeAnalysis/Compilation/Parser.cs

@@ -382,8 +382,7 @@ class Parser : IPoolNode<Parser>, IDisposable
 
     public static int UnaryPriority => 8;
 
-
-    public (ExprDesc, int ) SubExpression(int limit)
+    public (ExprDesc, int) SubExpression(int limit)
     {
         using var b = EnterLevel();
         ExprDesc e;

+ 9 - 11
src/Lua/CodeAnalysis/Compilation/Scanner.cs

@@ -1,12 +1,10 @@
 using Lua.Internal;
 using System.Globalization;
-using System.Text;
 using static System.Diagnostics.Debug;
+using static Lua.Internal.Constants;
 
 namespace Lua.CodeAnalysis.Compilation;
 
-using static Constants;
-
 struct Scanner
 {
     public LuaState L;
@@ -18,10 +16,10 @@ struct Scanner
     public Token LookAheadToken;
     int lastNewLinePos;
     public StringInternPool StringPool;
-    
+
     string Intern(ReadOnlySpan<char> s) => StringPool.Intern(s);
 
-    ///inline
+    // inline
     public Token Token;
 
     public int T => Token.T;
@@ -29,7 +27,7 @@ struct Scanner
     public const int FirstReserved = ushort.MaxValue + 257;
     public const int EndOfStream = -1;
 
-    public const int MaxInt = int.MaxValue >> (1 + 1); //9223372036854775807
+    public const int MaxInt = int.MaxValue >> (1 + 1); // 9223372036854775807
 
     public const int TkAnd = FirstReserved;
     public const int TkBreak = TkAnd + 1;
@@ -235,7 +233,7 @@ struct Scanner
             IncrementLineNumber();
         }
 
-        for (;;)
+        for (; ; )
         {
             switch (Current)
             {
@@ -249,7 +247,7 @@ struct Scanner
                         SaveAndAdvance();
                         if (!comment)
                         {
-                            var s = Intern( Buffer.AsSpan().Slice(2 + sep, Buffer.Length - (4 + (2 * sep))));
+                            var s = Intern(Buffer.AsSpan().Slice(2 + sep, Buffer.Length - (4 + (2 * sep))));
                             Buffer.Clear();
                             return s;
                         }
@@ -304,7 +302,7 @@ struct Scanner
 
         position++;
         var i = 0;
-        for (;;)
+        for (; ; )
         {
             switch (c)
             {
@@ -539,7 +537,7 @@ struct Scanner
                     ScanError(R.Position, "unfinished string", TkEos);
                     break;
                 case '\n' or '\r':
-                    Token = new(R.Position - Buffer.Length, TkString,Intern( Buffer.AsSpan()));
+                    Token = new(R.Position - Buffer.Length, TkString, Intern(Buffer.AsSpan()));
                     ScanError(R.Position, "unfinished string", TkString);
                     break;
                 case '\\':
@@ -593,7 +591,7 @@ struct Scanner
 
         SaveAndAdvance();
         var length = Buffer.Length - 2;
-        // if (0<length&&Buffer[^2] == '\0')
+        // if (0 < length && Buffer[^2] == '\0')
         // {
         //     length--;
         // }

+ 1 - 1
src/Lua/CodeAnalysis/Syntax/Parser.cs

@@ -602,7 +602,7 @@ public ref struct Parser
             return false;
         }
 
-        // nested table access & function call
+    // nested table access & function call
     RECURSIVE:
         enumerator.SkipEoL();
 

+ 2 - 5
src/Lua/IO/ConsoleStandardIO.cs

@@ -8,6 +8,8 @@ namespace Lua.IO;
 public sealed class ConsoleStandardIO : ILuaStandardIO
 {
     ILuaStream? standardInput;
+    ILuaStream? standardOutput;
+    ILuaStream? standardError;
 
     public ILuaStream Input =>
         standardInput ??=
@@ -15,17 +17,12 @@ public sealed class ConsoleStandardIO : ILuaStandardIO
                 ConsoleHelper.OpenStandardInput(),
                 LuaFileOpenMode.Read));
 
-    ILuaStream? standardOutput;
-
     public ILuaStream Output =>
         standardOutput ??=
             new StandardIOStream(ILuaStream.CreateFromStream(
                 ConsoleHelper.OpenStandardOutput(),
                 LuaFileOpenMode.Write));
 
-
-    ILuaStream? standardError;
-
     public ILuaStream Error =>
         standardError ??=
             new StandardIOStream(ILuaStream.CreateFromStream(

+ 1 - 1
src/Lua/Internal/BitFlags.cs

@@ -1,6 +1,6 @@
 namespace Lua.Internal;
 
-struct BitFlags2
+internal struct BitFlags2
 {
     public byte Value;
 

+ 1 - 2
src/Lua/Internal/CancellationExtensions.cs

@@ -8,5 +8,4 @@ internal static class CancellationTokenExtensions
         return cancellationToken.Register(callback, state, useSynchronizationContext: false);
     }
 }
-
-#endif
+#endif

+ 1 - 1
src/Lua/Internal/CompilerServices/AsyncMethodBuilderAttribute.cs

@@ -8,4 +8,4 @@ namespace System.Runtime.CompilerServices
         public Type BuilderType { get; } = builderType;
     }
 }
-#endif
+#endif

+ 1 - 1
src/Lua/Internal/Constants.cs

@@ -1,6 +1,6 @@
 namespace Lua.Internal;
 
-class Constants
+internal class Constants
 {
     public const int VersionMajor = 5;
     public const int VersionMinor = 2;

+ 13 - 22
src/Lua/Internal/CoroutineCore.cs

@@ -5,16 +5,9 @@ using System.Threading.Tasks.Sources;
 
 namespace Lua.Internal;
 
-class CoroutineCore:IValueTaskSource<CoroutineCore.YieldContext>, IValueTaskSource<CoroutineCore.ResumeContext>
+class CoroutineCore(LuaState state, LuaFunction function, bool isProtectedMode) : IValueTaskSource<CoroutineCore.YieldContext>,
+    IValueTaskSource<CoroutineCore.ResumeContext>
 {
-    
-    public CoroutineCore(LuaState state, LuaFunction function, bool isProtectedMode)
-    {
-        Thread = state;
-        Function = function;
-        IsProtectedMode = isProtectedMode;
-        status = (byte)LuaThreadStatus.Suspended;
-    }
     readonly struct YieldContext(LuaStack stack, int argCount)
     {
         public ReadOnlySpan<LuaValue> Results => stack.AsSpan()[^argCount..];
@@ -23,24 +16,22 @@ class CoroutineCore:IValueTaskSource<CoroutineCore.YieldContext>, IValueTaskSour
     readonly struct ResumeContext(LuaStack? stack, int argCount)
     {
         public ReadOnlySpan<LuaValue> Results => stack!.AsSpan()[^argCount..];
-
         public bool IsDead => stack == null;
     }
-    internal byte status ;
+
+    internal byte status = (byte)LuaThreadStatus.Suspended;
     bool isFirstCall = true;
     ValueTask<int> functionTask;
 
     ManualResetValueTaskSourceCore<ResumeContext> resume;
     ManualResetValueTaskSourceCore<YieldContext> yield;
     Traceback? traceback;
-    
-    public bool IsProtectedMode { get; private set; }
-    public LuaFunction Function { get; private set; } = null!;
-    
-    public LuaState Thread { get; private set; } = null!;
-    
+
+    public bool IsProtectedMode { get; private set; } = isProtectedMode;
+    public LuaFunction Function { get; private set; } = function;
+    public LuaState Thread { get; private set; } = state;
     public Traceback? Traceback => traceback;
-    
+
     YieldContext IValueTaskSource<YieldContext>.GetResult(short token)
     {
         return yield.GetResult(token);
@@ -70,8 +61,8 @@ class CoroutineCore:IValueTaskSource<CoroutineCore.YieldContext>, IValueTaskSour
     {
         resume.OnCompleted(continuation, state, token, flags);
     }
-    
-     [AsyncMethodBuilder(typeof(LightAsyncValueTaskMethodBuilder<>))]
+
+    [AsyncMethodBuilder(typeof(LightAsyncValueTaskMethodBuilder<>))]
     internal async ValueTask<int> ResumeAsyncCore(LuaStack stack, int argCount, int returnBase, LuaState? baseThread, CancellationToken cancellationToken = default)
     {
         if (baseThread != null)
@@ -138,7 +129,7 @@ class CoroutineCore:IValueTaskSource<CoroutineCore.YieldContext>, IValueTaskSour
                 if (isFirstCall)
                 {
                     Thread.Stack.PushRange(stack.AsSpan()[^argCount..]);
-                    //functionTask = Function.InvokeAsync(new() { Access = this.CurrentAccess, ArgumentCount = Stack.Count, ReturnFrameBase = 0 }, cancellationToken);
+                    // functionTask = Function.InvokeAsync(new() { Access = this.CurrentAccess, ArgumentCount = Stack.Count, ReturnFrameBase = 0 }, cancellationToken);
                     functionTask = Thread.RunAsync(Function, Thread.Stack.Count, cancellationToken);
                     Volatile.Write(ref isFirstCall, false);
                     if (!functionTask.IsCompleted)
@@ -204,6 +195,7 @@ class CoroutineCore:IValueTaskSource<CoroutineCore.YieldContext>, IValueTaskSour
             }
         }
     }
+
     [AsyncMethodBuilder(typeof(LightAsyncValueTaskMethodBuilder<>))]
     internal async ValueTask<int> YieldAsyncCore(LuaStack stack, int argCount, int returnBase, LuaState? baseThread, CancellationToken cancellationToken = default)
     {
@@ -222,7 +214,6 @@ class CoroutineCore:IValueTaskSource<CoroutineCore.YieldContext>, IValueTaskSour
 
         resume.SetResult(new(stack, argCount));
 
-
         CancellationTokenRegistration registration = default;
         if (cancellationToken.CanBeCanceled)
         {

+ 1 - 2
src/Lua/Internal/EnumerableEx.cs

@@ -10,14 +10,13 @@ static class EnumerableEx
         if (keySelector == null)
             throw new ArgumentNullException(nameof(keySelector));
 
-
         using var enumerator = source.GetEnumerator();
         if (!enumerator.MoveNext())
         {
             yield break;
         }
 
-        List<T> group = new() { enumerator.Current };
+        List<T> group = [enumerator.Current];
         var previousKey = keySelector(enumerator.Current);
 
         while (enumerator.MoveNext())

+ 37 - 38
src/Lua/Internal/LuaDebug.cs

@@ -679,49 +679,48 @@ readonly struct LuaDebug : IDisposable
         return (t << 7) | (a << 6) | ((byte)b << 4) | ((byte)c << 2) | (byte)m;
     }
 
-
     static readonly int[] OpModes =
     [
-        GetOpMode(0, 1, OpArgR, OpArgN, iABC), /* OP_MOVE */
-        GetOpMode(0, 1, OpArgK, OpArgN, iABx), /* OP_LOADK */
-        GetOpMode(0, 1, OpArgN, OpArgN, iABx), /* OP_LOADKX */
-        GetOpMode(0, 1, OpArgU, OpArgU, iABC), /* OP_LOADBOOL */
-        GetOpMode(0, 1, OpArgU, OpArgN, iABC), /* OP_LOADNIL */
-        GetOpMode(0, 1, OpArgU, OpArgN, iABC), /* OP_GETUPVAL */
-        GetOpMode(0, 1, OpArgU, OpArgK, iABC), /* OP_GETTABUP */
-        GetOpMode(0, 1, OpArgR, OpArgK, iABC), /* OP_GETTABLE */
-        GetOpMode(0, 0, OpArgK, OpArgK, iABC), /* OP_SETTABUP */
-        GetOpMode(0, 0, OpArgU, OpArgN, iABC), /* OP_SETUPVAL */
-        GetOpMode(0, 0, OpArgK, OpArgK, iABC), /* OP_SETTABLE */
-        GetOpMode(0, 1, OpArgU, OpArgU, iABC), /* OP_NEWTABLE */
-        GetOpMode(0, 1, OpArgR, OpArgK, iABC), /* OP_SELF */
-        GetOpMode(0, 1, OpArgK, OpArgK, iABC), /* OP_ADD */
-        GetOpMode(0, 1, OpArgK, OpArgK, iABC), /* OP_SUB */
-        GetOpMode(0, 1, OpArgK, OpArgK, iABC), /* OP_MUL */
-        GetOpMode(0, 1, OpArgK, OpArgK, iABC), /* OP_DIV */
-        GetOpMode(0, 1, OpArgK, OpArgK, iABC), /* OP_MOD */
-        GetOpMode(0, 1, OpArgK, OpArgK, iABC), /* OP_POW */
-        GetOpMode(0, 1, OpArgR, OpArgN, iABC), /* OP_UNM */
-        GetOpMode(0, 1, OpArgR, OpArgN, iABC), /* OP_NOT */
-        GetOpMode(0, 1, OpArgR, OpArgN, iABC), /* OP_LEN */
-        GetOpMode(0, 1, OpArgR, OpArgR, iABC), /* OP_CONCAT */
+        GetOpMode(0, 1, OpArgR, OpArgN, iABC),  /* OP_MOVE */
+        GetOpMode(0, 1, OpArgK, OpArgN, iABx),  /* OP_LOADK */
+        GetOpMode(0, 1, OpArgN, OpArgN, iABx),  /* OP_LOADKX */
+        GetOpMode(0, 1, OpArgU, OpArgU, iABC),  /* OP_LOADBOOL */
+        GetOpMode(0, 1, OpArgU, OpArgN, iABC),  /* OP_LOADNIL */
+        GetOpMode(0, 1, OpArgU, OpArgN, iABC),  /* OP_GETUPVAL */
+        GetOpMode(0, 1, OpArgU, OpArgK, iABC),  /* OP_GETTABUP */
+        GetOpMode(0, 1, OpArgR, OpArgK, iABC),  /* OP_GETTABLE */
+        GetOpMode(0, 0, OpArgK, OpArgK, iABC),  /* OP_SETTABUP */
+        GetOpMode(0, 0, OpArgU, OpArgN, iABC),  /* OP_SETUPVAL */
+        GetOpMode(0, 0, OpArgK, OpArgK, iABC),  /* OP_SETTABLE */
+        GetOpMode(0, 1, OpArgU, OpArgU, iABC),  /* OP_NEWTABLE */
+        GetOpMode(0, 1, OpArgR, OpArgK, iABC),  /* OP_SELF */
+        GetOpMode(0, 1, OpArgK, OpArgK, iABC),  /* OP_ADD */
+        GetOpMode(0, 1, OpArgK, OpArgK, iABC),  /* OP_SUB */
+        GetOpMode(0, 1, OpArgK, OpArgK, iABC),  /* OP_MUL */
+        GetOpMode(0, 1, OpArgK, OpArgK, iABC),  /* OP_DIV */
+        GetOpMode(0, 1, OpArgK, OpArgK, iABC),  /* OP_MOD */
+        GetOpMode(0, 1, OpArgK, OpArgK, iABC),  /* OP_POW */
+        GetOpMode(0, 1, OpArgR, OpArgN, iABC),  /* OP_UNM */
+        GetOpMode(0, 1, OpArgR, OpArgN, iABC),  /* OP_NOT */
+        GetOpMode(0, 1, OpArgR, OpArgN, iABC),  /* OP_LEN */
+        GetOpMode(0, 1, OpArgR, OpArgR, iABC),  /* OP_CONCAT */
         GetOpMode(0, 0, OpArgR, OpArgN, iAsBx), /* OP_JMP */
-        GetOpMode(1, 0, OpArgK, OpArgK, iABC), /* OP_EQ */
-        GetOpMode(1, 0, OpArgK, OpArgK, iABC), /* OP_LT */
-        GetOpMode(1, 0, OpArgK, OpArgK, iABC), /* OP_LE */
-        GetOpMode(1, 0, OpArgN, OpArgU, iABC), /* OP_TEST */
-        GetOpMode(1, 1, OpArgR, OpArgU, iABC), /* OP_TESTSET */
-        GetOpMode(0, 1, OpArgU, OpArgU, iABC), /* OP_CALL */
-        GetOpMode(0, 1, OpArgU, OpArgU, iABC), /* OP_TAILCALL */
-        GetOpMode(0, 0, OpArgU, OpArgN, iABC), /* OP_RETURN */
+        GetOpMode(1, 0, OpArgK, OpArgK, iABC),  /* OP_EQ */
+        GetOpMode(1, 0, OpArgK, OpArgK, iABC),  /* OP_LT */
+        GetOpMode(1, 0, OpArgK, OpArgK, iABC),  /* OP_LE */
+        GetOpMode(1, 0, OpArgN, OpArgU, iABC),  /* OP_TEST */
+        GetOpMode(1, 1, OpArgR, OpArgU, iABC),  /* OP_TESTSET */
+        GetOpMode(0, 1, OpArgU, OpArgU, iABC),  /* OP_CALL */
+        GetOpMode(0, 1, OpArgU, OpArgU, iABC),  /* OP_TAILCALL */
+        GetOpMode(0, 0, OpArgU, OpArgN, iABC),  /* OP_RETURN */
         GetOpMode(0, 1, OpArgR, OpArgN, iAsBx), /* OP_FORLOOP */
         GetOpMode(0, 1, OpArgR, OpArgN, iAsBx), /* OP_FORPREP */
-        GetOpMode(0, 0, OpArgN, OpArgU, iABC), /* OP_TFORCALL */
+        GetOpMode(0, 0, OpArgN, OpArgU, iABC),  /* OP_TFORCALL */
         GetOpMode(0, 1, OpArgR, OpArgN, iAsBx), /* OP_TFORLOOP */
-        GetOpMode(0, 0, OpArgU, OpArgU, iABC), /* OP_SETLIST */
-        GetOpMode(0, 1, OpArgU, OpArgN, iABx), /* OP_CLOSURE */
-        GetOpMode(0, 1, OpArgU, OpArgN, iABC), /* OP_VARARG */
-        GetOpMode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */
+        GetOpMode(0, 0, OpArgU, OpArgU, iABC),  /* OP_SETLIST */
+        GetOpMode(0, 1, OpArgU, OpArgN, iABx),  /* OP_CLOSURE */
+        GetOpMode(0, 1, OpArgU, OpArgN, iABC),  /* OP_VARARG */
+        GetOpMode(0, 0, OpArgU, OpArgU, iAx)    /* OP_EXTRAARG */
     ];
 
     internal static OpMode GetOpMode(OpCode m)
@@ -763,5 +762,5 @@ enum OpArgMask : byte
     OpArgN, /* argument is not used */
     OpArgU, /* argument is used */
     OpArgR, /* argument is a register or a jump offset */
-    OpArgK /* argument is a constant or register/constant */
+    OpArgK, /* argument is a constant or register/constant */
 }

+ 3 - 10
src/Lua/Internal/LuaGlobalState.cs

@@ -18,26 +18,19 @@ sealed class LuaGlobalState
 
     FastStackCore<LuaDebug.LuaDebugBuffer> debugBufferPool;
 
-    internal UpValue EnvUpValue => envUpValue;
+    public LuaPlatform Platform { get; set; }
+    public ILuaModuleLoader? ModuleLoader { get; set; }
 
+    internal UpValue EnvUpValue => envUpValue;
     internal ref FastStackCore<LuaState> ThreadStack => ref stateStack;
-
     internal ref FastStackCore<LuaDebug.LuaDebugBuffer> DebugBufferPool => ref debugBufferPool;
 
     public LuaTable Environment => environment;
-
     public LuaTable Registry => registry;
-
     public LuaTable LoadedModules => registry[ModuleLibrary.LoadedKeyForRegistry].Read<LuaTable>();
-
     public LuaTable PreloadModules => registry[ModuleLibrary.PreloadKeyForRegistry].Read<LuaTable>();
-
     public LuaState MainThread => mainState;
 
-    public LuaPlatform Platform { get; set; }
-
-    public ILuaModuleLoader? ModuleLoader { get; set; }
-
     // metatables
     LuaTable? nilMetatable;
     LuaTable? numberMetatable;

+ 4 - 1
src/Lua/Internal/MathEx.cs

@@ -1,4 +1,5 @@
 using System.Runtime.CompilerServices;
+
 #if NET6_0_OR_GREATER
 using System.Numerics;
 #endif
@@ -93,7 +94,9 @@ static class MathEx
         return ((int)Math.Truncate(d), d % 1.0);
     }
 
-    /// <summary>Returns the smallest power of two greater than or equal to the input.</summary>
+    /// <summary>
+    /// Returns the smallest power of two greater than or equal to the input.
+    /// </summary>
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public static int NextPowerOfTwo(int x)
     {

+ 1 - 1
src/Lua/LuaCoroutine.cs

@@ -320,4 +320,4 @@
 //         CoreData?.Release();
 //         CoreData = null!;
 //     }
-// }
+// }

+ 0 - 2
src/Lua/LuaFunction.cs

@@ -1,5 +1,3 @@
-using Lua.Runtime;
-
 namespace Lua;
 
 public class LuaFunction(string name, Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> func)

+ 4 - 6
src/Lua/LuaFunctionExecutionContext.cs

@@ -8,22 +8,20 @@ namespace Lua;
 public readonly record struct LuaFunctionExecutionContext
 {
     internal LuaGlobalState GlobalState => State.GlobalState;
-    
-    public LuaState State { get; init; }
 
+    public LuaState State { get; init; }
     public required int ArgumentCount { get; init; }
+    public required int ReturnFrameBase { get; init; }
+    // public object? AdditionalContext { get; init; }
 
     public int FrameBase => State.Stack.Count - ArgumentCount;
 
-    public required int ReturnFrameBase { get; init; }
-    //public object? AdditionalContext { get; init; }
-
     public ReadOnlySpan<LuaValue> Arguments
     {
         get
         {
             var stack = State.Stack.AsSpan();
-            return stack.Slice(stack.Length - ArgumentCount);
+            return stack[^ArgumentCount..];
         }
     }
 

+ 0 - 3
src/Lua/LuaModule.cs

@@ -1,6 +1,3 @@
-using System.Buffers;
-using System.Runtime.CompilerServices;
-
 namespace Lua;
 
 public enum LuaModuleType

+ 3 - 16
src/Lua/LuaState.cs

@@ -1,9 +1,9 @@
-using Lua.CodeAnalysis.Compilation;
 using System.Runtime.CompilerServices;
+using System.Buffers;
 using Lua.Internal;
 using Lua.Platforms;
 using Lua.Runtime;
-using System.Buffers;
+using Lua.CodeAnalysis.Compilation;
 
 namespace Lua;
 
@@ -48,7 +48,6 @@ public class LuaState : IDisposable
         return new(GlobalState, function, isProtectedMode);
     }
 
-
     public LuaThreadStatus GetStatus()
     {
         if (coroutine is not null)
@@ -113,7 +112,7 @@ public class LuaState : IDisposable
 
     class ThreadCoreData : IPoolNode<ThreadCoreData>
     {
-        //internal  LuaCoroutineData? coroutineData;
+        // internal LuaCoroutineData? coroutineData;
         internal readonly LuaStack Stack = new();
         internal FastStackCore<CallStackFrame> CallStack;
 
@@ -145,7 +144,6 @@ public class LuaState : IDisposable
         }
     }
 
-
     FastListCore<UpValue> openUpValues;
     internal int CallCount;
     internal LuaGlobalState GlobalState { get; }
@@ -168,21 +166,13 @@ public class LuaState : IDisposable
     internal LuaFunction? Hook { get; set; }
 
     public LuaFunction? CoroutineFunction => coroutine?.Function;
-
     public bool CanResume => GetStatus() == LuaThreadStatus.Suspended;
-
     public LuaStack Stack => CoreData!.Stack;
-
     internal Traceback? LuaTraceback => coroutine?.Traceback;
-
     public LuaTable Environment => GlobalState.Environment;
-
     public LuaTable Registry => GlobalState.Registry;
-
     public LuaTable LoadedModules => GlobalState.LoadedModules;
-
     public LuaTable PreloadModules => GlobalState.PreloadModules;
-
     public LuaState MainThread => GlobalState.MainThread;
 
     public ILuaModuleLoader? ModuleLoader
@@ -226,7 +216,6 @@ public class LuaState : IDisposable
         return CoreData == null ? default : CoreData!.CallStack.AsSpan();
     }
 
-
     internal CallStackFrame CreateCallStackFrame(LuaFunction function, int argumentCount, int returnBase, int callerInstructionIndex)
     {
         var state = this;
@@ -427,7 +416,6 @@ public class LuaState : IDisposable
         }
     }
 
-
     public unsafe LuaClosure Load(ReadOnlySpan<char> chunk, string chunkName, LuaTable? environment = null)
     {
         Prototype prototype;
@@ -467,7 +455,6 @@ public class LuaState : IDisposable
         }
     }
 
-
     internal UpValue GetOrAddUpValue(int registerIndex)
     {
         foreach (var upValue in openUpValues.AsSpan())

+ 1 - 2
src/Lua/LuaTable.cs

@@ -283,8 +283,7 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
         }
 
         var prevLength = array.Length;
-        var newLength = array.Length;
-        newLength = newCapacity <= 8 ? 8 : MathEx.NextPowerOfTwo(newCapacity);
+        var newLength = newCapacity <= 8 ? 8 : MathEx.NextPowerOfTwo(newCapacity);
 
         Array.Resize(ref array, newLength);
 

+ 0 - 3
src/Lua/LuaThreadExtensions.cs

@@ -1,10 +1,7 @@
-using Lua.Runtime;
-
 namespace Lua;
 
 public static class LuaThreadExtensions
 {
-
     internal static void ThrowIfCancellationRequested(this LuaState state, CancellationToken cancellationToken)
     {
         if (cancellationToken.IsCancellationRequested)

+ 1 - 1
src/Lua/LuaUserData.cs

@@ -18,6 +18,6 @@ public interface ILuaUserData
 {
     LuaTable? Metatable { get; set; }
 
-    //We use span for compatibility with lua5.4.
+    // We use span for compatibility with lua5.4.
     Span<LuaValue> UserValues => default;
 }

+ 0 - 1
src/Lua/Platforms/LuaPlatform.cs

@@ -20,5 +20,4 @@ public record LuaPlatform(ILuaFileSystem FileSystem, ILuaOsEnvironment OsEnviron
             OsEnvironment: new SystemOsEnvironment(),
             StandardIO: new ConsoleStandardIO(),
             TimeProvider: TimeProvider.System);
-
 }

+ 4 - 1
src/Lua/Runtime/CSharpClosure.cs

@@ -1,6 +1,9 @@
 namespace Lua.Runtime;
 
-public sealed class CSharpClosure(string name, LuaValue[] upValues, Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> func) : LuaFunction(name, func)
+public sealed class CSharpClosure(
+    string name,
+    LuaValue[] upValues,
+    Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> func) : LuaFunction(name, func)
 {
     public readonly LuaValue[] UpValues = upValues;
 }

+ 1 - 1
src/Lua/Runtime/CallStackFrame.cs

@@ -19,7 +19,7 @@ public record struct CallStackFrame
 [Flags]
 public enum CallStackFrameFlags
 {
-    //None = 0,
+    // None = 0,
     ReversedLe = 1,
     TailCall = 2,
     InHook = 4

+ 177 - 176
src/Lua/Runtime/Instruction.cs

@@ -7,7 +7,6 @@ public partial struct Instruction(uint value)
     public const int IAsBx = 2;
     public const int IAx = 3;
 
-
     public uint Value = value;
 
     public static implicit operator Instruction(uint value)
@@ -62,30 +61,31 @@ public partial struct Instruction(uint value)
     ];
 
     /*
-const (
-    sizeC             = 9
-    sizeB             = 9
-    sizeBx            = sizeC + sizeB
-    sizeA             = 8
-    sizeAx            = sizeC + sizeB + sizeA
-    sizeOp            = 6
-    posOp             = 0
-    posA              = posOp + sizeOp
-    posC              = posA + sizeA
-    posB              = posC + sizeC
-    posBx             = posC
-    posAx             = posA
-    bitRK             = 1 << (sizeB - 1)
-    maxIndexRK        = bitRK - 1
-    maxArgAx          = 1<<sizeAx - 1
-    maxArgBx          = 1<<sizeBx - 1
-    maxArgSBx         = maxArgBx >> 1 // sBx is signed
-    maxArgA           = 1<<sizeA - 1
-    maxArgB           = 1<<sizeB - 1
-    maxArgC           = 1<<sizeC - 1
-    listItemsPerFlush = 50 // # list items to accumulate before a setList instruction
-)
-     */
+    const (
+        sizeC             = 9
+        sizeB             = 9
+        sizeBx            = sizeC + sizeB
+        sizeA             = 8
+        sizeAx            = sizeC + sizeB + sizeA
+        sizeOp            = 6
+        posOp             = 0
+        posA              = posOp + sizeOp
+        posC              = posA + sizeA
+        posB              = posC + sizeC
+        posBx             = posC
+        posAx             = posA
+        bitRK             = 1 << (sizeB - 1)
+        maxIndexRK        = bitRK - 1
+        maxArgAx          = 1<<sizeAx - 1
+        maxArgBx          = 1<<sizeBx - 1
+        maxArgSBx         = maxArgBx >> 1 // sBx is signed
+        maxArgA           = 1<<sizeA - 1
+        maxArgB           = 1<<sizeB - 1
+        maxArgC           = 1<<sizeC - 1
+        listItemsPerFlush = 50 // # list items to accumulate before a setList instruction
+    )
+    */
+
     public const int SizeC = 9;
     public const int SizeB = 9;
     public const int SizeBx = SizeC + SizeB;
@@ -109,20 +109,21 @@ const (
     public const int ListItemsPerFlush = 50; // # list items to accumulate before a setList instruction
 
     /*
-func isConstant(x int) bool   { return 0 != x&bitRK }
-func constantIndex(r int) int { return r & ^bitRK }
-func asConstant(r int) int    { return r | bitRK }
-
-// creates a mask with 'n' 1 bits at position 'p'
-func mask1(n, p uint) instruction { return ^(^instruction(0) << n) << p }
-// creates a mask with 'n' 0 bits at position 'p'
-func mask0(n, p uint) instruction { return ^mask1(n, p) }
-func (i instruction) opCode() opCode         { return opCode(i >> posOp & (1<<sizeOp - 1)) }
-func (i instruction) arg(pos, size uint) int { return int(i >> pos & mask1(size, 0)) }
-func (i *instruction) setOpCode(op opCode)   { i.setArg(posOp, sizeOp, int(op)) }
-func (i *instruction) setArg(pos, size uint, arg int) {
-    *i = *i&mask0(size, pos) | instruction(arg)<<pos&mask1(size, pos)}
-     */
+    func isConstant(x int) bool   { return 0 != x&bitRK }
+    func constantIndex(r int) int { return r & ^bitRK }
+    func asConstant(r int) int    { return r | bitRK }
+
+    // creates a mask with 'n' 1 bits at position 'p'
+    func mask1(n, p uint) instruction { return ^(^instruction(0) << n) << p }
+    // creates a mask with 'n' 0 bits at position 'p'
+    func mask0(n, p uint) instruction { return ^mask1(n, p) }
+    func (i instruction) opCode() opCode         { return opCode(i >> posOp & (1<<sizeOp - 1)) }
+    func (i instruction) arg(pos, size uint) int { return int(i >> pos & mask1(size, 0)) }
+    func (i *instruction) setOpCode(op opCode)   { i.setArg(posOp, sizeOp, int(op)) }
+    func (i *instruction) setArg(pos, size uint, arg int) {
+        *i = *i&mask0(size, pos) | instruction(arg)<<pos&mask1(size, pos)}
+    */
+
     public static bool IsConstant(int x)
     {
         return 0 != (x & BitRK);
@@ -166,16 +167,15 @@ func (i *instruction) setArg(pos, size uint, arg int) {
         Value = (uint)((Value & Mask0(size, pos)) | ((arg << (int)pos) & Mask1(size, pos)));
     }
 
-
     /*
-func (i instruction) a() int   { return int(i >> posA & maxArgA) }
-func (i instruction) b() int   { return int(i >> posB & maxArgB) }
-func (i instruction) c() int   { return int(i >> posC & maxArgC) }
-func (i instruction) bx() int  { return int(i >> posBx & maxArgBx) }
-func (i instruction) ax() int  { return int(i >> posAx & maxArgAx) }
-func (i instruction) sbx() int { return int(i>>posBx&maxArgBx) - maxArgSBx }
-
-     */
+    func (i instruction) a() int   { return int(i >> posA & maxArgA) }
+    func (i instruction) b() int   { return int(i >> posB & maxArgB) }
+    func (i instruction) c() int   { return int(i >> posC & maxArgC) }
+    func (i instruction) bx() int  { return int(i >> posBx & maxArgBx) }
+    func (i instruction) ax() int  { return int(i >> posAx & maxArgAx) }
+    func (i instruction) sbx() int { return int(i>>posBx&maxArgBx) - maxArgSBx }
+    */
+
     public int A
     {
         get => (int)((Value >> PosA) & MaxArgA);
@@ -213,7 +213,6 @@ func (i instruction) sbx() int { return int(i>>posBx&maxArgBx) - maxArgSBx }
     }
 
     /*
-
 func createABC(op opCode, a, b, c int) instruction {
     return instruction(op)<<posOp |
         instruction(a)<<posA |
@@ -228,8 +227,8 @@ func createABx(op opCode, a, bx int) instruction {
 }
 
 func createAx(op opCode, a int) instruction { return instruction(op)<<posOp | instruction(a)<<posAx }
+    */
 
-*/
     public static uint CreateABC(OpCode op, int a, int b, int c)
     {
         return (uint)(((byte)op << PosOp) | (a << PosA) | (b << PosB) | (c << PosC));
@@ -247,39 +246,39 @@ func createAx(op opCode, a int) instruction { return instruction(op)<<posOp | in
 
 
     /*
-
-func (i instruction) String() string {
-    op := i.opCode()
-    s := opNames[op]
-    switch opMode(op) {
-    case iABC:
-        s = fmt.Sprintf("%s %d", s, i.a())
-        if bMode(op) == opArgK && isConstant(i.b()) {
-            s = fmt.Sprintf("%s constant %d", s, constantIndex(i.b()))
-        } else if bMode(op) != opArgN {
-            s = fmt.Sprintf("%s %d", s, i.b())
-        }
-        if cMode(op) == opArgK && isConstant(i.c()) {
-            s = fmt.Sprintf("%s constant %d", s, constantIndex(i.c()))
-        } else if cMode(op) != opArgN {
-            s = fmt.Sprintf("%s %d", s, i.c())
-        }
-    case iAsBx:
-        s = fmt.Sprintf("%s %d", s, i.a())
-        if bMode(op) != opArgN {
-            s = fmt.Sprintf("%s %d", s, i.sbx())
+    func (i instruction) String() string {
+        op := i.opCode()
+        s := opNames[op]
+        switch opMode(op) {
+        case iABC:
+            s = fmt.Sprintf("%s %d", s, i.a())
+            if bMode(op) == opArgK && isConstant(i.b()) {
+                s = fmt.Sprintf("%s constant %d", s, constantIndex(i.b()))
+            } else if bMode(op) != opArgN {
+                s = fmt.Sprintf("%s %d", s, i.b())
+            }
+            if cMode(op) == opArgK && isConstant(i.c()) {
+                s = fmt.Sprintf("%s constant %d", s, constantIndex(i.c()))
+            } else if cMode(op) != opArgN {
+                s = fmt.Sprintf("%s %d", s, i.c())
+            }
+        case iAsBx:
+            s = fmt.Sprintf("%s %d", s, i.a())
+            if bMode(op) != opArgN {
+                s = fmt.Sprintf("%s %d", s, i.sbx())
+            }
+        case iABx:
+            s = fmt.Sprintf("%s %d", s, i.a())
+            if bMode(op) != opArgN {
+                s = fmt.Sprintf("%s %d", s, i.bx())
+            }
+        case iAx:
+            s = fmt.Sprintf("%s %d", s, i.ax())
         }
-    case iABx:
-        s = fmt.Sprintf("%s %d", s, i.a())
-        if bMode(op) != opArgN {
-            s = fmt.Sprintf("%s %d", s, i.bx())
-        }
-    case iAx:
-        s = fmt.Sprintf("%s %d", s, i.ax())
+        return s
     }
-    return s
-}
-*/
+    */
+
     public override string ToString()
     {
         var op = OpCode;
@@ -341,22 +340,23 @@ func (i instruction) String() string {
     }
 
     /*
+    func opmode(t, a, b, c, m int) byte { return byte(t<<7 | a<<6 | b<<4 | c<<2 | m) }
+    */
 
-func opmode(t, a, b, c, m int) byte { return byte(t<<7 | a<<6 | b<<4 | c<<2 | m) }
-*/
     public static byte OpMode(int t, int a, int b, int c, int m)
     {
         return (byte)((t << 7) | (a << 6) | (b << 4) | (c << 2) | m);
     }
 
     /*
-const (
-    opArgN = iota // argument is not used
-    opArgU        // argument is used
-    opArgR        // argument is a register or a jump offset
-    opArgK        // argument is a constant or register/constant
-)
-*/
+    const (
+        opArgN = iota // argument is not used
+        opArgU        // argument is used
+        opArgR        // argument is a register or a jump offset
+        opArgK        // argument is a constant or register/constant
+    )
+    */
+
     public const int OpArgN = 0;
     public const int OpArgU = 1;
     public const int OpArgR = 2;
@@ -364,13 +364,13 @@ const (
     public const int OpArgK = 3;
 
     /*
+    func opMode(m opCode) int     { return int(opModes[m] & 3) }
+    func bMode(m opCode) byte     { return (opModes[m] >> 4) & 3 }
+    func cMode(m opCode) byte     { return (opModes[m] >> 2) & 3 }
+    func testAMode(m opCode) bool { return opModes[m]&(1<<6) != 0 }
+    func testTMode(m opCode) bool { return opModes[m]&(1<<7) != 0 }
+    */
 
-func opMode(m opCode) int     { return int(opModes[m] & 3) }
-func bMode(m opCode) byte     { return (opModes[m] >> 4) & 3 }
-func cMode(m opCode) byte     { return (opModes[m] >> 2) & 3 }
-func testAMode(m opCode) bool { return opModes[m]&(1<<6) != 0 }
-func testTMode(m opCode) bool { return opModes[m]&(1<<7) != 0 }
-*/
     public static int OpMode(OpCode m)
     {
         return (int)(opModes[(byte)m] & 3);
@@ -397,95 +397,96 @@ func testTMode(m opCode) bool { return opModes[m]&(1<<7) != 0 }
     }
 
     /*
-var opModes []byte = []byte{
-//     T  A    B       C     mode		    opcode
-opmode(0, 1, opArgR, opArgN, iABC),  // opMove
-opmode(0, 1, opArgK, opArgN, iABx),  // opLoadConstant
-opmode(0, 1, opArgN, opArgN, iABx),  // opLoadConstantEx
-opmode(0, 1, opArgU, opArgU, iABC),  // opLoadBool
-opmode(0, 1, opArgU, opArgN, iABC),  // opLoadNil
-opmode(0, 1, opArgU, opArgN, iABC),  // opGetUpValue
-opmode(0, 1, opArgU, opArgK, iABC),  // opGetTableUp
-opmode(0, 1, opArgR, opArgK, iABC),  // opGetTable
-opmode(0, 0, opArgK, opArgK, iABC),  // opSetTableUp
-opmode(0, 0, opArgU, opArgN, iABC),  // opSetUpValue
-opmode(0, 0, opArgK, opArgK, iABC),  // opSetTable
-opmode(0, 1, opArgU, opArgU, iABC),  // opNewTable
-opmode(0, 1, opArgR, opArgK, iABC),  // opSelf
-opmode(0, 1, opArgK, opArgK, iABC),  // opAdd
-opmode(0, 1, opArgK, opArgK, iABC),  // opSub
-opmode(0, 1, opArgK, opArgK, iABC),  // opMul
-opmode(0, 1, opArgK, opArgK, iABC),  // opDiv
-opmode(0, 1, opArgK, opArgK, iABC),  // opMod
-opmode(0, 1, opArgK, opArgK, iABC),  // opPow
-opmode(0, 1, opArgR, opArgN, iABC),  // opUnaryMinus
-opmode(0, 1, opArgR, opArgN, iABC),  // opNot
-opmode(0, 1, opArgR, opArgN, iABC),  // opLength
-opmode(0, 1, opArgR, opArgR, iABC),  // opConcat
-opmode(0, 0, opArgR, opArgN, iAsBx), // opJump
-opmode(1, 0, opArgK, opArgK, iABC),  // opEqual
-opmode(1, 0, opArgK, opArgK, iABC),  // opLessThan
-opmode(1, 0, opArgK, opArgK, iABC),  // opLessOrEqual
-opmode(1, 0, opArgN, opArgU, iABC),  // opTest
-opmode(1, 1, opArgR, opArgU, iABC),  // opTestSet
-opmode(0, 1, opArgU, opArgU, iABC),  // opCall
-opmode(0, 1, opArgU, opArgU, iABC),  // opTailCall
-opmode(0, 0, opArgU, opArgN, iABC),  // opReturn
-opmode(0, 1, opArgR, opArgN, iAsBx), // opForLoop
-opmode(0, 1, opArgR, opArgN, iAsBx), // opForPrep
-opmode(0, 0, opArgN, opArgU, iABC),  // opTForCall
-opmode(0, 1, opArgR, opArgN, iAsBx), // opTForLoop
-opmode(0, 0, opArgU, opArgU, iABC),  // opSetList
-opmode(0, 1, opArgU, opArgN, iABx),  // opClosure
-opmode(0, 1, opArgU, opArgN, iABC),  // opVarArg
-opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
-}
- */
+    var opModes []byte = []byte{
+    //     T  A    B       C     mode		    opcode
+    opmode(0, 1, opArgR, opArgN, iABC),  // opMove
+    opmode(0, 1, opArgK, opArgN, iABx),  // opLoadConstant
+    opmode(0, 1, opArgN, opArgN, iABx),  // opLoadConstantEx
+    opmode(0, 1, opArgU, opArgU, iABC),  // opLoadBool
+    opmode(0, 1, opArgU, opArgN, iABC),  // opLoadNil
+    opmode(0, 1, opArgU, opArgN, iABC),  // opGetUpValue
+    opmode(0, 1, opArgU, opArgK, iABC),  // opGetTableUp
+    opmode(0, 1, opArgR, opArgK, iABC),  // opGetTable
+    opmode(0, 0, opArgK, opArgK, iABC),  // opSetTableUp
+    opmode(0, 0, opArgU, opArgN, iABC),  // opSetUpValue
+    opmode(0, 0, opArgK, opArgK, iABC),  // opSetTable
+    opmode(0, 1, opArgU, opArgU, iABC),  // opNewTable
+    opmode(0, 1, opArgR, opArgK, iABC),  // opSelf
+    opmode(0, 1, opArgK, opArgK, iABC),  // opAdd
+    opmode(0, 1, opArgK, opArgK, iABC),  // opSub
+    opmode(0, 1, opArgK, opArgK, iABC),  // opMul
+    opmode(0, 1, opArgK, opArgK, iABC),  // opDiv
+    opmode(0, 1, opArgK, opArgK, iABC),  // opMod
+    opmode(0, 1, opArgK, opArgK, iABC),  // opPow
+    opmode(0, 1, opArgR, opArgN, iABC),  // opUnaryMinus
+    opmode(0, 1, opArgR, opArgN, iABC),  // opNot
+    opmode(0, 1, opArgR, opArgN, iABC),  // opLength
+    opmode(0, 1, opArgR, opArgR, iABC),  // opConcat
+    opmode(0, 0, opArgR, opArgN, iAsBx), // opJump
+    opmode(1, 0, opArgK, opArgK, iABC),  // opEqual
+    opmode(1, 0, opArgK, opArgK, iABC),  // opLessThan
+    opmode(1, 0, opArgK, opArgK, iABC),  // opLessOrEqual
+    opmode(1, 0, opArgN, opArgU, iABC),  // opTest
+    opmode(1, 1, opArgR, opArgU, iABC),  // opTestSet
+    opmode(0, 1, opArgU, opArgU, iABC),  // opCall
+    opmode(0, 1, opArgU, opArgU, iABC),  // opTailCall
+    opmode(0, 0, opArgU, opArgN, iABC),  // opReturn
+    opmode(0, 1, opArgR, opArgN, iAsBx), // opForLoop
+    opmode(0, 1, opArgR, opArgN, iAsBx), // opForPrep
+    opmode(0, 0, opArgN, opArgU, iABC),  // opTForCall
+    opmode(0, 1, opArgR, opArgN, iAsBx), // opTForLoop
+    opmode(0, 0, opArgU, opArgU, iABC),  // opSetList
+    opmode(0, 1, opArgU, opArgN, iABx),  // opClosure
+    opmode(0, 1, opArgU, opArgN, iABC),  // opVarArg
+    opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
+    }
+    */
+
     public static ReadOnlySpan<byte> OpModes => opModes;
 
     static readonly byte[] opModes =
     [
         //         T   A    B         C          mode	opcode]
-        OpMode(0, 1, OpArgR, OpArgN, IABC), // opMove
-        OpMode(0, 1, OpArgK, OpArgN, IABx), // opLoadConstant
-        OpMode(0, 1, OpArgN, OpArgN, IABx), // opLoadConstantEx
-        OpMode(0, 1, OpArgU, OpArgU, IABC), // opLoadBool
-        OpMode(0, 1, OpArgU, OpArgN, IABC), // opLoadNil
-        OpMode(0, 1, OpArgU, OpArgN, IABC), // opGetUpValue
-        OpMode(0, 1, OpArgU, OpArgK, IABC), // opGetTableUp
-        OpMode(0, 1, OpArgR, OpArgK, IABC), // opGetTable
-        OpMode(0, 0, OpArgK, OpArgK, IABC), // opSetTableUp
-        OpMode(0, 0, OpArgU, OpArgN, IABC), // opSetUpValue
-        OpMode(0, 0, OpArgK, OpArgK, IABC), // opSetTable
-        OpMode(0, 1, OpArgU, OpArgU, IABC), // opNewTable
-        OpMode(0, 1, OpArgR, OpArgK, IABC), // opSelf
-        OpMode(0, 1, OpArgK, OpArgK, IABC), // opAdd
-        OpMode(0, 1, OpArgK, OpArgK, IABC), // opSub
-        OpMode(0, 1, OpArgK, OpArgK, IABC), // opMul
-        OpMode(0, 1, OpArgK, OpArgK, IABC), // opDiv
-        OpMode(0, 1, OpArgK, OpArgK, IABC), // opMod
-        OpMode(0, 1, OpArgK, OpArgK, IABC), // opPow
-        OpMode(0, 1, OpArgR, OpArgN, IABC), // opUnaryMinus
-        OpMode(0, 1, OpArgR, OpArgN, IABC), // opNot
-        OpMode(0, 1, OpArgR, OpArgN, IABC), // opLength
-        OpMode(0, 1, OpArgR, OpArgR, IABC), // opConcat
+        OpMode(0, 1, OpArgR, OpArgN, IABC),  // opMove
+        OpMode(0, 1, OpArgK, OpArgN, IABx),  // opLoadConstant
+        OpMode(0, 1, OpArgN, OpArgN, IABx),  // opLoadConstantEx
+        OpMode(0, 1, OpArgU, OpArgU, IABC),  // opLoadBool
+        OpMode(0, 1, OpArgU, OpArgN, IABC),  // opLoadNil
+        OpMode(0, 1, OpArgU, OpArgN, IABC),  // opGetUpValue
+        OpMode(0, 1, OpArgU, OpArgK, IABC),  // opGetTableUp
+        OpMode(0, 1, OpArgR, OpArgK, IABC),  // opGetTable
+        OpMode(0, 0, OpArgK, OpArgK, IABC),  // opSetTableUp
+        OpMode(0, 0, OpArgU, OpArgN, IABC),  // opSetUpValue
+        OpMode(0, 0, OpArgK, OpArgK, IABC),  // opSetTable
+        OpMode(0, 1, OpArgU, OpArgU, IABC),  // opNewTable
+        OpMode(0, 1, OpArgR, OpArgK, IABC),  // opSelf
+        OpMode(0, 1, OpArgK, OpArgK, IABC),  // opAdd
+        OpMode(0, 1, OpArgK, OpArgK, IABC),  // opSub
+        OpMode(0, 1, OpArgK, OpArgK, IABC),  // opMul
+        OpMode(0, 1, OpArgK, OpArgK, IABC),  // opDiv
+        OpMode(0, 1, OpArgK, OpArgK, IABC),  // opMod
+        OpMode(0, 1, OpArgK, OpArgK, IABC),  // opPow
+        OpMode(0, 1, OpArgR, OpArgN, IABC),  // opUnaryMinus
+        OpMode(0, 1, OpArgR, OpArgN, IABC),  // opNot
+        OpMode(0, 1, OpArgR, OpArgN, IABC),  // opLength
+        OpMode(0, 1, OpArgR, OpArgR, IABC),  // opConcat
         OpMode(0, 0, OpArgR, OpArgN, IAsBx), // opJump
-        OpMode(1, 0, OpArgK, OpArgK, IABC), // opEqual
-        OpMode(1, 0, OpArgK, OpArgK, IABC), // opLessThan
-        OpMode(1, 0, OpArgK, OpArgK, IABC), // opLessOrEqual
-        OpMode(1, 0, OpArgN, OpArgU, IABC), // opTest
-        OpMode(1, 1, OpArgR, OpArgU, IABC), // opTestSet
-        OpMode(0, 1, OpArgU, OpArgU, IABC), // opCall
-        OpMode(0, 1, OpArgU, OpArgU, IABC), // opTailCall
-        OpMode(0, 0, OpArgU, OpArgN, IABC), // opReturn
+        OpMode(1, 0, OpArgK, OpArgK, IABC),  // opEqual
+        OpMode(1, 0, OpArgK, OpArgK, IABC),  // opLessThan
+        OpMode(1, 0, OpArgK, OpArgK, IABC),  // opLessOrEqual
+        OpMode(1, 0, OpArgN, OpArgU, IABC),  // opTest
+        OpMode(1, 1, OpArgR, OpArgU, IABC),  // opTestSet
+        OpMode(0, 1, OpArgU, OpArgU, IABC),  // opCall
+        OpMode(0, 1, OpArgU, OpArgU, IABC),  // opTailCall
+        OpMode(0, 0, OpArgU, OpArgN, IABC),  // opReturn
         OpMode(0, 1, OpArgR, OpArgN, IAsBx), // opForLoop
         OpMode(0, 1, OpArgR, OpArgN, IAsBx), // opForPrep
-        OpMode(0, 0, OpArgN, OpArgU, IABC), // opTForCall
+        OpMode(0, 0, OpArgN, OpArgU, IABC),  // opTForCall
         OpMode(0, 1, OpArgR, OpArgN, IAsBx), // opTForLoop
-        OpMode(0, 0, OpArgU, OpArgU, IABC), // opSetList
-        OpMode(0, 1, OpArgU, OpArgN, IABx), // opClosure
-        OpMode(0, 1, OpArgU, OpArgN, IABC), // opVarArg
-        OpMode(0, 0, OpArgU, OpArgU, IAx) // opExtraArg
+        OpMode(0, 0, OpArgU, OpArgU, IABC),  // opSetList
+        OpMode(0, 1, OpArgU, OpArgN, IABx),  // opClosure
+        OpMode(0, 1, OpArgU, OpArgN, IABC),  // opVarArg
+        OpMode(0, 0, OpArgU, OpArgU, IAx)    // opExtraArg
     ];
 
     /// <summary>

+ 4 - 1
src/Lua/Runtime/LuaStack.cs

@@ -1,8 +1,11 @@
 using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
 using Lua.Internal;
 using System.Diagnostics;
 
+#if NET6_0_OR_GREATER
+using System.Runtime.InteropServices;
+#endif
+
 namespace Lua.Runtime;
 
 public sealed class LuaStack(int initialSize = 256)

+ 1 - 3
src/Lua/Runtime/LuaVirtualMachine.Markers.cs

@@ -1,6 +1,4 @@
-using System.Diagnostics.CodeAnalysis;
-using System.Runtime.CompilerServices;
-using Lua.Internal;
+using System.Runtime.CompilerServices;
 using System.Diagnostics;
 
 // ReSharper disable InconsistentNaming

+ 29 - 22
src/Lua/Runtime/LuaVirtualMachine.cs

@@ -350,7 +350,7 @@ public static partial class LuaVirtualMachine
     {
         try
         {
-            // This is a label to restart the execution when new function is called or restarted
+        // This is a label to restart the execution when new function is called or restarted
         Restart:
             ref var instructionsHead = ref Unsafe.AsRef(in context.Prototype.Code[0]);
             var frameBase = context.FrameBase;
@@ -360,8 +360,8 @@ public static partial class LuaVirtualMachine
             ref var lineHookFlag = ref context.State.IsInHook ? ref DummyLineHookEnabled : ref context.State.IsLineHookEnabled;
             ref var hookCount = ref context.State.IsInHook ? ref DummyHookCount : ref context.State.HookCount;
             goto Loop;
-        LineHook:
 
+        LineHook:
             {
                 context.LastHookPc = context.Pc;
                 if (ExecutePerInstructionHook(context))
@@ -411,7 +411,6 @@ public static partial class LuaVirtualMachine
                         {
                             context.Pc++;
                         }
-
                         continue;
                     case OpCode.LoadNil:
                         Markers.LoadNil();
@@ -433,6 +432,7 @@ public static partial class LuaVirtualMachine
                     case OpCode.GetTable:
                         Markers.GetTabUp();
                         Markers.GetTable();
+
                         stackHead = ref stack.FastGet(frameBase);
                         ref readonly var vc = ref RKC(ref stackHead, ref constHead, instruction);
                         ref readonly var vb = ref instruction.OpCode == OpCode.GetTable ? ref Unsafe.Add(ref stackHead, instruction.B) : ref context.LuaClosure.GetUpValueRef(instruction.B);
@@ -453,6 +453,7 @@ public static partial class LuaVirtualMachine
                     case OpCode.SetTable:
                         Markers.SetTabUp();
                         Markers.SetTable();
+
                         stackHead = ref stack.FastGet(frameBase);
                         vb = ref RKB(ref stackHead, ref constHead, instruction);
                         if (vb.TryReadNumber(out var numB))
@@ -498,6 +499,7 @@ public static partial class LuaVirtualMachine
                         continue;
                     case OpCode.Self:
                         Markers.Self();
+
                         stackHead = ref stack.FastGet(frameBase);
                         vc = ref RKC(ref stackHead, ref constHead, instruction);
                         table = Unsafe.Add(ref stackHead, instruction.B);
@@ -529,6 +531,7 @@ public static partial class LuaVirtualMachine
                         Markers.Div();
                         Markers.Mod();
                         Markers.Pow();
+
                         stackHead = ref stack.FastGet(frameBase);
                         vb = ref RKB(ref stackHead, ref constHead, instruction);
                         vc = ref RKC(ref stackHead, ref constHead, instruction);
@@ -615,7 +618,6 @@ public static partial class LuaVirtualMachine
                         Unsafe.Add(ref stackHead, iA) = !Unsafe.Add(ref stackHead, instruction.B).ToBoolean();
                         stack.NotifyTop(iA + frameBase + 1);
                         continue;
-
                     case OpCode.Len:
                         Markers.Len();
                         stackHead = ref stack.FastGet(frameBase);
@@ -644,24 +646,25 @@ public static partial class LuaVirtualMachine
                         Markers.Concat();
                         if (Concat(context))
                         {
-                            //if (doRestart) goto Restart;
+                            // if (doRestart) goto Restart;
                             continue;
                         }
 
                         return true;
                     case OpCode.Jmp:
                         Markers.Jmp();
-                        context.Pc += instruction.SBx;
 
+                        context.Pc += instruction.SBx;
                         if (iA != 0)
                         {
-                            context.State.CloseUpValues( frameBase + iA - 1);
+                            context.State.CloseUpValues(frameBase + iA - 1);
                         }
 
                         context.ThrowIfCancellationRequested();
                         continue;
                     case OpCode.Eq:
                         Markers.Eq();
+
                         stackHead = ref stack.Get(frameBase);
                         vb = ref RKB(ref stackHead, ref constHead, instruction);
                         vc = ref RKC(ref stackHead, ref constHead, instruction);
@@ -690,6 +693,7 @@ public static partial class LuaVirtualMachine
                     case OpCode.Le:
                         Markers.Lt();
                         Markers.Le();
+
                         stackHead = ref stack.Get(frameBase);
                         vb = ref RKB(ref stackHead, ref constHead, instruction);
                         vc = ref RKC(ref stackHead, ref constHead, instruction);
@@ -792,6 +796,7 @@ public static partial class LuaVirtualMachine
                         goto End;
                     case OpCode.ForLoop:
                         Markers.ForLoop();
+
                         ref var indexRef = ref stack.Get(iA + frameBase);
                         var limit = Unsafe.Add(ref indexRef, 1).UnsafeReadDouble();
                         var step = Unsafe.Add(ref indexRef, 2).UnsafeReadDouble();
@@ -837,6 +842,7 @@ public static partial class LuaVirtualMachine
                         continue;
                     case OpCode.TForCall:
                         Markers.TForCall();
+
                         if (TForCall(context, out doRestart))
                         {
                             if (doRestart)
@@ -865,13 +871,16 @@ public static partial class LuaVirtualMachine
                         continue;
                     case OpCode.Closure:
                         Markers.Closure();
+
                         ra1 = iA + frameBase + 1;
                         stack.EnsureCapacity(ra1);
                         stack.Get(ra1 - 1) = new LuaClosure(context.State, context.Prototype.ChildPrototypes[instruction.Bx]);
                         stack.NotifyTop(ra1);
+
                         continue;
                     case OpCode.VarArg:
                         Markers.VarArg();
+
                         VarArg(context);
 
                         [MethodImpl(MethodImplOptions.NoInlining)]
@@ -1175,7 +1184,7 @@ public static partial class LuaVirtualMachine
             state.PushCallStackFrame(newFrame);
             try
             {
-                var functionContext = new LuaFunctionExecutionContext {State = state, ArgumentCount = argCount, ReturnFrameBase = target };
+                var functionContext = new LuaFunctionExecutionContext { State = state, ArgumentCount = argCount, ReturnFrameBase = target };
                 if (state.CallOrReturnHookMask.Value != 0 && !state.IsInHook)
                 {
                     await ExecuteCallHook(functionContext, context.CancellationToken);
@@ -1252,7 +1261,7 @@ public static partial class LuaVirtualMachine
 
         static bool FuncCall(VirtualMachineExecutionContext context, LuaState state, LuaFunction func, int argumentCount, int returnBase)
         {
-            var task = func.Func(new() {State = state, ArgumentCount = argumentCount, ReturnFrameBase = returnBase }, context.CancellationToken);
+            var task = func.Func(new() { State = state, ArgumentCount = argumentCount, ReturnFrameBase = returnBase }, context.CancellationToken);
 
             if (!task.IsCompleted)
             {
@@ -1363,7 +1372,7 @@ public static partial class LuaVirtualMachine
         var isMetamethod = false;
         var state = context.State;
 
-        state.CloseUpValues( context.FrameBase);
+        state.CloseUpValues(context.FrameBase);
 
         var va = stack.Get(RA);
         if (!va.TryReadFunction(out var func))
@@ -1410,7 +1419,7 @@ public static partial class LuaVirtualMachine
         }
 
         doRestart = false;
-        var task = func.Func(new() {State = state, ArgumentCount = argumentCount, ReturnFrameBase = lastFrame.ReturnBase }, context.CancellationToken);
+        var task = func.Func(new() { State = state, ArgumentCount = argumentCount, ReturnFrameBase = lastFrame.ReturnBase }, context.CancellationToken);
 
         if (!task.IsCompleted)
         {
@@ -1496,7 +1505,7 @@ public static partial class LuaVirtualMachine
             return true;
         }
 
-        var task = iterator.Func(new() {State = context.State, ArgumentCount = stack.Count - newBase, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
+        var task = iterator.Func(new() { State = context.State, ArgumentCount = stack.Count - newBase, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
         if (!task.IsCompleted)
         {
             context.PostOperation = PostOperationType.TForCall;
@@ -1665,7 +1674,7 @@ public static partial class LuaVirtualMachine
             return true;
         }
 
-        var task = indexTable.Func(new() {State = context.State, ArgumentCount = 2, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
+        var task = indexTable.Func(new() { State = context.State, ArgumentCount = 2, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
 
         if (!task.IsCompleted)
         {
@@ -1737,7 +1746,7 @@ public static partial class LuaVirtualMachine
         var newFrame = new CallStackFrame { Base = state.Stack.Count - 2 + varArgCount, VariableArgumentCount = varArgCount, Function = indexTable, ReturnBase = top };
 
         state.PushCallStackFrame(newFrame);
-        var functionContext = new LuaFunctionExecutionContext {State = state, ArgumentCount = 2, ReturnFrameBase = top };
+        var functionContext = new LuaFunctionExecutionContext { State = state, ArgumentCount = 2, ReturnFrameBase = top };
         if (state.CallOrReturnHookMask.Value != 0 && !state.IsInHook)
         {
             await ExecuteCallHook(functionContext, ct);
@@ -1988,7 +1997,7 @@ public static partial class LuaVirtualMachine
             }
 
 
-            var task = func.Func(new() {State = context.State, ArgumentCount = argCount, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
+            var task = func.Func(new() { State = context.State, ArgumentCount = argCount, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
 
             if (!task.IsCompleted)
             {
@@ -2044,7 +2053,7 @@ public static partial class LuaVirtualMachine
             state.PushCallStackFrame(newFrame);
             try
             {
-                var functionContext = new LuaFunctionExecutionContext {State = state, ArgumentCount = argCount, ReturnFrameBase = newBase };
+                var functionContext = new LuaFunctionExecutionContext { State = state, ArgumentCount = argCount, ReturnFrameBase = newBase };
                 if (state.CallOrReturnHookMask.Value != 0 && !state.IsInHook)
                 {
                     await ExecuteCallHook(functionContext, ct);
@@ -2115,7 +2124,7 @@ public static partial class LuaVirtualMachine
             }
 
 
-            var task = func.Func(new() {State = context.State, ArgumentCount = argCount, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
+            var task = func.Func(new() { State = context.State, ArgumentCount = argCount, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
 
             if (!task.IsCompleted)
             {
@@ -2178,7 +2187,7 @@ public static partial class LuaVirtualMachine
             state.PushCallStackFrame(newFrame);
             try
             {
-                var functionContext = new LuaFunctionExecutionContext {State = state, ArgumentCount = argCount, ReturnFrameBase = newBase };
+                var functionContext = new LuaFunctionExecutionContext { State = state, ArgumentCount = argCount, ReturnFrameBase = newBase };
                 if (state.CallOrReturnHookMask.Value != 0 && !state.IsInHook)
                 {
                     await ExecuteCallHook(functionContext, cancellationToken);
@@ -2257,7 +2266,7 @@ public static partial class LuaVirtualMachine
                 return true;
             }
 
-            var task = func.Func(new() {State = context.State, ArgumentCount = argCount, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
+            var task = func.Func(new() { State = context.State, ArgumentCount = argCount, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
 
             if (!task.IsCompleted)
             {
@@ -2344,7 +2353,7 @@ public static partial class LuaVirtualMachine
             state.PushCallStackFrame(newFrame);
             try
             {
-                var functionContext = new LuaFunctionExecutionContext {State = state, ArgumentCount = argCount, ReturnFrameBase = newBase };
+                var functionContext = new LuaFunctionExecutionContext { State = state, ArgumentCount = argCount, ReturnFrameBase = newBase };
                 if (state.CallOrReturnHookMask.Value != 0 && !state.IsInHook)
                 {
                     await ExecuteCallHook(functionContext, cancellationToken);
@@ -2503,7 +2512,6 @@ public static partial class LuaVirtualMachine
             state.Stack.SetTop(newBase + argumentCount);
         }
 
-
         // In the case of tailcall, the local variables of the caller are immediately discarded, so there is no need to retain them.
         // Therefore, a call can be made without allocating new registers.
         var currentBase = state.GetCurrentFrame().Base;
@@ -2533,7 +2541,6 @@ public static partial class LuaVirtualMachine
         return context.State;
     }
 
-
     static void GetstateWithCurrentPc(LuaState state, int pc)
     {
         var frame = state.GetCurrentFrame();

+ 18 - 36
src/Lua/Runtime/Metamethods.cs

@@ -24,42 +24,24 @@ public static class Metamethods
 
     internal static (string Name, string Description) GetNameAndDescription(this OpCode opCode)
     {
-        switch (opCode)
+        return opCode switch
         {
-            case OpCode.GetTabUp:
-            case OpCode.GetTable:
-            case OpCode.Self:
-                return (Index, "index");
-            case OpCode.SetTabUp:
-            case OpCode.SetTable:
-                return (NewIndex, "new index");
-            case OpCode.Add:
-                return (Add, "add");
-            case OpCode.Sub:
-                return (Sub, "sub");
-            case OpCode.Mul:
-                return (Mul, "mul");
-            case OpCode.Div:
-                return (Div, "div");
-            case OpCode.Mod:
-                return (Mod, "mod");
-            case OpCode.Pow:
-                return (Pow, "pow");
-            case OpCode.Unm:
-                return (Unm, "unm");
-            case OpCode.Len:
-                return (Len, "get length of");
-            case OpCode.Eq:
-                return (Eq, "eq");
-            case OpCode.Lt:
-                return (Lt, "lt");
-            case OpCode.Le:
-                return (Le, "le");
-            case OpCode.Call:
-                return (Call, "call");
-            case OpCode.Concat:
-                return (Concat, "concatenate");
-            default: return (opCode.ToString(), opCode.ToString());
-        }
+            OpCode.GetTabUp or OpCode.GetTable or OpCode.Self => (Index, "index"),
+            OpCode.SetTabUp or OpCode.SetTable => (NewIndex, "new index"),
+            OpCode.Add => (Add, "add"),
+            OpCode.Sub => (Sub, "sub"),
+            OpCode.Mul => (Mul, "mul"),
+            OpCode.Div => (Div, "div"),
+            OpCode.Mod => (Mod, "mod"),
+            OpCode.Pow => (Pow, "pow"),
+            OpCode.Unm => (Unm, "unm"),
+            OpCode.Len => (Len, "get length of"),
+            OpCode.Eq => (Eq, "eq"),
+            OpCode.Lt => (Lt, "lt"),
+            OpCode.Le => (Le, "le"),
+            OpCode.Call => (Call, "call"),
+            OpCode.Concat => (Concat, "concatenate"),
+            _ => (opCode.ToString(), opCode.ToString()),
+        };
     }
 }

+ 1 - 2
src/Lua/Runtime/Prototype.cs

@@ -31,13 +31,12 @@ public sealed class Prototype(
 
     public ReadOnlySpan<UpValueDesc> UpValues => upValues;
 
-    //public LuaClosure Cache;
+    // public LuaClosure Cache;
     public readonly string ChunkName = chunkName;
     public readonly int LineDefined = lineDefined, LastLineDefined = lastLineDefined;
     public readonly int ParameterCount = parameterCount, MaxStackSize = maxStackSize;
     public readonly bool HasVariableArguments = hasVariableArguments;
 
-
     /// <summary>
     ///  Lua bytecode signature. If the bytes start with this signature, they are considered as Lua bytecode.
     /// </summary>

+ 5 - 8
src/Lua/Runtime/Tracebacks.cs

@@ -5,14 +5,12 @@ namespace Lua.Runtime;
 
 public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
 {
+    readonly CallStackFrame[] stackFramesArray = stackFrames.ToArray();
+
     internal LuaGlobalState GlobalState => state.GlobalState;
 
     public LuaState State => state;
-
     public LuaFunction RootFunc => StackFrames[0].Function;
-
-    readonly CallStackFrame[] stackFramesArray = stackFrames.ToArray();
-
     public ReadOnlySpan<CallStackFrame> StackFrames => stackFramesArray;
 
     internal static void WriteLastLuaTrace(ReadOnlySpan<CallStackFrame> stackFrames, ref PooledList<char> list, int level = 1)
@@ -60,6 +58,7 @@ public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
         get
         {
             var stackFrames = StackFrames;
+
             for (var index = stackFrames.Length - 1; index >= 1; index--)
             {
                 var lastFunc = stackFrames[index - 1].Function;
@@ -77,7 +76,6 @@ public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
                 }
             }
 
-
             return default;
         }
     }
@@ -87,6 +85,7 @@ public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
         get
         {
             var stackFrames = StackFrames;
+
             for (var index = 1; index <= stackFrames.Length; index++)
             {
                 var lastFunc = stackFrames[index - 1].Function;
@@ -184,7 +183,6 @@ public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
                     list.AddRange(intFormatBuffer[..charsWritten]);
                 }
 
-
                 list.AddRange(": in ");
                 if (p.LineDefined == 0)
                 {
@@ -239,7 +237,6 @@ public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
                     }
                 }
 
-
                 list.AddRange("function <");
                 list.AddRange(shortSourceBuffer[..len]);
                 list.AddRange(":");
@@ -249,7 +246,7 @@ public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
                     list.AddRange(">\n");
                 }
 
-            Next: ;
+            Next:;
             }
         }
 

+ 0 - 1
src/Lua/Standard/BasicLibrary.cs

@@ -1,6 +1,5 @@
 using System.Globalization;
 using Lua.Internal;
-using Lua.IO;
 using Lua.Runtime;
 
 // ReSharper disable MethodHasAsyncOverloadWithCancellation

+ 0 - 1
src/Lua/Standard/BitwiseLibrary.cs

@@ -73,7 +73,6 @@ public sealed class BitwiseLibrary
             value &= v;
         }
 
-
         return new(context.Return(value));
     }
 

+ 9 - 13
src/Lua/Standard/DebugLibrary.cs

@@ -304,9 +304,7 @@ public class DebugLibrary
 
         var index = 1; // context.GetArgument<int>(1); //for lua 5.4
         var userValues = iUserData.UserValues;
-        if (index > userValues.Length
-            //index < 1 ||  // for lua 5.4
-           )
+        if (index > userValues.Length /* index < 1 ||  // for lua 5.4 */)
         {
             return new(context.Return(LuaValue.Nil));
         }
@@ -318,11 +316,9 @@ public class DebugLibrary
     {
         var iUserData = context.GetArgument<ILuaUserData>(0);
         var value = context.GetArgument(1);
-        var index = 1; // context.GetArgument<int>(2);// for lua 5.4
+        var index = 1; // context.GetArgument<int>(2); // for lua 5.4
         var userValues = iUserData.UserValues;
-        if (index > userValues.Length
-            //|| index < 1 // for lua 5.4
-           )
+        if (index > userValues.Length /* || index < 1 // for lua 5.4 */)
         {
             return new(context.Return(LuaValue.Nil));
         }
@@ -336,7 +332,7 @@ public class DebugLibrary
         var state = GetLuaThread(context, out var argOffset);
 
         var message = context.GetArgumentOrDefault(argOffset);
-        var level = context.GetArgumentOrDefault<int>(argOffset + 1, argOffset == 0 ? 1 : 0);
+        var level = context.GetArgumentOrDefault(argOffset + 1, argOffset == 0 ? 1 : 0);
 
         if (message.Type is not (LuaValueType.Nil or LuaValueType.String or LuaValueType.Number))
         {
@@ -348,7 +344,7 @@ public class DebugLibrary
             return new(context.Return(LuaValue.Nil));
         }
 
-        if (state is { IsCoroutine: true, LuaTraceback: {} traceback })
+        if (state is { IsCoroutine: true, LuaTraceback: { } traceback })
         {
             return new(context.Return(traceback.ToString(level)));
         }
@@ -454,7 +450,7 @@ public class DebugLibrary
 
     public ValueTask<int> GetHook(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
     {
-        var state = GetLuaThread(context, out var argOffset);
+        var state = GetLuaThread(context, out _);
         if (state.Hook is null)
         {
             return new(context.Return(LuaValue.Nil, LuaValue.Nil, LuaValue.Nil));
@@ -469,9 +465,9 @@ public class DebugLibrary
 
     public ValueTask<int> GetInfo(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
     {
-        //return new(0);
+        // return new(0);
         var state = GetLuaThread(context, out var argOffset);
-        var what = context.GetArgumentOrDefault<string>(argOffset + 1, "flnStu");
+        var what = context.GetArgumentOrDefault(argOffset + 1, "flnStu");
         CallStackFrame? previousFrame = null;
         CallStackFrame? currentFrame = null;
         var pc = 0;
@@ -479,7 +475,7 @@ public class DebugLibrary
 
         if (arg1.TryReadFunction(out var functionToInspect))
         {
-            //what = ">" + what;
+            // what = ">" + what;
         }
         else if (arg1.TryReadNumber(out _))
         {

+ 0 - 1
src/Lua/Standard/FileHandle.cs

@@ -89,7 +89,6 @@ public class FileHandle : ILuaUserData
         return stream.WriteAsync(content, cancellationToken);
     }
 
-
     public long Seek(string whence, long offset)
     {
         return whence switch

+ 0 - 3
src/Lua/Standard/Internal/IOHelper.cs

@@ -1,7 +1,5 @@
-using System.Text;
 using Lua.Internal;
 using Lua.IO;
-using Lua.Runtime;
 
 namespace Lua.Standard.Internal;
 
@@ -37,7 +35,6 @@ static class IOHelper
     }
 
     // TODO: optimize (use IBuffertWrite<byte>, async)
-
     public static async ValueTask<int> WriteAsync(FileHandle file, string name, LuaFunctionExecutionContext context, CancellationToken cancellationToken)
     {
         try

+ 89 - 89
src/Lua/Standard/Internal/MatchState.cs

@@ -176,122 +176,122 @@ class MatchState(LuaState state, string source, string pattern)
 
                 default:
                 Default:
-                {
-                    var ep = ClassEnd(Pattern, pIdx);
-                    if (!SingleMatch(sIdx, pIdx, ep))
                     {
-                        if (ep < Pattern.Length && Pattern[ep] is '*' or '?' or '-')
+                        var ep = ClassEnd(Pattern, pIdx);
+                        if (!SingleMatch(sIdx, pIdx, ep))
                         {
-                            pIdx = ep + 1;
-                            goto Init; // Continue the while loop with updated pIdx
+                            if (ep < Pattern.Length && Pattern[ep] is '*' or '?' or '-')
+                            {
+                                pIdx = ep + 1;
+                                goto Init; // Continue the while loop with updated pIdx
+                            }
+                            else
+                            {
+                                MatchDepth++;
+                                return -1;
+                            }
                         }
                         else
                         {
-                            MatchDepth++;
-                            return -1;
-                        }
-                    }
-                    else
-                    {
-                        if (ep >= Pattern.Length)
-                        {
-                            // No quantifier, we matched one occurrence
-                            sIdx++;
-                            pIdx = ep; // Move past this pattern element
-                            goto Init; // Continue matching with the rest of the pattern
-                        }
+                            if (ep >= Pattern.Length)
+                            {
+                                // No quantifier, we matched one occurrence
+                                sIdx++;
+                                pIdx = ep; // Move past this pattern element
+                                goto Init; // Continue matching with the rest of the pattern
+                            }
 
-                        switch (Pattern[ep])
-                        {
-                            case '?':
-                                {
-                                    // Try matching with this character
-                                    var res = Match(sIdx + 1, ep + 1);
-                                    if (res >= 0)
+                            switch (Pattern[ep])
+                            {
+                                case '?':
                                     {
-                                        MatchDepth++;
-                                        return res;
-                                    }
+                                        // Try matching with this character
+                                        var res = Match(sIdx + 1, ep + 1);
+                                        if (res >= 0)
+                                        {
+                                            MatchDepth++;
+                                            return res;
+                                        }
 
-                                    pIdx = ep + 1;
-                                    goto Init;
-                                }
+                                        pIdx = ep + 1;
+                                        goto Init;
+                                    }
 
-                            case '+':
-                                // For +, we need at least one match (already verified)
-                                // Skip the first match we already verified
-                                sIdx++;
-                                // Now match zero or more additional occurrences
-                                goto case '*';
+                                case '+':
+                                    // For +, we need at least one match (already verified)
+                                    // Skip the first match we already verified
+                                    sIdx++;
+                                    // Now match zero or more additional occurrences
+                                    goto case '*';
 
-                            case '*':
-                                // Match zero or more occurrences
-                                {
+                                case '*':
+                                    // Match zero or more occurrences
                                     {
-                                        var i = 0;
-                                        // Count how many we can match
-                                        while (sIdx + i < Source.Length && SingleMatch(sIdx + i, pIdx, ep))
                                         {
-                                            i++;
-                                        }
+                                            var i = 0;
+                                            // Count how many we can match
+                                            while (sIdx + i < Source.Length && SingleMatch(sIdx + i, pIdx, ep))
+                                            {
+                                                i++;
+                                            }
 
-                                        // Try matching from longest to shortest
-                                        while (i >= 0)
-                                        {
-                                            var res = Match(sIdx + i, ep + 1);
-                                            if (res >= 0)
+                                            // Try matching from longest to shortest
+                                            while (i >= 0)
                                             {
-                                                MatchDepth++;
-                                                return res;
+                                                var res = Match(sIdx + i, ep + 1);
+                                                if (res >= 0)
+                                                {
+                                                    MatchDepth++;
+                                                    return res;
+                                                }
+
+                                                i--;
                                             }
 
-                                            i--;
+                                            MatchDepth++;
+                                            return -1;
                                         }
-
-                                        MatchDepth++;
-                                        return -1;
                                     }
-                                }
 
-                            case '-':
-                                // Match zero or more occurrences (minimal)
-                                {
-                                    // for (;;) {
-                                    //     const char *res = match(ms, s, ep+1);
-                                    //     if (res != NULL)
-                                    //         return res;
-                                    //     else if (singlematch(ms, s, p, ep))
-                                    //         s++;  /* try with one more repetition */
-                                    //     else return NULL;
-                                    // }
-                                    while (true)
+                                case '-':
+                                    // Match zero or more occurrences (minimal)
                                     {
-                                        var res = Match(sIdx, ep + 1);
-                                        if (res >= 0)
+                                        // for (;;) {
+                                        //     const char *res = match(ms, s, ep+1);
+                                        //     if (res != NULL)
+                                        //         return res;
+                                        //     else if (singlematch(ms, s, p, ep))
+                                        //         s++;  /* try with one more repetition */
+                                        //     else return NULL;
+                                        // }
+                                        while (true)
                                         {
-                                            MatchDepth++;
-                                            return res;
-                                        }
+                                            var res = Match(sIdx, ep + 1);
+                                            if (res >= 0)
+                                            {
+                                                MatchDepth++;
+                                                return res;
+                                            }
 
-                                        if (SingleMatch(sIdx, pIdx, ep))
-                                        {
-                                            sIdx++; // Try with one more repetition
-                                        }
-                                        else
-                                        {
-                                            MatchDepth++;
-                                            return -1; // No match found
+                                            if (SingleMatch(sIdx, pIdx, ep))
+                                            {
+                                                sIdx++; // Try with one more repetition
+                                            }
+                                            else
+                                            {
+                                                MatchDepth++;
+                                                return -1; // No match found
+                                            }
                                         }
                                     }
-                                }
 
-                            default:
-                                sIdx++;
-                                pIdx = ep;
-                                goto Init; // Continue the while loop
+                                default:
+                                    sIdx++;
+                                    pIdx = ep;
+                                    goto Init; // Continue the while loop
+                            }
                         }
                     }
-                }
             }
         }
 

+ 0 - 2
src/Lua/Standard/OpenLibsExtensions.cs

@@ -1,4 +1,3 @@
-using Lua.IO;
 using Lua.Runtime;
 
 namespace Lua.Standard;
@@ -156,7 +155,6 @@ public static class OpenLibsExtensions
         globalState.LoadedModules["table"] = table;
     }
 
-
     public static void OpenDebugLibrary(this LuaState state)
     {
         var globalState = state.GlobalState;

+ 0 - 3
src/Lua/Standard/TableLibrary.cs

@@ -1,7 +1,5 @@
-using Lua.CodeAnalysis;
 using Lua.Internal;
 using System.Runtime.CompilerServices;
-using System.Text;
 using Lua.Runtime;
 using System.Globalization;
 
@@ -11,7 +9,6 @@ public sealed class TableLibrary
 {
     public static readonly TableLibrary Instance = new();
 
-
     public TableLibrary()
     {
         var libraryName = "table";