LuaState.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 ILuaPlatform Platform { get; }
  34. public ILuaModuleLoader ModuleLoader { get; set; } = FileModuleLoader.Instance;
  35. public ILuaFileSystem FileSystem => Platform.FileSystem ?? throw new InvalidOperationException("FileSystem is not set. Please set it before using LuaState.");
  36. public ILuaOsEnvironment OsEnvironment => Platform.OsEnvironment ?? throw new InvalidOperationException("OperatingSystem is not set. Please set it before using LuaState.");
  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()
  46. {
  47. return Create(LuaPlatform.Default);
  48. }
  49. public static LuaState Create(ILuaPlatform platform)
  50. {
  51. var state = new LuaState(platform);
  52. return state;
  53. }
  54. LuaState(ILuaPlatform platform)
  55. {
  56. mainThread = new(this);
  57. environment = new();
  58. envUpValue = UpValue.Closed(environment);
  59. registry[ModuleLibrary.LoadedKeyForRegistry] = new LuaTable(0, 8);
  60. registry[ModuleLibrary.PreloadKeyForRegistry] = new LuaTable(0, 8);
  61. Platform = platform;
  62. }
  63. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  64. internal bool TryGetMetatable(LuaValue value, [NotNullWhen(true)] out LuaTable? result)
  65. {
  66. result = value.Type switch
  67. {
  68. LuaValueType.Nil => nilMetatable,
  69. LuaValueType.Boolean => booleanMetatable,
  70. LuaValueType.String => stringMetatable,
  71. LuaValueType.Number => numberMetatable,
  72. LuaValueType.Function => functionMetatable,
  73. LuaValueType.Thread => threadMetatable,
  74. LuaValueType.UserData => value.UnsafeRead<ILuaUserData>().Metatable,
  75. LuaValueType.Table => value.UnsafeRead<LuaTable>().Metatable,
  76. _ => null
  77. };
  78. return result != null;
  79. }
  80. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  81. internal void SetMetatable(LuaValue value, LuaTable metatable)
  82. {
  83. switch (value.Type)
  84. {
  85. case LuaValueType.Nil:
  86. nilMetatable = metatable;
  87. break;
  88. case LuaValueType.Boolean:
  89. booleanMetatable = metatable;
  90. break;
  91. case LuaValueType.String:
  92. stringMetatable = metatable;
  93. break;
  94. case LuaValueType.Number:
  95. numberMetatable = metatable;
  96. break;
  97. case LuaValueType.Function:
  98. functionMetatable = metatable;
  99. break;
  100. case LuaValueType.Thread:
  101. threadMetatable = metatable;
  102. break;
  103. case LuaValueType.UserData:
  104. value.UnsafeRead<ILuaUserData>().Metatable = metatable;
  105. break;
  106. case LuaValueType.Table:
  107. value.UnsafeRead<LuaTable>().Metatable = metatable;
  108. break;
  109. }
  110. }
  111. internal UpValue GetOrAddUpValue(LuaThread thread, int registerIndex)
  112. {
  113. foreach (var upValue in openUpValues.AsSpan())
  114. {
  115. if (upValue.RegisterIndex == registerIndex && upValue.Thread == thread)
  116. {
  117. return upValue;
  118. }
  119. }
  120. var newUpValue = UpValue.Open(thread, registerIndex);
  121. openUpValues.Add(newUpValue);
  122. return newUpValue;
  123. }
  124. internal void CloseUpValues(LuaThread thread, int frameBase)
  125. {
  126. for (int i = 0; i < openUpValues.Length; i++)
  127. {
  128. var upValue = openUpValues[i];
  129. if (upValue.Thread != thread) continue;
  130. if (upValue.RegisterIndex >= frameBase)
  131. {
  132. upValue.Close();
  133. openUpValues.RemoveAtSwapBack(i);
  134. i--;
  135. }
  136. }
  137. }
  138. public unsafe LuaClosure Load(ReadOnlySpan<char> chunk, string chunkName, LuaTable? environment = null)
  139. {
  140. Prototype prototype;
  141. fixed (char* ptr = chunk)
  142. {
  143. prototype = Parser.Parse(this, new(ptr, chunk.Length), chunkName);
  144. }
  145. return new LuaClosure(MainThread, prototype, environment);
  146. }
  147. public LuaClosure Load(ReadOnlySpan<byte> chunk, string? chunkName = null, string mode = "bt", LuaTable? environment = null)
  148. {
  149. if (chunk.Length > 4)
  150. {
  151. if (chunk[0] == '\e')
  152. {
  153. return new LuaClosure(MainThread, Parser.UnDump(chunk, chunkName), environment);
  154. }
  155. }
  156. chunk = BomUtility.GetEncodingFromBytes(chunk, out var encoding);
  157. var charCount = encoding.GetCharCount(chunk);
  158. var pooled = ArrayPool<char>.Shared.Rent(charCount);
  159. try
  160. {
  161. var chars = pooled.AsSpan(0, charCount);
  162. encoding.GetChars(chunk, chars);
  163. chunkName ??= chars.ToString();
  164. return Load(chars, chunkName, environment);
  165. }
  166. finally
  167. {
  168. ArrayPool<char>.Shared.Return(pooled);
  169. }
  170. }
  171. }