LuaVirtualMachine.cs 65 KB

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