LuaVirtualMachine.cs 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  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. }
  1104. static void ComparePostOperation(ref VirtualMachineExecutionContext context)
  1105. {
  1106. var compareResult = context.TaskResult != 0 && context.ResultsBuffer[0].ToBoolean();
  1107. if (compareResult != (context.Instruction.A == 1))
  1108. {
  1109. context.Pc++;
  1110. }
  1111. context.ClearResultsBuffer();
  1112. }
  1113. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1114. static ref readonly LuaValue RKB(ref LuaValue stack, ref LuaValue constants, Instruction instruction)
  1115. {
  1116. var index = instruction.UIntB;
  1117. return ref (index >= 256 ? ref Unsafe.Add(ref constants, index - 256) : ref Unsafe.Add(ref stack, index));
  1118. }
  1119. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1120. static ref readonly LuaValue RKC(ref LuaValue stack, ref LuaValue constants, Instruction instruction)
  1121. {
  1122. var index = instruction.UIntC;
  1123. return ref (index >= 256 ? ref Unsafe.Add(ref constants, index - 256) : ref Unsafe.Add(ref stack, index));
  1124. }
  1125. [MethodImpl(MethodImplOptions.NoInlining)]
  1126. static bool GetTableValueSlowPath(LuaValue table, LuaValue key, ref VirtualMachineExecutionContext context, out LuaValue value, out bool doRestart)
  1127. {
  1128. var targetTable = table;
  1129. const int MAX_LOOP = 100;
  1130. doRestart = false;
  1131. var skip = targetTable.Type == LuaValueType.Table;
  1132. for (int i = 0; i < MAX_LOOP; i++)
  1133. {
  1134. if (table.TryReadTable(out var luaTable))
  1135. {
  1136. if (!skip && luaTable.TryGetValue(key, out value))
  1137. {
  1138. return true;
  1139. }
  1140. skip = false;
  1141. var metatable = luaTable.Metatable;
  1142. if (metatable != null && metatable.TryGetValue(Metamethods.Index, out table))
  1143. {
  1144. goto Function;
  1145. }
  1146. value = default;
  1147. return true;
  1148. }
  1149. if (!table.TryGetMetamethod(context.State, Metamethods.Index, out var metatableValue))
  1150. {
  1151. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "index", table);
  1152. }
  1153. table = metatableValue;
  1154. Function:
  1155. if (table.TryReadFunction(out var function))
  1156. {
  1157. return CallGetTableFunc(targetTable, function, key, ref context, out value, out doRestart);
  1158. }
  1159. }
  1160. throw new LuaRuntimeException(GetTracebacks(ref context), "loop in gettable");
  1161. }
  1162. [MethodImpl(MethodImplOptions.NoInlining)]
  1163. static bool CallGetTableFunc(LuaValue table, LuaFunction indexTable, LuaValue key, ref VirtualMachineExecutionContext context, out LuaValue result, out bool doRestart)
  1164. {
  1165. doRestart = false;
  1166. var stack = context.Stack;
  1167. stack.Push(table);
  1168. stack.Push(key);
  1169. var newFrame = indexTable.CreateNewFrame(ref context, stack.Count - 2);
  1170. context.Thread.PushCallStackFrame(newFrame);
  1171. if (indexTable is Closure)
  1172. {
  1173. context.Push(newFrame);
  1174. doRestart = true;
  1175. result = default;
  1176. return true;
  1177. }
  1178. var task = indexTable.Invoke(ref context, newFrame, 2);
  1179. if (!task.IsCompleted)
  1180. {
  1181. context.Task = task;
  1182. result = default;
  1183. return false;
  1184. }
  1185. var awaiter = task.GetAwaiter();
  1186. context.Thread.PopCallStackFrame();
  1187. var resultCount = awaiter.GetResult();
  1188. result = resultCount == 0 ? default : context.ResultsBuffer[0];
  1189. context.ClearResultsBuffer(resultCount);
  1190. return true;
  1191. }
  1192. [MethodImpl(MethodImplOptions.NoInlining)]
  1193. static bool SetTableValueSlowPath(LuaValue table, LuaValue key, LuaValue value,
  1194. ref VirtualMachineExecutionContext context, out bool doRestart)
  1195. {
  1196. var targetTable = table;
  1197. const int MAX_LOOP = 100;
  1198. doRestart = false;
  1199. var skip = targetTable.Type == LuaValueType.Table;
  1200. for (int i = 0; i < MAX_LOOP; i++)
  1201. {
  1202. if (table.TryReadTable(out var luaTable))
  1203. {
  1204. ref var valueRef = ref (skip ? ref Unsafe.NullRef<LuaValue>() : ref luaTable.FindValue(key));
  1205. skip = false;
  1206. if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
  1207. {
  1208. valueRef = value;
  1209. return true;
  1210. }
  1211. var metatable = luaTable.Metatable;
  1212. if (metatable == null || !metatable.TryGetValue(Metamethods.NewIndex, out table))
  1213. {
  1214. if (Unsafe.IsNullRef(ref valueRef))
  1215. {
  1216. luaTable[key] = value;
  1217. return true;
  1218. }
  1219. valueRef = value;
  1220. return true;
  1221. }
  1222. goto Function;
  1223. }
  1224. if (!table.TryGetMetamethod(context.State, Metamethods.NewIndex, out var metatableValue))
  1225. {
  1226. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "index", table);
  1227. }
  1228. table = metatableValue;
  1229. Function:
  1230. if (table.TryReadFunction(out var function))
  1231. {
  1232. return CallSetTableFunc(targetTable, function, key, value, ref context, out doRestart);
  1233. }
  1234. }
  1235. throw new LuaRuntimeException(GetTracebacks(ref context), "loop in settable");
  1236. }
  1237. [MethodImpl(MethodImplOptions.NoInlining)]
  1238. static bool CallSetTableFunc(LuaValue table, LuaFunction newIndexFunction, LuaValue key, LuaValue value, ref VirtualMachineExecutionContext context, out bool doRestart)
  1239. {
  1240. doRestart = false;
  1241. var thread = context.Thread;
  1242. var stack = thread.Stack;
  1243. stack.Push(table);
  1244. stack.Push(key);
  1245. stack.Push(value);
  1246. var newFrame = newIndexFunction.CreateNewFrame(ref context, stack.Count - 3);
  1247. context.Thread.PushCallStackFrame(newFrame);
  1248. if (newIndexFunction is Closure)
  1249. {
  1250. context.Push(newFrame);
  1251. doRestart = true;
  1252. return true;
  1253. }
  1254. var task = newIndexFunction.Invoke(ref context, newFrame, 3);
  1255. if (!task.IsCompleted)
  1256. {
  1257. context.Task = task;
  1258. return false;
  1259. }
  1260. var resultCount = task.GetAwaiter().GetResult();
  1261. if (0 < resultCount)
  1262. {
  1263. context.ClearResultsBuffer(resultCount);
  1264. }
  1265. thread.PopCallStackFrame();
  1266. return true;
  1267. }
  1268. [MethodImpl(MethodImplOptions.NoInlining)]
  1269. static bool ExecuteBinaryOperationMetaMethod(LuaValue vb, LuaValue vc,
  1270. ref VirtualMachineExecutionContext context, string name, string description, out bool doRestart)
  1271. {
  1272. doRestart = false;
  1273. if (vb.TryGetMetamethod(context.State, name, out var metamethod) ||
  1274. vc.TryGetMetamethod(context.State, name, out metamethod))
  1275. {
  1276. if (!metamethod.TryReadFunction(out var func))
  1277. {
  1278. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "call", metamethod);
  1279. }
  1280. var stack = context.Stack;
  1281. stack.Push(vb);
  1282. stack.Push(vc);
  1283. var newFrame = func.CreateNewFrame(ref context, stack.Count - 2);
  1284. context.Thread.PushCallStackFrame(newFrame);
  1285. if (func is Closure)
  1286. {
  1287. context.Push(newFrame);
  1288. doRestart = true;
  1289. return true;
  1290. }
  1291. var task = func.Invoke(ref context, newFrame, 2);
  1292. if (!task.IsCompleted)
  1293. {
  1294. context.Task = task;
  1295. return false;
  1296. }
  1297. var resultCount = task.GetAwaiter().GetResult();
  1298. context.Thread.PopCallStackFrame();
  1299. var RA = context.Instruction.A + context.FrameBase;
  1300. stack.Get(RA) = resultCount == 0 ? LuaValue.Nil : context.ResultsBuffer[0];
  1301. context.ClearResultsBuffer(resultCount);
  1302. return true;
  1303. }
  1304. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), description, vb, vc);
  1305. return false;
  1306. }
  1307. [MethodImpl(MethodImplOptions.NoInlining)]
  1308. static bool ExecuteUnaryOperationMetaMethod(LuaValue vb, ref VirtualMachineExecutionContext context,
  1309. string name, string description, bool isLen, out bool doRestart)
  1310. {
  1311. doRestart = false;
  1312. var stack = context.Stack;
  1313. if (vb.TryGetMetamethod(context.State, name, out var metamethod))
  1314. {
  1315. if (!metamethod.TryReadFunction(out var func))
  1316. {
  1317. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "call", metamethod);
  1318. }
  1319. stack.Push(vb);
  1320. var newFrame = func.CreateNewFrame(ref context, stack.Count - 1);
  1321. context.Thread.PushCallStackFrame(newFrame);
  1322. if (func is Closure)
  1323. {
  1324. context.Push(newFrame);
  1325. doRestart = true;
  1326. return true;
  1327. }
  1328. var task = func.Invoke(ref context, newFrame, 1);
  1329. if (!task.IsCompleted)
  1330. {
  1331. context.Task = task;
  1332. return false;
  1333. }
  1334. context.Thread.PopCallStackFrame();
  1335. var RA = context.Instruction.A + context.FrameBase;
  1336. var resultCount = task.GetAwaiter().GetResult();
  1337. stack.Get(RA) = resultCount == 0 ? LuaValue.Nil : context.ResultsBuffer[0];
  1338. context.ClearResultsBuffer(resultCount);
  1339. return true;
  1340. }
  1341. if (isLen && vb.TryReadTable(out var table))
  1342. {
  1343. var RA = context.Instruction.A + context.FrameBase;
  1344. stack.Get(RA) = table.ArrayLength;
  1345. return true;
  1346. }
  1347. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), description, vb);
  1348. return true;
  1349. }
  1350. [MethodImpl(MethodImplOptions.NoInlining)]
  1351. static bool ExecuteCompareOperationMetaMethod(LuaValue vb, LuaValue vc,
  1352. ref VirtualMachineExecutionContext context, string name, string? description, out bool doRestart)
  1353. {
  1354. doRestart = false;
  1355. bool reverseLe = false;
  1356. ReCheck:
  1357. if (vb.TryGetMetamethod(context.State, name, out var metamethod) ||
  1358. vc.TryGetMetamethod(context.State, name, out metamethod))
  1359. {
  1360. if (!metamethod.TryReadFunction(out var func))
  1361. {
  1362. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), "call", metamethod);
  1363. }
  1364. var stack = context.Stack;
  1365. stack.Push(vb);
  1366. stack.Push(vc);
  1367. var newFrame = func.CreateNewFrame(ref context, stack.Count - 2);
  1368. if (reverseLe) newFrame.Flags |= CallStackFrameFlags.ReversedLe;
  1369. context.Thread.PushCallStackFrame(newFrame);
  1370. if (func is Closure)
  1371. {
  1372. context.Push(newFrame);
  1373. doRestart = true;
  1374. return true;
  1375. }
  1376. var task = func.Invoke(ref context, newFrame, 2);
  1377. if (!task.IsCompleted)
  1378. {
  1379. context.Task = task;
  1380. return false;
  1381. }
  1382. context.Thread.PopCallStackFrame();
  1383. var resultCount = task.GetAwaiter().GetResult();
  1384. var compareResult = resultCount != 0 && context.ResultsBuffer[0].ToBoolean();
  1385. compareResult = reverseLe ? !compareResult : compareResult;
  1386. if (compareResult != (context.Instruction.A == 1))
  1387. {
  1388. context.Pc++;
  1389. }
  1390. context.ClearResultsBuffer(resultCount);
  1391. return true;
  1392. }
  1393. if (name == Metamethods.Le)
  1394. {
  1395. reverseLe = true;
  1396. name = Metamethods.Lt;
  1397. (vb, vc) = (vc, vb);
  1398. goto ReCheck;
  1399. }
  1400. if (description != null)
  1401. {
  1402. if (reverseLe)
  1403. {
  1404. (vb, vc) = (vc, vb);
  1405. }
  1406. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(ref context), description, vb, vc);
  1407. }
  1408. else
  1409. {
  1410. if (context.Instruction.A == 1)
  1411. {
  1412. context.Pc++;
  1413. }
  1414. }
  1415. return true;
  1416. }
  1417. // 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.
  1418. // see: https://wubingzheng.github.io/build-lua-in-rust/en/ch08-02.arguments.html
  1419. [MethodImpl(MethodImplOptions.NoInlining)]
  1420. static (int FrameBase, int ArgumentCount, int VariableArgumentCount) PrepareVariableArgument(LuaStack stack, int newBase, int argumentCount,
  1421. int variableArgumentCount)
  1422. {
  1423. var temp = newBase;
  1424. newBase += variableArgumentCount;
  1425. stack.EnsureCapacity(newBase + argumentCount);
  1426. stack.NotifyTop(newBase + argumentCount);
  1427. var stackBuffer = stack.GetBuffer()[temp..];
  1428. stackBuffer[..argumentCount].CopyTo(stackBuffer[variableArgumentCount..]);
  1429. stackBuffer.Slice(argumentCount, variableArgumentCount).CopyTo(stackBuffer);
  1430. return (newBase, argumentCount, variableArgumentCount);
  1431. }
  1432. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1433. static (int FrameBase, int ArgumentCount, int VariableArgumentCount) PrepareForFunctionCall(LuaThread thread, LuaFunction function,
  1434. Instruction instruction, int RA)
  1435. {
  1436. var argumentCount = instruction.B - 1;
  1437. if (argumentCount == -1)
  1438. {
  1439. argumentCount = (ushort)(thread.Stack.Count - (RA + 1));
  1440. }
  1441. else
  1442. {
  1443. thread.Stack.NotifyTop(RA + 1 + argumentCount);
  1444. }
  1445. var newBase = RA + 1;
  1446. var variableArgumentCount = function.GetVariableArgumentCount(argumentCount);
  1447. if (variableArgumentCount <= 0)
  1448. {
  1449. return (newBase, argumentCount, 0);
  1450. }
  1451. return PrepareVariableArgument(thread.Stack, newBase, argumentCount, variableArgumentCount);
  1452. }
  1453. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1454. static (int FrameBase, int ArgumentCount, int VariableArgumentCount) PrepareForFunctionTailCall(LuaThread thread, LuaFunction function,
  1455. Instruction instruction, int RA)
  1456. {
  1457. var stack = thread.Stack;
  1458. var argumentCount = instruction.B - 1;
  1459. if (instruction.B == 0)
  1460. {
  1461. argumentCount = (ushort)(stack.Count - (RA + 1));
  1462. }
  1463. else
  1464. {
  1465. thread.Stack.NotifyTop(RA + 1 + argumentCount);
  1466. }
  1467. var newBase = RA + 1;
  1468. // In the case of tailcall, the local variables of the caller are immediately discarded, so there is no need to retain them.
  1469. // Therefore, a call can be made without allocating new registers.
  1470. var currentBase = thread.GetCurrentFrame().Base;
  1471. {
  1472. var stackBuffer = stack.GetBuffer();
  1473. if (argumentCount > 0)
  1474. stackBuffer.Slice(newBase, argumentCount).CopyTo(stackBuffer.Slice(currentBase, argumentCount));
  1475. newBase = currentBase;
  1476. }
  1477. var variableArgumentCount = function.GetVariableArgumentCount(argumentCount);
  1478. if (variableArgumentCount <= 0)
  1479. {
  1480. return (newBase, argumentCount, 0);
  1481. }
  1482. return PrepareVariableArgument(thread.Stack, newBase, argumentCount, variableArgumentCount);
  1483. }
  1484. static Traceback GetTracebacks(ref VirtualMachineExecutionContext context)
  1485. {
  1486. return GetTracebacks(context.State, context.Pc);
  1487. }
  1488. static Traceback GetTracebacks(LuaState state, int pc)
  1489. {
  1490. var frame = state.CurrentThread.GetCurrentFrame();
  1491. state.CurrentThread.PushCallStackFrame(frame with
  1492. {
  1493. CallerInstructionIndex = pc
  1494. });
  1495. var tracebacks = state.GetTraceback();
  1496. state.CurrentThread.PopCallStackFrame();
  1497. return tracebacks;
  1498. }
  1499. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1500. static CallStackFrame CreateNewFrame(this LuaFunction function, ref VirtualMachineExecutionContext context, int newBase, int variableArgumentCount = 0)
  1501. {
  1502. return new()
  1503. {
  1504. Base = newBase,
  1505. Function = function,
  1506. VariableArgumentCount = variableArgumentCount,
  1507. CallerInstructionIndex = context.Pc,
  1508. };
  1509. }
  1510. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1511. static ValueTask<int> Invoke(this LuaFunction function, ref VirtualMachineExecutionContext context, in CallStackFrame frame, int arguments)
  1512. {
  1513. return function.Func(new()
  1514. {
  1515. State = context.State,
  1516. Thread = context.Thread,
  1517. ArgumentCount = arguments,
  1518. FrameBase = frame.Base,
  1519. CallerInstructionIndex = frame.CallerInstructionIndex,
  1520. }, context.ResultsBuffer, context.CancellationToken);
  1521. }
  1522. }