Browse Source

refactor: change editorconfig and cleanup code

Akeit0 4 months ago
parent
commit
48411ed9c6
100 changed files with 3400 additions and 2014 deletions
  1. 5 5
      .editorconfig
  2. 14 14
      Lua.slnx
  3. 1 1
      sandbox/Benchmark/BenchmarkCore.cs
  4. 1 2
      sandbox/ConsoleApp1/ConsoleApp1.csproj
  5. 25 7
      sandbox/ConsoleApp1/LVec3.cs
  6. 1 1
      sandbox/ConsoleApp2/ConsoleApp2.csproj
  7. 1 1
      src/Lua.SourceGenerator/Comparer.cs
  8. 99 44
      src/Lua.SourceGenerator/LuaObjectGenerator.Emit.cs
  9. 2 2
      src/Lua.SourceGenerator/LuaObjectMetamethod.cs
  10. 2 2
      src/Lua.SourceGenerator/MethodMetadata.cs
  11. 6 2
      src/Lua.SourceGenerator/SymbolReferences.cs
  12. 24 6
      src/Lua.SourceGenerator/TypeMetadata.cs
  13. 26 6
      src/Lua.SourceGenerator/Utilities/CodeBuilder.cs
  14. 3 5
      src/Lua.SourceGenerator/Utilities/RoslynAnalyzerExtensions.cs
  15. 1 1
      src/Lua.SourceGenerator/Utilities/SymbolExtensions.cs
  16. 4 1
      src/Lua/CodeAnalysis/Compilation/BomUtility.cs
  17. 26 12
      src/Lua/CodeAnalysis/Compilation/Declarements.cs
  18. 63 28
      src/Lua/CodeAnalysis/Compilation/Dump.cs
  19. 130 38
      src/Lua/CodeAnalysis/Compilation/Function.cs
  20. 55 30
      src/Lua/CodeAnalysis/Compilation/Parser.cs
  21. 16 3
      src/Lua/CodeAnalysis/Compilation/PrototypeBuilder.cs
  22. 127 54
      src/Lua/CodeAnalysis/Compilation/Scanner.cs
  23. 1 1
      src/Lua/CodeAnalysis/Compilation/TempBlock.cs
  24. 9 2
      src/Lua/CodeAnalysis/Compilation/Token.cs
  25. 5 1
      src/Lua/CodeAnalysis/SourcePosition.cs
  26. 37 10
      src/Lua/CodeAnalysis/Syntax/DisplayStringSyntaxVisitor.cs
  27. 1 1
      src/Lua/CodeAnalysis/Syntax/Keywords.cs
  28. 61 19
      src/Lua/CodeAnalysis/Syntax/Lexer.cs
  29. 2 2
      src/Lua/CodeAnalysis/Syntax/LuaSyntaxTree.cs
  30. 3 3
      src/Lua/CodeAnalysis/Syntax/Nodes/BinaryExpressionNode.cs
  31. 3 3
      src/Lua/CodeAnalysis/Syntax/Nodes/UnaryExpressionNode.cs
  32. 1 1
      src/Lua/CodeAnalysis/Syntax/OperatorPrecedence.cs
  33. 97 56
      src/Lua/CodeAnalysis/Syntax/Parser.cs
  34. 251 65
      src/Lua/CodeAnalysis/Syntax/SyntaxToken.cs
  35. 47 8
      src/Lua/CodeAnalysis/Syntax/SyntaxTokenEnumerator.cs
  36. 36 12
      src/Lua/Exceptions.cs
  37. 8 5
      src/Lua/IO/BufferedOutputStream.cs
  38. 11 5
      src/Lua/IO/CompositeLoaderFileSystem.cs
  39. 12 11
      src/Lua/IO/ConsoleStandardIO.cs
  40. 75 67
      src/Lua/IO/FileSystem.cs
  41. 2 2
      src/Lua/IO/ILuaFileLoader.cs
  42. 9 7
      src/Lua/IO/ILuaFileSystem.cs
  43. 67 65
      src/Lua/IO/ILuaStream.cs
  44. 1 1
      src/Lua/IO/LuaFileBufferingMode.cs
  45. 16 10
      src/Lua/IO/LuaFileOpenMode.cs
  46. 14 7
      src/Lua/IO/LuaStream.cs
  47. 31 15
      src/Lua/IO/MemoryStreams.cs
  48. 13 11
      src/Lua/IO/NumberReaderHelper.cs
  49. 53 37
      src/Lua/IO/StandardIOStream.cs
  50. 1 1
      src/Lua/Internal/BitFlags.cs
  51. 2 2
      src/Lua/Internal/CompilerServices/LightAsyncTaskMethodBuilder.cs
  52. 163 145
      src/Lua/Internal/CompilerServices/StateMachineRunner.cs
  53. 1 1
      src/Lua/Internal/Constants.cs
  54. 9 5
      src/Lua/Internal/EnumerableEx.cs
  55. 63 63
      src/Lua/Internal/FarmHash.cs
  56. 29 8
      src/Lua/Internal/FastListCore.cs
  57. 12 15
      src/Lua/Internal/FastStackCore.cs
  58. 40 21
      src/Lua/Internal/HexConverter.cs
  59. 115 41
      src/Lua/Internal/LuaDebug.cs
  60. 382 347
      src/Lua/Internal/LuaValueDictionary.cs
  61. 9 3
      src/Lua/Internal/MathEx.cs
  62. 1 1
      src/Lua/Internal/MemoryMarshalEx.cs
  63. 2 2
      src/Lua/Internal/Pool.cs
  64. 17 9
      src/Lua/Internal/PooledList.cs
  65. 28 8
      src/Lua/Internal/ReversedStack.cs
  66. 33 15
      src/Lua/Internal/StringHelper.cs
  67. 96 46
      src/Lua/Internal/Utf8Reader.cs
  68. 269 242
      src/Lua/Internal/ValueStringBuilder.cs
  69. 5 4
      src/Lua/Internal/ValueTaskEx.cs
  70. 4 1
      src/Lua/Loaders/CompositeModuleLoader.cs
  71. 11 5
      src/Lua/LuaCoroutine.cs
  72. 5 0
      src/Lua/LuaFunctionExecutionContext.cs
  73. 12 3
      src/Lua/LuaModule.cs
  74. 1 1
      src/Lua/LuaObjectMetamethod.cs
  75. 21 8
      src/Lua/LuaState.cs
  76. 1 1
      src/Lua/LuaStateExtensions.cs
  77. 31 15
      src/Lua/LuaTable.cs
  78. 11 7
      src/Lua/LuaThread.cs
  79. 1 1
      src/Lua/LuaThreadStatus.cs
  80. 6 1
      src/Lua/LuaTopValuesReader.cs
  81. 2 1
      src/Lua/LuaUserData.cs
  82. 3 2
      src/Lua/LuaUserThread.cs
  83. 63 12
      src/Lua/LuaValue.cs
  84. 5 5
      src/Lua/Platforms/LuaPlatform.cs
  85. 17 18
      src/Lua/Platforms/SystemOsEnvironment.cs
  86. 3 2
      src/Lua/Runtime/CallStackFrame.cs
  87. 136 128
      src/Lua/Runtime/Instruction.cs
  88. 14 15
      src/Lua/Runtime/Lease.cs
  89. 7 3
      src/Lua/Runtime/LuaClosure.cs
  90. 27 8
      src/Lua/Runtime/LuaStack.cs
  91. 5 5
      src/Lua/Runtime/LuaThreadAccess.cs
  92. 1 1
      src/Lua/Runtime/LuaThreadAccessExtensions.cs
  93. 1 1
      src/Lua/Runtime/LuaValueRuntimeExtensions.cs
  94. 7 7
      src/Lua/Runtime/LuaVirtualMachine.Debug.cs
  95. 174 64
      src/Lua/Runtime/LuaVirtualMachine.cs
  96. 13 2
      src/Lua/Runtime/Prototype.cs
  97. 12 5
      src/Lua/Runtime/Tracebacks.cs
  98. 20 10
      src/Lua/Standard/BasicLibrary.cs
  99. 9 9
      src/Lua/Standard/BitwiseLibrary.cs
  100. 2 2
      src/Lua/Standard/CoroutineLibrary.cs

+ 5 - 5
.editorconfig

@@ -39,7 +39,7 @@ dotnet_style_parentheses_in_other_operators = never_if_unnecessary
 dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity
 dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity
 
 
 # Modifier preferences
 # Modifier preferences
-dotnet_style_require_accessibility_modifiers = for_non_interface_members
+dotnet_style_require_accessibility_modifiers = omit_if_default
 
 
 # Expression-level preferences
 # Expression-level preferences
 dotnet_style_coalesce_expression = true
 dotnet_style_coalesce_expression = true
@@ -77,9 +77,9 @@ dotnet_style_allow_statement_immediately_after_block_experimental = true
 #### C# Coding Conventions ####
 #### C# Coding Conventions ####
 
 
 # var preferences
 # var preferences
-csharp_style_var_elsewhere = false
-csharp_style_var_for_built_in_types = false
-csharp_style_var_when_type_is_apparent = false
+csharp_style_var_elsewhere = true
+csharp_style_var_for_built_in_types = true
+csharp_style_var_when_type_is_apparent = true
 
 
 # Expression-bodied members
 # Expression-bodied members
 csharp_style_expression_bodied_accessors = true
 csharp_style_expression_bodied_accessors = true
@@ -111,7 +111,7 @@ csharp_style_prefer_readonly_struct_member = true
 # Code-block preferences
 # Code-block preferences
 csharp_prefer_braces = true
 csharp_prefer_braces = true
 csharp_prefer_simple_using_statement = true
 csharp_prefer_simple_using_statement = true
-csharp_style_namespace_declarations = block_scoped
+csharp_style_namespace_declarations = file_scoped
 csharp_style_prefer_method_group_conversion = true
 csharp_style_prefer_method_group_conversion = true
 csharp_style_prefer_primary_constructors = true
 csharp_style_prefer_primary_constructors = true
 csharp_style_prefer_top_level_statements = true
 csharp_style_prefer_top_level_statements = true

+ 14 - 14
Lua.slnx

@@ -1,16 +1,16 @@
 <Solution>
 <Solution>
-  <Folder Name="/sandbox/">
-    <File Path="sandbox/ConsoleApp2/.gitignore" />
-    <Project Path="sandbox/Benchmark/Benchmark.csproj" />
-    <Project Path="sandbox/ConsoleApp1/ConsoleApp1.csproj" />
-    <Project Path="sandbox/ConsoleApp2/ConsoleApp2.csproj" />
-    <Project Path="sandbox/JitTest/JitTest.csproj" />
-  </Folder>
-  <Folder Name="/src/">
-    <Project Path="src/Lua.SourceGenerator/Lua.SourceGenerator.csproj" />
-    <Project Path="src/Lua/Lua.csproj" />
-  </Folder>
-  <Folder Name="/tests/">
-    <Project Path="tests/Lua.Tests/Lua.Tests.csproj" />
-  </Folder>
+    <Folder Name="/sandbox/">
+        <File Path="sandbox/ConsoleApp2/.gitignore"/>
+        <Project Path="sandbox/Benchmark/Benchmark.csproj"/>
+        <Project Path="sandbox/ConsoleApp1/ConsoleApp1.csproj"/>
+        <Project Path="sandbox/ConsoleApp2/ConsoleApp2.csproj"/>
+        <Project Path="sandbox/JitTest/JitTest.csproj"/>
+    </Folder>
+    <Folder Name="/src/">
+        <Project Path="src/Lua.SourceGenerator/Lua.SourceGenerator.csproj"/>
+        <Project Path="src/Lua/Lua.csproj"/>
+    </Folder>
+    <Folder Name="/tests/">
+        <Project Path="tests/Lua.Tests/Lua.Tests.csproj"/>
+    </Folder>
 </Solution>
 </Solution>

+ 1 - 1
sandbox/Benchmark/BenchmarkCore.cs

@@ -18,7 +18,7 @@ public class BenchmarkCore : IDisposable
     public void Setup(string fileName)
     public void Setup(string fileName)
     {
     {
         // moonsharp
         // moonsharp
-        moonSharpState = new Script();
+        moonSharpState = new();
         Script.WarmUp();
         Script.WarmUp();
 
 
         // NLua
         // NLua

+ 1 - 2
sandbox/ConsoleApp1/ConsoleApp1.csproj

@@ -10,11 +10,10 @@
 
 
     <PropertyGroup>
     <PropertyGroup>
         <OutputType>Exe</OutputType>
         <OutputType>Exe</OutputType>
-        <TargetFramework>net8.0</TargetFramework>
+        <TargetFramework>net9.0</TargetFramework>
         <LangVersion>13</LangVersion>
         <LangVersion>13</LangVersion>
         <ImplicitUsings>enable</ImplicitUsings>
         <ImplicitUsings>enable</ImplicitUsings>
         <Nullable>enable</Nullable>
         <Nullable>enable</Nullable>
-
         <EmitCompilerGeneratedFiles>false</EmitCompilerGeneratedFiles>
         <EmitCompilerGeneratedFiles>false</EmitCompilerGeneratedFiles>
         <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
         <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
     </PropertyGroup>
     </PropertyGroup>

+ 25 - 7
sandbox/ConsoleApp1/LVec3.cs

@@ -9,28 +9,46 @@ public partial class LVec3
     [LuaMember("x")]
     [LuaMember("x")]
     public float X
     public float X
     {
     {
-        get => value.X;
-        set => this.value = this.value with { X = value };
+        get
+        {
+            return value.X;
+        }
+        set
+        {
+            this.value = this.value with { X = value };
+        }
     }
     }
 
 
     [LuaMember("y")]
     [LuaMember("y")]
     public float Y
     public float Y
     {
     {
-        get => value.Y;
-        set => this.value = this.value with { Y = value };
+        get
+        {
+            return value.Y;
+        }
+        set
+        {
+            this.value = this.value with { Y = value };
+        }
     }
     }
 
 
     [LuaMember("z")]
     [LuaMember("z")]
     public float Z
     public float Z
     {
     {
-        get => value.Z;
-        set => this.value = this.value with { Z = value };
+        get
+        {
+            return value.Z;
+        }
+        set
+        {
+            this.value = this.value with { Z = value };
+        }
     }
     }
 
 
     [LuaMember("create")]
     [LuaMember("create")]
     public static LVec3 Create(float x, float y, float z)
     public static LVec3 Create(float x, float y, float z)
     {
     {
-        return new LVec3() { value = new Vector3(x, y, z) };
+        return new() { value = new(x, y, z) };
     }
     }
 
 
     public override string ToString()
     public override string ToString()

+ 1 - 1
sandbox/ConsoleApp2/ConsoleApp2.csproj

@@ -9,7 +9,7 @@
     </PropertyGroup>
     </PropertyGroup>
 
 
     <ItemGroup>
     <ItemGroup>
-      <ProjectReference Include="..\..\src\Lua\Lua.csproj" />
+        <ProjectReference Include="..\..\src\Lua\Lua.csproj"/>
     </ItemGroup>
     </ItemGroup>
 
 
 </Project>
 </Project>

+ 1 - 1
src/Lua.SourceGenerator/Comparer.cs

@@ -2,7 +2,7 @@ using Microsoft.CodeAnalysis;
 
 
 namespace Lua.SourceGenerator;
 namespace Lua.SourceGenerator;
 
 
-internal sealed class Comparer : IEqualityComparer<(GeneratorAttributeSyntaxContext, Compilation)>
+sealed class Comparer : IEqualityComparer<(GeneratorAttributeSyntaxContext, Compilation)>
 {
 {
     public static readonly Comparer Instance = new();
     public static readonly Comparer Instance = new();
 
 

+ 99 - 44
src/Lua.SourceGenerator/LuaObjectGenerator.Emit.cs

@@ -6,10 +6,10 @@ namespace Lua.SourceGenerator;
 
 
 partial class LuaObjectGenerator
 partial class LuaObjectGenerator
 {
 {
-    static string GetLuaValuePrefix(ITypeSymbol typeSymbol, SymbolReferences references,Compilation compilation)
+    static string GetLuaValuePrefix(ITypeSymbol typeSymbol, SymbolReferences references, Compilation compilation)
     {
     {
-        return compilation.ClassifyCommonConversion(typeSymbol, references.LuaUserData).Exists 
-            ? "global::Lua.LuaValue.FromUserData(" 
+        return compilation.ClassifyCommonConversion(typeSymbol, references.LuaUserData).Exists
+            ? "global::Lua.LuaValue.FromUserData("
             : "(";
             : "(";
     }
     }
 
 
@@ -82,24 +82,24 @@ partial class LuaObjectGenerator
                 (true, true) => "record struct",
                 (true, true) => "record struct",
                 (true, false) => "record",
                 (true, false) => "record",
                 (false, true) => "struct",
                 (false, true) => "struct",
-                (false, false) => "class",
+                (false, false) => "class"
             };
             };
 
 
             using var _ = builder.BeginBlockScope($"partial {typeDeclarationKeyword} {typeMetadata.TypeName} : global::Lua.ILuaUserData");
             using var _ = builder.BeginBlockScope($"partial {typeDeclarationKeyword} {typeMetadata.TypeName} : global::Lua.ILuaUserData");
 
 
             var metamethodSet = new HashSet<LuaObjectMetamethod>();
             var metamethodSet = new HashSet<LuaObjectMetamethod>();
 
 
-            if (!TryEmitMethods(typeMetadata, builder, references,compilation, metamethodSet, context))
+            if (!TryEmitMethods(typeMetadata, builder, references, compilation, metamethodSet, context))
             {
             {
                 return false;
                 return false;
             }
             }
 
 
-            if (!TryEmitIndexMetamethod(typeMetadata, builder,references,compilation, context))
+            if (!TryEmitIndexMetamethod(typeMetadata, builder, references, compilation, context))
             {
             {
                 return false;
                 return false;
             }
             }
 
 
-            if (!TryEmitNewIndexMetamethod(typeMetadata, builder,references, context))
+            if (!TryEmitNewIndexMetamethod(typeMetadata, builder, references, context))
             {
             {
                 return false;
                 return false;
             }
             }
@@ -116,7 +116,10 @@ partial class LuaObjectGenerator
                 builder.AppendLine("return  global::Lua.LuaValue.FromUserData(value);");
                 builder.AppendLine("return  global::Lua.LuaValue.FromUserData(value);");
             }
             }
 
 
-            if (!ns.IsGlobalNamespace) builder.EndBlock();
+            if (!ns.IsGlobalNamespace)
+            {
+                builder.EndBlock();
+            }
 
 
             builder.AppendLine("#pragma warning restore CS0162 // Unreachable code");
             builder.AppendLine("#pragma warning restore CS0162 // Unreachable code");
             builder.AppendLine("#pragma warning restore CS0219 // Variable assigned but never used");
             builder.AppendLine("#pragma warning restore CS0219 // Variable assigned but never used");
@@ -139,10 +142,25 @@ partial class LuaObjectGenerator
 
 
         foreach (var property in typeMetadata.Properties)
         foreach (var property in typeMetadata.Properties)
         {
         {
-            if (SymbolEqualityComparer.Default.Equals(property.Type, references.LuaValue)) continue;
-            if (SymbolEqualityComparer.Default.Equals(property.Type, references.LuaUserData)) continue;
-            if (SymbolEqualityComparer.Default.Equals(property.Type, typeMetadata.Symbol)) continue;
-            if(compilation.ClassifyConversion(property.Type, references.LuaUserData).Exists)continue;
+            if (SymbolEqualityComparer.Default.Equals(property.Type, references.LuaValue))
+            {
+                continue;
+            }
+
+            if (SymbolEqualityComparer.Default.Equals(property.Type, references.LuaUserData))
+            {
+                continue;
+            }
+
+            if (SymbolEqualityComparer.Default.Equals(property.Type, typeMetadata.Symbol))
+            {
+                continue;
+            }
+
+            if (compilation.ClassifyConversion(property.Type, references.LuaUserData).Exists)
+            {
+                continue;
+            }
 
 
             var conversion = compilation.ClassifyConversion(property.Type, references.LuaValue);
             var conversion = compilation.ClassifyConversion(property.Type, references.LuaValue);
             if (!conversion.Exists && (property.Type is not INamedTypeSymbol namedTypeSymbol || !metaDict.ContainsKey(namedTypeSymbol)))
             if (!conversion.Exists && (property.Type is not INamedTypeSymbol namedTypeSymbol || !metaDict.ContainsKey(namedTypeSymbol)))
@@ -165,15 +183,33 @@ partial class LuaObjectGenerator
                 if (method.IsAsync)
                 if (method.IsAsync)
                 {
                 {
                     var namedType = (INamedTypeSymbol)typeSymbol;
                     var namedType = (INamedTypeSymbol)typeSymbol;
-                    if (namedType.TypeArguments.Length == 0) goto PARAMETERS;
+                    if (namedType.TypeArguments.Length == 0)
+                    {
+                        goto PARAMETERS;
+                    }
 
 
                     typeSymbol = namedType.TypeArguments[0];
                     typeSymbol = namedType.TypeArguments[0];
                 }
                 }
 
 
-                if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaValue)) goto PARAMETERS;
-                if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaUserData)) goto PARAMETERS;
-                if (SymbolEqualityComparer.Default.Equals(typeSymbol, typeMetadata.Symbol)) goto PARAMETERS;
-                if(compilation.ClassifyConversion(typeSymbol, references.LuaUserData).Exists) goto PARAMETERS;
+                if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaValue))
+                {
+                    goto PARAMETERS;
+                }
+
+                if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaUserData))
+                {
+                    goto PARAMETERS;
+                }
+
+                if (SymbolEqualityComparer.Default.Equals(typeSymbol, typeMetadata.Symbol))
+                {
+                    goto PARAMETERS;
+                }
+
+                if (compilation.ClassifyConversion(typeSymbol, references.LuaUserData).Exists)
+                {
+                    goto PARAMETERS;
+                }
 
 
                 var conversion = compilation.ClassifyConversion(typeSymbol, references.LuaValue);
                 var conversion = compilation.ClassifyConversion(typeSymbol, references.LuaValue);
                 if (!conversion.Exists && (typeSymbol is not INamedTypeSymbol namedTypeSymbol || !metaDict.ContainsKey(namedTypeSymbol)))
                 if (!conversion.Exists && (typeSymbol is not INamedTypeSymbol namedTypeSymbol || !metaDict.ContainsKey(namedTypeSymbol)))
@@ -188,18 +224,34 @@ partial class LuaObjectGenerator
             }
             }
 
 
         PARAMETERS:
         PARAMETERS:
-            for (int index = 0; index < method.Symbol.Parameters.Length; index++)
+            for (var index = 0; index < method.Symbol.Parameters.Length; index++)
             {
             {
-                IParameterSymbol? parameterSymbol = method.Symbol.Parameters[index];
+                var parameterSymbol = method.Symbol.Parameters[index];
                 var typeSymbol = parameterSymbol.Type;
                 var typeSymbol = parameterSymbol.Type;
-                if(index == method.Symbol.Parameters.Length - 1 && SymbolEqualityComparer.Default.Equals(typeSymbol, references.CancellationToken))
+                if (index == method.Symbol.Parameters.Length - 1 && SymbolEqualityComparer.Default.Equals(typeSymbol, references.CancellationToken))
+                {
+                    continue;
+                }
+
+                if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaValue))
+                {
+                    continue;
+                }
+
+                if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaUserData))
+                {
+                    continue;
+                }
+
+                if (SymbolEqualityComparer.Default.Equals(typeSymbol, typeMetadata.Symbol))
+                {
+                    continue;
+                }
+
+                if (compilation.ClassifyConversion(typeSymbol, references.LuaUserData).Exists)
                 {
                 {
                     continue;
                     continue;
                 }
                 }
-                if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaValue)) continue;
-                if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaUserData)) continue;
-                if (SymbolEqualityComparer.Default.Equals(typeSymbol, typeMetadata.Symbol)) continue;
-                if(compilation.ClassifyConversion(typeSymbol, references.LuaUserData).Exists) continue;
 
 
                 var conversion = compilation.ClassifyConversion(typeSymbol, references.LuaValue);
                 var conversion = compilation.ClassifyConversion(typeSymbol, references.LuaValue);
                 if (!conversion.Exists && (typeSymbol is not INamedTypeSymbol namedTypeSymbol || !metaDict.ContainsKey(namedTypeSymbol)))
                 if (!conversion.Exists && (typeSymbol is not INamedTypeSymbol namedTypeSymbol || !metaDict.ContainsKey(namedTypeSymbol)))
@@ -217,7 +269,7 @@ partial class LuaObjectGenerator
         return isValid;
         return isValid;
     }
     }
 
 
-    static bool TryEmitIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builder, SymbolReferences references, Compilation compilation,in SourceProductionContext context)
+    static bool TryEmitIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builder, SymbolReferences references, Compilation compilation, in SourceProductionContext context)
     {
     {
         builder.AppendLine(@"static readonly global::Lua.LuaFunction __metamethod_index = new global::Lua.LuaFunction(""index"", (context, ct) =>");
         builder.AppendLine(@"static readonly global::Lua.LuaFunction __metamethod_index = new global::Lua.LuaFunction(""index"", (context, ct) =>");
 
 
@@ -231,7 +283,7 @@ partial class LuaObjectGenerator
             {
             {
                 foreach (var propertyMetadata in typeMetadata.Properties)
                 foreach (var propertyMetadata in typeMetadata.Properties)
                 {
                 {
-                    var conversionPrefix =GetLuaValuePrefix(propertyMetadata.Type,references,compilation);
+                    var conversionPrefix = GetLuaValuePrefix(propertyMetadata.Type, references, compilation);
                     if (propertyMetadata.IsStatic)
                     if (propertyMetadata.IsStatic)
                     {
                     {
                         builder.AppendLine(@$"""{propertyMetadata.LuaMemberName}"" => {conversionPrefix}{typeMetadata.FullTypeName}.{propertyMetadata.Symbol.Name}),");
                         builder.AppendLine(@$"""{propertyMetadata.LuaMemberName}"" => {conversionPrefix}{typeMetadata.FullTypeName}.{propertyMetadata.Symbol.Name}),");
@@ -261,7 +313,7 @@ partial class LuaObjectGenerator
         return true;
         return true;
     }
     }
 
 
-    static bool TryEmitNewIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builder,SymbolReferences references,  in SourceProductionContext context)
+    static bool TryEmitNewIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builder, SymbolReferences references, in SourceProductionContext context)
     {
     {
         builder.AppendLine(@"static readonly global::Lua.LuaFunction __metamethod_newindex = new global::Lua.LuaFunction(""newindex"", (context, ct) =>");
         builder.AppendLine(@"static readonly global::Lua.LuaFunction __metamethod_newindex = new global::Lua.LuaFunction(""newindex"", (context, ct) =>");
 
 
@@ -306,6 +358,7 @@ partial class LuaObjectGenerator
                             {
                             {
                                 builder.AppendLine($"userData.{propertyMetadata.Symbol.Name} = context.GetArgument<{propertyMetadata.TypeFullName}>(2);");
                                 builder.AppendLine($"userData.{propertyMetadata.Symbol.Name} = context.GetArgument<{propertyMetadata.TypeFullName}>(2);");
                             }
                             }
+
                             builder.AppendLine("break;");
                             builder.AppendLine("break;");
                         }
                         }
                     }
                     }
@@ -338,7 +391,7 @@ partial class LuaObjectGenerator
         return true;
         return true;
     }
     }
 
 
-    static bool TryEmitMethods(TypeMetadata typeMetadata, CodeBuilder builder, SymbolReferences references,Compilation compilation, HashSet<LuaObjectMetamethod> metamethodSet, in SourceProductionContext context)
+    static bool TryEmitMethods(TypeMetadata typeMetadata, CodeBuilder builder, SymbolReferences references, Compilation compilation, HashSet<LuaObjectMetamethod> metamethodSet, in SourceProductionContext context)
     {
     {
         builder.AppendLine();
         builder.AppendLine();
 
 
@@ -349,7 +402,7 @@ partial class LuaObjectGenerator
             if (methodMetadata.HasMemberAttribute)
             if (methodMetadata.HasMemberAttribute)
             {
             {
                 functionName = $"__function_{methodMetadata.LuaMemberName}";
                 functionName = $"__function_{methodMetadata.LuaMemberName}";
-                EmitMethodFunction(functionName, methodMetadata.LuaMemberName, typeMetadata, methodMetadata, builder, references,compilation);
+                EmitMethodFunction(functionName, methodMetadata.LuaMemberName, typeMetadata, methodMetadata, builder, references, compilation);
             }
             }
 
 
             if (methodMetadata.HasMetamethodAttribute)
             if (methodMetadata.HasMetamethodAttribute)
@@ -368,7 +421,7 @@ partial class LuaObjectGenerator
 
 
                 if (functionName == null)
                 if (functionName == null)
                 {
                 {
-                    EmitMethodFunction($"__metamethod_{methodMetadata.Metamethod}", methodMetadata.Metamethod.ToString().ToLower(), typeMetadata, methodMetadata, builder, references,compilation);
+                    EmitMethodFunction($"__metamethod_{methodMetadata.Metamethod}", methodMetadata.Metamethod.ToString().ToLower(), typeMetadata, methodMetadata, builder, references, compilation);
                 }
                 }
                 else
                 else
                 {
                 {
@@ -380,7 +433,7 @@ partial class LuaObjectGenerator
         return true;
         return true;
     }
     }
 
 
-    static void EmitMethodFunction(string functionName, string chunkName, TypeMetadata typeMetadata, MethodMetadata methodMetadata, CodeBuilder builder, SymbolReferences references,Compilation compilation)
+    static void EmitMethodFunction(string functionName, string chunkName, TypeMetadata typeMetadata, MethodMetadata methodMetadata, CodeBuilder builder, SymbolReferences references, Compilation compilation)
     {
     {
         builder.AppendLine($@"static readonly global::Lua.LuaFunction {functionName} = new global::Lua.LuaFunction(""{chunkName}"", {(methodMetadata.IsAsync ? "async" : "")} (context, ct) =>");
         builder.AppendLine($@"static readonly global::Lua.LuaFunction {functionName} = new global::Lua.LuaFunction(""{chunkName}"", {(methodMetadata.IsAsync ? "async" : "")} (context, ct) =>");
 
 
@@ -393,12 +446,12 @@ partial class LuaObjectGenerator
                 builder.AppendLine($"var userData = context.GetArgument<{typeMetadata.FullTypeName}>(0);");
                 builder.AppendLine($"var userData = context.GetArgument<{typeMetadata.FullTypeName}>(0);");
                 index++;
                 index++;
             }
             }
-            
-            bool hasCancellationToken = false;
 
 
-            for (int i = 0; i < methodMetadata.Symbol.Parameters.Length; i++)
+            var hasCancellationToken = false;
+
+            for (var i = 0; i < methodMetadata.Symbol.Parameters.Length; i++)
             {
             {
-                IParameterSymbol? parameter = methodMetadata.Symbol.Parameters[i];
+                var parameter = methodMetadata.Symbol.Parameters[i];
                 var parameterType = parameter.Type;
                 var parameterType = parameter.Type;
                 var isParameterLuaValue = SymbolEqualityComparer.Default.Equals(parameterType, references.LuaValue);
                 var isParameterLuaValue = SymbolEqualityComparer.Default.Equals(parameterType, references.LuaValue);
 
 
@@ -443,24 +496,24 @@ partial class LuaObjectGenerator
 
 
             if (methodMetadata.IsAsync)
             if (methodMetadata.IsAsync)
             {
             {
-                builder.Append("await ",!methodMetadata.HasReturnValue);
+                builder.Append("await ", !methodMetadata.HasReturnValue);
             }
             }
 
 
             if (methodMetadata.IsStatic)
             if (methodMetadata.IsStatic)
             {
             {
-                builder.Append($"{typeMetadata.FullTypeName}.{methodMetadata.Symbol.Name}(",!(methodMetadata.HasReturnValue||methodMetadata.IsAsync));
+                builder.Append($"{typeMetadata.FullTypeName}.{methodMetadata.Symbol.Name}(", !(methodMetadata.HasReturnValue || methodMetadata.IsAsync));
                 builder.Append(string.Join(",", Enumerable.Range(0, index).Select(x => $"arg{x}")), false);
                 builder.Append(string.Join(",", Enumerable.Range(0, index).Select(x => $"arg{x}")), false);
 
 
                 if (hasCancellationToken)
                 if (hasCancellationToken)
                 {
                 {
-                    builder.Append(index > 0?",ct":"ct", false);
+                    builder.Append(index > 0 ? ",ct" : "ct", false);
                 }
                 }
 
 
                 builder.AppendLine(");", false);
                 builder.AppendLine(");", false);
             }
             }
             else
             else
             {
             {
-                builder.Append($"userData.{methodMetadata.Symbol.Name}(",!(methodMetadata.HasReturnValue||methodMetadata.IsAsync));
+                builder.Append($"userData.{methodMetadata.Symbol.Name}(", !(methodMetadata.HasReturnValue || methodMetadata.IsAsync));
                 builder.Append(string.Join(",", Enumerable.Range(1, index - 1).Select(x => $"arg{x}")), false);
                 builder.Append(string.Join(",", Enumerable.Range(1, index - 1).Select(x => $"arg{x}")), false);
 
 
                 if (hasCancellationToken)
                 if (hasCancellationToken)
@@ -478,16 +531,18 @@ partial class LuaObjectGenerator
                 if (methodMetadata.IsAsync)
                 if (methodMetadata.IsAsync)
                 {
                 {
                     var namedType = (INamedTypeSymbol)returnType;
                     var namedType = (INamedTypeSymbol)returnType;
-                    if (namedType.TypeArguments.Length == 1) returnType = namedType.TypeArguments[0];
+                    if (namedType.TypeArguments.Length == 1)
+                    {
+                        returnType = namedType.TypeArguments[0];
+                    }
                 }
                 }
 
 
-                var conversionPrefix =GetLuaValuePrefix(returnType,references,compilation);
-                builder.AppendLine(methodMetadata.IsAsync ? $"context.Return({conversionPrefix}result));" : $"new global::System.Threading.Tasks.ValueTask<int>(context.Return({conversionPrefix}result)));",false);
-                
+                var conversionPrefix = GetLuaValuePrefix(returnType, references, compilation);
+                builder.AppendLine(methodMetadata.IsAsync ? $"context.Return({conversionPrefix}result));" : $"new global::System.Threading.Tasks.ValueTask<int>(context.Return({conversionPrefix}result)));", false);
             }
             }
             else
             else
             {
             {
-                builder.AppendLine(methodMetadata.IsAsync ? "context.Return();" : "new global::System.Threading.Tasks.ValueTask<int>(context.Return());",false);
+                builder.AppendLine(methodMetadata.IsAsync ? "context.Return();" : "new global::System.Threading.Tasks.ValueTask<int>(context.Return());", false);
             }
             }
         }
         }
 
 

+ 2 - 2
src/Lua.SourceGenerator/LuaObjectMetamethod.cs

@@ -2,7 +2,7 @@ namespace Lua.SourceGenerator;
 
 
 // same as Lua.LuaObjectMetamethod
 // same as Lua.LuaObjectMetamethod
 
 
-internal enum LuaObjectMetamethod
+enum LuaObjectMetamethod
 {
 {
     Add,
     Add,
     Sub,
     Sub,
@@ -19,5 +19,5 @@ internal enum LuaObjectMetamethod
     Concat,
     Concat,
     Pairs,
     Pairs,
     IPairs,
     IPairs,
-    ToString,
+    ToString
 }
 }

+ 2 - 2
src/Lua.SourceGenerator/MethodMetadata.cs

@@ -2,7 +2,7 @@ using Microsoft.CodeAnalysis;
 
 
 namespace Lua.SourceGenerator;
 namespace Lua.SourceGenerator;
 
 
-internal class MethodMetadata
+class MethodMetadata
 {
 {
     public IMethodSymbol Symbol { get; }
     public IMethodSymbol Symbol { get; }
     public bool IsStatic { get; }
     public bool IsStatic { get; }
@@ -19,7 +19,7 @@ internal class MethodMetadata
         IsStatic = symbol.IsStatic;
         IsStatic = symbol.IsStatic;
 
 
         var returnType = symbol.ReturnType;
         var returnType = symbol.ReturnType;
-        var fullName = (returnType.ContainingNamespace.IsGlobalNamespace ? "" : (returnType.ContainingNamespace + ".")) + returnType.Name;
+        var fullName = (returnType.ContainingNamespace.IsGlobalNamespace ? "" : returnType.ContainingNamespace + ".") + returnType.Name;
         IsAsync = fullName is "System.Threading.Tasks.Task"
         IsAsync = fullName is "System.Threading.Tasks.Task"
             or "System.Threading.Tasks.ValueTask"
             or "System.Threading.Tasks.ValueTask"
             or "Cysharp.Threading.Tasks.UniTask"
             or "Cysharp.Threading.Tasks.UniTask"

+ 6 - 2
src/Lua.SourceGenerator/SymbolReferences.cs

@@ -7,8 +7,12 @@ public sealed class SymbolReferences
     public static SymbolReferences? Create(Compilation compilation)
     public static SymbolReferences? Create(Compilation compilation)
     {
     {
         var luaObjectAttribute = compilation.GetTypeByMetadataName("Lua.LuaObjectAttribute");
         var luaObjectAttribute = compilation.GetTypeByMetadataName("Lua.LuaObjectAttribute");
-        if (luaObjectAttribute == null) return null;
-        return new SymbolReferences
+        if (luaObjectAttribute == null)
+        {
+            return null;
+        }
+
+        return new()
         {
         {
             LuaObjectAttribute = luaObjectAttribute,
             LuaObjectAttribute = luaObjectAttribute,
             LuaMemberAttribute = compilation.GetTypeByMetadataName("Lua.LuaMemberAttribute")!,
             LuaMemberAttribute = compilation.GetTypeByMetadataName("Lua.LuaMemberAttribute")!,

+ 24 - 6
src/Lua.SourceGenerator/TypeMetadata.cs

@@ -4,7 +4,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax;
 
 
 namespace Lua.SourceGenerator;
 namespace Lua.SourceGenerator;
 
 
-internal class TypeMetadata
+class TypeMetadata
 {
 {
     public TypeDeclarationSyntax Syntax { get; }
     public TypeDeclarationSyntax Syntax { get; }
     public INamedTypeSymbol Symbol { get; }
     public INamedTypeSymbol Symbol { get; }
@@ -25,13 +25,27 @@ internal class TypeMetadata
             .Where(x => x is (IFieldSymbol or IPropertySymbol) and { IsImplicitlyDeclared: false })
             .Where(x => x is (IFieldSymbol or IPropertySymbol) and { IsImplicitlyDeclared: false })
             .Where(x =>
             .Where(x =>
             {
             {
-                if (!x.ContainsAttribute(references.LuaMemberAttribute)) return false;
-                if (x.ContainsAttribute(references.LuaIgnoreMemberAttribute)) return false;
+                if (!x.ContainsAttribute(references.LuaMemberAttribute))
+                {
+                    return false;
+                }
+
+                if (x.ContainsAttribute(references.LuaIgnoreMemberAttribute))
+                {
+                    return false;
+                }
 
 
                 if (x is IPropertySymbol p)
                 if (x is IPropertySymbol p)
                 {
                 {
-                    if (p.GetMethod == null || p.SetMethod == null) return false;
-                    if (p.IsIndexer) return false;
+                    if (p.GetMethod == null || p.SetMethod == null)
+                    {
+                        return false;
+                    }
+
+                    if (p.IsIndexer)
+                    {
+                        return false;
+                    }
                 }
                 }
 
 
                 return true;
                 return true;
@@ -44,7 +58,11 @@ internal class TypeMetadata
             .Select(x => (IMethodSymbol)x)
             .Select(x => (IMethodSymbol)x)
             .Where(x =>
             .Where(x =>
             {
             {
-                if (x.ContainsAttribute(references.LuaIgnoreMemberAttribute)) return false;
+                if (x.ContainsAttribute(references.LuaIgnoreMemberAttribute))
+                {
+                    return false;
+                }
+
                 return x.ContainsAttribute(references.LuaMemberAttribute) || x.ContainsAttribute(references.LuaMetamethodAttribute);
                 return x.ContainsAttribute(references.LuaMemberAttribute) || x.ContainsAttribute(references.LuaMetamethodAttribute);
             })
             })
             .Select(x => new MethodMetadata(x, references))
             .Select(x => new MethodMetadata(x, references))

+ 26 - 6
src/Lua.SourceGenerator/Utilities/CodeBuilder.cs

@@ -2,7 +2,7 @@ using System.Text;
 
 
 namespace Lua.SourceGenerator;
 namespace Lua.SourceGenerator;
 
 
-internal sealed class CodeBuilder
+sealed class CodeBuilder
 {
 {
     public ref struct IndentScope
     public ref struct IndentScope
     {
     {
@@ -11,7 +11,11 @@ internal sealed class CodeBuilder
         public IndentScope(CodeBuilder source, string? startLine = null)
         public IndentScope(CodeBuilder source, string? startLine = null)
         {
         {
             this.source = source;
             this.source = source;
-            if(startLine!=null) source.AppendLine(startLine);
+            if (startLine != null)
+            {
+                source.AppendLine(startLine);
+            }
+
             source.IncreaseIndent();
             source.IncreaseIndent();
         }
         }
 
 
@@ -28,7 +32,11 @@ internal sealed class CodeBuilder
         public BlockScope(CodeBuilder source, string? startLine = null)
         public BlockScope(CodeBuilder source, string? startLine = null)
         {
         {
             this.source = source;
             this.source = source;
-            if(startLine!=null) source.AppendLine(startLine);
+            if (startLine != null)
+            {
+                source.AppendLine(startLine);
+            }
+
             source.BeginBlock();
             source.BeginBlock();
         }
         }
 
 
@@ -41,8 +49,15 @@ internal sealed class CodeBuilder
     readonly StringBuilder buffer = new();
     readonly StringBuilder buffer = new();
     int indentLevel;
     int indentLevel;
 
 
-    public IndentScope BeginIndentScope(string? startLine = null) => new(this, startLine);
-    public BlockScope BeginBlockScope(string? startLine = null) => new(this, startLine);
+    public IndentScope BeginIndentScope(string? startLine = null)
+    {
+        return new(this, startLine);
+    }
+
+    public BlockScope BeginBlockScope(string? startLine = null)
+    {
+        return new(this, startLine);
+    }
 
 
     public void Append(string value, bool indent = true)
     public void Append(string value, bool indent = true)
     {
     {
@@ -90,7 +105,10 @@ internal sealed class CodeBuilder
         buffer.Append(" }");
         buffer.Append(" }");
     }
     }
 
 
-    public override string ToString() => buffer.ToString();
+    public override string ToString()
+    {
+        return buffer.ToString();
+    }
 
 
     public void IncreaseIndent()
     public void IncreaseIndent()
     {
     {
@@ -100,7 +118,9 @@ internal sealed class CodeBuilder
     public void DecreaseIndent()
     public void DecreaseIndent()
     {
     {
         if (indentLevel > 0)
         if (indentLevel > 0)
+        {
             indentLevel--;
             indentLevel--;
+        }
     }
     }
 
 
     public void BeginBlock()
     public void BeginBlock()

+ 3 - 5
src/Lua.SourceGenerator/Utilities/RoslynAnalyzerExtensions.cs

@@ -2,19 +2,17 @@ using Microsoft.CodeAnalysis;
 
 
 namespace Lua.SourceGenerator;
 namespace Lua.SourceGenerator;
 
 
-internal static class RoslynAnalyzerExtensions
+static class RoslynAnalyzerExtensions
 {
 {
     public static AttributeData? FindAttribute(this IEnumerable<AttributeData> attributeDataList, string typeName)
     public static AttributeData? FindAttribute(this IEnumerable<AttributeData> attributeDataList, string typeName)
     {
     {
         return attributeDataList
         return attributeDataList
-            .Where(x => x.AttributeClass?.ToDisplayString() == typeName)
-            .FirstOrDefault();
+            .FirstOrDefault(x => x.AttributeClass?.ToDisplayString() == typeName);
     }
     }
 
 
     public static AttributeData? FindAttributeShortName(this IEnumerable<AttributeData> attributeDataList, string typeName)
     public static AttributeData? FindAttributeShortName(this IEnumerable<AttributeData> attributeDataList, string typeName)
     {
     {
         return attributeDataList
         return attributeDataList
-            .Where(x => x.AttributeClass?.Name == typeName)
-            .FirstOrDefault();
+            .FirstOrDefault(x => x.AttributeClass?.Name == typeName);
     }
     }
 }
 }

+ 1 - 1
src/Lua.SourceGenerator/Utilities/SymbolExtensions.cs

@@ -2,7 +2,7 @@ using Microsoft.CodeAnalysis;
 
 
 namespace Lua.SourceGenerator;
 namespace Lua.SourceGenerator;
 
 
-internal static class SymbolExtensions
+static class SymbolExtensions
 {
 {
     public static bool ContainsAttribute(this ISymbol symbol, INamedTypeSymbol attribtue)
     public static bool ContainsAttribute(this ISymbol symbol, INamedTypeSymbol attribtue)
     {
     {

+ 4 - 1
src/Lua/CodeAnalysis/Compilation/BomUtility.cs

@@ -2,11 +2,14 @@
 
 
 namespace Lua.CodeAnalysis.Compilation;
 namespace Lua.CodeAnalysis.Compilation;
 
 
-internal static class BomUtility
+static class BomUtility
 {
 {
     static ReadOnlySpan<byte> BomUtf8 => [0xEF, 0xBB, 0xBF];
     static ReadOnlySpan<byte> BomUtf8 => [0xEF, 0xBB, 0xBF];
+
     static ReadOnlySpan<byte> BomUtf16Little => [0xFF, 0xFE];
     static ReadOnlySpan<byte> BomUtf16Little => [0xFF, 0xFE];
+
     static ReadOnlySpan<byte> BomUtf16Big => [0xFE, 0xFF];
     static ReadOnlySpan<byte> BomUtf16Big => [0xFE, 0xFF];
+
     static ReadOnlySpan<byte> BomUtf32Little => [0xFF, 0xFE, 0x00, 0x00];
     static ReadOnlySpan<byte> BomUtf32Little => [0xFF, 0xFE, 0x00, 0x00];
 
 
     /// <summary>
     /// <summary>

+ 26 - 12
src/Lua/CodeAnalysis/Compilation/Declarements.cs

@@ -9,8 +9,7 @@ unsafe struct TextReader(char* ptr, int length)
 
 
     public (char, bool) Read()
     public (char, bool) Read()
     {
     {
-        if (Position >= length) return ('\0', false);
-        return (ptr[Position++], true);
+        return Position >= length ? ('\0', false) : (ptr[Position++], true);
     }
     }
 
 
     public bool TryRead(out char c)
     public bool TryRead(out char c)
@@ -28,29 +27,31 @@ unsafe struct TextReader(char* ptr, int length)
     public char Current => ptr[Position];
     public char Current => ptr[Position];
 
 
     public ReadOnlySpan<char> Span => new(ptr, length);
     public ReadOnlySpan<char> Span => new(ptr, length);
+
     public int Length => length;
     public int Length => length;
 }
 }
 
 
-internal unsafe struct AssignmentTarget(ref AssignmentTarget previous, ExprDesc exprDesc)
+unsafe struct AssignmentTarget(ref AssignmentTarget previous, ExprDesc exprDesc)
 {
 {
     public readonly AssignmentTarget* Previous = (AssignmentTarget*)Unsafe.AsPointer(ref previous);
     public readonly AssignmentTarget* Previous = (AssignmentTarget*)Unsafe.AsPointer(ref previous);
     public ExprDesc Description = exprDesc;
     public ExprDesc Description = exprDesc;
 }
 }
 
 
-internal struct Label
+struct Label
 {
 {
     public string Name;
     public string Name;
     public int Pc, Line;
     public int Pc, Line;
     public int ActiveVariableCount;
     public int ActiveVariableCount;
 }
 }
 
 
-internal class Block : IPoolNode<Block>
+class Block : IPoolNode<Block>
 {
 {
     public Block? Previous;
     public Block? Previous;
     public int FirstLabel, FirstGoto;
     public int FirstLabel, FirstGoto;
     public int ActiveVariableCount;
     public int ActiveVariableCount;
     public bool HasUpValue, IsLoop;
     public bool HasUpValue, IsLoop;
     Block() { }
     Block() { }
+
     ref Block? IPoolNode<Block>.NextNode => ref Previous;
     ref Block? IPoolNode<Block>.NextNode => ref Previous;
 
 
     static LinkedPool<Block> Pool;
     static LinkedPool<Block> Pool;
@@ -59,7 +60,7 @@ internal class Block : IPoolNode<Block>
     {
     {
         if (!Pool.TryPop(out var block))
         if (!Pool.TryPop(out var block))
         {
         {
-            block = new Block();
+            block = new();
         }
         }
 
 
         block.Previous = previous;
         block.Previous = previous;
@@ -80,7 +81,7 @@ internal class Block : IPoolNode<Block>
     }
     }
 }
 }
 
 
-internal struct ExprDesc
+struct ExprDesc
 {
 {
     public Kind Kind;
     public Kind Kind;
     public int Index;
     public int Index;
@@ -89,16 +90,29 @@ internal struct ExprDesc
     public int Info;
     public int Info;
     public int T, F;
     public int T, F;
     public double Value;
     public double Value;
-    public readonly bool HasJumps() => T != F;
 
 
-    public readonly bool IsNumeral() => Kind == Kind.Number && T == Function.NoJump && F == Function.NoJump;
+    public readonly bool HasJumps()
+    {
+        return T != F;
+    }
 
 
-    public readonly bool IsVariable() => Kind.Local <= Kind && Kind <= Kind.Indexed;
+    public readonly bool IsNumeral()
+    {
+        return Kind == Kind.Number && T == Function.NoJump && F == Function.NoJump;
+    }
 
 
-    public readonly bool HasMultipleReturns() => Kind == Kind.Call || Kind == Kind.VarArg;
+    public readonly bool IsVariable()
+    {
+        return Kind is >= Kind.Local and <= Kind.Indexed;
+    }
+
+    public readonly bool HasMultipleReturns()
+    {
+        return Kind == Kind.Call || Kind == Kind.VarArg;
+    }
 }
 }
 
 
-internal enum Kind
+enum Kind
 {
 {
     Void = 0,
     Void = 0,
     Nil = 1,
     Nil = 1,

+ 63 - 28
src/Lua/CodeAnalysis/Compilation/Dump.cs

@@ -12,10 +12,12 @@ namespace Lua.CodeAnalysis.Compilation;
 
 
 [SuppressMessage("ReSharper", "MemberCanBePrivate.Local")]
 [SuppressMessage("ReSharper", "MemberCanBePrivate.Local")]
 [StructLayout(LayoutKind.Sequential, Pack = 1)]
 [StructLayout(LayoutKind.Sequential, Pack = 1)]
-internal unsafe struct Header
+unsafe struct Header
 {
 {
     public static ReadOnlySpan<byte> LuaSignature => "\eLua"u8;
     public static ReadOnlySpan<byte> LuaSignature => "\eLua"u8;
+
     public static ReadOnlySpan<byte> LuaTail => [0x19, 0x93, 0x0d, 0x0a, 0x1a, 0x0a];
     public static ReadOnlySpan<byte> LuaTail => [0x19, 0x93, 0x0d, 0x0a, 0x1a, 0x0a];
+
     public fixed byte Signature[4];
     public fixed byte Signature[4];
     public byte Version, Format, Endianness, IntSize;
     public byte Version, Format, Endianness, IntSize;
     public byte PointerSize, InstructionSize;
     public byte PointerSize, InstructionSize;
@@ -31,7 +33,7 @@ internal unsafe struct Header
             LuaSignature.CopyTo(new(signature, 4));
             LuaSignature.CopyTo(new(signature, 4));
         }
         }
 
 
-        Version = Constants.VersionMajor << 4 | Constants.VersionMinor;
+        Version = (Constants.VersionMajor << 4) | Constants.VersionMinor;
         Format = 0;
         Format = 0;
         Endianness = (byte)(isLittleEndian ? 1 : 0);
         Endianness = (byte)(isLittleEndian ? 1 : 0);
         IntSize = 4;
         IntSize = 4;
@@ -81,7 +83,7 @@ internal unsafe struct Header
     }
     }
 }
 }
 
 
-internal unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEndian)
+unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEndian)
 {
 {
     public readonly IBufferWriter<byte> Writer = writer;
     public readonly IBufferWriter<byte> Writer = writer;
     Span<byte> unWritten;
     Span<byte> unWritten;
@@ -107,7 +109,7 @@ internal unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEn
 
 
     void DumpHeader()
     void DumpHeader()
     {
     {
-        var header = new Header(BitConverter.IsLittleEndian ^ IsReversedEndian);
+        Header header = new(BitConverter.IsLittleEndian ^ IsReversedEndian);
         Write(new(&header, Header.Size));
         Write(new(&header, Header.Size));
     }
     }
 
 
@@ -173,7 +175,7 @@ internal unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEn
 
 
     void WriteDouble(double v)
     void WriteDouble(double v)
     {
     {
-        long l = BitConverter.DoubleToInt64Bits(v);
+        var l = BitConverter.DoubleToInt64Bits(v);
         WriteLong(l);
         WriteLong(l);
     }
     }
 
 
@@ -204,9 +206,20 @@ internal unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEn
     {
     {
         var bytes = Encoding.UTF8.GetBytes(v);
         var bytes = Encoding.UTF8.GetBytes(v);
         var len = bytes.Length;
         var len = bytes.Length;
-        if (bytes.Length != 0) len++;
-        if (sizeof(IntPtr) == 8) WriteLong(len);
-        else WriteInt(len);
+        if (bytes.Length != 0)
+        {
+            len++;
+        }
+
+        if (sizeof(IntPtr) == 8)
+        {
+            WriteLong(len);
+        }
+        else
+        {
+            WriteInt(len);
+        }
+
         if (len != 0)
         if (len != 0)
         {
         {
             Write(bytes);
             Write(bytes);
@@ -267,20 +280,31 @@ internal unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEn
     }
     }
 }
 }
 
 
-internal unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<char> name)
+unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<char> name)
 {
 {
     public ReadOnlySpan<byte> Unread = span;
     public ReadOnlySpan<byte> Unread = span;
     bool otherEndian;
     bool otherEndian;
     int pointerSize;
     int pointerSize;
     readonly ReadOnlySpan<char> name = name;
     readonly ReadOnlySpan<char> name = name;
 
 
-    void Throw(string why) => throw new LuaUnDumpException($"{name.ToString()}: {why} precompiled chunk");
-    void ThrowTooShort() => Throw("truncate");
+    void Throw(string why)
+    {
+        throw new LuaUnDumpException($"{name.ToString()}: {why} precompiled chunk");
+    }
+
+    void ThrowTooShort()
+    {
+        Throw("truncate");
+    }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     internal void Read(Span<byte> dst)
     internal void Read(Span<byte> dst)
     {
     {
-        if (Unread.Length < dst.Length) ThrowTooShort();
+        if (Unread.Length < dst.Length)
+        {
+            ThrowTooShort();
+        }
+
         Unread[..dst.Length].CopyTo(dst);
         Unread[..dst.Length].CopyTo(dst);
 
 
         Unread = Unread[dst.Length..];
         Unread = Unread[dst.Length..];
@@ -316,10 +340,13 @@ internal unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<cha
     int ReadInt()
     int ReadInt()
     {
     {
         var i = 0;
         var i = 0;
-        var span = new Span<byte>(&i, sizeof(int));
+        Span<byte> span = new(&i, sizeof(int));
         Read(span);
         Read(span);
 
 
-        if (otherEndian) i = BinaryPrimitives.ReverseEndianness(i);
+        if (otherEndian)
+        {
+            i = BinaryPrimitives.ReverseEndianness(i);
+        }
 
 
         return i;
         return i;
     }
     }
@@ -327,24 +354,28 @@ internal unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<cha
     long ReadLong()
     long ReadLong()
     {
     {
         long i = 0;
         long i = 0;
-        var span = new Span<byte>(&i, sizeof(long));
+        Span<byte> span = new(&i, sizeof(long));
         Read(span);
         Read(span);
 
 
-        if (otherEndian) i = BinaryPrimitives.ReverseEndianness(i);
+        if (otherEndian)
+        {
+            i = BinaryPrimitives.ReverseEndianness(i);
+        }
+
         return i;
         return i;
     }
     }
 
 
     double ReadDouble()
     double ReadDouble()
     {
     {
-        long i = ReadLong();
+        var i = ReadLong();
 
 
-        return *(double*)(&i);
+        return *(double*)&i;
     }
     }
 
 
     public Prototype UnDump()
     public Prototype UnDump()
     {
     {
         Header h = default;
         Header h = default;
-        var span = new Span<byte>(&h, sizeof(Header));
+        Span<byte> span = new(&h, sizeof(Header));
         Read(span);
         Read(span);
 
 
         h.Validate(name);
         h.Validate(name);
@@ -388,7 +419,7 @@ internal unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<cha
 
 
     void ReadInToIntSpan(Span<int> toWrite)
     void ReadInToIntSpan(Span<int> toWrite)
     {
     {
-        for (int i = 0; i < toWrite.Length; i++)
+        for (var i = 0; i < toWrite.Length; i++)
         {
         {
             toWrite[i] = ReadInt();
             toWrite[i] = ReadInt();
         }
         }
@@ -398,7 +429,11 @@ internal unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<cha
     string ReadString()
     string ReadString()
     {
     {
         var len = pointerSize == 4 ? ReadInt() : (int)ReadLong();
         var len = pointerSize == 4 ? ReadInt() : (int)ReadLong();
-        if (len == 0) return "";
+        if (len == 0)
+        {
+            return "";
+        }
+
         len--;
         len--;
         var arrayPooled = ArrayPool<byte>.Shared.Rent(len);
         var arrayPooled = ArrayPool<byte>.Shared.Rent(len);
         try
         try
@@ -421,20 +456,20 @@ internal unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<cha
     {
     {
         var count = ReadInt();
         var count = ReadInt();
         var constants = new LuaValue[count];
         var constants = new LuaValue[count];
-        for (int i = 0; i < count; i++)
+        for (var i = 0; i < count; i++)
         {
         {
             var type = (LuaValueType)ReadByte();
             var type = (LuaValueType)ReadByte();
             switch (type)
             switch (type)
             {
             {
                 case LuaValueType.Nil: break;
                 case LuaValueType.Nil: break;
                 case LuaValueType.Boolean:
                 case LuaValueType.Boolean:
-                    constants[i] = (ReadByte() == 1);
+                    constants[i] = ReadByte() == 1;
                     break;
                     break;
                 case LuaValueType.Number:
                 case LuaValueType.Number:
-                    constants[i] = (ReadDouble());
+                    constants[i] = ReadDouble();
                     break;
                     break;
                 case LuaValueType.String:
                 case LuaValueType.String:
-                    constants[i] = (ReadString());
+                    constants[i] = ReadString();
                     break;
                     break;
             }
             }
         }
         }
@@ -446,7 +481,7 @@ internal unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<cha
     {
     {
         var count = ReadInt();
         var count = ReadInt();
         var prototypes = count != 0 ? new Prototype[count] : [];
         var prototypes = count != 0 ? new Prototype[count] : [];
-        for (int i = 0; i < count; i++)
+        for (var i = 0; i < count; i++)
         {
         {
             prototypes[i] = UnDumpFunction();
             prototypes[i] = UnDumpFunction();
         }
         }
@@ -458,7 +493,7 @@ internal unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<cha
     {
     {
         var count = ReadInt();
         var count = ReadInt();
         var localVariables = new LocalVariable[count];
         var localVariables = new LocalVariable[count];
-        for (int i = 0; i < count; i++)
+        for (var i = 0; i < count; i++)
         {
         {
             var name = ReadString();
             var name = ReadString();
             var startPc = ReadInt();
             var startPc = ReadInt();
@@ -474,7 +509,7 @@ internal unsafe ref struct UnDumpState(ReadOnlySpan<byte> span, ReadOnlySpan<cha
         var count = ReadInt();
         var count = ReadInt();
         Debug.Assert(count < 100, $" too many upvalues :{count}");
         Debug.Assert(count < 100, $" too many upvalues :{count}");
         var upValues = new UpValueDesc[count];
         var upValues = new UpValueDesc[count];
-        for (int i = 0; i < count; i++)
+        for (var i = 0; i < count; i++)
         {
         {
             var isLocal = ReadBool();
             var isLocal = ReadBool();
             var index = ReadByte();
             var index = ReadByte();

+ 130 - 38
src/Lua/CodeAnalysis/Compilation/Function.cs

@@ -9,7 +9,7 @@ using static Debug;
 using static Instruction;
 using static Instruction;
 using static Constants;
 using static Constants;
 
 
-internal class Function : IPoolNode<Function>
+class Function : IPoolNode<Function>
 {
 {
     public readonly Dictionary<LuaValue, int> ConstantLookup = new();
     public readonly Dictionary<LuaValue, int> ConstantLookup = new();
     public PrototypeBuilder Proto = null!;
     public PrototypeBuilder Proto = null!;
@@ -29,7 +29,7 @@ internal class Function : IPoolNode<Function>
     {
     {
         if (!pool.TryPop(out var f))
         if (!pool.TryPop(out var f))
         {
         {
-            f = new Function();
+            f = new();
         }
         }
 
 
         f.P = p;
         f.P = p;
@@ -153,7 +153,7 @@ internal class Function : IPoolNode<Function>
     {
     {
         for (ActiveVariableCount += n; n != 0; n--)
         for (ActiveVariableCount += n; n != 0; n--)
         {
         {
-            LocalVariable(ActiveVariableCount - n).StartPc = ((Proto.CodeList.Length));
+            LocalVariable(ActiveVariableCount - n).StartPc = Proto.CodeList.Length;
         }
         }
     }
     }
 
 
@@ -161,10 +161,10 @@ internal class Function : IPoolNode<Function>
     {
     {
         for (var i = level; i < ActiveVariableCount; i++)
         for (var i = level; i < ActiveVariableCount; i++)
         {
         {
-            LocalVariable(i).EndPc = ((Proto.CodeList.Length));
+            LocalVariable(i).EndPc = Proto.CodeList.Length;
         }
         }
 
 
-        P.ActiveVariables.Shrink((P.ActiveVariables.Length - (ActiveVariableCount - level)));
+        P.ActiveVariables.Shrink(P.ActiveVariables.Length - (ActiveVariableCount - level));
         ActiveVariableCount = level;
         ActiveVariableCount = level;
     }
     }
 
 
@@ -172,20 +172,20 @@ internal class Function : IPoolNode<Function>
     {
     {
         var r = Proto.LocalVariablesList.Length;
         var r = Proto.LocalVariablesList.Length;
         Proto.LocalVariablesList.Add(new() { Name = name });
         Proto.LocalVariablesList.Add(new() { Name = name });
-        P.CheckLimit((P.ActiveVariables.Length + 1 - FirstLocal), MaxLocalVariables, "local variables");
+        P.CheckLimit(P.ActiveVariables.Length + 1 - FirstLocal, MaxLocalVariables, "local variables");
         P.ActiveVariables.Add(r);
         P.ActiveVariables.Add(r);
     }
     }
 
 
     public void MakeGoto(string name, int line, int pc)
     public void MakeGoto(string name, int line, int pc)
     {
     {
         P.PendingGotos.Add(new() { Name = name, Line = line, Pc = pc, ActiveVariableCount = ActiveVariableCount });
         P.PendingGotos.Add(new() { Name = name, Line = line, Pc = pc, ActiveVariableCount = ActiveVariableCount });
-        FindLabel((P.PendingGotos.Length - 1));
+        FindLabel(P.PendingGotos.Length - 1);
     }
     }
 
 
     public int MakeLabel(string name, int line)
     public int MakeLabel(string name, int line)
     {
     {
         P.ActiveLabels.Add(new() { Name = name, Line = line, Pc = Proto.CodeList.Length, ActiveVariableCount = ActiveVariableCount });
         P.ActiveLabels.Add(new() { Name = name, Line = line, Pc = Proto.CodeList.Length, ActiveVariableCount = ActiveVariableCount });
-        return (P.ActiveLabels.Length - 1);
+        return P.ActiveLabels.Length - 1;
     }
     }
 
 
     public void CloseGoto(int i, Label l)
     public void CloseGoto(int i, Label l)
@@ -297,10 +297,16 @@ internal class Function : IPoolNode<Function>
         b.Release();
         b.Release();
     }
     }
 
 
-    public static int Not(int b) => b == 0 ? 1 : 0;
+    public static int Not(int b)
+    {
+        return b == 0 ? 1 : 0;
+    }
 
 
 
 
-    public static ExprDesc MakeExpression(Kind kind, int info) => new() { F = NoJump, T = NoJump, Kind = kind, Info = info };
+    public static ExprDesc MakeExpression(Kind kind, int info)
+    {
+        return new() { F = NoJump, T = NoJump, Kind = kind, Info = info };
+    }
 
 
 
 
     public void SemanticError(string message)
     public void SemanticError(string message)
@@ -309,17 +315,29 @@ internal class Function : IPoolNode<Function>
         P.Scanner.SyntaxError(message);
         P.Scanner.SyntaxError(message);
     }
     }
 
 
-    public void BreakLabel() => FindGotos(MakeLabel("break", 0));
+    public void BreakLabel()
+    {
+        FindGotos(MakeLabel("break", 0));
+    }
 
 
     [Conditional("DEBUG")]
     [Conditional("DEBUG")]
-    public void Unreachable() => Assert(false);
+    public void Unreachable()
+    {
+        Assert(false);
+    }
 
 
 
 
-    public ref Instruction Instruction(ExprDesc e) => ref Proto.CodeList[e.Info];
+    public ref Instruction Instruction(ExprDesc e)
+    {
+        return ref Proto.CodeList[e.Info];
+    }
 
 
 
 
     [Conditional("DEBUG")]
     [Conditional("DEBUG")]
-    public void AssertEqual(int a, int b) => Assert(a == b, $"{a} != {b}");
+    public void AssertEqual(int a, int b)
+    {
+        Assert(a == b, $"{a} != {b}");
+    }
 
 
 
 
     public int Encode(Instruction i)
     public int Encode(Instruction i)
@@ -343,24 +361,39 @@ internal class Function : IPoolNode<Function>
         return Encode(CreateABC(op, a, b, c));
         return Encode(CreateABC(op, a, b, c));
     }
     }
 
 
-    public int EncodeABx(OpCode op, int a, int bx) => Encode(CreateABx(op, a, bx));
+    public int EncodeABx(OpCode op, int a, int bx)
+    {
+        return Encode(CreateABx(op, a, bx));
+    }
 
 
 
 
-    public int EncodeAsBx(OpCode op, int a, int sbx) => EncodeABx(op, a, sbx + MaxArgSBx);
+    public int EncodeAsBx(OpCode op, int a, int sbx)
+    {
+        return EncodeABx(op, a, sbx + MaxArgSBx);
+    }
 
 
-    public int EncodeExtraArg(int a) => Encode(CreateAx(OpCode.ExtraArg, a));
+    public int EncodeExtraArg(int a)
+    {
+        return Encode(CreateAx(OpCode.ExtraArg, a));
+    }
 
 
 
 
     public int EncodeConstant(int r, int constant)
     public int EncodeConstant(int r, int constant)
     {
     {
         if (constant <= MaxArgBx)
         if (constant <= MaxArgBx)
+        {
             return EncodeABx(OpCode.LoadK, r, constant);
             return EncodeABx(OpCode.LoadK, r, constant);
+        }
+
         var pc = EncodeABx(OpCode.LoadK, r, 0);
         var pc = EncodeABx(OpCode.LoadK, r, 0);
         EncodeExtraArg(constant);
         EncodeExtraArg(constant);
         return pc;
         return pc;
     }
     }
 
 
-    public ExprDesc EncodeString(string s) => MakeExpression(Kind.Constant, StringConstant(s));
+    public ExprDesc EncodeString(string s)
+    {
+        return MakeExpression(Kind.Constant, StringConstant(s));
+    }
 
 
 
 
     public void LoadNil(int from, int n)
     public void LoadNil(int from, int n)
@@ -373,7 +406,7 @@ internal class Function : IPoolNode<Function>
                 var pf = previous.A;
                 var pf = previous.A;
                 var pl = previous.A + previous.B;
                 var pl = previous.A + previous.B;
                 var l = from + n - 1;
                 var l = from + n - 1;
-                if (pf <= from && from <= pl + 1 || from <= pf && pf <= l + 1) // can connect both
+                if ((pf <= from && from <= pl + 1) || (from <= pf && pf <= l + 1)) // can connect both
                 {
                 {
                     from = Math.Min(from, pf);
                     from = Math.Min(from, pf);
                     l = Math.Max(l, pl);
                     l = Math.Max(l, pl);
@@ -424,7 +457,9 @@ internal class Function : IPoolNode<Function>
             EncodeABC(OpCode.Return, ActiveVariableCount, MultipleReturns + 1, 0);
             EncodeABC(OpCode.Return, ActiveVariableCount, MultipleReturns + 1, 0);
         }
         }
         else if (resultCount == 1)
         else if (resultCount == 1)
+        {
             EncodeABC(OpCode.Return, ExpressionToAnyRegister(e).Info, 1 + 1, 0);
             EncodeABC(OpCode.Return, ExpressionToAnyRegister(e).Info, 1 + 1, 0);
+        }
         else
         else
         {
         {
             ExpressionToNextRegister(e);
             ExpressionToNextRegister(e);
@@ -445,8 +480,11 @@ internal class Function : IPoolNode<Function>
         Assert(dest != NoJump);
         Assert(dest != NoJump);
         var offset = dest - (pc + 1);
         var offset = dest - (pc + 1);
         if (Math.Abs(offset) > MaxArgSBx)
         if (Math.Abs(offset) > MaxArgSBx)
+        {
             P.Scanner.SyntaxError("control structure too long");
             P.Scanner.SyntaxError("control structure too long");
-        Proto.CodeList[pc].SBx = (offset);
+        }
+
+        Proto.CodeList[pc].SBx = offset;
     }
     }
 
 
     public int Label()
     public int Label()
@@ -460,16 +498,25 @@ internal class Function : IPoolNode<Function>
         Assert(IsJumpListWalkable(pc));
         Assert(IsJumpListWalkable(pc));
         var offset = Proto.CodeList[pc].SBx;
         var offset = Proto.CodeList[pc].SBx;
         if (offset != NoJump)
         if (offset != NoJump)
+        {
             return pc + 1 + offset;
             return pc + 1 + offset;
+        }
+
         return NoJump;
         return NoJump;
     }
     }
 
 
     public bool IsJumpListWalkable(int list)
     public bool IsJumpListWalkable(int list)
     {
     {
         if (list == NoJump)
         if (list == NoJump)
+        {
             return true;
             return true;
+        }
+
         if (list < 0 || list >= Proto.CodeList.Length)
         if (list < 0 || list >= Proto.CodeList.Length)
+        {
             return false;
             return false;
+        }
+
         var offset = Proto.CodeList[list].SBx;
         var offset = Proto.CodeList[list].SBx;
         return offset == NoJump || IsJumpListWalkable(list + 1 + offset);
         return offset == NoJump || IsJumpListWalkable(list + 1 + offset);
     }
     }
@@ -477,7 +524,10 @@ internal class Function : IPoolNode<Function>
     public ref Instruction JumpControl(int pc)
     public ref Instruction JumpControl(int pc)
     {
     {
         if (pc >= 1 && TestTMode(Proto.CodeList[pc - 1].OpCode))
         if (pc >= 1 && TestTMode(Proto.CodeList[pc - 1].OpCode))
+        {
             return ref Proto.CodeList[pc - 1];
             return ref Proto.CodeList[pc - 1];
+        }
+
         return ref Proto.CodeList[pc];
         return ref Proto.CodeList[pc];
     }
     }
 
 
@@ -487,7 +537,9 @@ internal class Function : IPoolNode<Function>
         for (; list != NoJump; list = Jump(list))
         for (; list != NoJump; list = Jump(list))
         {
         {
             if (JumpControl(list).OpCode != OpCode.TestSet)
             if (JumpControl(list).OpCode != OpCode.TestSet)
+            {
                 return true;
                 return true;
+            }
         }
         }
 
 
         return false;
         return false;
@@ -497,11 +549,19 @@ internal class Function : IPoolNode<Function>
     {
     {
         ref var i = ref JumpControl(node);
         ref var i = ref JumpControl(node);
         if (i.OpCode != OpCode.TestSet)
         if (i.OpCode != OpCode.TestSet)
+        {
             return false;
             return false;
+        }
+
         if (register != NoRegister && register != i.B)
         if (register != NoRegister && register != i.B)
+        {
             i.A = register;
             i.A = register;
+        }
         else
         else
+        {
             i = CreateABC(OpCode.Test, i.B, 0, i.C);
             i = CreateABC(OpCode.Test, i.B, 0, i.C);
+        }
+
         return true;
         return true;
     }
     }
 
 
@@ -561,7 +621,7 @@ internal class Function : IPoolNode<Function>
         for (int next; list != NoJump; list = next)
         for (int next; list != NoJump; list = next)
         {
         {
             next = Jump(list);
             next = Jump(list);
-            Assert(Proto.CodeList[list].OpCode == OpCode.Jmp && Proto.CodeList[list].A == 0 || Proto.CodeList[list].A >= level);
+            Assert((Proto.CodeList[list].OpCode == OpCode.Jmp && Proto.CodeList[list].A == 0) || Proto.CodeList[list].A >= level);
             Proto.CodeList[list].A = level;
             Proto.CodeList[list].A = level;
         }
         }
     }
     }
@@ -579,7 +639,11 @@ internal class Function : IPoolNode<Function>
     {
     {
         Assert(IsJumpListWalkable(l1));
         Assert(IsJumpListWalkable(l1));
 
 
-        if (l2 == NoJump) return l1;
+        if (l2 == NoJump)
+        {
+            return l1;
+        }
+
         if (l1 == NoJump)
         if (l1 == NoJump)
         {
         {
             return l2;
             return l2;
@@ -802,18 +866,22 @@ internal class Function : IPoolNode<Function>
 
 
         if (e.HasJumps())
         if (e.HasJumps())
         {
         {
-            int loadFalse = NoJump;
-            int loadTrue = NoJump;
+            var loadFalse = NoJump;
+            var loadTrue = NoJump;
             if (NeedValue(e.T) || NeedValue(e.F))
             if (NeedValue(e.T) || NeedValue(e.F))
             {
             {
-                int jump = NoJump;
-                if (e.Kind != Kind.Jump) jump = Jump();
+                var jump = NoJump;
+                if (e.Kind != Kind.Jump)
+                {
+                    jump = Jump();
+                }
+
                 loadFalse = EncodeLabel(r, 0, 1);
                 loadFalse = EncodeLabel(r, 0, 1);
                 loadTrue = EncodeLabel(r, 1, 0);
                 loadTrue = EncodeLabel(r, 1, 0);
                 PatchToHere(jump);
                 PatchToHere(jump);
             }
             }
 
 
-            int end = Label();
+            var end = Label();
             PatchListHelper(e.F, end, r, loadFalse);
             PatchListHelper(e.F, end, r, loadFalse);
             PatchListHelper(e.T, end, r, loadTrue);
             PatchListHelper(e.T, end, r, loadTrue);
         }
         }
@@ -838,7 +906,10 @@ internal class Function : IPoolNode<Function>
         if (e.Kind == Kind.NonRelocatable)
         if (e.Kind == Kind.NonRelocatable)
         {
         {
             if (!e.HasJumps())
             if (!e.HasJumps())
+            {
                 return e;
                 return e;
+            }
+
             if (e.Info >= ActiveVariableCount)
             if (e.Info >= ActiveVariableCount)
             {
             {
                 return ExpressionToRegister(e, e.Info);
                 return ExpressionToRegister(e, e.Info);
@@ -860,7 +931,11 @@ internal class Function : IPoolNode<Function>
 
 
     public ExprDesc ExpressionToValue(ExprDesc e)
     public ExprDesc ExpressionToValue(ExprDesc e)
     {
     {
-        if (e.HasJumps()) return ExpressionToAnyRegister(e);
+        if (e.HasJumps())
+        {
+            return ExpressionToAnyRegister(e);
+        }
+
         return DischargeVariables(e);
         return DischargeVariables(e);
     }
     }
 
 
@@ -936,7 +1011,7 @@ internal class Function : IPoolNode<Function>
         e = ExpressionToAnyRegister(e);
         e = ExpressionToAnyRegister(e);
         var r = e.Info;
         var r = e.Info;
         FreeExpression(e);
         FreeExpression(e);
-        var result = new ExprDesc { Info = FreeRegisterCount, Kind = Kind.NonRelocatable }; // base register for opSelf
+        ExprDesc result = new() { Info = FreeRegisterCount, Kind = Kind.NonRelocatable }; // base register for opSelf
         ReserveRegisters(2); // function and 'self' produced by opSelf
         ReserveRegisters(2); // function and 'self' produced by opSelf
         (key, var k) = ExpressionToRegisterOrConstant(key);
         (key, var k) = ExpressionToRegisterOrConstant(key);
         EncodeABC(OpCode.Self, result.Info, r, k);
         EncodeABC(OpCode.Self, result.Info, r, k);
@@ -1059,7 +1134,9 @@ internal class Function : IPoolNode<Function>
         var (_, i) = ExpressionToRegisterOrConstant(k);
         var (_, i) = ExpressionToRegisterOrConstant(k);
         r.Index = i;
         r.Index = i;
         if (t.Kind == Kind.UpValue)
         if (t.Kind == Kind.UpValue)
+        {
             r.TableType = Kind.UpValue;
             r.TableType = Kind.UpValue;
+        }
         else
         else
         {
         {
             Assert(t.Kind == Kind.NonRelocatable || t.Kind == Kind.Local);
             Assert(t.Kind == Kind.NonRelocatable || t.Kind == Kind.Local);
@@ -1070,7 +1147,7 @@ internal class Function : IPoolNode<Function>
     }
     }
 
 
 
 
-    private static double Arith(OpCode op, double v1, double v2)
+    static double Arith(OpCode op, double v1, double v2)
     {
     {
         switch (op)
         switch (op)
         {
         {
@@ -1083,7 +1160,7 @@ internal class Function : IPoolNode<Function>
             case OpCode.Div:
             case OpCode.Div:
                 return v1 / v2;
                 return v1 / v2;
             case OpCode.Mod:
             case OpCode.Mod:
-                return v1 - Math.Floor(v1 / v2) * v2;
+                return v1 - (Math.Floor(v1 / v2) * v2);
             case OpCode.Pow:
             case OpCode.Pow:
                 return Math.Pow(v1, v2);
                 return Math.Pow(v1, v2);
             case OpCode.Unm:
             case OpCode.Unm:
@@ -1096,9 +1173,15 @@ internal class Function : IPoolNode<Function>
     public static (ExprDesc, bool) FoldConstants(OpCode op, ExprDesc e1, ExprDesc e2)
     public static (ExprDesc, bool) FoldConstants(OpCode op, ExprDesc e1, ExprDesc e2)
     {
     {
         if (!e1.IsNumeral() || !e2.IsNumeral())
         if (!e1.IsNumeral() || !e2.IsNumeral())
+        {
             return (e1, false);
             return (e1, false);
+        }
+
         if ((op == OpCode.Div || op == OpCode.Mod) && e2.Value == 0.0)
         if ((op == OpCode.Div || op == OpCode.Mod) && e2.Value == 0.0)
+        {
             return (e1, false);
             return (e1, false);
+        }
+
         e1.Value = Arith(op, e1.Value, e2.Value);
         e1.Value = Arith(op, e1.Value, e2.Value);
         return (e1, true);
         return (e1, true);
     }
     }
@@ -1107,7 +1190,10 @@ internal class Function : IPoolNode<Function>
     {
     {
         var (e, folded) = FoldConstants(op, e1, e2);
         var (e, folded) = FoldConstants(op, e1, e2);
         if (folded)
         if (folded)
+        {
             return e;
             return e;
+        }
+
         var o2 = 0;
         var o2 = 0;
         if (op != OpCode.Unm && op != OpCode.Len)
         if (op != OpCode.Unm && op != OpCode.Len)
         {
         {
@@ -1173,7 +1259,10 @@ internal class Function : IPoolNode<Function>
             case OprMod:
             case OprMod:
             case OprPow:
             case OprPow:
                 if (!e.IsNumeral())
                 if (!e.IsNumeral())
+                {
                     (e, _) = ExpressionToRegisterOrConstant(e);
                     (e, _) = ExpressionToRegisterOrConstant(e);
+                }
+
                 break;
                 break;
             default:
             default:
                 (e, _) = ExpressionToRegisterOrConstant(e);
                 (e, _) = ExpressionToRegisterOrConstant(e);
@@ -1217,7 +1306,7 @@ internal class Function : IPoolNode<Function>
                 {
                 {
                     Assert(e1.Info == Instruction(e2).B - 1);
                     Assert(e1.Info == Instruction(e2).B - 1);
                     FreeExpression(e1);
                     FreeExpression(e1);
-                    Instruction(e2).B = (e1.Info);
+                    Instruction(e2).B = e1.Info;
                     return MakeExpression(Kind.Relocatable, e2.Info);
                     return MakeExpression(Kind.Relocatable, e2.Info);
                 }
                 }
 
 
@@ -1242,7 +1331,10 @@ internal class Function : IPoolNode<Function>
         }
         }
     }
     }
 
 
-    public void FixLine(int line) => Proto.LineInfoList[Proto.CodeList.Length - 1] = line;
+    public void FixLine(int line)
+    {
+        Proto.LineInfoList[Proto.CodeList.Length - 1] = line;
+    }
 
 
 
 
     public void SetList(int @base, int elementCount, int storeCount)
     public void SetList(int @base, int elementCount, int storeCount)
@@ -1253,7 +1345,7 @@ internal class Function : IPoolNode<Function>
             storeCount = 0;
             storeCount = 0;
         }
         }
 
 
-        var c = (elementCount - 1) / ListItemsPerFlush + 1;
+        var c = ((elementCount - 1) / ListItemsPerFlush) + 1;
         if (c <= MaxArgC)
         if (c <= MaxArgC)
         {
         {
             EncodeABC(OpCode.SetList, @base, storeCount, c);
             EncodeABC(OpCode.SetList, @base, storeCount, c);
@@ -1453,8 +1545,8 @@ internal class Function : IPoolNode<Function>
 
 
     public void FlushFieldToConstructor(int tableRegister, int freeRegisterCount, ExprDesc k, Func<ExprDesc> v)
     public void FlushFieldToConstructor(int tableRegister, int freeRegisterCount, ExprDesc k, Func<ExprDesc> v)
     {
     {
-        (_, var rk) = ExpressionToRegisterOrConstant(k);
-        (_, var rv) = ExpressionToRegisterOrConstant(v());
+        var (_, rk) = ExpressionToRegisterOrConstant(k);
+        var (_, rv) = ExpressionToRegisterOrConstant(v());
         EncodeABC(OpCode.SetTable, tableRegister, rk, rv);
         EncodeABC(OpCode.SetTable, tableRegister, rk, rv);
         FreeRegisterCount = freeRegisterCount;
         FreeRegisterCount = freeRegisterCount;
     }
     }
@@ -1492,8 +1584,8 @@ internal class Function : IPoolNode<Function>
             }
             }
         }
         }
 
 
-        Proto.CodeList[pc].B = (((arrayCount)));
-        Proto.CodeList[pc].C = (((hashCount)));
+        Proto.CodeList[pc].B = arrayCount;
+        Proto.CodeList[pc].C = hashCount;
     }
     }
 
 
     public int OpenForBody(int @base, int n, bool isNumeric)
     public int OpenForBody(int @base, int n, bool isNumeric)

+ 55 - 30
src/Lua/CodeAnalysis/Compilation/Parser.cs

@@ -10,14 +10,22 @@ using static Function;
 using static Scanner;
 using static Scanner;
 using static Constants;
 using static Constants;
 
 
-internal class Parser : IPoolNode<Parser>, IDisposable
+class Parser : IPoolNode<Parser>, IDisposable
 {
 {
     /// inline
     /// inline
     internal Scanner Scanner;
     internal Scanner Scanner;
 
 
     internal int T => Scanner.Token.T;
     internal int T => Scanner.Token.T;
-    internal bool TestNext(int token) => Scanner.TestNext(token);
-    internal void Next() => Scanner.Next();
+
+    internal bool TestNext(int token)
+    {
+        return Scanner.TestNext(token);
+    }
+
+    internal void Next()
+    {
+        Scanner.Next();
+    }
 
 
     internal Function Function = null!;
     internal Function Function = null!;
     internal FastListCore<int> ActiveVariables;
     internal FastListCore<int> ActiveVariables;
@@ -29,6 +37,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
     }
     }
 
 
     Parser? nextNode;
     Parser? nextNode;
+
     ref Parser? IPoolNode<Parser>.NextNode => ref nextNode;
     ref Parser? IPoolNode<Parser>.NextNode => ref nextNode;
 
 
     static LinkedPool<Parser> pool;
     static LinkedPool<Parser> pool;
@@ -37,14 +46,17 @@ internal class Parser : IPoolNode<Parser>, IDisposable
     {
     {
         if (!pool.TryPop(out var parser))
         if (!pool.TryPop(out var parser))
         {
         {
-            parser = new Parser();
+            parser = new();
         }
         }
 
 
         parser.Scanner = scanner;
         parser.Scanner = scanner;
         return parser;
         return parser;
     }
     }
 
 
-    void IDisposable.Dispose() => Release();
+    void IDisposable.Dispose()
+    {
+        Release();
+    }
 
 
     public void Release()
     public void Release()
     {
     {
@@ -76,7 +88,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
     {
     {
         if (val > limit)
         if (val > limit)
         {
         {
-            string where = "main function";
+            var where = "main function";
             var line = Function.Proto.LineDefined;
             var line = Function.Proto.LineDefined;
             if (line != 0)
             if (line != 0)
             {
             {
@@ -93,20 +105,29 @@ internal class Parser : IPoolNode<Parser>, IDisposable
         Next();
         Next();
     }
     }
 
 
-    public ExprDesc CheckNameAsExpression() => Function.EncodeString(CheckName());
+    public ExprDesc CheckNameAsExpression()
+    {
+        return Function.EncodeString(CheckName());
+    }
 
 
 
 
-    public ExprDesc SingleVariable() => Function.SingleVariable(CheckName());
+    public ExprDesc SingleVariable()
+    {
+        return Function.SingleVariable(CheckName());
+    }
 
 
 
 
-    public void LeaveLevel() => Scanner.L.CallCount--;
+    public void LeaveLevel()
+    {
+        Scanner.L.CallCount--;
+    }
 
 
 
 
     public TempBlock EnterLevel()
     public TempBlock EnterLevel()
     {
     {
         Scanner.L.CallCount++;
         Scanner.L.CallCount++;
         CheckLimit(Scanner.L.CallCount, MaxCallCount, "Go levels");
         CheckLimit(Scanner.L.CallCount, MaxCallCount, "Go levels");
-        return new TempBlock(Scanner.L);
+        return new(Scanner.L);
     }
     }
 
 
     public (ExprDesc e, int n) ExpressionList()
     public (ExprDesc e, int n) ExpressionList()
@@ -233,7 +254,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
             case '(':
             case '(':
                 var line = Scanner.LineNumber;
                 var line = Scanner.LineNumber;
                 Next();
                 Next();
-                ExprDesc e = Expression();
+                var e = Expression();
                 Scanner.CheckMatch(')', '(', line);
                 Scanner.CheckMatch(')', '(', line);
                 e = Function.DischargeVariables(e);
                 e = Function.DischargeVariables(e);
                 return e;
                 return e;
@@ -366,10 +387,10 @@ internal class Parser : IPoolNode<Parser>, IDisposable
     {
     {
         using var b = EnterLevel();
         using var b = EnterLevel();
         ExprDesc e;
         ExprDesc e;
-        int u = UnaryOp(T);
+        var u = UnaryOp(T);
         if (u != OprNoUnary)
         if (u != OprNoUnary)
         {
         {
-            int line = Scanner.LineNumber;
+            var line = Scanner.LineNumber;
             Next();
             Next();
             (e, _) = SubExpression(UnaryPriority);
             (e, _) = SubExpression(UnaryPriority);
             e = Function.Prefix(u, e, line);
             e = Function.Prefix(u, e, line);
@@ -379,13 +400,13 @@ internal class Parser : IPoolNode<Parser>, IDisposable
             e = SimpleExpression();
             e = SimpleExpression();
         }
         }
 
 
-        int op = BinaryOp(T);
+        var op = BinaryOp(T);
         while (op != OprNoBinary && priority[op].Left > limit)
         while (op != OprNoBinary && priority[op].Left > limit)
         {
         {
-            int line = Scanner.LineNumber;
+            var line = Scanner.LineNumber;
             Next();
             Next();
             e = Function.Infix(op, e);
             e = Function.Infix(op, e);
-            (ExprDesc e2, int next) = SubExpression(priority[op].Right);
+            var (e2, next) = SubExpression(priority[op].Right);
             e = Function.Postfix(op, e, e2, line);
             e = Function.Postfix(op, e, e2, line);
             op = next;
             op = next;
         }
         }
@@ -395,7 +416,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
 
 
     public ExprDesc Expression()
     public ExprDesc Expression()
     {
     {
-        (ExprDesc e, _) = SubExpression(0);
+        var (e, _) = SubExpression(0);
         return e;
         return e;
     }
     }
 
 
@@ -439,7 +460,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
     public ExprDesc Index()
     public ExprDesc Index()
     {
     {
         Next(); // skip '['
         Next(); // skip '['
-        ExprDesc e = Function.ExpressionToValue(Expression());
+        var e = Function.ExpressionToValue(Expression());
         CheckNext(']');
         CheckNext(']');
         return e;
         return e;
     }
     }
@@ -449,14 +470,14 @@ internal class Parser : IPoolNode<Parser>, IDisposable
         CheckCondition(t.Description.IsVariable(), "syntax error");
         CheckCondition(t.Description.IsVariable(), "syntax error");
         if (TestNext(','))
         if (TestNext(','))
         {
         {
-            ExprDesc e = SuffixedExpression();
+            var e = SuffixedExpression();
             if (e.Kind != Kind.Indexed)
             if (e.Kind != Kind.Indexed)
             {
             {
                 Function.CheckConflict(t, e);
                 Function.CheckConflict(t, e);
             }
             }
 
 
             CheckLimit(variableCount + Scanner.L.CallCount, MaxCallCount, "Go levels");
             CheckLimit(variableCount + Scanner.L.CallCount, MaxCallCount, "Go levels");
-            Assignment(new(previous: ref t, exprDesc: e), variableCount + 1);
+            Assignment(new(ref t, e), variableCount + 1);
         }
         }
         else
         else
         {
         {
@@ -515,7 +536,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
 
 
         void Expr()
         void Expr()
         {
         {
-            ExprDesc e = Function.ExpressionToNextRegister(Expression());
+            var e = Function.ExpressionToNextRegister(Expression());
             Assert(e.Kind == Kind.NonRelocatable);
             Assert(e.Kind == Kind.NonRelocatable);
         }
         }
     }
     }
@@ -760,7 +781,11 @@ internal class Parser : IPoolNode<Parser>, IDisposable
     public (ExprDesc, bool IsMethod) FunctionName()
     public (ExprDesc, bool IsMethod) FunctionName()
     {
     {
         var e = SingleVariable();
         var e = SingleVariable();
-        for (; T == '.'; e = FieldSelector(e)) ;
+        for (; T == '.'; e = FieldSelector(e))
+        {
+            ;
+        }
+
         if (T == ':')
         if (T == ':')
         {
         {
             e = FieldSelector(e);
             e = FieldSelector(e);
@@ -782,7 +807,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
     {
     {
         Function.MakeLocalVariable(CheckName());
         Function.MakeLocalVariable(CheckName());
         Function.AdjustLocalVariables(1);
         Function.AdjustLocalVariables(1);
-        Function.LocalVariable(Body(false, Scanner.LineNumber).Info).StartPc = (Function.Proto.CodeList.Length);
+        Function.LocalVariable(Body(false, Scanner.LineNumber).Info).StartPc = Function.Proto.CodeList.Length;
     }
     }
 
 
     public void LocalStatement()
     public void LocalStatement()
@@ -801,7 +826,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
         }
         }
         else
         else
         {
         {
-            var e = default(ExprDesc);
+            ExprDesc e = default;
             Function.AdjustAssignment(v, 0, e);
             Function.AdjustAssignment(v, 0, e);
         }
         }
 
 
@@ -813,12 +838,12 @@ internal class Parser : IPoolNode<Parser>, IDisposable
         var e = SuffixedExpression();
         var e = SuffixedExpression();
         if (T == '=' || T == ',')
         if (T == '=' || T == ',')
         {
         {
-            Assignment(new AssignmentTarget(ref Unsafe.NullRef<AssignmentTarget>(), exprDesc: e), 1);
+            Assignment(new(ref Unsafe.NullRef<AssignmentTarget>(), e), 1);
         }
         }
         else
         else
         {
         {
             CheckCondition(e.Kind == Kind.Call, "syntax error");
             CheckCondition(e.Kind == Kind.Call, "syntax error");
-            Function.Instruction(e).C = (1); // call statement uses no results
+            Function.Instruction(e).C = 1; // call statement uses no results
         }
         }
     }
     }
 
 
@@ -920,7 +945,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
             LookAheadToken = new(0, TkEos),
             LookAheadToken = new(0, TkEos),
             L = l,
             L = l,
             Source = name,
             Source = name,
-            Buffer = new PooledList<char>(r.Length)
+            Buffer = new(r.Length)
         });
         });
         var f = Function.Get(p, PrototypeBuilder.Get(name));
         var f = Function.Get(p, PrototypeBuilder.Get(name));
         p.Function = f;
         p.Function = f;
@@ -932,13 +957,13 @@ internal class Parser : IPoolNode<Parser>, IDisposable
 
 
     public static void Dump(Prototype prototype, IBufferWriter<byte> writer, bool useLittleEndian = true)
     public static void Dump(Prototype prototype, IBufferWriter<byte> writer, bool useLittleEndian = true)
     {
     {
-        var state = new DumpState(writer, useLittleEndian ^ BitConverter.IsLittleEndian);
+        DumpState state = new(writer, useLittleEndian ^ BitConverter.IsLittleEndian);
         state.Dump(prototype);
         state.Dump(prototype);
     }
     }
 
 
     public static byte[] Dump(Prototype prototype, bool useLittleEndian = true)
     public static byte[] Dump(Prototype prototype, bool useLittleEndian = true)
     {
     {
-        var writer = new ArrayBufferWriter<byte>();
+        ArrayBufferWriter<byte> writer = new();
         Dump(prototype, writer, useLittleEndian);
         Dump(prototype, writer, useLittleEndian);
         return writer.WrittenSpan.ToArray();
         return writer.WrittenSpan.ToArray();
     }
     }
@@ -955,7 +980,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
             };
             };
         }
         }
 
 
-        var state = new UnDumpState(span, name);
+        UnDumpState state = new(span, name);
         return state.UnDump();
         return state.UnDump();
     }
     }
 }
 }

+ 16 - 3
src/Lua/CodeAnalysis/Compilation/PrototypeBuilder.cs

@@ -3,20 +3,32 @@ using Lua.Runtime;
 
 
 namespace Lua.CodeAnalysis.Compilation;
 namespace Lua.CodeAnalysis.Compilation;
 
 
-internal class PrototypeBuilder : IPoolNode<PrototypeBuilder>
+class PrototypeBuilder : IPoolNode<PrototypeBuilder>
 {
 {
     internal FastListCore<LuaValue> ConstantsList;
     internal FastListCore<LuaValue> ConstantsList;
+
     public ReadOnlySpan<LuaValue> Constants => ConstantsList.AsSpan();
     public ReadOnlySpan<LuaValue> Constants => ConstantsList.AsSpan();
+
     internal FastListCore<Instruction> CodeList;
     internal FastListCore<Instruction> CodeList;
+
     public ReadOnlySpan<Instruction> Code => CodeList.AsSpan();
     public ReadOnlySpan<Instruction> Code => CodeList.AsSpan();
+
     internal FastListCore<PrototypeBuilder> PrototypeList;
     internal FastListCore<PrototypeBuilder> PrototypeList;
+
     public ReadOnlySpan<PrototypeBuilder> Prototypes => PrototypeList.AsSpan();
     public ReadOnlySpan<PrototypeBuilder> Prototypes => PrototypeList.AsSpan();
+
     internal FastListCore<int> LineInfoList;
     internal FastListCore<int> LineInfoList;
+
     public ReadOnlySpan<int> LineInfo => LineInfoList.AsSpan();
     public ReadOnlySpan<int> LineInfo => LineInfoList.AsSpan();
+
     internal FastListCore<LocalVariable> LocalVariablesList;
     internal FastListCore<LocalVariable> LocalVariablesList;
+
     public ReadOnlySpan<LocalVariable> LocalVariables => LocalVariablesList.AsSpan();
     public ReadOnlySpan<LocalVariable> LocalVariables => LocalVariablesList.AsSpan();
+
     internal FastListCore<UpValueDesc> UpValuesList;
     internal FastListCore<UpValueDesc> UpValuesList;
+
     public ReadOnlySpan<UpValueDesc> UpValues => UpValuesList.AsSpan();
     public ReadOnlySpan<UpValueDesc> UpValues => UpValuesList.AsSpan();
+
     public string Source;
     public string Source;
     public int LineDefined, LastLineDefined;
     public int LineDefined, LastLineDefined;
     public int ParameterCount, MaxStackSize;
     public int ParameterCount, MaxStackSize;
@@ -32,13 +44,14 @@ internal class PrototypeBuilder : IPoolNode<PrototypeBuilder>
 
 
 
 
     PrototypeBuilder? nextNode;
     PrototypeBuilder? nextNode;
+
     ref PrototypeBuilder? IPoolNode<PrototypeBuilder>.NextNode => ref nextNode;
     ref PrototypeBuilder? IPoolNode<PrototypeBuilder>.NextNode => ref nextNode;
 
 
     internal static PrototypeBuilder Get(string source)
     internal static PrototypeBuilder Get(string source)
     {
     {
         if (!pool.TryPop(out var f))
         if (!pool.TryPop(out var f))
         {
         {
-            f = new PrototypeBuilder(source);
+            f = new(source);
         }
         }
 
 
         f.Source = source;
         f.Source = source;
@@ -64,7 +77,7 @@ internal class PrototypeBuilder : IPoolNode<PrototypeBuilder>
             protoTypes[i] = Prototypes[i].CreatePrototypeAndRelease(); //ref
             protoTypes[i] = Prototypes[i].CreatePrototypeAndRelease(); //ref
         }
         }
 
 
-        var p = new Prototype(Source, LineDefined, LastLineDefined, ParameterCount, MaxStackSize, IsVarArg, Constants.ToArray(), Code.ToArray(), protoTypes, LineInfo.ToArray(), LocalVariables.ToArray(), UpValues.ToArray());
+        Prototype p = new(Source, LineDefined, LastLineDefined, ParameterCount, MaxStackSize, IsVarArg, Constants.ToArray(), Code.ToArray(), protoTypes, LineInfo.ToArray(), LocalVariables.ToArray(), UpValues.ToArray());
         Release();
         Release();
         return p;
         return p;
     }
     }

+ 127 - 54
src/Lua/CodeAnalysis/Compilation/Scanner.cs

@@ -7,7 +7,7 @@ namespace Lua.CodeAnalysis.Compilation;
 
 
 using static Constants;
 using static Constants;
 
 
-internal struct Scanner
+struct Scanner
 {
 {
     public LuaState L;
     public LuaState L;
     public PooledList<char> Buffer;
     public PooledList<char> Buffer;
@@ -16,7 +16,7 @@ internal struct Scanner
     public int LineNumber, LastLine;
     public int LineNumber, LastLine;
     public string Source;
     public string Source;
     public Token LookAheadToken;
     public Token LookAheadToken;
-    private int lastNewLinePos;
+    int lastNewLinePos;
 
 
     ///inline
     ///inline
     public Token Token;
     public Token Token;
@@ -26,7 +26,7 @@ internal struct Scanner
     public const int FirstReserved = ushort.MaxValue + 257;
     public const int FirstReserved = ushort.MaxValue + 257;
     public const int EndOfStream = -1;
     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 TkAnd = FirstReserved;
     public const int TkBreak = TkAnd + 1;
     public const int TkBreak = TkAnd + 1;
@@ -75,46 +75,73 @@ internal struct Scanner
     ];
     ];
 
 
     public static ReadOnlySpan<string> Tokens => tokens;
     public static ReadOnlySpan<string> Tokens => tokens;
-    public void SyntaxError(int position, string message) => ScanError(position, message, Token.T);
-    public void SyntaxError(string message) => ScanError(R.Position, message, Token.T);
-    public void ErrorExpected(int position, char t) => SyntaxError(position, TokenToString(t) + " expected");
+
+    public void SyntaxError(int position, string message)
+    {
+        ScanError(position, message, Token.T);
+    }
+
+    public void SyntaxError(string message)
+    {
+        ScanError(R.Position, message, Token.T);
+    }
+
+    public void ErrorExpected(int position, char t)
+    {
+        SyntaxError(position, TokenToString(t) + " expected");
+    }
 
 
     public void NumberError(int numberStartPosition, int position)
     public void NumberError(int numberStartPosition, int position)
     {
     {
         Buffer.Clear();
         Buffer.Clear();
-        Token = new Token(numberStartPosition, TkString, R.Span[numberStartPosition..(position - 1)].ToString());
+        Token = new(numberStartPosition, TkString, R.Span[numberStartPosition..(position - 1)].ToString());
         ScanError(position, "malformed number", TkString);
         ScanError(position, "malformed number", TkString);
     }
     }
 
 
-    public static bool IsNewLine(int c) => c is '\n' or '\r';
+    public static bool IsNewLine(int c)
+    {
+        return c is '\n' or '\r';
+    }
 
 
-    public static bool IsDecimal(int c) => c is >= '0' and <= '9';
+    public static bool IsDecimal(int c)
+    {
+        return c is >= '0' and <= '9';
+    }
 
 
 
 
-    public static string TokenToString(Token t) => t.T switch
+    public static string TokenToString(Token t)
     {
     {
-        TkName or TkString => t.S,
-        TkNumber => $"{t.N}",
-        < FirstReserved => $"{(char)t.T}", // TODO check for printable rune
-        < TkEos => $"'{tokens[t.T - FirstReserved]}'",
-        _ => tokens[t.T - FirstReserved]
-    };
+        return t.T switch
+        {
+            TkName or TkString => t.S,
+            TkNumber => $"{t.N}",
+            < FirstReserved => $"{(char)t.T}", // TODO check for printable rune
+            < TkEos => $"'{tokens[t.T - FirstReserved]}'",
+            _ => tokens[t.T - FirstReserved]
+        };
+    }
 
 
-    public string TokenToString(int t) => t switch
+    public string TokenToString(int t)
     {
     {
-        TkName or TkString => Token.S,
-        TkNumber => $"{Token.N}",
-        < FirstReserved => $"{(char)t}", // TODO check for printable rune
-        < TkEos => $"'{tokens[t - FirstReserved]}'",
-        _ => tokens[t - FirstReserved]
-    };
+        return t switch
+        {
+            TkName or TkString => Token.S,
+            TkNumber => $"{Token.N}",
+            < FirstReserved => $"{(char)t}", // TODO check for printable rune
+            < TkEos => $"'{tokens[t - FirstReserved]}'",
+            _ => tokens[t - FirstReserved]
+        };
+    }
 
 
-    public static string TokenRuteToString(int t) => t switch
+    public static string TokenRuteToString(int t)
     {
     {
-        < FirstReserved => $"{(char)t}", // TODO check for printable rune
-        <= TkString => $"'{tokens[t - FirstReserved]}'",
-        _ => tokens[t - FirstReserved]
-    };
+        return t switch
+        {
+            < FirstReserved => $"{(char)t}", // TODO check for printable rune
+            <= TkString => $"'{tokens[t - FirstReserved]}'",
+            _ => tokens[t - FirstReserved]
+        };
+    }
 
 
     public void ScanError(int pos, string message, int token)
     public void ScanError(int pos, string message, int token)
     {
     {
@@ -127,7 +154,7 @@ internal struct Scanner
             nearToken = TokenToString(token);
             nearToken = TokenToString(token);
         }
         }
 
 
-        throw new LuaCompileException(buff, new SourcePosition(LineNumber, pos - lastNewLinePos + 1), pos - 1, message, nearToken);
+        throw new LuaCompileException(buff, new(LineNumber, pos - lastNewLinePos + 1), pos - 1, message, nearToken);
     }
     }
 
 
     public void IncrementLineNumber()
     public void IncrementLineNumber()
@@ -135,9 +162,16 @@ internal struct Scanner
         var old = Current;
         var old = Current;
         Assert(IsNewLine(old));
         Assert(IsNewLine(old));
         Advance();
         Advance();
-        if (IsNewLine(Current) && Current != old) Advance();
+        if (IsNewLine(Current) && Current != old)
+        {
+            Advance();
+        }
+
         lastNewLinePos = R.Position;
         lastNewLinePos = R.Position;
-        if (++LineNumber >= MaxLine) SyntaxError(lastNewLinePos, "chunk has too many lines");
+        if (++LineNumber >= MaxLine)
+        {
+            SyntaxError(lastNewLinePos, "chunk has too many lines");
+        }
     }
     }
 
 
     public void Advance()
     public void Advance()
@@ -164,7 +198,11 @@ internal struct Scanner
 
 
     public bool CheckNext(string str)
     public bool CheckNext(string str)
     {
     {
-        if (Current == 0 || !str.Contains((char)Current)) return false;
+        if (Current == 0 || !str.Contains((char)Current))
+        {
+            return false;
+        }
+
         SaveAndAdvance();
         SaveAndAdvance();
         return true;
         return true;
     }
     }
@@ -173,8 +211,16 @@ internal struct Scanner
     {
     {
         var (i, c) = (0, Current);
         var (i, c) = (0, Current);
         Assert(c is '[' or ']');
         Assert(c is '[' or ']');
-        for (SaveAndAdvance(); Current == '='; i++) SaveAndAdvance();
-        if (Current == c) return i;
+        for (SaveAndAdvance(); Current == '='; i++)
+        {
+            SaveAndAdvance();
+        }
+
+        if (Current == c)
+        {
+            return i;
+        }
+
         return -i - 1;
         return -i - 1;
     }
     }
 
 
@@ -200,7 +246,7 @@ internal struct Scanner
                         SaveAndAdvance();
                         SaveAndAdvance();
                         if (!comment)
                         if (!comment)
                         {
                         {
-                            var s = Buffer.AsSpan().Slice(2 + sep, Buffer.Length - (4 + 2 * sep)).ToString();
+                            var s = Buffer.AsSpan().Slice(2 + sep, Buffer.Length - (4 + (2 * sep))).ToString();
                             Buffer.Clear();
                             Buffer.Clear();
                             return s;
                             return s;
                         }
                         }
@@ -231,11 +277,18 @@ internal struct Scanner
     public int ReadDigits()
     public int ReadDigits()
     {
     {
         var c = Current;
         var c = Current;
-        for (; IsDecimal(c); c = Current) SaveAndAdvance();
+        for (; IsDecimal(c); c = Current)
+        {
+            SaveAndAdvance();
+        }
+
         return c;
         return c;
     }
     }
 
 
-    public static bool IsHexadecimal(int c) => c is >= '0' and <= '9' or >= 'a' and <= 'f' or >= 'A' and <= 'F';
+    public static bool IsHexadecimal(int c)
+    {
+        return c is >= '0' and <= '9' or >= 'a' and <= 'f' or >= 'A' and <= 'F';
+    }
 
 
     public (double n, int c, int i) ReadHexNumber(double x, ref int position)
     public (double n, int c, int i) ReadHexNumber(double x, ref int position)
     {
     {
@@ -263,13 +316,17 @@ internal struct Scanner
                     break;
                     break;
                 case EndOfStream or '}' or ',' or '.' or ')' or 'p' or 'P': return (n, c, i);
                 case EndOfStream or '}' or ',' or '.' or ')' or 'p' or 'P': return (n, c, i);
                 default:
                 default:
-                    if (IsWhiteSpace(c)) return (n, c, i);
+                    if (IsWhiteSpace(c))
+                    {
+                        return (n, c, i);
+                    }
+
                     return (n, 0, 0);
                     return (n, 0, 0);
             }
             }
 
 
             Advance();
             Advance();
             position++;
             position++;
-            (c, n, i) = (Current, n * 16.0 + c, i + 1);
+            (c, n, i) = (Current, (n * 16.0) + c, i + 1);
         }
         }
     }
     }
 
 
@@ -315,13 +372,13 @@ internal struct Scanner
 
 
                 _ = ReadDigits();
                 _ = ReadDigits();
 
 
-                if (!long.TryParse(Buffer.AsSpan(), NumberStyles.Float, CultureInfo.InvariantCulture, out long e))
+                if (!long.TryParse(Buffer.AsSpan(), NumberStyles.Float, CultureInfo.InvariantCulture, out var e))
                 {
                 {
                     NumberError(startPosition, pos + 1);
                     NumberError(startPosition, pos + 1);
                 }
                 }
                 else if (negativeExponent)
                 else if (negativeExponent)
                 {
                 {
-                    exponent += (int)(-e);
+                    exponent += (int)-e;
                 }
                 }
                 else
                 else
                 {
                 {
@@ -368,7 +425,7 @@ internal struct Scanner
             }
             }
         }
         }
 
 
-        if (!double.TryParse(strSpan, NumberStyles.Float, CultureInfo.InvariantCulture, out double f))
+        if (!double.TryParse(strSpan, NumberStyles.Float, CultureInfo.InvariantCulture, out var f))
         {
         {
             NumberError(startPosition, pos);
             NumberError(startPosition, pos);
         }
         }
@@ -388,7 +445,7 @@ internal struct Scanner
         { 'v', '\v' },
         { 'v', '\v' },
         { '\\', '\\' },
         { '\\', '\\' },
         { '"', '"' },
         { '"', '"' },
-        { '\'', '\'' },
+        { '\'', '\'' }
     };
     };
 
 
     public void EscapeError(int pos, ReadOnlySpan<int> c, string message)
     public void EscapeError(int pos, ReadOnlySpan<int> c, string message)
@@ -428,10 +485,10 @@ internal struct Scanner
                     c -= '0';
                     c -= '0';
                     break;
                     break;
                 case >= 'a' and <= 'f':
                 case >= 'a' and <= 'f':
-                    c -= ('a' - 10);
+                    c -= 'a' - 10;
                     break;
                     break;
                 case >= 'A' and <= 'F':
                 case >= 'A' and <= 'F':
-                    c -= ('A' - 10);
+                    c -= 'A' - 10;
                     break;
                     break;
                 default:
                 default:
                     EscapeError(R.Position - 1, b.Slice(0, i + 1), "hexadecimal digit expected");
                     EscapeError(R.Position - 1, b.Slice(0, i + 1), "hexadecimal digit expected");
@@ -450,10 +507,10 @@ internal struct Scanner
         var c = Current;
         var c = Current;
         var r = 0;
         var r = 0;
         var pos = R.Position;
         var pos = R.Position;
-        for (int i = 0; i < b.Length && IsDecimal(c); i++, c = Current)
+        for (var i = 0; i < b.Length && IsDecimal(c); i++, c = Current)
         {
         {
             b[i] = c;
             b[i] = c;
-            r = 10 * r + c - '0';
+            r = (10 * r) + c - '0';
             Advance();
             Advance();
             pos = R.Position;
             pos = R.Position;
         }
         }
@@ -564,7 +621,7 @@ internal struct Scanner
         {
         {
             if (str == Tokens[i])
             if (str == Tokens[i])
             {
             {
-                return new(pos, (i + FirstReserved), str);
+                return new(pos, i + FirstReserved, str);
             }
             }
         }
         }
 
 
@@ -612,7 +669,7 @@ internal struct Scanner
                     }
                     }
 
 
 
 
-                    while (!IsNewLine(Current) && (Current != EndOfStream))
+                    while (!IsNewLine(Current) && Current != EndOfStream)
                     {
                     {
                         Advance();
                         Advance();
                     }
                     }
@@ -627,7 +684,10 @@ internal struct Scanner
                         }
                         }
 
 
                         Buffer.Clear();
                         Buffer.Clear();
-                        if (sep == -1) return new(pos, '[');
+                        if (sep == -1)
+                        {
+                            return new(pos, '[');
+                        }
 
 
                         ScanError(pos, "invalid long string delimiter", TkString);
                         ScanError(pos, "invalid long string delimiter", TkString);
                         break;
                         break;
@@ -755,7 +815,10 @@ internal struct Scanner
     public bool TestNext(int t)
     public bool TestNext(int t)
     {
     {
         var r = Token.T == t;
         var r = Token.T == t;
-        if (!r) return false;
+        if (!r)
+        {
+            return false;
+        }
 
 
         Next();
         Next();
 
 
@@ -772,7 +835,10 @@ internal struct Scanner
 
 
     public void CheckMatch(int what, int who, int where)
     public void CheckMatch(int what, int who, int where)
     {
     {
-        if (TestNext(what)) return;
+        if (TestNext(what))
+        {
+            return;
+        }
 
 
         if (where == LineNumber)
         if (where == LineNumber)
         {
         {
@@ -784,8 +850,15 @@ internal struct Scanner
         }
         }
     }
     }
 
 
-    static bool IsWhiteSpace(int c) => c is ' ' or '\t' or '\n' or '\r' or '\f' or '\v';
-    static bool IsDigit(int c) => c is >= '0' and <= '9';
+    static bool IsWhiteSpace(int c)
+    {
+        return c is ' ' or '\t' or '\n' or '\r' or '\f' or '\v';
+    }
+
+    static bool IsDigit(int c)
+    {
+        return c is >= '0' and <= '9';
+    }
 
 
     static bool IsLetter(int c)
     static bool IsLetter(int c)
     {
     {

+ 1 - 1
src/Lua/CodeAnalysis/Compilation/TempBlock.cs

@@ -1,6 +1,6 @@
 namespace Lua.CodeAnalysis.Compilation;
 namespace Lua.CodeAnalysis.Compilation;
 
 
-internal readonly ref struct TempBlock(LuaState state)
+readonly ref struct TempBlock(LuaState state)
 {
 {
     public void Dispose()
     public void Dispose()
     {
     {

+ 9 - 2
src/Lua/CodeAnalysis/Compilation/Token.cs

@@ -3,7 +3,7 @@
 namespace Lua.CodeAnalysis.Compilation;
 namespace Lua.CodeAnalysis.Compilation;
 
 
 [DebuggerDisplay("{DebuggerDisplay}")]
 [DebuggerDisplay("{DebuggerDisplay}")]
-internal readonly struct Token(int pos, int t)
+readonly struct Token(int pos, int t)
 {
 {
     public Token(int pos, int t, string str) : this(pos, t)
     public Token(int pos, int t, string str) : this(pos, t)
     {
     {
@@ -21,5 +21,12 @@ internal readonly struct Token(int pos, int t)
     public readonly int T = t;
     public readonly int T = t;
     public readonly double N;
     public readonly double N;
     public readonly string S = "";
     public readonly string S = "";
-    string DebuggerDisplay => $"{Scanner.TokenToString(this)} {T} {N} {S}";
+
+    string DebuggerDisplay
+    {
+        get
+        {
+            return $"{Scanner.TokenToString(this)} {T} {N} {S}";
+        }
+    }
 }
 }

+ 5 - 1
src/Lua/CodeAnalysis/SourcePosition.cs

@@ -10,5 +10,9 @@ public record struct SourcePosition
 
 
     public int Line { get; set; }
     public int Line { get; set; }
     public int Column { get; set; }
     public int Column { get; set; }
-    public override readonly string ToString() => $"({Line},{Column})";
+
+    public override readonly string ToString()
+    {
+        return $"({Line},{Column})";
+    }
 }
 }

+ 37 - 10
src/Lua/CodeAnalysis/Syntax/DisplayStringSyntaxVisitor.cs

@@ -27,7 +27,10 @@ public sealed class DisplayStringSyntaxVisitor : ISyntaxNodeVisitor<DisplayStrin
         int indentLevel;
         int indentLevel;
         bool isNewLine = true;
         bool isNewLine = true;
 
 
-        public IndentScope BeginIndentScope() => new(this);
+        public IndentScope BeginIndentScope()
+        {
+            return new(this);
+        }
 
 
         public void Append(string value)
         public void Append(string value)
         {
         {
@@ -58,7 +61,10 @@ public sealed class DisplayStringSyntaxVisitor : ISyntaxNodeVisitor<DisplayStrin
             isNewLine = true;
             isNewLine = true;
         }
         }
 
 
-        public override string ToString() => buffer.ToString();
+        public override string ToString()
+        {
+            return buffer.ToString();
+        }
 
 
         public void IncreaseIndent()
         public void IncreaseIndent()
         {
         {
@@ -68,7 +74,9 @@ public sealed class DisplayStringSyntaxVisitor : ISyntaxNodeVisitor<DisplayStrin
         public void DecreaseIndent()
         public void DecreaseIndent()
         {
         {
             if (indentLevel > 0)
             if (indentLevel > 0)
+            {
                 indentLevel--;
                 indentLevel--;
+            }
         }
         }
 
 
         public void Reset()
         public void Reset()
@@ -146,7 +154,11 @@ public sealed class DisplayStringSyntaxVisitor : ISyntaxNodeVisitor<DisplayStrin
         VisitSyntaxNodes(node.ParameterNodes, context);
         VisitSyntaxNodes(node.ParameterNodes, context);
         if (node.HasVariableArguments)
         if (node.HasVariableArguments)
         {
         {
-            if (node.ParameterNodes.Length > 0) context.Append(", ");
+            if (node.ParameterNodes.Length > 0)
+            {
+                context.Append(", ");
+            }
+
             context.Append("...");
             context.Append("...");
         }
         }
 
 
@@ -174,7 +186,11 @@ public sealed class DisplayStringSyntaxVisitor : ISyntaxNodeVisitor<DisplayStrin
         VisitSyntaxNodes(node.ParameterNodes, context);
         VisitSyntaxNodes(node.ParameterNodes, context);
         if (node.HasVariableArguments)
         if (node.HasVariableArguments)
         {
         {
-            if (node.ParameterNodes.Length > 0) context.Append(", ");
+            if (node.ParameterNodes.Length > 0)
+            {
+                context.Append(", ");
+            }
+
             context.Append("...");
             context.Append("...");
         }
         }
 
 
@@ -198,7 +214,7 @@ public sealed class DisplayStringSyntaxVisitor : ISyntaxNodeVisitor<DisplayStrin
     {
     {
         context.Append("function ");
         context.Append("function ");
 
 
-        for (int i = 0; i < node.MemberPath.Length; i++)
+        for (var i = 0; i < node.MemberPath.Length; i++)
         {
         {
             context.Append(node.MemberPath[i].Name.ToString());
             context.Append(node.MemberPath[i].Name.ToString());
 
 
@@ -216,7 +232,11 @@ public sealed class DisplayStringSyntaxVisitor : ISyntaxNodeVisitor<DisplayStrin
         VisitSyntaxNodes(node.ParameterNodes, context);
         VisitSyntaxNodes(node.ParameterNodes, context);
         if (node.HasVariableArguments)
         if (node.HasVariableArguments)
         {
         {
-            if (node.ParameterNodes.Length > 0) context.Append(", ");
+            if (node.ParameterNodes.Length > 0)
+            {
+                context.Append(", ");
+            }
+
             context.Append("...");
             context.Append("...");
         }
         }
 
 
@@ -450,7 +470,7 @@ public sealed class DisplayStringSyntaxVisitor : ISyntaxNodeVisitor<DisplayStrin
         context.AppendLine("{");
         context.AppendLine("{");
         using (context.BeginIndentScope())
         using (context.BeginIndentScope())
         {
         {
-            for (int i = 0; i < node.Fields.Length; i++)
+            for (var i = 0; i < node.Fields.Length; i++)
             {
             {
                 var field = node.Fields[i];
                 var field = node.Fields[i];
 
 
@@ -513,7 +533,11 @@ public sealed class DisplayStringSyntaxVisitor : ISyntaxNodeVisitor<DisplayStrin
     public bool VisitUnaryExpressionNode(UnaryExpressionNode node, Context context)
     public bool VisitUnaryExpressionNode(UnaryExpressionNode node, Context context)
     {
     {
         context.Append(node.Operator.ToDisplayString());
         context.Append(node.Operator.ToDisplayString());
-        if (node.Operator is UnaryOperator.Not) context.Append(" ");
+        if (node.Operator is UnaryOperator.Not)
+        {
+            context.Append(" ");
+        }
+
         node.Node.Accept(this, context);
         node.Node.Accept(this, context);
 
 
         return true;
         return true;
@@ -547,10 +571,13 @@ public sealed class DisplayStringSyntaxVisitor : ISyntaxNodeVisitor<DisplayStrin
 
 
     void VisitSyntaxNodes(SyntaxNode[] nodes, Context context)
     void VisitSyntaxNodes(SyntaxNode[] nodes, Context context)
     {
     {
-        for (int i = 0; i < nodes.Length; i++)
+        for (var i = 0; i < nodes.Length; i++)
         {
         {
             nodes[i].Accept(this, context);
             nodes[i].Accept(this, context);
-            if (i != nodes.Length - 1) context.Append(", ");
+            if (i != nodes.Length - 1)
+            {
+                context.Append(", ");
+            }
         }
         }
     }
     }
 
 

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

@@ -1,6 +1,6 @@
 namespace Lua.CodeAnalysis.Syntax;
 namespace Lua.CodeAnalysis.Syntax;
 
 
-internal static class Keywords
+static class Keywords
 {
 {
     public const string LF = "\n";
     public const string LF = "\n";
 
 

+ 61 - 19
src/Lua/CodeAnalysis/Syntax/Lexer.cs

@@ -22,7 +22,7 @@ public ref struct Lexer
     void Advance(int count)
     void Advance(int count)
     {
     {
         var span = Source.Span;
         var span = Source.Span;
-        for (int i = 0; i < count; i++)
+        for (var i = 0; i < count; i++)
         {
         {
             if (offset >= span.Length)
             if (offset >= span.Length)
             {
             {
@@ -62,7 +62,10 @@ public ref struct Lexer
 
 
     public bool MoveNext()
     public bool MoveNext()
     {
     {
-        if (Source.Length <= offset) return false;
+        if (Source.Length <= offset)
+        {
+            return false;
+        }
 
 
         var span = Source.Span;
         var span = Source.Span;
         var startOffset = offset;
         var startOffset = offset;
@@ -81,7 +84,11 @@ public ref struct Lexer
                 current = SyntaxToken.EndOfLine(position);
                 current = SyntaxToken.EndOfLine(position);
                 return true;
                 return true;
             case '\r':
             case '\r':
-                if (c2 == '\n') Advance(1);
+                if (c2 == '\n')
+                {
+                    Advance(1);
+                }
+
                 current = SyntaxToken.EndOfLine(position);
                 current = SyntaxToken.EndOfLine(position);
                 return true;
                 return true;
             case '(':
             case '(':
@@ -113,8 +120,11 @@ public ref struct Lexer
                     if (span.Length > offset + 1 && span[offset] is '[' && span[offset + 1] is '[' or '=')
                     if (span.Length > offset + 1 && span[offset] is '[' && span[offset + 1] is '[' or '=')
                     {
                     {
                         Advance(1);
                         Advance(1);
-                        (_, _, var isTerminated) = ReadUntilLongBracketEnd(ref span);
-                        if (!isTerminated) LuaParseException.UnfinishedLongComment(ChunkName, pos);
+                        var (_, _, isTerminated) = ReadUntilLongBracketEnd(ref span);
+                        if (!isTerminated)
+                        {
+                            LuaParseException.UnfinishedLongComment(ChunkName, pos);
+                        }
                     }
                     }
                     else // line comment
                     else // line comment
                     {
                     {
@@ -191,7 +201,7 @@ public ref struct Lexer
             case '.':
             case '.':
                 if (c2 == '.')
                 if (c2 == '.')
                 {
                 {
-                    var c3 = span.Length == (offset + 1) ? char.MinValue : span[offset + 1];
+                    var c3 = span.Length == offset + 1 ? char.MinValue : span[offset + 1];
 
 
                     if (c3 == '.')
                     if (c3 == '.')
                     {
                     {
@@ -233,7 +243,10 @@ public ref struct Lexer
             if (c1 is '0' && c2 is 'x' or 'X') // hex 0x
             if (c1 is '0' && c2 is 'x' or 'X') // hex 0x
             {
             {
                 Advance(1);
                 Advance(1);
-                if (span[offset] is '.') Advance(1);
+                if (span[offset] is '.')
+                {
+                    Advance(1);
+                }
 
 
                 ReadDigit(ref span, ref offset, out var readCount);
                 ReadDigit(ref span, ref offset, out var readCount);
 
 
@@ -246,7 +259,10 @@ public ref struct Lexer
                 if (span.Length > offset && span[offset] is 'p' or 'P')
                 if (span.Length > offset && span[offset] is 'p' or 'P')
                 {
                 {
                     Advance(1);
                     Advance(1);
-                    if (span[offset] is '-' or '+') Advance(1);
+                    if (span[offset] is '-' or '+')
+                    {
+                        Advance(1);
+                    }
 
 
                     ReadDigit(ref span, ref offset, out _);
                     ReadDigit(ref span, ref offset, out _);
                 }
                 }
@@ -269,7 +285,10 @@ public ref struct Lexer
                 if (span.Length > offset && span[offset] is 'e' or 'E')
                 if (span.Length > offset && span[offset] is 'e' or 'E')
                 {
                 {
                     Advance(1);
                     Advance(1);
-                    if (span[offset] is '-' or '+') Advance(1);
+                    if (span[offset] is '-' or '+')
+                    {
+                        Advance(1);
+                    }
 
 
                     ReadNumber(ref span, ref offset, out _);
                     ReadNumber(ref span, ref offset, out _);
                 }
                 }
@@ -292,7 +311,10 @@ public ref struct Lexer
                 while (span.Length > offset)
                 while (span.Length > offset)
                 {
                 {
                     var c = span[offset];
                     var c = span[offset];
-                    if (prevC == ':' && c == ':') break;
+                    if (prevC == ':' && c == ':')
+                    {
+                        break;
+                    }
 
 
                     Advance(1);
                     Advance(1);
                     prevC = c;
                     prevC = c;
@@ -329,11 +351,22 @@ public ref struct Lexer
                 {
                 {
                     Advance(1);
                     Advance(1);
 
 
-                    if (span.Length <= offset) break;
+                    if (span.Length <= offset)
+                    {
+                        break;
+                    }
+
                     if (span[offset] == '\r')
                     if (span[offset] == '\r')
                     {
                     {
-                        if (span.Length <= offset + 1) continue;
-                        if (span[offset + 1] == '\n') Advance(1);
+                        if (span.Length <= offset + 1)
+                        {
+                            continue;
+                        }
+
+                        if (span[offset + 1] == '\n')
+                        {
+                            Advance(1);
+                        }
                     }
                     }
                 }
                 }
                 else if (c == quote)
                 else if (c == quote)
@@ -360,7 +393,7 @@ public ref struct Lexer
         {
         {
             if (c2 is '[' or '=')
             if (c2 is '[' or '=')
             {
             {
-                (var start, var end, var isTerminated) = ReadUntilLongBracketEnd(ref span);
+                var (start, end, isTerminated) = ReadUntilLongBracketEnd(ref span);
 
 
                 if (!isTerminated)
                 if (!isTerminated)
                 {
                 {
@@ -411,7 +444,7 @@ public ref struct Lexer
                 Keywords.Until => SyntaxToken.Until(position),
                 Keywords.Until => SyntaxToken.Until(position),
                 Keywords.Break => SyntaxToken.Break(position),
                 Keywords.Break => SyntaxToken.Break(position),
                 Keywords.Function => SyntaxToken.Function(position),
                 Keywords.Function => SyntaxToken.Function(position),
-                _ => new(SyntaxTokenType.Identifier, identifier, position),
+                _ => new(SyntaxTokenType.Identifier, identifier, position)
             };
             };
 
 
             return true;
             return true;
@@ -427,7 +460,10 @@ public ref struct Lexer
         var flag = true;
         var flag = true;
         while (flag)
         while (flag)
         {
         {
-            if (span.Length <= offset) return;
+            if (span.Length <= offset)
+            {
+                return;
+            }
 
 
             var c1 = span[offset];
             var c1 = span[offset];
 
 
@@ -495,12 +531,18 @@ public ref struct Lexer
             {
             {
                 endOffset = offset;
                 endOffset = offset;
 
 
-                for (int i = 1; i <= level; i++)
+                for (var i = 1; i <= level; i++)
                 {
                 {
-                    if (span[offset + i] is not '=') goto CONTINUE;
+                    if (span[offset + i] is not '=')
+                    {
+                        goto CONTINUE;
+                    }
                 }
                 }
 
 
-                if (span[offset + level + 1] is not ']') goto CONTINUE;
+                if (span[offset + level + 1] is not ']')
+                {
+                    goto CONTINUE;
+                }
 
 
                 Advance(level + 2);
                 Advance(level + 2);
                 isTerminated = true;
                 isTerminated = true;

+ 2 - 2
src/Lua/CodeAnalysis/Syntax/LuaSyntaxTree.cs

@@ -9,9 +9,9 @@ public record LuaSyntaxTree(SyntaxNode[] Nodes, SourcePosition Position) : Synta
 
 
     public static LuaSyntaxTree Parse(string source, string? chunkName = null)
     public static LuaSyntaxTree Parse(string source, string? chunkName = null)
     {
     {
-        var lexer = new Lexer { Source = source.AsMemory(), ChunkName = chunkName, };
+        Lexer lexer = new() { Source = source.AsMemory(), ChunkName = chunkName };
 
 
-        var parser = new Parser { ChunkName = chunkName };
+        Parser parser = new() { ChunkName = chunkName };
 
 
         while (lexer.MoveNext())
         while (lexer.MoveNext())
         {
         {

+ 3 - 3
src/Lua/CodeAnalysis/Syntax/Nodes/BinaryExpressionNode.cs

@@ -16,10 +16,10 @@ public enum BinaryOperator
     LessThanOrEqual,
     LessThanOrEqual,
     And,
     And,
     Or,
     Or,
-    Concat,
+    Concat
 }
 }
 
 
-internal static class BinaryOperatorEx
+static class BinaryOperatorEx
 {
 {
     public static string ToDisplayString(this BinaryOperator @operator)
     public static string ToDisplayString(this BinaryOperator @operator)
     {
     {
@@ -40,7 +40,7 @@ internal static class BinaryOperatorEx
             BinaryOperator.And => Keywords.And,
             BinaryOperator.And => Keywords.And,
             BinaryOperator.Or => Keywords.Or,
             BinaryOperator.Or => Keywords.Or,
             BinaryOperator.Concat => Keywords.Concat,
             BinaryOperator.Concat => Keywords.Concat,
-            _ => "",
+            _ => ""
         };
         };
     }
     }
 }
 }

+ 3 - 3
src/Lua/CodeAnalysis/Syntax/Nodes/UnaryExpressionNode.cs

@@ -4,7 +4,7 @@ public enum UnaryOperator
 {
 {
     Negate,
     Negate,
     Not,
     Not,
-    Length,
+    Length
 }
 }
 
 
 public record UnaryExpressionNode(UnaryOperator Operator, ExpressionNode Node, SourcePosition Position) : ExpressionNode(Position)
 public record UnaryExpressionNode(UnaryOperator Operator, ExpressionNode Node, SourcePosition Position) : ExpressionNode(Position)
@@ -15,7 +15,7 @@ public record UnaryExpressionNode(UnaryOperator Operator, ExpressionNode Node, S
     }
     }
 }
 }
 
 
-internal static class UnaryOperatorEx
+static class UnaryOperatorEx
 {
 {
     public static string ToDisplayString(this UnaryOperator @operator)
     public static string ToDisplayString(this UnaryOperator @operator)
     {
     {
@@ -24,7 +24,7 @@ internal static class UnaryOperatorEx
             UnaryOperator.Negate => Keywords.Subtraction,
             UnaryOperator.Negate => Keywords.Subtraction,
             UnaryOperator.Not => Keywords.Not,
             UnaryOperator.Not => Keywords.Not,
             UnaryOperator.Length => Keywords.Length,
             UnaryOperator.Length => Keywords.Length,
-            _ => "",
+            _ => ""
         };
         };
     }
     }
 }
 }

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

@@ -45,5 +45,5 @@ public enum OperatorPrecedence
     /// <summary>
     /// <summary>
     /// Exponentiation (^)
     /// Exponentiation (^)
     /// </summary>
     /// </summary>
-    Exponentiation,
+    Exponentiation
 }
 }

+ 97 - 56
src/Lua/CodeAnalysis/Syntax/Parser.cs

@@ -13,7 +13,10 @@ public ref struct Parser
     PooledList<SyntaxToken> tokens;
     PooledList<SyntaxToken> tokens;
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
-    public void Add(SyntaxToken token) => tokens.Add(token);
+    public void Add(SyntaxToken token)
+    {
+        tokens.Add(token);
+    }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public void Dispose()
     public void Dispose()
@@ -23,12 +26,15 @@ public ref struct Parser
 
 
     public LuaSyntaxTree Parse()
     public LuaSyntaxTree Parse()
     {
     {
-        using var root = new PooledList<SyntaxNode>(64);
+        using PooledList<SyntaxNode> root = new(64);
 
 
-        var enumerator = new SyntaxTokenEnumerator(tokens.AsSpan());
+        SyntaxTokenEnumerator enumerator = new(tokens.AsSpan());
         while (enumerator.MoveNext())
         while (enumerator.MoveNext())
         {
         {
-            if (enumerator.Current.Type is SyntaxTokenType.EndOfLine or SyntaxTokenType.SemiColon) continue;
+            if (enumerator.Current.Type is SyntaxTokenType.EndOfLine or SyntaxTokenType.SemiColon)
+            {
+                continue;
+            }
 
 
             var node = ParseStatement(ref enumerator);
             var node = ParseStatement(ref enumerator);
             root.Add(node);
             root.Add(node);
@@ -36,7 +42,7 @@ public ref struct Parser
 
 
         var tokensSpan = tokens.AsSpan();
         var tokensSpan = tokens.AsSpan();
         var lastToken = tokensSpan[0];
         var lastToken = tokensSpan[0];
-        for (int i = tokensSpan.Length - 1; 0 < i; i--)
+        for (var i = tokensSpan.Length - 1; 0 < i; i--)
         {
         {
             var t = tokensSpan[i];
             var t = tokensSpan[i];
             if (t.Type is not SyntaxTokenType.EndOfLine)
             if (t.Type is not SyntaxTokenType.EndOfLine)
@@ -46,7 +52,7 @@ public ref struct Parser
             }
             }
         }
         }
 
 
-        var tree = new LuaSyntaxTree(root.AsSpan().ToArray(), lastToken.Position);
+        LuaSyntaxTree tree = new(root.AsSpan().ToArray(), lastToken.Position);
         Dispose();
         Dispose();
 
 
         return tree;
         return tree;
@@ -138,7 +144,7 @@ public ref struct Parser
                     }
                     }
                     else if (nextType is SyntaxTokenType.EndOfLine or SyntaxTokenType.SemiColon)
                     else if (nextType is SyntaxTokenType.EndOfLine or SyntaxTokenType.SemiColon)
                     {
                     {
-                        return new LocalAssignmentStatementNode([new IdentifierNode(enumerator.Current.Text, enumerator.Current.Position)], [], localToken.Position);
+                        return new LocalAssignmentStatementNode([new(enumerator.Current.Text, enumerator.Current.Position)], [], localToken.Position);
                     }
                     }
                 }
                 }
                 break;
                 break;
@@ -171,7 +177,7 @@ public ref struct Parser
         // parse parameters
         // parse parameters
         var expressions = ParseExpressionList(ref enumerator);
         var expressions = ParseExpressionList(ref enumerator);
 
 
-        return new ReturnStatementNode(expressions, returnToken.Position);
+        return new(expressions, returnToken.Position);
     }
     }
 
 
     DoStatementNode ParseDoStatement(ref SyntaxTokenEnumerator enumerator)
     DoStatementNode ParseDoStatement(ref SyntaxTokenEnumerator enumerator)
@@ -183,7 +189,7 @@ public ref struct Parser
         // parse statements
         // parse statements
         var statements = ParseStatementList(ref enumerator, SyntaxTokenType.End, out _);
         var statements = ParseStatementList(ref enumerator, SyntaxTokenType.End, out _);
 
 
-        return new DoStatementNode(statements, doToken.Position);
+        return new(statements, doToken.Position);
     }
     }
 
 
     GotoStatementNode ParseGotoStatement(ref SyntaxTokenEnumerator enumerator)
     GotoStatementNode ParseGotoStatement(ref SyntaxTokenEnumerator enumerator)
@@ -192,13 +198,13 @@ public ref struct Parser
         CheckCurrentAndSkip(ref enumerator, SyntaxTokenType.Goto, out var gotoToken);
         CheckCurrentAndSkip(ref enumerator, SyntaxTokenType.Goto, out var gotoToken);
 
 
         CheckCurrent(ref enumerator, SyntaxTokenType.Identifier);
         CheckCurrent(ref enumerator, SyntaxTokenType.Identifier);
-        return new GotoStatementNode(enumerator.Current.Text, gotoToken.Position);
+        return new(enumerator.Current.Text, gotoToken.Position);
     }
     }
 
 
     AssignmentStatementNode ParseAssignmentStatement(ExpressionNode firstExpression, ref SyntaxTokenEnumerator enumerator)
     AssignmentStatementNode ParseAssignmentStatement(ExpressionNode firstExpression, ref SyntaxTokenEnumerator enumerator)
     {
     {
         // parse leftNodes
         // parse leftNodes
-        using var leftNodes = new PooledList<SyntaxNode>(8);
+        using PooledList<SyntaxNode> leftNodes = new(8);
         leftNodes.Add(firstExpression);
         leftNodes.Add(firstExpression);
 
 
         while (enumerator.Current.Type == SyntaxTokenType.Comma)
         while (enumerator.Current.Type == SyntaxTokenType.Comma)
@@ -219,7 +225,7 @@ public ref struct Parser
         if (enumerator.Current.Type is not SyntaxTokenType.Assignment)
         if (enumerator.Current.Type is not SyntaxTokenType.Assignment)
         {
         {
             enumerator.MovePrevious();
             enumerator.MovePrevious();
-            return new AssignmentStatementNode(leftNodes.AsSpan().ToArray(), [], firstExpression.Position);
+            return new(leftNodes.AsSpan().ToArray(), [], firstExpression.Position);
         }
         }
 
 
         MoveNextWithValidation(ref enumerator);
         MoveNextWithValidation(ref enumerator);
@@ -227,7 +233,7 @@ public ref struct Parser
         // parse expressions
         // parse expressions
         var expressions = ParseExpressionList(ref enumerator);
         var expressions = ParseExpressionList(ref enumerator);
 
 
-        return new AssignmentStatementNode(leftNodes.AsSpan().ToArray(), expressions, firstExpression.Position);
+        return new(leftNodes.AsSpan().ToArray(), expressions, firstExpression.Position);
     }
     }
 
 
     LocalAssignmentStatementNode ParseLocalAssignmentStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken localToken)
     LocalAssignmentStatementNode ParseLocalAssignmentStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken localToken)
@@ -239,7 +245,7 @@ public ref struct Parser
         if (enumerator.Current.Type is not SyntaxTokenType.Assignment)
         if (enumerator.Current.Type is not SyntaxTokenType.Assignment)
         {
         {
             enumerator.MovePrevious();
             enumerator.MovePrevious();
-            return new LocalAssignmentStatementNode(identifiers, [], localToken.Position);
+            return new(identifiers, [], localToken.Position);
         }
         }
 
 
         MoveNextWithValidation(ref enumerator);
         MoveNextWithValidation(ref enumerator);
@@ -247,7 +253,7 @@ public ref struct Parser
         // parse expressions
         // parse expressions
         var expressions = ParseExpressionList(ref enumerator);
         var expressions = ParseExpressionList(ref enumerator);
 
 
-        return new LocalAssignmentStatementNode(identifiers, expressions, localToken.Position);
+        return new(identifiers, expressions, localToken.Position);
     }
     }
 
 
     IfStatementNode ParseIfStatement(ref SyntaxTokenEnumerator enumerator)
     IfStatementNode ParseIfStatement(ref SyntaxTokenEnumerator enumerator)
@@ -265,8 +271,8 @@ public ref struct Parser
         CheckCurrent(ref enumerator, SyntaxTokenType.Then);
         CheckCurrent(ref enumerator, SyntaxTokenType.Then);
         var thenToken = enumerator.Current;
         var thenToken = enumerator.Current;
 
 
-        using var builder = new PooledList<StatementNode>(64);
-        using var elseIfBuilder = new PooledList<IfStatementNode.ConditionAndThenNodes>(64);
+        using PooledList<StatementNode> builder = new(64);
+        using PooledList<IfStatementNode.ConditionAndThenNodes> elseIfBuilder = new(64);
 
 
         IfStatementNode.ConditionAndThenNodes ifNodes = default!;
         IfStatementNode.ConditionAndThenNodes ifNodes = default!;
         StatementNode[] elseNodes = [];
         StatementNode[] elseNodes = [];
@@ -294,11 +300,11 @@ public ref struct Parser
                 switch (state)
                 switch (state)
                 {
                 {
                     case 0:
                     case 0:
-                        ifNodes = new() { Position = thenToken.Position, ConditionNode = condition, ThenNodes = builder.AsSpan().ToArray(), };
+                        ifNodes = new() { Position = thenToken.Position, ConditionNode = condition, ThenNodes = builder.AsSpan().ToArray() };
                         builder.Clear();
                         builder.Clear();
                         break;
                         break;
                     case 1:
                     case 1:
-                        elseIfBuilder.Add(new() { Position = thenToken.Position, ConditionNode = condition, ThenNodes = builder.AsSpan().ToArray(), });
+                        elseIfBuilder.Add(new() { Position = thenToken.Position, ConditionNode = condition, ThenNodes = builder.AsSpan().ToArray() });
                         builder.Clear();
                         builder.Clear();
                         break;
                         break;
                     case 2:
                     case 2:
@@ -343,7 +349,7 @@ public ref struct Parser
         }
         }
 
 
     RETURN:
     RETURN:
-        return new IfStatementNode(ifNodes, elseIfBuilder.AsSpan().ToArray(), elseNodes, ifToken.Position);
+        return new(ifNodes, elseIfBuilder.AsSpan().ToArray(), elseNodes, ifToken.Position);
     }
     }
 
 
     WhileStatementNode ParseWhileStatement(ref SyntaxTokenEnumerator enumerator)
     WhileStatementNode ParseWhileStatement(ref SyntaxTokenEnumerator enumerator)
@@ -363,7 +369,7 @@ public ref struct Parser
         // parse statements
         // parse statements
         var statements = ParseStatementList(ref enumerator, SyntaxTokenType.End, out _);
         var statements = ParseStatementList(ref enumerator, SyntaxTokenType.End, out _);
 
 
-        return new WhileStatementNode(condition, statements, whileToken.Position);
+        return new(condition, statements, whileToken.Position);
     }
     }
 
 
     RepeatStatementNode ParseRepeatStatement(ref SyntaxTokenEnumerator enumerator)
     RepeatStatementNode ParseRepeatStatement(ref SyntaxTokenEnumerator enumerator)
@@ -382,7 +388,7 @@ public ref struct Parser
         // parse condition
         // parse condition
         var condition = ParseExpression(ref enumerator, GetPrecedence(enumerator.Current.Type));
         var condition = ParseExpression(ref enumerator, GetPrecedence(enumerator.Current.Type));
 
 
-        return new RepeatStatementNode(condition, statements, repeatToken.Position);
+        return new(condition, statements, repeatToken.Position);
     }
     }
 
 
     NumericForStatementNode ParseNumericForStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken forToken)
     NumericForStatementNode ParseNumericForStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken forToken)
@@ -431,7 +437,7 @@ public ref struct Parser
         // parse statements
         // parse statements
         var statements = ParseStatementList(ref enumerator, SyntaxTokenType.End, out _);
         var statements = ParseStatementList(ref enumerator, SyntaxTokenType.End, out _);
 
 
-        return new NumericForStatementNode(varName, initialValueNode, limitNode, stepNode, statements, forToken.Position, doToken.Position);
+        return new(varName, initialValueNode, limitNode, stepNode, statements, forToken.Position, doToken.Position);
     }
     }
 
 
     GenericForStatementNode ParseGenericForStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken forToken)
     GenericForStatementNode ParseGenericForStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken forToken)
@@ -453,19 +459,19 @@ public ref struct Parser
         // parse statements
         // parse statements
         var statements = ParseStatementList(ref enumerator, SyntaxTokenType.End, out var endToken);
         var statements = ParseStatementList(ref enumerator, SyntaxTokenType.End, out var endToken);
 
 
-        return new GenericForStatementNode(identifiers, expressions, statements, iteratorToken.Position, doToken.Position, endToken.Position);
+        return new(identifiers, expressions, statements, iteratorToken.Position, doToken.Position, endToken.Position);
     }
     }
 
 
     FunctionDeclarationStatementNode ParseFunctionDeclarationStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken functionToken)
     FunctionDeclarationStatementNode ParseFunctionDeclarationStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken functionToken)
     {
     {
         var (Name, Identifiers, Statements, HasVariableArgments, LineDefined, EndPosition) = ParseFunctionDeclarationCore(ref enumerator, false);
         var (Name, Identifiers, Statements, HasVariableArgments, LineDefined, EndPosition) = ParseFunctionDeclarationCore(ref enumerator, false);
-        return new FunctionDeclarationStatementNode(Name, Identifiers, Statements, HasVariableArgments, functionToken.Position, LineDefined, EndPosition);
+        return new(Name, Identifiers, Statements, HasVariableArgments, functionToken.Position, LineDefined, EndPosition);
     }
     }
 
 
     LocalFunctionDeclarationStatementNode ParseLocalFunctionDeclarationStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken functionToken)
     LocalFunctionDeclarationStatementNode ParseLocalFunctionDeclarationStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken functionToken)
     {
     {
         var (Name, Identifiers, Statements, HasVariableArgments, LineDefined, EndPosition) = ParseFunctionDeclarationCore(ref enumerator, false);
         var (Name, Identifiers, Statements, HasVariableArgments, LineDefined, EndPosition) = ParseFunctionDeclarationCore(ref enumerator, false);
-        return new LocalFunctionDeclarationStatementNode(Name, Identifiers, Statements, HasVariableArgments, functionToken.Position, LineDefined, EndPosition);
+        return new(Name, Identifiers, Statements, HasVariableArgments, functionToken.Position, LineDefined, EndPosition);
     }
     }
 
 
     (ReadOnlyMemory<char> Name, IdentifierNode[] Identifiers, StatementNode[] Statements, bool HasVariableArgments, int LineDefined, SourcePosition EndPosition) ParseFunctionDeclarationCore(ref SyntaxTokenEnumerator enumerator, bool isAnonymous)
     (ReadOnlyMemory<char> Name, IdentifierNode[] Identifiers, StatementNode[] Statements, bool HasVariableArgments, int LineDefined, SourcePosition EndPosition) ParseFunctionDeclarationCore(ref SyntaxTokenEnumerator enumerator, bool isAnonymous)
@@ -497,7 +503,10 @@ public ref struct Parser
 
 
         // check variable arguments
         // check variable arguments
         var hasVarArg = enumerator.Current.Type is SyntaxTokenType.VarArg;
         var hasVarArg = enumerator.Current.Type is SyntaxTokenType.VarArg;
-        if (hasVarArg) enumerator.MoveNext();
+        if (hasVarArg)
+        {
+            enumerator.MoveNext();
+        }
 
 
         // skip ')'
         // skip ')'
         CheckCurrent(ref enumerator, SyntaxTokenType.RParen);
         CheckCurrent(ref enumerator, SyntaxTokenType.RParen);
@@ -510,13 +519,13 @@ public ref struct Parser
 
 
     TableMethodDeclarationStatementNode ParseTableMethodDeclarationStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken functionToken)
     TableMethodDeclarationStatementNode ParseTableMethodDeclarationStatement(ref SyntaxTokenEnumerator enumerator, SyntaxToken functionToken)
     {
     {
-        using var names = new PooledList<IdentifierNode>(32);
+        using PooledList<IdentifierNode> names = new(32);
         var hasSelfParameter = false;
         var hasSelfParameter = false;
         SyntaxToken leftParenToken;
         SyntaxToken leftParenToken;
         while (true)
         while (true)
         {
         {
             CheckCurrent(ref enumerator, SyntaxTokenType.Identifier);
             CheckCurrent(ref enumerator, SyntaxTokenType.Identifier);
-            names.Add(new IdentifierNode(enumerator.Current.Text, enumerator.Current.Position));
+            names.Add(new(enumerator.Current.Text, enumerator.Current.Position));
             MoveNextWithValidation(ref enumerator);
             MoveNextWithValidation(ref enumerator);
             enumerator.SkipEoL();
             enumerator.SkipEoL();
 
 
@@ -549,7 +558,10 @@ public ref struct Parser
 
 
         // check variable arguments
         // check variable arguments
         var hasVarArg = enumerator.Current.Type is SyntaxTokenType.VarArg;
         var hasVarArg = enumerator.Current.Type is SyntaxTokenType.VarArg;
-        if (hasVarArg) enumerator.MoveNext();
+        if (hasVarArg)
+        {
+            enumerator.MoveNext();
+        }
 
 
         // skip ')'
         // skip ')'
         CheckCurrent(ref enumerator, SyntaxTokenType.RParen);
         CheckCurrent(ref enumerator, SyntaxTokenType.RParen);
@@ -557,7 +569,7 @@ public ref struct Parser
         // parse statements
         // parse statements
         var statements = ParseStatementList(ref enumerator, SyntaxTokenType.End, out var endToken);
         var statements = ParseStatementList(ref enumerator, SyntaxTokenType.End, out var endToken);
 
 
-        return new TableMethodDeclarationStatementNode(names.AsSpan().ToArray(), identifiers, statements, hasVarArg, hasSelfParameter, functionToken.Position, leftParenToken.Position.Line, endToken.Position);
+        return new(names.AsSpan().ToArray(), identifiers, statements, hasVarArg, hasSelfParameter, functionToken.Position, leftParenToken.Position.Line, endToken.Position);
     }
     }
 
 
     bool TryParseExpression(ref SyntaxTokenEnumerator enumerator, OperatorPrecedence precedence, [NotNullWhen(true)] out ExpressionNode? result)
     bool TryParseExpression(ref SyntaxTokenEnumerator enumerator, OperatorPrecedence precedence, [NotNullWhen(true)] out ExpressionNode? result)
@@ -568,7 +580,7 @@ public ref struct Parser
             {
             {
                 SyntaxTokenType.LParen or SyntaxTokenType.String or SyntaxTokenType.RawString => ParseCallFunctionExpression(ref enumerator, null),
                 SyntaxTokenType.LParen or SyntaxTokenType.String or SyntaxTokenType.RawString => ParseCallFunctionExpression(ref enumerator, null),
                 SyntaxTokenType.LSquare or SyntaxTokenType.Dot or SyntaxTokenType.Colon => ParseTableAccessExpression(ref enumerator, null),
                 SyntaxTokenType.LSquare or SyntaxTokenType.Dot or SyntaxTokenType.Colon => ParseTableAccessExpression(ref enumerator, null),
-                _ => new IdentifierNode(enumerator.Current.Text, enumerator.Current.Position),
+                _ => new IdentifierNode(enumerator.Current.Text, enumerator.Current.Position)
             },
             },
             SyntaxTokenType.Number => new NumericLiteralNode(ConvertTextToNumber(enumerator.Current.Text.Span), enumerator.Current.Position),
             SyntaxTokenType.Number => new NumericLiteralNode(ConvertTextToNumber(enumerator.Current.Text.Span), enumerator.Current.Position),
             SyntaxTokenType.String => new StringLiteralNode(enumerator.Current.Text, true, enumerator.Current.Position),
             SyntaxTokenType.String => new StringLiteralNode(enumerator.Current.Text, true, enumerator.Current.Position),
@@ -582,10 +594,13 @@ public ref struct Parser
             SyntaxTokenType.LParen => ParseGroupedExpression(ref enumerator),
             SyntaxTokenType.LParen => ParseGroupedExpression(ref enumerator),
             SyntaxTokenType.LCurly => ParseTableConstructorExpression(ref enumerator),
             SyntaxTokenType.LCurly => ParseTableConstructorExpression(ref enumerator),
             SyntaxTokenType.Function => ParseFunctionDeclarationExpression(ref enumerator),
             SyntaxTokenType.Function => ParseFunctionDeclarationExpression(ref enumerator),
-            _ => null,
+            _ => null
         };
         };
 
 
-        if (result == null) return false;
+        if (result == null)
+        {
+            return false;
+        }
 
 
         // nested table access & function call
         // nested table access & function call
     RECURSIVE:
     RECURSIVE:
@@ -609,7 +624,10 @@ public ref struct Parser
         while (true)
         while (true)
         {
         {
             var opPrecedence = GetPrecedence(enumerator.GetNext(true).Type);
             var opPrecedence = GetPrecedence(enumerator.GetNext(true).Type);
-            if (precedence >= opPrecedence) break;
+            if (precedence >= opPrecedence)
+            {
+                break;
+            }
 
 
             MoveNextWithValidation(ref enumerator);
             MoveNextWithValidation(ref enumerator);
             enumerator.SkipEoL();
             enumerator.SkipEoL();
@@ -654,13 +672,13 @@ public ref struct Parser
             SyntaxTokenType.Subtraction => UnaryOperator.Negate,
             SyntaxTokenType.Subtraction => UnaryOperator.Negate,
             SyntaxTokenType.Not => UnaryOperator.Not,
             SyntaxTokenType.Not => UnaryOperator.Not,
             SyntaxTokenType.Length => UnaryOperator.Length,
             SyntaxTokenType.Length => UnaryOperator.Length,
-            _ => throw new LuaParseException(ChunkName, operatorToken.Position, $"unexpected symbol near '{enumerator.Current.Text}'"),
+            _ => throw new LuaParseException(ChunkName, operatorToken.Position, $"unexpected symbol near '{enumerator.Current.Text}'")
         };
         };
 
 
         MoveNextWithValidation(ref enumerator);
         MoveNextWithValidation(ref enumerator);
         var right = ParseExpression(ref enumerator, OperatorPrecedence.Unary);
         var right = ParseExpression(ref enumerator, OperatorPrecedence.Unary);
 
 
-        return new UnaryExpressionNode(operatorType, right, operatorToken.Position);
+        return new(operatorType, right, operatorToken.Position);
     }
     }
 
 
     BinaryExpressionNode ParseBinaryExpression(ref SyntaxTokenEnumerator enumerator, OperatorPrecedence precedence, ExpressionNode left)
     BinaryExpressionNode ParseBinaryExpression(ref SyntaxTokenEnumerator enumerator, OperatorPrecedence precedence, ExpressionNode left)
@@ -683,7 +701,7 @@ public ref struct Parser
             SyntaxTokenType.And => BinaryOperator.And,
             SyntaxTokenType.And => BinaryOperator.And,
             SyntaxTokenType.Or => BinaryOperator.Or,
             SyntaxTokenType.Or => BinaryOperator.Or,
             SyntaxTokenType.Concat => BinaryOperator.Concat,
             SyntaxTokenType.Concat => BinaryOperator.Concat,
-            _ => throw new LuaParseException(ChunkName, enumerator.Current.Position, $"unexpected symbol near '{enumerator.Current.Text}'"),
+            _ => throw new LuaParseException(ChunkName, enumerator.Current.Position, $"unexpected symbol near '{enumerator.Current.Text}'")
         };
         };
 
 
         enumerator.SkipEoL();
         enumerator.SkipEoL();
@@ -692,7 +710,7 @@ public ref struct Parser
 
 
         var right = ParseExpression(ref enumerator, precedence);
         var right = ParseExpression(ref enumerator, precedence);
 
 
-        return new BinaryExpressionNode(operatorType, left, right, operatorToken.Position);
+        return new(operatorType, left, right, operatorToken.Position);
     }
     }
 
 
     TableConstructorExpressionNode ParseTableConstructorExpression(ref SyntaxTokenEnumerator enumerator)
     TableConstructorExpressionNode ParseTableConstructorExpression(ref SyntaxTokenEnumerator enumerator)
@@ -700,7 +718,7 @@ public ref struct Parser
         CheckCurrent(ref enumerator, SyntaxTokenType.LCurly);
         CheckCurrent(ref enumerator, SyntaxTokenType.LCurly);
         var startToken = enumerator.Current;
         var startToken = enumerator.Current;
 
 
-        using var items = new PooledList<TableConstructorField>(16);
+        using PooledList<TableConstructorField> items = new(16);
 
 
         while (enumerator.MoveNext())
         while (enumerator.MoveNext())
         {
         {
@@ -749,7 +767,7 @@ public ref struct Parser
         }
         }
 
 
     RETURN:
     RETURN:
-        return new TableConstructorExpressionNode(items.AsSpan().ToArray(), startToken.Position);
+        return new(items.AsSpan().ToArray(), startToken.Position);
     }
     }
 
 
     ExpressionNode ParseTableAccessExpression(ref SyntaxTokenEnumerator enumerator, ExpressionNode? parentTable)
     ExpressionNode ParseTableAccessExpression(ref SyntaxTokenEnumerator enumerator, ExpressionNode? parentTable)
@@ -759,7 +777,7 @@ public ref struct Parser
         {
         {
             // parse identifier
             // parse identifier
             CheckCurrent(ref enumerator, SyntaxTokenType.Identifier);
             CheckCurrent(ref enumerator, SyntaxTokenType.Identifier);
-            identifier = new IdentifierNode(enumerator.Current.Text, enumerator.Current.Position);
+            identifier = new(enumerator.Current.Text, enumerator.Current.Position);
             MoveNextWithValidation(ref enumerator);
             MoveNextWithValidation(ref enumerator);
             enumerator.SkipEoL();
             enumerator.SkipEoL();
         }
         }
@@ -837,7 +855,7 @@ public ref struct Parser
         // check ')'
         // check ')'
         CheckCurrent(ref enumerator, SyntaxTokenType.RParen);
         CheckCurrent(ref enumerator, SyntaxTokenType.RParen);
 
 
-        return new GroupedExpressionNode(expression, lParen.Position);
+        return new(expression, lParen.Position);
     }
     }
 
 
     ExpressionNode ParseCallFunctionExpression(ref SyntaxTokenEnumerator enumerator, ExpressionNode? function)
     ExpressionNode ParseCallFunctionExpression(ref SyntaxTokenEnumerator enumerator, ExpressionNode? function)
@@ -864,7 +882,7 @@ public ref struct Parser
         enumerator.SkipEoL();
         enumerator.SkipEoL();
 
 
         var (_, Identifiers, Statements, HasVariableArgments, LineDefined, LastLineDefined) = ParseFunctionDeclarationCore(ref enumerator, true);
         var (_, Identifiers, Statements, HasVariableArgments, LineDefined, LastLineDefined) = ParseFunctionDeclarationCore(ref enumerator, true);
-        return new FunctionDeclarationExpressionNode(Identifiers, Statements, HasVariableArgments, functionToken.Position, LineDefined, LastLineDefined);
+        return new(Identifiers, Statements, HasVariableArgments, functionToken.Position, LineDefined, LastLineDefined);
     }
     }
 
 
     ExpressionNode[] ParseCallFunctionArguments(ref SyntaxTokenEnumerator enumerator)
     ExpressionNode[] ParseCallFunctionArguments(ref SyntaxTokenEnumerator enumerator)
@@ -909,7 +927,7 @@ public ref struct Parser
 
 
     ExpressionNode[] ParseExpressionList(ref SyntaxTokenEnumerator enumerator)
     ExpressionNode[] ParseExpressionList(ref SyntaxTokenEnumerator enumerator)
     {
     {
-        using var builder = new PooledList<ExpressionNode>(8);
+        using PooledList<ExpressionNode> builder = new(8);
 
 
         while (true)
         while (true)
         {
         {
@@ -924,12 +942,18 @@ public ref struct Parser
             builder.Add(expression);
             builder.Add(expression);
 
 
             enumerator.SkipEoL();
             enumerator.SkipEoL();
-            if (enumerator.GetNext().Type != SyntaxTokenType.Comma) break;
+            if (enumerator.GetNext().Type != SyntaxTokenType.Comma)
+            {
+                break;
+            }
 
 
             MoveNextWithValidation(ref enumerator);
             MoveNextWithValidation(ref enumerator);
             enumerator.SkipEoL();
             enumerator.SkipEoL();
 
 
-            if (!enumerator.MoveNext()) break;
+            if (!enumerator.MoveNext())
+            {
+                break;
+            }
         }
         }
 
 
         return builder.AsSpan().ToArray();
         return builder.AsSpan().ToArray();
@@ -937,18 +961,25 @@ public ref struct Parser
 
 
     IdentifierNode[] ParseIdentifierList(ref SyntaxTokenEnumerator enumerator)
     IdentifierNode[] ParseIdentifierList(ref SyntaxTokenEnumerator enumerator)
     {
     {
-        using var buffer = new PooledList<IdentifierNode>(8);
+        using PooledList<IdentifierNode> buffer = new(8);
 
 
         while (true)
         while (true)
         {
         {
-            if (enumerator.Current.Type != SyntaxTokenType.Identifier) break;
-            var identifier = new IdentifierNode(enumerator.Current.Text, enumerator.Current.Position);
+            if (enumerator.Current.Type != SyntaxTokenType.Identifier)
+            {
+                break;
+            }
+
+            IdentifierNode identifier = new(enumerator.Current.Text, enumerator.Current.Position);
             buffer.Add(identifier);
             buffer.Add(identifier);
 
 
             MoveNextWithValidation(ref enumerator);
             MoveNextWithValidation(ref enumerator);
             enumerator.SkipEoL();
             enumerator.SkipEoL();
 
 
-            if (enumerator.Current.Type != SyntaxTokenType.Comma) break;
+            if (enumerator.Current.Type != SyntaxTokenType.Comma)
+            {
+                break;
+            }
 
 
             MoveNextWithValidation(ref enumerator);
             MoveNextWithValidation(ref enumerator);
             enumerator.SkipEoL();
             enumerator.SkipEoL();
@@ -959,13 +990,20 @@ public ref struct Parser
 
 
     StatementNode[] ParseStatementList(ref SyntaxTokenEnumerator enumerator, SyntaxTokenType endTokenType, out SyntaxToken endToken)
     StatementNode[] ParseStatementList(ref SyntaxTokenEnumerator enumerator, SyntaxTokenType endTokenType, out SyntaxToken endToken)
     {
     {
-        using var statements = new PooledList<StatementNode>(64);
+        using PooledList<StatementNode> statements = new(64);
 
 
         // parse statements
         // parse statements
         while (enumerator.MoveNext())
         while (enumerator.MoveNext())
         {
         {
-            if (enumerator.Current.Type == endTokenType) break;
-            if (enumerator.Current.Type is SyntaxTokenType.EndOfLine or SyntaxTokenType.SemiColon) continue;
+            if (enumerator.Current.Type == endTokenType)
+            {
+                break;
+            }
+
+            if (enumerator.Current.Type is SyntaxTokenType.EndOfLine or SyntaxTokenType.SemiColon)
+            {
+                continue;
+            }
 
 
             var node = ParseStatement(ref enumerator);
             var node = ParseStatement(ref enumerator);
             statements.Add(node);
             statements.Add(node);
@@ -995,7 +1033,10 @@ public ref struct Parser
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     void MoveNextWithValidation(ref SyntaxTokenEnumerator enumerator)
     void MoveNextWithValidation(ref SyntaxTokenEnumerator enumerator)
     {
     {
-        if (!enumerator.MoveNext()) LuaParseException.SyntaxError(ChunkName, enumerator.Current.Position, enumerator.Current);
+        if (!enumerator.MoveNext())
+        {
+            LuaParseException.SyntaxError(ChunkName, enumerator.Current.Position, enumerator.Current);
+        }
     }
     }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -1010,7 +1051,7 @@ public ref struct Parser
             SyntaxTokenType.Exponentiation => OperatorPrecedence.Exponentiation,
             SyntaxTokenType.Exponentiation => OperatorPrecedence.Exponentiation,
             SyntaxTokenType.And => OperatorPrecedence.And,
             SyntaxTokenType.And => OperatorPrecedence.And,
             SyntaxTokenType.Or => OperatorPrecedence.Or,
             SyntaxTokenType.Or => OperatorPrecedence.Or,
-            _ => OperatorPrecedence.NonOperator,
+            _ => OperatorPrecedence.NonOperator
         };
         };
     }
     }
 
 

+ 251 - 65
src/Lua/CodeAnalysis/Syntax/SyntaxToken.cs

@@ -4,68 +4,250 @@ namespace Lua.CodeAnalysis.Syntax;
 
 
 public readonly struct SyntaxToken(SyntaxTokenType type, ReadOnlyMemory<char> text, SourcePosition position) : IEquatable<SyntaxToken>
 public readonly struct SyntaxToken(SyntaxTokenType type, ReadOnlyMemory<char> text, SourcePosition position) : IEquatable<SyntaxToken>
 {
 {
-    public static SyntaxToken EndOfLine(SourcePosition position) => new(SyntaxTokenType.EndOfLine, Keywords.LF.AsMemory(), position);
-
-    public static SyntaxToken LParen(SourcePosition position) => new(SyntaxTokenType.LParen, Keywords.LParen.AsMemory(), position);
-    public static SyntaxToken RParen(SourcePosition position) => new(SyntaxTokenType.RParen, Keywords.RParen.AsMemory(), position);
-    public static SyntaxToken LCurly(SourcePosition position) => new(SyntaxTokenType.LCurly, Keywords.LCurly.AsMemory(), position);
-    public static SyntaxToken RCurly(SourcePosition position) => new(SyntaxTokenType.RCurly, Keywords.RCurly.AsMemory(), position);
-    public static SyntaxToken LSquare(SourcePosition position) => new(SyntaxTokenType.LSquare, Keywords.LSquare.AsMemory(), position);
-    public static SyntaxToken RSquare(SourcePosition position) => new(SyntaxTokenType.RSquare, Keywords.RSquare.AsMemory(), position);
-
-    public static SyntaxToken Nil(SourcePosition position) => new(SyntaxTokenType.Nil, Keywords.Nil.AsMemory(), position);
-    public static SyntaxToken True(SourcePosition position) => new(SyntaxTokenType.True, Keywords.True.AsMemory(), position);
-    public static SyntaxToken False(SourcePosition position) => new(SyntaxTokenType.False, Keywords.False.AsMemory(), position);
-
-    public static SyntaxToken Addition(SourcePosition position) => new(SyntaxTokenType.Addition, Keywords.Addition.AsMemory(), position);
-    public static SyntaxToken Subtraction(SourcePosition position) => new(SyntaxTokenType.Subtraction, Keywords.Subtraction.AsMemory(), position);
-    public static SyntaxToken Multiplication(SourcePosition position) => new(SyntaxTokenType.Multiplication, Keywords.Multiplication.AsMemory(), position);
-    public static SyntaxToken Division(SourcePosition position) => new(SyntaxTokenType.Division, Keywords.Division.AsMemory(), position);
-    public static SyntaxToken Modulo(SourcePosition position) => new(SyntaxTokenType.Modulo, Keywords.Modulo.AsMemory(), position);
-    public static SyntaxToken Exponentiation(SourcePosition position) => new(SyntaxTokenType.Exponentiation, Keywords.Exponentiation.AsMemory(), position);
-
-    public static SyntaxToken Equality(SourcePosition position) => new(SyntaxTokenType.Equality, Keywords.Equality.AsMemory(), position);
-    public static SyntaxToken Inequality(SourcePosition position) => new(SyntaxTokenType.Inequality, Keywords.Inequality.AsMemory(), position);
-    public static SyntaxToken GreaterThan(SourcePosition position) => new(SyntaxTokenType.GreaterThan, Keywords.GreaterThan.AsMemory(), position);
-    public static SyntaxToken GreaterThanOrEqual(SourcePosition position) => new(SyntaxTokenType.GreaterThanOrEqual, Keywords.GreaterThanOrEqual.AsMemory(), position);
-    public static SyntaxToken LessThan(SourcePosition position) => new(SyntaxTokenType.LessThan, Keywords.LessThan.AsMemory(), position);
-    public static SyntaxToken LessThanOrEqual(SourcePosition position) => new(SyntaxTokenType.LessThanOrEqual, Keywords.LessThanOrEqual.AsMemory(), position);
-
-    public static SyntaxToken Length(SourcePosition position) => new(SyntaxTokenType.Length, Keywords.Length.AsMemory(), position);
-    public static SyntaxToken Concat(SourcePosition position) => new(SyntaxTokenType.Concat, Keywords.Concat.AsMemory(), position);
-    public static SyntaxToken VarArg(SourcePosition position) => new(SyntaxTokenType.VarArg, "...".AsMemory(), position);
-
-    public static SyntaxToken Assignment(SourcePosition position) => new(SyntaxTokenType.Assignment, Keywords.Assignment.AsMemory(), position);
-
-    public static SyntaxToken And(SourcePosition position) => new(SyntaxTokenType.And, Keywords.And.AsMemory(), position);
-    public static SyntaxToken Or(SourcePosition position) => new(SyntaxTokenType.Or, Keywords.Or.AsMemory(), position);
-    public static SyntaxToken Not(SourcePosition position) => new(SyntaxTokenType.Not, Keywords.Not.AsMemory(), position);
-
-    public static SyntaxToken End(SourcePosition position) => new(SyntaxTokenType.End, Keywords.End.AsMemory(), position);
-    public static SyntaxToken Then(SourcePosition position) => new(SyntaxTokenType.Then, Keywords.Then.AsMemory(), position);
-
-    public static SyntaxToken If(SourcePosition position) => new(SyntaxTokenType.If, Keywords.If.AsMemory(), position);
-    public static SyntaxToken ElseIf(SourcePosition position) => new(SyntaxTokenType.ElseIf, Keywords.ElseIf.AsMemory(), position);
-    public static SyntaxToken Else(SourcePosition position) => new(SyntaxTokenType.Else, Keywords.Else.AsMemory(), position);
-
-    public static SyntaxToken Local(SourcePosition position) => new(SyntaxTokenType.Local, Keywords.Local.AsMemory(), position);
-
-    public static SyntaxToken Return(SourcePosition position) => new(SyntaxTokenType.Return, Keywords.Return.AsMemory(), position);
-    public static SyntaxToken Goto(SourcePosition position) => new(SyntaxTokenType.Goto, Keywords.Goto.AsMemory(), position);
-
-    public static SyntaxToken Comma(SourcePosition position) => new(SyntaxTokenType.Comma, ",".AsMemory(), position);
-    public static SyntaxToken Dot(SourcePosition position) => new(SyntaxTokenType.Dot, ".".AsMemory(), position);
-    public static SyntaxToken SemiColon(SourcePosition position) => new(SyntaxTokenType.SemiColon, ";".AsMemory(), position);
-    public static SyntaxToken Colon(SourcePosition position) => new(SyntaxTokenType.Colon, ":".AsMemory(), position);
-
-    public static SyntaxToken Do(SourcePosition position) => new(SyntaxTokenType.Do, Keywords.Do.AsMemory(), position);
-    public static SyntaxToken While(SourcePosition position) => new(SyntaxTokenType.While, Keywords.While.AsMemory(), position);
-    public static SyntaxToken Repeat(SourcePosition position) => new(SyntaxTokenType.Repeat, Keywords.Repeat.AsMemory(), position);
-    public static SyntaxToken Until(SourcePosition position) => new(SyntaxTokenType.Until, Keywords.Until.AsMemory(), position);
-    public static SyntaxToken Break(SourcePosition position) => new(SyntaxTokenType.Break, Keywords.Break.AsMemory(), position);
-    public static SyntaxToken Function(SourcePosition position) => new(SyntaxTokenType.Function, Keywords.Function.AsMemory(), position);
-    public static SyntaxToken For(SourcePosition position) => new(SyntaxTokenType.For, Keywords.For.AsMemory(), position);
-    public static SyntaxToken In(SourcePosition position) => new(SyntaxTokenType.In, Keywords.In.AsMemory(), position);
+    public static SyntaxToken EndOfLine(SourcePosition position)
+    {
+        return new(SyntaxTokenType.EndOfLine, Keywords.LF.AsMemory(), position);
+    }
+
+    public static SyntaxToken LParen(SourcePosition position)
+    {
+        return new(SyntaxTokenType.LParen, Keywords.LParen.AsMemory(), position);
+    }
+
+    public static SyntaxToken RParen(SourcePosition position)
+    {
+        return new(SyntaxTokenType.RParen, Keywords.RParen.AsMemory(), position);
+    }
+
+    public static SyntaxToken LCurly(SourcePosition position)
+    {
+        return new(SyntaxTokenType.LCurly, Keywords.LCurly.AsMemory(), position);
+    }
+
+    public static SyntaxToken RCurly(SourcePosition position)
+    {
+        return new(SyntaxTokenType.RCurly, Keywords.RCurly.AsMemory(), position);
+    }
+
+    public static SyntaxToken LSquare(SourcePosition position)
+    {
+        return new(SyntaxTokenType.LSquare, Keywords.LSquare.AsMemory(), position);
+    }
+
+    public static SyntaxToken RSquare(SourcePosition position)
+    {
+        return new(SyntaxTokenType.RSquare, Keywords.RSquare.AsMemory(), position);
+    }
+
+    public static SyntaxToken Nil(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Nil, Keywords.Nil.AsMemory(), position);
+    }
+
+    public static SyntaxToken True(SourcePosition position)
+    {
+        return new(SyntaxTokenType.True, Keywords.True.AsMemory(), position);
+    }
+
+    public static SyntaxToken False(SourcePosition position)
+    {
+        return new(SyntaxTokenType.False, Keywords.False.AsMemory(), position);
+    }
+
+    public static SyntaxToken Addition(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Addition, Keywords.Addition.AsMemory(), position);
+    }
+
+    public static SyntaxToken Subtraction(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Subtraction, Keywords.Subtraction.AsMemory(), position);
+    }
+
+    public static SyntaxToken Multiplication(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Multiplication, Keywords.Multiplication.AsMemory(), position);
+    }
+
+    public static SyntaxToken Division(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Division, Keywords.Division.AsMemory(), position);
+    }
+
+    public static SyntaxToken Modulo(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Modulo, Keywords.Modulo.AsMemory(), position);
+    }
+
+    public static SyntaxToken Exponentiation(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Exponentiation, Keywords.Exponentiation.AsMemory(), position);
+    }
+
+    public static SyntaxToken Equality(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Equality, Keywords.Equality.AsMemory(), position);
+    }
+
+    public static SyntaxToken Inequality(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Inequality, Keywords.Inequality.AsMemory(), position);
+    }
+
+    public static SyntaxToken GreaterThan(SourcePosition position)
+    {
+        return new(SyntaxTokenType.GreaterThan, Keywords.GreaterThan.AsMemory(), position);
+    }
+
+    public static SyntaxToken GreaterThanOrEqual(SourcePosition position)
+    {
+        return new(SyntaxTokenType.GreaterThanOrEqual, Keywords.GreaterThanOrEqual.AsMemory(), position);
+    }
+
+    public static SyntaxToken LessThan(SourcePosition position)
+    {
+        return new(SyntaxTokenType.LessThan, Keywords.LessThan.AsMemory(), position);
+    }
+
+    public static SyntaxToken LessThanOrEqual(SourcePosition position)
+    {
+        return new(SyntaxTokenType.LessThanOrEqual, Keywords.LessThanOrEqual.AsMemory(), position);
+    }
+
+    public static SyntaxToken Length(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Length, Keywords.Length.AsMemory(), position);
+    }
+
+    public static SyntaxToken Concat(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Concat, Keywords.Concat.AsMemory(), position);
+    }
+
+    public static SyntaxToken VarArg(SourcePosition position)
+    {
+        return new(SyntaxTokenType.VarArg, "...".AsMemory(), position);
+    }
+
+    public static SyntaxToken Assignment(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Assignment, Keywords.Assignment.AsMemory(), position);
+    }
+
+    public static SyntaxToken And(SourcePosition position)
+    {
+        return new(SyntaxTokenType.And, Keywords.And.AsMemory(), position);
+    }
+
+    public static SyntaxToken Or(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Or, Keywords.Or.AsMemory(), position);
+    }
+
+    public static SyntaxToken Not(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Not, Keywords.Not.AsMemory(), position);
+    }
+
+    public static SyntaxToken End(SourcePosition position)
+    {
+        return new(SyntaxTokenType.End, Keywords.End.AsMemory(), position);
+    }
+
+    public static SyntaxToken Then(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Then, Keywords.Then.AsMemory(), position);
+    }
+
+    public static SyntaxToken If(SourcePosition position)
+    {
+        return new(SyntaxTokenType.If, Keywords.If.AsMemory(), position);
+    }
+
+    public static SyntaxToken ElseIf(SourcePosition position)
+    {
+        return new(SyntaxTokenType.ElseIf, Keywords.ElseIf.AsMemory(), position);
+    }
+
+    public static SyntaxToken Else(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Else, Keywords.Else.AsMemory(), position);
+    }
+
+    public static SyntaxToken Local(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Local, Keywords.Local.AsMemory(), position);
+    }
+
+    public static SyntaxToken Return(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Return, Keywords.Return.AsMemory(), position);
+    }
+
+    public static SyntaxToken Goto(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Goto, Keywords.Goto.AsMemory(), position);
+    }
+
+    public static SyntaxToken Comma(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Comma, ",".AsMemory(), position);
+    }
+
+    public static SyntaxToken Dot(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Dot, ".".AsMemory(), position);
+    }
+
+    public static SyntaxToken SemiColon(SourcePosition position)
+    {
+        return new(SyntaxTokenType.SemiColon, ";".AsMemory(), position);
+    }
+
+    public static SyntaxToken Colon(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Colon, ":".AsMemory(), position);
+    }
+
+    public static SyntaxToken Do(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Do, Keywords.Do.AsMemory(), position);
+    }
+
+    public static SyntaxToken While(SourcePosition position)
+    {
+        return new(SyntaxTokenType.While, Keywords.While.AsMemory(), position);
+    }
+
+    public static SyntaxToken Repeat(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Repeat, Keywords.Repeat.AsMemory(), position);
+    }
+
+    public static SyntaxToken Until(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Until, Keywords.Until.AsMemory(), position);
+    }
+
+    public static SyntaxToken Break(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Break, Keywords.Break.AsMemory(), position);
+    }
+
+    public static SyntaxToken Function(SourcePosition position)
+    {
+        return new(SyntaxTokenType.Function, Keywords.Function.AsMemory(), position);
+    }
+
+    public static SyntaxToken For(SourcePosition position)
+    {
+        return new(SyntaxTokenType.For, Keywords.For.AsMemory(), position);
+    }
+
+    public static SyntaxToken In(SourcePosition position)
+    {
+        return new(SyntaxTokenType.In, Keywords.In.AsMemory(), position);
+    }
 
 
     public SyntaxTokenType Type { get; } = type;
     public SyntaxTokenType Type { get; } = type;
     public ReadOnlyMemory<char> Text { get; } = text;
     public ReadOnlyMemory<char> Text { get; } = text;
@@ -165,7 +347,7 @@ public readonly struct SyntaxToken(SyntaxTokenType type, ReadOnlyMemory<char> te
             SyntaxTokenType.Return => Keywords.Return,
             SyntaxTokenType.Return => Keywords.Return,
             SyntaxTokenType.Until => Keywords.Until,
             SyntaxTokenType.Until => Keywords.Until,
             SyntaxTokenType.While => Keywords.While,
             SyntaxTokenType.While => Keywords.While,
-            _ => "",
+            _ => ""
         };
         };
     }
     }
 
 
@@ -178,7 +360,11 @@ public readonly struct SyntaxToken(SyntaxTokenType type, ReadOnlyMemory<char> te
 
 
     public override bool Equals(object? obj)
     public override bool Equals(object? obj)
     {
     {
-        if (obj is SyntaxToken token) return Equals(token);
+        if (obj is SyntaxToken token)
+        {
+            return Equals(token);
+        }
+
         return false;
         return false;
     }
     }
 
 
@@ -369,5 +555,5 @@ public enum SyntaxTokenType
     Repeat, // repeat
     Repeat, // repeat
     Return, // return
     Return, // return
     Until, // until
     Until, // until
-    While, // while
+    While // while
 }
 }

+ 47 - 8
src/Lua/CodeAnalysis/Syntax/SyntaxTokenEnumerator.cs

@@ -8,14 +8,38 @@ public ref struct SyntaxTokenEnumerator(ReadOnlySpan<SyntaxToken> source)
     SyntaxToken current;
     SyntaxToken current;
     int offset;
     int offset;
 
 
-    public SyntaxToken Current => current;
-    public int Position => offset;
-    public bool IsCompleted => source.Length == offset;
+    public SyntaxToken Current
+    {
+        get
+        {
+            return current;
+        }
+    }
+
+    public int Position
+    {
+        get
+        {
+            return offset;
+        }
+    }
+
+    public bool IsCompleted
+    {
+        get
+        {
+            return source.Length == offset;
+        }
+    }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public bool MoveNext()
     public bool MoveNext()
     {
     {
-        if (IsCompleted) return false;
+        if (IsCompleted)
+        {
+            return false;
+        }
+
         current = source[offset];
         current = source[offset];
         offset++;
         offset++;
         return true;
         return true;
@@ -24,7 +48,11 @@ public ref struct SyntaxTokenEnumerator(ReadOnlySpan<SyntaxToken> source)
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public bool MovePrevious()
     public bool MovePrevious()
     {
     {
-        if (offset == 0) return false;
+        if (offset == 0)
+        {
+            return false;
+        }
+
         offset--;
         offset--;
         current = source[offset - 1];
         current = source[offset - 1];
         return true;
         return true;
@@ -35,8 +63,15 @@ public ref struct SyntaxTokenEnumerator(ReadOnlySpan<SyntaxToken> source)
     {
     {
         while (true)
         while (true)
         {
         {
-            if (current.Type != SyntaxTokenType.EndOfLine) return;
-            if (!MoveNext()) return;
+            if (current.Type != SyntaxTokenType.EndOfLine)
+            {
+                return;
+            }
+
+            if (!MoveNext())
+            {
+                return;
+            }
         }
         }
     }
     }
 
 
@@ -51,7 +86,11 @@ public ref struct SyntaxTokenEnumerator(ReadOnlySpan<SyntaxToken> source)
         while (i < source.Length)
         while (i < source.Length)
         {
         {
             var c = source[i];
             var c = source[i];
-            if (source[i].Type is not SyntaxTokenType.EndOfLine) return c;
+            if (source[i].Type is not SyntaxTokenType.EndOfLine)
+            {
+                return c;
+            }
+
             i++;
             i++;
         }
         }
 
 

+ 36 - 12
src/Lua/Exceptions.cs

@@ -49,10 +49,15 @@ public class LuaCompileException(string chunkName, SourcePosition position, int
 {
 {
     public string ChunkName { get; } = chunkName;
     public string ChunkName { get; } = chunkName;
     public int OffSet { get; } = offset;
     public int OffSet { get; } = offset;
+
     public SourcePosition Position => position;
     public SourcePosition Position => position;
+
     public string MainMessage => message;
     public string MainMessage => message;
+
     public string? NearToken => nearToken;
     public string? NearToken => nearToken;
+
     public string MessageWithNearToken => base.Message;
     public string MessageWithNearToken => base.Message;
+
     public override string Message => $"{ChunkName}:{Position.Line}: {base.Message}";
     public override string Message => $"{ChunkName}:{Position.Line}: {base.Message}";
 
 
     static string GetMessageWithNearToken(string message, string? nearToken)
     static string GetMessageWithNearToken(string message, string? nearToken)
@@ -68,7 +73,7 @@ public class LuaCompileException(string chunkName, SourcePosition position, int
 
 
 public class LuaUnDumpException(string message) : Exception(message);
 public class LuaUnDumpException(string message) : Exception(message);
 
 
-internal class LuaStackOverflowException() : Exception("stack overflow")
+class LuaStackOverflowException() : Exception("stack overflow")
 {
 {
     public override string ToString()
     public override string ToString()
     {
     {
@@ -76,7 +81,7 @@ internal class LuaStackOverflowException() : Exception("stack overflow")
     }
     }
 }
 }
 
 
-internal interface ILuaTracebackBuildable
+interface ILuaTracebackBuildable
 {
 {
     Traceback? BuildOrGet();
     Traceback? BuildOrGet();
 }
 }
@@ -153,8 +158,8 @@ public class LuaRuntimeException : Exception, ILuaTracebackBuildable
         var luaValueA = regA < 255 ? thread.Stack[caller.Base + regA] : ((LuaClosure)caller.Function).Proto.Constants[regA - 256];
         var luaValueA = regA < 255 ? thread.Stack[caller.Base + regA] : ((LuaClosure)caller.Function).Proto.Constants[regA - 256];
         var luaValueB = regB < 255 ? thread.Stack[caller.Base + regB] : ((LuaClosure)caller.Function).Proto.Constants[regB - 256];
         var luaValueB = regB < 255 ? thread.Stack[caller.Base + regB] : ((LuaClosure)caller.Function).Proto.Constants[regB - 256];
         var function = caller.Function;
         var function = caller.Function;
-        var tA = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, regA, out string? nameA);
-        var tB = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, regB, out string? nameB);
+        var tA = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, regA, out var nameA);
+        var tB = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, regB, out var nameB);
 
 
         using var builder = new PooledList<char>(64);
         using var builder = new PooledList<char>(64);
         builder.Clear();
         builder.Clear();
@@ -184,7 +189,7 @@ public class LuaRuntimeException : Exception, ILuaTracebackBuildable
         var caller = thread.GetCurrentFrame();
         var caller = thread.GetCurrentFrame();
         var luaValue = reg < 255 ? thread.Stack[caller.Base + reg] : ((LuaClosure)caller.Function).Proto.Constants[reg - 256];
         var luaValue = reg < 255 ? thread.Stack[caller.Base + reg] : ((LuaClosure)caller.Function).Proto.Constants[reg - 256];
         var function = caller.Function;
         var function = caller.Function;
-        var t = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, reg, out string? name);
+        var t = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, reg, out var name);
 
 
         using var builder = new PooledList<char>(64);
         using var builder = new PooledList<char>(64);
         builder.Clear();
         builder.Clear();
@@ -320,12 +325,20 @@ public class LuaRuntimeException : Exception, ILuaTracebackBuildable
     [MethodImpl(MethodImplOptions.NoInlining)]
     [MethodImpl(MethodImplOptions.NoInlining)]
     Traceback? ILuaTracebackBuildable.BuildOrGet()
     Traceback? ILuaTracebackBuildable.BuildOrGet()
     {
     {
-        if (luaTraceback != null) return luaTraceback;
+        if (luaTraceback != null)
+        {
+            return luaTraceback;
+        }
+
         if (Thread != null)
         if (Thread != null)
         {
         {
             var callStack = Thread.ExceptionTrace.AsSpan();
             var callStack = Thread.ExceptionTrace.AsSpan();
-            if (callStack.IsEmpty) return null;
-            luaTraceback = new Traceback(Thread.State, callStack);
+            if (callStack.IsEmpty)
+            {
+                return null;
+            }
+
+            luaTraceback = new(Thread.State, callStack);
             Thread.ExceptionTrace.Clear();
             Thread.ExceptionTrace.Clear();
             Thread = null;
             Thread = null;
         }
         }
@@ -398,7 +411,11 @@ public class LuaRuntimeException : Exception, ILuaTracebackBuildable
     {
     {
         get
         get
         {
         {
-            if (InnerException != null) return InnerException.Message;
+            if (InnerException != null)
+            {
+                return InnerException.Message;
+            }
+
             if (LuaTraceback == null)
             if (LuaTraceback == null)
             {
             {
                 return ErrorObject.ToString();
                 return ErrorObject.ToString();
@@ -468,13 +485,20 @@ public sealed class LuaCanceledException : OperationCanceledException, ILuaTrace
     [MethodImpl(MethodImplOptions.NoInlining)]
     [MethodImpl(MethodImplOptions.NoInlining)]
     Traceback? ILuaTracebackBuildable.BuildOrGet()
     Traceback? ILuaTracebackBuildable.BuildOrGet()
     {
     {
-        if (luaTraceback != null) return luaTraceback;
+        if (luaTraceback != null)
+        {
+            return luaTraceback;
+        }
 
 
         if (Thread != null)
         if (Thread != null)
         {
         {
             var callStack = Thread.ExceptionTrace.AsSpan();
             var callStack = Thread.ExceptionTrace.AsSpan();
-            if (callStack.IsEmpty) return null;
-            luaTraceback = new Traceback(Thread.State, callStack);
+            if (callStack.IsEmpty)
+            {
+                return null;
+            }
+
+            luaTraceback = new(Thread.State, callStack);
             Thread.ExceptionTrace.Clear();
             Thread.ExceptionTrace.Clear();
             Thread = null!;
             Thread = null!;
         }
         }

+ 8 - 5
src/Lua/IO/BufferedOutputStream.cs

@@ -10,18 +10,21 @@ public class BufferedOutputStream(Action<ReadOnlyMemory<char>> onFlush) : ILuaSt
     }
     }
 
 
     public bool IsOpen { get; set; } = true;
     public bool IsOpen { get; set; } = true;
-    public LuaFileOpenMode Mode  => LuaFileOpenMode.Write;
 
 
-    private FastListCore<char> buffer;
+    public LuaFileOpenMode Mode => LuaFileOpenMode.Write;
+
+    FastListCore<char> buffer;
+
     public ValueTask WriteAsync(ReadOnlyMemory<char> text, CancellationToken cancellationToken = default)
     public ValueTask WriteAsync(ReadOnlyMemory<char> text, CancellationToken cancellationToken = default)
     {
     {
         foreach (var c in text.Span)
         foreach (var c in text.Span)
         {
         {
-            buffer .Add(c);
+            buffer.Add(c);
         }
         }
+
         return default;
         return default;
     }
     }
-        
+
     public ValueTask FlushAsync(CancellationToken cancellationToken = default)
     public ValueTask FlushAsync(CancellationToken cancellationToken = default)
     {
     {
         if (buffer.Length > 0)
         if (buffer.Length > 0)
@@ -29,7 +32,7 @@ public class BufferedOutputStream(Action<ReadOnlyMemory<char>> onFlush) : ILuaSt
             onFlush(buffer.AsArray().AsMemory(0, buffer.Length));
             onFlush(buffer.AsArray().AsMemory(0, buffer.Length));
             buffer.Clear();
             buffer.Clear();
         }
         }
+
         return default;
         return default;
     }
     }
-        
 }
 }

+ 11 - 5
src/Lua/IO/CompositeLoaderFileSystem.cs

@@ -17,13 +17,13 @@ public class CompositeLoaderFileSystem(ILuaFileLoader[] loaders, ILuaFileSystem?
         return new(loaders);
         return new(loaders);
     }
     }
 
 
-    private (int index, string path)? cached;
+    (int index, string path)? cached;
 
 
     public bool IsReadable(string path)
     public bool IsReadable(string path)
     {
     {
-        for (int index = 0; index < loaders.Length; index++)
+        for (var index = 0; index < loaders.Length; index++)
         {
         {
-            ILuaFileLoader? loader = loaders[index];
+            var loader = loaders[index];
             if (loader.Exists(path))
             if (loader.Exists(path))
             {
             {
                 cached = (index, path);
                 cached = (index, path);
@@ -50,8 +50,11 @@ public class CompositeLoaderFileSystem(ILuaFileLoader[] loaders, ILuaFileSystem?
                 if (cachedValue.index < loaders.Length)
                 if (cachedValue.index < loaders.Length)
                 {
                 {
                     if (mode.CanWrite())
                     if (mode.CanWrite())
+                    {
                         throw new NotSupportedException("Cannot write to a file opened with a loader.");
                         throw new NotSupportedException("Cannot write to a file opened with a loader.");
-                    return (await loaders[cachedValue.index].LoadAsync(path, cancellationToken));
+                    }
+
+                    return await loaders[cachedValue.index].LoadAsync(path, cancellationToken);
                 }
                 }
             }
             }
         }
         }
@@ -62,8 +65,11 @@ public class CompositeLoaderFileSystem(ILuaFileLoader[] loaders, ILuaFileSystem?
                 if (loader.Exists(path))
                 if (loader.Exists(path))
                 {
                 {
                     if (mode.CanWrite())
                     if (mode.CanWrite())
+                    {
                         throw new NotSupportedException("Cannot write to a file opened with a loader.");
                         throw new NotSupportedException("Cannot write to a file opened with a loader.");
-                    return (await loader.LoadAsync(path, cancellationToken));
+                    }
+
+                    return await loader.LoadAsync(path, cancellationToken);
                 }
                 }
             }
             }
         }
         }

+ 12 - 11
src/Lua/IO/ConsoleStandardIO.cs

@@ -9,16 +9,16 @@ public sealed class ConsoleStandardIO : ILuaStandardIO
 {
 {
     ILuaStream? standardInput;
     ILuaStream? standardInput;
 
 
-    public ILuaStream Input => standardInput ??=
-        new StandardIOStream(ILuaStream.CreateFromStream(
-            ConsoleHelper.OpenStandardInput(),
-            LuaFileOpenMode.Read));
+    public ILuaStream Input =>
+        standardInput ??=
+            new StandardIOStream(ILuaStream.CreateFromStream(
+                ConsoleHelper.OpenStandardInput(),
+                LuaFileOpenMode.Read));
 
 
     ILuaStream? standardOutput;
     ILuaStream? standardOutput;
 
 
-    public ILuaStream Output
-
-        => standardOutput ??=
+    public ILuaStream Output =>
+        standardOutput ??=
             new StandardIOStream(ILuaStream.CreateFromStream(
             new StandardIOStream(ILuaStream.CreateFromStream(
                 ConsoleHelper.OpenStandardOutput(),
                 ConsoleHelper.OpenStandardOutput(),
                 LuaFileOpenMode.Write));
                 LuaFileOpenMode.Write));
@@ -26,8 +26,9 @@ public sealed class ConsoleStandardIO : ILuaStandardIO
 
 
     ILuaStream? standardError;
     ILuaStream? standardError;
 
 
-    public ILuaStream Error => standardError ??=
-        new StandardIOStream(ILuaStream.CreateFromStream(
-            ConsoleHelper.OpenStandardError(),
-            LuaFileOpenMode.Write));
+    public ILuaStream Error =>
+        standardError ??=
+            new StandardIOStream(ILuaStream.CreateFromStream(
+                ConsoleHelper.OpenStandardError(),
+                LuaFileOpenMode.Write));
 }
 }

+ 75 - 67
src/Lua/IO/FileSystem.cs

@@ -1,93 +1,101 @@
-namespace Lua.IO
+namespace Lua.IO;
+
+public sealed class FileSystem(string? baseDirectory = null) : ILuaFileSystem
 {
 {
-    public sealed class FileSystem(string? baseDirectory = null) : ILuaFileSystem
+    public string BaseDirectory => baseDirectory ?? Directory.GetCurrentDirectory();
+
+    public static (FileMode, FileAccess access) GetFileMode(LuaFileOpenMode luaFileOpenMode)
     {
     {
-        public string BaseDirectory => baseDirectory ?? Directory.GetCurrentDirectory();
+        return luaFileOpenMode switch
+        {
+            LuaFileOpenMode.Read => (FileMode.Open, FileAccess.Read),
+            LuaFileOpenMode.Write => (FileMode.Create, FileAccess.Write),
+            LuaFileOpenMode.Append => (FileMode.Append, FileAccess.Write),
+            LuaFileOpenMode.ReadUpdate => (FileMode.Open, FileAccess.ReadWrite),
+            LuaFileOpenMode.WriteUpdate => (FileMode.Truncate, FileAccess.ReadWrite),
+            LuaFileOpenMode.AppendUpdate => (FileMode.Append, FileAccess.ReadWrite),
+            _ => throw new ArgumentOutOfRangeException(nameof(luaFileOpenMode), luaFileOpenMode, null)
+        };
+    }
 
 
-        public static (FileMode, FileAccess access) GetFileMode(LuaFileOpenMode luaFileOpenMode)
+    public string GetFullPath(string path)
+    {
+        if (baseDirectory == null || Path.IsPathRooted(path))
         {
         {
-            return luaFileOpenMode switch
-            {
-                LuaFileOpenMode.Read => (FileMode.Open, FileAccess.Read),
-                LuaFileOpenMode.Write => (FileMode.Create, FileAccess.Write),
-                LuaFileOpenMode.Append => (FileMode.Append, FileAccess.Write),
-                LuaFileOpenMode.ReadUpdate => (FileMode.Open, FileAccess.ReadWrite),
-                LuaFileOpenMode.WriteUpdate => (FileMode.Truncate, FileAccess.ReadWrite),
-                LuaFileOpenMode.AppendUpdate => (FileMode.Append, FileAccess.ReadWrite),
-                _ => throw new ArgumentOutOfRangeException(nameof(luaFileOpenMode), luaFileOpenMode, null)
-            };
+            return path;
         }
         }
 
 
-        public string GetFullPath(string path)
-        {
-            if (baseDirectory == null || Path.IsPathRooted(path))
-            {
-                return path;
-            }
+        return Path.Combine(baseDirectory, path);
+    }
 
 
-            return Path.Combine(baseDirectory, path);
-        }
+    public bool IsReadable(string path)
+    {
+        return File.Exists(GetFullPath(path));
+    }
 
 
-        public bool IsReadable(string path)
+
+    public ValueTask<ILuaStream> Open(string path, LuaFileOpenMode openMode, CancellationToken cancellationToken)
+    {
+        var (mode, access) = GetFileMode(openMode);
+        Stream stream;
+        path = GetFullPath(path);
+        if (openMode == LuaFileOpenMode.AppendUpdate)
         {
         {
-            return File.Exists(GetFullPath(path));
+            stream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete);
+        }
+        else
+        {
+            stream = File.Open(path, mode, access, FileShare.ReadWrite | FileShare.Delete);
         }
         }
 
 
+        ILuaStream wrapper =
+            new LuaStream(openMode, stream);
 
 
-        public ValueTask<ILuaStream> Open(string path, LuaFileOpenMode openMode, CancellationToken cancellationToken)
+        if (openMode == LuaFileOpenMode.AppendUpdate)
         {
         {
-            var (mode, access) = GetFileMode(openMode);
-            Stream stream;
-            path = GetFullPath(path);
-            if (openMode == LuaFileOpenMode.AppendUpdate)
-            {
-                stream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete);
-            }
-            else
-            {
-                stream = File.Open(path, mode, access, FileShare.ReadWrite | FileShare.Delete);
-            }
-
-            ILuaStream wrapper =
-                new LuaStream(openMode, stream);
-
-            if (openMode == LuaFileOpenMode.AppendUpdate)
-            {
-                wrapper.Seek(SeekOrigin.End, 0);
-            }
-
-            return new(wrapper);
+            wrapper.Seek(SeekOrigin.End, 0);
         }
         }
 
 
-        public ValueTask Rename(string oldName, string newName, CancellationToken cancellationToken)
+        return new(wrapper);
+    }
+
+    public ValueTask Rename(string oldName, string newName, CancellationToken cancellationToken)
+    {
+        oldName = GetFullPath(oldName);
+        newName = GetFullPath(newName);
+        if (oldName == newName)
         {
         {
-            oldName = GetFullPath(oldName);
-            newName = GetFullPath(newName);
-            if (oldName == newName) return default;
-            if (File.Exists(newName)) File.Delete(newName);
-            File.Move(oldName, newName);
-            File.Delete(oldName);
             return default;
             return default;
         }
         }
 
 
-        public ValueTask Remove(string path, CancellationToken cancellationToken)
+        if (File.Exists(newName))
         {
         {
-            path = GetFullPath(path);
-            File.Delete(path);
-            return default;
+            File.Delete(newName);
         }
         }
 
 
-        static readonly string directorySeparator = Path.DirectorySeparatorChar.ToString();
-        public string DirectorySeparator => directorySeparator;
+        File.Move(oldName, newName);
+        File.Delete(oldName);
+        return default;
+    }
 
 
-        public string GetTempFileName()
-        {
-            return Path.GetTempFileName();
-        }
+    public ValueTask Remove(string path, CancellationToken cancellationToken)
+    {
+        path = GetFullPath(path);
+        File.Delete(path);
+        return default;
+    }
 
 
-        public ValueTask<ILuaStream> OpenTempFileStream(CancellationToken cancellationToken)
-        {
-            return new(new LuaStream(LuaFileOpenMode.WriteUpdate, File.Open(Path.GetTempFileName(), FileMode.Open, FileAccess.ReadWrite)));
-        }
+    static readonly string directorySeparator = Path.DirectorySeparatorChar.ToString();
+
+    public string DirectorySeparator => directorySeparator;
+
+    public string GetTempFileName()
+    {
+        return Path.GetTempFileName();
+    }
+
+    public ValueTask<ILuaStream> OpenTempFileStream(CancellationToken cancellationToken)
+    {
+        return new(new LuaStream(LuaFileOpenMode.WriteUpdate, File.Open(Path.GetTempFileName(), FileMode.Open, FileAccess.ReadWrite)));
     }
     }
 }
 }

+ 2 - 2
src/Lua/IO/ILuaFileLoader.cs

@@ -2,6 +2,6 @@
 
 
 public interface ILuaFileLoader
 public interface ILuaFileLoader
 {
 {
-    public bool Exists(string path);
-    public ValueTask<ILuaStream> LoadAsync(string path, CancellationToken cancellationToken = default);
+    bool Exists(string path);
+    ValueTask<ILuaStream> LoadAsync(string path, CancellationToken cancellationToken = default);
 }
 }

+ 9 - 7
src/Lua/IO/ILuaFileSystem.cs

@@ -2,11 +2,13 @@
 
 
 public interface ILuaFileSystem
 public interface ILuaFileSystem
 {
 {
-    public bool IsReadable(string path);
-    public ValueTask<ILuaStream> Open(string path, LuaFileOpenMode mode, CancellationToken cancellationToken);
-    public ValueTask Rename(string oldName, string newName, CancellationToken cancellationToken);
-    public ValueTask Remove(string path, CancellationToken cancellationToken);
-    public string DirectorySeparator => "/";
-    public string GetTempFileName();
-    public ValueTask<ILuaStream> OpenTempFileStream(CancellationToken cancellationToken);
+    bool IsReadable(string path);
+    ValueTask<ILuaStream> Open(string path, LuaFileOpenMode mode, CancellationToken cancellationToken);
+    ValueTask Rename(string oldName, string newName, CancellationToken cancellationToken);
+    ValueTask Remove(string path, CancellationToken cancellationToken);
+
+    string DirectorySeparator => "/";
+
+    string GetTempFileName();
+    ValueTask<ILuaStream> OpenTempFileStream(CancellationToken cancellationToken);
 }
 }

+ 67 - 65
src/Lua/IO/ILuaStream.cs

@@ -1,88 +1,90 @@
-namespace Lua.IO
+namespace Lua.IO;
+
+public interface ILuaStream : IDisposable
 {
 {
-    public interface ILuaStream : IDisposable
-    {
-        public bool IsOpen { get; }
-        public LuaFileOpenMode Mode { get; }
+    bool IsOpen { get; }
+    LuaFileOpenMode Mode { get; }
 
 
-        public ValueTask<string> ReadAllAsync(CancellationToken cancellationToken)
-        {
-            Mode.ThrowIfNotReadable();
+    ValueTask<string> ReadAllAsync(CancellationToken cancellationToken)
+    {
+        Mode.ThrowIfNotReadable();
 
 
-            // Default implementation using ReadStringAsync
-            throw new NotImplementedException($"ReadAllAsync must be implemented by {GetType().Name}");
-        }
+        // Default implementation using ReadStringAsync
+        throw new NotImplementedException($"ReadAllAsync must be implemented by {GetType().Name}");
+    }
 
 
-        public ValueTask<double?> ReadNumberAsync(CancellationToken cancellationToken)
-        {
-            Mode.ThrowIfNotReadable();
+    ValueTask<double?> ReadNumberAsync(CancellationToken cancellationToken)
+    {
+        Mode.ThrowIfNotReadable();
 
 
-            // Default implementation using ReadStringAsync
-            throw new NotImplementedException($"ReadNumberAsync must be implemented by {GetType().Name}");
-        }
+        // Default implementation using ReadStringAsync
+        throw new NotImplementedException($"ReadNumberAsync must be implemented by {GetType().Name}");
+    }
 
 
-        public ValueTask<string?> ReadLineAsync(bool keepEol, CancellationToken cancellationToken)
-        {
-            Mode.ThrowIfNotReadable();
+    ValueTask<string?> ReadLineAsync(bool keepEol, CancellationToken cancellationToken)
+    {
+        Mode.ThrowIfNotReadable();
 
 
 
 
-            // Default implementation using ReadStringAsync
-            throw new NotImplementedException($"ReadLineAsync must be implemented by {GetType().Name}");
-        }
+        // Default implementation using ReadStringAsync
+        throw new NotImplementedException($"ReadLineAsync must be implemented by {GetType().Name}");
+    }
 
 
-        public ValueTask<string?> ReadAsync(int count, CancellationToken cancellationToken)
-        {
-            Mode.ThrowIfNotReadable();
+    ValueTask<string?> ReadAsync(int count, CancellationToken cancellationToken)
+    {
+        Mode.ThrowIfNotReadable();
 
 
-            // Default implementation using ReadAllAsync
-            throw new NotImplementedException($"ReadStringAsync must be implemented by {GetType().Name}");
-        }
+        // Default implementation using ReadAllAsync
+        throw new NotImplementedException($"ReadStringAsync must be implemented by {GetType().Name}");
+    }
 
 
-        public ValueTask WriteAsync(ReadOnlyMemory<char> content, CancellationToken cancellationToken)
-        {
-            Mode.ThrowIfNotWritable();
+    ValueTask WriteAsync(ReadOnlyMemory<char> content, CancellationToken cancellationToken)
+    {
+        Mode.ThrowIfNotWritable();
 
 
-            throw new NotImplementedException($"WriteAsync must be implemented by {GetType().Name}");
-        }
+        throw new NotImplementedException($"WriteAsync must be implemented by {GetType().Name}");
+    }
 
 
-        public ValueTask WriteAsync(string content, CancellationToken cancellationToken) => WriteAsync(content.AsMemory(), cancellationToken);
+    ValueTask WriteAsync(string content, CancellationToken cancellationToken)
+    {
+        return WriteAsync(content.AsMemory(), cancellationToken);
+    }
 
 
-        public ValueTask FlushAsync(CancellationToken cancellationToken)
-        {
-            // Default implementation does nothing (no buffering)
-            return default;
-        }
+    ValueTask FlushAsync(CancellationToken cancellationToken)
+    {
+        // Default implementation does nothing (no buffering)
+        return default;
+    }
 
 
-        public void SetVBuf(LuaFileBufferingMode mode, int size)
-        {
-            // Default implementation does nothing (no configurable buffering)
-        }
+    void SetVBuf(LuaFileBufferingMode mode, int size)
+    {
+        // Default implementation does nothing (no configurable buffering)
+    }
 
 
-        public long Seek(SeekOrigin origin, long offset)
-        {
-            throw new NotSupportedException($"Seek is not supported by {GetType().Name}");
-        }
+    long Seek(SeekOrigin origin, long offset)
+    {
+        throw new NotSupportedException($"Seek is not supported by {GetType().Name}");
+    }
 
 
-        public static ILuaStream CreateFromStream(Stream stream, LuaFileOpenMode openMode)
-        {
-            return new LuaStream(openMode, stream);
-        }
+    static ILuaStream CreateFromStream(Stream stream, LuaFileOpenMode openMode)
+    {
+        return new LuaStream(openMode, stream);
+    }
 
 
-        public static ILuaStream CreateFromString(string content)
-        {
-            return new StringStream(content);
-        }
+    static ILuaStream CreateFromString(string content)
+    {
+        return new StringStream(content);
+    }
 
 
-        public static ILuaStream CreateFromMemory(ReadOnlyMemory<char> content)
-        {
-            return new CharMemoryStream(content);
-        }
+    static ILuaStream CreateFromMemory(ReadOnlyMemory<char> content)
+    {
+        return new CharMemoryStream(content);
+    }
 
 
 
 
-        public ValueTask CloseAsync(CancellationToken cancellationToken)
-        {
-            Dispose();
-            return default;
-        }
+    ValueTask CloseAsync(CancellationToken cancellationToken)
+    {
+        Dispose();
+        return default;
     }
     }
 }
 }

+ 1 - 1
src/Lua/IO/LuaFileBufferingMode.cs

@@ -15,5 +15,5 @@ public enum LuaFileBufferingMode
     /// <summary>
     /// <summary>
     /// No buffering. `no` in Lua
     /// No buffering. `no` in Lua
     /// </summary>
     /// </summary>
-    NoBuffering,
+    NoBuffering
 }
 }

+ 16 - 10
src/Lua/IO/LuaFileOpenMode.cs

@@ -30,21 +30,27 @@ public enum LuaFileOpenMode
     /// <summary>
     /// <summary>
     /// a+
     /// a+
     /// </summary>
     /// </summary>
-    AppendUpdate,
+    AppendUpdate
 }
 }
 
 
 public static class LuaFileOpenModeExtensions
 public static class LuaFileOpenModeExtensions
 {
 {
-    public static bool CanRead(this LuaFileOpenMode mode) => mode is LuaFileOpenMode.Read
-        or LuaFileOpenMode.ReadUpdate
-        or LuaFileOpenMode.WriteUpdate
-        or LuaFileOpenMode.AppendUpdate;
+    public static bool CanRead(this LuaFileOpenMode mode)
+    {
+        return mode is LuaFileOpenMode.Read
+            or LuaFileOpenMode.ReadUpdate
+            or LuaFileOpenMode.WriteUpdate
+            or LuaFileOpenMode.AppendUpdate;
+    }
 
 
-    public static bool CanWrite(this LuaFileOpenMode mode) => mode is LuaFileOpenMode.Write
-        or LuaFileOpenMode.ReadUpdate
-        or LuaFileOpenMode.WriteUpdate
-        or LuaFileOpenMode.Append
-        or LuaFileOpenMode.AppendUpdate;
+    public static bool CanWrite(this LuaFileOpenMode mode)
+    {
+        return mode is LuaFileOpenMode.Write
+            or LuaFileOpenMode.ReadUpdate
+            or LuaFileOpenMode.WriteUpdate
+            or LuaFileOpenMode.Append
+            or LuaFileOpenMode.AppendUpdate;
+    }
 
 
     public static LuaFileOpenMode ParseModeFromString(string mode)
     public static LuaFileOpenMode ParseModeFromString(string mode)
     {
     {

+ 14 - 7
src/Lua/IO/LuaStream.cs

@@ -3,7 +3,7 @@ using System.Text;
 
 
 namespace Lua.IO;
 namespace Lua.IO;
 
 
-internal sealed class LuaStream(LuaFileOpenMode mode, Stream innerStream) : ILuaStream
+sealed class LuaStream(LuaFileOpenMode mode, Stream innerStream) : ILuaStream
 {
 {
     Utf8Reader? reader;
     Utf8Reader? reader;
     ulong flushSize = ulong.MaxValue;
     ulong flushSize = ulong.MaxValue;
@@ -11,6 +11,7 @@ internal sealed class LuaStream(LuaFileOpenMode mode, Stream innerStream) : ILua
     bool disposed;
     bool disposed;
 
 
     public LuaFileOpenMode Mode => mode;
     public LuaFileOpenMode Mode => mode;
+
     public bool IsOpen => !disposed;
     public bool IsOpen => !disposed;
 
 
     public ValueTask<string?> ReadLineAsync(bool keepEol, CancellationToken cancellationToken)
     public ValueTask<string?> ReadLineAsync(bool keepEol, CancellationToken cancellationToken)
@@ -39,12 +40,14 @@ internal sealed class LuaStream(LuaFileOpenMode mode, Stream innerStream) : ILua
     {
     {
         mode.ThrowIfNotReadable();
         mode.ThrowIfNotReadable();
         reader ??= new();
         reader ??= new();
-        
+
         // Use the Utf8Reader's ReadNumber method which handles positioning correctly
         // Use the Utf8Reader's ReadNumber method which handles positioning correctly
         var numberStr = reader.ReadNumber(innerStream);
         var numberStr = reader.ReadNumber(innerStream);
         if (numberStr == null)
         if (numberStr == null)
+        {
             return new((double?)null);
             return new((double?)null);
-            
+        }
+
         // Parse using the shared utility
         // Parse using the shared utility
         var result = NumberReaderHelper.ParseNumber(numberStr.AsSpan());
         var result = NumberReaderHelper.ParseNumber(numberStr.AsSpan());
         return new(result);
         return new(result);
@@ -58,7 +61,7 @@ internal sealed class LuaStream(LuaFileOpenMode mode, Stream innerStream) : ILua
             innerStream.Seek(0, SeekOrigin.End);
             innerStream.Seek(0, SeekOrigin.End);
         }
         }
 
 
-        using var byteBuffer = new PooledArray<byte>(4096);
+        using PooledArray<byte> byteBuffer = new(4096);
         var encoder = Encoding.UTF8.GetEncoder();
         var encoder = Encoding.UTF8.GetEncoder();
         var totalBytes = encoder.GetByteCount(buffer.Span, true);
         var totalBytes = encoder.GetByteCount(buffer.Span, true);
         var remainingBytes = totalBytes;
         var remainingBytes = totalBytes;
@@ -101,7 +104,7 @@ internal sealed class LuaStream(LuaFileOpenMode mode, Stream innerStream) : ILua
         }
         }
     }
     }
 
 
-    public long Seek(SeekOrigin origin,long offset)
+    public long Seek(SeekOrigin origin, long offset)
     {
     {
         if (reader != null && origin == SeekOrigin.Current)
         if (reader != null && origin == SeekOrigin.Current)
         {
         {
@@ -114,9 +117,13 @@ internal sealed class LuaStream(LuaFileOpenMode mode, Stream innerStream) : ILua
 
 
     public void Dispose()
     public void Dispose()
     {
     {
-        if (disposed) return;
+        if (disposed)
+        {
+            return;
+        }
+
         disposed = true;
         disposed = true;
-        
+
         try
         try
         {
         {
             if (innerStream.CanWrite)
             if (innerStream.CanWrite)

+ 31 - 15
src/Lua/IO/MemoryStreams.cs

@@ -3,9 +3,10 @@ namespace Lua.IO;
 public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
 public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
 {
 {
     protected int Position;
     protected int Position;
-    private bool disposed;
+    bool disposed;
 
 
     public LuaFileOpenMode Mode => LuaFileOpenMode.Read;
     public LuaFileOpenMode Mode => LuaFileOpenMode.Read;
+
     public bool IsOpen => !disposed;
     public bool IsOpen => !disposed;
 
 
     public void Dispose()
     public void Dispose()
@@ -19,7 +20,9 @@ public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
 
 
         cancellationToken.ThrowIfCancellationRequested();
         cancellationToken.ThrowIfCancellationRequested();
         if (Position >= contents.Length)
         if (Position >= contents.Length)
+        {
             return new("");
             return new("");
+        }
 
 
         var remaining = contents[Position..];
         var remaining = contents[Position..];
         Position = contents.Length;
         Position = contents.Length;
@@ -32,7 +35,9 @@ public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
         cancellationToken.ThrowIfCancellationRequested();
         cancellationToken.ThrowIfCancellationRequested();
 
 
         if (Position >= contents.Length)
         if (Position >= contents.Length)
+        {
             return new((string?)null);
             return new((string?)null);
+        }
 
 
         var remainingSpan = contents[Position..].Span;
         var remainingSpan = contents[Position..].Span;
         var newlineIndex = remainingSpan.IndexOfAny('\r', '\n');
         var newlineIndex = remainingSpan.IndexOfAny('\r', '\n');
@@ -49,13 +54,13 @@ public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
             var lineSpan = remainingSpan[..newlineIndex];
             var lineSpan = remainingSpan[..newlineIndex];
             var nlChar = remainingSpan[newlineIndex];
             var nlChar = remainingSpan[newlineIndex];
             var endOfLineLength = 1;
             var endOfLineLength = 1;
-            
+
             // Check for CRLF
             // Check for CRLF
             if (nlChar == '\r' && newlineIndex + 1 < remainingSpan.Length && remainingSpan[newlineIndex + 1] == '\n')
             if (nlChar == '\r' && newlineIndex + 1 < remainingSpan.Length && remainingSpan[newlineIndex + 1] == '\n')
             {
             {
                 endOfLineLength = 2; // \r\n
                 endOfLineLength = 2; // \r\n
             }
             }
-            
+
             if (keepEol)
             if (keepEol)
             {
             {
                 // Include the newline character(s)
                 // Include the newline character(s)
@@ -66,7 +71,7 @@ public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
                 // Just the line content without newlines
                 // Just the line content without newlines
                 result = lineSpan.ToString();
                 result = lineSpan.ToString();
             }
             }
-            
+
             Position += newlineIndex + endOfLineLength;
             Position += newlineIndex + endOfLineLength;
         }
         }
 
 
@@ -79,7 +84,9 @@ public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
         cancellationToken.ThrowIfCancellationRequested();
         cancellationToken.ThrowIfCancellationRequested();
 
 
         if (Position >= contents.Length)
         if (Position >= contents.Length)
+        {
             return new((string?)null);
             return new((string?)null);
+        }
 
 
         var available = contents.Length - Position;
         var available = contents.Length - Position;
         var toRead = Math.Min(count, available);
         var toRead = Math.Min(count, available);
@@ -94,32 +101,34 @@ public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
     {
     {
         ThrowIfDisposed();
         ThrowIfDisposed();
         cancellationToken.ThrowIfCancellationRequested();
         cancellationToken.ThrowIfCancellationRequested();
-        
+
         if (Position >= contents.Length)
         if (Position >= contents.Length)
+        {
             return new((double?)null);
             return new((double?)null);
-        
+        }
+
         var remaining = contents[Position..].Span;
         var remaining = contents[Position..].Span;
         var startPos = Position;
         var startPos = Position;
-        
+
         // Use the shared utility to scan for a number
         // Use the shared utility to scan for a number
-        var numberLength = NumberReaderHelper.ScanNumberLength(remaining, skipWhitespace: true);
-        
+        var numberLength = NumberReaderHelper.ScanNumberLength(remaining, true);
+
         if (numberLength == 0)
         if (numberLength == 0)
         {
         {
             Position = contents.Length;
             Position = contents.Length;
             return new((double?)null);
             return new((double?)null);
         }
         }
-        
+
         // Find where the actual number starts (after whitespace)
         // Find where the actual number starts (after whitespace)
         var whitespaceLength = 0;
         var whitespaceLength = 0;
         while (whitespaceLength < remaining.Length && char.IsWhiteSpace(remaining[whitespaceLength]))
         while (whitespaceLength < remaining.Length && char.IsWhiteSpace(remaining[whitespaceLength]))
         {
         {
             whitespaceLength++;
             whitespaceLength++;
         }
         }
-        
+
         var numberSpan = remaining.Slice(whitespaceLength, numberLength);
         var numberSpan = remaining.Slice(whitespaceLength, numberLength);
         Position = startPos + whitespaceLength + numberLength;
         Position = startPos + whitespaceLength + numberLength;
-        
+
         // Parse using shared utility
         // Parse using shared utility
         var result = NumberReaderHelper.ParseNumber(numberSpan);
         var result = NumberReaderHelper.ParseNumber(numberSpan);
         return new(result);
         return new(result);
@@ -147,11 +156,11 @@ public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
         return default;
         return default;
     }
     }
 
 
-    public long Seek(SeekOrigin origin,long offset)
+    public long Seek(SeekOrigin origin, long offset)
     {
     {
         ThrowIfDisposed();
         ThrowIfDisposed();
 
 
-        long newPosition = origin switch
+        var newPosition = origin switch
         {
         {
             SeekOrigin.Begin => offset,
             SeekOrigin.Begin => offset,
             SeekOrigin.Current => Position + offset,
             SeekOrigin.Current => Position + offset,
@@ -160,7 +169,9 @@ public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
         };
         };
 
 
         if (newPosition < 0 || newPosition > contents.Length)
         if (newPosition < 0 || newPosition > contents.Length)
+        {
             throw new ArgumentOutOfRangeException(nameof(offset), "Seek position is out of range");
             throw new ArgumentOutOfRangeException(nameof(offset), "Seek position is out of range");
+        }
 
 
         Position = (int)newPosition;
         Position = (int)newPosition;
         return Position;
         return Position;
@@ -169,7 +180,9 @@ public class CharMemoryStream(ReadOnlyMemory<char> contents) : ILuaStream
     protected void ThrowIfDisposed()
     protected void ThrowIfDisposed()
     {
     {
         if (disposed)
         if (disposed)
+        {
             throw new ObjectDisposedException(nameof(StringStream));
             throw new ObjectDisposedException(nameof(StringStream));
+        }
     }
     }
 }
 }
 
 
@@ -180,7 +193,10 @@ public sealed class StringStream(string content) : CharMemoryStream(content.AsMe
         ThrowIfDisposed();
         ThrowIfDisposed();
         cancellationToken.ThrowIfCancellationRequested();
         cancellationToken.ThrowIfCancellationRequested();
         if (Position == 0)
         if (Position == 0)
-            return new((content));
+        {
+            return new(content);
+        }
+
         return base.ReadAllAsync(cancellationToken);
         return base.ReadAllAsync(cancellationToken);
     }
     }
 }
 }

+ 13 - 11
src/Lua/IO/NumberReaderHelper.cs

@@ -15,7 +15,7 @@ public static class NumberReaderHelper
     public static int ScanNumberLength(ReadOnlySpan<char> span, bool skipWhitespace = true)
     public static int ScanNumberLength(ReadOnlySpan<char> span, bool skipWhitespace = true)
     {
     {
         var position = 0;
         var position = 0;
-        
+
         // Skip leading whitespace
         // Skip leading whitespace
         if (skipWhitespace)
         if (skipWhitespace)
         {
         {
@@ -24,23 +24,25 @@ public static class NumberReaderHelper
                 position++;
                 position++;
             }
             }
         }
         }
-        
+
         if (position >= span.Length)
         if (position >= span.Length)
+        {
             return 0;
             return 0;
-        
+        }
+
         var numberStart = position;
         var numberStart = position;
         var hasStarted = false;
         var hasStarted = false;
         var isHex = false;
         var isHex = false;
         var hasDecimal = false;
         var hasDecimal = false;
         var lastWasE = false;
         var lastWasE = false;
-        
+
         // Check for sign
         // Check for sign
         if (position < span.Length && (span[position] == '+' || span[position] == '-'))
         if (position < span.Length && (span[position] == '+' || span[position] == '-'))
         {
         {
             position++;
             position++;
             hasStarted = true;
             hasStarted = true;
         }
         }
-        
+
         // Check for hex prefix right at the start (after optional sign)
         // Check for hex prefix right at the start (after optional sign)
         if (position < span.Length - 1 && span[position] == '0' && (span[position + 1] == 'x' || span[position + 1] == 'X'))
         if (position < span.Length - 1 && span[position] == '0' && (span[position + 1] == 'x' || span[position + 1] == 'X'))
         {
         {
@@ -48,14 +50,14 @@ public static class NumberReaderHelper
             position += 2; // Skip '0x' or '0X'
             position += 2; // Skip '0x' or '0X'
             hasStarted = true;
             hasStarted = true;
         }
         }
-        
+
         // Scan for valid number characters
         // Scan for valid number characters
         while (position < span.Length)
         while (position < span.Length)
         {
         {
             var c = span[position];
             var c = span[position];
-            
+
             // Hex prefix is handled above before the loop
             // Hex prefix is handled above before the loop
-            
+
             if (isHex)
             if (isHex)
             {
             {
                 // Hex digits
                 // Hex digits
@@ -121,11 +123,11 @@ public static class NumberReaderHelper
                 }
                 }
             }
             }
         }
         }
-        
+
         // Return the length of the number portion
         // Return the length of the number portion
         return position - numberStart;
         return position - numberStart;
     }
     }
-    
+
     public static bool TryParseToDouble(ReadOnlySpan<char> span, out double result)
     public static bool TryParseToDouble(ReadOnlySpan<char> span, out double result)
     {
     {
         span = span.Trim();
         span = span.Trim();
@@ -168,7 +170,7 @@ public static class NumberReaderHelper
             return double.TryParse(span, NumberStyles.Float, CultureInfo.InvariantCulture, out result);
             return double.TryParse(span, NumberStyles.Float, CultureInfo.InvariantCulture, out result);
         }
         }
     }
     }
-    
+
     /// <summary>
     /// <summary>
     /// Parses a number from a span and returns the result or null if parsing fails.
     /// Parses a number from a span and returns the result or null if parsing fails.
     /// </summary>
     /// </summary>

+ 53 - 37
src/Lua/IO/StandardIOStream.cs

@@ -1,51 +1,67 @@
-namespace Lua.IO
+namespace Lua.IO;
+
+/// <summary>
+/// Wrapper for standard IO streams that prevents closing
+/// </summary>
+sealed class StandardIOStream(ILuaStream innerStream) : ILuaStream
 {
 {
-    /// <summary>
-    /// Wrapper for standard IO streams that prevents closing
-    /// </summary>
-    internal sealed class StandardIOStream(ILuaStream innerStream) : ILuaStream
-    {
-        public LuaFileOpenMode Mode => innerStream.Mode;
-        public bool IsOpen => innerStream.IsOpen;
+    public LuaFileOpenMode Mode => innerStream.Mode;
+
+    public bool IsOpen => innerStream.IsOpen;
 
 
-        public ValueTask<string> ReadAllAsync(CancellationToken cancellationToken)
-            => innerStream.ReadAllAsync(cancellationToken);
+    public ValueTask<string> ReadAllAsync(CancellationToken cancellationToken)
+    {
+        return innerStream.ReadAllAsync(cancellationToken);
+    }
 
 
-        public ValueTask<string?> ReadLineAsync(bool keepEol, CancellationToken cancellationToken)
-            => innerStream.ReadLineAsync(keepEol, cancellationToken);
+    public ValueTask<string?> ReadLineAsync(bool keepEol, CancellationToken cancellationToken)
+    {
+        return innerStream.ReadLineAsync(keepEol, cancellationToken);
+    }
 
 
-        public ValueTask<string?> ReadAsync(int count, CancellationToken cancellationToken)
-            => innerStream.ReadAsync(count, cancellationToken);
+    public ValueTask<string?> ReadAsync(int count, CancellationToken cancellationToken)
+    {
+        return innerStream.ReadAsync(count, cancellationToken);
+    }
 
 
-        public ValueTask<double?> ReadNumberAsync(CancellationToken cancellationToken)
-            => innerStream.ReadNumberAsync(cancellationToken);
+    public ValueTask<double?> ReadNumberAsync(CancellationToken cancellationToken)
+    {
+        return innerStream.ReadNumberAsync(cancellationToken);
+    }
 
 
-        public ValueTask WriteAsync(ReadOnlyMemory<char> content, CancellationToken cancellationToken)
-            => innerStream.WriteAsync(content, cancellationToken);
+    public ValueTask WriteAsync(ReadOnlyMemory<char> content, CancellationToken cancellationToken)
+    {
+        return innerStream.WriteAsync(content, cancellationToken);
+    }
 
 
-        public ValueTask FlushAsync(CancellationToken cancellationToken)
-            => innerStream.FlushAsync(cancellationToken);
+    public ValueTask FlushAsync(CancellationToken cancellationToken)
+    {
+        return innerStream.FlushAsync(cancellationToken);
+    }
 
 
-        public void SetVBuf(LuaFileBufferingMode mode, int size)
-            => innerStream.SetVBuf(mode, size);
+    public void SetVBuf(LuaFileBufferingMode mode, int size)
+    {
+        innerStream.SetVBuf(mode, size);
+    }
 
 
-        public long Seek(SeekOrigin origin, long offset)
-            => innerStream.Seek(origin, offset);
+    public long Seek(SeekOrigin origin, long offset)
+    {
+        return innerStream.Seek(origin, offset);
+    }
 
 
-        public void Close()
-        {
-            throw new IOException("cannot close standard file");
-        }
+    public void Close()
+    {
+        throw new IOException("cannot close standard file");
+    }
 
 
-        public ValueTask CloseAsync(CancellationToken cancellationToken)
-        {
-            throw new IOException("cannot close standard file");
-        }
+    public ValueTask CloseAsync(CancellationToken cancellationToken)
+    {
+        throw new IOException("cannot close standard file");
+    }
 
 
-        public void Dispose()
-        {
-            // Do not dispose inner stream to prevent closing standard IO streams
-            innerStream.Dispose();
-        }
+    public void Dispose()
+    {
+        // Do not dispose inner stream to prevent closing standard IO streams
+        innerStream.Dispose();
     }
     }
 }
 }

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

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

+ 2 - 2
src/Lua/Internal/CompilerServices/LightAsyncTaskMethodBuilder.cs

@@ -35,7 +35,7 @@ using System.Security;
 namespace Lua.Internal.CompilerServices;
 namespace Lua.Internal.CompilerServices;
 
 
 [StructLayout(LayoutKind.Auto)]
 [StructLayout(LayoutKind.Auto)]
-internal struct LightAsyncValueTaskMethodBuilder
+struct LightAsyncValueTaskMethodBuilder
 {
 {
     IStateMachineRunnerPromise? runnerPromise;
     IStateMachineRunnerPromise? runnerPromise;
     Exception? ex;
     Exception? ex;
@@ -141,7 +141,7 @@ internal struct LightAsyncValueTaskMethodBuilder
 }
 }
 
 
 [StructLayout(LayoutKind.Auto)]
 [StructLayout(LayoutKind.Auto)]
-internal struct LightAsyncValueTaskMethodBuilder<T>
+struct LightAsyncValueTaskMethodBuilder<T>
 {
 {
     IStateMachineRunnerPromise<T>? runnerPromise;
     IStateMachineRunnerPromise<T>? runnerPromise;
     Exception? ex;
     Exception? ex;

+ 163 - 145
src/Lua/Internal/CompilerServices/StateMachineRunner.cs

@@ -33,207 +33,225 @@ using System.Threading.Tasks.Sources;
 
 
 // ReSharper disable ArrangeTypeMemberModifiers
 // ReSharper disable ArrangeTypeMemberModifiers
 
 
-namespace Lua.Internal.CompilerServices
-{
-    internal interface IStateMachineRunnerPromise : IValueTaskSource
-    {
-        Action MoveNext { get; }
-        ValueTask Task { get; }
-        void SetResult();
-        void SetException(Exception exception);
-    }
+namespace Lua.Internal.CompilerServices;
 
 
-    internal interface IStateMachineRunnerPromise<T> : IValueTaskSource<T>
-    {
-        Action MoveNext { get; }
-        ValueTask<T> Task { get; }
-        void SetResult(T result);
-        void SetException(Exception exception);
-    }
+interface IStateMachineRunnerPromise : IValueTaskSource
+{
+    Action MoveNext { get; }
+    ValueTask Task { get; }
+    void SetResult();
+    void SetException(Exception exception);
+}
 
 
+interface IStateMachineRunnerPromise<T> : IValueTaskSource<T>
+{
+    Action MoveNext { get; }
+    ValueTask<T> Task { get; }
+    void SetResult(T result);
+    void SetException(Exception exception);
+}
+
+sealed class LightAsyncValueTask<TStateMachine> : IStateMachineRunnerPromise, IPoolNode<LightAsyncValueTask<TStateMachine>>
+    where TStateMachine : IAsyncStateMachine
+{
+    static LinkedPool<LightAsyncValueTask<TStateMachine>> pool;
 
 
-    internal sealed class LightAsyncValueTask<TStateMachine> : IStateMachineRunnerPromise, IPoolNode<LightAsyncValueTask<TStateMachine>>
-        where TStateMachine : IAsyncStateMachine
-    {
-        static LinkedPool<LightAsyncValueTask<TStateMachine>> pool;
+    public Action MoveNext { get; }
 
 
-        public Action MoveNext { get; }
+    TStateMachine? stateMachine;
+    ManualResetValueTaskSourceCore<byte> core;
 
 
-        TStateMachine? stateMachine;
-        ManualResetValueTaskSourceCore<byte> core;
+    LightAsyncValueTask()
+    {
+        MoveNext = Run;
+    }
 
 
-        LightAsyncValueTask()
+    public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunnerPromise? runnerPromiseFieldRef)
+    {
+        if (!pool.TryPop(out var result))
         {
         {
-            MoveNext = Run;
+            result = new();
         }
         }
 
 
-        public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunnerPromise? runnerPromiseFieldRef)
-        {
-            if (!pool.TryPop(out var result))
-            {
-                result = new();
-            }
-
-            runnerPromiseFieldRef = result; // set runner before copied.
-            result.stateMachine = stateMachine; // copy struct StateMachine(in release build).
-        }
+        runnerPromiseFieldRef = result; // set runner before copied.
+        result.stateMachine = stateMachine; // copy struct StateMachine(in release build).
+    }
 
 
-        LightAsyncValueTask<TStateMachine>? nextNode;
-        public ref LightAsyncValueTask<TStateMachine>? NextNode => ref nextNode;
+    LightAsyncValueTask<TStateMachine>? nextNode;
 
 
-        void Return()
+    public ref LightAsyncValueTask<TStateMachine>? NextNode
+    {
+        get
         {
         {
-            core.Reset();
-            stateMachine = default;
-            pool.TryPush(this);
+            return ref nextNode;
         }
         }
+    }
 
 
+    void Return()
+    {
+        core.Reset();
+        stateMachine = default;
+        pool.TryPush(this);
+    }
 
 
-        [DebuggerHidden]
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        void Run()
-        {
-            stateMachine!.MoveNext();
-        }
 
 
-        public ValueTask Task
-        {
-            [DebuggerHidden]
-            get => new(this, core.Version);
-        }
+    [DebuggerHidden]
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    void Run()
+    {
+        stateMachine!.MoveNext();
+    }
 
 
+    public ValueTask Task
+    {
         [DebuggerHidden]
         [DebuggerHidden]
-        public void SetResult()
+        get
         {
         {
-            core.SetResult(0);
+            return new(this, core.Version);
         }
         }
+    }
 
 
-        [DebuggerHidden]
-        public void SetException(Exception exception)
-        {
-            core.SetException(exception);
-        }
+    [DebuggerHidden]
+    public void SetResult()
+    {
+        core.SetResult(0);
+    }
 
 
-        [DebuggerHidden]
-        public void GetResult(short token)
-        {
-            try
-            {
-                core.GetResult(token);
-            }
-            finally
-            {
-                Return();
-            }
-        }
+    [DebuggerHidden]
+    public void SetException(Exception exception)
+    {
+        core.SetException(exception);
+    }
 
 
-        [DebuggerHidden]
-        public ValueTaskSourceStatus GetStatus(short token)
+    [DebuggerHidden]
+    public void GetResult(short token)
+    {
+        try
         {
         {
-            return core.GetStatus(token);
+            core.GetResult(token);
         }
         }
-
-
-        [DebuggerHidden]
-        public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
+        finally
         {
         {
-            core.OnCompleted(continuation, state, token, flags);
+            Return();
         }
         }
     }
     }
 
 
-    internal sealed class LightAsyncValueTask<TStateMachine, T> : IStateMachineRunnerPromise<T>, IPoolNode<LightAsyncValueTask<TStateMachine, T>>
-        where TStateMachine : IAsyncStateMachine
+    [DebuggerHidden]
+    public ValueTaskSourceStatus GetStatus(short token)
     {
     {
-        static LinkedPool<LightAsyncValueTask<TStateMachine, T>> pool;
-
-        public Action MoveNext { get; }
+        return core.GetStatus(token);
+    }
 
 
-        TStateMachine? stateMachine;
-        ManualResetValueTaskSourceCore<T> core;
 
 
-        LightAsyncValueTask()
-        {
-            MoveNext = Run;
-        }
+    [DebuggerHidden]
+    public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
+    {
+        core.OnCompleted(continuation, state, token, flags);
+    }
+}
 
 
-        public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunnerPromise<T>? runnerPromiseFieldRef)
-        {
-            if (!pool.TryPop(out var result))
-            {
-                result = new();
-            }
+sealed class LightAsyncValueTask<TStateMachine, T> : IStateMachineRunnerPromise<T>, IPoolNode<LightAsyncValueTask<TStateMachine, T>>
+    where TStateMachine : IAsyncStateMachine
+{
+    static LinkedPool<LightAsyncValueTask<TStateMachine, T>> pool;
 
 
-            runnerPromiseFieldRef = result; // set runner before copied.
-            result.stateMachine = stateMachine; // copy struct StateMachine(in release build).
-        }
+    public Action MoveNext { get; }
 
 
-        LightAsyncValueTask<TStateMachine, T>? nextNode;
-        public ref LightAsyncValueTask<TStateMachine, T>? NextNode => ref nextNode;
+    TStateMachine? stateMachine;
+    ManualResetValueTaskSourceCore<T> core;
 
 
+    LightAsyncValueTask()
+    {
+        MoveNext = Run;
+    }
 
 
-        void Return()
+    public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunnerPromise<T>? runnerPromiseFieldRef)
+    {
+        if (!pool.TryPop(out var result))
         {
         {
-            core.Reset();
-            stateMachine = default!;
-            pool.TryPush(this);
+            result = new();
         }
         }
 
 
+        runnerPromiseFieldRef = result; // set runner before copied.
+        result.stateMachine = stateMachine; // copy struct StateMachine(in release build).
+    }
 
 
-        [DebuggerHidden]
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        void Run()
-        {
-            stateMachine!.MoveNext();
-        }
+    LightAsyncValueTask<TStateMachine, T>? nextNode;
 
 
-        public ValueTask<T> Task
+    public ref LightAsyncValueTask<TStateMachine, T>? NextNode
+    {
+        get
         {
         {
-            [DebuggerHidden]
-            get => new(this, core.Version);
+            return ref nextNode;
         }
         }
+    }
 
 
-        [DebuggerHidden]
-        public void SetResult(T result)
-        {
-            core.SetResult(result);
-        }
 
 
-        [DebuggerHidden]
-        public void SetException(Exception exception)
-        {
-            core.SetException(exception);
-        }
+    void Return()
+    {
+        core.Reset();
+        stateMachine = default!;
+        pool.TryPush(this);
+    }
+
+
+    [DebuggerHidden]
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    void Run()
+    {
+        stateMachine!.MoveNext();
+    }
 
 
+    public ValueTask<T> Task
+    {
         [DebuggerHidden]
         [DebuggerHidden]
-        public T GetResult(short token)
+        get
         {
         {
-            try
-            {
-                return core.GetResult(token);
-            }
-            finally
-            {
-                Return();
-            }
+            return new(this, core.Version);
         }
         }
+    }
 
 
-        [DebuggerHidden]
-        T IValueTaskSource<T>.GetResult(short token)
+    [DebuggerHidden]
+    public void SetResult(T result)
+    {
+        core.SetResult(result);
+    }
+
+    [DebuggerHidden]
+    public void SetException(Exception exception)
+    {
+        core.SetException(exception);
+    }
+
+    [DebuggerHidden]
+    public T GetResult(short token)
+    {
+        try
         {
         {
-            return GetResult(token);
+            return core.GetResult(token);
         }
         }
-
-        [DebuggerHidden]
-        public ValueTaskSourceStatus GetStatus(short token)
+        finally
         {
         {
-            return core.GetStatus(token);
+            Return();
         }
         }
+    }
 
 
+    [DebuggerHidden]
+    T IValueTaskSource<T>.GetResult(short token)
+    {
+        return GetResult(token);
+    }
 
 
-        [DebuggerHidden]
-        public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
-        {
-            core.OnCompleted(continuation, state, token, flags);
-        }
+    [DebuggerHidden]
+    public ValueTaskSourceStatus GetStatus(short token)
+    {
+        return core.GetStatus(token);
+    }
+
+
+    [DebuggerHidden]
+    public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
+    {
+        core.OnCompleted(continuation, state, token, flags);
     }
     }
 }
 }

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

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

+ 9 - 5
src/Lua/Internal/EnumerableEx.cs

@@ -1,11 +1,15 @@
 namespace Lua;
 namespace Lua;
 
 
-internal static class EnumerableEx
+static class EnumerableEx
 {
 {
     public static IEnumerable<IEnumerable<T>> GroupConsecutiveBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
     public static IEnumerable<IEnumerable<T>> GroupConsecutiveBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
     {
     {
-        if (source == null) throw new ArgumentNullException(nameof(source));
-        if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
+        if (source == null)
+            throw new ArgumentNullException(nameof(source));
+
+        if (keySelector == null)
+            throw new ArgumentNullException(nameof(keySelector));
+
 
 
         using var enumerator = source.GetEnumerator();
         using var enumerator = source.GetEnumerator();
         if (!enumerator.MoveNext())
         if (!enumerator.MoveNext())
@@ -13,12 +17,12 @@ internal static class EnumerableEx
             yield break;
             yield break;
         }
         }
 
 
-        var group = new List<T> { enumerator.Current };
+        List<T> group = new() { enumerator.Current };
         var previousKey = keySelector(enumerator.Current);
         var previousKey = keySelector(enumerator.Current);
 
 
         while (enumerator.MoveNext())
         while (enumerator.MoveNext())
         {
         {
-            TKey currentKey = keySelector(enumerator.Current);
+            var currentKey = keySelector(enumerator.Current);
 
 
             if (!EqualityComparer<TKey>.Default.Equals(previousKey, currentKey))
             if (!EqualityComparer<TKey>.Default.Equals(previousKey, currentKey))
             {
             {

+ 63 - 63
src/Lua/Internal/FarmHash.cs

@@ -3,7 +3,7 @@ using System.Runtime.InteropServices;
 
 
 namespace Lua;
 namespace Lua;
 
 
-internal static class FarmHash
+static class FarmHash
 {
 {
     // entry point
     // entry point
 
 
@@ -46,7 +46,7 @@ internal static class FarmHash
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     static Pair make_pair(ulong first, ulong second)
     static Pair make_pair(ulong first, ulong second)
     {
     {
-        return new Pair(first, second);
+        return new(first, second);
     }
     }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -86,9 +86,9 @@ internal static class FarmHash
         unchecked
         unchecked
         {
         {
             // Murmur-inspired hashing.
             // Murmur-inspired hashing.
-            ulong a = (u ^ v) * mul;
+            var a = (u ^ v) * mul;
             a ^= a >> 47;
             a ^= a >> 47;
-            ulong b = (v ^ a) * mul;
+            var b = (v ^ a) * mul;
             b ^= b >> 47;
             b ^= b >> 47;
             b *= mul;
             b *= mul;
             return b;
             return b;
@@ -139,17 +139,17 @@ internal static class FarmHash
         {
         {
             if (len >= 8)
             if (len >= 8)
             {
             {
-                ulong mul = k2 + len * 2;
-                ulong a = Fetch64(s) + k2;
-                ulong b = Fetch64(s + len - 8);
-                ulong c = Rotate64(b, 37) * mul + a;
-                ulong d = (Rotate64(a, 25) + b) * mul;
+                var mul = k2 + (len * 2);
+                var a = Fetch64(s) + k2;
+                var b = Fetch64(s + len - 8);
+                var c = (Rotate64(b, 37) * mul) + a;
+                var d = (Rotate64(a, 25) + b) * mul;
                 return HashLen16(c, d, mul);
                 return HashLen16(c, d, mul);
             }
             }
 
 
             if (len >= 4)
             if (len >= 4)
             {
             {
-                ulong mul = k2 + len * 2;
+                var mul = k2 + (len * 2);
                 ulong a = Fetch32(s);
                 ulong a = Fetch32(s);
                 return HashLen16(len + (a << 3), Fetch32(s + len - 4), mul);
                 return HashLen16(len + (a << 3), Fetch32(s + len - 4), mul);
             }
             }
@@ -159,9 +159,9 @@ internal static class FarmHash
                 ushort a = s[0];
                 ushort a = s[0];
                 ushort b = s[len >> 1];
                 ushort b = s[len >> 1];
                 ushort c = s[len - 1];
                 ushort c = s[len - 1];
-                uint y = a + ((uint)b << 8);
-                uint z = len + ((uint)c << 2);
-                return ShiftMix(y * k2 ^ z * k0) * k2;
+                var y = a + ((uint)b << 8);
+                var z = len + ((uint)c << 2);
+                return ShiftMix((y * k2) ^ (z * k0)) * k2;
             }
             }
 
 
             return k2;
             return k2;
@@ -174,11 +174,11 @@ internal static class FarmHash
     {
     {
         unchecked
         unchecked
         {
         {
-            ulong mul = k2 + len * 2;
-            ulong a = Fetch64(s) * k1;
-            ulong b = Fetch64(s + 8);
-            ulong c = Fetch64(s + len - 8) * mul;
-            ulong d = Fetch64(s + len - 16) * k2;
+            var mul = k2 + (len * 2);
+            var a = Fetch64(s) * k1;
+            var b = Fetch64(s + 8);
+            var c = Fetch64(s + len - 8) * mul;
+            var d = Fetch64(s + len - 16) * k2;
             return HashLen16(Rotate64(a + b, 43) + Rotate64(c, 30) + d,
             return HashLen16(Rotate64(a + b, 43) + Rotate64(c, 30) + d,
                 a + Rotate64(b + k2, 18) + c, mul);
                 a + Rotate64(b + k2, 18) + c, mul);
         }
         }
@@ -190,12 +190,12 @@ internal static class FarmHash
     {
     {
         unchecked
         unchecked
         {
         {
-            ulong a = Fetch64(s) * k1;
-            ulong b = Fetch64(s + 8);
-            ulong c = Fetch64(s + len - 8) * mul;
-            ulong d = Fetch64(s + len - 16) * k2;
-            ulong u = Rotate64(a + b, 43) + Rotate64(c, 30) + d + seed0;
-            ulong v = a + Rotate64(b + k2, 18) + c + seed1;
+            var a = Fetch64(s) * k1;
+            var b = Fetch64(s + 8);
+            var c = Fetch64(s + len - 8) * mul;
+            var d = Fetch64(s + len - 16) * k2;
+            var u = Rotate64(a + b, 43) + Rotate64(c, 30) + d + seed0;
+            var v = a + Rotate64(b + k2, 18) + c + seed1;
             a = ShiftMix((u ^ v) * mul);
             a = ShiftMix((u ^ v) * mul);
             b = ShiftMix((v ^ a) * mul);
             b = ShiftMix((v ^ a) * mul);
             return b;
             return b;
@@ -210,10 +210,10 @@ internal static class FarmHash
 
 
         unchecked
         unchecked
         {
         {
-            ulong mul1 = k2 - 30 + 2 * len;
-            ulong h0 = H32(s, 32, mul0);
-            ulong h1 = H32(s + len - 32, 32, mul1);
-            return (h1 * mul1 + h0) * mul1;
+            var mul1 = k2 - 30 + (2 * len);
+            var h0 = H32(s, 32, mul0);
+            var h1 = H32(s + len - 32, 32, mul1);
+            return ((h1 * mul1) + h0) * mul1;
         }
         }
     }
     }
 
 
@@ -225,11 +225,11 @@ internal static class FarmHash
 
 
         unchecked
         unchecked
         {
         {
-            ulong mul1 = k2 - 114 + 2 * len;
-            ulong h0 = H32(s, 32, mul0);
-            ulong h1 = H32(s + 32, 32, mul1);
-            ulong h2 = H32(s + len - 32, 32, mul1, h0, h1);
-            return (h2 * 9 + (h0 >> 17) + (h1 >> 21)) * mul1;
+            var mul1 = k2 - 114 + (2 * len);
+            var h0 = H32(s, 32, mul0);
+            var h1 = H32(s + 32, 32, mul1);
+            var h2 = H32(s + len - 32, 32, mul1, h0, h1);
+            return ((h2 * 9) + (h0 >> 17) + (h1 >> 21)) * mul1;
         }
         }
     }
     }
 
 
@@ -243,7 +243,7 @@ internal static class FarmHash
         {
         {
             a += w;
             a += w;
             b = Rotate64(b + a + z, 21);
             b = Rotate64(b + a + z, 21);
-            ulong c = a;
+            var c = a;
             a += x;
             a += x;
             a += y;
             a += y;
             b += Rotate64(a, 44);
             b += Rotate64(a, 44);
@@ -274,16 +274,16 @@ internal static class FarmHash
         {
         {
             // For strings over 64 bytes we loop.  Internal state consists of
             // For strings over 64 bytes we loop.  Internal state consists of
             // 56 bytes: v, w, x, y, and z.
             // 56 bytes: v, w, x, y, and z.
-            ulong x = seed;
-            ulong y = seed * k1 + 113;
-            ulong z = ShiftMix(y * k2 + 113) * k2;
+            var x = seed;
+            var y = (seed * k1) + 113;
+            var z = ShiftMix((y * k2) + 113) * k2;
             var v = make_pair(0, 0);
             var v = make_pair(0, 0);
             var w = make_pair(0, 0);
             var w = make_pair(0, 0);
-            x = x * k2 + Fetch64(s);
+            x = (x * k2) + Fetch64(s);
 
 
             // Set end so that after the loop we have 1 to 64 bytes left to process.
             // Set end so that after the loop we have 1 to 64 bytes left to process.
-            byte* end = s + ((len - 1) / 64) * 64;
-            byte* last64 = end + ((len - 1) & 63) - 63;
+            var end = s + ((len - 1) / 64 * 64);
+            var last64 = end + ((len - 1) & 63) - 63;
 
 
             do
             do
             {
             {
@@ -298,21 +298,21 @@ internal static class FarmHash
                 s += 64;
                 s += 64;
             } while (s != end);
             } while (s != end);
 
 
-            ulong mul = k1 + ((z & 0xff) << 1);
+            var mul = k1 + ((z & 0xff) << 1);
             // Make s point to the last 64 bytes of input.
             // Make s point to the last 64 bytes of input.
             s = last64;
             s = last64;
-            w.first += ((len - 1) & 63);
+            w.first += (len - 1) & 63;
             v.first += w.first;
             v.first += w.first;
             w.first += v.first;
             w.first += v.first;
             x = Rotate64(x + y + v.first + Fetch64(s + 8), 37) * mul;
             x = Rotate64(x + y + v.first + Fetch64(s + 8), 37) * mul;
             y = Rotate64(y + v.second + Fetch64(s + 48), 42) * mul;
             y = Rotate64(y + v.second + Fetch64(s + 48), 42) * mul;
             x ^= w.second * 9;
             x ^= w.second * 9;
-            y += v.first * 9 + Fetch64(s + 40);
+            y += (v.first * 9) + Fetch64(s + 40);
             z = Rotate64(z + w.first, 33) * mul;
             z = Rotate64(z + w.first, 33) * mul;
             v = WeakHashLen32WithSeeds(s, v.second * mul, x + w.first);
             v = WeakHashLen32WithSeeds(s, v.second * mul, x + w.first);
             w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch64(s + 16));
             w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch64(s + 16));
             swap(ref z, ref x);
             swap(ref z, ref x);
-            return HashLen16(HashLen16(v.first, w.first, mul) + ShiftMix(y) * k0 + z,
+            return HashLen16(HashLen16(v.first, w.first, mul) + (ShiftMix(y) * k0) + z,
                 HashLen16(v.second, w.second, mul) + x,
                 HashLen16(v.second, w.second, mul) + x,
                 mul);
                 mul);
         }
         }
@@ -324,9 +324,9 @@ internal static class FarmHash
     {
     {
         unchecked
         unchecked
         {
         {
-            ulong a = (x ^ y) * mul;
-            a ^= (a >> 47);
-            ulong b = (y ^ a) * mul;
+            var a = (x ^ y) * mul;
+            a ^= a >> 47;
+            var b = (y ^ a) * mul;
             return Rotate64(b, r) * mul;
             return Rotate64(b, r) * mul;
         }
         }
     }
     }
@@ -342,29 +342,29 @@ internal static class FarmHash
         {
         {
             // For strings over 64 bytes we loop.  Internal state consists of
             // For strings over 64 bytes we loop.  Internal state consists of
             // 64 bytes: u, v, w, x, y, and z.
             // 64 bytes: u, v, w, x, y, and z.
-            ulong x = seed0;
-            ulong y = seed1 * k2 + 113;
-            ulong z = ShiftMix(y * k2) * k2;
+            var x = seed0;
+            var y = (seed1 * k2) + 113;
+            var z = ShiftMix(y * k2) * k2;
             var v = make_pair(seed0, seed1);
             var v = make_pair(seed0, seed1);
             var w = make_pair(0, 0);
             var w = make_pair(0, 0);
-            ulong u = x - z;
+            var u = x - z;
             x *= k2;
             x *= k2;
-            ulong mul = k2 + (u & 0x82);
+            var mul = k2 + (u & 0x82);
 
 
             // Set end so that after the loop we have 1 to 64 bytes left to process.
             // Set end so that after the loop we have 1 to 64 bytes left to process.
-            byte* end = s + ((len - 1) / 64) * 64;
-            byte* last64 = end + ((len - 1) & 63) - 63;
+            var end = s + ((len - 1) / 64 * 64);
+            var last64 = end + ((len - 1) & 63) - 63;
 
 
             do
             do
             {
             {
-                ulong a0 = Fetch64(s);
-                ulong a1 = Fetch64(s + 8);
-                ulong a2 = Fetch64(s + 16);
-                ulong a3 = Fetch64(s + 24);
-                ulong a4 = Fetch64(s + 32);
-                ulong a5 = Fetch64(s + 40);
-                ulong a6 = Fetch64(s + 48);
-                ulong a7 = Fetch64(s + 56);
+                var a0 = Fetch64(s);
+                var a1 = Fetch64(s + 8);
+                var a2 = Fetch64(s + 16);
+                var a3 = Fetch64(s + 24);
+                var a4 = Fetch64(s + 32);
+                var a5 = Fetch64(s + 40);
+                var a6 = Fetch64(s + 48);
+                var a7 = Fetch64(s + 56);
                 x += a0 + a1;
                 x += a0 + a1;
                 y += a2;
                 y += a2;
                 z += a3;
                 z += a3;
@@ -411,7 +411,7 @@ internal static class FarmHash
             u *= 9;
             u *= 9;
             v.second = Rotate64(v.second, 28);
             v.second = Rotate64(v.second, 28);
             v.first = Rotate64(v.first, 20);
             v.first = Rotate64(v.first, 20);
-            w.first += ((len - 1) & 63);
+            w.first += (len - 1) & 63;
             u += y;
             u += y;
             y += u;
             y += u;
             x = Rotate64(y - x + v.first + Fetch64(s + 8), 37) * mul;
             x = Rotate64(y - x + v.first + Fetch64(s + 8), 37) * mul;

+ 29 - 8
src/Lua/Internal/FastListCore.cs

@@ -56,7 +56,10 @@ public struct FastListCore<T>
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public void Shrink(int newSize)
     public void Shrink(int newSize)
     {
     {
-        if (newSize >= tailIndex) return;
+        if (newSize >= tailIndex)
+        {
+            return;
+        }
 
 
         array.AsSpan(newSize).Clear();
         array.AsSpan(newSize).Clear();
         tailIndex = newSize;
         tailIndex = newSize;
@@ -65,11 +68,17 @@ public struct FastListCore<T>
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public void Clear(bool removeArray = false)
     public void Clear(bool removeArray = false)
     {
     {
-        if (array == null) return;
+        if (array == null)
+        {
+            return;
+        }
 
 
         array.AsSpan().Clear();
         array.AsSpan().Clear();
         tailIndex = 0;
         tailIndex = 0;
-        if (removeArray) array = null;
+        if (removeArray)
+        {
+            array = null;
+        }
     }
     }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -106,17 +115,29 @@ public struct FastListCore<T>
         get => tailIndex;
         get => tailIndex;
     }
     }
 
 
-    public readonly Span<T> AsSpan() => array == null ? Span<T>.Empty : array.AsSpan(0, tailIndex);
+    public readonly Span<T> AsSpan()
+    {
+        return array == null ? Span<T>.Empty : array.AsSpan(0, tailIndex);
+    }
 
 
     [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
     [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
-    private readonly Span<T> Span => AsSpan();
+    readonly Span<T> Span => AsSpan();
 
 
-    public readonly T[]? AsArray() => array;
+    public readonly T[]? AsArray()
+    {
+        return array;
+    }
 
 
     readonly void CheckIndex(int index)
     readonly void CheckIndex(int index)
     {
     {
-        if (array == null || index < 0 || index > tailIndex) ThrowIndexOutOfRange();
+        if (array == null || index < 0 || index > tailIndex)
+        {
+            ThrowIndexOutOfRange();
+        }
     }
     }
 
 
-    static void ThrowIndexOutOfRange() => throw new IndexOutOfRangeException();
+    static void ThrowIndexOutOfRange()
+    {
+        throw new IndexOutOfRangeException();
+    }
 }
 }

+ 12 - 15
src/Lua/Internal/FastStackCore.cs

@@ -14,25 +14,17 @@ public struct FastStackCore<T>
 
 
     public int Count => tail;
     public int Count => tail;
 
 
-    public readonly ReadOnlySpan<T> AsSpan()
+    public readonly Span<T?> AsSpan()
     {
     {
-        if (array == null) return [];
-        return array.AsSpan(0, tail)!;
+        return array == null ? [] : array.AsSpan(0, tail)!;
     }
     }
 
 
     public readonly Span<T?> GetBuffer()
     public readonly Span<T?> GetBuffer()
     {
     {
-        if (array == null) return [];
-        return array.AsSpan();
+        return array == null ? [] : array.AsSpan();
     }
     }
 
 
-    public readonly T? this[int index]
-    {
-        get
-        {
-            return array[index];
-        }
-    }
+    public readonly T? this[int index] => array[index];
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public void Push(in T item)
     public void Push(in T item)
@@ -79,7 +71,9 @@ public struct FastStackCore<T>
 
 
     public T Pop()
     public T Pop()
     {
     {
-        if (!TryPop(out var result)) ThrowForEmptyStack();
+        if (!TryPop(out var result))
+            ThrowForEmptyStack();
+
         return result;
         return result;
     }
     }
 
 
@@ -104,7 +98,9 @@ public struct FastStackCore<T>
 
 
     public T Peek()
     public T Peek()
     {
     {
-        if (!TryPeek(out var result)) ThrowForEmptyStack();
+        if (!TryPeek(out var result))
+            ThrowForEmptyStack();
+
         return result;
         return result;
     }
     }
 
 
@@ -140,7 +136,8 @@ public struct FastStackCore<T>
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public void NotifyTop(int top)
     public void NotifyTop(int top)
     {
     {
-        if (tail < top) tail = top;
+        if (tail < top)
+            tail = top;
     }
     }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]

+ 40 - 21
src/Lua/Internal/HexConverter.cs

@@ -35,7 +35,7 @@ public static class HexConverter
         {
         {
             // unsigned big integer
             // unsigned big integer
             // TODO: optimize
             // TODO: optimize
-            using var buffer = new PooledArray<char>(text.Length + 1);
+            using PooledArray<char> buffer = new(text.Length + 1);
             text.CopyTo(buffer.AsSpan()[1..]);
             text.CopyTo(buffer.AsSpan()[1..]);
             buffer[0] = '0';
             buffer[0] = '0';
             return sign * (double)BigInteger.Parse(buffer.AsSpan()[..(text.Length + 1)], NumberStyles.AllowHexSpecifier);
             return sign * (double)BigInteger.Parse(buffer.AsSpan()[..(text.Length + 1)], NumberStyles.AllowHexSpecifier);
@@ -69,12 +69,12 @@ public static class HexConverter
             : long.Parse(intPart, NumberStyles.AllowHexSpecifier);
             : long.Parse(intPart, NumberStyles.AllowHexSpecifier);
 
 
         var decimalValue = 0.0;
         var decimalValue = 0.0;
-        for (int i = 0; i < decimalPart.Length; i++)
+        for (var i = 0; i < decimalPart.Length; i++)
         {
         {
             decimalValue += ToInt(decimalPart[i]) * Math.Pow(16, -(i + 1));
             decimalValue += ToInt(decimalPart[i]) * Math.Pow(16, -(i + 1));
         }
         }
 
 
-        double result = value + decimalValue;
+        var result = value + decimalValue;
 
 
         if (expPart.Length > 0)
         if (expPart.Length > 0)
         {
         {
@@ -93,11 +93,11 @@ public static class HexConverter
                 case < '0':
                 case < '0':
                     return 0;
                     return 0;
                 case <= '9':
                 case <= '9':
-                    return (c - '0');
+                    return c - '0';
                 case >= 'A' and <= 'F':
                 case >= 'A' and <= 'F':
-                    return (c - 'A' + 10);
+                    return c - 'A' + 10;
                 case >= 'a' and <= 'f':
                 case >= 'a' and <= 'f':
-                    return (c - 'a' + 10);
+                    return c - 'a' + 10;
             }
             }
         }
         }
 
 
@@ -107,56 +107,73 @@ public static class HexConverter
     public static string FromDouble(double value)
     public static string FromDouble(double value)
     {
     {
         if (double.IsNaN(value))
         if (double.IsNaN(value))
+        {
             return "(0/0)";
             return "(0/0)";
+        }
+
         if (double.IsPositiveInfinity(value))
         if (double.IsPositiveInfinity(value))
+        {
             return "1e9999";
             return "1e9999";
+        }
+
         if (double.IsNegativeInfinity(value))
         if (double.IsNegativeInfinity(value))
+        {
             return "-1e9999";
             return "-1e9999";
+        }
+
         if (value == 0.0)
         if (value == 0.0)
+        {
             return BitConverter.DoubleToInt64Bits(value) < 0 ? "-0x0p+0" : "0x0p+0";
             return BitConverter.DoubleToInt64Bits(value) < 0 ? "-0x0p+0" : "0x0p+0";
+        }
 
 
         // Convert double to IEEE 754 representation
         // Convert double to IEEE 754 representation
-        long bits = BitConverter.DoubleToInt64Bits(value);
+        var bits = BitConverter.DoubleToInt64Bits(value);
 
 
         // sign bit 
         // sign bit 
-        bool isNegative = (bits & (1L << 63)) != 0;
+        var isNegative = (bits & (1L << 63)) != 0;
 
 
         // 11 bits of exponent
         // 11 bits of exponent
-        int exponent = (int)((bits >> 52) & ((1L << 11) - 1));
+        var exponent = (int)((bits >> 52) & ((1L << 11) - 1));
 
 
         // 52 bits of mantissa
         // 52 bits of mantissa
-        long mantissa = bits & ((1L << 52) - 1);
+        var mantissa = bits & ((1L << 52) - 1);
 
 
-        string sign = isNegative ? "-" : "";
+        var sign = isNegative ? "-" : "";
 
 
         if (exponent == 0)
         if (exponent == 0)
         {
         {
-            int leadingZeros = CountLeadingZeros(mantissa, 52);
-            mantissa <<= (leadingZeros + 1);
-            mantissa &= ((1L << 52) - 1); // 52ビットにマスク
+            var leadingZeros = CountLeadingZeros(mantissa, 52);
+            mantissa <<= leadingZeros + 1;
+            mantissa &= (1L << 52) - 1; // 52ビットにマスク
 
 
-            int adjustedExponent = -1022 - leadingZeros;
+            var adjustedExponent = -1022 - leadingZeros;
 
 
-            string mantissaHex = FormatMantissa(mantissa);
+            var mantissaHex = FormatMantissa(mantissa);
             return $"{sign}0x0.{mantissaHex}p{adjustedExponent:+0;-0}";
             return $"{sign}0x0.{mantissaHex}p{adjustedExponent:+0;-0}";
         }
         }
         else
         else
         {
         {
-            int adjustedExponent = exponent - 1023;
-            string mantissaHex = FormatMantissa(mantissa);
+            var adjustedExponent = exponent - 1023;
+            var mantissaHex = FormatMantissa(mantissa);
 
 
             if (mantissa == 0)
             if (mantissa == 0)
+            {
                 return $"{sign}0x1p{adjustedExponent:+0;-0}";
                 return $"{sign}0x1p{adjustedExponent:+0;-0}";
+            }
             else
             else
+            {
                 return $"{sign}0x1.{mantissaHex}p{adjustedExponent:+0;-0}";
                 return $"{sign}0x1.{mantissaHex}p{adjustedExponent:+0;-0}";
+            }
         }
         }
 
 
         static string FormatMantissa(long mantissa)
         static string FormatMantissa(long mantissa)
         {
         {
             if (mantissa == 0)
             if (mantissa == 0)
+            {
                 return "";
                 return "";
+            }
 
 
-            string hex = mantissa.ToString("x13"); // 13桁の16進数
+            var hex = mantissa.ToString("x13"); // 13桁の16進数
 
 
             hex = hex.TrimEnd('0');
             hex = hex.TrimEnd('0');
 
 
@@ -166,10 +183,12 @@ public static class HexConverter
         static int CountLeadingZeros(long value, int bitLength)
         static int CountLeadingZeros(long value, int bitLength)
         {
         {
             if (value == 0)
             if (value == 0)
+            {
                 return bitLength;
                 return bitLength;
+            }
 
 
-            int count = 0;
-            long mask = 1L << (bitLength - 1);
+            var count = 0;
+            var mask = 1L << (bitLength - 1);
 
 
             while ((value & mask) == 0 && count < bitLength)
             while ((value & mask) == 0 && count < bitLength)
             {
             {

+ 115 - 41
src/Lua/Internal/LuaDebug.cs

@@ -1,10 +1,11 @@
+using Lua.CodeAnalysis;
 using Lua.Runtime;
 using Lua.Runtime;
 using static Lua.Internal.OpMode;
 using static Lua.Internal.OpMode;
 using static Lua.Internal.OpArgMask;
 using static Lua.Internal.OpArgMask;
 
 
 namespace Lua.Internal;
 namespace Lua.Internal;
 
 
-internal readonly struct LuaDebug : IDisposable
+readonly struct LuaDebug : IDisposable
 {
 {
     readonly LuaDebugBuffer buffer;
     readonly LuaDebugBuffer buffer;
     readonly uint version;
     readonly uint version;
@@ -137,12 +138,19 @@ internal readonly struct LuaDebug : IDisposable
 
 
     public void CheckVersion()
     public void CheckVersion()
     {
     {
-        if (buffer.version != version) ThrowObjectDisposedException();
+        if (buffer.version != version)
+        {
+            ThrowObjectDisposedException();
+        }
     }
     }
 
 
     public void Dispose()
     public void Dispose()
     {
     {
-        if (buffer.version != version) ThrowObjectDisposedException();
+        if (buffer.version != version)
+        {
+            ThrowObjectDisposedException();
+        }
+
         buffer.Return(version);
         buffer.Return(version);
     }
     }
 
 
@@ -172,7 +180,10 @@ internal readonly struct LuaDebug : IDisposable
 
 
         internal void Return(uint version)
         internal void Return(uint version)
         {
         {
-            if (this.version != version) throw new ObjectDisposedException("Buffer has been modified");
+            if (this.version != version)
+            {
+                throw new ObjectDisposedException("Buffer has been modified");
+            }
 
 
             Name = null;
             Name = null;
             NameWhat = null;
             NameWhat = null;
@@ -196,8 +207,8 @@ internal readonly struct LuaDebug : IDisposable
 
 
         internal bool GetInfo(CallStackFrame? prevFrame, CallStackFrame? frame, LuaFunction function, int pc, ReadOnlySpan<char> what)
         internal bool GetInfo(CallStackFrame? prevFrame, CallStackFrame? frame, LuaFunction function, int pc, ReadOnlySpan<char> what)
         {
         {
-            LuaClosure? closure = function as LuaClosure;
-            int status = 1;
+            var closure = function as LuaClosure;
+            var status = 1;
             foreach (var c in what)
             foreach (var c in what)
             {
             {
                 switch (c)
                 switch (c)
@@ -209,12 +220,12 @@ internal readonly struct LuaDebug : IDisposable
                         }
                         }
                     case 'l':
                     case 'l':
                         {
                         {
-                            CurrentLine = (pc >= 0 && closure is not null) ? closure.Proto.LineInfo[pc] : -1;
+                            CurrentLine = pc >= 0 && closure is not null ? closure.Proto.LineInfo[pc] : -1;
                             break;
                             break;
                         }
                         }
                     case 'u':
                     case 'u':
                         {
                         {
-                            UpValueCount = (closure is null) ? 0 : closure.UpValues.Length;
+                            UpValueCount = closure is null ? 0 : closure.UpValues.Length;
                             if (closure is null)
                             if (closure is null)
                             {
                             {
                                 IsVarArg = true;
                                 IsVarArg = true;
@@ -237,9 +248,14 @@ internal readonly struct LuaDebug : IDisposable
                         {
                         {
                             /* calling function is a known Lua function? */
                             /* calling function is a known Lua function? */
                             if (prevFrame is { Function: LuaClosure prevFrameClosure })
                             if (prevFrame is { Function: LuaClosure prevFrameClosure })
+                            {
                                 NameWhat = GetFuncName(prevFrameClosure.Proto, frame?.CallerInstructionIndex ?? 0, out Name);
                                 NameWhat = GetFuncName(prevFrameClosure.Proto, frame?.CallerInstructionIndex ?? 0, out Name);
+                            }
                             else
                             else
+                            {
                                 NameWhat = null;
                                 NameWhat = null;
+                            }
+
                             if (NameWhat is null)
                             if (NameWhat is null)
                             {
                             {
                                 NameWhat = ""; /* not found */
                                 NameWhat = ""; /* not found */
@@ -279,7 +295,7 @@ internal readonly struct LuaDebug : IDisposable
                 Source = p.ChunkName;
                 Source = p.ChunkName;
                 LineDefined = p.LineDefined;
                 LineDefined = p.LineDefined;
                 LastLineDefined = p.LastLineDefined;
                 LastLineDefined = p.LastLineDefined;
-                What = (LineDefined == 0) ? "main" : "Lua";
+                What = LineDefined == 0 ? "main" : "Lua";
             }
             }
 
 
             ShortSourceLength = WriteShortSource(Source, ShortSource);
             ShortSourceLength = WriteShortSource(Source, ShortSource);
@@ -293,8 +309,16 @@ internal readonly struct LuaDebug : IDisposable
         var localId = register + 1;
         var localId = register + 1;
         foreach (var l in locals)
         foreach (var l in locals)
         {
         {
-            if (pc < l.StartPc) break;
-            if (l.EndPc <= pc) continue;
+            if (pc < l.StartPc)
+            {
+                break;
+            }
+
+            if (l.EndPc <= pc)
+            {
+                continue;
+            }
+
             localId--;
             localId--;
             if (localId == 0)
             if (localId == 0)
             {
             {
@@ -308,52 +332,68 @@ internal readonly struct LuaDebug : IDisposable
     static int FilterPc(int pc, int jmpTarget)
     static int FilterPc(int pc, int jmpTarget)
     {
     {
         if (pc < jmpTarget) /* is code conditional (inside a jump)? */
         if (pc < jmpTarget) /* is code conditional (inside a jump)? */
+        {
             return -1; /* cannot know who sets that register */
             return -1; /* cannot know who sets that register */
-        else return pc; /* current position sets that register */
+        }
+        else
+        {
+            return pc; /* current position sets that register */
+        }
     }
     }
 
 
     internal static int FindSetRegister(Prototype prototype, int lastPc, int reg)
     internal static int FindSetRegister(Prototype prototype, int lastPc, int reg)
     {
     {
         int pc;
         int pc;
-        int setReg = -1; /* keep last instruction that changed 'reg' */
-        int jmpTarget = 0; /* any code before this address is conditional */
+        var setReg = -1; /* keep last instruction that changed 'reg' */
+        var jmpTarget = 0; /* any code before this address is conditional */
         var instructions = prototype.Code;
         var instructions = prototype.Code;
         for (pc = 0; pc < lastPc; pc++)
         for (pc = 0; pc < lastPc; pc++)
         {
         {
-            Instruction i = instructions[pc];
-            OpCode op = i.OpCode;
-            int a = i.A;
+            var i = instructions[pc];
+            var op = i.OpCode;
+            var a = i.A;
             switch (op)
             switch (op)
             {
             {
                 case OpCode.LoadNil:
                 case OpCode.LoadNil:
                     {
                     {
-                        int b = i.B;
+                        var b = i.B;
                         if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */
                         if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */
+                        {
                             setReg = FilterPc(pc, jmpTarget);
                             setReg = FilterPc(pc, jmpTarget);
+                        }
+
                         break;
                         break;
                     }
                     }
                 case OpCode.TForCall:
                 case OpCode.TForCall:
                     {
                     {
                         if (reg >= a + 2) /* affect all regs above its base */
                         if (reg >= a + 2) /* affect all regs above its base */
+                        {
                             setReg = FilterPc(pc, jmpTarget);
                             setReg = FilterPc(pc, jmpTarget);
+                        }
+
                         break;
                         break;
                     }
                     }
                 case OpCode.Call:
                 case OpCode.Call:
                 case OpCode.TailCall:
                 case OpCode.TailCall:
                     {
                     {
                         if (reg >= a) /* affect all registers above base */
                         if (reg >= a) /* affect all registers above base */
+                        {
                             setReg = FilterPc(pc, jmpTarget);
                             setReg = FilterPc(pc, jmpTarget);
+                        }
+
                         break;
                         break;
                     }
                     }
                 case OpCode.Jmp:
                 case OpCode.Jmp:
                     {
                     {
-                        int b = i.SBx;
-                        int dest = pc + 1 + b;
+                        var b = i.SBx;
+                        var dest = pc + 1 + b;
                         /* jump is forward and do not skip `lastpc'? */
                         /* jump is forward and do not skip `lastpc'? */
                         if (pc < dest && dest <= lastPc)
                         if (pc < dest && dest <= lastPc)
                         {
                         {
                             if (dest > jmpTarget)
                             if (dest > jmpTarget)
+                            {
                                 jmpTarget = dest; /* update 'jmptarget' */
                                 jmpTarget = dest; /* update 'jmptarget' */
+                            }
                         }
                         }
 
 
                         break;
                         break;
@@ -361,12 +401,18 @@ internal readonly struct LuaDebug : IDisposable
                 case OpCode.Test:
                 case OpCode.Test:
                     {
                     {
                         if (reg == a) /* jumped code can change 'a' */
                         if (reg == a) /* jumped code can change 'a' */
+                        {
                             setReg = FilterPc(pc, jmpTarget);
                             setReg = FilterPc(pc, jmpTarget);
+                        }
+
                         break;
                         break;
                     }
                     }
                 default:
                 default:
                     if (TestAMode(op) && reg == a) /* any instruction that set A */
                     if (TestAMode(op) && reg == a) /* any instruction that set A */
+                    {
                         setReg = FilterPc(pc, jmpTarget);
                         setReg = FilterPc(pc, jmpTarget);
+                    }
+
                     break;
                     break;
             }
             }
         }
         }
@@ -416,24 +462,27 @@ internal readonly struct LuaDebug : IDisposable
         if (pc != -1)
         if (pc != -1)
         {
         {
             /* could find instruction? */
             /* could find instruction? */
-            Instruction i = prototype.Code[pc];
-            OpCode op = i.OpCode;
+            var i = prototype.Code[pc];
+            var op = i.OpCode;
             switch (op)
             switch (op)
             {
             {
                 case OpCode.Move:
                 case OpCode.Move:
                     {
                     {
-                        int b = i.B; /* move from 'b' to 'a' */
+                        var b = i.B; /* move from 'b' to 'a' */
                         if (b < i.A)
                         if (b < i.A)
+                        {
                             return GetName(prototype, pc, b, out name); /* get name for 'b' */
                             return GetName(prototype, pc, b, out name); /* get name for 'b' */
+                        }
+
                         break;
                         break;
                     }
                     }
                 case OpCode.GetTabUp:
                 case OpCode.GetTabUp:
                 case OpCode.GetTable:
                 case OpCode.GetTable:
                     {
                     {
-                        int k = i.C; /* key index */
-                        int t = i.B; /* table index */
+                        var k = i.C; /* key index */
+                        var t = i.B; /* table index */
 
 
-                        var vn = (op == OpCode.GetTable) /* name of indexed variable */
+                        var vn = op == OpCode.GetTable /* name of indexed variable */
                             ? GetLocalName(prototype, t, pc)
                             ? GetLocalName(prototype, t, pc)
                             : prototype.UpValues[t].Name.ToString();
                             : prototype.UpValues[t].Name.ToString();
                         GetConstantName(prototype, pc, k, out name);
                         GetConstantName(prototype, pc, k, out name);
@@ -447,9 +496,9 @@ internal readonly struct LuaDebug : IDisposable
                 case OpCode.LoadK:
                 case OpCode.LoadK:
                 case OpCode.LoadKX:
                 case OpCode.LoadKX:
                     {
                     {
-                        int b = (op != OpCode.LoadKX)
+                        var b = op != OpCode.LoadKX
                             ? i.Bx
                             ? i.Bx
-                            : (prototype.Code[pc + 1].Ax);
+                            : prototype.Code[pc + 1].Ax;
                         if (prototype.Constants[b].TryReadString(out name))
                         if (prototype.Constants[b].TryReadString(out name))
                         {
                         {
                             return "constant";
                             return "constant";
@@ -459,7 +508,7 @@ internal readonly struct LuaDebug : IDisposable
                     }
                     }
                 case OpCode.Self:
                 case OpCode.Self:
                     {
                     {
-                        int k = i.C; /* key index */
+                        var k = i.C; /* key index */
                         GetConstantName(prototype, pc, k, out name);
                         GetConstantName(prototype, pc, k, out name);
                         return "method";
                         return "method";
                     }
                     }
@@ -472,7 +521,7 @@ internal readonly struct LuaDebug : IDisposable
 
 
     internal static string? GetFuncName(Prototype prototype, int pc, out string? name)
     internal static string? GetFuncName(Prototype prototype, int pc, out string? name)
     {
     {
-        Instruction i = prototype.Code[pc]; /* calling instruction */
+        var i = prototype.Code[pc]; /* calling instruction */
         switch (i.OpCode)
         switch (i.OpCode)
         {
         {
             case OpCode.Call:
             case OpCode.Call:
@@ -548,7 +597,10 @@ internal readonly struct LuaDebug : IDisposable
         const string PREPOS = "[string \"\"]";
         const string PREPOS = "[string \"\"]";
 
 
         const int BUFFER_LEN = 59;
         const int BUFFER_LEN = 59;
-        if (dest.Length != BUFFER_LEN) throw new ArgumentException("dest must be 60 chars long");
+        if (dest.Length != BUFFER_LEN)
+        {
+            throw new ArgumentException("dest must be 60 chars long");
+        }
 
 
         if (source.Length == 0)
         if (source.Length == 0)
         {
         {
@@ -596,7 +648,7 @@ internal readonly struct LuaDebug : IDisposable
 
 
 
 
             PRE.AsSpan().CopyTo(dest);
             PRE.AsSpan().CopyTo(dest);
-            int newLine = source.IndexOfAny("\r\n");
+            var newLine = source.IndexOfAny("\r\n");
             if (newLine == -1 && source.Length < BUFFER_LEN - (PRE_LEN + RETS_LEN + POS_LEN))
             if (newLine == -1 && source.Length < BUFFER_LEN - (PRE_LEN + RETS_LEN + POS_LEN))
             {
             {
                 source.CopyTo(dest[PRE_LEN..]);
                 source.CopyTo(dest[PRE_LEN..]);
@@ -622,7 +674,10 @@ internal readonly struct LuaDebug : IDisposable
         }
         }
     }
     }
 
 
-    static int GetOpMode(byte t, byte a, OpArgMask b, OpArgMask c, OpMode m) => (((t) << 7) | ((a) << 6) | (((byte)b) << 4) | (((byte)c) << 2) | ((byte)m));
+    static int GetOpMode(byte t, byte a, OpArgMask b, OpArgMask c, OpMode m)
+    {
+        return (t << 7) | (a << 6) | ((byte)b << 4) | ((byte)c << 2) | (byte)m;
+    }
 
 
 
 
     static readonly int[] OpModes =
     static readonly int[] OpModes =
@@ -666,17 +721,36 @@ internal readonly struct LuaDebug : IDisposable
         GetOpMode(0, 0, OpArgU, OpArgU, iABC), /* OP_SETLIST */
         GetOpMode(0, 0, OpArgU, OpArgU, iABC), /* OP_SETLIST */
         GetOpMode(0, 1, OpArgU, OpArgN, iABx), /* OP_CLOSURE */
         GetOpMode(0, 1, OpArgU, OpArgN, iABx), /* OP_CLOSURE */
         GetOpMode(0, 1, OpArgU, OpArgN, iABC), /* OP_VARARG */
         GetOpMode(0, 1, OpArgU, OpArgN, iABC), /* OP_VARARG */
-        GetOpMode(0, 0, OpArgU, OpArgU, iAx), /* OP_EXTRAARG */
+        GetOpMode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */
     ];
     ];
 
 
-    internal static OpMode GetOpMode(OpCode m) => (OpMode)(OpModes[(int)m] & 3);
-    internal static OpArgMask GetBMode(OpCode m) => (OpArgMask)((OpModes[(int)m] >> 4) & 3);
-    internal static OpArgMask GetCMode(OpCode m) => (OpArgMask)((OpModes[(int)m] >> 2) & 3);
-    internal static bool TestAMode(OpCode m) => (OpModes[(int)m] & (1 << 6)) != 0;
-    internal static bool TestTMode(OpCode m) => (OpModes[(int)m] & (1 << 7)) != 0;
+    internal static OpMode GetOpMode(OpCode m)
+    {
+        return (OpMode)(OpModes[(int)m] & 3);
+    }
+
+    internal static OpArgMask GetBMode(OpCode m)
+    {
+        return (OpArgMask)((OpModes[(int)m] >> 4) & 3);
+    }
+
+    internal static OpArgMask GetCMode(OpCode m)
+    {
+        return (OpArgMask)((OpModes[(int)m] >> 2) & 3);
+    }
+
+    internal static bool TestAMode(OpCode m)
+    {
+        return (OpModes[(int)m] & (1 << 6)) != 0;
+    }
+
+    internal static bool TestTMode(OpCode m)
+    {
+        return (OpModes[(int)m] & (1 << 7)) != 0;
+    }
 }
 }
 
 
-internal enum OpMode : byte
+enum OpMode : byte
 {
 {
     iABC,
     iABC,
     iABx,
     iABx,
@@ -684,7 +758,7 @@ internal enum OpMode : byte
     iAx
     iAx
 }
 }
 
 
-internal enum OpArgMask : byte
+enum OpArgMask : byte
 {
 {
     OpArgN, /* argument is not used */
     OpArgN, /* argument is not used */
     OpArgU, /* argument is used */
     OpArgU, /* argument is used */

+ 382 - 347
src/Lua/Internal/LuaValueDictionary.cs

@@ -4,480 +4,515 @@
 using System.Diagnostics;
 using System.Diagnostics;
 using System.Runtime.CompilerServices;
 using System.Runtime.CompilerServices;
 
 
-namespace Lua.Internal
+namespace Lua.Internal;
+
+/// <summary>
+/// A minimal dictionary that uses LuaValue as key and value.
+/// Nil value counting is included.
+/// </summary>
+sealed class LuaValueDictionary
 {
 {
-    /// <summary>
-    /// A minimal dictionary that uses LuaValue as key and value.
-    /// Nil value counting is included.
-    /// </summary>
-    internal sealed class LuaValueDictionary
-    {
-        private int[]? _buckets;
-        private Entry[]? _entries;
-        private int _count;
-        private int _freeList;
-        private int _freeCount;
-        private int _version;
-        private const int StartOfFreeList = -3;
+    int[]? _buckets;
+    Entry[]? _entries;
+    int _count;
+    int _freeList;
+    int _freeCount;
+    int _version;
+    const int StartOfFreeList = -3;
 
 
-        private int _nilCount;
+    int _nilCount;
 
 
-        public LuaValueDictionary(int capacity)
+    public LuaValueDictionary(int capacity)
+    {
+        if (capacity < 0)
         {
         {
-            if (capacity < 0)
-            {
-                ThrowHelper.ThrowArgumentOutOfRangeException(nameof(capacity));
-            }
+            ThrowHelper.ThrowArgumentOutOfRangeException(nameof(capacity));
+        }
 
 
-            if (capacity > 0)
-            {
-                Initialize(capacity);
-            }
+        if (capacity > 0)
+        {
+            Initialize(capacity);
         }
         }
+    }
 
 
-        public int Count => _count - _freeCount;
+    public int Count => _count - _freeCount;
 
 
-        public int NilCount => _nilCount;
+    public int NilCount => _nilCount;
 
 
 
 
-        public LuaValue this[LuaValue key]
+    public LuaValue this[LuaValue key]
+    {
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        get
         {
         {
-            [MethodImpl(MethodImplOptions.AggressiveInlining)]
-            get
+            ref var value = ref FindValue(key, out _);
+            if (!Unsafe.IsNullRef(ref value))
             {
             {
-                ref LuaValue value = ref FindValue(key, out _);
-                if (!Unsafe.IsNullRef(ref value))
-                {
-                    return value;
-                }
-
-                return default;
+                return value;
             }
             }
-            [MethodImpl(MethodImplOptions.AggressiveInlining)]
-            set => Insert(key, value);
+
+            return default;
         }
         }
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        set => Insert(key, value);
+    }
 
 
 
 
-        public void Clear()
+    public void Clear()
+    {
+        var count = _count;
+        if (count > 0)
         {
         {
-            int count = _count;
-            if (count > 0)
-            {
-                Debug.Assert(_buckets != null, "_buckets should be non-null");
-                Debug.Assert(_entries != null, "_entries should be non-null");
+            Debug.Assert(_buckets != null, "_buckets should be non-null");
+            Debug.Assert(_entries != null, "_entries should be non-null");
 
 
-                Array.Clear(_buckets, 0, _buckets.Length);
+            Array.Clear(_buckets, 0, _buckets.Length);
 
 
-                _count = 0;
-                _freeList = -1;
-                _freeCount = 0;
-                Array.Clear(_entries, 0, count);
-                _nilCount = 0;
-            }
+            _count = 0;
+            _freeList = -1;
+            _freeCount = 0;
+            Array.Clear(_entries, 0, count);
+            _nilCount = 0;
         }
         }
+    }
 
 
-        public bool ContainsKey(LuaValue key) =>
-            !Unsafe.IsNullRef(ref FindValue(key, out _));
+    public bool ContainsKey(LuaValue key)
+    {
+        return !Unsafe.IsNullRef(ref FindValue(key, out _));
+    }
 
 
-        public bool ContainsValue(LuaValue value)
-        {
-            Entry[]? entries = _entries;
+    public bool ContainsValue(LuaValue value)
+    {
+        var entries = _entries;
 
 
-            for (int i = 0; i < _count; i++)
+        for (var i = 0; i < _count; i++)
+        {
+            if (entries![i].next >= -1 && entries[i].value.Equals(value))
             {
             {
-                if (entries![i].next >= -1 && entries[i].value.Equals(value))
-                {
-                    return true;
-                }
+                return true;
             }
             }
-
-            return false;
         }
         }
 
 
+        return false;
+    }
+
 
 
-        public Enumerator GetEnumerator() => new Enumerator(this);
+    public Enumerator GetEnumerator()
+    {
+        return new(this);
+    }
 
 
-        internal ref LuaValue FindValue(LuaValue key, out int index)
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    internal ref LuaValue FindValue(LuaValue key, out int index)
+    {
+        index = -1;
+        ref var entry = ref Unsafe.NullRef<Entry>();
+        if (_buckets != null)
         {
         {
-            index = -1;
-            ref Entry entry = ref Unsafe.NullRef<Entry>();
-            if (_buckets != null)
+            Debug.Assert(_entries != null, "expected entries to be != null");
             {
             {
-                Debug.Assert(_entries != null, "expected entries to be != null");
+                var hashCode = (uint)key.GetHashCode();
+                var i = GetBucket(hashCode);
+                var entriesLength = _entries.Length;
+                ref var entriesRef = ref _entries[0];
+                uint collisionCount = 0;
+
+                // ValueType: Devirtualize with EqualityComparer<LuaValue>.Default intrinsic
+                i--; // Value in _buckets is 1-based; subtract 1 from i. We do it here so it fuses with the following conditional.
+                do
                 {
                 {
-                    uint hashCode = (uint)key.GetHashCode();
-                    int i = GetBucket(hashCode);
-                    Entry[]? entries = _entries;
-                    uint collisionCount = 0;
-
-                    // ValueType: Devirtualize with EqualityComparer<LuaValue>.Default intrinsic
-                    i--; // Value in _buckets is 1-based; subtract 1 from i. We do it here so it fuses with the following conditional.
-                    do
+                    // Should be a while loop https://github.com/dotnet/runtime/issues/9422
+                    // Test in if to drop range check for following array access
+                    if ((uint)i >= (uint)entriesLength)
                     {
                     {
-                        // Should be a while loop https://github.com/dotnet/runtime/issues/9422
-                        // Test in if to drop range check for following array access
-                        if ((uint)i >= (uint)entries.Length)
-                        {
-                            goto ReturnNotFound;
-                        }
+                        goto ReturnNotFound;
+                    }
 
 
-                        entry = ref entries[i];
-                        if (entry.hashCode == hashCode && entry.key.Equals(key))
+                    entry = ref Unsafe.Add(ref entriesRef, i);
+                    if (entry.hashCode == hashCode && entry.keyType == key.Type &&
+                        key.Type switch
                         {
                         {
-                            index = i;
-                            goto ReturnFound;
-                        }
+                            LuaValueType.String => Unsafe.As<string>(entry.keyObject) == key.UnsafeReadString(),
+                            LuaValueType.Number or LuaValueType.Boolean => entry.keyNumber == key.UnsafeReadDouble(),
+                            _ => entry.keyObject == key.UnsafeReadObject()
+                        })
+                    {
+                        index = i;
+                        goto ReturnFound;
+                    }
 
 
-                        i = entry.next;
+                    i = entry.next;
 
 
-                        collisionCount++;
-                    } while (collisionCount <= (uint)entries.Length);
+                    collisionCount++;
+                } while (collisionCount <= (uint)entriesLength);
 
 
-                    // The chain of entries forms a loop; which means a concurrent update has happened.
-                    // Break out of the loop and throw, rather than looping forever.
-                    goto ConcurrentOperation;
-                }
+                // The chain of entries forms a loop; which means a concurrent update has happened.
+                // Break out of the loop and throw, rather than looping forever.
+                goto ConcurrentOperation;
             }
             }
-
-            goto ReturnNotFound;
-
-        ConcurrentOperation:
-            ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
-        ReturnFound:
-            ref LuaValue value = ref entry.value;
-        Return:
-            return ref value;
-        ReturnNotFound:
-            value = ref Unsafe.NullRef<LuaValue>();
-            goto Return;
         }
         }
 
 
-        private void Initialize(int capacity)
+        goto ReturnNotFound;
+
+    ConcurrentOperation:
+        ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
+    ReturnFound:
+        ref var value = ref entry.value;
+    Return:
+        return ref value;
+    ReturnNotFound:
+        value = ref Unsafe.NullRef<LuaValue>();
+        goto Return;
+    }
+
+    void Initialize(int capacity)
+    {
+        var newSize = 8;
+        while (newSize < capacity)
         {
         {
-            var newSize = 8;
-            while (newSize < capacity)
-            {
-                newSize *= 2;
-            }
+            newSize *= 2;
+        }
 
 
-            int size = newSize;
-            int[] buckets = new int[size];
-            Entry[] entries = new Entry[size];
+        var size = newSize;
+        var buckets = new int[size];
+        var entries = new Entry[size];
 
 
-            // Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
-            _freeList = -1;
-            _buckets = buckets;
-            _entries = entries;
-        }
+        // Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
+        _freeList = -1;
+        _buckets = buckets;
+        _entries = entries;
+    }
 
 
-        private void Insert(LuaValue key, LuaValue value)
+    void Insert(LuaValue key, LuaValue value)
+    {
+        if (value.Type is LuaValueType.Nil)
         {
         {
-            if (value.Type is LuaValueType.Nil)
-            {
-                _nilCount++;
-            }
+            _nilCount++;
+        }
 
 
-            if (_buckets == null)
-            {
-                Initialize(0);
-            }
+        if (_buckets == null)
+        {
+            Initialize(0);
+        }
 
 
-            Debug.Assert(_buckets != null);
+        Debug.Assert(_buckets != null);
 
 
-            Entry[]? entries = _entries;
-            Debug.Assert(entries != null, "expected entries to be non-null");
+        var entries = _entries;
+        Debug.Assert(entries != null, "expected entries to be non-null");
 
 
 
 
-            uint hashCode = (uint)key.GetHashCode();
+        var hashCode = (uint)key.GetHashCode();
 
 
-            uint collisionCount = 0;
-            ref int bucket = ref GetBucket(hashCode);
-            int i = bucket - 1; // Value in _buckets is 1-based
+        uint collisionCount = 0;
+        ref var bucket = ref GetBucket(hashCode);
+        var i = bucket - 1; // Value in _buckets is 1-based
 
 
+        {
+            ref var entry = ref Unsafe.NullRef<Entry>();
+            while ((uint)i < (uint)entries.Length)
             {
             {
-                ref Entry entry = ref Unsafe.NullRef<Entry>();
-                while ((uint)i < (uint)entries.Length)
+                entry = ref entries[i];
+                if (entry.hashCode == hashCode && entry.keyType == key.Type &&
+                    key.Type switch
+                    {
+                        LuaValueType.Number or LuaValueType.Boolean => entry.keyNumber == key.UnsafeReadDouble(),
+                        LuaValueType.String => Unsafe.As<string>(entry.keyObject) == key.UnsafeReadString(),
+                        _ => entry.keyObject == key.UnsafeReadObject()
+                    })
                 {
                 {
-                    entry = ref entries[i];
-                    if (entry.hashCode == hashCode && entry.key.Equals(key))
+                    if (entry.value.Type is LuaValueType.Nil)
                     {
                     {
-                        if (entry.value.Type is LuaValueType.Nil)
-                        {
-                            _nilCount--;
-                        }
-
-                        entry.value = value;
-                        return;
+                        _nilCount--;
                     }
                     }
 
 
-                    i = entry.next;
-
-                    collisionCount++;
-                    if (collisionCount > (uint)entries.Length)
-                    {
-                        // The chain of entries forms a loop; which means a concurrent update has happened.
-                        // Break out of the loop and throw, rather than looping forever.
-                        ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
-                    }
+                    entry.value = value;
+                    return;
                 }
                 }
-            }
 
 
-            int index;
-            if (_freeCount > 0)
-            {
-                index = _freeList;
-                Debug.Assert((StartOfFreeList - entries[_freeList].next) >= -1, "shouldn't overflow because `next` cannot underflow");
-                _freeList = StartOfFreeList - entries[_freeList].next;
-                _freeCount--;
-            }
-            else
-            {
-                int count = _count;
-                if (count == entries.Length)
+                i = entry.next;
+
+                collisionCount++;
+                if (collisionCount > (uint)entries.Length)
                 {
                 {
-                    Resize();
-                    bucket = ref GetBucket(hashCode);
+                    // The chain of entries forms a loop; which means a concurrent update has happened.
+                    // Break out of the loop and throw, rather than looping forever.
+                    ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
                 }
                 }
-
-                index = count;
-                _count = count + 1;
-                entries = _entries;
             }
             }
+        }
 
 
+        int index;
+        if (_freeCount > 0)
+        {
+            index = _freeList;
+            Debug.Assert(StartOfFreeList - entries[_freeList].next >= -1, "shouldn't overflow because `next` cannot underflow");
+            _freeList = StartOfFreeList - entries[_freeList].next;
+            _freeCount--;
+        }
+        else
+        {
+            var count = _count;
+            if (count == entries.Length)
             {
             {
-                ref Entry entry = ref entries![index];
-                entry.hashCode = hashCode;
-                entry.next = bucket - 1; // Value in _buckets is 1-based
-                entry.key = key;
-                entry.value = value;
-                bucket = index + 1; // Value in _buckets is 1-based
-                _version++;
+                Resize();
+                bucket = ref GetBucket(hashCode);
             }
             }
+
+            index = count;
+            _count = count + 1;
+            entries = _entries;
         }
         }
 
 
+        {
+            ref var entry = ref entries![index];
+            entry.hashCode = hashCode;
+            entry.next = bucket - 1; // Value in _buckets is 1-based
+            entry.keyType = key.Type;
+            entry.keyObject = key.UnsafeReadObject();
+            entry.keyNumber = key.UnsafeReadDouble();
+            entry.value = value;
+            bucket = index + 1; // Value in _buckets is 1-based
+            _version++;
+        }
+    }
 
 
-        private void Resize() => Resize(_entries!.Length * 2);
 
 
-        private void Resize(int newSize)
-        {
-            // Value types never rehash
-            Debug.Assert(_entries != null, "_entries should be non-null");
-            Debug.Assert(newSize >= _entries.Length);
+    void Resize()
+    {
+        Resize(_entries!.Length * 2);
+    }
+
+    void Resize(int newSize)
+    {
+        // Value types never rehash
+        Debug.Assert(_entries != null, "_entries should be non-null");
+        Debug.Assert(newSize >= _entries.Length);
 
 
-            Entry[] entries = new Entry[newSize];
+        var entries = new Entry[newSize];
 
 
-            int count = _count;
-            Array.Copy(_entries, entries, count);
+        var count = _count;
+        Array.Copy(_entries, entries, count);
 
 
 
 
-            // Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
-            _buckets = new int[newSize];
+        // Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
+        _buckets = new int[newSize];
 
 
-            for (int i = 0; i < count; i++)
+        for (var i = 0; i < count; i++)
+        {
+            if (entries[i].next >= -1)
             {
             {
-                if (entries[i].next >= -1)
-                {
-                    ref int bucket = ref GetBucket(entries[i].hashCode);
-                    entries[i].next = bucket - 1; // Value in _buckets is 1-based
-                    bucket = i + 1;
-                }
+                ref var bucket = ref GetBucket(entries[i].hashCode);
+                entries[i].next = bucket - 1; // Value in _buckets is 1-based
+                bucket = i + 1;
             }
             }
-
-            _entries = entries;
         }
         }
 
 
-        public bool Remove(LuaValue key)
+        _entries = entries;
+    }
+
+    public bool Remove(LuaValue key)
+    {
+        // The overload Remove(LuaValue key, out LuaValue value) is a copy of this method with one additional
+        // statement to copy the value for entry being removed into the output parameter.
+        // Code has been intentionally duplicated for performance reasons.
+
+        if (_buckets != null)
         {
         {
-            // The overload Remove(LuaValue key, out LuaValue value) is a copy of this method with one additional
-            // statement to copy the value for entry being removed into the output parameter.
-            // Code has been intentionally duplicated for performance reasons.
+            Debug.Assert(_entries != null, "entries should be non-null");
+            uint collisionCount = 0;
 
 
-            if (_buckets != null)
-            {
-                Debug.Assert(_entries != null, "entries should be non-null");
-                uint collisionCount = 0;
 
 
+            var hashCode = (uint)key.GetHashCode();
 
 
-                uint hashCode = (uint)key.GetHashCode();
+            ref var bucket = ref GetBucket(hashCode);
+            var entries = _entries;
+            var last = -1;
+            var i = bucket - 1; // Value in buckets is 1-based
+            while (i >= 0)
+            {
+                ref var entry = ref entries[i];
 
 
-                ref int bucket = ref GetBucket(hashCode);
-                Entry[]? entries = _entries;
-                int last = -1;
-                int i = bucket - 1; // Value in buckets is 1-based
-                while (i >= 0)
+                if (entry.hashCode == hashCode && entry.keyType == key.Type &&
+                    key.Type switch
+                    {
+                        LuaValueType.Number or LuaValueType.Boolean => entry.keyNumber == key.UnsafeReadDouble(),
+                        LuaValueType.String => Unsafe.As<string>(entry.keyObject) == key.UnsafeReadString(),
+                        _ => entry.keyObject == key.UnsafeReadObject()
+                    })
                 {
                 {
-                    ref Entry entry = ref entries[i];
-
-                    if (entry.hashCode == hashCode && entry.key.Equals(key))
+                    if (last < 0)
                     {
                     {
-                        if (last < 0)
-                        {
-                            bucket = entry.next + 1; // Value in buckets is 1-based
-                        }
-                        else
-                        {
-                            entries[last].next = entry.next;
-                        }
+                        bucket = entry.next + 1; // Value in buckets is 1-based
+                    }
+                    else
+                    {
+                        entries[last].next = entry.next;
+                    }
 
 
-                        Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
-                        entry.next = StartOfFreeList - _freeList;
+                    Debug.Assert(StartOfFreeList - _freeList < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
+                    entry.next = StartOfFreeList - _freeList;
 
 
-                        if (entry.value.Type is LuaValueType.Nil)
-                        {
-                            _nilCount--;
-                        }
+                    if (entry.value.Type is LuaValueType.Nil)
+                    {
+                        _nilCount--;
+                    }
 
 
-                        entry.key = default;
-                        entry.value = default;
+                    entry.keyType = default;
+                    entry.keyObject = null!;
+                    entry.value = default;
 
 
-                        _freeList = i;
-                        _freeCount++;
-                        return true;
-                    }
+                    _freeList = i;
+                    _freeCount++;
+                    return true;
+                }
 
 
-                    last = i;
-                    i = entry.next;
+                last = i;
+                i = entry.next;
 
 
-                    collisionCount++;
-                    if (collisionCount > (uint)entries.Length)
-                    {
-                        // The chain of entries forms a loop; which means a concurrent update has happened.
-                        // Break out of the loop and throw, rather than looping forever.
-                        ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
-                    }
+                collisionCount++;
+                if (collisionCount > (uint)entries.Length)
+                {
+                    // The chain of entries forms a loop; which means a concurrent update has happened.
+                    // Break out of the loop and throw, rather than looping forever.
+                    ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
                 }
                 }
             }
             }
-
-            return false;
         }
         }
 
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public bool TryGetValue(LuaValue key, out LuaValue value)
-        {
-            ref LuaValue valRef = ref FindValue(key, out _);
-            if (!Unsafe.IsNullRef(ref valRef))
-            {
-                value = valRef;
-                return true;
-            }
+        return false;
+    }
 
 
-            value = default;
-            return false;
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public bool TryGetValue(LuaValue key, out LuaValue value)
+    {
+        ref var valRef = ref FindValue(key, out _);
+        if (!Unsafe.IsNullRef(ref valRef))
+        {
+            value = valRef;
+            return true;
         }
         }
 
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public bool TryGetNext(LuaValue key, out KeyValuePair<LuaValue, LuaValue> pair)
+        value = default;
+        return false;
+    }
+
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public bool TryGetNext(LuaValue key, out KeyValuePair<LuaValue, LuaValue> pair)
+    {
+        ref var valRef = ref FindValue(key, out var index);
+        if (!Unsafe.IsNullRef(ref valRef))
         {
         {
-            ref LuaValue valRef = ref FindValue(key, out var index);
-            if (!Unsafe.IsNullRef(ref valRef))
+            var entries = _entries!;
+            while (++index < _count)
             {
             {
-                Entry[] entries = _entries!;
-                while (++index < _count)
+                ref var entry = ref entries[index];
+                if (entry is { next: >= -1, value.Type: not LuaValueType.Nil })
                 {
                 {
-                    ref Entry entry = ref entries[index];
-                    if (entry is { next: >= -1, value.Type: not LuaValueType.Nil })
-                    {
-                        pair = new(entry.key, entry.value);
-                        return true;
-                    }
+                    pair = new(new(entry.keyType, entry.keyNumber, entry.keyObject), entry.value);
+                    return true;
                 }
                 }
             }
             }
-
-            pair = default;
-            return false;
         }
         }
 
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        private ref int GetBucket(uint hashCode)
-        {
-            int[] buckets = _buckets!;
-            return ref buckets[hashCode & (buckets.Length - 1)];
-        }
+        pair = default;
+        return false;
+    }
 
 
-        private struct Entry
-        {
-            public uint hashCode;
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    ref int GetBucket(uint hashCode)
+    {
+        var buckets = _buckets!;
+        return ref buckets[hashCode & (buckets.Length - 1)];
+    }
 
 
-            /// <summary>
-            /// 0-based index of next entry in chain: -1 means end of chain
-            /// also encodes whether this entry _itself_ is part of the free list by changing sign and subtracting 3,
-            /// so -2 means end of free list, -3 means index 0 but on free list, -4 means index 1 but on free list, etc.
-            /// </summary>
-            public int next;
+    struct Entry
+    {
+        public uint hashCode;
+        public LuaValueType keyType;
+        public object? keyObject;
+        public double keyNumber;
+
+        /// <summary>
+        /// 0-based index of next entry in chain: -1 means end of chain
+        /// also encodes whether this entry _itself_ is part of the free list by changing sign and subtracting 3,
+        /// so -2 means end of free list, -3 means index 0 but on free list, -4 means index 1 but on free list, etc.
+        /// </summary>
+        public int next;
+
+        public LuaValue value; // Value of entry
+    }
 
 
-            public LuaValue key; // Key of entry
-            public LuaValue value; // Value of entry
-        }
+    internal int Version => _version;
 
 
-        internal int Version => _version;
+    internal static bool MoveNext(LuaValueDictionary dictionary, int version, ref int index, out KeyValuePair<LuaValue, LuaValue> current)
+    {
+        if (version != dictionary._version)
+        {
+            ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
+        }
 
 
-        internal static bool MoveNext(LuaValueDictionary dictionary, int version, ref int index, out KeyValuePair<LuaValue, LuaValue> current)
+    SearchNext:
+        // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
+        // dictionary.count+1 could be negative if dictionary.count is int.MaxValue
+        while ((uint)index < (uint)dictionary._count)
         {
         {
-            if (version != dictionary._version)
-            {
-                ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
-            }
+            ref var entry = ref dictionary._entries![index++];
 
 
-        SearchNext:
-            // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
-            // dictionary.count+1 could be negative if dictionary.count is int.MaxValue
-            while ((uint)index < (uint)dictionary._count)
+            if (entry.next >= -1)
             {
             {
-                ref Entry entry = ref dictionary._entries![index++];
-
-                if (entry.next >= -1)
+                if (entry.value.Type is LuaValueType.Nil)
                 {
                 {
-                    if (entry.value.Type is LuaValueType.Nil)
-                    {
-                        goto SearchNext;
-                    }
-
-                    current = new KeyValuePair<LuaValue, LuaValue>(entry.key, entry.value);
-                    return true;
+                    goto SearchNext;
                 }
                 }
-            }
 
 
-            index = dictionary._count + 1;
-            current = default;
-            return false;
+                current = new(new(entry.keyType, entry.keyNumber, entry.keyObject), entry.value);
+                return true;
+            }
         }
         }
 
 
-        public struct Enumerator
-        {
-            private readonly LuaValueDictionary dictionary;
-            private readonly int _version;
-            private int _index;
-            private KeyValuePair<LuaValue, LuaValue> _current;
+        index = dictionary._count + 1;
+        current = default;
+        return false;
+    }
 
 
-            internal Enumerator(LuaValueDictionary dictionary)
-            {
-                this.dictionary = dictionary;
-                _version = dictionary._version;
-                _index = 0;
-                _current = default;
-            }
+    public struct Enumerator
+    {
+        readonly LuaValueDictionary dictionary;
+        readonly int _version;
+        int _index;
+        KeyValuePair<LuaValue, LuaValue> _current;
 
 
-            public bool MoveNext() => LuaValueDictionary.MoveNext(dictionary, _version, ref _index, out _current);
+        internal Enumerator(LuaValueDictionary dictionary)
+        {
+            this.dictionary = dictionary;
+            _version = dictionary._version;
+            _index = 0;
+            _current = default;
+        }
 
 
-            public KeyValuePair<LuaValue, LuaValue> Current => _current;
+        public bool MoveNext()
+        {
+            return LuaValueDictionary.MoveNext(dictionary, _version, ref _index, out _current);
         }
         }
 
 
-        static class ThrowHelper
+        public KeyValuePair<LuaValue, LuaValue> Current => _current;
+    }
+
+    static class ThrowHelper
+    {
+        public static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported()
         {
         {
-            public static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported()
-            {
-                throw new InvalidOperationException("Concurrent operations are not supported");
-            }
+            throw new InvalidOperationException("Concurrent operations are not supported");
+        }
 
 
-            public static void ThrowArgumentOutOfRangeException(string paramName)
-            {
-                throw new ArgumentOutOfRangeException(paramName);
-            }
+        public static void ThrowArgumentOutOfRangeException(string paramName)
+        {
+            throw new ArgumentOutOfRangeException(paramName);
+        }
 
 
-            public static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion()
-            {
-                throw new InvalidOperationException("Collection was modified after the enumerator was instantiated.");
-            }
+        public static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion()
+        {
+            throw new InvalidOperationException("Collection was modified after the enumerator was instantiated.");
         }
         }
     }
     }
 }
 }

+ 9 - 3
src/Lua/Internal/MathEx.cs

@@ -5,7 +5,7 @@ using System.Numerics;
 
 
 namespace Lua;
 namespace Lua;
 
 
-internal static class MathEx
+static class MathEx
 {
 {
     const ulong PositiveInfinityBits = 0x7FF0_0000_0000_0000;
     const ulong PositiveInfinityBits = 0x7FF0_0000_0000_0000;
 
 
@@ -23,7 +23,7 @@ internal static class MathEx
     public static unsafe bool IsFinite(double d)
     public static unsafe bool IsFinite(double d)
     {
     {
 #if NET6_0_OR_GREATER
 #if NET6_0_OR_GREATER
-        ulong bits = BitConverter.DoubleToUInt64Bits(d);
+        var bits = BitConverter.DoubleToUInt64Bits(d);
 #else
 #else
         ulong bits = BitCast<double, ulong>(d);
         ulong bits = BitCast<double, ulong>(d);
 #endif
 #endif
@@ -65,7 +65,9 @@ internal static class MathEx
         var e = 0;
         var e = 0;
 
 
         if (exp == 0x7ff || d == 0D)
         if (exp == 0x7ff || d == 0D)
+        {
             d += d;
             d += d;
+        }
         else
         else
         {
         {
             // Not zero and finite.
             // Not zero and finite.
@@ -96,7 +98,11 @@ internal static class MathEx
     public static int NextPowerOfTwo(int x)
     public static int NextPowerOfTwo(int x)
     {
     {
 #if NET6_0_OR_GREATER
 #if NET6_0_OR_GREATER
-        if (x <= 0) return 0;
+        if (x <= 0)
+        {
+            return 0;
+        }
+
         return (int)BitOperations.RoundUpToPowerOf2((uint)x);
         return (int)BitOperations.RoundUpToPowerOf2((uint)x);
 #else
 #else
         if (x <= 0) return 0;
         if (x <= 0) return 0;

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

@@ -3,7 +3,7 @@ using System.Runtime.InteropServices;
 
 
 namespace Lua.Internal;
 namespace Lua.Internal;
 
 
-internal static class MemoryMarshalEx
+static class MemoryMarshalEx
 {
 {
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public static ref T UnsafeElementAt<T>(T[] array, int index)
     public static ref T UnsafeElementAt<T>(T[] array, int index)

+ 2 - 2
src/Lua/Internal/Pool.cs

@@ -3,14 +3,14 @@ using System.Runtime.InteropServices;
 
 
 namespace Lua.Internal;
 namespace Lua.Internal;
 
 
-internal interface IPoolNode<T>
+interface IPoolNode<T>
 {
 {
     ref T? NextNode { get; }
     ref T? NextNode { get; }
 }
 }
 
 
 // mutable struct, don't mark readonly.
 // mutable struct, don't mark readonly.
 [StructLayout(LayoutKind.Auto)]
 [StructLayout(LayoutKind.Auto)]
-internal struct LinkedPool<T>
+struct LinkedPool<T>
     where T : class, IPoolNode<T>
     where T : class, IPoolNode<T>
 {
 {
     int gate;
     int gate;

+ 17 - 9
src/Lua/Internal/PooledList.cs

@@ -3,7 +3,7 @@ using System.Runtime.CompilerServices;
 
 
 namespace Lua.Internal;
 namespace Lua.Internal;
 
 
-internal struct PooledList<T> : IDisposable
+struct PooledList<T> : IDisposable
 {
 {
     T[]? buffer;
     T[]? buffer;
     int tail;
     int tail;
@@ -14,7 +14,9 @@ internal struct PooledList<T> : IDisposable
     }
     }
 
 
     public bool IsDisposed => tail == -1;
     public bool IsDisposed => tail == -1;
+
     public int Count => tail;
     public int Count => tail;
+
     public int Length => tail;
     public int Length => tail;
 
 
     public void Add(in T item)
     public void Add(in T item)
@@ -67,7 +69,10 @@ internal struct PooledList<T> : IDisposable
     {
     {
         ThrowIfDisposed();
         ThrowIfDisposed();
 
 
-        if (count > tail) throw new ArgumentOutOfRangeException(nameof(count));
+        if (count > tail)
+        {
+            throw new ArgumentOutOfRangeException(nameof(count));
+        }
 
 
         tail = count;
         tail = count;
     }
     }
@@ -76,7 +81,10 @@ internal struct PooledList<T> : IDisposable
     {
     {
         ThrowIfDisposed();
         ThrowIfDisposed();
 
 
-        if (count > tail) throw new ArgumentOutOfRangeException(nameof(count));
+        if (count > tail)
+        {
+            throw new ArgumentOutOfRangeException(nameof(count));
+        }
 
 
         tail -= count;
         tail -= count;
     }
     }
@@ -109,21 +117,21 @@ internal struct PooledList<T> : IDisposable
     public T this[int index]
     public T this[int index]
     {
     {
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        get
-        {
-            return AsSpan()[index];
-        }
+        get => AsSpan()[index];
     }
     }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public ReadOnlySpan<T> AsSpan()
     public ReadOnlySpan<T> AsSpan()
     {
     {
-        return new ReadOnlySpan<T>(buffer, 0, tail);
+        return new(buffer, 0, tail);
     }
     }
 
 
     void ThrowIfDisposed()
     void ThrowIfDisposed()
     {
     {
-        if (tail == -1) ThrowDisposedException();
+        if (tail == -1)
+        {
+            ThrowDisposedException();
+        }
     }
     }
 
 
     void ThrowDisposedException()
     void ThrowDisposedException()

+ 28 - 8
src/Lua/Internal/ReversedStack.cs

@@ -1,6 +1,6 @@
 namespace Lua.Internal;
 namespace Lua.Internal;
 
 
-internal sealed class ReversedStack<T>(int capacity = 16)
+sealed class ReversedStack<T>(int capacity = 16)
 {
 {
     T[] buffer = new T[capacity];
     T[] buffer = new T[capacity];
     int tail = capacity;
     int tail = capacity;
@@ -20,7 +20,11 @@ internal sealed class ReversedStack<T>(int capacity = 16)
 
 
     public void Push(ReadOnlySpan<T> elements)
     public void Push(ReadOnlySpan<T> elements)
     {
     {
-        if (elements.Length == 0) return;
+        if (elements.Length == 0)
+        {
+            return;
+        }
+
         EnsureAdditionalCapacity(elements.Length);
         EnsureAdditionalCapacity(elements.Length);
         tail -= elements.Length;
         tail -= elements.Length;
         elements.CopyTo(buffer.AsSpan(tail));
         elements.CopyTo(buffer.AsSpan(tail));
@@ -33,7 +37,11 @@ internal sealed class ReversedStack<T>(int capacity = 16)
             ThrowEmpty();
             ThrowEmpty();
         }
         }
 
 
-        static void ThrowEmpty() => throw new InvalidOperationException("Cannot pop an empty stack");
+        static void ThrowEmpty()
+        {
+            throw new InvalidOperationException("Cannot pop an empty stack");
+        }
+
         return buffer[tail++];
         return buffer[tail++];
     }
     }
 
 
@@ -44,7 +52,11 @@ internal sealed class ReversedStack<T>(int capacity = 16)
             ThrowEmpty();
             ThrowEmpty();
         }
         }
 
 
-        static void ThrowEmpty() => throw new InvalidOperationException("Cannot pop more elements than exist in the stack");
+        static void ThrowEmpty()
+        {
+            throw new InvalidOperationException("Cannot pop more elements than exist in the stack");
+        }
+
         tail += count;
         tail += count;
     }
     }
 
 
@@ -73,25 +85,33 @@ internal sealed class ReversedStack<T>(int capacity = 16)
             ThrowEmpty();
             ThrowEmpty();
         }
         }
 
 
-        static void ThrowEmpty() => throw new InvalidOperationException("Cannot peek an empty stack");
+        static void ThrowEmpty()
+        {
+            throw new InvalidOperationException("Cannot peek an empty stack");
+        }
+
         return buffer[tail];
         return buffer[tail];
     }
     }
 
 
 
 
     void EnsureAdditionalCapacity(int required)
     void EnsureAdditionalCapacity(int required)
     {
     {
-        if (tail >= required) return;
+        if (tail >= required)
+        {
+            return;
+        }
+
         Resize(required - tail + buffer.Length);
         Resize(required - tail + buffer.Length);
 
 
         void Resize(int requiredCapacity)
         void Resize(int requiredCapacity)
         {
         {
-            int newCapacity = buffer.Length * 2;
+            var newCapacity = buffer.Length * 2;
             while (newCapacity < requiredCapacity)
             while (newCapacity < requiredCapacity)
             {
             {
                 newCapacity *= 2;
                 newCapacity *= 2;
             }
             }
 
 
-            T[] newBuffer = new T[newCapacity];
+            var newBuffer = new T[newCapacity];
             AsSpan().CopyTo(newBuffer.AsSpan(newCapacity - buffer.Length));
             AsSpan().CopyTo(newBuffer.AsSpan(newCapacity - buffer.Length));
             tail = newCapacity - (buffer.Length - tail);
             tail = newCapacity - (buffer.Length - tail);
             buffer = newBuffer;
             buffer = newBuffer;

+ 33 - 15
src/Lua/Internal/StringHelper.cs

@@ -6,7 +6,7 @@ using System.Text.RegularExpressions;
 
 
 namespace Lua.Internal;
 namespace Lua.Internal;
 
 
-internal static class StringHelper
+static class StringHelper
 {
 {
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public static ReadOnlySpan<char> Slice(string s, int i, int j)
     public static ReadOnlySpan<char> Slice(string s, int i, int j)
@@ -22,8 +22,8 @@ internal static class StringHelper
 
 
     public static bool TryFromStringLiteral(ReadOnlySpan<char> literal, [NotNullWhen(true)] out string? result)
     public static bool TryFromStringLiteral(ReadOnlySpan<char> literal, [NotNullWhen(true)] out string? result)
     {
     {
-        var builder = new ValueStringBuilder(literal.Length);
-        for (int i = 0; i < literal.Length; i++)
+        ValueStringBuilder builder = new(literal.Length);
+        for (var i = 0; i < literal.Length; i++)
         {
         {
             var c = literal[i];
             var c = literal[i];
             if (c is '\\' && i < literal.Length - 1)
             if (c is '\\' && i < literal.Length - 1)
@@ -93,12 +93,19 @@ internal static class StringHelper
                         if (IsDigit(c))
                         if (IsDigit(c))
                         {
                         {
                             var start = i;
                             var start = i;
-                            for (int j = 0; j < 2; j++)
+                            for (var j = 0; j < 2; j++)
                             {
                             {
                                 i++;
                                 i++;
-                                if (i >= literal.Length) break;
+                                if (i >= literal.Length)
+                                {
+                                    break;
+                                }
+
                                 c = literal[i];
                                 c = literal[i];
-                                if (!IsDigit(c)) break;
+                                if (!IsDigit(c))
+                                {
+                                    break;
+                                }
                             }
                             }
 
 
                             builder.Append((char)int.Parse(literal[start..i], NumberStyles.HexNumber));
                             builder.Append((char)int.Parse(literal[start..i], NumberStyles.HexNumber));
@@ -115,12 +122,19 @@ internal static class StringHelper
                         if (IsNumber(c))
                         if (IsNumber(c))
                         {
                         {
                             var start = i;
                             var start = i;
-                            for (int j = 0; j < 3; j++)
+                            for (var j = 0; j < 3; j++)
                             {
                             {
                                 i++;
                                 i++;
-                                if (i >= literal.Length) break;
+                                if (i >= literal.Length)
+                                {
+                                    break;
+                                }
+
                                 c = literal[i];
                                 c = literal[i];
-                                if (!IsNumber(c)) break;
+                                if (!IsNumber(c))
+                                {
+                                    break;
+                                }
                             }
                             }
 
 
                             builder.Append((char)int.Parse(literal[start..i]));
                             builder.Append((char)int.Parse(literal[start..i]));
@@ -147,9 +161,9 @@ internal static class StringHelper
 
 
     public static string Escape(ReadOnlySpan<char> str)
     public static string Escape(ReadOnlySpan<char> str)
     {
     {
-        var builder = new ValueStringBuilder(str.Length);
+        ValueStringBuilder builder = new(str.Length);
 
 
-        for (int i = 0; i < str.Length; i++)
+        for (var i = 0; i < str.Length; i++)
         {
         {
             var c = str[i];
             var c = str[i];
 
 
@@ -196,7 +210,7 @@ internal static class StringHelper
 
 
     public static Regex ToRegex(ReadOnlySpan<char> pattern)
     public static Regex ToRegex(ReadOnlySpan<char> pattern)
     {
     {
-        var builder = new ValueStringBuilder();
+        ValueStringBuilder builder = new();
         var isEscapeSequence = false;
         var isEscapeSequence = false;
         var isInSet = false;
         var isInSet = false;
 
 
@@ -300,7 +314,7 @@ internal static class StringHelper
                             }
                             }
                             else
                             else
                             {
                             {
-                                throw new Exception(); // TODO: add message
+                                throw new(); // TODO: add message
                             }
                             }
 
 
                             break;
                             break;
@@ -323,7 +337,11 @@ internal static class StringHelper
             }
             }
             else if (isInSet)
             else if (isInSet)
             {
             {
-                if (c == ']') isInSet = false;
+                if (c == ']')
+                {
+                    isInSet = false;
+                }
+
                 builder.Append(c);
                 builder.Append(c);
             }
             }
             else if (c == '-')
             else if (c == '-')
@@ -349,7 +367,7 @@ internal static class StringHelper
             }
             }
         }
         }
 
 
-        return new Regex(builder.ToString());
+        return new(builder.ToString());
     }
     }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]

+ 96 - 46
src/Lua/Internal/Utf8Reader.cs

@@ -3,7 +3,7 @@ using System.Text;
 
 
 namespace Lua.Internal;
 namespace Lua.Internal;
 
 
-internal sealed class Utf8Reader
+sealed class Utf8Reader
 {
 {
     [ThreadStatic]
     [ThreadStatic]
     static byte[]? scratchBuffer;
     static byte[]? scratchBuffer;
@@ -11,9 +11,9 @@ internal sealed class Utf8Reader
     [ThreadStatic]
     [ThreadStatic]
     internal static bool scratchBufferUsed;
     internal static bool scratchBufferUsed;
 
 
-    private readonly byte[] buffer;
-    private int bufPos, bufLen;
-    private Decoder? decoder;
+    readonly byte[] buffer;
+    int bufPos, bufLen;
+    Decoder? decoder;
 
 
     const int ThreadStaticBufferSize = 1024;
     const int ThreadStaticBufferSize = 1024;
 
 
@@ -46,23 +46,25 @@ internal sealed class Utf8Reader
                     bufLen = stream.Read(buffer, 0, buffer.Length);
                     bufLen = stream.Read(buffer, 0, buffer.Length);
                     bufPos = 0;
                     bufPos = 0;
                     if (bufLen == 0)
                     if (bufLen == 0)
+                    {
                         break; // EOF
                         break; // EOF
+                    }
                 }
                 }
 
 
-                var span = new Span<byte>(buffer, bufPos, bufLen - bufPos);
-                int idx = span.IndexOfAny((byte)'\r', (byte)'\n');
+                Span<byte> span = new(buffer, bufPos, bufLen - bufPos);
+                var idx = span.IndexOfAny((byte)'\r', (byte)'\n');
 
 
                 if (idx >= 0)
                 if (idx >= 0)
                 {
                 {
                     // Add the line content (before the newline)
                     // Add the line content (before the newline)
                     AppendToBuffer(ref resultBuffer, span[..idx], ref lineLen);
                     AppendToBuffer(ref resultBuffer, span[..idx], ref lineLen);
 
 
-                    byte nl = span[idx];
+                    var nl = span[idx];
                     var eolStart = bufPos + idx;
                     var eolStart = bufPos + idx;
                     bufPos += idx + 1;
                     bufPos += idx + 1;
 
 
                     // Handle CRLF - check if we have \r\n
                     // Handle CRLF - check if we have \r\n
-                    bool isCRLF = false;
+                    var isCRLF = false;
                     if (nl == (byte)'\r' && bufPos < bufLen && buffer[bufPos] == (byte)'\n')
                     if (nl == (byte)'\r' && bufPos < bufLen && buffer[bufPos] == (byte)'\n')
                     {
                     {
                         isCRLF = true;
                         isCRLF = true;
@@ -75,12 +77,12 @@ internal sealed class Utf8Reader
                         if (isCRLF)
                         if (isCRLF)
                         {
                         {
                             // Add \r\n
                             // Add \r\n
-                            AppendToBuffer(ref resultBuffer, new ReadOnlySpan<byte>(new byte[] { (byte)'\r', (byte)'\n' }), ref lineLen);
+                            AppendToBuffer(ref resultBuffer, new(new byte[] { (byte)'\r', (byte)'\n' }), ref lineLen);
                         }
                         }
                         else
                         else
                         {
                         {
                             // Add just the single newline character (\r or \n)
                             // Add just the single newline character (\r or \n)
-                            AppendToBuffer(ref resultBuffer, new ReadOnlySpan<byte>(new byte[] { nl }), ref lineLen);
+                            AppendToBuffer(ref resultBuffer, new(new byte[] { nl }), ref lineLen);
                         }
                         }
                     }
                     }
 
 
@@ -95,7 +97,10 @@ internal sealed class Utf8Reader
             }
             }
 
 
             if (lineLen == 0)
             if (lineLen == 0)
+            {
                 return null;
                 return null;
+            }
+
             return Encoding.UTF8.GetString(resultBuffer, 0, lineLen);
             return Encoding.UTF8.GetString(resultBuffer, 0, lineLen);
         }
         }
         finally
         finally
@@ -118,16 +123,21 @@ internal sealed class Utf8Reader
 
 
                     bufPos = 0;
                     bufPos = 0;
                     if (bufLen == 0)
                     if (bufLen == 0)
+                    {
                         break; // EOF
                         break; // EOF
+                    }
                 }
                 }
 
 
-                var span = new Span<byte>(buffer, bufPos, bufLen - bufPos);
+                Span<byte> span = new(buffer, bufPos, bufLen - bufPos);
                 AppendToBuffer(ref resultBuffer, span, ref len);
                 AppendToBuffer(ref resultBuffer, span, ref len);
                 bufPos = bufLen;
                 bufPos = bufLen;
             }
             }
 
 
             if (len == 0)
             if (len == 0)
+            {
                 return "";
                 return "";
+            }
+
             return Encoding.UTF8.GetString(resultBuffer, 0, len);
             return Encoding.UTF8.GetString(resultBuffer, 0, len);
         }
         }
         finally
         finally
@@ -138,20 +148,30 @@ internal sealed class Utf8Reader
 
 
     public byte ReadByte(Stream stream)
     public byte ReadByte(Stream stream)
     {
     {
-        if (buffer.Length == 0) return 0;
+        if (buffer.Length == 0)
+        {
+            return 0;
+        }
 
 
         var len = 0;
         var len = 0;
         while (len < 1)
         while (len < 1)
         {
         {
             if (bufPos >= bufLen)
             if (bufPos >= bufLen)
             {
             {
-                
-                bufLen = stream.Read(this.buffer, 0, this.buffer.Length);
+                bufLen = stream.Read(buffer, 0, buffer.Length);
                 bufPos = 0;
                 bufPos = 0;
-                if (bufLen == 0) break; // EOF
+                if (bufLen == 0)
+                {
+                    break; // EOF
+                }
             }
             }
+
             var bytesToRead = Math.Min(1, bufLen - bufPos);
             var bytesToRead = Math.Min(1, bufLen - bufPos);
-            if (bytesToRead == 0) break;
+            if (bytesToRead == 0)
+            {
+                break;
+            }
+
             if (bytesToRead > 0)
             if (bytesToRead > 0)
             {
             {
                 len += bytesToRead;
                 len += bytesToRead;
@@ -160,13 +180,21 @@ internal sealed class Utf8Reader
 
 
         return buffer[bufPos++];
         return buffer[bufPos++];
     }
     }
+
     public string? Read(Stream stream, int charCount)
     public string? Read(Stream stream, int charCount)
     {
     {
-        if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount));
-        if (charCount == 0) return string.Empty;
+        if (charCount < 0)
+        {
+            throw new ArgumentOutOfRangeException(nameof(charCount));
+        }
+
+        if (charCount == 0)
+        {
+            return string.Empty;
+        }
 
 
         var len = 0;
         var len = 0;
-        bool dataRead = false;
+        var dataRead = false;
         var resultBuffer = ArrayPool<char>.Shared.Rent(charCount);
         var resultBuffer = ArrayPool<char>.Shared.Rent(charCount);
 
 
         try
         try
@@ -177,18 +205,21 @@ internal sealed class Utf8Reader
                 {
                 {
                     bufLen = stream.Read(buffer, 0, buffer.Length);
                     bufLen = stream.Read(buffer, 0, buffer.Length);
                     bufPos = 0;
                     bufPos = 0;
-                    if (bufLen == 0) break; // EOF
+                    if (bufLen == 0)
+                    {
+                        break; // EOF
+                    }
                 }
                 }
 
 
-                var byteSpan = new ReadOnlySpan<byte>(buffer, bufPos, bufLen - bufPos);
-                var charSpan = new Span<char>(resultBuffer, len, charCount - len);
+                ReadOnlySpan<byte> byteSpan = new(buffer, bufPos, bufLen - bufPos);
+                Span<char> charSpan = new(resultBuffer, len, charCount - len);
                 decoder ??= Encoding.UTF8.GetDecoder();
                 decoder ??= Encoding.UTF8.GetDecoder();
                 decoder.Convert(
                 decoder.Convert(
                     byteSpan,
                     byteSpan,
                     charSpan,
                     charSpan,
-                    flush: false,
-                    out int bytesUsed,
-                    out int charsUsed,
+                    false,
+                    out var bytesUsed,
+                    out var charsUsed,
                     out _);
                     out _);
 
 
                 if (charsUsed > 0)
                 if (charsUsed > 0)
@@ -198,10 +229,17 @@ internal sealed class Utf8Reader
                 }
                 }
 
 
                 bufPos += bytesUsed;
                 bufPos += bytesUsed;
-                if (bytesUsed == 0) break;
+                if (bytesUsed == 0)
+                {
+                    break;
+                }
+            }
+
+            if (!dataRead || len != charCount)
+            {
+                return null;
             }
             }
 
 
-            if (!dataRead || len != charCount) return null;
             return resultBuffer.AsSpan(0, len).ToString();
             return resultBuffer.AsSpan(0, len).ToString();
         }
         }
         finally
         finally
@@ -211,11 +249,11 @@ internal sealed class Utf8Reader
     }
     }
 
 
 
 
-    private static void AppendToBuffer(ref byte[] buffer, ReadOnlySpan<byte> segment, ref int length)
+    static void AppendToBuffer(ref byte[] buffer, ReadOnlySpan<byte> segment, ref int length)
     {
     {
         if (length + segment.Length > buffer.Length)
         if (length + segment.Length > buffer.Length)
         {
         {
-            int newSize = Math.Max(buffer.Length * 2, length + segment.Length);
+            var newSize = Math.Max(buffer.Length * 2, length + segment.Length);
             var newBuffer = ArrayPool<byte>.Shared.Rent(newSize);
             var newBuffer = ArrayPool<byte>.Shared.Rent(newSize);
             Array.Copy(buffer, newBuffer, length);
             Array.Copy(buffer, newBuffer, length);
             ArrayPool<byte>.Shared.Return(buffer);
             ArrayPool<byte>.Shared.Return(buffer);
@@ -240,21 +278,27 @@ internal sealed class Utf8Reader
         var isHex = false;
         var isHex = false;
         var hasDecimal = false;
         var hasDecimal = false;
         var lastWasE = false;
         var lastWasE = false;
-        
+
         try
         try
         {
         {
             // Skip leading whitespace
             // Skip leading whitespace
             while (true)
             while (true)
             {
             {
                 var b = PeekByte(stream);
                 var b = PeekByte(stream);
-                if (b == -1) return null; // EOF
-                
+                if (b == -1)
+                {
+                    return null; // EOF
+                }
+
                 var c = (char)b;
                 var c = (char)b;
-                if (!char.IsWhiteSpace(c)) break;
-                
+                if (!char.IsWhiteSpace(c))
+                {
+                    break;
+                }
+
                 ReadByte(stream); // Consume whitespace
                 ReadByte(stream); // Consume whitespace
             }
             }
-            
+
             // Check for hex prefix at the start
             // Check for hex prefix at the start
             if (PeekByte(stream) == '0')
             if (PeekByte(stream) == '0')
             {
             {
@@ -268,16 +312,19 @@ internal sealed class Utf8Reader
                     hasStarted = true;
                     hasStarted = true;
                 }
                 }
             }
             }
-            
+
             // Read number characters
             // Read number characters
             while (true)
             while (true)
             {
             {
                 var b = PeekByte(stream);
                 var b = PeekByte(stream);
-                if (b == -1) break; // EOF
-                
+                if (b == -1)
+                {
+                    break; // EOF
+                }
+
                 var c = (char)b;
                 var c = (char)b;
                 var shouldConsume = false;
                 var shouldConsume = false;
-                
+
                 if (!hasStarted && (c == '+' || c == '-'))
                 if (!hasStarted && (c == '+' || c == '-'))
                 {
                 {
                     shouldConsume = true;
                     shouldConsume = true;
@@ -339,7 +386,7 @@ internal sealed class Utf8Reader
                         lastWasE = false;
                         lastWasE = false;
                     }
                     }
                 }
                 }
-                
+
                 if (shouldConsume)
                 if (shouldConsume)
                 {
                 {
                     if (len >= resultBuffer.Length)
                     if (len >= resultBuffer.Length)
@@ -350,7 +397,7 @@ internal sealed class Utf8Reader
                         ArrayPool<char>.Shared.Return(resultBuffer);
                         ArrayPool<char>.Shared.Return(resultBuffer);
                         resultBuffer = newBuffer;
                         resultBuffer = newBuffer;
                     }
                     }
-                    
+
                     resultBuffer[len++] = c;
                     resultBuffer[len++] = c;
                     ReadByte(stream); // Consume the byte
                     ReadByte(stream); // Consume the byte
                 }
                 }
@@ -359,7 +406,7 @@ internal sealed class Utf8Reader
                     break; // Not part of the number
                     break; // Not part of the number
                 }
                 }
             }
             }
-            
+
             return len == 0 ? null : resultBuffer.AsSpan(0, len).ToString();
             return len == 0 ? null : resultBuffer.AsSpan(0, len).ToString();
         }
         }
         finally
         finally
@@ -367,8 +414,8 @@ internal sealed class Utf8Reader
             ArrayPool<char>.Shared.Return(resultBuffer);
             ArrayPool<char>.Shared.Return(resultBuffer);
         }
         }
     }
     }
-    
-    private int PeekByte(Stream stream, int offset = 0)
+
+    int PeekByte(Stream stream, int offset = 0)
     {
     {
         // Ensure we have enough data in buffer
         // Ensure we have enough data in buffer
         while (bufPos + offset >= bufLen)
         while (bufPos + offset >= bufLen)
@@ -377,7 +424,10 @@ internal sealed class Utf8Reader
             {
             {
                 bufLen = stream.Read(buffer, 0, buffer.Length);
                 bufLen = stream.Read(buffer, 0, buffer.Length);
                 bufPos = 0;
                 bufPos = 0;
-                if (bufLen == 0) return -1; // EOF
+                if (bufLen == 0)
+                {
+                    return -1; // EOF
+                }
             }
             }
             else
             else
             {
             {
@@ -385,7 +435,7 @@ internal sealed class Utf8Reader
                 return -1;
                 return -1;
             }
             }
         }
         }
-        
+
         return buffer[bufPos + offset];
         return buffer[bufPos + offset];
     }
     }
 
 

+ 269 - 242
src/Lua/Internal/ValueStringBuilder.cs

@@ -8,330 +8,357 @@ using System.Runtime.InteropServices;
 
 
 #nullable enable
 #nullable enable
 
 
-namespace System.Text
+namespace System.Text;
+
+ref partial struct ValueStringBuilder
 {
 {
-    internal ref partial struct ValueStringBuilder
+    char[]? _arrayToReturnToPool;
+    Span<char> _chars;
+    int _pos;
+
+    public ValueStringBuilder(Span<char> initialBuffer)
+    {
+        _arrayToReturnToPool = null;
+        _chars = initialBuffer;
+        _pos = 0;
+    }
+
+    public ValueStringBuilder(int initialCapacity)
     {
     {
-        private char[]? _arrayToReturnToPool;
-        private Span<char> _chars;
-        private int _pos;
+        _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
+        _chars = _arrayToReturnToPool;
+        _pos = 0;
+    }
 
 
-        public ValueStringBuilder(Span<char> initialBuffer)
+    public int Length
+    {
+        get
         {
         {
-            _arrayToReturnToPool = null;
-            _chars = initialBuffer;
-            _pos = 0;
+            return _pos;
         }
         }
-
-        public ValueStringBuilder(int initialCapacity)
+        set
         {
         {
-            _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
-            _chars = _arrayToReturnToPool;
-            _pos = 0;
+            Debug.Assert(value >= 0);
+            Debug.Assert(value <= _chars.Length);
+            _pos = value;
         }
         }
+    }
 
 
-        public int Length
+    public int Capacity
+    {
+        get
         {
         {
-            get => _pos;
-            set
-            {
-                Debug.Assert(value >= 0);
-                Debug.Assert(value <= _chars.Length);
-                _pos = value;
-            }
+            return _chars.Length;
         }
         }
+    }
 
 
-        public int Capacity => _chars.Length;
+    public void EnsureCapacity(int capacity)
+    {
+        // This is not expected to be called this with negative capacity
+        Debug.Assert(capacity >= 0);
 
 
-        public void EnsureCapacity(int capacity)
+        // If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.
+        if ((uint)capacity > (uint)_chars.Length)
         {
         {
-            // This is not expected to be called this with negative capacity
-            Debug.Assert(capacity >= 0);
-
-            // If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.
-            if ((uint)capacity > (uint)_chars.Length)
-                Grow(capacity - _pos);
+            Grow(capacity - _pos);
         }
         }
+    }
+
+    /// <summary>
+    /// Get a pinnable reference to the builder.
+    /// Does not ensure there is a null char after <see cref="Length"/>
+    /// This overload is pattern matched in the C# 7.3+ compiler so you can omit
+    /// the explicit method call, and write eg "fixed (char* c = builder)"
+    /// </summary>
+    public ref char GetPinnableReference()
+    {
+        return ref MemoryMarshal.GetReference(_chars);
+    }
 
 
-        /// <summary>
-        /// Get a pinnable reference to the builder.
-        /// Does not ensure there is a null char after <see cref="Length"/>
-        /// This overload is pattern matched in the C# 7.3+ compiler so you can omit
-        /// the explicit method call, and write eg "fixed (char* c = builder)"
-        /// </summary>
-        public ref char GetPinnableReference()
+    /// <summary>
+    /// Get a pinnable reference to the builder.
+    /// </summary>
+    /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
+    public ref char GetPinnableReference(bool terminate)
+    {
+        if (terminate)
         {
         {
-            return ref MemoryMarshal.GetReference(_chars);
+            EnsureCapacity(Length + 1);
+            _chars[Length] = '\0';
         }
         }
 
 
-        /// <summary>
-        /// Get a pinnable reference to the builder.
-        /// </summary>
-        /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
-        public ref char GetPinnableReference(bool terminate)
-        {
-            if (terminate)
-            {
-                EnsureCapacity(Length + 1);
-                _chars[Length] = '\0';
-            }
+        return ref MemoryMarshal.GetReference(_chars);
+    }
 
 
-            return ref MemoryMarshal.GetReference(_chars);
+    public ref char this[int index]
+    {
+        get
+        {
+            Debug.Assert(index < _pos);
+            return ref _chars[index];
         }
         }
+    }
+
+    public override string ToString()
+    {
+        var s = _chars.Slice(0, _pos).ToString();
+        Dispose();
+        return s;
+    }
 
 
-        public ref char this[int index]
+    /// <summary>Returns the underlying storage of the builder.</summary>
+    public Span<char> RawChars
+    {
+        get
         {
         {
-            get
-            {
-                Debug.Assert(index < _pos);
-                return ref _chars[index];
-            }
+            return _chars;
         }
         }
+    }
 
 
-        public override string ToString()
+    /// <summary>
+    /// Returns a span around the contents of the builder.
+    /// </summary>
+    /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
+    public ReadOnlySpan<char> AsSpan(bool terminate)
+    {
+        if (terminate)
         {
         {
-            string s = _chars.Slice(0, _pos).ToString();
-            Dispose();
-            return s;
+            EnsureCapacity(Length + 1);
+            _chars[Length] = '\0';
         }
         }
 
 
-        /// <summary>Returns the underlying storage of the builder.</summary>
-        public Span<char> RawChars => _chars;
+        return _chars.Slice(0, _pos);
+    }
 
 
-        /// <summary>
-        /// Returns a span around the contents of the builder.
-        /// </summary>
-        /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
-        public ReadOnlySpan<char> AsSpan(bool terminate)
-        {
-            if (terminate)
-            {
-                EnsureCapacity(Length + 1);
-                _chars[Length] = '\0';
-            }
+    public ReadOnlySpan<char> AsSpan()
+    {
+        return _chars.Slice(0, _pos);
+    }
 
 
-            return _chars.Slice(0, _pos);
-        }
+    public ReadOnlySpan<char> AsSpan(int start)
+    {
+        return _chars.Slice(start, _pos - start);
+    }
 
 
-        public ReadOnlySpan<char> AsSpan() => _chars.Slice(0, _pos);
-        public ReadOnlySpan<char> AsSpan(int start) => _chars.Slice(start, _pos - start);
-        public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
+    public ReadOnlySpan<char> AsSpan(int start, int length)
+    {
+        return _chars.Slice(start, length);
+    }
 
 
-        public bool TryCopyTo(Span<char> destination, out int charsWritten)
+    public bool TryCopyTo(Span<char> destination, out int charsWritten)
+    {
+        if (_chars.Slice(0, _pos).TryCopyTo(destination))
         {
         {
-            if (_chars.Slice(0, _pos).TryCopyTo(destination))
-            {
-                charsWritten = _pos;
-                Dispose();
-                return true;
-            }
-            else
-            {
-                charsWritten = 0;
-                Dispose();
-                return false;
-            }
+            charsWritten = _pos;
+            Dispose();
+            return true;
+        }
+        else
+        {
+            charsWritten = 0;
+            Dispose();
+            return false;
         }
         }
+    }
 
 
-        public void Insert(int index, char value, int count)
+    public void Insert(int index, char value, int count)
+    {
+        if (_pos > _chars.Length - count)
         {
         {
-            if (_pos > _chars.Length - count)
-            {
-                Grow(count);
-            }
-
-            int remaining = _pos - index;
-            _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
-            _chars.Slice(index, count).Fill(value);
-            _pos += count;
+            Grow(count);
         }
         }
 
 
-        public void Insert(int index, string? s)
+        var remaining = _pos - index;
+        _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
+        _chars.Slice(index, count).Fill(value);
+        _pos += count;
+    }
+
+    public void Insert(int index, string? s)
+    {
+        if (s == null)
         {
         {
-            if (s == null)
-            {
-                return;
-            }
+            return;
+        }
 
 
-            int count = s.Length;
+        var count = s.Length;
 
 
-            if (_pos > (_chars.Length - count))
-            {
-                Grow(count);
-            }
+        if (_pos > _chars.Length - count)
+        {
+            Grow(count);
+        }
 
 
-            int remaining = _pos - index;
-            _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
-            s
+        var remaining = _pos - index;
+        _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
+        s
 #if !NET
 #if !NET
                 .AsSpan()
                 .AsSpan()
 #endif
 #endif
-                .CopyTo(_chars.Slice(index));
-            _pos += count;
+            .CopyTo(_chars.Slice(index));
+        _pos += count;
+    }
+
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Append(char c)
+    {
+        var pos = _pos;
+        var chars = _chars;
+        if ((uint)pos < (uint)chars.Length)
+        {
+            chars[pos] = c;
+            _pos = pos + 1;
+        }
+        else
+        {
+            GrowAndAppend(c);
         }
         }
+    }
 
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Append(char c)
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Append(string? s)
+    {
+        if (s == null)
         {
         {
-            int pos = _pos;
-            Span<char> chars = _chars;
-            if ((uint)pos < (uint)chars.Length)
-            {
-                chars[pos] = c;
-                _pos = pos + 1;
-            }
-            else
-            {
-                GrowAndAppend(c);
-            }
+            return;
         }
         }
 
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Append(string? s)
+        var pos = _pos;
+        if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
         {
         {
-            if (s == null)
-            {
-                return;
-            }
-
-            int pos = _pos;
-            if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
-            {
-                _chars[pos] = s[0];
-                _pos = pos + 1;
-            }
-            else
-            {
-                AppendSlow(s);
-            }
+            _chars[pos] = s[0];
+            _pos = pos + 1;
         }
         }
+        else
+        {
+            AppendSlow(s);
+        }
+    }
 
 
-        private void AppendSlow(string s)
+    void AppendSlow(string s)
+    {
+        var pos = _pos;
+        if (pos > _chars.Length - s.Length)
         {
         {
-            int pos = _pos;
-            if (pos > _chars.Length - s.Length)
-            {
-                Grow(s.Length);
-            }
+            Grow(s.Length);
+        }
 
 
-            s
+        s
 #if !NET
 #if !NET
                 .AsSpan()
                 .AsSpan()
 #endif
 #endif
-                .CopyTo(_chars.Slice(pos));
-            _pos += s.Length;
-        }
+            .CopyTo(_chars.Slice(pos));
+        _pos += s.Length;
+    }
 
 
-        public void Append(char c, int count)
+    public void Append(char c, int count)
+    {
+        if (_pos > _chars.Length - count)
         {
         {
-            if (_pos > _chars.Length - count)
-            {
-                Grow(count);
-            }
-
-            Span<char> dst = _chars.Slice(_pos, count);
-            for (int i = 0; i < dst.Length; i++)
-            {
-                dst[i] = c;
-            }
-
-            _pos += count;
+            Grow(count);
         }
         }
 
 
-        public unsafe void Append(char* value, int length)
+        var dst = _chars.Slice(_pos, count);
+        for (var i = 0; i < dst.Length; i++)
         {
         {
-            int pos = _pos;
-            if (pos > _chars.Length - length)
-            {
-                Grow(length);
-            }
-
-            Span<char> dst = _chars.Slice(_pos, length);
-            for (int i = 0; i < dst.Length; i++)
-            {
-                dst[i] = *value++;
-            }
-
-            _pos += length;
+            dst[i] = c;
         }
         }
 
 
-        public void Append(scoped ReadOnlySpan<char> value)
+        _pos += count;
+    }
+
+    public unsafe void Append(char* value, int length)
+    {
+        var pos = _pos;
+        if (pos > _chars.Length - length)
         {
         {
-            int pos = _pos;
-            if (pos > _chars.Length - value.Length)
-            {
-                Grow(value.Length);
-            }
-
-            value.CopyTo(_chars.Slice(_pos));
-            _pos += value.Length;
+            Grow(length);
         }
         }
 
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public Span<char> AppendSpan(int length)
+        var dst = _chars.Slice(_pos, length);
+        for (var i = 0; i < dst.Length; i++)
         {
         {
-            int origPos = _pos;
-            if (origPos > _chars.Length - length)
-            {
-                Grow(length);
-            }
-
-            _pos = origPos + length;
-            return _chars.Slice(origPos, length);
+            dst[i] = *value++;
         }
         }
 
 
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private void GrowAndAppend(char c)
+        _pos += length;
+    }
+
+    public void Append(scoped ReadOnlySpan<char> value)
+    {
+        var pos = _pos;
+        if (pos > _chars.Length - value.Length)
         {
         {
-            Grow(1);
-            Append(c);
+            Grow(value.Length);
         }
         }
 
 
-        /// <summary>
-        /// Resize the internal buffer either by doubling current buffer size or
-        /// by adding <paramref name="additionalCapacityBeyondPos"/> to
-        /// <see cref="_pos"/> whichever is greater.
-        /// </summary>
-        /// <param name="additionalCapacityBeyondPos">
-        /// Number of chars requested beyond current position.
-        /// </param>
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private void Grow(int additionalCapacityBeyondPos)
+        value.CopyTo(_chars.Slice(_pos));
+        _pos += value.Length;
+    }
+
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public Span<char> AppendSpan(int length)
+    {
+        var origPos = _pos;
+        if (origPos > _chars.Length - length)
         {
         {
-            Debug.Assert(additionalCapacityBeyondPos > 0);
-            Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
+            Grow(length);
+        }
+
+        _pos = origPos + length;
+        return _chars.Slice(origPos, length);
+    }
 
 
-            const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    void GrowAndAppend(char c)
+    {
+        Grow(1);
+        Append(c);
+    }
 
 
-            // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try
-            // to double the size if possible, bounding the doubling to not go beyond the max array length.
-            int newCapacity = (int)Math.Max(
-                (uint)(_pos + additionalCapacityBeyondPos),
-                Math.Min((uint)_chars.Length * 2, ArrayMaxLength));
+    /// <summary>
+    /// Resize the internal buffer either by doubling current buffer size or
+    /// by adding <paramref name="additionalCapacityBeyondPos"/> to
+    /// <see cref="_pos"/> whichever is greater.
+    /// </summary>
+    /// <param name="additionalCapacityBeyondPos">
+    /// Number of chars requested beyond current position.
+    /// </param>
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    void Grow(int additionalCapacityBeyondPos)
+    {
+        Debug.Assert(additionalCapacityBeyondPos > 0);
+        Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
 
 
-            // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.
-            // This could also go negative if the actual required length wraps around.
-            char[] poolArray = ArrayPool<char>.Shared.Rent(newCapacity);
+        const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength
 
 
-            _chars.Slice(0, _pos).CopyTo(poolArray);
+        // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try
+        // to double the size if possible, bounding the doubling to not go beyond the max array length.
+        var newCapacity = (int)Math.Max(
+            (uint)(_pos + additionalCapacityBeyondPos),
+            Math.Min((uint)_chars.Length * 2, ArrayMaxLength));
 
 
-            char[]? toReturn = _arrayToReturnToPool;
-            _chars = _arrayToReturnToPool = poolArray;
-            if (toReturn != null)
-            {
-                ArrayPool<char>.Shared.Return(toReturn);
-            }
+        // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.
+        // This could also go negative if the actual required length wraps around.
+        var poolArray = ArrayPool<char>.Shared.Rent(newCapacity);
+
+        _chars.Slice(0, _pos).CopyTo(poolArray);
+
+        var toReturn = _arrayToReturnToPool;
+        _chars = _arrayToReturnToPool = poolArray;
+        if (toReturn != null)
+        {
+            ArrayPool<char>.Shared.Return(toReturn);
         }
         }
+    }
 
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Dispose()
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Dispose()
+    {
+        var toReturn = _arrayToReturnToPool;
+        this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
+        if (toReturn != null)
         {
         {
-            char[]? toReturn = _arrayToReturnToPool;
-            this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
-            if (toReturn != null)
-            {
-                ArrayPool<char>.Shared.Return(toReturn);
-            }
+            ArrayPool<char>.Shared.Return(toReturn);
         }
         }
     }
     }
 }
 }

+ 5 - 4
src/Lua/Internal/ValueTaskEx.cs

@@ -33,13 +33,13 @@ SOFTWARE.
 
 
 namespace Lua.Internal;
 namespace Lua.Internal;
 
 
-internal static class ContinuationSentinel
+static class ContinuationSentinel
 {
 {
     public static readonly Action<object?> AvailableContinuation = _ => { };
     public static readonly Action<object?> AvailableContinuation = _ => { };
     public static readonly Action<object?> CompletedContinuation = _ => { };
     public static readonly Action<object?> CompletedContinuation = _ => { };
 }
 }
 
 
-internal static class ValueTaskEx
+static class ValueTaskEx
 {
 {
     public static ValueTask<(int winArgumentIndex, T0 result0, T1 result1, IDisposable promis)> WhenAnyPooled<T0, T1>(ValueTask<T0> task0, ValueTask<T1> task1)
     public static ValueTask<(int winArgumentIndex, T0 result0, T1 result1, IDisposable promis)> WhenAnyPooled<T0, T1>(ValueTask<T0> task0, ValueTask<T1> task1)
     {
     {
@@ -54,6 +54,7 @@ internal static class ValueTaskEx
 
 
         static LinkedPool<WhenAnyPromise<T0, T1>> pool;
         static LinkedPool<WhenAnyPromise<T0, T1>> pool;
         WhenAnyPromise<T0, T1>? nextNode;
         WhenAnyPromise<T0, T1>? nextNode;
+
         public ref WhenAnyPromise<T0, T1>? NextNode => ref nextNode;
         public ref WhenAnyPromise<T0, T1>? NextNode => ref nextNode;
 
 
         public static WhenAnyPromise<T0, T1> Get(ValueTask<T0> task0, ValueTask<T1> task1)
         public static WhenAnyPromise<T0, T1> Get(ValueTask<T0> task0, ValueTask<T1> task1)
@@ -64,7 +65,7 @@ internal static class ValueTaskEx
             }
             }
             else
             else
             {
             {
-                f = new WhenAnyPromise<T0, T1>(task0, task1);
+                f = new(task0, task1);
             }
             }
 
 
             return f;
             return f;
@@ -245,7 +246,7 @@ internal static class ValueTaskEx
             var c = Interlocked.Exchange(ref continuation, ContinuationSentinel.CompletedContinuation);
             var c = Interlocked.Exchange(ref continuation, ContinuationSentinel.CompletedContinuation);
             if (c != ContinuationSentinel.AvailableContinuation && c != ContinuationSentinel.CompletedContinuation)
             if (c != ContinuationSentinel.AvailableContinuation && c != ContinuationSentinel.CompletedContinuation)
             {
             {
-                var spinWait = new SpinWait();
+                SpinWait spinWait = new();
                 while (state == null) // worst case, state is not set yet so wait.
                 while (state == null) // worst case, state is not set yet so wait.
                 {
                 {
                     spinWait.SpinOnce();
                     spinWait.SpinOnce();

+ 4 - 1
src/Lua/Loaders/CompositeModuleLoader.cs

@@ -189,7 +189,10 @@ public static class CompositeModuleLoader
         {
         {
             foreach (var loader in loaders)
             foreach (var loader in loaders)
             {
             {
-                if (loader.Exists(moduleName)) return true;
+                if (loader.Exists(moduleName))
+                {
+                    return true;
+                }
             }
             }
 
 
             return false;
             return false;

+ 11 - 5
src/Lua/LuaCoroutine.cs

@@ -10,11 +10,12 @@ public sealed class LuaCoroutine : LuaThread, IValueTaskSource<LuaCoroutine.Yiel
 {
 {
     static LinkedPool<LuaCoroutine> pool;
     static LinkedPool<LuaCoroutine> pool;
     LuaCoroutine? nextNode;
     LuaCoroutine? nextNode;
+
     ref LuaCoroutine? IPoolNode<LuaCoroutine>.NextNode => ref nextNode;
     ref LuaCoroutine? IPoolNode<LuaCoroutine>.NextNode => ref nextNode;
 
 
     public static LuaCoroutine Create(LuaThread parent, LuaFunction function, bool isProtectedMode)
     public static LuaCoroutine Create(LuaThread parent, LuaFunction function, bool isProtectedMode)
     {
     {
-        if (!pool.TryPop(out LuaCoroutine result))
+        if (!pool.TryPop(out var result))
         {
         {
             result = new();
             result = new();
         }
         }
@@ -42,6 +43,7 @@ public sealed class LuaCoroutine : LuaThread, IValueTaskSource<LuaCoroutine.Yiel
     readonly struct ResumeContext(LuaStack? stack, int argCount)
     readonly struct ResumeContext(LuaStack? stack, int argCount)
     {
     {
         public ReadOnlySpan<LuaValue> Results => stack!.AsSpan()[^argCount..];
         public ReadOnlySpan<LuaValue> Results => stack!.AsSpan()[^argCount..];
+
         public bool IsDead => stack == null;
         public bool IsDead => stack == null;
     }
     }
 
 
@@ -61,7 +63,10 @@ public sealed class LuaCoroutine : LuaThread, IValueTaskSource<LuaCoroutine.Yiel
         Function = function;
         Function = function;
     }
     }
 
 
-    public override LuaThreadStatus GetStatus() => (LuaThreadStatus)status;
+    public override LuaThreadStatus GetStatus()
+    {
+        return (LuaThreadStatus)status;
+    }
 
 
     public override void UnsafeSetStatus(LuaThreadStatus status)
     public override void UnsafeSetStatus(LuaThreadStatus status)
     {
     {
@@ -70,6 +75,7 @@ public sealed class LuaCoroutine : LuaThread, IValueTaskSource<LuaCoroutine.Yiel
 
 
     public bool IsProtectedMode { get; private set; }
     public bool IsProtectedMode { get; private set; }
     public LuaFunction Function { get; private set; } = null!;
     public LuaFunction Function { get; private set; } = null!;
+
     internal Traceback? LuaTraceback => traceback;
     internal Traceback? LuaTraceback => traceback;
 
 
     public bool CanResume => status == (byte)LuaThreadStatus.Suspended;
     public bool CanResume => status == (byte)LuaThreadStatus.Suspended;
@@ -135,7 +141,7 @@ public sealed class LuaCoroutine : LuaThread, IValueTaskSource<LuaCoroutine.Yiel
                     }
                     }
             }
             }
 
 
-            var resumeTask = new ValueTask<ResumeContext>(this, resume.Version);
+            ValueTask<ResumeContext> resumeTask = new(this, resume.Version);
 
 
             CancellationTokenRegistration registration = default;
             CancellationTokenRegistration registration = default;
             if (cancellationToken.CanBeCanceled)
             if (cancellationToken.CanBeCanceled)
@@ -157,7 +163,7 @@ public sealed class LuaCoroutine : LuaThread, IValueTaskSource<LuaCoroutine.Yiel
                     Volatile.Write(ref isFirstCall, false);
                     Volatile.Write(ref isFirstCall, false);
                     if (!functionTask.IsCompleted)
                     if (!functionTask.IsCompleted)
                     {
                     {
-                        functionTask.GetAwaiter().OnCompleted(() => this.resume.SetResult(default));
+                        functionTask.GetAwaiter().OnCompleted(() => resume.SetResult(default));
                     }
                     }
                 }
                 }
 
 
@@ -264,7 +270,7 @@ public sealed class LuaCoroutine : LuaThread, IValueTaskSource<LuaCoroutine.Yiel
             var result = await new ValueTask<YieldContext>(this, yield.Version);
             var result = await new ValueTask<YieldContext>(this, yield.Version);
             stack.PopUntil(returnBase);
             stack.PopUntil(returnBase);
             stack.PushRange(result.Results);
             stack.PushRange(result.Results);
-            return (result.Results).Length;
+            return result.Results.Length;
         }
         }
         catch (Exception ex) when (ex is not OperationCanceledException)
         catch (Exception ex) when (ex is not OperationCanceledException)
         {
         {

+ 5 - 0
src/Lua/LuaFunctionExecutionContext.cs

@@ -8,10 +8,15 @@ namespace Lua;
 public readonly record struct LuaFunctionExecutionContext
 public readonly record struct LuaFunctionExecutionContext
 {
 {
     public LuaState State => Thread.State;
     public LuaState State => Thread.State;
+
     public required LuaThreadAccess Access { get; init; }
     public required LuaThreadAccess Access { get; init; }
+
     public LuaThread Thread => Access.Thread;
     public LuaThread Thread => Access.Thread;
+
     public required int ArgumentCount { get; init; }
     public required int ArgumentCount { get; init; }
+
     public int FrameBase => Thread.Stack.Count - ArgumentCount;
     public int FrameBase => Thread.Stack.Count - ArgumentCount;
+
     public required int ReturnFrameBase { get; init; }
     public required int ReturnFrameBase { get; init; }
     //public object? AdditionalContext { get; init; }
     //public object? AdditionalContext { get; init; }
 
 

+ 12 - 3
src/Lua/LuaModule.cs

@@ -6,12 +6,13 @@ namespace Lua;
 public enum LuaModuleType
 public enum LuaModuleType
 {
 {
     Text,
     Text,
-    Bytes,
+    Bytes
 }
 }
 
 
 public readonly struct LuaModule
 public readonly struct LuaModule
 {
 {
     public string Name => name;
     public string Name => name;
+
     public LuaModuleType Type => type;
     public LuaModuleType Type => type;
 
 
     readonly string name;
     readonly string name;
@@ -42,13 +43,21 @@ public readonly struct LuaModule
 
 
     public ReadOnlySpan<char> ReadText()
     public ReadOnlySpan<char> ReadText()
     {
     {
-        if (type != LuaModuleType.Text) throw new Exception(); // TODO: add message
+        if (type != LuaModuleType.Text)
+        {
+            throw new(); // TODO: add message
+        }
+
         return text.Span;
         return text.Span;
     }
     }
 
 
     public ReadOnlySpan<byte> ReadBytes()
     public ReadOnlySpan<byte> ReadBytes()
     {
     {
-        if (type != LuaModuleType.Bytes) throw new Exception(); // TODO: add message
+        if (type != LuaModuleType.Bytes)
+        {
+            throw new(); // TODO: add message
+        }
+
         return bytes.Span;
         return bytes.Span;
     }
     }
 }
 }

+ 1 - 1
src/Lua/LuaObjectMetamethod.cs

@@ -17,5 +17,5 @@ public enum LuaObjectMetamethod
     Concat,
     Concat,
     Pairs,
     Pairs,
     IPairs,
     IPairs,
-    ToString,
+    ToString
 }
 }

+ 21 - 8
src/Lua/LuaState.cs

@@ -8,6 +8,7 @@ using Lua.Platforms;
 using Lua.Runtime;
 using Lua.Runtime;
 using Lua.Standard;
 using Lua.Standard;
 using System.Buffers;
 using System.Buffers;
+using System.Text;
 
 
 namespace Lua;
 namespace Lua;
 
 
@@ -25,27 +26,36 @@ public sealed class LuaState
     FastStackCore<LuaDebug.LuaDebugBuffer> debugBufferPool;
     FastStackCore<LuaDebug.LuaDebugBuffer> debugBufferPool;
 
 
     internal int CallCount;
     internal int CallCount;
+
     internal UpValue EnvUpValue => envUpValue;
     internal UpValue EnvUpValue => envUpValue;
+
     internal ref FastStackCore<LuaThread> ThreadStack => ref threadStack;
     internal ref FastStackCore<LuaThread> ThreadStack => ref threadStack;
+
     internal ref FastListCore<UpValue> OpenUpValues => ref openUpValues;
     internal ref FastListCore<UpValue> OpenUpValues => ref openUpValues;
+
     internal ref FastStackCore<LuaDebug.LuaDebugBuffer> DebugBufferPool => ref debugBufferPool;
     internal ref FastStackCore<LuaDebug.LuaDebugBuffer> DebugBufferPool => ref debugBufferPool;
 
 
     public LuaTable Environment => environment;
     public LuaTable Environment => environment;
+
     public LuaTable Registry => registry;
     public LuaTable Registry => registry;
+
     public LuaTable LoadedModules => registry[ModuleLibrary.LoadedKeyForRegistry].Read<LuaTable>();
     public LuaTable LoadedModules => registry[ModuleLibrary.LoadedKeyForRegistry].Read<LuaTable>();
+
     public LuaTable PreloadModules => registry[ModuleLibrary.PreloadKeyForRegistry].Read<LuaTable>();
     public LuaTable PreloadModules => registry[ModuleLibrary.PreloadKeyForRegistry].Read<LuaTable>();
+
     public LuaMainThread MainThread => mainThread;
     public LuaMainThread MainThread => mainThread;
 
 
     public LuaThreadAccess RootAccess => new(mainThread, 0);
     public LuaThreadAccess RootAccess => new(mainThread, 0);
 
 
     public LuaPlatform Platform { get; }
     public LuaPlatform Platform { get; }
 
 
-    public ILuaModuleLoader? ModuleLoader { get; set; } 
+    public ILuaModuleLoader? ModuleLoader { get; set; }
+
     public ILuaFileSystem FileSystem => Platform.FileSystem ?? throw new InvalidOperationException("FileSystem is not set. Please set it before access.");
     public ILuaFileSystem FileSystem => Platform.FileSystem ?? throw new InvalidOperationException("FileSystem is not set. Please set it before access.");
 
 
     public ILuaOsEnvironment OsEnvironment => Platform.OsEnvironment ?? throw new InvalidOperationException("OperatingSystem is not set. Please set it before access.");
     public ILuaOsEnvironment OsEnvironment => Platform.OsEnvironment ?? throw new InvalidOperationException("OperatingSystem is not set. Please set it before access.");
-    
-    
+
+
     public TimeProvider TimeProvider => Platform.TimeProvider ?? throw new InvalidOperationException("TimeProvider is not set. Please set it before access.");
     public TimeProvider TimeProvider => Platform.TimeProvider ?? throw new InvalidOperationException("TimeProvider is not set. Please set it before access.");
 
 
     public ILuaStandardIO StandardIO => Platform.StandardIO;
     public ILuaStandardIO StandardIO => Platform.StandardIO;
@@ -60,7 +70,7 @@ public sealed class LuaState
 
 
     public static LuaState Create(LuaPlatform? platform = null)
     public static LuaState Create(LuaPlatform? platform = null)
     {
     {
-        var state = new LuaState(platform ?? LuaPlatform.Default);
+        LuaState state = new(platform ?? LuaPlatform.Default);
         return state;
         return state;
     }
     }
 
 
@@ -143,10 +153,13 @@ public sealed class LuaState
 
 
     internal void CloseUpValues(LuaThread thread, int frameBase)
     internal void CloseUpValues(LuaThread thread, int frameBase)
     {
     {
-        for (int i = 0; i < openUpValues.Length; i++)
+        for (var i = 0; i < openUpValues.Length; i++)
         {
         {
             var upValue = openUpValues[i];
             var upValue = openUpValues[i];
-            if (upValue.Thread != thread) continue;
+            if (upValue.Thread != thread)
+            {
+                continue;
+            }
 
 
             if (upValue.RegisterIndex >= frameBase)
             if (upValue.RegisterIndex >= frameBase)
             {
             {
@@ -165,7 +178,7 @@ public sealed class LuaState
             prototype = Parser.Parse(this, new(ptr, chunk.Length), chunkName);
             prototype = Parser.Parse(this, new(ptr, chunk.Length), chunkName);
         }
         }
 
 
-        return new LuaClosure(MainThread, prototype, environment);
+        return new(MainThread, prototype, environment);
     }
     }
 
 
     public LuaClosure Load(ReadOnlySpan<byte> chunk, string? chunkName = null, string mode = "bt", LuaTable? environment = null)
     public LuaClosure Load(ReadOnlySpan<byte> chunk, string? chunkName = null, string mode = "bt", LuaTable? environment = null)
@@ -174,7 +187,7 @@ public sealed class LuaState
         {
         {
             if (chunk[0] == '\e')
             if (chunk[0] == '\e')
             {
             {
-                return new LuaClosure(MainThread, Parser.UnDump(chunk, chunkName), environment);
+                return new(MainThread, Parser.UnDump(chunk, chunkName), environment);
             }
             }
         }
         }
 
 

+ 1 - 1
src/Lua/LuaStateExtensions.cs

@@ -40,7 +40,7 @@ public static class LuaStateExtensions
         var name = "@" + fileName;
         var name = "@" + fileName;
         using var stream = await state.FileSystem.Open(fileName, LuaFileOpenMode.Read, cancellationToken);
         using var stream = await state.FileSystem.Open(fileName, LuaFileOpenMode.Read, cancellationToken);
         var source = await stream.ReadAllAsync(cancellationToken);
         var source = await stream.ReadAllAsync(cancellationToken);
-        LuaClosure closure = state.Load(source, name, environment);
+        var closure = state.Load(source, name, environment);
 
 
         return closure;
         return closure;
     }
     }

+ 31 - 15
src/Lua/LuaTable.cs

@@ -21,8 +21,9 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
     LuaTable? metatable;
     LuaTable? metatable;
 
 
     internal LuaValueDictionary Dictionary => dictionary;
     internal LuaValueDictionary Dictionary => dictionary;
-    private const int MaxArraySize = 1 << 24;
-    private const int MaxDistance = 1 << 12;
+
+    const int MaxArraySize = 1 << 24;
+    const int MaxDistance = 1 << 12;
 
 
 
 
     public LuaValue this[LuaValue key]
     public LuaValue this[LuaValue key]
@@ -30,7 +31,10 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         get
         get
         {
         {
-            if (key.Type is LuaValueType.Nil) ThrowIndexIsNil();
+            if (key.Type is LuaValueType.Nil)
+            {
+                ThrowIndexIsNil();
+            }
 
 
             if (TryGetInteger(key, out var index))
             if (TryGetInteger(key, out var index))
             {
             {
@@ -41,7 +45,11 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
                 }
                 }
             }
             }
 
 
-            if (dictionary.TryGetValue(key, out var value)) return value;
+            if (dictionary.TryGetValue(key, out var value))
+            {
+                return value;
+            }
+
             return LuaValue.Nil;
             return LuaValue.Nil;
         }
         }
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -68,7 +76,10 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
                     if (0 < index && index < MaxArraySize && index <= Math.Max(array.Length * 2, 8))
                     if (0 < index && index < MaxArraySize && index <= Math.Max(array.Length * 2, 8))
                     {
                     {
                         if (array.Length < index)
                         if (array.Length < index)
+                        {
                             EnsureArrayCapacity(index);
                             EnsureArrayCapacity(index);
+                        }
+
                         array[index - 1] = value;
                         array[index - 1] = value;
                         return;
                         return;
                     }
                     }
@@ -79,18 +90,18 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
         }
         }
     }
     }
 
 
-    public int HashMapCount
-    {
-        get => dictionary.Count - dictionary.NilCount;
-    }
+    public int HashMapCount => dictionary.Count - dictionary.NilCount;
 
 
     public int ArrayLength
     public int ArrayLength
     {
     {
         get
         get
         {
         {
-            for (int i = 0; i < array.Length; i++)
+            for (var i = 0; i < array.Length; i++)
             {
             {
-                if (array[i].Type is LuaValueType.Nil) return i;
+                if (array[i].Type is LuaValueType.Nil)
+                {
+                    return i;
+                }
             }
             }
 
 
             return array.Length;
             return array.Length;
@@ -132,6 +143,7 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
             ThrowIndexIsNil();
             ThrowIndexIsNil();
         }
         }
 
 
+
         if (TryGetInteger(key, out var index))
         if (TryGetInteger(key, out var index))
         {
         {
             if (index > 0 && index <= array.Length)
             if (index > 0 && index <= array.Length)
@@ -217,7 +229,7 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
         if (index != -1)
         if (index != -1)
         {
         {
             var span = array.AsSpan(index);
             var span = array.AsSpan(index);
-            for (int i = 0; i < span.Length; i++)
+            for (var i = 0; i < span.Length; i++)
             {
             {
                 if (span[i].Type is not LuaValueType.Nil)
                 if (span[i].Type is not LuaValueType.Nil)
                 {
                 {
@@ -265,7 +277,10 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
 
 
     internal void EnsureArrayCapacity(int newCapacity)
     internal void EnsureArrayCapacity(int newCapacity)
     {
     {
-        if (array.Length >= newCapacity) return;
+        if (array.Length >= newCapacity)
+        {
+            return;
+        }
 
 
         var prevLength = array.Length;
         var prevLength = array.Length;
         var newLength = array.Length;
         var newLength = array.Length;
@@ -273,7 +288,7 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
 
 
         Array.Resize(ref array, newLength);
         Array.Resize(ref array, newLength);
 
 
-        using var indexList = new PooledList<(int, LuaValue)>(dictionary.Count);
+        using PooledList<(int, LuaValue)> indexList = new(dictionary.Count);
 
 
         // Move some of the elements of the hash part to a newly allocated array
         // Move some of the elements of the hash part to a newly allocated array
         foreach (var kv in dictionary)
         foreach (var kv in dictionary)
@@ -287,7 +302,7 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
             }
             }
         }
         }
 
 
-        foreach ((var index, var value) in indexList.AsSpan())
+        foreach (var (index, value) in indexList.AsSpan())
         {
         {
             dictionary.Remove(index);
             dictionary.Remove(index);
             array[index - 1] = value;
             array[index - 1] = value;
@@ -335,6 +350,7 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
     public struct LuaTableEnumerator(LuaTable table) : IEnumerator<KeyValuePair<LuaValue, LuaValue>>
     public struct LuaTableEnumerator(LuaTable table) : IEnumerator<KeyValuePair<LuaValue, LuaValue>>
     {
     {
         public KeyValuePair<LuaValue, LuaValue> Current => current;
         public KeyValuePair<LuaValue, LuaValue> Current => current;
+
         int index = -1;
         int index = -1;
         readonly int version = table.dictionary.Version;
         readonly int version = table.dictionary.Version;
         KeyValuePair<LuaValue, LuaValue> current = default;
         KeyValuePair<LuaValue, LuaValue> current = default;
@@ -345,7 +361,7 @@ public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>
             {
             {
                 var arrayIndex = -index - 1;
                 var arrayIndex = -index - 1;
                 var span = table.array.AsSpan(arrayIndex);
                 var span = table.array.AsSpan(arrayIndex);
-                for (int i = 0; i < span.Length; i++)
+                for (var i = 0; i < span.Length; i++)
                 {
                 {
                     if (span[i].Type is not LuaValueType.Nil)
                     if (span[i].Type is not LuaValueType.Nil)
                     {
                     {

+ 11 - 7
src/Lua/LuaThread.cs

@@ -39,13 +39,14 @@ public abstract class LuaThread
 
 
         static LinkedPool<ThreadCoreData> pool;
         static LinkedPool<ThreadCoreData> pool;
         ThreadCoreData? nextNode;
         ThreadCoreData? nextNode;
+
         public ref ThreadCoreData? NextNode => ref nextNode;
         public ref ThreadCoreData? NextNode => ref nextNode;
 
 
         public static ThreadCoreData Create()
         public static ThreadCoreData Create()
         {
         {
-            if (!pool.TryPop(out ThreadCoreData result))
+            if (!pool.TryPop(out var result))
             {
             {
-                result = new ThreadCoreData();
+                result = new();
             }
             }
 
 
             return result;
             return result;
@@ -75,7 +76,9 @@ public abstract class LuaThread
     internal LuaFunction? LastCallerFunction;
     internal LuaFunction? LastCallerFunction;
 
 
     public bool IsRunning => CallStackFrameCount != 0;
     public bool IsRunning => CallStackFrameCount != 0;
+
     internal LuaFunction? Hook { get; set; }
     internal LuaFunction? Hook { get; set; }
+
     public LuaStack Stack => CoreData!.Stack;
     public LuaStack Stack => CoreData!.Stack;
 
 
     internal bool IsCallHookEnabled
     internal bool IsCallHookEnabled
@@ -93,6 +96,7 @@ public abstract class LuaThread
     public int CallStackFrameCount => CoreData == null ? 0 : CoreData!.CallStack.Count;
     public int CallStackFrameCount => CoreData == null ? 0 : CoreData!.CallStack.Count;
 
 
     internal LuaThreadAccess CurrentAccess => new(this, CurrentVersion);
     internal LuaThreadAccess CurrentAccess => new(this, CurrentVersion);
+
     public LuaThreadAccess RootAccess => new(this, 0);
     public LuaThreadAccess RootAccess => new(this, 0);
 
 
     public ref readonly CallStackFrame GetCurrentFrame()
     public ref readonly CallStackFrame GetCurrentFrame()
@@ -124,7 +128,7 @@ public abstract class LuaThread
         ref var callStack = ref CoreData!.CallStack;
         ref var callStack = ref CoreData!.CallStack;
         callStack.Push(frame);
         callStack.Push(frame);
         callStack.PeekRef().Version = CurrentVersion = ++LastVersion;
         callStack.PeekRef().Version = CurrentVersion = ++LastVersion;
-        return new LuaThreadAccess(this, CurrentVersion);
+        return new(this, CurrentVersion);
     }
     }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -202,9 +206,9 @@ public abstract class LuaThread
         HookCount = count > 0 ? count + 1 : 0;
         HookCount = count > 0 ? count + 1 : 0;
         BaseHookCount = count;
         BaseHookCount = count;
 
 
-        IsLineHookEnabled = (mask.Contains('l'));
-        IsCallHookEnabled = (mask.Contains('c'));
-        IsReturnHookEnabled = (mask.Contains('r'));
+        IsLineHookEnabled = mask.Contains('l');
+        IsCallHookEnabled = mask.Contains('c');
+        IsReturnHookEnabled = mask.Contains('r');
 
 
         if (IsLineHookEnabled)
         if (IsLineHookEnabled)
         {
         {
@@ -217,7 +221,7 @@ public abstract class LuaThread
     internal void DumpStackValues()
     internal void DumpStackValues()
     {
     {
         var span = GetStackValues();
         var span = GetStackValues();
-        for (int i = 0; i < span.Length; i++)
+        for (var i = 0; i < span.Length; i++)
         {
         {
             Console.WriteLine($"LuaStack [{i}]\t{span[i]}");
             Console.WriteLine($"LuaStack [{i}]\t{span[i]}");
         }
         }

+ 1 - 1
src/Lua/LuaThreadStatus.cs

@@ -5,5 +5,5 @@ public enum LuaThreadStatus : byte
     Suspended,
     Suspended,
     Normal,
     Normal,
     Running,
     Running,
-    Dead,
+    Dead
 }
 }

+ 6 - 1
src/Lua/LuaTopValuesReader.cs

@@ -14,8 +14,13 @@ public readonly struct LuaTopValuesReader : IDisposable
     }
     }
 
 
     public int Count => stack.Count - returnBase;
     public int Count => stack.Count - returnBase;
+
     public int Length => stack.Count - returnBase;
     public int Length => stack.Count - returnBase;
-    public ReadOnlySpan<LuaValue> AsSpan() => stack.AsSpan()[returnBase..];
+
+    public ReadOnlySpan<LuaValue> AsSpan()
+    {
+        return stack.AsSpan()[returnBase..];
+    }
 
 
     public LuaValue this[int index] => AsSpan()[index];
     public LuaValue this[int index] => AsSpan()[index];
 
 

+ 2 - 1
src/Lua/LuaUserData.cs

@@ -1,9 +1,10 @@
 namespace Lua;
 namespace Lua;
 
 
-internal sealed class LuaUserData : ILuaUserData
+sealed class LuaUserData : ILuaUserData
 {
 {
     public LuaTable? Metatable { get; set; }
     public LuaTable? Metatable { get; set; }
     readonly LuaValue[] userValues = new LuaValue[1];
     readonly LuaValue[] userValues = new LuaValue[1];
+
     public Span<LuaValue> UserValues => userValues;
     public Span<LuaValue> UserValues => userValues;
 
 
     public LuaUserData(LuaValue value, LuaTable? metatable)
     public LuaUserData(LuaValue value, LuaTable? metatable)

+ 3 - 2
src/Lua/LuaUserThread.cs

@@ -6,13 +6,14 @@ public sealed class LuaUserThread : LuaThread, IPoolNode<LuaUserThread>
 {
 {
     static LinkedPool<LuaUserThread> pool;
     static LinkedPool<LuaUserThread> pool;
     LuaUserThread? nextNode;
     LuaUserThread? nextNode;
+
     ref LuaUserThread? IPoolNode<LuaUserThread>.NextNode => ref nextNode;
     ref LuaUserThread? IPoolNode<LuaUserThread>.NextNode => ref nextNode;
 
 
     public static LuaUserThread Create(LuaThread parent)
     public static LuaUserThread Create(LuaThread parent)
     {
     {
-        if (!pool.TryPop(out LuaUserThread result))
+        if (!pool.TryPop(out var result))
         {
         {
-            result = new LuaUserThread();
+            result = new();
         }
         }
 
 
         result.State = parent.State;
         result.State = parent.State;

+ 63 - 12
src/Lua/LuaValue.cs

@@ -16,7 +16,7 @@ public enum LuaValueType : byte
     Thread,
     Thread,
     LightUserData,
     LightUserData,
     UserData,
     UserData,
-    Table,
+    Table
 }
 }
 
 
 [StructLayout(LayoutKind.Auto)]
 [StructLayout(LayoutKind.Auto)]
@@ -28,6 +28,13 @@ public readonly struct LuaValue : IEquatable<LuaValue>
     readonly double value;
     readonly double value;
     readonly object? referenceValue;
     readonly object? referenceValue;
 
 
+    internal LuaValue(LuaValueType type, double value, object? referenceValue)
+    {
+        Type = type;
+        this.value = value;
+        this.referenceValue = referenceValue;
+    }
+
     public bool TryRead<T>(out T result)
     public bool TryRead<T>(out T result)
     {
     {
         var t = typeof(T);
         var t = typeof(T);
@@ -49,14 +56,22 @@ public readonly struct LuaValue : IEquatable<LuaValue>
                 }
                 }
                 else if (t == typeof(int))
                 else if (t == typeof(int))
                 {
                 {
-                    if (!MathEx.IsInteger(value)) break;
+                    if (!MathEx.IsInteger(value))
+                    {
+                        break;
+                    }
+
                     var v = (int)value;
                     var v = (int)value;
                     result = Unsafe.As<int, T>(ref v);
                     result = Unsafe.As<int, T>(ref v);
                     return true;
                     return true;
                 }
                 }
                 else if (t == typeof(long))
                 else if (t == typeof(long))
                 {
                 {
-                    if (!MathEx.IsInteger(value)) break;
+                    if (!MathEx.IsInteger(value))
+                    {
+                        break;
+                    }
+
                     var v = (long)value;
                     var v = (long)value;
                     result = Unsafe.As<long, T>(ref v);
                     result = Unsafe.As<long, T>(ref v);
                     return true;
                     return true;
@@ -302,6 +317,12 @@ public readonly struct LuaValue : IEquatable<LuaValue>
         return Unsafe.As<string>(referenceValue!);
         return Unsafe.As<string>(referenceValue!);
     }
     }
 
 
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    internal object UnsafeReadObject()
+    {
+        return Unsafe.As<object>(referenceValue!);
+    }
+
     bool TryParseToDouble(out double result)
     bool TryParseToDouble(out double result)
     {
     {
         if (Type != LuaValueType.String)
         if (Type != LuaValueType.String)
@@ -354,7 +375,11 @@ public readonly struct LuaValue : IEquatable<LuaValue>
 
 
     public T Read<T>()
     public T Read<T>()
     {
     {
-        if (!TryRead<T>(out var result)) throw new InvalidOperationException($"Cannot convert LuaValueType.{Type} to {typeof(T).FullName}.");
+        if (!TryRead<T>(out var result))
+        {
+            throw new InvalidOperationException($"Cannot convert LuaValueType.{Type} to {typeof(T).FullName}.");
+        }
+
         return result;
         return result;
     }
     }
 
 
@@ -391,8 +416,16 @@ public readonly struct LuaValue : IEquatable<LuaValue>
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public bool ToBoolean()
     public bool ToBoolean()
     {
     {
-        if (Type == LuaValueType.Boolean) return value != 0;
-        if (Type is LuaValueType.Nil) return false;
+        if (Type == LuaValueType.Boolean)
+        {
+            return value != 0;
+        }
+
+        if (Type is LuaValueType.Nil)
+        {
+            return false;
+        }
+
         return true;
         return true;
     }
     }
 
 
@@ -412,13 +445,17 @@ public readonly struct LuaValue : IEquatable<LuaValue>
             int intValue => intValue,
             int intValue => intValue,
             long longValue => longValue,
             long longValue => longValue,
             float floatValue => floatValue,
             float floatValue => floatValue,
-            _ => new LuaValue(obj)
+            _ => new(obj)
         };
         };
     }
     }
 
 
     public static LuaValue FromUserData(ILuaUserData? userData)
     public static LuaValue FromUserData(ILuaUserData? userData)
     {
     {
-        if (userData is null) return Nil;
+        if (userData is null)
+        {
+            return Nil;
+        }
+
         return new(userData);
         return new(userData);
     }
     }
 
 
@@ -529,14 +566,28 @@ public readonly struct LuaValue : IEquatable<LuaValue>
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public bool Equals(LuaValue other)
     public bool Equals(LuaValue other)
     {
     {
-        if (other.Type != Type) return false;
+        if (other.Type != Type)
+        {
+            return false;
+        }
 
 
         return Type switch
         return Type switch
         {
         {
             LuaValueType.Nil => true,
             LuaValueType.Nil => true,
             LuaValueType.Boolean or LuaValueType.Number => other.value == value,
             LuaValueType.Boolean or LuaValueType.Number => other.value == value,
             LuaValueType.String => Unsafe.As<string>(other.referenceValue) == Unsafe.As<string>(referenceValue),
             LuaValueType.String => Unsafe.As<string>(other.referenceValue) == Unsafe.As<string>(referenceValue),
-            _ => other.referenceValue!.Equals(referenceValue)
+            _ => other.referenceValue == referenceValue
+        };
+    }
+
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public bool EqualsForDict(LuaValue other)
+    {
+        return other.Type == Type && Type switch
+        {
+            LuaValueType.Boolean or LuaValueType.Number => other.value == value,
+            LuaValueType.String => Unsafe.As<string>(other.referenceValue) == Unsafe.As<string>(referenceValue),
+            _ => other.referenceValue == referenceValue
         };
         };
     }
     }
 
 
@@ -570,7 +621,7 @@ public readonly struct LuaValue : IEquatable<LuaValue>
             LuaValueType.Table => $"table: {referenceValue!.GetHashCode()}",
             LuaValueType.Table => $"table: {referenceValue!.GetHashCode()}",
             LuaValueType.LightUserData => $"userdata: {referenceValue!.GetHashCode()}",
             LuaValueType.LightUserData => $"userdata: {referenceValue!.GetHashCode()}",
             LuaValueType.UserData => $"userdata: {referenceValue!.GetHashCode()}",
             LuaValueType.UserData => $"userdata: {referenceValue!.GetHashCode()}",
-            _ => "",
+            _ => ""
         };
         };
     }
     }
 
 
@@ -592,7 +643,7 @@ public readonly struct LuaValue : IEquatable<LuaValue>
             LuaValueType.Table => "table",
             LuaValueType.Table => "table",
             LuaValueType.LightUserData => "light userdata",
             LuaValueType.LightUserData => "light userdata",
             LuaValueType.UserData => "userdata",
             LuaValueType.UserData => "userdata",
-            _ => "",
+            _ => ""
         };
         };
     }
     }
 
 

+ 5 - 5
src/Lua/Platforms/LuaPlatform.cs

@@ -15,11 +15,11 @@ public sealed class LuaPlatform(ILuaFileSystem fileSystem, ILuaOsEnvironment osE
     /// Standard console platform implementation.
     /// Standard console platform implementation.
     /// Uses real file system, console I/O, and system operations.
     /// Uses real file system, console I/O, and system operations.
     /// </summary>
     /// </summary>
-    public static LuaPlatform Default => new(
-        fileSystem: new FileSystem(),
-        osEnvironment: new SystemOsEnvironment(),
-        standardIO: new ConsoleStandardIO()
-        , timeProvider: TimeProvider.System);
+    public static LuaPlatform Default =>
+        new(fileSystem: new FileSystem(),
+            osEnvironment: new SystemOsEnvironment(),
+            standardIO: new ConsoleStandardIO(),
+            timeProvider: TimeProvider.System);
 
 
     public ILuaFileSystem FileSystem { get; set; } = fileSystem;
     public ILuaFileSystem FileSystem { get; set; } = fileSystem;
     public ILuaOsEnvironment OsEnvironment { get; set; } = osEnvironment;
     public ILuaOsEnvironment OsEnvironment { get; set; } = osEnvironment;

+ 17 - 18
src/Lua/Platforms/SystemOsEnvironment.cs

@@ -1,26 +1,25 @@
 using System.Diagnostics;
 using System.Diagnostics;
 
 
-namespace Lua.Platforms
+namespace Lua.Platforms;
+
+/// <summary>
+/// Default implementation of ILuaEnvironment
+/// </summary>
+public sealed class SystemOsEnvironment : ILuaOsEnvironment
 {
 {
-    /// <summary>
-    /// Default implementation of ILuaEnvironment
-    /// </summary>
-    public sealed class SystemOsEnvironment : ILuaOsEnvironment
+    public string? GetEnvironmentVariable(string name)
     {
     {
-        public string? GetEnvironmentVariable(string name)
-        {
-            return Environment.GetEnvironmentVariable(name);
-        }
+        return Environment.GetEnvironmentVariable(name);
+    }
 
 
-        public ValueTask Exit(int exitCode, CancellationToken cancellationToken)
-        {
-            Environment.Exit(exitCode);
-            return default;
-        }
+    public ValueTask Exit(int exitCode, CancellationToken cancellationToken)
+    {
+        Environment.Exit(exitCode);
+        return default;
+    }
 
 
-        public double GetTotalProcessorTime()
-        {
-            return Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
-        }
+    public double GetTotalProcessorTime()
+    {
+        return Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
     }
     }
 }
 }

+ 3 - 2
src/Lua/Runtime/CallStackFrame.cs

@@ -11,8 +11,9 @@ public record struct CallStackFrame
     public required int VariableArgumentCount;
     public required int VariableArgumentCount;
     public int CallerInstructionIndex;
     public int CallerInstructionIndex;
     internal CallStackFrameFlags Flags;
     internal CallStackFrameFlags Flags;
-    internal bool IsTailCall => (Flags & CallStackFrameFlags.TailCall) == CallStackFrameFlags.TailCall;
     public int Version;
     public int Version;
+
+    internal bool IsTailCall => (Flags & CallStackFrameFlags.TailCall) == CallStackFrameFlags.TailCall;
 }
 }
 
 
 [Flags]
 [Flags]
@@ -21,5 +22,5 @@ public enum CallStackFrameFlags
     //None = 0,
     //None = 0,
     ReversedLe = 1,
     ReversedLe = 1,
     TailCall = 2,
     TailCall = 2,
-    InHook = 4,
+    InHook = 4
 }
 }

+ 136 - 128
src/Lua/Runtime/Instruction.cs

@@ -9,7 +9,11 @@ public partial struct Instruction(uint value)
 
 
 
 
     public uint Value = value;
     public uint Value = value;
-    public static implicit operator Instruction(uint value) => new(value);
+
+    public static implicit operator Instruction(uint value)
+    {
+        return new(value);
+    }
 
 
     public static ReadOnlySpan<string> OpNames => opNames;
     public static ReadOnlySpan<string> OpNames => opNames;
 
 
@@ -119,15 +123,32 @@ func (i *instruction) setOpCode(op opCode)   { i.setArg(posOp, sizeOp, int(op))
 func (i *instruction) setArg(pos, size uint, arg int) {
 func (i *instruction) setArg(pos, size uint, arg int) {
     *i = *i&mask0(size, pos) | instruction(arg)<<pos&mask1(size, pos)}
     *i = *i&mask0(size, pos) | instruction(arg)<<pos&mask1(size, pos)}
      */
      */
-    public static bool IsConstant(int x) => 0 != (x & BitRK);
-    public static int ConstantIndex(int r) => r & ~BitRK;
-    public static int AsConstant(int r) => r | BitRK;
+    public static bool IsConstant(int x)
+    {
+        return 0 != (x & BitRK);
+    }
+
+    public static int ConstantIndex(int r)
+    {
+        return r & ~BitRK;
+    }
+
+    public static int AsConstant(int r)
+    {
+        return r | BitRK;
+    }
 
 
     // creates a mask with 'n' 1 bits at position 'p'
     // creates a mask with 'n' 1 bits at position 'p'
-    public static uint Mask1(uint n, uint p) => (uint)(~(~0 << (int)n) << (int)p);
+    public static uint Mask1(uint n, uint p)
+    {
+        return (uint)(~(~0 << (int)n) << (int)p);
+    }
 
 
     // creates a mask with 'n' 0 bits at position 'p'
     // creates a mask with 'n' 0 bits at position 'p'
-    public static uint Mask0(uint n, uint p) => (~Mask1(n, p));
+    public static uint Mask0(uint n, uint p)
+    {
+        return ~Mask1(n, p);
+    }
 
 
     public OpCode OpCode
     public OpCode OpCode
     {
     {
@@ -135,11 +156,14 @@ func (i *instruction) setArg(pos, size uint, arg int) {
         set => SetArg(PosOp, SizeOp, (byte)value);
         set => SetArg(PosOp, SizeOp, (byte)value);
     }
     }
 
 
-    public int Arg(uint pos) => (int)((Value >> (int)pos) & Mask1(1, 0));
+    public int Arg(uint pos)
+    {
+        return (int)((Value >> (int)pos) & Mask1(1, 0));
+    }
 
 
     public void SetArg(uint pos, uint size, int arg)
     public void SetArg(uint pos, uint size, int arg)
     {
     {
-        Value = (uint)(Value & Mask0(size, pos) | arg << (int)pos & Mask1(size, pos));
+        Value = (uint)((Value & Mask0(size, pos)) | ((arg << (int)pos) & Mask1(size, pos)));
     }
     }
 
 
 
 
@@ -160,31 +184,31 @@ func (i instruction) sbx() int { return int(i>>posBx&maxArgBx) - maxArgSBx }
 
 
     public int B
     public int B
     {
     {
-        get => (int)(Value >> PosB & MaxArgB);
+        get => (int)((Value >> PosB) & MaxArgB);
         set => SetArg(PosB, SizeB, value);
         set => SetArg(PosB, SizeB, value);
     }
     }
 
 
     public int C
     public int C
     {
     {
-        get => (int)Value >> PosC & MaxArgC;
+        get => ((int)Value >> PosC) & MaxArgC;
         set => SetArg(PosC, SizeC, value);
         set => SetArg(PosC, SizeC, value);
     }
     }
 
 
     public int Bx
     public int Bx
     {
     {
-        get => (int)Value >> PosBx & MaxArgBx;
+        get => ((int)Value >> PosBx) & MaxArgBx;
         set => SetArg(PosBx, SizeBx, value);
         set => SetArg(PosBx, SizeBx, value);
     }
     }
 
 
     public int Ax
     public int Ax
     {
     {
-        get => (int)Value >> PosAx & MaxArgAx;
+        get => ((int)Value >> PosAx) & MaxArgAx;
         set => SetArg(PosAx, SizeAx, value);
         set => SetArg(PosAx, SizeAx, value);
     }
     }
 
 
     public int SBx
     public int SBx
     {
     {
-        get => (int)(Value >> PosBx & MaxArgBx) - MaxArgSBx;
+        get => (int)((Value >> PosBx) & MaxArgBx) - MaxArgSBx;
         set => SetArg(PosBx, SizeBx, value + MaxArgSBx);
         set => SetArg(PosBx, SizeBx, value + MaxArgSBx);
     }
     }
 
 
@@ -206,10 +230,20 @@ func createABx(op opCode, a, bx int) instruction {
 func createAx(op opCode, a int) instruction { return instruction(op)<<posOp | instruction(a)<<posAx }
 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) => (uint)(((byte)op << PosOp) | (a << PosA) | (b << PosB) | (c << PosC));
+    public static uint CreateABC(OpCode op, int a, int b, int c)
+    {
+        return (uint)(((byte)op << PosOp) | (a << PosA) | (b << PosB) | (c << PosC));
+    }
+
+    public static uint CreateABx(OpCode op, int a, int bx)
+    {
+        return (uint)(((byte)op << PosOp) | (a << PosA) | (bx << PosBx));
+    }
 
 
-    public static uint CreateABx(OpCode op, int a, int bx) => (uint)(((byte)op << PosOp) | (a << PosA) | (bx << PosBx));
-    public static uint CreateAx(OpCode op, int a) => (uint)(((byte)op << PosOp) | (a << PosAx));
+    public static uint CreateAx(OpCode op, int a)
+    {
+        return (uint)(((byte)op << PosOp) | (a << PosAx));
+    }
 
 
 
 
     /*
     /*
@@ -255,13 +289,23 @@ func (i instruction) String() string {
             case IABC:
             case IABC:
                 s = $"{s} {A}";
                 s = $"{s} {A}";
                 if (BMode(op) == OpArgK && IsConstant(B))
                 if (BMode(op) == OpArgK && IsConstant(B))
+                {
                     s = $"{s} -{1 + ConstantIndex(B)}";
                     s = $"{s} -{1 + ConstantIndex(B)}";
+                }
                 else if (BMode(op) != OpArgN)
                 else if (BMode(op) != OpArgN)
+                {
                     s = $"{s} {B}";
                     s = $"{s} {B}";
+                }
+
                 if (CMode(op) == OpArgK && IsConstant(C))
                 if (CMode(op) == OpArgK && IsConstant(C))
+                {
                     s = $"{s} -{1 + ConstantIndex(C)}";
                     s = $"{s} -{1 + ConstantIndex(C)}";
+                }
                 else if (CMode(op) != OpArgN)
                 else if (CMode(op) != OpArgN)
+                {
                     s = $"{s} {C}";
                     s = $"{s} {C}";
+                }
+
                 // s = $"{s} {A}";
                 // s = $"{s} {A}";
                 // if (BMode(op) == OpArgK && IsConstant(B))
                 // if (BMode(op) == OpArgK && IsConstant(B))
                 // 	s = $"{s} constant {ConstantIndex(B)}";
                 // 	s = $"{s} constant {ConstantIndex(B)}";
@@ -275,12 +319,17 @@ func (i instruction) String() string {
             case IAsBx:
             case IAsBx:
                 s = $"{s} {A}";
                 s = $"{s} {A}";
                 if (BMode(op) != OpArgN)
                 if (BMode(op) != OpArgN)
+                {
                     s = $"{s} {SBx}";
                     s = $"{s} {SBx}";
+                }
+
                 break;
                 break;
             case IABx:
             case IABx:
                 s = $"{s} {A}";
                 s = $"{s} {A}";
                 if (BMode(op) != OpArgN)
                 if (BMode(op) != OpArgN)
+                {
                     s = $"{s} {Bx}";
                     s = $"{s} {Bx}";
+                }
 
 
                 break;
                 break;
             case IAx:
             case IAx:
@@ -295,7 +344,10 @@ 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) => (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 (
 const (
@@ -319,13 +371,32 @@ func cMode(m opCode) byte     { return (opModes[m] >> 2) & 3 }
 func testAMode(m opCode) bool { return opModes[m]&(1<<6) != 0 }
 func testAMode(m opCode) bool { return opModes[m]&(1<<6) != 0 }
 func testTMode(m opCode) bool { return opModes[m]&(1<<7) != 0 }
 func testTMode(m opCode) bool { return opModes[m]&(1<<7) != 0 }
 */
 */
-    public static int OpMode(OpCode m) => (int)(opModes[(byte)m] & 3);
-    public static byte BMode(OpCode m) => (byte)((opModes[(byte)m] >> 4) & 3);
-    public static byte CMode(OpCode m) => (byte)((opModes[(byte)m] >> 2) & 3);
-    public static bool TestAMode(OpCode m) => (opModes[(byte)m] & (1 << 6)) != 0;
-    public static bool TestTMode(OpCode m) => (opModes[(byte)m] & (1 << 7)) != 0;
+    public static int OpMode(OpCode m)
+    {
+        return (int)(opModes[(byte)m] & 3);
+    }
 
 
-/*
+    public static byte BMode(OpCode m)
+    {
+        return (byte)((opModes[(byte)m] >> 4) & 3);
+    }
+
+    public static byte CMode(OpCode m)
+    {
+        return (byte)((opModes[(byte)m] >> 2) & 3);
+    }
+
+    public static bool TestAMode(OpCode m)
+    {
+        return (opModes[(byte)m] & (1 << 6)) != 0;
+    }
+
+    public static bool TestTMode(OpCode m)
+    {
+        return (opModes[(byte)m] & (1 << 7)) != 0;
+    }
+
+    /*
 var opModes []byte = []byte{
 var opModes []byte = []byte{
 //     T  A    B       C     mode		    opcode
 //     T  A    B       C     mode		    opcode
 opmode(0, 1, opArgR, opArgN, iABC),  // opMove
 opmode(0, 1, opArgR, opArgN, iABC),  // opMove
@@ -370,7 +441,7 @@ opmode(0, 1, opArgU, opArgN, iABC),  // opVarArg
 opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
 opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
 }
 }
  */
  */
-    public static ReadOnlySpan<byte> OpModes => (opModes);
+    public static ReadOnlySpan<byte> OpModes => opModes;
 
 
     static readonly byte[] opModes =
     static readonly byte[] opModes =
     [
     [
@@ -414,7 +485,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
         OpMode(0, 0, OpArgU, OpArgU, IABC), // opSetList
         OpMode(0, 0, OpArgU, OpArgU, IABC), // opSetList
         OpMode(0, 1, OpArgU, OpArgN, IABx), // opClosure
         OpMode(0, 1, OpArgU, OpArgN, IABx), // opClosure
         OpMode(0, 1, OpArgU, OpArgN, IABC), // opVarArg
         OpMode(0, 1, OpArgU, OpArgN, IABC), // opVarArg
-        OpMode(0, 0, OpArgU, OpArgU, IAx), // opExtraArg
+        OpMode(0, 0, OpArgU, OpArgU, IAx) // opExtraArg
     ];
     ];
 
 
     /// <summary>
     /// <summary>
@@ -422,7 +493,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Move(byte a, ushort b)
     public static Instruction Move(byte a, ushort b)
     {
     {
-        return new() { OpCode = OpCode.Move, A = a, B = b, };
+        return new() { OpCode = OpCode.Move, A = a, B = b };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -430,7 +501,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction LoadK(byte a, uint bx)
     public static Instruction LoadK(byte a, uint bx)
     {
     {
-        return new() { OpCode = OpCode.LoadK, A = a, Bx = (int)bx, };
+        return new() { OpCode = OpCode.LoadK, A = a, Bx = (int)bx };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -438,7 +509,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction LoadKX(byte a)
     public static Instruction LoadKX(byte a)
     {
     {
-        return new() { OpCode = OpCode.LoadKX, A = a, };
+        return new() { OpCode = OpCode.LoadKX, A = a };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -447,10 +518,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction LoadBool(byte a, ushort b, ushort c)
     public static Instruction LoadBool(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.LoadBool, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.LoadBool, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -458,7 +526,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction LoadNil(byte a, ushort b)
     public static Instruction LoadNil(byte a, ushort b)
     {
     {
-        return new() { OpCode = OpCode.LoadNil, A = a, B = b, };
+        return new() { OpCode = OpCode.LoadNil, A = a, B = b };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -466,7 +534,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction GetUpVal(byte a, ushort b)
     public static Instruction GetUpVal(byte a, ushort b)
     {
     {
-        return new() { OpCode = OpCode.GetUpVal, A = a, B = b, };
+        return new() { OpCode = OpCode.GetUpVal, A = a, B = b };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -474,10 +542,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction GetTabUp(byte a, ushort b, ushort c)
     public static Instruction GetTabUp(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.GetTabUp, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.GetTabUp, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -485,10 +550,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction GetTable(byte a, ushort b, ushort c)
     public static Instruction GetTable(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.GetTable, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.GetTable, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -496,7 +558,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction SetUpVal(byte a, ushort b)
     public static Instruction SetUpVal(byte a, ushort b)
     {
     {
-        return new() { OpCode = OpCode.SetUpVal, A = a, B = b, };
+        return new() { OpCode = OpCode.SetUpVal, A = a, B = b };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -504,10 +566,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction SetTabUp(byte a, ushort b, ushort c)
     public static Instruction SetTabUp(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.SetTabUp, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.SetTabUp, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -515,10 +574,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction SetTable(byte a, ushort b, ushort c)
     public static Instruction SetTable(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.SetTable, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.SetTable, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -526,10 +582,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction NewTable(byte a, ushort b, ushort c)
     public static Instruction NewTable(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.NewTable, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.NewTable, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -537,10 +590,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Self(byte a, ushort b, ushort c)
     public static Instruction Self(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Self, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Self, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -548,10 +598,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Add(byte a, ushort b, ushort c)
     public static Instruction Add(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Add, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Add, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -559,10 +606,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Sub(byte a, ushort b, ushort c)
     public static Instruction Sub(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Sub, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Sub, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -570,10 +614,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Mul(byte a, ushort b, ushort c)
     public static Instruction Mul(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Mul, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Mul, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -581,10 +622,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Div(byte a, ushort b, ushort c)
     public static Instruction Div(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Div, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Div, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -592,10 +630,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Mod(byte a, ushort b, ushort c)
     public static Instruction Mod(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Mod, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Mod, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -603,10 +638,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Pow(byte a, ushort b, ushort c)
     public static Instruction Pow(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Pow, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Pow, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -614,7 +646,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Unm(byte a, ushort b)
     public static Instruction Unm(byte a, ushort b)
     {
     {
-        return new() { OpCode = OpCode.Unm, A = a, B = b, };
+        return new() { OpCode = OpCode.Unm, A = a, B = b };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -622,7 +654,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Not(byte a, ushort b)
     public static Instruction Not(byte a, ushort b)
     {
     {
-        return new() { OpCode = OpCode.Not, A = a, B = b, };
+        return new() { OpCode = OpCode.Not, A = a, B = b };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -630,7 +662,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Len(byte a, ushort b)
     public static Instruction Len(byte a, ushort b)
     {
     {
-        return new() { OpCode = OpCode.Len, A = a, B = b, };
+        return new() { OpCode = OpCode.Len, A = a, B = b };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -638,10 +670,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Concat(byte a, ushort b, ushort c)
     public static Instruction Concat(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Concat, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Concat, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -650,7 +679,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Jmp(byte a, int sBx)
     public static Instruction Jmp(byte a, int sBx)
     {
     {
-        return new() { OpCode = OpCode.Jmp, A = a, SBx = sBx, };
+        return new() { OpCode = OpCode.Jmp, A = a, SBx = sBx };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -658,10 +687,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Eq(byte a, ushort b, ushort c)
     public static Instruction Eq(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Eq, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Eq, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -669,10 +695,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Lt(byte a, ushort b, ushort c)
     public static Instruction Lt(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Lt, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Lt, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -680,10 +703,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Le(byte a, ushort b, ushort c)
     public static Instruction Le(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Le, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Le, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -691,7 +711,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Test(byte a, ushort c)
     public static Instruction Test(byte a, ushort c)
     {
     {
-        return new() { OpCode = OpCode.Test, A = a, C = c, };
+        return new() { OpCode = OpCode.Test, A = a, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -699,10 +719,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction TestSet(byte a, ushort b, ushort c)
     public static Instruction TestSet(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.TestSet, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.TestSet, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -710,10 +727,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Call(byte a, ushort b, ushort c)
     public static Instruction Call(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.Call, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.Call, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -721,10 +735,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction TailCall(byte a, ushort b, ushort c)
     public static Instruction TailCall(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.TailCall, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.TailCall, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -732,7 +743,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Return(byte a, ushort b)
     public static Instruction Return(byte a, ushort b)
     {
     {
-        return new() { OpCode = OpCode.Return, A = a, B = b, };
+        return new() { OpCode = OpCode.Return, A = a, B = b };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -741,7 +752,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction ForLoop(byte a, int sBx)
     public static Instruction ForLoop(byte a, int sBx)
     {
     {
-        return new() { OpCode = OpCode.ForLoop, A = a, SBx = sBx, };
+        return new() { OpCode = OpCode.ForLoop, A = a, SBx = sBx };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -750,7 +761,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction ForPrep(byte a, int sBx)
     public static Instruction ForPrep(byte a, int sBx)
     {
     {
-        return new() { OpCode = OpCode.ForPrep, A = a, SBx = sBx, };
+        return new() { OpCode = OpCode.ForPrep, A = a, SBx = sBx };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -758,7 +769,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction TForCall(byte a, ushort c)
     public static Instruction TForCall(byte a, ushort c)
     {
     {
-        return new() { OpCode = OpCode.TForCall, A = a, C = c, };
+        return new() { OpCode = OpCode.TForCall, A = a, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -766,7 +777,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction TForLoop(byte a, int sBx)
     public static Instruction TForLoop(byte a, int sBx)
     {
     {
-        return new() { OpCode = OpCode.TForLoop, A = a, SBx = sBx, };
+        return new() { OpCode = OpCode.TForLoop, A = a, SBx = sBx };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -774,10 +785,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction SetList(byte a, ushort b, ushort c)
     public static Instruction SetList(byte a, ushort b, ushort c)
     {
     {
-        return new()
-        {
-            OpCode = OpCode.SetList, A = a, B = b, C = c,
-        };
+        return new() { OpCode = OpCode.SetList, A = a, B = b, C = c };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -785,7 +793,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction Closure(byte a, int sBx)
     public static Instruction Closure(byte a, int sBx)
     {
     {
-        return new() { OpCode = OpCode.Closure, A = a, SBx = sBx, };
+        return new() { OpCode = OpCode.Closure, A = a, SBx = sBx };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -793,7 +801,7 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction VarArg(byte a, ushort b)
     public static Instruction VarArg(byte a, ushort b)
     {
     {
-        return new() { OpCode = OpCode.VarArg, A = a, B = b, };
+        return new() { OpCode = OpCode.VarArg, A = a, B = b };
     }
     }
 
 
     /// <summary>
     /// <summary>
@@ -801,6 +809,6 @@ opmode(0, 0, opArgU, opArgU, iAx),   // opExtraArg
     /// </summary>
     /// </summary>
     public static Instruction ExtraArg(uint ax)
     public static Instruction ExtraArg(uint ax)
     {
     {
-        return new() { OpCode = OpCode.ExtraArg, Ax = (int)ax, };
+        return new() { OpCode = OpCode.ExtraArg, Ax = (int)ax };
     }
     }
 }
 }

+ 14 - 15
src/Lua/Runtime/Lease.cs

@@ -1,22 +1,21 @@
-namespace Lua.Runtime
+namespace Lua.Runtime;
+
+public readonly struct UserThreadLease(LuaUserThread thread) : IDisposable
 {
 {
-    public readonly struct UserThreadLease(LuaUserThread thread) : IDisposable
-    {
-        public LuaUserThread Thread { get; } = thread;
+    public LuaUserThread Thread { get; } = thread;
 
 
-        public void Dispose()
-        {
-            Thread.Release();
-        }
+    public void Dispose()
+    {
+        Thread.Release();
     }
     }
+}
 
 
-    public readonly struct CoroutineLease(LuaCoroutine thread) : IDisposable
-    {
-        public LuaCoroutine Thread { get; } = thread;
+public readonly struct CoroutineLease(LuaCoroutine thread) : IDisposable
+{
+    public LuaCoroutine Thread { get; } = thread;
 
 
-        public void Dispose()
-        {
-            Thread.Release();
-        }
+    public void Dispose()
+    {
+        Thread.Release();
     }
     }
 }
 }

+ 7 - 3
src/Lua/Runtime/LuaClosure.cs

@@ -27,7 +27,7 @@ public sealed class LuaClosure : LuaFunction
         var baseIndex = thread.GetCallStackFrames()[^1].Base;
         var baseIndex = thread.GetCallStackFrames()[^1].Base;
 
 
         // add upvalues
         // add upvalues
-        for (int i = 0; i < proto.UpValues.Length; i++)
+        for (var i = 0; i < proto.UpValues.Length; i++)
         {
         {
             var description = proto.UpValues[i];
             var description = proto.UpValues[i];
             var upValue = GetUpValueFromDescription(thread.State, thread, description, baseIndex);
             var upValue = GetUpValueFromDescription(thread.State, thread, description, baseIndex);
@@ -38,7 +38,11 @@ public sealed class LuaClosure : LuaFunction
     public Prototype Proto { get; }
     public Prototype Proto { get; }
 
 
     public ReadOnlySpan<UpValue> UpValues => upValues.AsSpan();
     public ReadOnlySpan<UpValue> UpValues => upValues.AsSpan();
-    internal Span<UpValue> GetUpValuesSpan() => upValues.AsSpan();
+
+    internal Span<UpValue> GetUpValuesSpan()
+    {
+        return upValues.AsSpan();
+    }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     internal LuaValue GetUpValue(int index)
     internal LuaValue GetUpValue(int index)
@@ -76,6 +80,6 @@ public sealed class LuaClosure : LuaFunction
             return parentClosure.UpValues[description.Index];
             return parentClosure.UpValues[description.Index];
         }
         }
 
 
-        throw new Exception();
+        throw new();
     }
     }
 }
 }

+ 27 - 8
src/Lua/Runtime/LuaStack.cs

@@ -17,7 +17,10 @@ public sealed class LuaStack(int initialSize = 256)
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public void EnsureCapacity(int newSize)
     public void EnsureCapacity(int newSize)
     {
     {
-        if (array.Length >= newSize) return;
+        if (array.Length >= newSize)
+        {
+            return;
+        }
 
 
         Resize(ref array, newSize);
         Resize(ref array, newSize);
         return;
         return;
@@ -42,7 +45,10 @@ public sealed class LuaStack(int initialSize = 256)
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public void NotifyTop(int top)
     public void NotifyTop(int top)
     {
     {
-        if (this.top < top) this.top = top;
+        if (this.top < top)
+        {
+            this.top = top;
+        }
     }
     }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -64,7 +70,11 @@ public sealed class LuaStack(int initialSize = 256)
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public LuaValue Pop()
     public LuaValue Pop()
     {
     {
-        if (top == 0) ThrowEmptyStack();
+        if (top == 0)
+        {
+            ThrowEmptyStack();
+        }
+
         top--;
         top--;
         var item = array[top];
         var item = array[top];
         array[top] = default;
         array[top] = default;
@@ -75,7 +85,10 @@ public sealed class LuaStack(int initialSize = 256)
     public void Pop(int count)
     public void Pop(int count)
     {
     {
         var newSize = top - count;
         var newSize = top - count;
-        if (newSize >= top) return;
+        if (newSize >= top)
+        {
+            return;
+        }
 
 
         array.AsSpan(newSize, top - newSize).Clear();
         array.AsSpan(newSize, top - newSize).Clear();
         top = newSize;
         top = newSize;
@@ -84,7 +97,10 @@ public sealed class LuaStack(int initialSize = 256)
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public void PopUntil(int newSize)
     public void PopUntil(int newSize)
     {
     {
-        if (newSize >= top) return;
+        if (newSize >= top)
+        {
+            return;
+        }
 
 
         array.AsSpan(newSize, top - newSize).Clear();
         array.AsSpan(newSize, top - newSize).Clear();
         top = newSize;
         top = newSize;
@@ -100,7 +116,7 @@ public sealed class LuaStack(int initialSize = 256)
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public Span<LuaValue> AsSpan()
     public Span<LuaValue> AsSpan()
     {
     {
-        return new Span<LuaValue>(array, 0, top);
+        return new(array, 0, top);
     }
     }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -140,7 +156,10 @@ public sealed class LuaStack(int initialSize = 256)
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     internal ref LuaValue GetWithNotifyTop(int index)
     internal ref LuaValue GetWithNotifyTop(int index)
     {
     {
-        if (this.top <= index) this.top = index + 1;
+        if (top <= index)
+        {
+            top = index + 1;
+        }
 #if NET6_0_OR_GREATER
 #if NET6_0_OR_GREATER
         return ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), index);
         return ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), index);
 #else
 #else
@@ -154,7 +173,7 @@ public sealed class LuaStack(int initialSize = 256)
     }
     }
 
 
     [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
     [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
-    private Span<LuaValue> Span => AsSpan();
+    Span<LuaValue> Span => AsSpan();
 
 
     internal void SetTop(int top)
     internal void SetTop(int top)
     {
     {

+ 5 - 5
src/Lua/Runtime/LuaThreadAccess.cs

@@ -71,18 +71,18 @@ public readonly struct LuaThreadAccess
             argumentCount -= varArgumentCount;
             argumentCount -= varArgumentCount;
         }
         }
 
 
-        var frame = new CallStackFrame { Base = thread.Stack.Count - argumentCount, VariableArgumentCount = varArgumentCount, Function = function, ReturnBase = returnBase };
+        CallStackFrame frame = new() { Base = thread.Stack.Count - argumentCount, VariableArgumentCount = varArgumentCount, Function = function, ReturnBase = returnBase };
         if (thread.IsInHook)
         if (thread.IsInHook)
         {
         {
             frame.Flags |= CallStackFrameFlags.InHook;
             frame.Flags |= CallStackFrameFlags.InHook;
         }
         }
 
 
         var access = thread.PushCallStackFrame(frame);
         var access = thread.PushCallStackFrame(frame);
-        LuaFunctionExecutionContext context = new() { Access = access, ArgumentCount = argumentCount, ReturnFrameBase = returnBase, };
+        LuaFunctionExecutionContext context = new() { Access = access, ArgumentCount = argumentCount, ReturnFrameBase = returnBase };
         var callStackTop = thread.CallStackFrameCount;
         var callStackTop = thread.CallStackFrameCount;
         try
         try
         {
         {
-            if (this.Thread.CallOrReturnHookMask.Value != 0 && !this.Thread.IsInHook)
+            if (Thread.CallOrReturnHookMask.Value != 0 && !Thread.IsInHook)
             {
             {
                 return await LuaVirtualMachine.ExecuteCallHook(context, cancellationToken);
                 return await LuaVirtualMachine.ExecuteCallHook(context, cancellationToken);
             }
             }
@@ -91,7 +91,7 @@ public readonly struct LuaThreadAccess
         }
         }
         finally
         finally
         {
         {
-            this.Thread.PopCallStackFrameUntil(callStackTop - 1);
+            Thread.PopCallStackFrameUntil(callStackTop - 1);
         }
         }
     }
     }
 
 
@@ -114,7 +114,7 @@ public readonly struct LuaThreadAccess
             }
             }
         }
         }
 
 
-        var frame = new CallStackFrame
+        CallStackFrame frame = new()
         {
         {
             Base = thread.Stack.Count - argumentCount,
             Base = thread.Stack.Count - argumentCount,
             VariableArgumentCount = varArgumentCount,
             VariableArgumentCount = varArgumentCount,

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

@@ -97,7 +97,7 @@ public static class LuaThreadAccessAccessExtensions
     {
     {
         access.ThrowIfInvalid();
         access.ThrowIfInvalid();
         var stack = access.Stack;
         var stack = access.Stack;
-        return new LuaTopValuesReader(stack, stack.Count - argumentCount);
+        return new(stack, stack.Count - argumentCount);
     }
     }
 
 
     public static ValueTask<LuaValue> Add(this LuaThreadAccess access, LuaValue x, LuaValue y, CancellationToken cancellationToken = default)
     public static ValueTask<LuaValue> Add(this LuaThreadAccess access, LuaValue x, LuaValue y, CancellationToken cancellationToken = default)

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

@@ -2,7 +2,7 @@ using System.Runtime.CompilerServices;
 
 
 namespace Lua.Runtime;
 namespace Lua.Runtime;
 
 
-internal static class LuaRuntimeExtensions
+static class LuaRuntimeExtensions
 {
 {
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public static bool TryGetMetamethod(this LuaValue value, LuaState state, string methodName, out LuaValue result)
     public static bool TryGetMetamethod(this LuaValue value, LuaState state, string methodName, out LuaValue result)

+ 7 - 7
src/Lua/Runtime/LuaVirtualMachine.Debug.cs

@@ -24,7 +24,7 @@ public static partial class LuaVirtualMachine
 
 
         static async ValueTask<int> Impl(VirtualMachineExecutionContext context)
         static async ValueTask<int> Impl(VirtualMachineExecutionContext context)
         {
         {
-            bool countHookIsDone = false;
+            var countHookIsDone = false;
             var pc = context.Pc;
             var pc = context.Pc;
             var prototype = context.Prototype;
             var prototype = context.Prototype;
             if (context.Thread.HookCount == 0)
             if (context.Thread.HookCount == 0)
@@ -40,7 +40,7 @@ public static partial class LuaVirtualMachine
                 context.Thread.IsInHook = true;
                 context.Thread.IsInHook = true;
                 var frame = context.Thread.CurrentAccess.CreateCallStackFrame(hook, 2, top, pc);
                 var frame = context.Thread.CurrentAccess.CreateCallStackFrame(hook, 2, top, pc);
                 var access = context.Thread.PushCallStackFrame(frame);
                 var access = context.Thread.PushCallStackFrame(frame);
-                var funcContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = stack.Count - frame.Base, ReturnFrameBase = frame.ReturnBase };
+                LuaFunctionExecutionContext funcContext = new() { Access = access, ArgumentCount = stack.Count - frame.Base, ReturnFrameBase = frame.ReturnBase };
                 await hook.Func(funcContext, context.CancellationToken);
                 await hook.Func(funcContext, context.CancellationToken);
                 context.Thread.IsInHook = false;
                 context.Thread.IsInHook = false;
 
 
@@ -69,7 +69,7 @@ public static partial class LuaVirtualMachine
                     context.Thread.IsInHook = true;
                     context.Thread.IsInHook = true;
                     var frame = context.Thread.CurrentAccess.CreateCallStackFrame(hook, 2, top, pc);
                     var frame = context.Thread.CurrentAccess.CreateCallStackFrame(hook, 2, top, pc);
                     var access = context.Thread.PushCallStackFrame(frame);
                     var access = context.Thread.PushCallStackFrame(frame);
-                    var funcContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = stack.Count - frame.Base, ReturnFrameBase = frame.ReturnBase };
+                    LuaFunctionExecutionContext funcContext = new() { Access = access, ArgumentCount = stack.Count - frame.Base, ReturnFrameBase = frame.ReturnBase };
                     try
                     try
                     {
                     {
                         await hook.Func(funcContext, context.CancellationToken);
                         await hook.Func(funcContext, context.CancellationToken);
@@ -109,13 +109,13 @@ public static partial class LuaVirtualMachine
         if (context.Thread.IsCallHookEnabled)
         if (context.Thread.IsCallHookEnabled)
         {
         {
             var top = stack.Count;
             var top = stack.Count;
-            stack.Push((isTailCall ? "tail call" : "call"));
+            stack.Push(isTailCall ? "tail call" : "call");
 
 
             stack.Push(LuaValue.Nil);
             stack.Push(LuaValue.Nil);
             context.Thread.IsInHook = true;
             context.Thread.IsInHook = true;
             var frame = context.Thread.CurrentAccess.CreateCallStackFrame(hook, 2, top, 0);
             var frame = context.Thread.CurrentAccess.CreateCallStackFrame(hook, 2, top, 0);
             var access = context.Thread.PushCallStackFrame(frame);
             var access = context.Thread.PushCallStackFrame(frame);
-            var funcContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = stack.Count - frame.Base, ReturnFrameBase = frame.ReturnBase };
+            LuaFunctionExecutionContext funcContext = new() { Access = access, ArgumentCount = stack.Count - frame.Base, ReturnFrameBase = frame.ReturnBase };
             try
             try
             {
             {
                 await hook.Func(funcContext, cancellationToken);
                 await hook.Func(funcContext, cancellationToken);
@@ -131,7 +131,7 @@ public static partial class LuaVirtualMachine
 
 
         {
         {
             var frame = context.Thread.GetCurrentFrame();
             var frame = context.Thread.GetCurrentFrame();
-            var task = frame.Function.Func(new() { Access = context.Thread.CurrentAccess, ArgumentCount = argCount, ReturnFrameBase = frame.ReturnBase, }, cancellationToken);
+            var task = frame.Function.Func(new() { Access = context.Thread.CurrentAccess, ArgumentCount = argCount, ReturnFrameBase = frame.ReturnBase }, cancellationToken);
             var r = await task;
             var r = await task;
             if (isTailCall || !context.Thread.IsReturnHookEnabled)
             if (isTailCall || !context.Thread.IsReturnHookEnabled)
             {
             {
@@ -145,7 +145,7 @@ public static partial class LuaVirtualMachine
             context.Thread.IsInHook = true;
             context.Thread.IsInHook = true;
             frame = context.Thread.CurrentAccess.CreateCallStackFrame(hook, 2, top, 0);
             frame = context.Thread.CurrentAccess.CreateCallStackFrame(hook, 2, top, 0);
             var access = context.Thread.PushCallStackFrame(frame);
             var access = context.Thread.PushCallStackFrame(frame);
-            var funcContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = stack.Count - frame.Base, ReturnFrameBase = frame.ReturnBase };
+            LuaFunctionExecutionContext funcContext = new() { Access = access, ArgumentCount = stack.Count - frame.Base, ReturnFrameBase = frame.ReturnBase };
             try
             try
             {
             {
                 context.Thread.IsInHook = true;
                 context.Thread.IsInHook = true;

+ 174 - 64
src/Lua/Runtime/LuaVirtualMachine.cs

@@ -22,7 +22,7 @@ public static partial class LuaVirtualMachine
         {
         {
             if (!pool.TryPop(out var executionContext))
             if (!pool.TryPop(out var executionContext))
             {
             {
-                executionContext = new VirtualMachineExecutionContext();
+                executionContext = new();
             }
             }
 
 
             executionContext.Init(thread, frame, cancellationToken);
             executionContext.Init(thread, frame, cancellationToken);
@@ -50,10 +50,13 @@ public static partial class LuaVirtualMachine
         }
         }
 
 
         public LuaState State => Thread.State;
         public LuaState State => Thread.State;
+
         public LuaStack Stack = default!;
         public LuaStack Stack = default!;
         public LuaClosure LuaClosure = default!;
         public LuaClosure LuaClosure = default!;
         public LuaThread Thread = default!;
         public LuaThread Thread = default!;
+
         public Prototype Prototype => LuaClosure.Proto;
         public Prototype Prototype => LuaClosure.Proto;
+
         public int FrameBase;
         public int FrameBase;
         public int VariableArgumentCount;
         public int VariableArgumentCount;
         public CancellationToken CancellationToken;
         public CancellationToken CancellationToken;
@@ -62,6 +65,7 @@ public static partial class LuaVirtualMachine
         public int CurrentReturnFrameBase;
         public int CurrentReturnFrameBase;
         public ValueTask<int> Task;
         public ValueTask<int> Task;
         public int LastHookPc;
         public int LastHookPc;
+
         public bool IsTopLevel => BaseCallStackCount == Thread.CallStackFrameCount;
         public bool IsTopLevel => BaseCallStackCount == Thread.CallStackFrameCount;
 
 
         public int BaseCallStackCount;
         public int BaseCallStackCount;
@@ -71,6 +75,7 @@ public static partial class LuaVirtualMachine
         static LinkedPool<VirtualMachineExecutionContext> pool;
         static LinkedPool<VirtualMachineExecutionContext> pool;
 
 
         VirtualMachineExecutionContext? nextNode;
         VirtualMachineExecutionContext? nextNode;
+
         ref VirtualMachineExecutionContext? IPoolNode<VirtualMachineExecutionContext>.NextNode => ref nextNode;
         ref VirtualMachineExecutionContext? IPoolNode<VirtualMachineExecutionContext>.NextNode => ref nextNode;
 
 
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -78,7 +83,11 @@ public static partial class LuaVirtualMachine
         {
         {
             var count = instruction.B - 1;
             var count = instruction.B - 1;
             var src = instruction.A + frameBase;
             var src = instruction.A + frameBase;
-            if (count == -1) count = Stack.Count - src;
+            if (count == -1)
+            {
+                count = Stack.Count - src;
+            }
+
             return PopFromBuffer(src, count);
             return PopFromBuffer(src, count);
         }
         }
 
 
@@ -189,7 +198,7 @@ public static partial class LuaVirtualMachine
         public void Push(in CallStackFrame frame)
         public void Push(in CallStackFrame frame)
         {
         {
             Pc = -1;
             Pc = -1;
-            LuaClosure = (LuaClosure)(frame.Function);
+            LuaClosure = (LuaClosure)frame.Function;
             FrameBase = frame.Base;
             FrameBase = frame.Base;
             CurrentReturnFrameBase = frame.ReturnBase;
             CurrentReturnFrameBase = frame.ReturnBase;
             VariableArgumentCount = frame.VariableArgumentCount;
             VariableArgumentCount = frame.VariableArgumentCount;
@@ -198,7 +207,11 @@ public static partial class LuaVirtualMachine
         public void PopOnTopCallStackFrames()
         public void PopOnTopCallStackFrames()
         {
         {
             var count = Thread.CallStackFrameCount;
             var count = Thread.CallStackFrameCount;
-            if (count == BaseCallStackCount) return;
+            if (count == BaseCallStackCount)
+            {
+                return;
+            }
+
             Thread.PopCallStackFrameUntil(BaseCallStackCount);
             Thread.PopCallStackFrameUntil(BaseCallStackCount);
         }
         }
 
 
@@ -293,7 +306,11 @@ public static partial class LuaVirtualMachine
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public void ThrowIfCancellationRequested()
         public void ThrowIfCancellationRequested()
         {
         {
-            if (!CancellationToken.IsCancellationRequested) return;
+            if (!CancellationToken.IsCancellationRequested)
+            {
+                return;
+            }
+
             Throw();
             Throw();
 
 
             void Throw()
             void Throw()
@@ -313,7 +330,7 @@ public static partial class LuaVirtualMachine
         TailCall,
         TailCall,
         Self,
         Self,
         Compare,
         Compare,
-        DontPop,
+        DontPop
     }
     }
 
 
     internal static ValueTask<int> ExecuteClosureAsync(LuaThread thread, CancellationToken cancellationToken)
     internal static ValueTask<int> ExecuteClosureAsync(LuaThread thread, CancellationToken cancellationToken)
@@ -340,8 +357,8 @@ public static partial class LuaVirtualMachine
             var stack = context.Stack;
             var stack = context.Stack;
             stack.EnsureCapacity(frameBase + context.Prototype.MaxStackSize);
             stack.EnsureCapacity(frameBase + context.Prototype.MaxStackSize);
             ref var constHead = ref MemoryMarshalEx.UnsafeElementAt(context.Prototype.Constants, 0);
             ref var constHead = ref MemoryMarshalEx.UnsafeElementAt(context.Prototype.Constants, 0);
-            ref var lineHookFlag = ref (context.Thread.IsInHook ? ref DummyLineHookEnabled : ref context.Thread.IsLineHookEnabled);
-            ref var hookCount = ref (context.Thread.IsInHook ? ref DummyHookCount : ref context.Thread.HookCount);
+            ref var lineHookFlag = ref context.Thread.IsInHook ? ref DummyLineHookEnabled : ref context.Thread.IsLineHookEnabled;
+            ref var hookCount = ref context.Thread.IsInHook ? ref DummyHookCount : ref context.Thread.HookCount;
             goto Loop;
             goto Loop;
         LineHook:
         LineHook:
 
 
@@ -363,7 +380,7 @@ public static partial class LuaVirtualMachine
             {
             {
                 var instruction = Unsafe.Add(ref instructionsHead, ++context.Pc);
                 var instruction = Unsafe.Add(ref instructionsHead, ++context.Pc);
                 context.Instruction = instruction;
                 context.Instruction = instruction;
-                if (--hookCount == 0 || (lineHookFlag && (context.Pc != context.LastHookPc)))
+                if (--hookCount == 0 || (lineHookFlag && context.Pc != context.LastHookPc))
                 {
                 {
                     goto LineHook;
                     goto LineHook;
                 }
                 }
@@ -390,13 +407,22 @@ public static partial class LuaVirtualMachine
                     case OpCode.LoadBool:
                     case OpCode.LoadBool:
                         Markers.LoadBool();
                         Markers.LoadBool();
                         stack.GetWithNotifyTop(iA + frameBase) = instruction.B != 0;
                         stack.GetWithNotifyTop(iA + frameBase) = instruction.B != 0;
-                        if (instruction.C != 0) context.Pc++;
+                        if (instruction.C != 0)
+                        {
+                            context.Pc++;
+                        }
+
                         continue;
                         continue;
                     case OpCode.LoadNil:
                     case OpCode.LoadNil:
                         Markers.LoadNil();
                         Markers.LoadNil();
                         var ra1 = iA + frameBase + 1;
                         var ra1 = iA + frameBase + 1;
                         var iB = instruction.B;
                         var iB = instruction.B;
-                        stack.GetBuffer().Slice(ra1 - 1, iB + 1).Clear();
+                        stackHead = ref stack.FastGet(ra1 - 1);
+                        for (var i = 0; i <= iB; i++)
+                        {
+                            Unsafe.Add(ref stackHead, ra1 + i) = LuaValue.Nil;
+                        }
+
                         stack.NotifyTop(ra1 + iB);
                         stack.NotifyTop(ra1 + iB);
                         continue;
                         continue;
                     case OpCode.GetUpVal:
                     case OpCode.GetUpVal:
@@ -409,11 +435,15 @@ public static partial class LuaVirtualMachine
                         Markers.GetTable();
                         Markers.GetTable();
                         stackHead = ref stack.FastGet(frameBase);
                         stackHead = ref stack.FastGet(frameBase);
                         ref readonly var vc = ref RKC(ref stackHead, ref constHead, instruction);
                         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));
+                        ref readonly var vb = ref instruction.OpCode == OpCode.GetTable ? ref Unsafe.Add(ref stackHead, instruction.B) : ref context.LuaClosure.GetUpValueRef(instruction.B);
                         var doRestart = false;
                         var doRestart = false;
-                        if (vb.TryReadTable(out var luaTable) && luaTable.TryGetValue(vc, out var resultValue) || GetTableValueSlowPath(vb, vc, context, out resultValue, out doRestart))
+                        if ((vb.TryReadTable(out var luaTable) && luaTable.TryGetValue(vc, out var resultValue)) || GetTableValueSlowPath(vb, vc, context, out resultValue, out doRestart))
                         {
                         {
-                            if (doRestart) goto Restart;
+                            if (doRestart)
+                            {
+                                goto Restart;
+                            }
+
                             stack.GetWithNotifyTop(instruction.A + frameBase) = resultValue;
                             stack.GetWithNotifyTop(instruction.A + frameBase) = resultValue;
                             continue;
                             continue;
                         }
                         }
@@ -449,7 +479,11 @@ public static partial class LuaVirtualMachine
                         vc = ref RKC(ref stackHead, ref constHead, instruction);
                         vc = ref RKC(ref stackHead, ref constHead, instruction);
                         if (SetTableValueSlowPath(table, vb, vc, context, out doRestart))
                         if (SetTableValueSlowPath(table, vb, vc, context, out doRestart))
                         {
                         {
-                            if (doRestart) goto Restart;
+                            if (doRestart)
+                            {
+                                goto Restart;
+                            }
+
                             continue;
                             continue;
                         }
                         }
 
 
@@ -471,7 +505,11 @@ public static partial class LuaVirtualMachine
                         doRestart = false;
                         doRestart = false;
                         if ((table.TryReadTable(out luaTable) && luaTable.TryGetValue(vc, out resultValue)) || GetTableValueSlowPath(table, vc, context, out resultValue, out doRestart))
                         if ((table.TryReadTable(out luaTable) && luaTable.TryGetValue(vc, out resultValue)) || GetTableValueSlowPath(table, vc, context, out resultValue, out doRestart))
                         {
                         {
-                            if (doRestart) goto Restart;
+                            if (doRestart)
+                            {
+                                goto Restart;
+                            }
+
                             Unsafe.Add(ref stackHead, iA) = resultValue;
                             Unsafe.Add(ref stackHead, iA) = resultValue;
                             Unsafe.Add(ref stackHead, iA + 1) = table;
                             Unsafe.Add(ref stackHead, iA + 1) = table;
                             stack.NotifyTop(iA + frameBase + 2);
                             stack.NotifyTop(iA + frameBase + 2);
@@ -538,7 +576,11 @@ public static partial class LuaVirtualMachine
 
 
                         if (ExecuteBinaryOperationMetaMethod(vb, vc, context, opCode, out doRestart))
                         if (ExecuteBinaryOperationMetaMethod(vb, vc, context, opCode, out doRestart))
                         {
                         {
-                            if (doRestart) goto Restart;
+                            if (doRestart)
+                            {
+                                goto Restart;
+                            }
+
                             continue;
                             continue;
                         }
                         }
 
 
@@ -558,7 +600,11 @@ public static partial class LuaVirtualMachine
 
 
                         if (ExecuteUnaryOperationMetaMethod(vb, context, OpCode.Unm, out doRestart))
                         if (ExecuteUnaryOperationMetaMethod(vb, context, OpCode.Unm, out doRestart))
                         {
                         {
-                            if (doRestart) goto Restart;
+                            if (doRestart)
+                            {
+                                goto Restart;
+                            }
+
                             continue;
                             continue;
                         }
                         }
 
 
@@ -585,7 +631,11 @@ public static partial class LuaVirtualMachine
 
 
                         if (ExecuteUnaryOperationMetaMethod(vb, context, OpCode.Len, out doRestart))
                         if (ExecuteUnaryOperationMetaMethod(vb, context, OpCode.Len, out doRestart))
                         {
                         {
-                            if (doRestart) goto Restart;
+                            if (doRestart)
+                            {
+                                goto Restart;
+                            }
+
                             continue;
                             continue;
                         }
                         }
 
 
@@ -627,7 +677,11 @@ public static partial class LuaVirtualMachine
 
 
                         if (ExecuteCompareOperationMetaMethod(vb, vc, context, OpCode.Eq, out doRestart))
                         if (ExecuteCompareOperationMetaMethod(vb, vc, context, OpCode.Eq, out doRestart))
                         {
                         {
-                            if (doRestart) goto Restart;
+                            if (doRestart)
+                            {
+                                goto Restart;
+                            }
+
                             continue;
                             continue;
                         }
                         }
 
 
@@ -665,7 +719,11 @@ public static partial class LuaVirtualMachine
 
 
                         if (ExecuteCompareOperationMetaMethod(vb, vc, context, opCode, out doRestart))
                         if (ExecuteCompareOperationMetaMethod(vb, vc, context, opCode, out doRestart))
                         {
                         {
-                            if (doRestart) goto Restart;
+                            if (doRestart)
+                            {
+                                goto Restart;
+                            }
+
                             continue;
                             continue;
                         }
                         }
 
 
@@ -709,8 +767,16 @@ public static partial class LuaVirtualMachine
                         Markers.TailCall();
                         Markers.TailCall();
                         if (TailCall(context, out doRestart))
                         if (TailCall(context, out doRestart))
                         {
                         {
-                            if (doRestart) goto Restart;
-                            if (context.IsTopLevel) goto End;
+                            if (doRestart)
+                            {
+                                goto Restart;
+                            }
+
+                            if (context.IsTopLevel)
+                            {
+                                goto End;
+                            }
+
                             continue;
                             continue;
                         }
                         }
 
 
@@ -773,7 +839,11 @@ public static partial class LuaVirtualMachine
                         Markers.TForCall();
                         Markers.TForCall();
                         if (TForCall(context, out doRestart))
                         if (TForCall(context, out doRestart))
                         {
                         {
-                            if (doRestart) goto Restart;
+                            if (doRestart)
+                            {
+                                goto Restart;
+                            }
+
                             continue;
                             continue;
                         }
                         }
 
 
@@ -804,6 +874,7 @@ public static partial class LuaVirtualMachine
                         Markers.VarArg();
                         Markers.VarArg();
                         VarArg(context);
                         VarArg(context);
 
 
+                        [MethodImpl(MethodImplOptions.NoInlining)]
                         static void VarArg(VirtualMachineExecutionContext context)
                         static void VarArg(VirtualMachineExecutionContext context)
                         {
                         {
                             var instruction = context.Instruction;
                             var instruction = context.Instruction;
@@ -817,7 +888,7 @@ public static partial class LuaVirtualMachine
                             var stack = context.Stack;
                             var stack = context.Stack;
                             stack.EnsureCapacity(ra + count);
                             stack.EnsureCapacity(ra + count);
                             ref var stackHead = ref stack.Get(0);
                             ref var stackHead = ref stack.Get(0);
-                            for (int i = 0; i < count; i++)
+                            for (var i = 0; i < count; i++)
                             {
                             {
                                 Unsafe.Add(ref stackHead, ra + i) = frameVariableArgumentCount > i
                                 Unsafe.Add(ref stackHead, ra + i) = frameVariableArgumentCount > i
                                     ? Unsafe.Add(ref stackHead, frameBase - (frameVariableArgumentCount - i))
                                     ? Unsafe.Add(ref stackHead, frameBase - (frameVariableArgumentCount - i))
@@ -915,7 +986,11 @@ public static partial class LuaVirtualMachine
     {
     {
         static bool ToString(ref LuaValue v)
         static bool ToString(ref LuaValue v)
         {
         {
-            if (v.Type == LuaValueType.String) return true;
+            if (v.Type == LuaValueType.String)
+            {
+                return true;
+            }
+
             if (v.Type == LuaValueType.Number)
             if (v.Type == LuaValueType.Number)
             {
             {
                 v = v.ToString();
                 v = v.ToString();
@@ -948,7 +1023,7 @@ public static partial class LuaVirtualMachine
             {
             {
                 var tl = rhs.UnsafeReadString().Length;
                 var tl = rhs.UnsafeReadString().Length;
 
 
-                int i = 1;
+                var i = 1;
                 for (; i < total; i++)
                 for (; i < total; i++)
                 {
                 {
                     ref var v = ref stack.Get(top - i - 1);
                     ref var v = ref stack.Get(top - i - 1);
@@ -967,7 +1042,11 @@ public static partial class LuaVirtualMachine
                     foreach (var v in stack.AsSpan().Slice(index))
                     foreach (var v in stack.AsSpan().Slice(index))
                     {
                     {
                         var s = v.UnsafeReadString();
                         var s = v.UnsafeReadString();
-                        if (s.Length == 0) continue;
+                        if (s.Length == 0)
+                        {
+                            continue;
+                        }
+
                         s.AsSpan().CopyTo(span);
                         s.AsSpan().CopyTo(span);
                         span = span[s.Length..];
                         span = span[s.Length..];
                     }
                     }
@@ -987,7 +1066,11 @@ public static partial class LuaVirtualMachine
     {
     {
         static bool ToString(ref LuaValue v)
         static bool ToString(ref LuaValue v)
         {
         {
-            if (v.Type == LuaValueType.String) return true;
+            if (v.Type == LuaValueType.String)
+            {
+                return true;
+            }
+
             if (v.Type == LuaValueType.Number)
             if (v.Type == LuaValueType.Number)
             {
             {
                 v = v.ToString();
                 v = v.ToString();
@@ -1021,7 +1104,7 @@ public static partial class LuaVirtualMachine
             {
             {
                 var tl = rhs.UnsafeReadString().Length;
                 var tl = rhs.UnsafeReadString().Length;
 
 
-                int i = 1;
+                var i = 1;
                 for (; i < total; i++)
                 for (; i < total; i++)
                 {
                 {
                     ref var v = ref stack.Get(top - i - 1);
                     ref var v = ref stack.Get(top - i - 1);
@@ -1040,7 +1123,11 @@ public static partial class LuaVirtualMachine
                     foreach (var v in stack.AsSpan().Slice(index))
                     foreach (var v in stack.AsSpan().Slice(index))
                     {
                     {
                         var s = v.UnsafeReadString();
                         var s = v.UnsafeReadString();
-                        if (s.Length == 0) continue;
+                        if (s.Length == 0)
+                        {
+                            continue;
+                        }
+
                         s.AsSpan().CopyTo(span);
                         s.AsSpan().CopyTo(span);
                         span = span[s.Length..];
                         span = span[s.Length..];
                     }
                     }
@@ -1088,7 +1175,7 @@ public static partial class LuaVirtualMachine
             var access = thread.PushCallStackFrame(newFrame);
             var access = thread.PushCallStackFrame(newFrame);
             try
             try
             {
             {
-                var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = argCount, ReturnFrameBase = target };
+                var functionContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = argCount, ReturnFrameBase = target };
                 if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
                 if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
                 {
                 {
                     await ExecuteCallHook(functionContext, context.CancellationToken);
                     await ExecuteCallHook(functionContext, context.CancellationToken);
@@ -1122,7 +1209,7 @@ public static partial class LuaVirtualMachine
         var RA = instruction.A + context.FrameBase;
         var RA = instruction.A + context.FrameBase;
         var newBase = RA + 1;
         var newBase = RA + 1;
         var va = context.Stack.Get(RA);
         var va = context.Stack.Get(RA);
-        bool isMetamethod = false;
+        var isMetamethod = false;
         if (!va.TryReadFunction(out var func))
         if (!va.TryReadFunction(out var func))
         {
         {
             if (va.TryGetMetamethod(context.State, Metamethods.Call, out var metamethod) &&
             if (va.TryGetMetamethod(context.State, Metamethods.Call, out var metamethod) &&
@@ -1217,12 +1304,12 @@ public static partial class LuaVirtualMachine
 
 
         var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
         var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
         newBase += variableArgumentCount;
         newBase += variableArgumentCount;
-        var newFrame = new CallStackFrame() { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = returnBase };
+        var newFrame = new CallStackFrame { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = returnBase };
 
 
         var access = thread.PushCallStackFrame(newFrame);
         var access = thread.PushCallStackFrame(newFrame);
         try
         try
         {
         {
-            var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = argCount, ReturnFrameBase = returnBase };
+            var functionContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = argCount, ReturnFrameBase = returnBase };
             if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
             if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
             {
             {
                 await ExecuteCallHook(functionContext, cancellationToken);
                 await ExecuteCallHook(functionContext, cancellationToken);
@@ -1273,7 +1360,7 @@ public static partial class LuaVirtualMachine
         var stack = context.Stack;
         var stack = context.Stack;
         var RA = instruction.A + context.FrameBase;
         var RA = instruction.A + context.FrameBase;
         var newBase = RA + 1;
         var newBase = RA + 1;
-        bool isMetamethod = false;
+        var isMetamethod = false;
         var state = context.State;
         var state = context.State;
         var thread = context.Thread;
         var thread = context.Thread;
 
 
@@ -1352,7 +1439,7 @@ public static partial class LuaVirtualMachine
         var instruction = context.Instruction;
         var instruction = context.Instruction;
         var stack = context.Stack;
         var stack = context.Stack;
         var RA = instruction.A + context.FrameBase;
         var RA = instruction.A + context.FrameBase;
-        bool isMetamethod = false;
+        var isMetamethod = false;
         var iteratorRaw = stack.Get(RA);
         var iteratorRaw = stack.Get(RA);
         if (!iteratorRaw.TryReadFunction(out var iterator))
         if (!iteratorRaw.TryReadFunction(out var iterator))
         {
         {
@@ -1456,7 +1543,7 @@ public static partial class LuaVirtualMachine
             c = context.Prototype.Code[context.Pc].Ax;
             c = context.Prototype.Code[context.Pc].Ax;
         }
         }
 
 
-        table.EnsureArrayCapacity((c - 1) * 50 + count);
+        table.EnsureArrayCapacity(((c - 1) * 50) + count);
         stack.GetBuffer().Slice(RA + 1, count)
         stack.GetBuffer().Slice(RA + 1, count)
             .CopyTo(table.GetArraySpan()[((c - 1) * 50)..]);
             .CopyTo(table.GetArraySpan()[((c - 1) * 50)..]);
         stack.PopUntil(RA + 1);
         stack.PopUntil(RA + 1);
@@ -1477,14 +1564,14 @@ public static partial class LuaVirtualMachine
     static ref readonly LuaValue RKB(ref LuaValue stack, ref LuaValue constants, Instruction instruction)
     static ref readonly LuaValue RKB(ref LuaValue stack, ref LuaValue constants, Instruction instruction)
     {
     {
         var index = instruction.B;
         var index = instruction.B;
-        return ref (index >= 256 ? ref Unsafe.Add(ref constants, index - 256) : ref Unsafe.Add(ref stack, index));
+        return ref index >= 256 ? ref Unsafe.Add(ref constants, index - 256) : ref Unsafe.Add(ref stack, index);
     }
     }
 
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     static ref readonly LuaValue RKC(ref LuaValue stack, ref LuaValue constants, Instruction instruction)
     static ref readonly LuaValue RKC(ref LuaValue stack, ref LuaValue constants, Instruction instruction)
     {
     {
         var index = instruction.C;
         var index = instruction.C;
-        return ref (index >= 256 ? ref Unsafe.Add(ref constants, index - 256) : ref Unsafe.Add(ref stack, index));
+        return ref index >= 256 ? ref Unsafe.Add(ref constants, index - 256) : ref Unsafe.Add(ref stack, index);
     }
     }
 
 
     [MethodImpl(MethodImplOptions.NoInlining)]
     [MethodImpl(MethodImplOptions.NoInlining)]
@@ -1494,7 +1581,7 @@ public static partial class LuaVirtualMachine
         const int MAX_LOOP = 100;
         const int MAX_LOOP = 100;
         doRestart = false;
         doRestart = false;
         var skip = targetTable.Type == LuaValueType.Table;
         var skip = targetTable.Type == LuaValueType.Table;
-        for (int i = 0; i < MAX_LOOP; i++)
+        for (var i = 0; i < MAX_LOOP; i++)
         {
         {
             if (table.TryReadTable(out var luaTable))
             if (table.TryReadTable(out var luaTable))
             {
             {
@@ -1518,9 +1605,13 @@ public static partial class LuaVirtualMachine
             if (!table.TryGetMetamethod(context.State, Metamethods.Index, out var metatableValue))
             if (!table.TryGetMetamethod(context.State, Metamethods.Index, out var metatableValue))
             {
             {
                 if (i == 0)
                 if (i == 0)
+                {
                     ThrowInvalidOperationWithName();
                     ThrowInvalidOperationWithName();
+                }
                 else
                 else
+                {
                     LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "index", table);
                     LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "index", table);
+                }
             }
             }
 
 
             table = metatableValue;
             table = metatableValue;
@@ -1538,9 +1629,13 @@ public static partial class LuaVirtualMachine
         {
         {
             var op = context.Instruction.OpCode;
             var op = context.Instruction.OpCode;
             if (op != OpCode.GetTabUp)
             if (op != OpCode.GetTabUp)
+            {
                 LuaRuntimeException.AttemptInvalidOperationOnLuaStack(GetThreadWithCurrentPc(context), "index", context.Pc, context.Instruction.B);
                 LuaRuntimeException.AttemptInvalidOperationOnLuaStack(GetThreadWithCurrentPc(context), "index", context.Pc, context.Instruction.B);
+            }
             else
             else
+            {
                 LuaRuntimeException.AttemptInvalidOperationOnUpValues(GetThreadWithCurrentPc(context), "index", context.Instruction.B);
                 LuaRuntimeException.AttemptInvalidOperationOnUpValues(GetThreadWithCurrentPc(context), "index", context.Instruction.B);
+            }
         }
         }
     }
     }
 
 
@@ -1595,7 +1690,7 @@ public static partial class LuaVirtualMachine
         var targetTable = table;
         var targetTable = table;
         const int MAX_LOOP = 100;
         const int MAX_LOOP = 100;
         var skip = targetTable.Type == LuaValueType.Table;
         var skip = targetTable.Type == LuaValueType.Table;
-        for (int i = 0; i < MAX_LOOP; i++)
+        for (var i = 0; i < MAX_LOOP; i++)
         {
         {
             if (table.TryReadTable(out var luaTable))
             if (table.TryReadTable(out var luaTable))
             {
             {
@@ -1612,7 +1707,7 @@ public static partial class LuaVirtualMachine
                     goto Function;
                     goto Function;
                 }
                 }
 
 
-                return default(ValueTask<LuaValue>);
+                return default;
             }
             }
 
 
             if (!table.TryGetMetamethod(thread.State, Metamethods.Index, out var metatableValue))
             if (!table.TryGetMetamethod(thread.State, Metamethods.Index, out var metatableValue))
@@ -1640,10 +1735,10 @@ public static partial class LuaVirtualMachine
         stack.Push(key);
         stack.Push(key);
         var varArgCount = indexTable.GetVariableArgumentCount(2);
         var varArgCount = indexTable.GetVariableArgumentCount(2);
 
 
-        var newFrame = new CallStackFrame() { Base = thread.Stack.Count - 2 + varArgCount, VariableArgumentCount = varArgCount, Function = indexTable, ReturnBase = top };
+        var newFrame = new CallStackFrame { Base = thread.Stack.Count - 2 + varArgCount, VariableArgumentCount = varArgCount, Function = indexTable, ReturnBase = top };
 
 
         var access = thread.PushCallStackFrame(newFrame);
         var access = thread.PushCallStackFrame(newFrame);
-        var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = 2, ReturnFrameBase = top };
+        var functionContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = 2, ReturnFrameBase = top };
         if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
         if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
         {
         {
             await ExecuteCallHook(functionContext, ct);
             await ExecuteCallHook(functionContext, ct);
@@ -1664,12 +1759,12 @@ public static partial class LuaVirtualMachine
         const int MAX_LOOP = 100;
         const int MAX_LOOP = 100;
         doRestart = false;
         doRestart = false;
         var skip = targetTable.Type == LuaValueType.Table;
         var skip = targetTable.Type == LuaValueType.Table;
-        for (int i = 0; i < MAX_LOOP; i++)
+        for (var i = 0; i < MAX_LOOP; i++)
         {
         {
             if (table.TryReadTable(out var luaTable))
             if (table.TryReadTable(out var luaTable))
             {
             {
                 targetTable = luaTable;
                 targetTable = luaTable;
-                ref var valueRef = ref (skip ? ref Unsafe.NullRef<LuaValue>() : ref luaTable.FindValue(key));
+                ref var valueRef = ref skip ? ref Unsafe.NullRef<LuaValue>() : ref luaTable.FindValue(key);
                 skip = false;
                 skip = false;
                 if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
                 if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
                 {
                 {
@@ -1696,9 +1791,13 @@ public static partial class LuaVirtualMachine
             if (!table.TryGetMetamethod(context.State, Metamethods.NewIndex, out var metatableValue))
             if (!table.TryGetMetamethod(context.State, Metamethods.NewIndex, out var metatableValue))
             {
             {
                 if (i == 0)
                 if (i == 0)
+                {
                     ThrowInvalidOperationWithName();
                     ThrowInvalidOperationWithName();
+                }
                 else
                 else
+                {
                     LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "index", table);
                     LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "index", table);
+                }
             }
             }
 
 
             table = metatableValue;
             table = metatableValue;
@@ -1718,9 +1817,13 @@ public static partial class LuaVirtualMachine
         {
         {
             var op = context.Instruction.OpCode;
             var op = context.Instruction.OpCode;
             if (op != OpCode.SetTabUp)
             if (op != OpCode.SetTabUp)
+            {
                 LuaRuntimeException.AttemptInvalidOperationOnLuaStack(GetThreadWithCurrentPc(context), "index", context.Pc, context.Instruction.A);
                 LuaRuntimeException.AttemptInvalidOperationOnLuaStack(GetThreadWithCurrentPc(context), "index", context.Pc, context.Instruction.A);
+            }
             else
             else
+            {
                 LuaRuntimeException.AttemptInvalidOperationOnUpValues(GetThreadWithCurrentPc(context), "index", context.Instruction.A);
                 LuaRuntimeException.AttemptInvalidOperationOnUpValues(GetThreadWithCurrentPc(context), "index", context.Instruction.A);
+            }
         }
         }
     }
     }
 
 
@@ -1769,17 +1872,17 @@ public static partial class LuaVirtualMachine
         var targetTable = table;
         var targetTable = table;
         const int MAX_LOOP = 100;
         const int MAX_LOOP = 100;
         var skip = targetTable.Type == LuaValueType.Table;
         var skip = targetTable.Type == LuaValueType.Table;
-        for (int i = 0; i < MAX_LOOP; i++)
+        for (var i = 0; i < MAX_LOOP; i++)
         {
         {
             if (table.TryReadTable(out var luaTable))
             if (table.TryReadTable(out var luaTable))
             {
             {
                 targetTable = luaTable;
                 targetTable = luaTable;
-                ref var valueRef = ref (skip ? ref Unsafe.NullRef<LuaValue>() : ref luaTable.FindValue(key));
+                ref var valueRef = ref skip ? ref Unsafe.NullRef<LuaValue>() : ref luaTable.FindValue(key);
                 skip = false;
                 skip = false;
                 if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
                 if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
                 {
                 {
                     valueRef = value;
                     valueRef = value;
-                    return default(ValueTask);
+                    return default;
                 }
                 }
 
 
                 var metatable = luaTable.Metatable;
                 var metatable = luaTable.Metatable;
@@ -1788,7 +1891,7 @@ public static partial class LuaVirtualMachine
                     if (Unsafe.IsNullRef(ref valueRef))
                     if (Unsafe.IsNullRef(ref valueRef))
                     {
                     {
                         luaTable[key] = value;
                         luaTable[key] = value;
-                        return default(ValueTask);
+                        return default;
                     }
                     }
 
 
                     valueRef = value;
                     valueRef = value;
@@ -1825,10 +1928,10 @@ public static partial class LuaVirtualMachine
         stack.Push(value);
         stack.Push(value);
         var varArgCount = newIndexFunction.GetVariableArgumentCount(3);
         var varArgCount = newIndexFunction.GetVariableArgumentCount(3);
 
 
-        var newFrame = new CallStackFrame() { Base = thread.Stack.Count - 3 + varArgCount, VariableArgumentCount = varArgCount, Function = newIndexFunction, ReturnBase = top };
+        var newFrame = new CallStackFrame { Base = thread.Stack.Count - 3 + varArgCount, VariableArgumentCount = varArgCount, Function = newIndexFunction, ReturnBase = top };
 
 
         var access = thread.PushCallStackFrame(newFrame);
         var access = thread.PushCallStackFrame(newFrame);
-        var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = 3, ReturnFrameBase = top };
+        var functionContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = 3, ReturnFrameBase = top };
         if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
         if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
         {
         {
             await ExecuteCallHook(functionContext, ct);
             await ExecuteCallHook(functionContext, ct);
@@ -1937,12 +2040,12 @@ public static partial class LuaVirtualMachine
             var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
             var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
             newBase += variableArgumentCount;
             newBase += variableArgumentCount;
 
 
-            var newFrame = new CallStackFrame() { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = newBase };
+            var newFrame = new CallStackFrame { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = newBase };
 
 
             var access = thread.PushCallStackFrame(newFrame);
             var access = thread.PushCallStackFrame(newFrame);
             try
             try
             {
             {
-                var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = argCount, ReturnFrameBase = newBase };
+                var functionContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = argCount, ReturnFrameBase = newBase };
                 if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
                 if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
                 {
                 {
                     await ExecuteCallHook(functionContext, ct);
                     await ExecuteCallHook(functionContext, ct);
@@ -2071,12 +2174,12 @@ public static partial class LuaVirtualMachine
             stack.Push(vb);
             stack.Push(vb);
             var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
             var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
             newBase += variableArgumentCount;
             newBase += variableArgumentCount;
-            var newFrame = new CallStackFrame() { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = newBase };
+            var newFrame = new CallStackFrame { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = newBase };
 
 
             var access = thread.PushCallStackFrame(newFrame);
             var access = thread.PushCallStackFrame(newFrame);
             try
             try
             {
             {
-                var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = argCount, ReturnFrameBase = newBase };
+                var functionContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = argCount, ReturnFrameBase = newBase };
                 if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
                 if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
                 {
                 {
                     await ExecuteCallHook(functionContext, cancellationToken);
                     await ExecuteCallHook(functionContext, cancellationToken);
@@ -2108,7 +2211,7 @@ public static partial class LuaVirtualMachine
     {
     {
         var (name, description) = opCode.GetNameAndDescription();
         var (name, description) = opCode.GetNameAndDescription();
         doRestart = false;
         doRestart = false;
-        bool reverseLe = false;
+        var reverseLe = false;
     ReCheck:
     ReCheck:
         if (vb.TryGetMetamethod(context.State, name, out var metamethod) ||
         if (vb.TryGetMetamethod(context.State, name, out var metamethod) ||
             vc.TryGetMetamethod(context.State, name, out metamethod))
             vc.TryGetMetamethod(context.State, name, out metamethod))
@@ -2134,7 +2237,11 @@ public static partial class LuaVirtualMachine
             stack.Push(vc);
             stack.Push(vc);
             var varArgCount = func.GetVariableArgumentCount(argCount);
             var varArgCount = func.GetVariableArgumentCount(argCount);
             var newFrame = func.CreateNewFrame(context, stack.Count - argCount + varArgCount);
             var newFrame = func.CreateNewFrame(context, stack.Count - argCount + varArgCount);
-            if (reverseLe) newFrame.Flags |= CallStackFrameFlags.ReversedLe;
+            if (reverseLe)
+            {
+                newFrame.Flags |= CallStackFrameFlags.ReversedLe;
+            }
+
             var access = context.Thread.PushCallStackFrame(newFrame);
             var access = context.Thread.PushCallStackFrame(newFrame);
             if (context.Thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
             if (context.Thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
             {
             {
@@ -2208,7 +2315,7 @@ public static partial class LuaVirtualMachine
         thread.ThrowIfCancellationRequested(cancellationToken);
         thread.ThrowIfCancellationRequested(cancellationToken);
 
 
         var (name, description) = opCode.GetNameAndDescription();
         var (name, description) = opCode.GetNameAndDescription();
-        bool reverseLe = false;
+        var reverseLe = false;
     ReCheck:
     ReCheck:
         if (vb.TryGetMetamethod(thread.State, name, out var metamethod) ||
         if (vb.TryGetMetamethod(thread.State, name, out var metamethod) ||
             vc.TryGetMetamethod(thread.State, name, out metamethod))
             vc.TryGetMetamethod(thread.State, name, out metamethod))
@@ -2233,12 +2340,12 @@ public static partial class LuaVirtualMachine
             stack.Push(vc);
             stack.Push(vc);
             var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
             var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
             newBase += variableArgumentCount;
             newBase += variableArgumentCount;
-            var newFrame = new CallStackFrame() { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = newBase };
+            var newFrame = new CallStackFrame { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = newBase };
 
 
             var access = thread.PushCallStackFrame(newFrame);
             var access = thread.PushCallStackFrame(newFrame);
             try
             try
             {
             {
-                var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = argCount, ReturnFrameBase = newBase };
+                var functionContext = new LuaFunctionExecutionContext { Access = access, ArgumentCount = argCount, ReturnFrameBase = newBase };
                 if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
                 if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
                 {
                 {
                     await ExecuteCallHook(functionContext, cancellationToken);
                     await ExecuteCallHook(functionContext, cancellationToken);
@@ -2404,7 +2511,10 @@ public static partial class LuaVirtualMachine
         {
         {
             var stackBuffer = stack.GetBuffer();
             var stackBuffer = stack.GetBuffer();
             if (argumentCount > 0)
             if (argumentCount > 0)
+            {
                 stackBuffer.Slice(newBase, argumentCount).CopyTo(stackBuffer.Slice(currentBase, argumentCount));
                 stackBuffer.Slice(newBase, argumentCount).CopyTo(stackBuffer.Slice(currentBase, argumentCount));
+            }
+
             newBase = currentBase;
             newBase = currentBase;
         }
         }
 
 
@@ -2440,7 +2550,7 @@ public static partial class LuaVirtualMachine
             ReturnBase = newBase,
             ReturnBase = newBase,
             Function = function,
             Function = function,
             VariableArgumentCount = 0,
             VariableArgumentCount = 0,
-            CallerInstructionIndex = context.Pc,
+            CallerInstructionIndex = context.Pc
         };
         };
     }
     }
 
 
@@ -2453,7 +2563,7 @@ public static partial class LuaVirtualMachine
             ReturnBase = returnBase,
             ReturnBase = returnBase,
             Function = function,
             Function = function,
             VariableArgumentCount = variableArgumentCount,
             VariableArgumentCount = variableArgumentCount,
-            CallerInstructionIndex = context.Pc,
+            CallerInstructionIndex = context.Pc
         };
         };
     }
     }
 
 

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

@@ -20,10 +20,15 @@ public sealed class Prototype(
 )
 )
 {
 {
     public ReadOnlySpan<LuaValue> Constants => constants;
     public ReadOnlySpan<LuaValue> Constants => constants;
+
     public ReadOnlySpan<Instruction> Code => code;
     public ReadOnlySpan<Instruction> Code => code;
+
     public ReadOnlySpan<Prototype> ChildPrototypes => childPrototypes;
     public ReadOnlySpan<Prototype> ChildPrototypes => childPrototypes;
+
     public ReadOnlySpan<int> LineInfo => lineInfo;
     public ReadOnlySpan<int> LineInfo => lineInfo;
+
     public ReadOnlySpan<LocalVariable> LocalVariables => localVariables;
     public ReadOnlySpan<LocalVariable> LocalVariables => localVariables;
+
     public ReadOnlySpan<UpValueDesc> UpValues => upValues;
     public ReadOnlySpan<UpValueDesc> UpValues => upValues;
 
 
     //public LuaClosure Cache;
     //public LuaClosure Cache;
@@ -44,14 +49,20 @@ public sealed class Prototype(
     /// <param name="span">binary bytecode</param>
     /// <param name="span">binary bytecode</param>
     /// <param name="name">chunk name</param>
     /// <param name="name">chunk name</param>
     /// <returns></returns>
     /// <returns></returns>
-    public static Prototype FromByteCode(ReadOnlySpan<byte> span, ReadOnlySpan<char> name) => Parser.UnDump(span, name);
+    public static Prototype FromByteCode(ReadOnlySpan<byte> span, ReadOnlySpan<char> name)
+    {
+        return Parser.UnDump(span, name);
+    }
 
 
     /// <summary>
     /// <summary>
     ///  Converts a Prototype object to a Lua bytecode.
     ///  Converts a Prototype object to a Lua bytecode.
     ///  </summary>
     ///  </summary>
     ///  <param name="useLittleEndian">true if the bytecode should be in little endian format, false if it should be in big endian format</param>
     ///  <param name="useLittleEndian">true if the bytecode should be in little endian format, false if it should be in big endian format</param>
     /// <returns>binary bytecode</returns>
     /// <returns>binary bytecode</returns>
-    public byte[] ToByteCode(bool useLittleEndian = true) => Parser.Dump(this, useLittleEndian);
+    public byte[] ToByteCode(bool useLittleEndian = true)
+    {
+        return Parser.Dump(this, useLittleEndian);
+    }
 
 
     /// <summary>
     /// <summary>
     ///  Writes the Lua bytecode to a buffer writer.
     ///  Writes the Lua bytecode to a buffer writer.

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

@@ -6,18 +6,25 @@ namespace Lua.Runtime;
 public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
 public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
 {
 {
     public LuaState State => state;
     public LuaState State => state;
+
     public LuaFunction RootFunc => StackFrames[0].Function;
     public LuaFunction RootFunc => StackFrames[0].Function;
+
     readonly CallStackFrame[] stackFramesArray = stackFrames.ToArray();
     readonly CallStackFrame[] stackFramesArray = stackFrames.ToArray();
+
     public ReadOnlySpan<CallStackFrame> StackFrames => stackFramesArray;
     public ReadOnlySpan<CallStackFrame> StackFrames => stackFramesArray;
 
 
     internal static void WriteLastLuaTrace(ReadOnlySpan<CallStackFrame> stackFrames, ref PooledList<char> list, int level = 1)
     internal static void WriteLastLuaTrace(ReadOnlySpan<CallStackFrame> stackFrames, ref PooledList<char> list, int level = 1)
     {
     {
-        if (level < 1) return;
+        if (level < 1)
+        {
+            return;
+        }
+
         var intFormatBuffer = (stackalloc char[15]);
         var intFormatBuffer = (stackalloc char[15]);
         var shortSourceBuffer = (stackalloc char[59]);
         var shortSourceBuffer = (stackalloc char[59]);
         for (var index = stackFrames.Length - level; index >= 1; index--)
         for (var index = stackFrames.Length - level; index >= 1; index--)
         {
         {
-            LuaFunction lastFunc = stackFrames[index - 1].Function;
+            var lastFunc = stackFrames[index - 1].Function;
             var frame = stackFrames[index];
             var frame = stackFrames[index];
             if (!frame.IsTailCall && lastFunc is LuaClosure closure)
             if (!frame.IsTailCall && lastFunc is LuaClosure closure)
             {
             {
@@ -53,7 +60,7 @@ public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
             var stackFrames = StackFrames;
             var stackFrames = StackFrames;
             for (var index = stackFrames.Length - 1; index >= 1; index--)
             for (var index = stackFrames.Length - 1; index >= 1; index--)
             {
             {
-                LuaFunction lastFunc = stackFrames[index - 1].Function;
+                var lastFunc = stackFrames[index - 1].Function;
                 var frame = stackFrames[index];
                 var frame = stackFrames[index];
                 if (!frame.IsTailCall && lastFunc is LuaClosure closure)
                 if (!frame.IsTailCall && lastFunc is LuaClosure closure)
                 {
                 {
@@ -80,7 +87,7 @@ public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
             var stackFrames = StackFrames;
             var stackFrames = StackFrames;
             for (var index = 1; index <= stackFrames.Length; index++)
             for (var index = 1; index <= stackFrames.Length; index++)
             {
             {
-                LuaFunction lastFunc = stackFrames[index - 1].Function;
+                var lastFunc = stackFrames[index - 1].Function;
                 var frame = stackFrames[index];
                 var frame = stackFrames[index];
                 if (!frame.IsTailCall && lastFunc is LuaClosure closure)
                 if (!frame.IsTailCall && lastFunc is LuaClosure closure)
                 {
                 {
@@ -134,7 +141,7 @@ public class Traceback(LuaState state, ReadOnlySpan<CallStackFrame> stackFrames)
 
 
         for (var index = stackFrames.Length - 1; index >= 0; index--)
         for (var index = stackFrames.Length - 1; index >= 0; index--)
         {
         {
-            LuaFunction lastFunc = stackFrames[index].Function;
+            var lastFunc = stackFrames[index].Function;
             if (lastFunc is not null and not LuaClosure)
             if (lastFunc is not null and not LuaClosure)
             {
             {
                 if (1 <= skipCount--)
                 if (1 <= skipCount--)

+ 20 - 10
src/Lua/Standard/BasicLibrary.cs

@@ -36,7 +36,7 @@ public sealed class BasicLibrary
             new("tonumber", ToNumber),
             new("tonumber", ToNumber),
             new("tostring", ToString),
             new("tostring", ToString),
             new("type", Type),
             new("type", Type),
-            new("xpcall", XPCall),
+            new("xpcall", XPCall)
         ];
         ];
 
 
         IPairsIterator = new("iterator", (context, cancellationToken) =>
         IPairsIterator = new("iterator", (context, cancellationToken) =>
@@ -82,7 +82,11 @@ public sealed class BasicLibrary
 
 
     public ValueTask<int> CollectGarbage(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
     public ValueTask<int> CollectGarbage(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
     {
     {
-        if (context.HasArgument(0)) context.GetArgument<string>(0);
+        if (context.HasArgument(0))
+        {
+            context.GetArgument<string>(0);
+        }
+
         GC.Collect();
         GC.Collect();
         return new(context.Return());
         return new(context.Return());
     }
     }
@@ -244,7 +248,7 @@ public sealed class BasicLibrary
             return 3;
             return 3;
         }
         }
 
 
-        return (context.Return(PairsIterator, arg0, LuaValue.Nil));
+        return context.Return(PairsIterator, arg0, LuaValue.Nil);
     }
     }
 
 
     public async ValueTask<int> PCall(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
     public async ValueTask<int> PCall(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
@@ -273,7 +277,7 @@ public sealed class BasicLibrary
                             return context.Return(false, luaEx.ErrorObject);
                             return context.Return(false, luaEx.ErrorObject);
                         }
                         }
 
 
-                        using var builder = new PooledList<char>();
+                        using PooledList<char> builder = new();
                         var message = luaEx.MinimalMessage();
                         var message = luaEx.MinimalMessage();
                         luaEx.Forget();
                         luaEx.Forget();
                         return context.Return(false, message);
                         return context.Return(false, message);
@@ -288,7 +292,7 @@ public sealed class BasicLibrary
     {
     {
         var stdout = context.State.StandardIO.Output;
         var stdout = context.State.StandardIO.Output;
 
 
-        for (int i = 0; i < context.ArgumentCount; i++)
+        for (var i = 0; i < context.ArgumentCount; i++)
         {
         {
             await context.Arguments[i].CallToStringAsync(context, cancellationToken);
             await context.Arguments[i].CallToStringAsync(context, cancellationToken);
             await stdout.WriteAsync(context.Thread.Stack.Pop().Read<string>(), cancellationToken);
             await stdout.WriteAsync(context.Thread.Stack.Pop().Read<string>(), cancellationToken);
@@ -441,7 +445,10 @@ public sealed class BasicLibrary
                 {
                 {
                     // if the base is not 10, str cannot contain a minus sign
                     // if the base is not 10, str cannot contain a minus sign
                     var span = str.AsSpan().Trim();
                     var span = str.AsSpan().Trim();
-                    if (span.Length == 0) goto END;
+                    if (span.Length == 0)
+                    {
+                        goto END;
+                    }
 
 
                     var first = span[0];
                     var first = span[0];
                     var sign = first == '-' ? -1 : 1;
                     var sign = first == '-' ? -1 : 1;
@@ -450,7 +457,10 @@ public sealed class BasicLibrary
                         span = span[1..];
                         span = span[1..];
                     }
                     }
 
 
-                    if (span.Length == 0) goto END;
+                    if (span.Length == 0)
+                    {
+                        goto END;
+                    }
 
 
                     if (toBase == 16 && span.Length > 2 && span[0] is '0' && span[1] is 'x' or 'X')
                     if (toBase == 16 && span.Length > 2 && span[0] is '0' && span[1] is 'x' or 'X')
                     {
                     {
@@ -485,7 +495,7 @@ public sealed class BasicLibrary
     static double StringToDouble(ReadOnlySpan<char> text, int toBase)
     static double StringToDouble(ReadOnlySpan<char> text, int toBase)
     {
     {
         var value = 0.0;
         var value = 0.0;
-        for (int i = 0; i < text.Length; i++)
+        for (var i = 0; i < text.Length; i++)
         {
         {
             var v = text[i] switch
             var v = text[i] switch
             {
             {
@@ -525,7 +535,7 @@ public sealed class BasicLibrary
                 'x' or 'X' => 33,
                 'x' or 'X' => 33,
                 'y' or 'Y' => 34,
                 'y' or 'Y' => 34,
                 'z' or 'Z' => 35,
                 'z' or 'Z' => 35,
-                _ => 0,
+                _ => 0
             };
             };
 
 
             if (v >= toBase)
             if (v >= toBase)
@@ -561,7 +571,7 @@ public sealed class BasicLibrary
             LuaValueType.LightUserData => "userdata",
             LuaValueType.LightUserData => "userdata",
             LuaValueType.UserData => "userdata",
             LuaValueType.UserData => "userdata",
             LuaValueType.Table => "table",
             LuaValueType.Table => "table",
-            _ => throw new NotImplementedException(),
+            _ => throw new NotImplementedException()
         }));
         }));
     }
     }
 
 

+ 9 - 9
src/Lua/Standard/BitwiseLibrary.cs

@@ -22,7 +22,7 @@ public sealed class BitwiseLibrary
             new(libraryName, "lshift", LShift),
             new(libraryName, "lshift", LShift),
             new(libraryName, "replace", Replace),
             new(libraryName, "replace", Replace),
             new(libraryName, "rrotate", RRotate),
             new(libraryName, "rrotate", RRotate),
-            new(libraryName, "rshift", RShift),
+            new(libraryName, "rshift", RShift)
         ];
         ];
     }
     }
 
 
@@ -64,7 +64,7 @@ public sealed class BitwiseLibrary
 
 
         var value = Bit32Helper.ToUInt32(arg0);
         var value = Bit32Helper.ToUInt32(arg0);
 
 
-        for (int i = 1; i < context.ArgumentCount; i++)
+        for (var i = 1; i < context.ArgumentCount; i++)
         {
         {
             var arg = context.GetArgument<double>(i);
             var arg = context.GetArgument<double>(i);
             LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 1 + i, arg);
             LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 1 + i, arg);
@@ -98,7 +98,7 @@ public sealed class BitwiseLibrary
 
 
         var value = Bit32Helper.ToUInt32(arg0);
         var value = Bit32Helper.ToUInt32(arg0);
 
 
-        for (int i = 1; i < context.ArgumentCount; i++)
+        for (var i = 1; i < context.ArgumentCount; i++)
         {
         {
             var arg = context.GetArgument<double>(i);
             var arg = context.GetArgument<double>(i);
             LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 1 + i, arg);
             LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 1 + i, arg);
@@ -123,7 +123,7 @@ public sealed class BitwiseLibrary
 
 
         var value = Bit32Helper.ToUInt32(arg0);
         var value = Bit32Helper.ToUInt32(arg0);
 
 
-        for (int i = 1; i < context.ArgumentCount; i++)
+        for (var i = 1; i < context.ArgumentCount; i++)
         {
         {
             var arg = context.GetArgument<double>(i);
             var arg = context.GetArgument<double>(i);
             LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 1 + i, arg);
             LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 1 + i, arg);
@@ -147,7 +147,7 @@ public sealed class BitwiseLibrary
 
 
         var value = Bit32Helper.ToUInt32(arg0);
         var value = Bit32Helper.ToUInt32(arg0);
 
 
-        for (int i = 1; i < context.ArgumentCount; i++)
+        for (var i = 1; i < context.ArgumentCount; i++)
         {
         {
             var arg = context.GetArgument<double>(i);
             var arg = context.GetArgument<double>(i);
             LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 1 + i, arg);
             LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 1 + i, arg);
@@ -197,11 +197,11 @@ public sealed class BitwiseLibrary
         LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 2, disp);
         LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 2, disp);
 
 
         var v = Bit32Helper.ToUInt32(x);
         var v = Bit32Helper.ToUInt32(x);
-        var a = ((int)disp) % 32;
+        var a = (int)disp % 32;
 
 
         if (a < 0)
         if (a < 0)
         {
         {
-            v = (v >> (-a)) | (v << (32 + a));
+            v = (v >> -a) | (v << (32 + a));
         }
         }
         else
         else
         {
         {
@@ -283,11 +283,11 @@ public sealed class BitwiseLibrary
         LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 2, disp);
         LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.Thread, 2, disp);
 
 
         var v = Bit32Helper.ToUInt32(x);
         var v = Bit32Helper.ToUInt32(x);
-        var a = ((int)disp) % 32;
+        var a = (int)disp % 32;
 
 
         if (a < 0)
         if (a < 0)
         {
         {
-            v = (v << (-a)) | (v >> (32 + a));
+            v = (v << -a) | (v >> (32 + a));
         }
         }
         else
         else
         {
         {

+ 2 - 2
src/Lua/Standard/CoroutineLibrary.cs

@@ -16,7 +16,7 @@ public sealed class CoroutineLibrary
             new(libraryName, "running", Running),
             new(libraryName, "running", Running),
             new(libraryName, "status", Status),
             new(libraryName, "status", Status),
             new(libraryName, "wrap", Wrap),
             new(libraryName, "wrap", Wrap),
-            new(libraryName, "yield", Yield),
+            new(libraryName, "yield", Yield)
         ];
         ];
     }
     }
 
 
@@ -48,7 +48,7 @@ public sealed class CoroutineLibrary
             LuaThreadStatus.Suspended => "suspended",
             LuaThreadStatus.Suspended => "suspended",
             LuaThreadStatus.Running => "running",
             LuaThreadStatus.Running => "running",
             LuaThreadStatus.Dead => "dead",
             LuaThreadStatus.Dead => "dead",
-            _ => "",
+            _ => ""
         }));
         }));
     }
     }
 
 

Some files were not shown because too many files changed in this diff