LuaVirtualMachine.cs 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Globalization;
  3. using System.Runtime.CompilerServices;
  4. using System.Runtime.InteropServices;
  5. using Lua.Internal;
  6. namespace Lua.Runtime;
  7. [SuppressMessage("Reliability", "CA2012:Use ValueTasks correctly")]
  8. public static partial class LuaVirtualMachine
  9. {
  10. [StructLayout(LayoutKind.Auto)]
  11. [method: MethodImpl(MethodImplOptions.AggressiveInlining)]
  12. struct VirtualMachineExecutionContext(
  13. LuaState state,
  14. LuaStack stack,
  15. LuaValue[] resultsBuffer,
  16. Memory<LuaValue> buffer,
  17. LuaThread thread,
  18. in CallStackFrame frame,
  19. CancellationToken cancellationToken)
  20. {
  21. public readonly LuaState State = state;
  22. public readonly LuaStack Stack = stack;
  23. public Closure Closure = (Closure)frame.Function;
  24. public readonly LuaValue[] ResultsBuffer = resultsBuffer;
  25. public readonly Memory<LuaValue> Buffer = buffer;
  26. public readonly LuaThread Thread = thread;
  27. public Chunk Chunk => Closure.Proto;
  28. public int FrameBase = frame.Base;
  29. public int VariableArgumentCount = frame.VariableArgumentCount;
  30. public readonly CancellationToken CancellationToken = cancellationToken;
  31. public int Pc = -1;
  32. public Instruction Instruction;
  33. public int ResultCount;
  34. public int TaskResult;
  35. public ValueTask<int> Task;
  36. public bool IsTopLevel => BaseCallStackCount == Thread.CallStack.Count;
  37. readonly int BaseCallStackCount = thread.CallStack.Count;
  38. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  39. public bool Pop(Instruction instruction, int frameBase)
  40. {
  41. if (BaseCallStackCount == Thread.CallStack.Count) return false;
  42. var count = instruction.B - 1;
  43. var src = instruction.A + frameBase;
  44. if (count == -1) count = Stack.Count - src;
  45. return PopFromBuffer(Stack.GetBuffer().Slice(src, count));
  46. }
  47. [MethodImpl(MethodImplOptions.NoInlining)]
  48. public bool PopFromBuffer(Span<LuaValue> result)
  49. {
  50. ref var callStack = ref Thread.CallStack;
  51. Re:
  52. var frames = callStack.AsSpan();
  53. if (frames.Length == BaseCallStackCount) return false;
  54. ref readonly var frame = ref frames[^1];
  55. Pc = frame.CallerInstructionIndex;
  56. ref readonly var lastFrame = ref frames[^2];
  57. Closure = Unsafe.As<Closure>(lastFrame.Function);
  58. var callInstruction = Chunk.Instructions[Pc];
  59. FrameBase = lastFrame.Base;
  60. VariableArgumentCount = lastFrame.VariableArgumentCount;
  61. if (callInstruction.OpCode == OpCode.TailCall)
  62. {
  63. Thread.PopCallStackFrameUnsafe();
  64. goto Re;
  65. }
  66. var opCode = callInstruction.OpCode;
  67. if (opCode is OpCode.Eq or OpCode.Lt or OpCode.Le)
  68. {
  69. var compareResult = result.Length > 0 && result[0].ToBoolean();
  70. if ((frame.Flags & CallStackFrameFlags.ReversedLe) != 0)
  71. {
  72. compareResult = !compareResult;
  73. }
  74. if (compareResult != (callInstruction.A == 1))
  75. {
  76. Pc++;
  77. }
  78. Thread.PopCallStackFrameUnsafe(frame.Base);
  79. return true;
  80. }
  81. var target = callInstruction.A + FrameBase;
  82. var targetCount = result.Length;
  83. switch (opCode)
  84. {
  85. case OpCode.Call:
  86. {
  87. var c = callInstruction.C;
  88. if (c != 0)
  89. {
  90. targetCount = c - 1;
  91. }
  92. break;
  93. }
  94. case OpCode.TForCall:
  95. target += 3;
  96. targetCount = callInstruction.C;
  97. break;
  98. case OpCode.Self:
  99. Stack.Get(target) = result.Length == 0 ? LuaValue.Nil : result[0];
  100. Thread.PopCallStackFrameUnsafe(target + 2);
  101. return true;
  102. case OpCode.SetTable or OpCode.SetTabUp:
  103. targetCount = 0;
  104. break;
  105. // Other opcodes has one result
  106. default:
  107. targetCount = 1;
  108. break;
  109. }
  110. var count = Math.Min(result.Length, targetCount);
  111. Stack.EnsureCapacity(target + targetCount);
  112. var stackBuffer = Stack.GetBuffer();
  113. if (count > 0)
  114. {
  115. result[..count].CopyTo(stackBuffer.Slice(target, count));
  116. }
  117. if (targetCount > count)
  118. {
  119. stackBuffer.Slice(target + count, targetCount - count).Clear();
  120. }
  121. Stack.NotifyTop(target + targetCount);
  122. Thread.PopCallStackFrameUnsafe(target + targetCount);
  123. return true;
  124. }
  125. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  126. public void Push(in CallStackFrame frame)
  127. {
  128. Pc = -1;
  129. Closure = (frame.Function as Closure)!;
  130. FrameBase = frame.Base;
  131. VariableArgumentCount = frame.VariableArgumentCount;
  132. }
  133. public void PopOnTopCallStackFrames()
  134. {
  135. ref var callStack = ref Thread.CallStack;
  136. var count = callStack.Count;
  137. if (count == BaseCallStackCount) return;
  138. while (callStack.Count > BaseCallStackCount + 1)
  139. {
  140. callStack.TryPop();
  141. }
  142. Thread.PopCallStackFrame();
  143. }
  144. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  145. public void ClearResultsBuffer()
  146. {
  147. if (TaskResult == 0) return;
  148. if (TaskResult == 1)
  149. {
  150. ResultsBuffer[0] = default;
  151. return;
  152. }
  153. ResultsBuffer.AsSpan(0, TaskResult).Clear();
  154. }
  155. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  156. public void ClearResultsBuffer(int count)
  157. {
  158. if (count == 0) return;
  159. if (count == 1)
  160. {
  161. ResultsBuffer[0] = default;
  162. return;
  163. }
  164. ResultsBuffer.AsSpan(0, count).Clear();
  165. }
  166. public async ValueTask<int> ExecuteClosureAsyncImpl()
  167. {
  168. while (MoveNext(ref this, out var postOperation))
  169. {
  170. TaskResult = await Task;
  171. Task = default;
  172. Thread.PopCallStackFrame();
  173. switch (postOperation)
  174. {
  175. case PostOperationType.Nop: break;
  176. case PostOperationType.SetResult:
  177. var RA = Instruction.A + FrameBase;
  178. Stack.Get(RA) = TaskResult == 0 ? LuaValue.Nil : ResultsBuffer[0];
  179. Stack.NotifyTop(RA + 1);
  180. ClearResultsBuffer();
  181. break;
  182. case PostOperationType.TForCall:
  183. TForCallPostOperation(ref this);
  184. break;
  185. case PostOperationType.Call:
  186. CallPostOperation(ref this);
  187. break;
  188. case PostOperationType.TailCall:
  189. var resultsSpan = ResultsBuffer.AsSpan(0, TaskResult);
  190. if (!PopFromBuffer(resultsSpan))
  191. {
  192. ResultCount = TaskResult;
  193. resultsSpan.CopyTo(Buffer.Span);
  194. resultsSpan.Clear();
  195. LuaValueArrayPool.Return1024(ResultsBuffer);
  196. return TaskResult;
  197. }
  198. resultsSpan.Clear();
  199. break;
  200. case PostOperationType.Self:
  201. SelfPostOperation(ref this);
  202. break;
  203. case PostOperationType.Compare:
  204. ComparePostOperation(ref this);
  205. break;
  206. }
  207. }
  208. return ResultCount;
  209. }
  210. }
  211. enum PostOperationType
  212. {
  213. None,
  214. Nop,
  215. SetResult,
  216. TForCall,
  217. Call,
  218. TailCall,
  219. Self,
  220. Compare,
  221. }
  222. internal static ValueTask<int> ExecuteClosureAsync(LuaState luaState, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  223. {
  224. var thread = luaState.CurrentThread;
  225. ref readonly var frame = ref thread.GetCallStackFrames()[^1];
  226. var resultBuffer = LuaValueArrayPool.Rent1024();
  227. var context = new VirtualMachineExecutionContext(luaState, thread.Stack, resultBuffer, buffer, thread, in frame,
  228. cancellationToken);
  229. return context.ExecuteClosureAsyncImpl();
  230. }
  231. static bool MoveNext(ref VirtualMachineExecutionContext context, out PostOperationType postOperation)
  232. {
  233. postOperation = PostOperationType.None;
  234. try
  235. {
  236. // This is a label to restart the execution when new function is called or restarted
  237. Restart:
  238. ref var instructionsHead = ref context.Chunk.Instructions[0];
  239. var frameBase = context.FrameBase;
  240. var stack = context.Stack;
  241. stack.EnsureCapacity(frameBase + context.Chunk.MaxStackPosition);
  242. ref var constHead = ref MemoryMarshalEx.UnsafeElementAt(context.Chunk.Constants, 0);
  243. while (true)
  244. {
  245. var instructionRef = Unsafe.Add(ref instructionsHead, ++context.Pc);
  246. context.Instruction = instructionRef;
  247. switch (instructionRef.OpCode)
  248. {
  249. case OpCode.Move:
  250. var instruction = instructionRef;
  251. ref var stackHead = ref stack.FastGet(frameBase);
  252. var iA = instruction.A;
  253. Unsafe.Add(ref stackHead, iA) = Unsafe.Add(ref stackHead, instruction.UIntB);
  254. stack.NotifyTop(iA + frameBase + 1);
  255. continue;
  256. case OpCode.LoadK:
  257. instruction = instructionRef;
  258. stack.GetWithNotifyTop(instruction.A + frameBase) = Unsafe.Add(ref constHead, instruction.Bx);
  259. continue;
  260. case OpCode.LoadBool:
  261. instruction = instructionRef;
  262. stack.GetWithNotifyTop(instruction.A + frameBase) = instruction.B != 0;
  263. if (instruction.C != 0) context.Pc++;
  264. continue;
  265. case OpCode.LoadNil:
  266. instruction = instructionRef;
  267. var ra1 = instruction.A + frameBase + 1;
  268. var iB = instruction.B;
  269. stack.GetBuffer().Slice(ra1 - 1, iB + 1).Clear();
  270. stack.NotifyTop(ra1 + iB);
  271. continue;
  272. case OpCode.GetUpVal:
  273. instruction = instructionRef;
  274. stack.GetWithNotifyTop(instruction.A + frameBase) = context.Closure.GetUpValue(instruction.B);
  275. continue;
  276. case OpCode.GetTabUp:
  277. case OpCode.GetTable:
  278. instruction = instructionRef;
  279. stackHead = ref stack.FastGet(frameBase);
  280. ref readonly var vc = ref RKC(ref stackHead, ref constHead, instruction);
  281. ref readonly var vb = ref (instruction.OpCode == OpCode.GetTable ? ref Unsafe.Add(ref stackHead, instruction.UIntB) : ref context.Closure.GetUpValueRef(instruction.B));
  282. var doRestart = false;
  283. if (vb.TryReadTable(out var luaTable) && luaTable.TryGetValue(vc, out var resultValue) || GetTableValueSlowPath(vb, vc, ref context, out resultValue, out doRestart))
  284. {
  285. if (doRestart) goto Restart;
  286. stack.GetWithNotifyTop(instruction.A + frameBase) = resultValue;
  287. continue;
  288. }
  289. postOperation = PostOperationType.SetResult;
  290. return true;
  291. case OpCode.SetTabUp:
  292. instruction = instructionRef;
  293. stackHead = ref stack.FastGet(frameBase);
  294. vb = ref RKB(ref stackHead, ref constHead, instruction);
  295. if (vb.TryReadNumber(out var numB))
  296. {
  297. if (double.IsNaN(numB))
  298. {
  299. ThrowLuaRuntimeException(ref context, "table index is NaN");
  300. return true;
  301. }
  302. }
  303. var table = context.Closure.GetUpValue(instruction.A);
  304. if (table.TryReadTable(out luaTable))
  305. {
  306. ref var valueRef = ref luaTable.FindValue(vb);
  307. if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
  308. {
  309. valueRef = RKC(ref stackHead, ref constHead, instruction);
  310. continue;
  311. }
  312. }
  313. vc = ref RKC(ref stackHead, ref constHead, instruction);
  314. if (SetTableValueSlowPath(table, vb, vc, ref context, out doRestart))
  315. {
  316. if (doRestart) goto Restart;
  317. continue;
  318. }
  319. postOperation = PostOperationType.Nop;
  320. return true;
  321. case OpCode.SetUpVal:
  322. instruction = instructionRef;
  323. context.Closure.SetUpValue(instruction.B, stack.FastGet(instruction.A + frameBase));
  324. continue;
  325. case OpCode.SetTable:
  326. instruction = instructionRef;
  327. stackHead = ref stack.FastGet(frameBase);
  328. vb = ref RKB(ref stackHead, ref constHead, instruction);
  329. if (vb.TryReadNumber(out numB))
  330. {
  331. if (double.IsNaN(numB))
  332. {
  333. ThrowLuaRuntimeException(ref context, " table index is NaN");
  334. return true;
  335. }
  336. }
  337. table = Unsafe.Add(ref stackHead, instruction.A);
  338. if (table.TryReadTable(out luaTable))
  339. {
  340. ref var valueRef = ref luaTable.FindValue(vb);
  341. if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
  342. {
  343. valueRef = RKC(ref stackHead, ref constHead, instruction);
  344. continue;
  345. }
  346. }
  347. vc = ref RKC(ref stackHead, ref constHead, instruction);
  348. if (SetTableValueSlowPath(table, vb, vc, ref context, out doRestart))
  349. {
  350. if (doRestart) goto Restart;
  351. continue;
  352. }
  353. postOperation = PostOperationType.Nop;
  354. return true;
  355. case OpCode.NewTable:
  356. instruction = instructionRef;
  357. stack.GetWithNotifyTop(instruction.A + frameBase) = new LuaTable(instruction.B, instruction.C);
  358. continue;
  359. case OpCode.Self:
  360. instruction = instructionRef;
  361. iA = instruction.A;
  362. stackHead = ref stack.FastGet(frameBase);
  363. vc = ref RKC(ref stackHead, ref constHead, instruction);
  364. table = Unsafe.Add(ref stackHead, instruction.UIntB);
  365. doRestart = false;
  366. if ((table.TryReadTable(out luaTable) && luaTable.TryGetValue(vc, out resultValue)) || GetTableValueSlowPath(table, vc, ref context, out resultValue, out doRestart))
  367. {
  368. if (doRestart) goto Restart;
  369. Unsafe.Add(ref stackHead, iA) = resultValue;
  370. Unsafe.Add(ref stackHead, iA + 1) = table;
  371. stack.NotifyTop(iA + frameBase + 2);
  372. continue;
  373. }
  374. postOperation = PostOperationType.Self;
  375. return true;
  376. case OpCode.Add:
  377. instruction = instructionRef;
  378. iA = instruction.A;
  379. stackHead = ref stack.FastGet(frameBase);
  380. vb = ref RKB(ref stackHead, ref constHead, instruction);
  381. vc = ref RKC(ref stackHead, ref constHead, instruction);
  382. if (vb.Type == LuaValueType.Number && vc.Type == LuaValueType.Number)
  383. {
  384. Unsafe.Add(ref stackHead, iA) = vb.UnsafeReadDouble() + vc.UnsafeReadDouble();
  385. stack.NotifyTop(iA + frameBase + 1);
  386. continue;
  387. }
  388. if (vb.TryReadDouble(out numB) && vc.TryReadDouble(out var numC))
  389. {
  390. Unsafe.Add(ref stackHead, iA) = numB + numC;
  391. stack.NotifyTop(iA + frameBase + 1);
  392. continue;
  393. }
  394. if (ExecuteBinaryOperationMetaMethod(vb, vc, ref context, Metamethods.Add, "add", out doRestart))
  395. {
  396. if (doRestart) goto Restart;
  397. continue;
  398. }
  399. postOperation = PostOperationType.SetResult;
  400. return true;
  401. case OpCode.Sub:
  402. instruction = instructionRef;
  403. iA = instruction.A;
  404. stackHead = ref stack.FastGet(frameBase);
  405. vb = ref RKB(ref stackHead, ref constHead, instruction);
  406. vc = ref RKC(ref stackHead, ref constHead, instruction);
  407. if (vb.Type == LuaValueType.Number && vc.Type == LuaValueType.Number)
  408. {
  409. ra1 = iA + frameBase + 1;
  410. Unsafe.Add(ref stackHead, iA) = vb.UnsafeReadDouble() - vc.UnsafeReadDouble();
  411. stack.NotifyTop(ra1);
  412. continue;
  413. }
  414. if (vb.TryReadDouble(out numB) && vc.TryReadDouble(out numC))
  415. {
  416. ra1 = iA + frameBase + 1;
  417. Unsafe.Add(ref stackHead, iA) = numB - numC;
  418. stack.NotifyTop(ra1);
  419. continue;
  420. }
  421. if (ExecuteBinaryOperationMetaMethod(vb, vc, ref context, Metamethods.Sub, "sub", out doRestart))
  422. {
  423. if (doRestart) goto Restart;
  424. continue;
  425. }
  426. postOperation = PostOperationType.SetResult;
  427. return true;
  428. case OpCode.Mul:
  429. instruction = instructionRef;
  430. iA = instruction.A;
  431. stackHead = ref stack.FastGet(frameBase);
  432. vb = ref RKB(ref stackHead, ref constHead, instruction);
  433. vc = ref RKC(ref stackHead, ref constHead, instruction);
  434. if (vb.Type == LuaValueType.Number && vc.Type == LuaValueType.Number)
  435. {
  436. ra1 = iA + frameBase + 1;
  437. Unsafe.Add(ref stackHead, iA) = vb.UnsafeReadDouble() * vc.UnsafeReadDouble();
  438. stack.NotifyTop(ra1);
  439. continue;
  440. }
  441. if (vb.TryReadDouble(out numB) && vc.TryReadDouble(out numC))
  442. {
  443. ra1 = iA + frameBase + 1;
  444. Unsafe.Add(ref stackHead, iA) = numB * numC;
  445. stack.NotifyTop(ra1);
  446. continue;
  447. }
  448. if (ExecuteBinaryOperationMetaMethod(vb, vc, ref context, Metamethods.Mul, "mul", out doRestart))
  449. {
  450. if (doRestart) goto Restart;
  451. continue;
  452. }
  453. postOperation = PostOperationType.SetResult;
  454. return true;
  455. case OpCode.Div:
  456. instruction = instructionRef;
  457. iA = instruction.A;
  458. stackHead = ref stack.FastGet(frameBase);
  459. vb = ref RKB(ref stackHead, ref constHead, instruction);
  460. vc = ref RKC(ref stackHead, ref constHead, instruction);
  461. if (vb.Type == LuaValueType.Number && vc.Type == LuaValueType.Number)
  462. {
  463. ra1 = iA + frameBase + 1;
  464. Unsafe.Add(ref stackHead, iA) = vb.UnsafeReadDouble() / vc.UnsafeReadDouble();
  465. stack.NotifyTop(ra1);
  466. continue;
  467. }
  468. if (vb.TryReadDouble(out numB) && vc.TryReadDouble(out numC))
  469. {
  470. ra1 = iA + frameBase + 1;
  471. Unsafe.Add(ref stackHead, iA) = numB / numC;
  472. stack.NotifyTop(ra1);
  473. continue;
  474. }
  475. if (ExecuteBinaryOperationMetaMethod(vb, vc, ref context, Metamethods.Div, "div", out doRestart))
  476. {
  477. if (doRestart) goto Restart;
  478. continue;
  479. }
  480. postOperation = PostOperationType.SetResult;
  481. return true;
  482. case OpCode.Mod:
  483. instruction = instructionRef;
  484. iA = instruction.A;
  485. stackHead = ref stack.FastGet(frameBase);
  486. vb = ref RKB(ref stackHead, ref constHead, instruction);
  487. vc = ref RKC(ref stackHead, ref constHead, instruction);
  488. if (vb.TryReadDouble(out numB) && vc.TryReadDouble(out numC))
  489. {
  490. var mod = numB % numC;
  491. if ((numC > 0 && mod < 0) || (numC < 0 && mod > 0))
  492. {
  493. mod += numC;
  494. }
  495. Unsafe.Add(ref stackHead, iA) = mod;
  496. continue;
  497. }
  498. if (ExecuteBinaryOperationMetaMethod(vb, vc, ref context, Metamethods.Mod, "mod", out doRestart))
  499. {
  500. if (doRestart) goto Restart;
  501. continue;
  502. }
  503. postOperation = PostOperationType.SetResult;
  504. return true;
  505. case OpCode.Pow:
  506. instruction = instructionRef;
  507. iA = instruction.A;
  508. stackHead = ref stack.FastGet(frameBase);
  509. vb = ref RKB(ref stackHead, ref constHead, instruction);
  510. vc = ref RKC(ref stackHead, ref constHead, instruction);
  511. if (vb.TryReadDouble(out numB) && vc.TryReadDouble(out numC))
  512. {
  513. ra1 = iA + frameBase + 1;
  514. Unsafe.Add(ref stackHead, iA) = Math.Pow(numB, numC);
  515. stack.NotifyTop(ra1);
  516. continue;
  517. }
  518. if (ExecuteBinaryOperationMetaMethod(vb, vc, ref context, Metamethods.Pow, "pow", out doRestart))
  519. {
  520. if (doRestart) goto Restart;
  521. continue;
  522. }
  523. postOperation = PostOperationType.SetResult;
  524. return true;
  525. case OpCode.Unm:
  526. instruction = instructionRef;
  527. iA = instruction.A;
  528. stackHead = ref stack.FastGet(frameBase);
  529. vb = ref Unsafe.Add(ref stackHead, instruction.UIntB);
  530. if (vb.TryReadDouble(out numB))
  531. {
  532. ra1 = iA + frameBase + 1;
  533. Unsafe.Add(ref stackHead, iA) = -numB;
  534. stack.NotifyTop(ra1);
  535. continue;
  536. }
  537. if (ExecuteUnaryOperationMetaMethod(vb, ref context, Metamethods.Unm, "unm", false, out doRestart))
  538. {
  539. if (doRestart) goto Restart;
  540. continue;
  541. }
  542. postOperation = PostOperationType.SetResult;
  543. return true;
  544. case OpCode.Not:
  545. instruction = instructionRef;
  546. iA = instruction.A;
  547. ra1 = iA + frameBase + 1;
  548. stackHead = ref stack.FastGet(frameBase);
  549. Unsafe.Add(ref stackHead, iA) = !Unsafe.Add(ref stackHead, instruction.UIntB).ToBoolean();
  550. stack.NotifyTop(ra1);
  551. continue;
  552. case OpCode.Len:
  553. instruction = instructionRef;
  554. stackHead = ref stack.FastGet(frameBase);
  555. vb = ref Unsafe.Add(ref stackHead, instruction.UIntB);
  556. if (vb.TryReadString(out var str))
  557. {
  558. iA = instruction.A;
  559. ra1 = iA + frameBase + 1;
  560. Unsafe.Add(ref stackHead, iA) = str.Length;
  561. stack.NotifyTop(ra1);
  562. continue;
  563. }
  564. if (ExecuteUnaryOperationMetaMethod(vb, ref context, Metamethods.Len, "get length of", true, out doRestart))
  565. {
  566. if (doRestart) goto Restart;
  567. continue;
  568. }
  569. postOperation = PostOperationType.SetResult;
  570. return true;
  571. case OpCode.Concat:
  572. if (Concat(ref context, out doRestart))
  573. {
  574. if (doRestart) goto Restart;
  575. continue;
  576. }
  577. postOperation = PostOperationType.SetResult;
  578. return true;
  579. case OpCode.Jmp:
  580. instruction = instructionRef;
  581. context.Pc += instruction.SBx;
  582. iA = instruction.A;
  583. if (iA != 0)
  584. {
  585. context.State.CloseUpValues(context.Thread, frameBase + iA - 1);
  586. }
  587. continue;
  588. case OpCode.Eq:
  589. instruction = instructionRef;
  590. iA = instruction.A;
  591. stackHead = ref stack.Get(frameBase);
  592. vb = ref RKB(ref stackHead, ref constHead, instruction);
  593. vc = ref RKC(ref stackHead, ref constHead, instruction);
  594. if (vb == vc)
  595. {
  596. if (iA != 1)
  597. {
  598. context.Pc++;
  599. }
  600. continue;
  601. }
  602. if (ExecuteCompareOperationMetaMethod(vb, vc, ref context, Metamethods.Eq, null, out doRestart))
  603. {
  604. if (doRestart) goto Restart;
  605. continue;
  606. }
  607. postOperation = PostOperationType.Compare;
  608. return true;
  609. case OpCode.Lt:
  610. instruction = instructionRef;
  611. iA = instruction.A;
  612. stackHead = ref stack.Get(frameBase);
  613. vb = ref RKB(ref stackHead, ref constHead, instruction);
  614. vc = ref RKC(ref stackHead, ref constHead, instruction);
  615. if (vb.TryReadNumber(out numB) && vc.TryReadNumber(out numC))
  616. {
  617. var compareResult = numB < numC;
  618. if (compareResult != (iA == 1))
  619. {
  620. context.Pc++;
  621. }
  622. continue;
  623. }
  624. if (vb.TryReadString(out var strB) && vc.TryReadString(out var strC))
  625. {
  626. var compareResult = StringComparer.Ordinal.Compare(strB, strC) < 0;
  627. if (compareResult != (iA == 1))
  628. {
  629. context.Pc++;
  630. }
  631. continue;
  632. }
  633. if (ExecuteCompareOperationMetaMethod(vb, vc, ref context, Metamethods.Lt, "less than", out doRestart))
  634. {
  635. if (doRestart) goto Restart;
  636. continue;
  637. }
  638. postOperation = PostOperationType.Compare;
  639. return true;
  640. case OpCode.Le:
  641. instruction = instructionRef;
  642. iA = instruction.A;
  643. stackHead = ref stack.Get(frameBase);
  644. vb = ref RKB(ref stackHead, ref constHead, instruction);
  645. vc = ref RKC(ref stackHead, ref constHead, instruction);
  646. if (vb.TryReadNumber(out numB) && vc.TryReadNumber(out numC))
  647. {
  648. var compareResult = numB <= numC;
  649. if (compareResult != (iA == 1))
  650. {
  651. context.Pc++;
  652. }
  653. continue;
  654. }
  655. if (vb.TryReadString(out strB) && vc.TryReadString(out strC))
  656. {
  657. var compareResult = StringComparer.Ordinal.Compare(strB, strC) <= 0;
  658. if (compareResult != (iA == 1))
  659. {
  660. context.Pc++;
  661. }
  662. continue;
  663. }
  664. if (ExecuteCompareOperationMetaMethod(vb, vc, ref context, Metamethods.Le, "less than or equals", out doRestart))
  665. {
  666. if (doRestart) goto Restart;
  667. continue;
  668. }
  669. postOperation = PostOperationType.Compare;
  670. return true;
  671. case OpCode.Test:
  672. instruction = instructionRef;
  673. if (stack.Get(instruction.A + frameBase).ToBoolean() != (instruction.C == 1))
  674. {
  675. context.Pc++;
  676. }
  677. continue;
  678. case OpCode.TestSet:
  679. instruction = instructionRef;
  680. vb = ref stack.Get(instruction.B + frameBase);
  681. if (vb.ToBoolean() != (instruction.C == 1))
  682. {
  683. context.Pc++;
  684. }
  685. else
  686. {
  687. stack.GetWithNotifyTop(instruction.A + frameBase) = vb;
  688. }
  689. continue;
  690. case OpCode.Call:
  691. if (Call(ref context, out doRestart))
  692. {
  693. if (doRestart) goto Restart;
  694. continue;
  695. }
  696. postOperation = PostOperationType.Call;
  697. return true;
  698. case OpCode.TailCall:
  699. if (TailCall(ref context, out doRestart))
  700. {
  701. if (doRestart) goto Restart;
  702. if (context.IsTopLevel) goto End;
  703. continue;
  704. }
  705. postOperation = PostOperationType.TailCall;
  706. return true;
  707. case OpCode.Return:
  708. instruction = instructionRef;
  709. iA = instruction.A;
  710. ra1 = iA + frameBase + 1;
  711. context.State.CloseUpValues(context.Thread, frameBase);
  712. if (context.Pop(instruction, frameBase)) goto Restart;
  713. var retCount = instruction.B - 1;
  714. if (retCount == -1)
  715. {
  716. retCount = stack.Count - (ra1 - 1);
  717. }
  718. if (0 < retCount)
  719. {
  720. stack.GetBuffer().Slice(ra1 - 1, retCount).CopyTo(context.Buffer.Span);
  721. }
  722. context.ResultCount = retCount;
  723. goto End;
  724. case OpCode.ForLoop:
  725. ref var indexRef = ref stack.Get(instructionRef.A + frameBase);
  726. var limit = Unsafe.Add(ref indexRef, 1).UnsafeReadDouble();
  727. var step = Unsafe.Add(ref indexRef, 2).UnsafeReadDouble();
  728. var index = indexRef.UnsafeReadDouble() + step;
  729. if (step >= 0 ? index <= limit : limit <= index)
  730. {
  731. context.Pc += instructionRef.SBx;
  732. indexRef = index;
  733. Unsafe.Add(ref indexRef, 3) = index;
  734. stack.NotifyTop(instructionRef.A + frameBase + 4);
  735. continue;
  736. }
  737. stack.NotifyTop(instructionRef.A + frameBase + 1);
  738. continue;
  739. case OpCode.ForPrep:
  740. indexRef = ref stack.Get(instructionRef.A + frameBase);
  741. if (!indexRef.TryReadDouble(out var init))
  742. {
  743. ThrowLuaRuntimeException(ref context, "'for' initial value must be a number");
  744. return true;
  745. }
  746. if (!LuaValue.TryReadOrSetDouble(ref Unsafe.Add(ref indexRef, 1), out _))
  747. {
  748. ThrowLuaRuntimeException(ref context, "'for' limit must be a number");
  749. return true;
  750. }
  751. if (!LuaValue.TryReadOrSetDouble(ref Unsafe.Add(ref indexRef, 2), out step))
  752. {
  753. ThrowLuaRuntimeException(ref context, "'for' step must be a number");
  754. return true;
  755. }
  756. indexRef = init - step;
  757. stack.NotifyTop(instructionRef.A + frameBase + 1);
  758. context.Pc += instructionRef.SBx;
  759. continue;
  760. case OpCode.TForCall:
  761. if (TForCall(ref context, out doRestart))
  762. {
  763. if (doRestart) goto Restart;
  764. continue;
  765. }
  766. postOperation = PostOperationType.TForCall;
  767. return true;
  768. case OpCode.TForLoop:
  769. instruction = instructionRef;
  770. iA = instruction.A;
  771. ra1 = iA + frameBase + 1;
  772. ref var forState = ref stack.Get(ra1);
  773. if (forState.Type is not LuaValueType.Nil)
  774. {
  775. Unsafe.Add(ref forState, -1) = forState;
  776. context.Pc += instruction.SBx;
  777. }
  778. continue;
  779. case OpCode.SetList:
  780. SetList(ref context);
  781. continue;
  782. case OpCode.Closure:
  783. instruction = instructionRef;
  784. iA = instruction.A;
  785. ra1 = iA + frameBase + 1;
  786. stack.EnsureCapacity(ra1);
  787. stack.Get(ra1 - 1) = new Closure(context.State, context.Chunk.Functions[instruction.SBx]);
  788. stack.NotifyTop(ra1);
  789. continue;
  790. case OpCode.VarArg:
  791. instruction = instructionRef;
  792. iA = instruction.A;
  793. ra1 = iA + frameBase + 1;
  794. var frameVariableArgumentCount = context.VariableArgumentCount;
  795. var count = instruction.B == 0
  796. ? frameVariableArgumentCount
  797. : instruction.B - 1;
  798. var ra = ra1 - 1;
  799. stack.EnsureCapacity(ra + count);
  800. stackHead = ref stack.Get(0);
  801. for (int i = 0; i < count; i++)
  802. {
  803. Unsafe.Add(ref stackHead, ra + i) = frameVariableArgumentCount > i
  804. ? Unsafe.Add(ref stackHead, frameBase - (frameVariableArgumentCount - i))
  805. : default;
  806. }
  807. stack.NotifyTop(ra + count);
  808. continue;
  809. case OpCode.ExtraArg:
  810. default:
  811. ThrowLuaNotImplementedException(ref context, context.Instruction.OpCode);
  812. return true;
  813. }
  814. }
  815. End:
  816. postOperation = PostOperationType.None;
  817. LuaValueArrayPool.Return1024(context.ResultsBuffer);
  818. return false;
  819. }
  820. catch (Exception e)
  821. {
  822. context.State.CloseUpValues(context.Thread, context.FrameBase);
  823. LuaValueArrayPool.Return1024(context.ResultsBuffer, true);
  824. if (e is not LuaRuntimeException)
  825. {
  826. var newException = new LuaRuntimeException(context.State.GetTraceback(), e);
  827. context.PopOnTopCallStackFrames();
  828. context = default;
  829. throw newException;
  830. }
  831. context.PopOnTopCallStackFrames();
  832. throw;
  833. }
  834. }
  835. static void ThrowLuaRuntimeException(ref VirtualMachineExecutionContext context, string message)
  836. {
  837. throw new LuaRuntimeException(context.State.GetTraceback(), message);
  838. }
  839. static void ThrowLuaNotImplementedException(ref VirtualMachineExecutionContext context, OpCode opcode)
  840. {
  841. throw new LuaRuntimeException(context.State.GetTraceback(), $"OpCode {opcode} is not implemented");
  842. }
  843. static void SelfPostOperation(ref VirtualMachineExecutionContext context)
  844. {
  845. var stack = context.Stack;
  846. var instruction = context.Instruction;
  847. var RA = instruction.A + context.FrameBase;
  848. var RB = instruction.B + context.FrameBase;
  849. ref var stackHead = ref stack.Get(0);
  850. var table = Unsafe.Add(ref stackHead, RB);
  851. Unsafe.Add(ref stackHead, RA + 1) = table;
  852. Unsafe.Add(ref stackHead, RA) = context.TaskResult == 0 ? LuaValue.Nil : context.ResultsBuffer[0];
  853. stack.NotifyTop(RA + 2);
  854. context.ClearResultsBuffer();
  855. }
  856. static bool Concat(ref VirtualMachineExecutionContext context, out bool doRestart)
  857. {
  858. var instruction = context.Instruction;
  859. var stack = context.Stack;
  860. var RA = instruction.A + context.FrameBase;
  861. stack.EnsureCapacity(RA + 1);
  862. ref var stackHead = ref stack.Get(context.FrameBase);
  863. ref var constHead = ref MemoryMarshalEx.UnsafeElementAt(context.Chunk.Constants, 0);
  864. var vb = RKB(ref stackHead, ref constHead, instruction);
  865. var vc = RKC(ref stackHead, ref constHead, instruction);
  866. var bIsValid = vb.TryReadString(out var strB);
  867. var cIsValid = vc.TryReadString(out var strC);
  868. if (!bIsValid && vb.TryReadDouble(out var numB))
  869. {
  870. strB = numB.ToString(CultureInfo.InvariantCulture);
  871. bIsValid = true;
  872. }
  873. if (!cIsValid && vc.TryReadDouble(out var numC))
  874. {
  875. strC = numC.ToString(CultureInfo.InvariantCulture);
  876. cIsValid = true;
  877. }
  878. if (bIsValid && cIsValid)
  879. {
  880. stack.Get(RA) = strB + strC;
  881. stack.NotifyTop(RA + 1);
  882. doRestart = false;
  883. return true;
  884. }
  885. return ExecuteBinaryOperationMetaMethod(vb, vc, ref context, Metamethods.Concat, "concat", out doRestart);
  886. }
  887. static bool Call(ref VirtualMachineExecutionContext context, out bool doRestart)
  888. {
  889. var instruction = context.Instruction;
  890. var RA = instruction.A + context.FrameBase;
  891. var va = context.Stack.Get(RA);
  892. if (!va.TryReadFunction(out var func))
  893. {
  894. if (va.TryGetMetamethod(context.State, Metamethods.Call, out var metamethod) &&
  895. metamethod.TryReadFunction(out func))
  896. {
  897. }
  898. else
  899. {
  900. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "call", va);
  901. }
  902. }
  903. var thread = context.Thread;
  904. var (newBase, argumentCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, instruction, RA);
  905. var newFrame = func.CreateNewFrame(ref context, newBase, variableArgumentCount);
  906. thread.PushCallStackFrame(newFrame);
  907. if (func is Closure)
  908. {
  909. context.Push(newFrame);
  910. doRestart = true;
  911. return true;
  912. }
  913. doRestart = false;
  914. return FuncCall(ref context, in newFrame, func, newBase, argumentCount);
  915. static bool FuncCall(ref VirtualMachineExecutionContext context, in CallStackFrame newFrame, LuaFunction func, int newBase, int argumentCount)
  916. {
  917. var task = func.Invoke(ref context, newFrame, argumentCount);
  918. if (!task.IsCompleted)
  919. {
  920. context.Task = task;
  921. return false;
  922. }
  923. var awaiter = task.GetAwaiter();
  924. context.Thread.PopCallStackFrameUnsafe(newBase);
  925. context.TaskResult = awaiter.GetResult();
  926. var instruction = context.Instruction;
  927. var rawResultCount = context.TaskResult;
  928. var resultCount = rawResultCount;
  929. var ic = instruction.C;
  930. if (ic != 0)
  931. {
  932. resultCount = ic - 1;
  933. }
  934. if (resultCount == 0)
  935. {
  936. context.Stack.Pop();
  937. }
  938. else
  939. {
  940. var stack = context.Stack;
  941. var RA = instruction.A + context.FrameBase;
  942. stack.EnsureCapacity(RA + resultCount);
  943. ref var stackHead = ref stack.Get(RA);
  944. var results = context.ResultsBuffer.AsSpan(0, rawResultCount);
  945. for (int i = 0; i < resultCount; i++)
  946. {
  947. Unsafe.Add(ref stackHead, i) = i >= rawResultCount
  948. ? default
  949. : results[i];
  950. }
  951. stack.NotifyTop(RA + resultCount);
  952. results.Clear();
  953. }
  954. return true;
  955. }
  956. }
  957. static void CallPostOperation(ref VirtualMachineExecutionContext context)
  958. {
  959. var instruction = context.Instruction;
  960. var rawResultCount = context.TaskResult;
  961. var resultCount = rawResultCount;
  962. var ic = instruction.C;
  963. if (ic != 0)
  964. {
  965. resultCount = ic - 1;
  966. }
  967. if (resultCount == 0)
  968. {
  969. context.Stack.Pop();
  970. }
  971. else
  972. {
  973. var stack = context.Stack;
  974. var RA = instruction.A + context.FrameBase;
  975. stack.EnsureCapacity(RA + resultCount);
  976. ref var stackHead = ref stack.Get(RA);
  977. var results = context.ResultsBuffer.AsSpan(0, rawResultCount);
  978. for (int i = 0; i < resultCount; i++)
  979. {
  980. Unsafe.Add(ref stackHead, i) = i >= rawResultCount
  981. ? default
  982. : results[i];
  983. }
  984. stack.NotifyTop(RA + resultCount);
  985. results.Clear();
  986. }
  987. }
  988. static bool TailCall(ref VirtualMachineExecutionContext context, out bool doRestart)
  989. {
  990. var instruction = context.Instruction;
  991. var stack = context.Stack;
  992. var RA = instruction.A + context.FrameBase;
  993. var state = context.State;
  994. var thread = context.Thread;
  995. state.CloseUpValues(thread, context.FrameBase);
  996. var va = stack.Get(RA);
  997. if (!va.TryReadFunction(out var func))
  998. {
  999. if (!va.TryGetMetamethod(state, Metamethods.Call, out var metamethod) &&
  1000. !metamethod.TryReadFunction(out func))
  1001. {
  1002. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "call", metamethod);
  1003. }
  1004. }
  1005. var (newBase, argumentCount, variableArgumentCount) = PrepareForFunctionTailCall(thread, func, instruction, RA);
  1006. var newFrame = func.CreateNewFrame(ref context, newBase, variableArgumentCount);
  1007. thread.PushCallStackFrame(newFrame);
  1008. context.Push(newFrame);
  1009. if (func is Closure)
  1010. {
  1011. doRestart = true;
  1012. return true;
  1013. }
  1014. doRestart = false;
  1015. var task = func.Invoke(ref context, newFrame, argumentCount);
  1016. if (!task.IsCompleted)
  1017. {
  1018. context.Task = task;
  1019. return false;
  1020. }
  1021. context.Thread.PopCallStackFrame();
  1022. doRestart = true;
  1023. var awaiter = task.GetAwaiter();
  1024. var resultCount = awaiter.GetResult();
  1025. var resultsSpan = context.ResultsBuffer.AsSpan(0, resultCount);
  1026. if (!context.PopFromBuffer(resultsSpan))
  1027. {
  1028. doRestart = false;
  1029. context.ResultCount = resultCount;
  1030. resultsSpan.CopyTo(context.Buffer.Span);
  1031. }
  1032. resultsSpan.Clear();
  1033. return true;
  1034. }
  1035. static bool TForCall(ref VirtualMachineExecutionContext context, out bool doRestart)
  1036. {
  1037. doRestart = false;
  1038. var instruction = context.Instruction;
  1039. var stack = context.Stack;
  1040. var RA = instruction.A + context.FrameBase;
  1041. var iteratorRaw = stack.Get(RA);
  1042. if (!iteratorRaw.TryReadFunction(out var iterator))
  1043. {
  1044. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "call", iteratorRaw);
  1045. }
  1046. var newBase = RA + 3 + instruction.C;
  1047. stack.Get(newBase) = stack.Get(RA + 1);
  1048. stack.Get(newBase + 1) = stack.Get(RA + 2);
  1049. stack.NotifyTop(newBase + 2);
  1050. var newFrame = iterator.CreateNewFrame(ref context, newBase);
  1051. context.Thread.PushCallStackFrame(newFrame);
  1052. if (iterator is Closure)
  1053. {
  1054. context.Push(newFrame);
  1055. doRestart = true;
  1056. return true;
  1057. }
  1058. var task = iterator.Invoke(ref context, newFrame, 2);
  1059. if (!task.IsCompleted)
  1060. {
  1061. context.Task = task;
  1062. return false;
  1063. }
  1064. var awaiter = task.GetAwaiter();
  1065. context.TaskResult = awaiter.GetResult();
  1066. context.Thread.PopCallStackFrame();
  1067. TForCallPostOperation(ref context);
  1068. return true;
  1069. }
  1070. static void TForCallPostOperation(ref VirtualMachineExecutionContext context)
  1071. {
  1072. var stack = context.Stack;
  1073. var instruction = context.Instruction;
  1074. var RA = instruction.A + context.FrameBase;
  1075. var resultBuffer = context.ResultsBuffer;
  1076. var resultCount = context.TaskResult;
  1077. stack.EnsureCapacity(RA + instruction.C + 3);
  1078. for (int i = 1; i <= instruction.C; i++)
  1079. {
  1080. var index = i - 1;
  1081. stack.Get(RA + 2 + i) = index >= resultCount
  1082. ? LuaValue.Nil
  1083. : resultBuffer[i - 1];
  1084. }
  1085. stack.NotifyTop(RA + instruction.C + 3);
  1086. context.ClearResultsBuffer(resultCount);
  1087. }
  1088. static void SetList(ref VirtualMachineExecutionContext context)
  1089. {
  1090. var instruction = context.Instruction;
  1091. var stack = context.Stack;
  1092. var RA = instruction.A + context.FrameBase;
  1093. if (!stack.Get(RA).TryReadTable(out var table))
  1094. {
  1095. throw new LuaException("internal error");
  1096. }
  1097. var count = instruction.B == 0
  1098. ? stack.Count - (RA + 1)
  1099. : instruction.B;
  1100. table.EnsureArrayCapacity((instruction.C - 1) * 50 + count);
  1101. stack.GetBuffer().Slice(RA + 1, count)
  1102. .CopyTo(table.GetArraySpan()[((instruction.C - 1) * 50)..]);
  1103. stack.PopUntil(RA + 1);
  1104. }
  1105. static void ComparePostOperation(ref VirtualMachineExecutionContext context)
  1106. {
  1107. var compareResult = context.TaskResult != 0 && context.ResultsBuffer[0].ToBoolean();
  1108. if (compareResult != (context.Instruction.A == 1))
  1109. {
  1110. context.Pc++;
  1111. }
  1112. context.ClearResultsBuffer();
  1113. }
  1114. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1115. static ref readonly LuaValue RKB(ref LuaValue stack, ref LuaValue constants, Instruction instruction)
  1116. {
  1117. var index = instruction.UIntB;
  1118. return ref (index >= 256 ? ref Unsafe.Add(ref constants, index - 256) : ref Unsafe.Add(ref stack, index));
  1119. }
  1120. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1121. static ref readonly LuaValue RKC(ref LuaValue stack, ref LuaValue constants, Instruction instruction)
  1122. {
  1123. var index = instruction.UIntC;
  1124. return ref (index >= 256 ? ref Unsafe.Add(ref constants, index - 256) : ref Unsafe.Add(ref stack, index));
  1125. }
  1126. [MethodImpl(MethodImplOptions.NoInlining)]
  1127. static bool GetTableValueSlowPath(LuaValue table, LuaValue key, ref VirtualMachineExecutionContext context, out LuaValue value, out bool doRestart)
  1128. {
  1129. var targetTable = table;
  1130. const int MAX_LOOP = 100;
  1131. doRestart = false;
  1132. var skip = targetTable.Type == LuaValueType.Table;
  1133. for (int i = 0; i < MAX_LOOP; i++)
  1134. {
  1135. if (table.TryReadTable(out var luaTable))
  1136. {
  1137. if (!skip && luaTable.TryGetValue(key, out value))
  1138. {
  1139. return true;
  1140. }
  1141. skip = false;
  1142. var metatable = luaTable.Metatable;
  1143. if (metatable != null && metatable.TryGetValue(Metamethods.Index, out table))
  1144. {
  1145. goto Function;
  1146. }
  1147. value = default;
  1148. return true;
  1149. }
  1150. if (!table.TryGetMetamethod(context.State, Metamethods.Index, out var metatableValue))
  1151. {
  1152. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "index", table);
  1153. }
  1154. table = metatableValue;
  1155. Function:
  1156. if (table.TryReadFunction(out var function))
  1157. {
  1158. return CallGetTableFunc(targetTable, function, key, ref context, out value, out doRestart);
  1159. }
  1160. }
  1161. throw new LuaRuntimeException(GetTracebacks(ref context), "loop in gettable");
  1162. }
  1163. [MethodImpl(MethodImplOptions.NoInlining)]
  1164. static bool CallGetTableFunc(LuaValue table, LuaFunction indexTable, LuaValue key, ref VirtualMachineExecutionContext context, out LuaValue result, out bool doRestart)
  1165. {
  1166. doRestart = false;
  1167. var stack = context.Stack;
  1168. stack.Push(table);
  1169. stack.Push(key);
  1170. var newFrame = indexTable.CreateNewFrame(ref context, stack.Count - 2);
  1171. context.Thread.PushCallStackFrame(newFrame);
  1172. if (indexTable is Closure)
  1173. {
  1174. context.Push(newFrame);
  1175. doRestart = true;
  1176. result = default;
  1177. return true;
  1178. }
  1179. var task = indexTable.Invoke(ref context, newFrame, 2);
  1180. if (!task.IsCompleted)
  1181. {
  1182. context.Task = task;
  1183. result = default;
  1184. return false;
  1185. }
  1186. var awaiter = task.GetAwaiter();
  1187. context.Thread.PopCallStackFrame();
  1188. var resultCount = awaiter.GetResult();
  1189. result = resultCount == 0 ? default : context.ResultsBuffer[0];
  1190. context.ClearResultsBuffer(resultCount);
  1191. return true;
  1192. }
  1193. [MethodImpl(MethodImplOptions.NoInlining)]
  1194. static bool SetTableValueSlowPath(LuaValue table, LuaValue key, LuaValue value,
  1195. ref VirtualMachineExecutionContext context, out bool doRestart)
  1196. {
  1197. var targetTable = table;
  1198. const int MAX_LOOP = 100;
  1199. doRestart = false;
  1200. var skip = targetTable.Type == LuaValueType.Table;
  1201. for (int i = 0; i < MAX_LOOP; i++)
  1202. {
  1203. if (table.TryReadTable(out var luaTable))
  1204. {
  1205. ref var valueRef = ref (skip ? ref Unsafe.NullRef<LuaValue>() : ref luaTable.FindValue(key));
  1206. skip = false;
  1207. if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
  1208. {
  1209. valueRef = value;
  1210. return true;
  1211. }
  1212. var metatable = luaTable.Metatable;
  1213. if (metatable == null || !metatable.TryGetValue(Metamethods.NewIndex, out table))
  1214. {
  1215. if (Unsafe.IsNullRef(ref valueRef))
  1216. {
  1217. luaTable[key] = value;
  1218. return true;
  1219. }
  1220. valueRef = value;
  1221. return true;
  1222. }
  1223. goto Function;
  1224. }
  1225. if (!table.TryGetMetamethod(context.State, Metamethods.NewIndex, out var metatableValue))
  1226. {
  1227. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "index", table);
  1228. }
  1229. table = metatableValue;
  1230. Function:
  1231. if (table.TryReadFunction(out var function))
  1232. {
  1233. return CallSetTableFunc(targetTable, function, key, value, ref context, out doRestart);
  1234. }
  1235. }
  1236. throw new LuaRuntimeException(GetTracebacks(ref context), "loop in settable");
  1237. }
  1238. [MethodImpl(MethodImplOptions.NoInlining)]
  1239. static bool CallSetTableFunc(LuaValue table, LuaFunction newIndexFunction, LuaValue key, LuaValue value, ref VirtualMachineExecutionContext context, out bool doRestart)
  1240. {
  1241. doRestart = false;
  1242. var thread = context.Thread;
  1243. var stack = thread.Stack;
  1244. stack.Push(table);
  1245. stack.Push(key);
  1246. stack.Push(value);
  1247. var newFrame = newIndexFunction.CreateNewFrame(ref context, stack.Count - 3);
  1248. context.Thread.PushCallStackFrame(newFrame);
  1249. if (newIndexFunction is Closure)
  1250. {
  1251. context.Push(newFrame);
  1252. doRestart = true;
  1253. return true;
  1254. }
  1255. var task = newIndexFunction.Invoke(ref context, newFrame, 3);
  1256. if (!task.IsCompleted)
  1257. {
  1258. context.Task = task;
  1259. return false;
  1260. }
  1261. var resultCount = task.GetAwaiter().GetResult();
  1262. if (0 < resultCount)
  1263. {
  1264. context.ClearResultsBuffer(resultCount);
  1265. }
  1266. thread.PopCallStackFrame();
  1267. return true;
  1268. }
  1269. [MethodImpl(MethodImplOptions.NoInlining)]
  1270. static bool ExecuteBinaryOperationMetaMethod(LuaValue vb, LuaValue vc,
  1271. ref VirtualMachineExecutionContext context, string name, string description, out bool doRestart)
  1272. {
  1273. doRestart = false;
  1274. if (vb.TryGetMetamethod(context.State, name, out var metamethod) ||
  1275. vc.TryGetMetamethod(context.State, name, out metamethod))
  1276. {
  1277. if (!metamethod.TryReadFunction(out var func))
  1278. {
  1279. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "call", metamethod);
  1280. }
  1281. var stack = context.Stack;
  1282. stack.Push(vb);
  1283. stack.Push(vc);
  1284. var newFrame = func.CreateNewFrame(ref context, stack.Count - 2);
  1285. context.Thread.PushCallStackFrame(newFrame);
  1286. if (func is Closure)
  1287. {
  1288. context.Push(newFrame);
  1289. doRestart = true;
  1290. return true;
  1291. }
  1292. var task = func.Invoke(ref context, newFrame, 2);
  1293. if (!task.IsCompleted)
  1294. {
  1295. context.Task = task;
  1296. return false;
  1297. }
  1298. var resultCount = task.GetAwaiter().GetResult();
  1299. context.Thread.PopCallStackFrame();
  1300. var RA = context.Instruction.A + context.FrameBase;
  1301. stack.Get(RA) = resultCount == 0 ? LuaValue.Nil : context.ResultsBuffer[0];
  1302. context.ClearResultsBuffer(resultCount);
  1303. return true;
  1304. }
  1305. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), description, vb, vc);
  1306. return false;
  1307. }
  1308. [MethodImpl(MethodImplOptions.NoInlining)]
  1309. static bool ExecuteUnaryOperationMetaMethod(LuaValue vb, ref VirtualMachineExecutionContext context,
  1310. string name, string description, bool isLen, out bool doRestart)
  1311. {
  1312. doRestart = false;
  1313. var stack = context.Stack;
  1314. if (vb.TryGetMetamethod(context.State, name, out var metamethod))
  1315. {
  1316. if (!metamethod.TryReadFunction(out var func))
  1317. {
  1318. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "call", metamethod);
  1319. }
  1320. stack.Push(vb);
  1321. var newFrame = func.CreateNewFrame(ref context, stack.Count - 1);
  1322. context.Thread.PushCallStackFrame(newFrame);
  1323. if (func is Closure)
  1324. {
  1325. context.Push(newFrame);
  1326. doRestart = true;
  1327. return true;
  1328. }
  1329. var task = func.Invoke(ref context, newFrame, 1);
  1330. if (!task.IsCompleted)
  1331. {
  1332. context.Task = task;
  1333. return false;
  1334. }
  1335. context.Thread.PopCallStackFrame();
  1336. var RA = context.Instruction.A + context.FrameBase;
  1337. var resultCount = task.GetAwaiter().GetResult();
  1338. stack.Get(RA) = resultCount == 0 ? LuaValue.Nil : context.ResultsBuffer[0];
  1339. context.ClearResultsBuffer(resultCount);
  1340. return true;
  1341. }
  1342. if (isLen && vb.TryReadTable(out var table))
  1343. {
  1344. var RA = context.Instruction.A + context.FrameBase;
  1345. stack.Get(RA) = table.ArrayLength;
  1346. return true;
  1347. }
  1348. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), description, vb);
  1349. return true;
  1350. }
  1351. [MethodImpl(MethodImplOptions.NoInlining)]
  1352. static bool ExecuteCompareOperationMetaMethod(LuaValue vb, LuaValue vc,
  1353. ref VirtualMachineExecutionContext context, string name, string? description, out bool doRestart)
  1354. {
  1355. doRestart = false;
  1356. bool reverseLe = false;
  1357. ReCheck:
  1358. if (vb.TryGetMetamethod(context.State, name, out var metamethod) ||
  1359. vc.TryGetMetamethod(context.State, name, out metamethod))
  1360. {
  1361. if (!metamethod.TryReadFunction(out var func))
  1362. {
  1363. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "call", metamethod);
  1364. }
  1365. var stack = context.Stack;
  1366. stack.Push(vb);
  1367. stack.Push(vc);
  1368. var newFrame = func.CreateNewFrame(ref context, stack.Count - 2);
  1369. if (reverseLe) newFrame.Flags |= CallStackFrameFlags.ReversedLe;
  1370. context.Thread.PushCallStackFrame(newFrame);
  1371. if (func is Closure)
  1372. {
  1373. context.Push(newFrame);
  1374. doRestart = true;
  1375. return true;
  1376. }
  1377. var task = func.Invoke(ref context, newFrame, 2);
  1378. if (!task.IsCompleted)
  1379. {
  1380. context.Task = task;
  1381. return false;
  1382. }
  1383. context.Thread.PopCallStackFrame();
  1384. var resultCount = task.GetAwaiter().GetResult();
  1385. var compareResult = resultCount != 0 && context.ResultsBuffer[0].ToBoolean();
  1386. compareResult = reverseLe ? !compareResult : compareResult;
  1387. if (compareResult != (context.Instruction.A == 1))
  1388. {
  1389. context.Pc++;
  1390. }
  1391. context.ClearResultsBuffer(resultCount);
  1392. return true;
  1393. }
  1394. if (name == Metamethods.Le)
  1395. {
  1396. reverseLe = true;
  1397. name = Metamethods.Lt;
  1398. (vb, vc) = (vc, vb);
  1399. goto ReCheck;
  1400. }
  1401. if (description != null)
  1402. {
  1403. if (reverseLe)
  1404. {
  1405. (vb, vc) = (vc, vb);
  1406. }
  1407. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), description, vb, vc);
  1408. }
  1409. else
  1410. {
  1411. if (context.Instruction.A == 1)
  1412. {
  1413. context.Pc++;
  1414. }
  1415. }
  1416. return true;
  1417. }
  1418. // If there are variable arguments, the base of the stack is moved by that number and the values of the variable arguments are placed in front of it.
  1419. // see: https://wubingzheng.github.io/build-lua-in-rust/en/ch08-02.arguments.html
  1420. [MethodImpl(MethodImplOptions.NoInlining)]
  1421. static (int FrameBase, int ArgumentCount, int VariableArgumentCount) PrepareVariableArgument(LuaStack stack, int newBase, int argumentCount,
  1422. int variableArgumentCount)
  1423. {
  1424. var temp = newBase;
  1425. newBase += variableArgumentCount;
  1426. stack.EnsureCapacity(newBase + argumentCount);
  1427. stack.NotifyTop(newBase + argumentCount);
  1428. var stackBuffer = stack.GetBuffer()[temp..];
  1429. stackBuffer[..argumentCount].CopyTo(stackBuffer[variableArgumentCount..]);
  1430. stackBuffer.Slice(argumentCount, variableArgumentCount).CopyTo(stackBuffer);
  1431. return (newBase, argumentCount, variableArgumentCount);
  1432. }
  1433. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1434. static (int FrameBase, int ArgumentCount, int VariableArgumentCount) PrepareForFunctionCall(LuaThread thread, LuaFunction function,
  1435. Instruction instruction, int RA)
  1436. {
  1437. var argumentCount = instruction.B - 1;
  1438. if (argumentCount == -1)
  1439. {
  1440. argumentCount = (ushort)(thread.Stack.Count - (RA + 1));
  1441. }
  1442. else
  1443. {
  1444. thread.Stack.NotifyTop(RA + 1 + argumentCount);
  1445. }
  1446. var newBase = RA + 1;
  1447. var variableArgumentCount = function.GetVariableArgumentCount(argumentCount);
  1448. if (variableArgumentCount <= 0)
  1449. {
  1450. return (newBase, argumentCount, 0);
  1451. }
  1452. return PrepareVariableArgument(thread.Stack, newBase, argumentCount, variableArgumentCount);
  1453. }
  1454. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1455. static (int FrameBase, int ArgumentCount, int VariableArgumentCount) PrepareForFunctionTailCall(LuaThread thread, LuaFunction function,
  1456. Instruction instruction, int RA)
  1457. {
  1458. var stack = thread.Stack;
  1459. var argumentCount = instruction.B - 1;
  1460. if (instruction.B == 0)
  1461. {
  1462. argumentCount = (ushort)(stack.Count - (RA + 1));
  1463. }
  1464. else
  1465. {
  1466. thread.Stack.NotifyTop(RA + 1 + argumentCount);
  1467. }
  1468. var newBase = RA + 1;
  1469. // In the case of tailcall, the local variables of the caller are immediately discarded, so there is no need to retain them.
  1470. // Therefore, a call can be made without allocating new registers.
  1471. var currentBase = thread.GetCurrentFrame().Base;
  1472. {
  1473. var stackBuffer = stack.GetBuffer();
  1474. if (argumentCount > 0)
  1475. stackBuffer.Slice(newBase, argumentCount).CopyTo(stackBuffer.Slice(currentBase, argumentCount));
  1476. newBase = currentBase;
  1477. }
  1478. var variableArgumentCount = function.GetVariableArgumentCount(argumentCount);
  1479. if (variableArgumentCount <= 0)
  1480. {
  1481. return (newBase, argumentCount, 0);
  1482. }
  1483. return PrepareVariableArgument(thread.Stack, newBase, argumentCount, variableArgumentCount);
  1484. }
  1485. static Traceback GetTracebacks(ref VirtualMachineExecutionContext context)
  1486. {
  1487. return GetTracebacks(context.State, context.Pc);
  1488. }
  1489. static Traceback GetTracebacks(LuaState state, int pc)
  1490. {
  1491. var frame = state.CurrentThread.GetCurrentFrame();
  1492. state.CurrentThread.PushCallStackFrame(frame with
  1493. {
  1494. CallerInstructionIndex = pc
  1495. });
  1496. var tracebacks = state.GetTraceback();
  1497. state.CurrentThread.PopCallStackFrame();
  1498. return tracebacks;
  1499. }
  1500. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1501. static CallStackFrame CreateNewFrame(this LuaFunction function, ref VirtualMachineExecutionContext context, int newBase, int variableArgumentCount = 0)
  1502. {
  1503. return new()
  1504. {
  1505. Base = newBase,
  1506. Function = function,
  1507. VariableArgumentCount = variableArgumentCount,
  1508. CallerInstructionIndex = context.Pc,
  1509. };
  1510. }
  1511. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1512. static ValueTask<int> Invoke(this LuaFunction function, ref VirtualMachineExecutionContext context, in CallStackFrame frame, int arguments)
  1513. {
  1514. return function.Func(new()
  1515. {
  1516. State = context.State,
  1517. Thread = context.Thread,
  1518. ArgumentCount = arguments,
  1519. FrameBase = frame.Base,
  1520. CallerInstructionIndex = frame.CallerInstructionIndex,
  1521. }, context.ResultsBuffer, context.CancellationToken);
  1522. }
  1523. }