Browse Source

refactor: Lua.CodeAnalysis.Compilation

Akeit0 7 months ago
parent
commit
d8448b7a14

+ 9 - 9
src/Lua/CodeAnalysis/Compilation/Declarements.cs

@@ -3,29 +3,29 @@ using System.Runtime.CompilerServices;
 
 
 namespace Lua.CodeAnalysis.Compilation;
 namespace Lua.CodeAnalysis.Compilation;
 
 
-unsafe struct TextReader(char* Ptr, int Length)
+unsafe struct TextReader(char* ptr, int length)
 {
 {
     public int Position;
     public int Position;
 
 
     public (char, bool) Read()
     public (char, bool) Read()
     {
     {
-        if (Position >= Length) return ('\0', false);
-        return (Ptr[Position++], true);
+        if (Position >= length) return ('\0', false);
+        return (ptr[Position++], true);
     }
     }
 
 
     public bool TryRead(out char c)
     public bool TryRead(out char c)
     {
     {
-        if (Position >= Length)
+        if (Position >= length)
         {
         {
             c = '\0';
             c = '\0';
             return false;
             return false;
         }
         }
 
 
-        c = Ptr[Position++];
+        c = ptr[Position++];
         return true;
         return true;
     }
     }
 
 
-    public char Current => Ptr[Position];
+    public char Current => ptr[Position];
 }
 }
 
 
 internal unsafe struct AssignmentTarget(ref AssignmentTarget previous, ExprDesc exprDesc)
 internal unsafe struct AssignmentTarget(ref AssignmentTarget previous, ExprDesc exprDesc)
@@ -50,11 +50,11 @@ internal class Block : IPoolNode<Block>
     Block() { }
     Block() { }
     ref Block? IPoolNode<Block>.NextNode => ref Previous;
     ref Block? IPoolNode<Block>.NextNode => ref Previous;
 
 
-    static LinkedPool<Block> pool;
+    static LinkedPool<Block> Pool;
 
 
     public static Block Get(Block? previous, int firstLabel, int firstGoto, int activeVariableCount, bool hasUpValue, bool isLoop)
     public static Block Get(Block? previous, int firstLabel, int firstGoto, int activeVariableCount, bool hasUpValue, bool isLoop)
     {
     {
-        if (!pool.TryPop(out var block))
+        if (!Pool.TryPop(out var block))
         {
         {
             block = new Block();
             block = new Block();
         }
         }
@@ -73,7 +73,7 @@ internal class Block : IPoolNode<Block>
     public void Release()
     public void Release()
     {
     {
         Previous = null;
         Previous = null;
-        pool.TryPush(this);
+        Pool.TryPush(this);
     }
     }
 }
 }
 
 

+ 9 - 9
src/Lua/CodeAnalysis/Compilation/Dump.cs

@@ -84,23 +84,23 @@ internal unsafe struct Header
 internal unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEndian)
 internal 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;
 
 
     void Write(ReadOnlySpan<byte> span)
     void Write(ReadOnlySpan<byte> span)
     {
     {
         var toWrite = span;
         var toWrite = span;
-        var remaining = UnWritten.Length;
+        var remaining = unWritten.Length;
         if (span.Length > remaining)
         if (span.Length > remaining)
         {
         {
-            span[..remaining].CopyTo(UnWritten);
+            span[..remaining].CopyTo(unWritten);
             Writer.Advance(remaining);
             Writer.Advance(remaining);
             toWrite = span[remaining..];
             toWrite = span[remaining..];
-            UnWritten = Writer.GetSpan(toWrite.Length);
+            unWritten = Writer.GetSpan(toWrite.Length);
         }
         }
 
 
-        toWrite.CopyTo(UnWritten);
+        toWrite.CopyTo(unWritten);
         Writer.Advance(toWrite.Length);
         Writer.Advance(toWrite.Length);
-        UnWritten = UnWritten[toWrite.Length..];
+        unWritten = unWritten[toWrite.Length..];
     }
     }
 
 
     public bool IsReversedEndian => reversedEndian;
     public bool IsReversedEndian => reversedEndian;
@@ -113,9 +113,9 @@ internal unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEn
 
 
     public void Dump(Prototype prototype)
     public void Dump(Prototype prototype)
     {
     {
-        if (UnWritten.Length == 0)
+        if (unWritten.Length == 0)
         {
         {
-            UnWritten = Writer.GetSpan(Header.Size + 32);
+            unWritten = Writer.GetSpan(Header.Size + 32);
         }
         }
 
 
         DumpHeader();
         DumpHeader();
@@ -230,7 +230,7 @@ internal unsafe ref struct DumpState(IBufferWriter<byte> writer, bool reversedEn
                     WriteDouble(c.UnsafeReadDouble());
                     WriteDouble(c.UnsafeReadDouble());
                     break;
                     break;
                 case LuaValueType.String:
                 case LuaValueType.String:
-                    WriteString(c.UnsafeRead<string>()!);
+                    WriteString(c.UnsafeRead<string>());
                     break;
                     break;
             }
             }
         }
         }

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

@@ -117,7 +117,7 @@ internal class Function : IPoolNode<Function>
 
 
     public ExprDesc CloseFunction()
     public ExprDesc CloseFunction()
     {
     {
-        var e = P.Function!.Previous!.ExpressionToNextRegister(MakeExpression(Kind.Relocatable, Previous!.EncodeABx(OpCode.Closure, 0, Previous!.Proto.PrototypeList.Length - 1)));
+        var e = P.Function.Previous!.ExpressionToNextRegister(MakeExpression(Kind.Relocatable, Previous!.EncodeABx(OpCode.Closure, 0, Previous!.Proto.PrototypeList.Length - 1)));
         P.Function.ReturnNone();
         P.Function.ReturnNone();
         P.Function.LeaveBlock();
         P.Function.LeaveBlock();
         Assert(P.Function.Block == null);
         Assert(P.Function.Block == null);
@@ -238,7 +238,7 @@ internal class Function : IPoolNode<Function>
 
 
     public void CheckRepeatedLabel(string name)
     public void CheckRepeatedLabel(string name)
     {
     {
-        foreach (var l in P.ActiveLabels.AsSpan().Slice(Block!.FirstLabel))
+        foreach (var l in P.ActiveLabels.AsSpan().Slice(Block.FirstLabel))
         {
         {
             if (l.Name == name)
             if (l.Name == name)
             {
             {
@@ -250,7 +250,7 @@ internal class Function : IPoolNode<Function>
 
 
     public void FindGotos(int label)
     public void FindGotos(int label)
     {
     {
-        for (var i = Block!.FirstGoto; i < P.PendingGotos.Length;)
+        for (var i = Block.FirstGoto; i < P.PendingGotos.Length;)
         {
         {
             var l = P.ActiveLabels[label];
             var l = P.ActiveLabels[label];
             if (P.PendingGotos[i].Name == l.Name)
             if (P.PendingGotos[i].Name == l.Name)

+ 6 - 6
src/Lua/CodeAnalysis/Compilation/Parser.cs

@@ -360,17 +360,17 @@ internal class Parser : IPoolNode<Parser>, IDisposable
                 return OprPow;
                 return OprPow;
             case TkConcat:
             case TkConcat:
                 return OprConcat;
                 return OprConcat;
-            case TkNE:
+            case TkNe:
                 return OprNE;
                 return OprNE;
             case TkEq:
             case TkEq:
                 return OprEq;
                 return OprEq;
             case '<':
             case '<':
                 return OprLT;
                 return OprLT;
-            case TkLE:
+            case TkLe:
                 return OprLE;
                 return OprLE;
             case '>':
             case '>':
                 return OprGT;
                 return OprGT;
-            case TkGE:
+            case TkGe:
                 return OprGE;
                 return OprGE;
             case TkAnd:
             case TkAnd:
                 return OprAnd;
                 return OprAnd;
@@ -440,7 +440,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
             case TkElse:
             case TkElse:
             case TkElseif:
             case TkElseif:
             case TkEnd:
             case TkEnd:
-            case TkEOS:
+            case TkEos:
                 return true;
                 return true;
             case TkUntil:
             case TkUntil:
                 return withUntil;
                 return withUntil;
@@ -966,7 +966,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
         Function.OpenMainFunction();
         Function.OpenMainFunction();
         Next();
         Next();
         StatementList();
         StatementList();
-        Scanner.Check(TkEOS);
+        Scanner.Check(TkEos);
         Function = Function.CloseMainFunction();
         Function = Function.CloseMainFunction();
     }
     }
 
 
@@ -977,7 +977,7 @@ internal class Parser : IPoolNode<Parser>, IDisposable
             R = r,
             R = r,
             LineNumber = 1,
             LineNumber = 1,
             LastLine = 1,
             LastLine = 1,
-            LookAheadToken = new() { T = TkEOS },
+            LookAheadToken = new() { T = TkEos },
             L = l,
             L = l,
             Buffer = new(),
             Buffer = new(),
             Source = name
             Source = name

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

@@ -32,7 +32,7 @@ internal class PrototypeBuilder : IPoolNode<PrototypeBuilder>
         Source = source;
         Source = source;
     }
     }
 
 
-    static LinkedPool<PrototypeBuilder> pool;
+    static LinkedPool<PrototypeBuilder> Pool;
 
 
 
 
     PrototypeBuilder? nextNode;
     PrototypeBuilder? nextNode;
@@ -40,7 +40,7 @@ internal class PrototypeBuilder : IPoolNode<PrototypeBuilder>
 
 
     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 PrototypeBuilder(source);
         }
         }
@@ -57,7 +57,7 @@ internal class PrototypeBuilder : IPoolNode<PrototypeBuilder>
         LineInfoList.Clear();
         LineInfoList.Clear();
         LocalVariablesList.Clear();
         LocalVariablesList.Clear();
         UpValuesList.Clear();
         UpValuesList.Clear();
-        pool.TryPush(this);
+        Pool.TryPush(this);
     }
     }
 
 
 
 

+ 26 - 40
src/Lua/CodeAnalysis/Compilation/Scanner.cs

@@ -23,14 +23,6 @@ internal struct Scanner
     public int T => Token.T;
     public int T => Token.T;
 
 
 
 
-    static string ChunkID(string source)
-    {
-        var shortSourceBuffer = (stackalloc char[59]);
-        var len = LuaDebug.WriteShortSource(source, shortSourceBuffer);
-        return shortSourceBuffer[..len].ToString();
-    }
-
-
     public const int FirstReserved = ushort.MaxValue + 257;
     public const int FirstReserved = ushort.MaxValue + 257;
     public const int EndOfStream = -1;
     public const int EndOfStream = -1;
 
 
@@ -62,12 +54,12 @@ internal struct Scanner
     public const int TkConcat = TkWhile + 1;
     public const int TkConcat = TkWhile + 1;
     public const int TkDots = TkConcat + 1;
     public const int TkDots = TkConcat + 1;
     public const int TkEq = TkDots + 1;
     public const int TkEq = TkDots + 1;
-    public const int TkGE = TkEq + 1;
-    public const int TkLE = TkGE + 1;
-    public const int TkNE = TkLE + 1;
-    public const int TkDoubleColon = TkNE + 1;
-    public const int TkEOS = TkDoubleColon + 1;
-    public const int TkNumber = TkEOS + 1;
+    public const int TkGe = TkEq + 1;
+    public const int TkLe = TkGe + 1;
+    public const int TkNe = TkLe + 1;
+    public const int TkDoubleColon = TkNe + 1;
+    public const int TkEos = TkDoubleColon + 1;
+    public const int TkNumber = TkEos + 1;
     public const int TkName = TkNumber + 1;
     public const int TkName = TkNumber + 1;
     public const int TkString = TkName + 1;
     public const int TkString = TkName + 1;
 
 
@@ -90,9 +82,9 @@ internal struct Scanner
     public void SyntaxError(string message) => ScanError(message, Token.T);
     public void SyntaxError(string message) => ScanError(message, Token.T);
     public void ErrorExpected(char t) => SyntaxError(TokenToString(t) + " expected");
     public void ErrorExpected(char t) => SyntaxError(TokenToString(t) + " expected");
     public void NumberError() => ScanError("malformed number", TkNumber);
     public void NumberError() => ScanError("malformed number", TkNumber);
-    public static bool IsNewLine(int c) => c == '\n' || c == '\r';
+    public static bool IsNewLine(int c) => c is '\n' or '\r';
 
 
-    public static bool IsDecimal(int c) => '0' <= c && c <= '9';
+    public static bool IsDecimal(int c) => c is >= '0' and <= '9';
 
 
 
 
     public static string TokenToString(Token t) => t.T switch
     public static string TokenToString(Token t) => t.T switch
@@ -100,7 +92,7 @@ internal struct Scanner
         TkName or TkString => t.S,
         TkName or TkString => t.S,
         TkNumber => $"{t.N}",
         TkNumber => $"{t.N}",
         < FirstReserved => $"{(char)t.T}", // TODO check for printable rune
         < FirstReserved => $"{(char)t.T}", // TODO check for printable rune
-        < TkEOS => $"'{tokens[t.T - FirstReserved]}'",
+        < TkEos => $"'{tokens[t.T - FirstReserved]}'",
         _ => tokens[t.T - FirstReserved]
         _ => tokens[t.T - FirstReserved]
     };
     };
 
 
@@ -109,7 +101,7 @@ internal struct Scanner
         TkName or TkString => Token.S,
         TkName or TkString => Token.S,
         TkNumber => $"{Token.N}",
         TkNumber => $"{Token.N}",
         < FirstReserved => $"{(char)t}", // TODO check for printable rune
         < FirstReserved => $"{(char)t}", // TODO check for printable rune
-        < TkEOS => $"'{tokens[t - FirstReserved]}'",
+        < TkEos => $"'{tokens[t - FirstReserved]}'",
         _ => tokens[t - FirstReserved]
         _ => tokens[t - FirstReserved]
     };
     };
 
 
@@ -123,9 +115,10 @@ internal struct Scanner
 
 
     public void ScanError(string message, int token)
     public void ScanError(string message, int token)
     {
     {
-        var buff = ChunkID(Source);
-        if (token != 0) message = $"{buff}:{LineNumber}: {message} near {TokenToString(token)}";
-        else message = $"{buff}:{LineNumber}: {message}";
+        var shortSourceBuffer = (stackalloc char[59]);
+        var len = LuaDebug.WriteShortSource(Source, shortSourceBuffer);
+        var buff = shortSourceBuffer[..len].ToString();
+        message = token != 0 ? $"{buff}:{LineNumber}: {message} near {TokenToString(token)}" : $"{buff}:{LineNumber}: {message}";
         throw new LuaScanException(message);
         throw new LuaScanException(message);
     }
     }
 
 
@@ -177,7 +170,7 @@ internal struct Scanner
     public int SkipSeparator()
     public int SkipSeparator()
     {
     {
         var (i, c) = (0, Current);
         var (i, c) = (0, Current);
-        Assert(c == '[' || c == ']');
+        Assert(c is '[' or ']');
         for (SaveAndAdvance(); Current == '='; i++) SaveAndAdvance();
         for (SaveAndAdvance(); Current == '='; i++) SaveAndAdvance();
         if (Current == c) return i;
         if (Current == c) return i;
         return -i - 1;
         return -i - 1;
@@ -197,14 +190,7 @@ internal struct Scanner
             switch (Current)
             switch (Current)
             {
             {
                 case EndOfStream:
                 case EndOfStream:
-                    if (comment)
-                    {
-                        ScanError("unfinished long comment", TkEOS);
-                    }
-                    else
-                    {
-                        ScanError("unfinished long string", TkEOS);
-                    }
+                    ScanError(comment ? "unfinished long comment" : "unfinished long string", TkEos);
 
 
                     break;
                     break;
                 case ']':
                 case ']':
@@ -488,7 +474,7 @@ internal struct Scanner
             switch (Current)
             switch (Current)
             {
             {
                 case EndOfStream:
                 case EndOfStream:
-                    ScanError("unfinished string", TkEOS);
+                    ScanError("unfinished string", TkEos);
                     break;
                     break;
                 case '\n' or '\r':
                 case '\n' or '\r':
                     ScanError("unfinished string", TkString);
                     ScanError("unfinished string", TkString);
@@ -660,7 +646,7 @@ internal struct Scanner
                     }
                     }
 
 
                     Advance();
                     Advance();
-                    return new() { T = TkLE };
+                    return new() { T = TkLe };
                 case '>':
                 case '>':
                     Advance();
                     Advance();
                     if (Current != '=')
                     if (Current != '=')
@@ -669,7 +655,7 @@ internal struct Scanner
                     }
                     }
 
 
                     Advance();
                     Advance();
-                    return new() { T = TkGE };
+                    return new() { T = TkGe };
                 case '~':
                 case '~':
                     Advance();
                     Advance();
                     if (Current != '=')
                     if (Current != '=')
@@ -678,7 +664,7 @@ internal struct Scanner
                     }
                     }
 
 
                     Advance();
                     Advance();
-                    return new() { T = TkNE };
+                    return new() { T = TkNe };
                 case ':':
                 case ':':
                     Advance();
                     Advance();
                     if (Current != ':')
                     if (Current != ':')
@@ -692,7 +678,7 @@ internal struct Scanner
                 case '\'':
                 case '\'':
                     return ReadString();
                     return ReadString();
                 case EndOfStream:
                 case EndOfStream:
-                    return new() { T = TkEOS };
+                    return new() { T = TkEos };
                 case '.':
                 case '.':
                     SaveAndAdvance();
                     SaveAndAdvance();
                     if (CheckNext("."))
                     if (CheckNext("."))
@@ -745,10 +731,10 @@ internal struct Scanner
     public void Next()
     public void Next()
     {
     {
         LastLine = LineNumber;
         LastLine = LineNumber;
-        if (LookAheadToken.T != TkEOS)
+        if (LookAheadToken.T != TkEos)
         {
         {
             Token = LookAheadToken;
             Token = LookAheadToken;
-            LookAheadToken.T = TkEOS;
+            LookAheadToken.T = TkEos;
         }
         }
         else
         else
         {
         {
@@ -759,7 +745,7 @@ internal struct Scanner
 
 
     public int LookAhead()
     public int LookAhead()
     {
     {
-        Assert(LookAheadToken.T == TkEOS);
+        Assert(LookAheadToken.T == TkEos);
         LookAheadToken = Scan();
         LookAheadToken = Scan();
         return LookAheadToken.T;
         return LookAheadToken.T;
     }
     }
@@ -801,11 +787,11 @@ internal struct Scanner
         }
         }
     }
     }
 
 
-    static bool IsWhiteSpace(int c) => c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v';
+    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 IsDigit(int c) => c is >= '0' and <= '9';
 
 
     static bool IsLetter(int c)
     static bool IsLetter(int c)
     {
     {
-        return c < ushort.MaxValue && c is '_' or >= 'a' and <= 'z' or >= 'A' and <= 'Z';
+        return c is < ushort.MaxValue and ('_' or >= 'a' and <= 'z' or >= 'A' and <= 'Z');
     }
     }
 }
 }

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

@@ -12,6 +12,6 @@ internal struct Token
 
 
     public static implicit operator Token(int token)
     public static implicit operator Token(int token)
     {
     {
-        return new Token { T = token };
+        return new() { T = token };
     }
     }
 }
 }