LuaState.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. using Lua.CodeAnalysis.Compilation;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Runtime.CompilerServices;
  4. using Lua.Internal;
  5. using Lua.IO;
  6. using Lua.Loaders;
  7. using Lua.Platforms;
  8. using Lua.Runtime;
  9. using Lua.Standard;
  10. using System.Buffers;
  11. namespace Lua;
  12. public sealed class LuaState
  13. {
  14. // states
  15. readonly LuaMainThread mainThread;
  16. FastListCore<UpValue> openUpValues;
  17. FastStackCore<LuaThread> threadStack;
  18. readonly LuaTable environment;
  19. readonly LuaTable registry = new();
  20. readonly UpValue envUpValue;
  21. FastStackCore<LuaDebug.LuaDebugBuffer> debugBufferPool;
  22. internal int CallCount;
  23. internal UpValue EnvUpValue => envUpValue;
  24. internal ref FastStackCore<LuaThread> ThreadStack => ref threadStack;
  25. internal ref FastListCore<UpValue> OpenUpValues => ref openUpValues;
  26. internal ref FastStackCore<LuaDebug.LuaDebugBuffer> DebugBufferPool => ref debugBufferPool;
  27. public LuaTable Environment => environment;
  28. public LuaTable Registry => registry;
  29. public LuaTable LoadedModules => registry[ModuleLibrary.LoadedKeyForRegistry].Read<LuaTable>();
  30. public LuaTable PreloadModules => registry[ModuleLibrary.PreloadKeyForRegistry].Read<LuaTable>();
  31. public LuaMainThread MainThread => mainThread;
  32. public LuaThreadAccess RootAccess => new(mainThread, 0);
  33. public LuaPlatform Platform { get; }
  34. public ILuaModuleLoader? ModuleLoader { get; set; }
  35. public ILuaFileSystem FileSystem => Platform.FileSystem ?? throw new InvalidOperationException("FileSystem is not set. Please set it before access.");
  36. public ILuaOsEnvironment OsEnvironment => Platform.OsEnvironment ?? throw new InvalidOperationException("OperatingSystem is not set. Please set it before access.");
  37. public ILuaStandardIO StandardIO => Platform.StandardIO;
  38. // metatables
  39. LuaTable? nilMetatable;
  40. LuaTable? numberMetatable;
  41. LuaTable? stringMetatable;
  42. LuaTable? booleanMetatable;
  43. LuaTable? functionMetatable;
  44. LuaTable? threadMetatable;
  45. public static LuaState Create(LuaPlatform? platform = null)
  46. {
  47. var state = new LuaState(platform ?? LuaPlatform.Default);
  48. return state;
  49. }
  50. LuaState(LuaPlatform platform)
  51. {
  52. mainThread = new(this);
  53. environment = new();
  54. envUpValue = UpValue.Closed(environment);
  55. registry[ModuleLibrary.LoadedKeyForRegistry] = new LuaTable(0, 8);
  56. registry[ModuleLibrary.PreloadKeyForRegistry] = new LuaTable(0, 8);
  57. Platform = platform;
  58. }
  59. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  60. internal bool TryGetMetatable(LuaValue value, [NotNullWhen(true)] out LuaTable? result)
  61. {
  62. result = value.Type switch
  63. {
  64. LuaValueType.Nil => nilMetatable,
  65. LuaValueType.Boolean => booleanMetatable,
  66. LuaValueType.String => stringMetatable,
  67. LuaValueType.Number => numberMetatable,
  68. LuaValueType.Function => functionMetatable,
  69. LuaValueType.Thread => threadMetatable,
  70. LuaValueType.UserData => value.UnsafeRead<ILuaUserData>().Metatable,
  71. LuaValueType.Table => value.UnsafeRead<LuaTable>().Metatable,
  72. _ => null
  73. };
  74. return result != null;
  75. }
  76. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  77. internal void SetMetatable(LuaValue value, LuaTable metatable)
  78. {
  79. switch (value.Type)
  80. {
  81. case LuaValueType.Nil:
  82. nilMetatable = metatable;
  83. break;
  84. case LuaValueType.Boolean:
  85. booleanMetatable = metatable;
  86. break;
  87. case LuaValueType.String:
  88. stringMetatable = metatable;
  89. break;
  90. case LuaValueType.Number:
  91. numberMetatable = metatable;
  92. break;
  93. case LuaValueType.Function:
  94. functionMetatable = metatable;
  95. break;
  96. case LuaValueType.Thread:
  97. threadMetatable = metatable;
  98. break;
  99. case LuaValueType.UserData:
  100. value.UnsafeRead<ILuaUserData>().Metatable = metatable;
  101. break;
  102. case LuaValueType.Table:
  103. value.UnsafeRead<LuaTable>().Metatable = metatable;
  104. break;
  105. }
  106. }
  107. internal UpValue GetOrAddUpValue(LuaThread thread, int registerIndex)
  108. {
  109. foreach (var upValue in openUpValues.AsSpan())
  110. {
  111. if (upValue.RegisterIndex == registerIndex && upValue.Thread == thread)
  112. {
  113. return upValue;
  114. }
  115. }
  116. var newUpValue = UpValue.Open(thread, registerIndex);
  117. openUpValues.Add(newUpValue);
  118. return newUpValue;
  119. }
  120. internal void CloseUpValues(LuaThread thread, int frameBase)
  121. {
  122. for (int i = 0; i < openUpValues.Length; i++)
  123. {
  124. var upValue = openUpValues[i];
  125. if (upValue.Thread != thread) continue;
  126. if (upValue.RegisterIndex >= frameBase)
  127. {
  128. upValue.Close();
  129. openUpValues.RemoveAtSwapBack(i);
  130. i--;
  131. }
  132. }
  133. }
  134. public unsafe LuaClosure Load(ReadOnlySpan<char> chunk, string chunkName, LuaTable? environment = null)
  135. {
  136. Prototype prototype;
  137. fixed (char* ptr = chunk)
  138. {
  139. prototype = Parser.Parse(this, new(ptr, chunk.Length), chunkName);
  140. }
  141. return new LuaClosure(MainThread, prototype, environment);
  142. }
  143. public LuaClosure Load(ReadOnlySpan<byte> chunk, string? chunkName = null, string mode = "bt", LuaTable? environment = null)
  144. {
  145. if (chunk.Length > 4)
  146. {
  147. if (chunk[0] == '\e')
  148. {
  149. return new LuaClosure(MainThread, Parser.UnDump(chunk, chunkName), environment);
  150. }
  151. }
  152. chunk = BomUtility.GetEncodingFromBytes(chunk, out var encoding);
  153. var charCount = encoding.GetCharCount(chunk);
  154. var pooled = ArrayPool<char>.Shared.Rent(charCount);
  155. try
  156. {
  157. var chars = pooled.AsSpan(0, charCount);
  158. encoding.GetChars(chunk, chars);
  159. chunkName ??= chars.ToString();
  160. return Load(chars, chunkName, environment);
  161. }
  162. finally
  163. {
  164. ArrayPool<char>.Shared.Return(pooled);
  165. }
  166. }
  167. }