LuaVirtualMachine.cs 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Runtime.CompilerServices;
  3. using Lua.Internal;
  4. // ReSharper disable MethodHasAsyncOverload
  5. // ReSharper disable InconsistentNaming
  6. namespace Lua.Runtime;
  7. [SuppressMessage("Reliability", "CA2012:Use ValueTasks correctly")]
  8. public static partial class LuaVirtualMachine
  9. {
  10. class VirtualMachineExecutionContext
  11. : IPoolNode<VirtualMachineExecutionContext>
  12. {
  13. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  14. public static VirtualMachineExecutionContext Get(
  15. LuaThread thread,
  16. in CallStackFrame frame,
  17. CancellationToken cancellationToken)
  18. {
  19. if (!pool.TryPop(out var executionContext))
  20. {
  21. executionContext = new VirtualMachineExecutionContext();
  22. }
  23. executionContext.Init(thread, frame, cancellationToken);
  24. return executionContext;
  25. }
  26. void Init(
  27. LuaThread thread,
  28. in CallStackFrame frame,
  29. CancellationToken cancellationToken)
  30. {
  31. Stack = thread.Stack;
  32. Thread = thread;
  33. LuaClosure = (LuaClosure)frame.Function;
  34. FrameBase = frame.Base;
  35. VariableArgumentCount = frame.VariableArgumentCount;
  36. CurrentReturnFrameBase = frame.ReturnBase;
  37. CancellationToken = cancellationToken;
  38. Pc = -1;
  39. Instruction = default;
  40. PostOperation = PostOperationType.None;
  41. BaseCallStackCount = thread.CallStackFrameCount;
  42. LastHookPc = -1;
  43. Task = default;
  44. }
  45. public LuaState State => Thread.State;
  46. public LuaStack Stack = default!;
  47. public LuaClosure LuaClosure = default!;
  48. public LuaThread Thread = default!;
  49. public Prototype Prototype => LuaClosure.Proto;
  50. public int FrameBase;
  51. public int VariableArgumentCount;
  52. public CancellationToken CancellationToken;
  53. public int Pc;
  54. public Instruction Instruction;
  55. public int CurrentReturnFrameBase;
  56. public ValueTask<int> Task;
  57. public int LastHookPc;
  58. public bool IsTopLevel => BaseCallStackCount == Thread.CallStackFrameCount;
  59. public int BaseCallStackCount;
  60. public PostOperationType PostOperation;
  61. static LinkedPool<VirtualMachineExecutionContext> pool;
  62. VirtualMachineExecutionContext? nextNode;
  63. ref VirtualMachineExecutionContext? IPoolNode<VirtualMachineExecutionContext>.NextNode => ref nextNode;
  64. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  65. public bool Pop(Instruction instruction, int frameBase)
  66. {
  67. var count = instruction.B - 1;
  68. var src = instruction.A + frameBase;
  69. if (count == -1) count = Stack.Count - src;
  70. return PopFromBuffer(src, count);
  71. }
  72. [MethodImpl(MethodImplOptions.NoInlining)]
  73. public bool PopFromBuffer(int src, int srcCount)
  74. {
  75. var result = Stack.GetBuffer().Slice(src, srcCount);
  76. Re:
  77. var frames = Thread.GetCallStackFrames();
  78. if (frames.Length == BaseCallStackCount)
  79. {
  80. var returnBase = frames[^1].ReturnBase;
  81. if (src != returnBase)
  82. {
  83. result.CopyTo(Stack.AsSpan()[returnBase..]);
  84. }
  85. Stack.PopUntil(returnBase + srcCount);
  86. return false;
  87. }
  88. ref readonly var frame = ref frames[^1];
  89. Pc = frame.CallerInstructionIndex;
  90. Thread.LastPc = Pc;
  91. ref readonly var lastFrame = ref frames[^2];
  92. LuaClosure = Unsafe.As<LuaClosure>(lastFrame.Function);
  93. CurrentReturnFrameBase = frame.ReturnBase;
  94. var callInstruction = Prototype.Code[Pc];
  95. if (callInstruction.OpCode == OpCode.TailCall)
  96. {
  97. Thread.PopCallStackFrame();
  98. goto Re;
  99. }
  100. FrameBase = lastFrame.Base;
  101. VariableArgumentCount = lastFrame.VariableArgumentCount;
  102. var opCode = callInstruction.OpCode;
  103. if (opCode is OpCode.Eq or OpCode.Lt or OpCode.Le)
  104. {
  105. var compareResult = srcCount > 0 && result[0].ToBoolean();
  106. if ((frame.Flags & CallStackFrameFlags.ReversedLe) != 0)
  107. {
  108. compareResult = !compareResult;
  109. }
  110. if (compareResult != (callInstruction.A == 1))
  111. {
  112. Pc++;
  113. }
  114. Thread.PopCallStackFrameWithStackPop();
  115. return true;
  116. }
  117. var target = callInstruction.A + FrameBase;
  118. var targetCount = result.Length;
  119. switch (opCode)
  120. {
  121. case OpCode.Call:
  122. {
  123. var c = callInstruction.C;
  124. if (c != 0)
  125. {
  126. targetCount = c - 1;
  127. }
  128. break;
  129. }
  130. case OpCode.TForCall:
  131. target += 3;
  132. targetCount = callInstruction.C;
  133. break;
  134. case OpCode.Self:
  135. Stack.Get(target) = result.Length == 0 ? LuaValue.Nil : result[0];
  136. Thread.PopCallStackFrameWithStackPop(target + 2);
  137. return true;
  138. case OpCode.SetTable or OpCode.SetTabUp:
  139. target = frame.Base;
  140. targetCount = 0;
  141. break;
  142. // Other opcodes has one result
  143. default:
  144. Stack.Get(target) = result.Length == 0 ? LuaValue.Nil : result[0];
  145. Thread.PopCallStackFrameWithStackPop(target + 1);
  146. return true;
  147. }
  148. Stack.EnsureCapacity(target + targetCount);
  149. if (0 < targetCount && src != target)
  150. {
  151. if (targetCount < result.Length)
  152. {
  153. result = result.Slice(0, targetCount);
  154. }
  155. result.CopyTo(Stack.GetBuffer().Slice(target, targetCount));
  156. }
  157. Stack.PopUntil(target + Math.Min(targetCount, srcCount));
  158. Stack.NotifyTop(target + targetCount);
  159. Thread.PopCallStackFrame();
  160. return true;
  161. }
  162. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  163. public void Push(in CallStackFrame frame)
  164. {
  165. Pc = -1;
  166. LuaClosure = (LuaClosure)(frame.Function);
  167. FrameBase = frame.Base;
  168. CurrentReturnFrameBase = frame.ReturnBase;
  169. VariableArgumentCount = frame.VariableArgumentCount;
  170. }
  171. public void PopOnTopCallStackFrames()
  172. {
  173. var count = Thread.CallStackFrameCount;
  174. if (count == BaseCallStackCount) return;
  175. Thread.PopCallStackFrameUntil(BaseCallStackCount);
  176. }
  177. bool ExecutePostOperation(PostOperationType postOperation)
  178. {
  179. var stackCount = Stack.Count;
  180. var resultsSpan = Stack.GetBuffer()[CurrentReturnFrameBase..];
  181. switch (postOperation)
  182. {
  183. case PostOperationType.Nop: break;
  184. case PostOperationType.SetResult:
  185. var RA = Instruction.A + FrameBase;
  186. Stack.Get(RA) = stackCount > CurrentReturnFrameBase ? Stack.Get(CurrentReturnFrameBase) : LuaValue.Nil;
  187. Stack.NotifyTop(RA + 1);
  188. Stack.PopUntil(RA + 1);
  189. break;
  190. case PostOperationType.TForCall:
  191. TForCallPostOperation(this);
  192. break;
  193. case PostOperationType.Call:
  194. CallPostOperation(this);
  195. break;
  196. case PostOperationType.TailCall:
  197. if (!PopFromBuffer(CurrentReturnFrameBase, Stack.Count - CurrentReturnFrameBase))
  198. {
  199. return false;
  200. }
  201. break;
  202. case PostOperationType.Self:
  203. SelfPostOperation(this, resultsSpan);
  204. break;
  205. case PostOperationType.Compare:
  206. ComparePostOperation(this, resultsSpan);
  207. break;
  208. }
  209. return true;
  210. }
  211. public async ValueTask<int> ExecuteClosureAsyncImpl()
  212. {
  213. var returnFrameBase = CurrentReturnFrameBase;
  214. var toCatchFlag = false;
  215. try
  216. {
  217. while (MoveNext(this))
  218. {
  219. toCatchFlag = true;
  220. await Task;
  221. Task = default;
  222. if (PostOperation is not (PostOperationType.TailCall or PostOperationType.DontPop))
  223. {
  224. Thread.PopCallStackFrame();
  225. }
  226. if (!ExecutePostOperation(PostOperation))
  227. {
  228. break;
  229. }
  230. toCatchFlag = false;
  231. ThrowIfCancellationRequested();
  232. }
  233. return Thread.Stack.Count - returnFrameBase;
  234. }
  235. catch (Exception e)
  236. {
  237. if (toCatchFlag)
  238. {
  239. State.CloseUpValues(Thread, FrameBase);
  240. if (e is not (LuaRuntimeException or LuaCanceledException))
  241. {
  242. Exception newException = e is OperationCanceledException ? new LuaCanceledException(Thread, CancellationToken, e) : new LuaRuntimeException(Thread, e);
  243. PopOnTopCallStackFrames();
  244. throw newException;
  245. }
  246. PopOnTopCallStackFrames();
  247. }
  248. throw;
  249. }
  250. finally
  251. {
  252. pool.TryPush(this);
  253. }
  254. }
  255. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  256. public void ThrowIfCancellationRequested()
  257. {
  258. if (!CancellationToken.IsCancellationRequested) return;
  259. Throw();
  260. void Throw()
  261. {
  262. GetThreadWithCurrentPc(this).ThrowIfCancellationRequested(CancellationToken);
  263. }
  264. }
  265. }
  266. enum PostOperationType
  267. {
  268. None,
  269. Nop,
  270. SetResult,
  271. TForCall,
  272. Call,
  273. TailCall,
  274. Self,
  275. Compare,
  276. DontPop,
  277. }
  278. internal static ValueTask<int> ExecuteClosureAsync(LuaThread thread, CancellationToken cancellationToken)
  279. {
  280. ref readonly var frame = ref thread.GetCurrentFrame();
  281. var context = VirtualMachineExecutionContext.Get(thread, in frame,
  282. cancellationToken);
  283. return context.ExecuteClosureAsyncImpl();
  284. }
  285. static long DummyHookCount = 0;
  286. static bool DummyLineHookEnabled = false;
  287. static bool MoveNext(VirtualMachineExecutionContext context)
  288. {
  289. try
  290. {
  291. // This is a label to restart the execution when new function is called or restarted
  292. Restart:
  293. ref var instructionsHead = ref Unsafe.AsRef(in context.Prototype.Code[0]);
  294. var frameBase = context.FrameBase;
  295. var stack = context.Stack;
  296. stack.EnsureCapacity(frameBase + context.Prototype.MaxStackSize);
  297. ref var constHead = ref MemoryMarshalEx.UnsafeElementAt(context.Prototype.Constants, 0);
  298. ref var lineHookFlag = ref (context.Thread.IsInHook ? ref DummyLineHookEnabled : ref context.Thread.IsLineHookEnabled);
  299. ref var hookCount = ref (context.Thread.IsInHook ? ref DummyHookCount : ref context.Thread.HookCount);
  300. goto Loop;
  301. LineHook:
  302. {
  303. context.LastHookPc = context.Pc;
  304. if (ExecutePerInstructionHook(context))
  305. {
  306. {
  307. context.PostOperation = PostOperationType.Nop;
  308. return true;
  309. }
  310. }
  311. --context.Pc;
  312. }
  313. Loop:
  314. while (true)
  315. {
  316. var instruction = Unsafe.Add(ref instructionsHead, ++context.Pc);
  317. context.Instruction = instruction;
  318. if (--hookCount == 0 || (lineHookFlag && (context.Pc != context.LastHookPc)))
  319. {
  320. goto LineHook;
  321. }
  322. context.LastHookPc = -1;
  323. var iA = instruction.A;
  324. var opCode = instruction.OpCode;
  325. switch (opCode)
  326. {
  327. case OpCode.Move:
  328. Markers.Move();
  329. ref var stackHead = ref stack.FastGet(frameBase);
  330. Unsafe.Add(ref stackHead, iA) = Unsafe.Add(ref stackHead, instruction.B);
  331. stack.NotifyTop(iA + frameBase + 1);
  332. continue;
  333. case OpCode.LoadK:
  334. Markers.LoadK();
  335. stack.GetWithNotifyTop(iA + frameBase) = Unsafe.Add(ref constHead, instruction.Bx);
  336. continue;
  337. case OpCode.LoadKX:
  338. Markers.LoadKX();
  339. stack.GetWithNotifyTop(iA + frameBase) = Unsafe.Add(ref constHead, Unsafe.Add(ref instructionsHead, ++context.Pc).Ax);
  340. continue;
  341. case OpCode.LoadBool:
  342. Markers.LoadBool();
  343. stack.GetWithNotifyTop(iA + frameBase) = instruction.B != 0;
  344. if (instruction.C != 0) context.Pc++;
  345. continue;
  346. case OpCode.LoadNil:
  347. Markers.LoadNil();
  348. var ra1 = iA + frameBase + 1;
  349. var iB = instruction.B;
  350. stack.GetBuffer().Slice(ra1 - 1, iB + 1).Clear();
  351. stack.NotifyTop(ra1 + iB);
  352. continue;
  353. case OpCode.GetUpVal:
  354. Markers.GetUpVal();
  355. stack.GetWithNotifyTop(iA + frameBase) = context.LuaClosure.GetUpValue(instruction.B);
  356. continue;
  357. case OpCode.GetTabUp:
  358. case OpCode.GetTable:
  359. Markers.GetTabUp();
  360. Markers.GetTable();
  361. stackHead = ref stack.FastGet(frameBase);
  362. ref readonly var vc = ref RKC(ref stackHead, ref constHead, instruction);
  363. ref readonly var vb = ref (instruction.OpCode == OpCode.GetTable ? ref Unsafe.Add(ref stackHead, instruction.B) : ref context.LuaClosure.GetUpValueRef(instruction.B));
  364. var doRestart = false;
  365. if (vb.TryReadTable(out var luaTable) && luaTable.TryGetValue(vc, out var resultValue) || GetTableValueSlowPath(vb, vc, context, out resultValue, out doRestart))
  366. {
  367. if (doRestart) goto Restart;
  368. stack.GetWithNotifyTop(instruction.A + frameBase) = resultValue;
  369. continue;
  370. }
  371. return true;
  372. case OpCode.SetTabUp:
  373. case OpCode.SetTable:
  374. Markers.SetTabUp();
  375. Markers.SetTable();
  376. stackHead = ref stack.FastGet(frameBase);
  377. vb = ref RKB(ref stackHead, ref constHead, instruction);
  378. if (vb.TryReadNumber(out var numB))
  379. {
  380. if (double.IsNaN(numB))
  381. {
  382. ThrowLuaRuntimeException(context, "table index is NaN");
  383. return true;
  384. }
  385. }
  386. var table = opCode == OpCode.SetTabUp ? context.LuaClosure.GetUpValue(iA) : Unsafe.Add(ref stackHead, iA);
  387. if (table.TryReadTable(out luaTable))
  388. {
  389. ref var valueRef = ref luaTable.FindValue(vb);
  390. if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
  391. {
  392. valueRef = RKC(ref stackHead, ref constHead, instruction);
  393. continue;
  394. }
  395. }
  396. vc = ref RKC(ref stackHead, ref constHead, instruction);
  397. if (SetTableValueSlowPath(table, vb, vc, context, out doRestart))
  398. {
  399. if (doRestart) goto Restart;
  400. continue;
  401. }
  402. return true;
  403. case OpCode.SetUpVal:
  404. Markers.SetUpVal();
  405. context.LuaClosure.SetUpValue(instruction.B, stack.FastGet(iA + frameBase));
  406. continue;
  407. case OpCode.NewTable:
  408. Markers.NewTable();
  409. stack.GetWithNotifyTop(iA + frameBase) = new LuaTable(instruction.B, instruction.C);
  410. continue;
  411. case OpCode.Self:
  412. Markers.Self();
  413. stackHead = ref stack.FastGet(frameBase);
  414. vc = ref RKC(ref stackHead, ref constHead, instruction);
  415. table = Unsafe.Add(ref stackHead, instruction.B);
  416. doRestart = false;
  417. if ((table.TryReadTable(out luaTable) && luaTable.TryGetValue(vc, out resultValue)) || GetTableValueSlowPath(table, vc, context, out resultValue, out doRestart))
  418. {
  419. if (doRestart) goto Restart;
  420. Unsafe.Add(ref stackHead, iA) = resultValue;
  421. Unsafe.Add(ref stackHead, iA + 1) = table;
  422. stack.NotifyTop(iA + frameBase + 2);
  423. continue;
  424. }
  425. return true;
  426. case OpCode.Add:
  427. case OpCode.Sub:
  428. case OpCode.Mul:
  429. case OpCode.Div:
  430. case OpCode.Mod:
  431. case OpCode.Pow:
  432. Markers.Add();
  433. Markers.Sub();
  434. Markers.Mul();
  435. Markers.Div();
  436. Markers.Mod();
  437. Markers.Pow();
  438. stackHead = ref stack.FastGet(frameBase);
  439. vb = ref RKB(ref stackHead, ref constHead, instruction);
  440. vc = ref RKC(ref stackHead, ref constHead, instruction);
  441. [MethodImpl(MethodImplOptions.NoInlining)]
  442. static double Mod(double a, double b)
  443. {
  444. var mod = a % b;
  445. if ((b > 0 && mod < 0) || (b < 0 && mod > 0))
  446. {
  447. mod += b;
  448. }
  449. return mod;
  450. }
  451. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  452. static double ArithmeticOperation(OpCode code, double a, double b)
  453. {
  454. return code switch
  455. {
  456. OpCode.Add => a + b,
  457. OpCode.Sub => a - b,
  458. OpCode.Mul => a * b,
  459. OpCode.Div => a / b,
  460. OpCode.Mod => Mod(a, b),
  461. OpCode.Pow => Math.Pow(a, b),
  462. _ => 0
  463. };
  464. }
  465. if (vb.Type == LuaValueType.Number && vc.Type == LuaValueType.Number)
  466. {
  467. Unsafe.Add(ref stackHead, iA) = ArithmeticOperation(opCode, vb.UnsafeReadDouble(), vc.UnsafeReadDouble());
  468. stack.NotifyTop(iA + frameBase + 1);
  469. continue;
  470. }
  471. if (vb.TryReadDouble(out numB) && vc.TryReadDouble(out var numC))
  472. {
  473. Unsafe.Add(ref stackHead, iA) = ArithmeticOperation(opCode, numB, numC);
  474. stack.NotifyTop(iA + frameBase + 1);
  475. continue;
  476. }
  477. if (ExecuteBinaryOperationMetaMethod(vb, vc, context, opCode, out doRestart))
  478. {
  479. if (doRestart) goto Restart;
  480. continue;
  481. }
  482. return true;
  483. case OpCode.Unm:
  484. Markers.Unm();
  485. stackHead = ref stack.FastGet(frameBase);
  486. vb = ref Unsafe.Add(ref stackHead, instruction.B);
  487. if (vb.TryReadDouble(out numB))
  488. {
  489. ra1 = iA + frameBase + 1;
  490. Unsafe.Add(ref stackHead, iA) = -numB;
  491. stack.NotifyTop(ra1);
  492. continue;
  493. }
  494. if (ExecuteUnaryOperationMetaMethod(vb, context, OpCode.Unm, out doRestart))
  495. {
  496. if (doRestart) goto Restart;
  497. continue;
  498. }
  499. return true;
  500. case OpCode.Not:
  501. Markers.Not();
  502. stackHead = ref stack.FastGet(frameBase);
  503. Unsafe.Add(ref stackHead, iA) = !Unsafe.Add(ref stackHead, instruction.B).ToBoolean();
  504. stack.NotifyTop(iA + frameBase + 1);
  505. continue;
  506. case OpCode.Len:
  507. Markers.Len();
  508. stackHead = ref stack.FastGet(frameBase);
  509. vb = ref Unsafe.Add(ref stackHead, instruction.B);
  510. if (vb.TryReadString(out var str))
  511. {
  512. ra1 = iA + frameBase + 1;
  513. Unsafe.Add(ref stackHead, iA) = str.Length;
  514. stack.NotifyTop(ra1);
  515. continue;
  516. }
  517. if (ExecuteUnaryOperationMetaMethod(vb, context, OpCode.Len, out doRestart))
  518. {
  519. if (doRestart) goto Restart;
  520. continue;
  521. }
  522. return true;
  523. case OpCode.Concat:
  524. Markers.Concat();
  525. if (Concat(context))
  526. {
  527. //if (doRestart) goto Restart;
  528. continue;
  529. }
  530. return true;
  531. case OpCode.Jmp:
  532. Markers.Jmp();
  533. context.Pc += instruction.SBx;
  534. if (iA != 0)
  535. {
  536. context.Thread.State.CloseUpValues(context.Thread, frameBase + iA - 1);
  537. }
  538. context.ThrowIfCancellationRequested();
  539. continue;
  540. case OpCode.Eq:
  541. Markers.Eq();
  542. stackHead = ref stack.Get(frameBase);
  543. vb = ref RKB(ref stackHead, ref constHead, instruction);
  544. vc = ref RKC(ref stackHead, ref constHead, instruction);
  545. if (vb == vc)
  546. {
  547. if (iA != 1)
  548. {
  549. context.Pc++;
  550. }
  551. continue;
  552. }
  553. if (ExecuteCompareOperationMetaMethod(vb, vc, context, OpCode.Eq, out doRestart))
  554. {
  555. if (doRestart) goto Restart;
  556. continue;
  557. }
  558. return true;
  559. case OpCode.Lt:
  560. case OpCode.Le:
  561. Markers.Lt();
  562. Markers.Le();
  563. stackHead = ref stack.Get(frameBase);
  564. vb = ref RKB(ref stackHead, ref constHead, instruction);
  565. vc = ref RKC(ref stackHead, ref constHead, instruction);
  566. if (vb.TryReadNumber(out numB) && vc.TryReadNumber(out numC))
  567. {
  568. var compareResult = opCode == OpCode.Lt ? numB < numC : numB <= numC;
  569. if (compareResult != (iA == 1))
  570. {
  571. context.Pc++;
  572. }
  573. continue;
  574. }
  575. if (vb.TryReadString(out var strB) && vc.TryReadString(out var strC))
  576. {
  577. var c = StringComparer.Ordinal.Compare(strB, strC);
  578. var compareResult = opCode == OpCode.Lt ? c < 0 : c <= 0;
  579. if (compareResult != (iA == 1))
  580. {
  581. context.Pc++;
  582. }
  583. continue;
  584. }
  585. if (ExecuteCompareOperationMetaMethod(vb, vc, context, opCode, out doRestart))
  586. {
  587. if (doRestart) goto Restart;
  588. continue;
  589. }
  590. return true;
  591. case OpCode.Test:
  592. Markers.Test();
  593. if (stack.Get(iA + frameBase).ToBoolean() != (instruction.C == 1))
  594. {
  595. context.Pc++;
  596. }
  597. continue;
  598. case OpCode.TestSet:
  599. Markers.TestSet();
  600. vb = ref stack.Get(instruction.B + frameBase);
  601. if (vb.ToBoolean() != (instruction.C == 1))
  602. {
  603. context.Pc++;
  604. }
  605. else
  606. {
  607. stack.GetWithNotifyTop(iA + frameBase) = vb;
  608. }
  609. continue;
  610. case OpCode.Call:
  611. Markers.Call();
  612. if (Call(context, out doRestart))
  613. {
  614. if (doRestart)
  615. {
  616. goto Restart;
  617. }
  618. continue;
  619. }
  620. return true;
  621. case OpCode.TailCall:
  622. Markers.TailCall();
  623. if (TailCall(context, out doRestart))
  624. {
  625. if (doRestart) goto Restart;
  626. if (context.IsTopLevel) goto End;
  627. continue;
  628. }
  629. return true;
  630. case OpCode.Return:
  631. Markers.Return();
  632. context.State.CloseUpValues(context.Thread, frameBase);
  633. if (context.Pop(instruction, frameBase))
  634. {
  635. goto Restart;
  636. }
  637. goto End;
  638. case OpCode.ForLoop:
  639. Markers.ForLoop();
  640. ref var indexRef = ref stack.Get(iA + frameBase);
  641. var limit = Unsafe.Add(ref indexRef, 1).UnsafeReadDouble();
  642. var step = Unsafe.Add(ref indexRef, 2).UnsafeReadDouble();
  643. var index = indexRef.UnsafeReadDouble() + step;
  644. if (step >= 0 ? index <= limit : limit <= index)
  645. {
  646. context.Pc += instruction.SBx;
  647. indexRef = index;
  648. Unsafe.Add(ref indexRef, 3) = index;
  649. stack.NotifyTop(iA + frameBase + 4);
  650. context.ThrowIfCancellationRequested();
  651. continue;
  652. }
  653. stack.NotifyTop(iA + frameBase + 1);
  654. continue;
  655. case OpCode.ForPrep:
  656. Markers.ForPrep();
  657. indexRef = ref stack.Get(iA + frameBase);
  658. if (!indexRef.TryReadDouble(out var init))
  659. {
  660. ThrowLuaRuntimeException(context, "'for' initial value must be a number");
  661. return true;
  662. }
  663. if (!LuaValue.TryReadOrSetDouble(ref Unsafe.Add(ref indexRef, 1), out _))
  664. {
  665. ThrowLuaRuntimeException(context, "'for' limit must be a number");
  666. return true;
  667. }
  668. if (!LuaValue.TryReadOrSetDouble(ref Unsafe.Add(ref indexRef, 2), out step))
  669. {
  670. ThrowLuaRuntimeException(context, "'for' step must be a number");
  671. return true;
  672. }
  673. indexRef = init - step;
  674. stack.NotifyTop(iA + frameBase + 1);
  675. context.Pc += instruction.SBx;
  676. continue;
  677. case OpCode.TForCall:
  678. Markers.TForCall();
  679. if (TForCall(context, out doRestart))
  680. {
  681. if (doRestart) goto Restart;
  682. continue;
  683. }
  684. return true;
  685. case OpCode.TForLoop:
  686. Markers.TForLoop();
  687. ref var forState = ref stack.Get(iA + frameBase + 1);
  688. if (forState.Type is not LuaValueType.Nil)
  689. {
  690. Unsafe.Add(ref forState, -1) = forState;
  691. context.Pc += instruction.SBx;
  692. }
  693. continue;
  694. case OpCode.SetList:
  695. Markers.SetList();
  696. SetList(context);
  697. continue;
  698. case OpCode.Closure:
  699. Markers.Closure();
  700. ra1 = iA + frameBase + 1;
  701. stack.EnsureCapacity(ra1);
  702. stack.Get(ra1 - 1) = new LuaClosure(context.Thread, context.Prototype.ChildPrototypes[instruction.Bx]);
  703. stack.NotifyTop(ra1);
  704. continue;
  705. case OpCode.VarArg:
  706. Markers.VarArg();
  707. VarArg(context);
  708. static void VarArg(VirtualMachineExecutionContext context)
  709. {
  710. var instruction = context.Instruction;
  711. var iA = instruction.A;
  712. var frameBase = context.FrameBase;
  713. var frameVariableArgumentCount = context.VariableArgumentCount;
  714. var count = instruction.B == 0
  715. ? frameVariableArgumentCount
  716. : instruction.B - 1;
  717. var ra = iA + frameBase;
  718. var stack = context.Stack;
  719. stack.EnsureCapacity(ra + count);
  720. ref var stackHead = ref stack.Get(0);
  721. for (int i = 0; i < count; i++)
  722. {
  723. Unsafe.Add(ref stackHead, ra + i) = frameVariableArgumentCount > i
  724. ? Unsafe.Add(ref stackHead, frameBase - (frameVariableArgumentCount - i))
  725. : default;
  726. }
  727. stack.NotifyTop(ra + count);
  728. }
  729. continue;
  730. case OpCode.ExtraArg:
  731. default:
  732. ThrowLuaNotImplementedException(context, context.Instruction.OpCode);
  733. return true;
  734. }
  735. }
  736. End:
  737. context.PostOperation = PostOperationType.None;
  738. return false;
  739. }
  740. catch (Exception e)
  741. {
  742. context.State.CloseUpValues(context.Thread, context.FrameBase);
  743. if (e is not (LuaRuntimeException or LuaCanceledException))
  744. {
  745. Exception newException = e is OperationCanceledException ? new LuaCanceledException(context.Thread, context.CancellationToken, e) : new LuaRuntimeException(context.Thread, e);
  746. context.PopOnTopCallStackFrames();
  747. throw newException;
  748. }
  749. context.PopOnTopCallStackFrames();
  750. throw;
  751. }
  752. }
  753. static void ThrowLuaRuntimeException(VirtualMachineExecutionContext context, string message)
  754. {
  755. throw new LuaRuntimeException(GetThreadWithCurrentPc(context), message);
  756. }
  757. static void ThrowLuaNotImplementedException(VirtualMachineExecutionContext context, OpCode opcode)
  758. {
  759. throw new LuaRuntimeException(GetThreadWithCurrentPc(context), $"OpCode {opcode} is not implemented");
  760. }
  761. [MethodImpl(MethodImplOptions.NoInlining)]
  762. internal static double Mod(double a, double b)
  763. {
  764. var mod = a % b;
  765. if ((b > 0 && mod < 0) || (b < 0 && mod > 0))
  766. {
  767. mod += b;
  768. }
  769. return mod;
  770. }
  771. static void SelfPostOperation(VirtualMachineExecutionContext context, Span<LuaValue> results)
  772. {
  773. var stack = context.Stack;
  774. var instruction = context.Instruction;
  775. var RA = instruction.A + context.FrameBase;
  776. var RB = instruction.B + context.FrameBase;
  777. ref var stackHead = ref stack.Get(0);
  778. var table = Unsafe.Add(ref stackHead, RB);
  779. Unsafe.Add(ref stackHead, RA + 1) = table;
  780. Unsafe.Add(ref stackHead, RA) = results.Length == 0 ? LuaValue.Nil : results[0];
  781. stack.NotifyTop(RA + 2);
  782. }
  783. [MethodImpl(MethodImplOptions.NoInlining)]
  784. static bool Concat(VirtualMachineExecutionContext context)
  785. {
  786. var instruction = context.Instruction;
  787. var stack = context.Stack;
  788. var b = instruction.B;
  789. var c = instruction.C;
  790. stack.SetTop(context.FrameBase + c + 1);
  791. var a = instruction.A;
  792. var task = Concat(context, context.FrameBase + a, c - b + 1);
  793. if (task.IsCompleted)
  794. {
  795. _ = task.Result;
  796. return true;
  797. }
  798. context.Task = task;
  799. context.PostOperation = PostOperationType.None;
  800. return false;
  801. }
  802. static async ValueTask<int> Concat(VirtualMachineExecutionContext context, int target, int total)
  803. {
  804. static bool ToString(ref LuaValue v)
  805. {
  806. if (v.Type == LuaValueType.String) return true;
  807. if (v.Type == LuaValueType.Number)
  808. {
  809. v = v.ToString();
  810. return true;
  811. }
  812. return false;
  813. }
  814. var stack = context.Stack;
  815. do
  816. {
  817. var top = context.Thread.Stack.Count;
  818. var n = 2;
  819. ref var lhs = ref stack.Get(top - 2);
  820. ref var rhs = ref stack.Get(top - 1);
  821. if (!(lhs.Type is LuaValueType.String or LuaValueType.Number) || !ToString(ref rhs))
  822. {
  823. await ExecuteBinaryOperationMetaMethod(top - 2, lhs, rhs, context, OpCode.Concat);
  824. }
  825. else if (rhs.UnsafeReadString().Length == 0)
  826. {
  827. ToString(ref lhs);
  828. }
  829. else if (lhs.TryReadString(out var str) && str.Length == 0)
  830. {
  831. lhs = rhs;
  832. }
  833. else
  834. {
  835. var tl = rhs.UnsafeReadString().Length;
  836. int i = 1;
  837. for (; i < total; i++)
  838. {
  839. ref var v = ref stack.Get(top - i - 1);
  840. if (!ToString(ref v))
  841. {
  842. break;
  843. }
  844. tl += v.UnsafeReadString().Length;
  845. }
  846. n = i;
  847. stack.Get(top - n) = string.Create(tl, (stack, top - n), static (span, pair) =>
  848. {
  849. var (stack, index) = pair;
  850. foreach (var v in stack.AsSpan().Slice(index))
  851. {
  852. var s = v.UnsafeReadString();
  853. if (s.Length == 0) continue;
  854. s.AsSpan().CopyTo(span);
  855. span = span[s.Length..];
  856. }
  857. });
  858. }
  859. total -= n - 1;
  860. stack.PopUntil(top - (n - 1));
  861. } while (total > 1);
  862. stack.Get(target) = stack.AsSpan()[^1];
  863. return 1;
  864. }
  865. internal static async ValueTask<LuaValue> Concat(LuaThread thread, int total, CancellationToken ct)
  866. {
  867. static bool ToString(ref LuaValue v)
  868. {
  869. if (v.Type == LuaValueType.String) return true;
  870. if (v.Type == LuaValueType.Number)
  871. {
  872. v = v.ToString();
  873. return true;
  874. }
  875. return false;
  876. }
  877. var stack = thread.Stack;
  878. do
  879. {
  880. var top = stack.Count;
  881. var n = 2;
  882. ref var lhs = ref stack.Get(top - 2);
  883. ref var rhs = ref stack.Get(top - 1);
  884. if (!(lhs.Type is LuaValueType.String or LuaValueType.Number) || !ToString(ref rhs))
  885. {
  886. var value = await ExecuteBinaryOperationMetaMethod(thread, lhs, rhs, OpCode.Concat, ct);
  887. stack.Get(top - 2) = value;
  888. }
  889. else if (rhs.UnsafeReadString().Length == 0)
  890. {
  891. ToString(ref lhs);
  892. }
  893. else if (lhs.TryReadString(out var str) && str.Length == 0)
  894. {
  895. lhs = rhs;
  896. }
  897. else
  898. {
  899. var tl = rhs.UnsafeReadString().Length;
  900. int i = 1;
  901. for (; i < total; i++)
  902. {
  903. ref var v = ref stack.Get(top - i - 1);
  904. if (!ToString(ref v))
  905. {
  906. break;
  907. }
  908. tl += v.UnsafeReadString().Length;
  909. }
  910. n = i;
  911. stack.Get(top - n) = string.Create(tl, (stack, top - n), static (span, pair) =>
  912. {
  913. var (stack, index) = pair;
  914. foreach (var v in stack.AsSpan().Slice(index))
  915. {
  916. var s = v.UnsafeReadString();
  917. if (s.Length == 0) continue;
  918. s.AsSpan().CopyTo(span);
  919. span = span[s.Length..];
  920. }
  921. });
  922. }
  923. total -= n - 1;
  924. stack.PopUntil(top - (n - 1));
  925. } while (total > 1);
  926. return stack.AsSpan()[^1];
  927. }
  928. static async ValueTask ExecuteBinaryOperationMetaMethod(int target, LuaValue vb, LuaValue vc,
  929. VirtualMachineExecutionContext context, OpCode opCode)
  930. {
  931. context.ThrowIfCancellationRequested();
  932. var (name, description) = opCode.GetNameAndDescription();
  933. if (vb.TryGetMetamethod(context.State, name, out var metamethod) ||
  934. vc.TryGetMetamethod(context.State, name, out metamethod))
  935. {
  936. var stack = context.Stack;
  937. var argCount = 2;
  938. var callable = metamethod;
  939. if (!metamethod.TryReadFunction(out var func))
  940. {
  941. if (metamethod.TryGetMetamethod(context.State, Metamethods.Call, out metamethod) &&
  942. metamethod.TryReadFunction(out func))
  943. {
  944. stack.Push(callable);
  945. argCount++;
  946. }
  947. else
  948. {
  949. LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "call", metamethod);
  950. }
  951. }
  952. stack.Push(vb);
  953. stack.Push(vc);
  954. var varArgCount = func.GetVariableArgumentCount(argCount);
  955. var newFrame = func.CreateNewFrame(context, stack.Count - argCount + varArgCount, target, varArgCount);
  956. var thread = context.Thread;
  957. var access = thread.PushCallStackFrame(newFrame);
  958. try
  959. {
  960. var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = argCount, ReturnFrameBase = target };
  961. if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
  962. {
  963. await ExecuteCallHook(functionContext, context.CancellationToken);
  964. stack.PopUntil(target + 1);
  965. context.PostOperation = PostOperationType.DontPop;
  966. context.ThrowIfCancellationRequested();
  967. return;
  968. }
  969. await func.Func(functionContext, context.CancellationToken);
  970. stack.PopUntil(target + 1);
  971. context.PostOperation = PostOperationType.DontPop;
  972. context.ThrowIfCancellationRequested();
  973. return;
  974. }
  975. finally
  976. {
  977. thread.PopCallStackFrame();
  978. }
  979. }
  980. LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), description, vb, vc);
  981. return;
  982. }
  983. static bool Call(VirtualMachineExecutionContext context, out bool doRestart)
  984. {
  985. context.ThrowIfCancellationRequested();
  986. var instruction = context.Instruction;
  987. var RA = instruction.A + context.FrameBase;
  988. var newBase = RA + 1;
  989. var va = context.Stack.Get(RA);
  990. bool isMetamethod = false;
  991. if (!va.TryReadFunction(out var func))
  992. {
  993. if (va.TryGetMetamethod(context.State, Metamethods.Call, out var metamethod) &&
  994. metamethod.TryReadFunction(out func))
  995. {
  996. newBase -= 1;
  997. isMetamethod = true;
  998. }
  999. else
  1000. {
  1001. LuaRuntimeException.AttemptInvalidOperationOnLuaStack(GetThreadWithCurrentPc(context), "call", context.Pc, instruction.A);
  1002. }
  1003. }
  1004. var thread = context.Thread;
  1005. var (argumentCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, instruction, newBase, isMetamethod);
  1006. newBase += variableArgumentCount;
  1007. thread.Stack.PopUntil(newBase + argumentCount);
  1008. var newFrame = func.CreateNewFrame(context, newBase, RA, variableArgumentCount);
  1009. var access = thread.PushCallStackFrame(newFrame);
  1010. if (thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
  1011. {
  1012. context.PostOperation = PostOperationType.Call;
  1013. context.Task = ExecuteCallHook(context, newFrame, argumentCount);
  1014. doRestart = false;
  1015. return false;
  1016. }
  1017. if (func is LuaClosure)
  1018. {
  1019. context.Push(newFrame);
  1020. doRestart = true;
  1021. return true;
  1022. }
  1023. doRestart = false;
  1024. return FuncCall(context, access, func, argumentCount, newFrame.ReturnBase);
  1025. static bool FuncCall(VirtualMachineExecutionContext context, LuaThreadAccess access, LuaFunction func, int argumentCount, int returnBase)
  1026. {
  1027. var task = func.Func(new() { Access = access, ArgumentCount = argumentCount, ReturnFrameBase = returnBase }, context.CancellationToken);
  1028. if (!task.IsCompleted)
  1029. {
  1030. context.PostOperation = PostOperationType.Call;
  1031. context.Task = task;
  1032. return false;
  1033. }
  1034. var awaiter = task.GetAwaiter();
  1035. awaiter.GetResult();
  1036. context.Thread.ThrowIfCancellationRequested(context.CancellationToken);
  1037. var instruction = context.Instruction;
  1038. var ic = instruction.C;
  1039. if (ic != 0)
  1040. {
  1041. var resultCount = ic - 1;
  1042. var stack = context.Stack;
  1043. var top = instruction.A + context.FrameBase + resultCount;
  1044. stack.EnsureCapacity(top);
  1045. stack.PopUntil(top);
  1046. stack.NotifyTop(top);
  1047. }
  1048. context.Thread.PopCallStackFrame();
  1049. return true;
  1050. }
  1051. }
  1052. internal static async ValueTask<int> Call(LuaThread thread, int funcIndex, int returnBase, CancellationToken cancellationToken)
  1053. {
  1054. thread.ThrowIfCancellationRequested(cancellationToken);
  1055. var stack = thread.Stack;
  1056. var newBase = funcIndex + 1;
  1057. var va = stack.Get(funcIndex);
  1058. if (!va.TryReadFunction(out var func))
  1059. {
  1060. if (va.TryGetMetamethod(thread.State, Metamethods.Call, out va) &&
  1061. va.TryReadFunction(out func))
  1062. {
  1063. newBase--;
  1064. }
  1065. else
  1066. {
  1067. LuaRuntimeException.AttemptInvalidOperation(thread, "call", va);
  1068. }
  1069. }
  1070. var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
  1071. newBase += variableArgumentCount;
  1072. var newFrame = new CallStackFrame() { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = returnBase };
  1073. var access = thread.PushCallStackFrame(newFrame);
  1074. try
  1075. {
  1076. var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = argCount, ReturnFrameBase = returnBase };
  1077. if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
  1078. {
  1079. await ExecuteCallHook(functionContext, cancellationToken);
  1080. }
  1081. else
  1082. {
  1083. await func.Func(functionContext, cancellationToken);
  1084. }
  1085. thread.ThrowIfCancellationRequested(cancellationToken);
  1086. return thread.Stack.Count - funcIndex;
  1087. }
  1088. catch (OperationCanceledException operationCanceledException)
  1089. {
  1090. if (operationCanceledException is not LuaCanceledException)
  1091. {
  1092. throw new LuaCanceledException(thread, cancellationToken, operationCanceledException);
  1093. }
  1094. throw;
  1095. }
  1096. finally
  1097. {
  1098. thread.PopCallStackFrame();
  1099. }
  1100. }
  1101. static void CallPostOperation(VirtualMachineExecutionContext context)
  1102. {
  1103. var instruction = context.Instruction;
  1104. var ic = instruction.C;
  1105. if (ic != 0)
  1106. {
  1107. var resultCount = ic - 1;
  1108. var stack = context.Stack;
  1109. var top = instruction.A + context.FrameBase + resultCount;
  1110. stack.EnsureCapacity(top);
  1111. stack.PopUntil(top);
  1112. stack.NotifyTop(top);
  1113. }
  1114. }
  1115. static bool TailCall(VirtualMachineExecutionContext context, out bool doRestart)
  1116. {
  1117. context.ThrowIfCancellationRequested();
  1118. var instruction = context.Instruction;
  1119. var stack = context.Stack;
  1120. var RA = instruction.A + context.FrameBase;
  1121. var newBase = RA + 1;
  1122. bool isMetamethod = false;
  1123. var state = context.State;
  1124. var thread = context.Thread;
  1125. state.CloseUpValues(thread, context.FrameBase);
  1126. var va = stack.Get(RA);
  1127. if (!va.TryReadFunction(out var func))
  1128. {
  1129. if (va.TryGetMetamethod(state, Metamethods.Call, out var metamethod) &&
  1130. metamethod.TryReadFunction(out func))
  1131. {
  1132. isMetamethod = true;
  1133. newBase -= 1;
  1134. }
  1135. else
  1136. {
  1137. LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "call", metamethod);
  1138. }
  1139. }
  1140. var (argumentCount, variableArgumentCount) = PrepareForFunctionTailCall(thread, func, instruction, newBase, isMetamethod);
  1141. newBase = context.FrameBase + variableArgumentCount;
  1142. stack.PopUntil(newBase + argumentCount);
  1143. var lastFrame = thread.GetCurrentFrame();
  1144. thread.LastPc = context.Pc;
  1145. thread.LastCallerFunction = lastFrame.Function;
  1146. context.Thread.PopCallStackFrame();
  1147. var newFrame = func.CreateNewTailCallFrame(context, newBase, lastFrame.ReturnBase, variableArgumentCount);
  1148. newFrame.CallerInstructionIndex = lastFrame.CallerInstructionIndex;
  1149. newFrame.Version = lastFrame.Version;
  1150. var access = thread.PushCallStackFrame(newFrame);
  1151. if (thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
  1152. {
  1153. context.PostOperation = PostOperationType.TailCall;
  1154. context.Task = ExecuteCallHook(context, newFrame, argumentCount, true);
  1155. doRestart = false;
  1156. return false;
  1157. }
  1158. if (func is LuaClosure)
  1159. {
  1160. context.Push(newFrame);
  1161. doRestart = true;
  1162. return true;
  1163. }
  1164. doRestart = false;
  1165. var task = func.Func(new() { Access = access, ArgumentCount = argumentCount, ReturnFrameBase = lastFrame.ReturnBase }, context.CancellationToken);
  1166. if (!task.IsCompleted)
  1167. {
  1168. context.PostOperation = PostOperationType.TailCall;
  1169. context.Task = task;
  1170. return false;
  1171. }
  1172. task.GetAwaiter().GetResult();
  1173. context.ThrowIfCancellationRequested();
  1174. if (!context.PopFromBuffer(lastFrame.ReturnBase, context.Stack.Count - lastFrame.ReturnBase))
  1175. {
  1176. return true;
  1177. }
  1178. doRestart = true;
  1179. return true;
  1180. }
  1181. static bool TForCall(VirtualMachineExecutionContext context, out bool doRestart)
  1182. {
  1183. context.ThrowIfCancellationRequested();
  1184. doRestart = false;
  1185. var instruction = context.Instruction;
  1186. var stack = context.Stack;
  1187. var RA = instruction.A + context.FrameBase;
  1188. bool isMetamethod = false;
  1189. var iteratorRaw = stack.Get(RA);
  1190. if (!iteratorRaw.TryReadFunction(out var iterator))
  1191. {
  1192. if (iteratorRaw.TryGetMetamethod(context.State, Metamethods.Call, out var metamethod) &&
  1193. metamethod.TryReadFunction(out iterator))
  1194. {
  1195. isMetamethod = true;
  1196. }
  1197. else
  1198. {
  1199. LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "call", metamethod);
  1200. }
  1201. }
  1202. var newBase = RA + 3 + instruction.C;
  1203. if (isMetamethod)
  1204. {
  1205. stack.Get(newBase) = iteratorRaw;
  1206. stack.Get(newBase + 1) = stack.Get(RA + 1);
  1207. stack.Get(newBase + 2) = stack.Get(RA + 2);
  1208. stack.SetTop(newBase + 3);
  1209. }
  1210. else
  1211. {
  1212. stack.Get(newBase) = stack.Get(RA + 1);
  1213. stack.Get(newBase + 1) = stack.Get(RA + 2);
  1214. stack.SetTop(newBase + 2);
  1215. }
  1216. var argumentCount = isMetamethod ? 3 : 2;
  1217. var variableArgumentCount = iterator.GetVariableArgumentCount(argumentCount);
  1218. if (variableArgumentCount != 0)
  1219. {
  1220. PrepareVariableArgument(stack, newBase, argumentCount, variableArgumentCount);
  1221. newBase += variableArgumentCount;
  1222. }
  1223. stack.PopUntil(newBase + argumentCount);
  1224. var newFrame = iterator.CreateNewFrame(context, newBase, RA + 3, variableArgumentCount);
  1225. var access = context.Thread.PushCallStackFrame(newFrame);
  1226. if (context.Thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
  1227. {
  1228. context.PostOperation = PostOperationType.TForCall;
  1229. context.Task = ExecuteCallHook(context, newFrame, stack.Count - newBase);
  1230. doRestart = false;
  1231. return false;
  1232. }
  1233. if (iterator is LuaClosure)
  1234. {
  1235. context.Push(newFrame);
  1236. doRestart = true;
  1237. return true;
  1238. }
  1239. var task = iterator.Func(new() { Access = access, ArgumentCount = stack.Count - newBase, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
  1240. if (!task.IsCompleted)
  1241. {
  1242. context.PostOperation = PostOperationType.TForCall;
  1243. context.Task = task;
  1244. return false;
  1245. }
  1246. task.GetAwaiter().GetResult();
  1247. context.ThrowIfCancellationRequested();
  1248. context.Thread.PopCallStackFrame();
  1249. TForCallPostOperation(context);
  1250. return true;
  1251. }
  1252. // ReSharper disable once InconsistentNaming
  1253. static void TForCallPostOperation(VirtualMachineExecutionContext context)
  1254. {
  1255. var stack = context.Stack;
  1256. var instruction = context.Instruction;
  1257. var RA = instruction.A + context.FrameBase;
  1258. stack.SetTop(RA + instruction.C + 3);
  1259. }
  1260. static void SetList(VirtualMachineExecutionContext context)
  1261. {
  1262. var instruction = context.Instruction;
  1263. var stack = context.Stack;
  1264. var RA = instruction.A + context.FrameBase;
  1265. if (!stack.Get(RA).TryReadTable(out var table))
  1266. {
  1267. throw new LuaRuntimeException(GetThreadWithCurrentPc(context), "internal error");
  1268. }
  1269. var count = instruction.B == 0
  1270. ? stack.Count - (RA + 1)
  1271. : instruction.B;
  1272. var c = instruction.C;
  1273. if (c == 0)
  1274. {
  1275. context.Pc++;
  1276. c = context.Prototype.Code[context.Pc].Ax;
  1277. }
  1278. table.EnsureArrayCapacity((c - 1) * 50 + count);
  1279. stack.GetBuffer().Slice(RA + 1, count)
  1280. .CopyTo(table.GetArraySpan()[((c - 1) * 50)..]);
  1281. stack.PopUntil(RA + 1);
  1282. }
  1283. static void ComparePostOperation(VirtualMachineExecutionContext context, Span<LuaValue> results)
  1284. {
  1285. var compareResult = results.Length != 0 && results[0].ToBoolean();
  1286. if (compareResult != (context.Instruction.A == 1))
  1287. {
  1288. context.Pc++;
  1289. }
  1290. results.Clear();
  1291. }
  1292. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1293. static ref readonly LuaValue RKB(ref LuaValue stack, ref LuaValue constants, Instruction instruction)
  1294. {
  1295. var index = instruction.B;
  1296. return ref (index >= 256 ? ref Unsafe.Add(ref constants, index - 256) : ref Unsafe.Add(ref stack, index));
  1297. }
  1298. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1299. static ref readonly LuaValue RKC(ref LuaValue stack, ref LuaValue constants, Instruction instruction)
  1300. {
  1301. var index = instruction.C;
  1302. return ref (index >= 256 ? ref Unsafe.Add(ref constants, index - 256) : ref Unsafe.Add(ref stack, index));
  1303. }
  1304. [MethodImpl(MethodImplOptions.NoInlining)]
  1305. static bool GetTableValueSlowPath(LuaValue table, LuaValue key, VirtualMachineExecutionContext context, out LuaValue value, out bool doRestart)
  1306. {
  1307. var targetTable = table;
  1308. const int MAX_LOOP = 100;
  1309. doRestart = false;
  1310. var skip = targetTable.Type == LuaValueType.Table;
  1311. for (int i = 0; i < MAX_LOOP; i++)
  1312. {
  1313. if (table.TryReadTable(out var luaTable))
  1314. {
  1315. if (!skip && luaTable.TryGetValue(key, out value))
  1316. {
  1317. return true;
  1318. }
  1319. skip = false;
  1320. var metatable = luaTable.Metatable;
  1321. if (metatable != null && metatable.TryGetValue(Metamethods.Index, out table))
  1322. {
  1323. goto Function;
  1324. }
  1325. value = default;
  1326. return true;
  1327. }
  1328. if (!table.TryGetMetamethod(context.State, Metamethods.Index, out var metatableValue))
  1329. {
  1330. if (i == 0)
  1331. ThrowInvalidOperationWithName();
  1332. else
  1333. LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "index", table);
  1334. }
  1335. table = metatableValue;
  1336. Function:
  1337. if (table.TryReadFunction(out var function))
  1338. {
  1339. return CallGetTableFunc(targetTable, function, key, context, out value, out doRestart);
  1340. }
  1341. }
  1342. throw new LuaRuntimeException(GetThreadWithCurrentPc(context), "loop in gettable");
  1343. [MethodImpl(MethodImplOptions.NoInlining)]
  1344. void ThrowInvalidOperationWithName()
  1345. {
  1346. var op = context.Instruction.OpCode;
  1347. if (op != OpCode.GetTabUp)
  1348. LuaRuntimeException.AttemptInvalidOperationOnLuaStack(GetThreadWithCurrentPc(context), "index", context.Pc, context.Instruction.B);
  1349. else
  1350. LuaRuntimeException.AttemptInvalidOperationOnUpValues(GetThreadWithCurrentPc(context), "index", context.Instruction.B);
  1351. }
  1352. }
  1353. [MethodImpl(MethodImplOptions.NoInlining)]
  1354. static bool CallGetTableFunc(LuaValue table, LuaFunction indexTable, LuaValue key, VirtualMachineExecutionContext context, out LuaValue result, out bool doRestart)
  1355. {
  1356. doRestart = false;
  1357. var stack = context.Stack;
  1358. stack.Push(table);
  1359. stack.Push(key);
  1360. var newFrame = indexTable.CreateNewFrame(context, stack.Count - 2);
  1361. var access = context.Thread.PushCallStackFrame(newFrame);
  1362. if (context.Thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
  1363. {
  1364. context.PostOperation = context.Instruction.OpCode == OpCode.GetTable ? PostOperationType.SetResult : PostOperationType.Self;
  1365. context.Task = ExecuteCallHook(context, newFrame, 2);
  1366. doRestart = false;
  1367. result = default;
  1368. return false;
  1369. }
  1370. if (indexTable is LuaClosure)
  1371. {
  1372. context.Push(newFrame);
  1373. doRestart = true;
  1374. result = default;
  1375. return true;
  1376. }
  1377. var task = indexTable.Func(new() { Access = access, ArgumentCount = 2, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
  1378. if (!task.IsCompleted)
  1379. {
  1380. context.PostOperation = context.Instruction.OpCode == OpCode.GetTable ? PostOperationType.SetResult : PostOperationType.Self;
  1381. context.Task = task;
  1382. result = default;
  1383. return false;
  1384. }
  1385. var awaiter = task.GetAwaiter();
  1386. awaiter.GetResult();
  1387. var results = stack.GetBuffer()[newFrame.ReturnBase..];
  1388. result = results.Length == 0 ? default : results[0];
  1389. context.Thread.PopCallStackFrameWithStackPop();
  1390. return true;
  1391. }
  1392. [MethodImpl(MethodImplOptions.NoInlining)]
  1393. internal static ValueTask<LuaValue> ExecuteGetTableSlowPath(LuaThread thread, LuaValue table, LuaValue key, CancellationToken ct)
  1394. {
  1395. var targetTable = table;
  1396. const int MAX_LOOP = 100;
  1397. var skip = targetTable.Type == LuaValueType.Table;
  1398. for (int i = 0; i < MAX_LOOP; i++)
  1399. {
  1400. if (table.TryReadTable(out var luaTable))
  1401. {
  1402. if (!skip && luaTable.TryGetValue(key, out var value))
  1403. {
  1404. return new(value);
  1405. }
  1406. skip = false;
  1407. var metatable = luaTable.Metatable;
  1408. if (metatable != null && metatable.TryGetValue(Metamethods.Index, out table))
  1409. {
  1410. goto Function;
  1411. }
  1412. return default(ValueTask<LuaValue>);
  1413. }
  1414. if (!table.TryGetMetamethod(thread.State, Metamethods.Index, out var metatableValue))
  1415. {
  1416. LuaRuntimeException.AttemptInvalidOperation(thread, "index", table);
  1417. }
  1418. table = metatableValue;
  1419. Function:
  1420. if (table.TryReadFunction(out var function))
  1421. {
  1422. return CallGetTableFunc(thread, function, targetTable, key, ct);
  1423. }
  1424. }
  1425. throw new LuaRuntimeException(thread, "loop in gettable");
  1426. }
  1427. [MethodImpl(MethodImplOptions.NoInlining)]
  1428. static async ValueTask<LuaValue> CallGetTableFunc(LuaThread thread, LuaFunction indexTable, LuaValue table, LuaValue key, CancellationToken ct)
  1429. {
  1430. var stack = thread.Stack;
  1431. var top = stack.Count;
  1432. stack.Push(table);
  1433. stack.Push(key);
  1434. var varArgCount = indexTable.GetVariableArgumentCount(2);
  1435. var newFrame = new CallStackFrame() { Base = thread.Stack.Count - 2 + varArgCount, VariableArgumentCount = varArgCount, Function = indexTable, ReturnBase = top };
  1436. var access = thread.PushCallStackFrame(newFrame);
  1437. var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = 2, ReturnFrameBase = top };
  1438. if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
  1439. {
  1440. await ExecuteCallHook(functionContext, ct);
  1441. }
  1442. await indexTable.Func(functionContext, ct);
  1443. var results = stack.GetBuffer()[newFrame.ReturnBase..];
  1444. var result = results.Length == 0 ? default : results[0];
  1445. thread.PopCallStackFrameWithStackPop();
  1446. return result;
  1447. }
  1448. [MethodImpl(MethodImplOptions.NoInlining)]
  1449. static bool SetTableValueSlowPath(LuaValue table, LuaValue key, LuaValue value,
  1450. VirtualMachineExecutionContext context, out bool doRestart)
  1451. {
  1452. var targetTable = table;
  1453. const int MAX_LOOP = 100;
  1454. doRestart = false;
  1455. var skip = targetTable.Type == LuaValueType.Table;
  1456. for (int i = 0; i < MAX_LOOP; i++)
  1457. {
  1458. if (table.TryReadTable(out var luaTable))
  1459. {
  1460. targetTable = luaTable;
  1461. ref var valueRef = ref (skip ? ref Unsafe.NullRef<LuaValue>() : ref luaTable.FindValue(key));
  1462. skip = false;
  1463. if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
  1464. {
  1465. valueRef = value;
  1466. return true;
  1467. }
  1468. var metatable = luaTable.Metatable;
  1469. if (metatable == null || !metatable.TryGetValue(Metamethods.NewIndex, out table))
  1470. {
  1471. if (Unsafe.IsNullRef(ref valueRef))
  1472. {
  1473. luaTable[key] = value;
  1474. return true;
  1475. }
  1476. valueRef = value;
  1477. return true;
  1478. }
  1479. goto Function;
  1480. }
  1481. if (!table.TryGetMetamethod(context.State, Metamethods.NewIndex, out var metatableValue))
  1482. {
  1483. if (i == 0)
  1484. ThrowInvalidOperationWithName();
  1485. else
  1486. LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "index", table);
  1487. }
  1488. table = metatableValue;
  1489. Function:
  1490. if (table.TryReadFunction(out var function))
  1491. {
  1492. context.PostOperation = PostOperationType.Nop;
  1493. return CallSetTableFunc(targetTable, function, key, value, context, out doRestart);
  1494. }
  1495. }
  1496. throw new LuaRuntimeException(GetThreadWithCurrentPc(context), "loop in settable");
  1497. [MethodImpl(MethodImplOptions.NoInlining)]
  1498. void ThrowInvalidOperationWithName()
  1499. {
  1500. var op = context.Instruction.OpCode;
  1501. if (op != OpCode.SetTabUp)
  1502. LuaRuntimeException.AttemptInvalidOperationOnLuaStack(GetThreadWithCurrentPc(context), "index", context.Pc, context.Instruction.A);
  1503. else
  1504. LuaRuntimeException.AttemptInvalidOperationOnUpValues(GetThreadWithCurrentPc(context), "index", context.Instruction.A);
  1505. }
  1506. }
  1507. [MethodImpl(MethodImplOptions.NoInlining)]
  1508. static bool CallSetTableFunc(LuaValue table, LuaFunction newIndexFunction, LuaValue key, LuaValue value, VirtualMachineExecutionContext context, out bool doRestart)
  1509. {
  1510. doRestart = false;
  1511. var thread = context.Thread;
  1512. var stack = thread.Stack;
  1513. stack.Push(table);
  1514. stack.Push(key);
  1515. stack.Push(value);
  1516. var newFrame = newIndexFunction.CreateNewFrame(context, stack.Count - 3);
  1517. var access = context.Thread.PushCallStackFrame(newFrame);
  1518. if (context.Thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
  1519. {
  1520. context.PostOperation = PostOperationType.Nop;
  1521. context.Task = ExecuteCallHook(context, newFrame, 3);
  1522. doRestart = false;
  1523. return false;
  1524. }
  1525. if (newIndexFunction is LuaClosure)
  1526. {
  1527. context.Push(newFrame);
  1528. doRestart = true;
  1529. return true;
  1530. }
  1531. var task = newIndexFunction.Func(new() { Access = access, ArgumentCount = 3, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
  1532. if (!task.IsCompleted)
  1533. {
  1534. context.PostOperation = PostOperationType.Nop;
  1535. context.Task = task;
  1536. return false;
  1537. }
  1538. task.GetAwaiter().GetResult();
  1539. thread.PopCallStackFrameWithStackPop();
  1540. return true;
  1541. }
  1542. internal static ValueTask ExecuteSetTableSlowPath(LuaThread thread, LuaValue table, LuaValue key, LuaValue value, CancellationToken ct)
  1543. {
  1544. var targetTable = table;
  1545. const int MAX_LOOP = 100;
  1546. var skip = targetTable.Type == LuaValueType.Table;
  1547. for (int i = 0; i < MAX_LOOP; i++)
  1548. {
  1549. if (table.TryReadTable(out var luaTable))
  1550. {
  1551. targetTable = luaTable;
  1552. ref var valueRef = ref (skip ? ref Unsafe.NullRef<LuaValue>() : ref luaTable.FindValue(key));
  1553. skip = false;
  1554. if (!Unsafe.IsNullRef(ref valueRef) && valueRef.Type != LuaValueType.Nil)
  1555. {
  1556. valueRef = value;
  1557. return default(ValueTask);
  1558. }
  1559. var metatable = luaTable.Metatable;
  1560. if (metatable == null || !metatable.TryGetValue(Metamethods.NewIndex, out table))
  1561. {
  1562. if (Unsafe.IsNullRef(ref valueRef))
  1563. {
  1564. luaTable[key] = value;
  1565. return default(ValueTask);
  1566. }
  1567. valueRef = value;
  1568. return default;
  1569. }
  1570. goto Function;
  1571. }
  1572. if (!table.TryGetMetamethod(thread.State, Metamethods.NewIndex, out var metatableValue))
  1573. {
  1574. LuaRuntimeException.AttemptInvalidOperation(thread, "index", table);
  1575. }
  1576. table = metatableValue;
  1577. Function:
  1578. if (table.TryReadFunction(out var function))
  1579. {
  1580. return CallSetTableFunc(thread, function, targetTable, key, value, ct);
  1581. }
  1582. }
  1583. throw new LuaRuntimeException(thread, "loop in settable");
  1584. }
  1585. [MethodImpl(MethodImplOptions.NoInlining)]
  1586. static async ValueTask CallSetTableFunc(LuaThread thread, LuaFunction newIndexFunction, LuaValue table, LuaValue key, LuaValue value, CancellationToken ct)
  1587. {
  1588. var stack = thread.Stack;
  1589. var top = stack.Count;
  1590. stack.Push(table);
  1591. stack.Push(key);
  1592. stack.Push(value);
  1593. var varArgCount = newIndexFunction.GetVariableArgumentCount(3);
  1594. var newFrame = new CallStackFrame() { Base = thread.Stack.Count - 3 + varArgCount, VariableArgumentCount = varArgCount, Function = newIndexFunction, ReturnBase = top };
  1595. var access = thread.PushCallStackFrame(newFrame);
  1596. var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = 3, ReturnFrameBase = top };
  1597. if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
  1598. {
  1599. await ExecuteCallHook(functionContext, ct);
  1600. }
  1601. await newIndexFunction.Func(functionContext, ct);
  1602. thread.PopCallStackFrameWithStackPop();
  1603. }
  1604. [MethodImpl(MethodImplOptions.NoInlining)]
  1605. static bool ExecuteBinaryOperationMetaMethod(LuaValue vb, LuaValue vc,
  1606. VirtualMachineExecutionContext context, OpCode opCode, out bool doRestart)
  1607. {
  1608. var (name, description) = opCode.GetNameAndDescription();
  1609. doRestart = false;
  1610. if (vb.TryGetMetamethod(context.State, name, out var metamethod) ||
  1611. vc.TryGetMetamethod(context.State, name, out metamethod))
  1612. {
  1613. var stack = context.Stack;
  1614. var newBase = stack.Count;
  1615. var callable = metamethod;
  1616. if (!metamethod.TryReadFunction(out var func))
  1617. {
  1618. if (metamethod.TryGetMetamethod(context.State, Metamethods.Call, out metamethod) &&
  1619. metamethod.TryReadFunction(out func))
  1620. {
  1621. stack.Push(callable);
  1622. }
  1623. else
  1624. {
  1625. LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "call", metamethod);
  1626. }
  1627. }
  1628. stack.Push(vb);
  1629. stack.Push(vc);
  1630. var (argCount, variableArgumentCount) = PrepareForFunctionCall(context.Thread, func, newBase);
  1631. newBase += variableArgumentCount;
  1632. var newFrame = func.CreateNewFrame(context, newBase, context.FrameBase + context.Instruction.A, variableArgumentCount);
  1633. var access = context.Thread.PushCallStackFrame(newFrame);
  1634. if (context.Thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
  1635. {
  1636. context.PostOperation = PostOperationType.SetResult;
  1637. context.Task = ExecuteCallHook(context, newFrame, argCount);
  1638. doRestart = false;
  1639. return false;
  1640. }
  1641. if (func is LuaClosure)
  1642. {
  1643. context.Push(newFrame);
  1644. doRestart = true;
  1645. return true;
  1646. }
  1647. var task = func.Func(new() { Access = access, ArgumentCount = argCount, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
  1648. if (!task.IsCompleted)
  1649. {
  1650. context.PostOperation = PostOperationType.SetResult;
  1651. context.Task = task;
  1652. return false;
  1653. }
  1654. task.GetAwaiter().GetResult();
  1655. var RA = context.Instruction.A + context.FrameBase;
  1656. var results = stack.GetBuffer()[newFrame.ReturnBase..];
  1657. LuaValue result = default;
  1658. if (results.Length != 0)
  1659. {
  1660. result = results[0];
  1661. results.Clear();
  1662. }
  1663. stack.Get(RA) = result;
  1664. context.Thread.PopCallStackFrameWithStackPop();
  1665. return true;
  1666. }
  1667. LuaRuntimeException.AttemptInvalidOperationOnLuaStack(GetThreadWithCurrentPc(context), description, context.Pc, context.Instruction.B, context.Instruction.C);
  1668. return false;
  1669. }
  1670. [MethodImpl(MethodImplOptions.NoInlining)]
  1671. internal static async ValueTask<LuaValue> ExecuteBinaryOperationMetaMethod(LuaThread thread, LuaValue vb, LuaValue vc, OpCode opCode, CancellationToken ct)
  1672. {
  1673. var (name, description) = opCode.GetNameAndDescription();
  1674. if (vb.TryGetMetamethod(thread.State, name, out var metamethod) ||
  1675. vc.TryGetMetamethod(thread.State, name, out metamethod))
  1676. {
  1677. var stack = thread.Stack;
  1678. var newBase = stack.Count;
  1679. var callable = metamethod;
  1680. if (!metamethod.TryReadFunction(out var func))
  1681. {
  1682. if (metamethod.TryGetMetamethod(thread.State, Metamethods.Call, out metamethod) &&
  1683. metamethod.TryReadFunction(out func))
  1684. {
  1685. stack.Push(callable);
  1686. }
  1687. else
  1688. {
  1689. LuaRuntimeException.AttemptInvalidOperation(thread, "call", metamethod);
  1690. }
  1691. }
  1692. stack.Push(vb);
  1693. stack.Push(vc);
  1694. var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
  1695. newBase += variableArgumentCount;
  1696. var newFrame = new CallStackFrame() { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = newBase };
  1697. var access = thread.PushCallStackFrame(newFrame);
  1698. try
  1699. {
  1700. var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = argCount, ReturnFrameBase = newBase };
  1701. if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
  1702. {
  1703. await ExecuteCallHook(functionContext, ct);
  1704. }
  1705. await func.Func(functionContext, ct);
  1706. var results = stack.AsSpan()[newFrame.ReturnBase..];
  1707. var result = results.Length == 0 ? default : results[0];
  1708. return result;
  1709. }
  1710. finally
  1711. {
  1712. thread.PopCallStackFrameWithStackPop();
  1713. }
  1714. }
  1715. LuaRuntimeException.AttemptInvalidOperation(thread, description, vb, vc);
  1716. return default;
  1717. }
  1718. [MethodImpl(MethodImplOptions.NoInlining)]
  1719. static bool ExecuteUnaryOperationMetaMethod(LuaValue vb, VirtualMachineExecutionContext context,
  1720. OpCode opCode, out bool doRestart)
  1721. {
  1722. var (name, description) = opCode.GetNameAndDescription();
  1723. doRestart = false;
  1724. var stack = context.Stack;
  1725. if (vb.TryGetMetamethod(context.State, name, out var metamethod))
  1726. {
  1727. var newBase = stack.Count;
  1728. var callable = metamethod;
  1729. if (!metamethod.TryReadFunction(out var func))
  1730. {
  1731. if (metamethod.TryGetMetamethod(context.State, Metamethods.Call, out metamethod) &&
  1732. metamethod.TryReadFunction(out func))
  1733. {
  1734. stack.Push(callable);
  1735. }
  1736. else
  1737. {
  1738. LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "call", metamethod);
  1739. }
  1740. }
  1741. stack.Push(vb);
  1742. stack.Push(vb);
  1743. var (argCount, variableArgumentCount) = PrepareForFunctionCall(context.Thread, func, newBase);
  1744. newBase += variableArgumentCount;
  1745. var newFrame = func.CreateNewFrame(context, newBase, context.FrameBase + context.Instruction.A, variableArgumentCount);
  1746. var access = context.Thread.PushCallStackFrame(newFrame);
  1747. if (context.Thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
  1748. {
  1749. context.PostOperation = PostOperationType.SetResult;
  1750. context.Task = ExecuteCallHook(context, newFrame, argCount);
  1751. doRestart = false;
  1752. return false;
  1753. }
  1754. if (func is LuaClosure)
  1755. {
  1756. context.Push(newFrame);
  1757. doRestart = true;
  1758. return true;
  1759. }
  1760. var task = func.Func(new() { Access = access, ArgumentCount = argCount, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
  1761. if (!task.IsCompleted)
  1762. {
  1763. context.PostOperation = PostOperationType.SetResult;
  1764. context.Task = task;
  1765. return false;
  1766. }
  1767. stack.PopUntil(newFrame.ReturnBase + 1);
  1768. context.Thread.PopCallStackFrame();
  1769. return true;
  1770. }
  1771. if (opCode == OpCode.Len && vb.TryReadTable(out var table))
  1772. {
  1773. var RA = context.Instruction.A + context.FrameBase;
  1774. stack.Get(RA) = table.ArrayLength;
  1775. return true;
  1776. }
  1777. LuaRuntimeException.AttemptInvalidOperationOnLuaStack(GetThreadWithCurrentPc(context), description, context.Pc, context.Instruction.B);
  1778. return true;
  1779. }
  1780. [MethodImpl(MethodImplOptions.NoInlining)]
  1781. internal static async ValueTask<LuaValue> ExecuteUnaryOperationMetaMethod(LuaThread thread, LuaValue vb, OpCode opCode, CancellationToken cancellationToken)
  1782. {
  1783. thread.ThrowIfCancellationRequested(cancellationToken);
  1784. var (name, description) = opCode.GetNameAndDescription();
  1785. if (vb.TryGetMetamethod(thread.State, name, out var metamethod))
  1786. {
  1787. var stack = thread.Stack;
  1788. var newBase = stack.Count;
  1789. var callable = metamethod;
  1790. if (!metamethod.TryReadFunction(out var func))
  1791. {
  1792. if (metamethod.TryGetMetamethod(thread.State, Metamethods.Call, out metamethod) &&
  1793. metamethod.TryReadFunction(out func))
  1794. {
  1795. stack.Push(callable);
  1796. }
  1797. else
  1798. {
  1799. LuaRuntimeException.AttemptInvalidOperation(thread, "call", metamethod);
  1800. }
  1801. }
  1802. stack.Push(vb);
  1803. stack.Push(vb);
  1804. var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
  1805. newBase += variableArgumentCount;
  1806. var newFrame = new CallStackFrame() { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = newBase };
  1807. var access = thread.PushCallStackFrame(newFrame);
  1808. try
  1809. {
  1810. var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = argCount, ReturnFrameBase = newBase };
  1811. if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
  1812. {
  1813. await ExecuteCallHook(functionContext, cancellationToken);
  1814. }
  1815. else
  1816. {
  1817. await func.Func(functionContext, cancellationToken);
  1818. }
  1819. thread.ThrowIfCancellationRequested(cancellationToken);
  1820. var results = stack.AsSpan()[newFrame.ReturnBase..];
  1821. var result = results.Length == 0 ? default : results[0];
  1822. results.Clear();
  1823. return result;
  1824. }
  1825. finally
  1826. {
  1827. thread.PopCallStackFrameWithStackPop();
  1828. }
  1829. }
  1830. LuaRuntimeException.AttemptInvalidOperation(thread, description, vb);
  1831. return default;
  1832. }
  1833. [MethodImpl(MethodImplOptions.NoInlining)]
  1834. static bool ExecuteCompareOperationMetaMethod(LuaValue vb, LuaValue vc,
  1835. VirtualMachineExecutionContext context, OpCode opCode, out bool doRestart)
  1836. {
  1837. var (name, description) = opCode.GetNameAndDescription();
  1838. doRestart = false;
  1839. bool reverseLe = false;
  1840. ReCheck:
  1841. if (vb.TryGetMetamethod(context.State, name, out var metamethod) ||
  1842. vc.TryGetMetamethod(context.State, name, out metamethod))
  1843. {
  1844. var stack = context.Stack;
  1845. var argCount = 2;
  1846. var callable = metamethod;
  1847. if (!metamethod.TryReadFunction(out var func))
  1848. {
  1849. if (metamethod.TryGetMetamethod(context.State, Metamethods.Call, out metamethod) &&
  1850. metamethod.TryReadFunction(out func))
  1851. {
  1852. stack.Push(callable);
  1853. argCount++;
  1854. }
  1855. else
  1856. {
  1857. LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "call", metamethod);
  1858. }
  1859. }
  1860. stack.Push(vb);
  1861. stack.Push(vc);
  1862. var varArgCount = func.GetVariableArgumentCount(argCount);
  1863. var newFrame = func.CreateNewFrame(context, stack.Count - argCount + varArgCount);
  1864. if (reverseLe) newFrame.Flags |= CallStackFrameFlags.ReversedLe;
  1865. var access = context.Thread.PushCallStackFrame(newFrame);
  1866. if (context.Thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
  1867. {
  1868. context.PostOperation = PostOperationType.Compare;
  1869. context.Task = ExecuteCallHook(context, newFrame, argCount);
  1870. doRestart = false;
  1871. return false;
  1872. }
  1873. if (func is LuaClosure)
  1874. {
  1875. context.Push(newFrame);
  1876. doRestart = true;
  1877. return true;
  1878. }
  1879. var task = func.Func(new() { Access = access, ArgumentCount = argCount, ReturnFrameBase = newFrame.ReturnBase }, context.CancellationToken);
  1880. if (!task.IsCompleted)
  1881. {
  1882. context.PostOperation = PostOperationType.Compare;
  1883. context.Task = task;
  1884. return false;
  1885. }
  1886. var results = stack.AsSpan()[newFrame.ReturnBase..];
  1887. var compareResult = results.Length == 0 && results[0].ToBoolean();
  1888. compareResult = reverseLe ? !compareResult : compareResult;
  1889. if (compareResult != (context.Instruction.A == 1))
  1890. {
  1891. context.Pc++;
  1892. }
  1893. stack.PopUntil(newFrame.ReturnBase + 1);
  1894. context.Thread.PopCallStackFrame();
  1895. return true;
  1896. }
  1897. if (opCode == OpCode.Le)
  1898. {
  1899. reverseLe = true;
  1900. name = Metamethods.Lt;
  1901. (vb, vc) = (vc, vb);
  1902. goto ReCheck;
  1903. }
  1904. if (opCode != OpCode.Eq)
  1905. {
  1906. if (reverseLe)
  1907. {
  1908. (vb, vc) = (vc, vb);
  1909. }
  1910. LuaRuntimeException.AttemptInvalidOperation(GetThreadWithCurrentPc(context), "compare", vb, vc);
  1911. }
  1912. else
  1913. {
  1914. if (context.Instruction.A == 1)
  1915. {
  1916. context.Pc++;
  1917. }
  1918. }
  1919. return true;
  1920. }
  1921. [MethodImpl(MethodImplOptions.NoInlining)]
  1922. internal static async ValueTask<bool> ExecuteCompareOperationMetaMethod(LuaThread thread, LuaValue vb, LuaValue vc, OpCode opCode, CancellationToken cancellationToken)
  1923. {
  1924. thread.ThrowIfCancellationRequested(cancellationToken);
  1925. var (name, description) = opCode.GetNameAndDescription();
  1926. bool reverseLe = false;
  1927. ReCheck:
  1928. if (vb.TryGetMetamethod(thread.State, name, out var metamethod) ||
  1929. vc.TryGetMetamethod(thread.State, name, out metamethod))
  1930. {
  1931. var stack = thread.Stack;
  1932. var newBase = stack.Count;
  1933. var callable = metamethod;
  1934. if (!metamethod.TryReadFunction(out var func))
  1935. {
  1936. if (metamethod.TryGetMetamethod(thread.State, Metamethods.Call, out metamethod) &&
  1937. metamethod.TryReadFunction(out func))
  1938. {
  1939. stack.Push(callable);
  1940. }
  1941. else
  1942. {
  1943. LuaRuntimeException.AttemptInvalidOperation(thread, "call", metamethod);
  1944. }
  1945. }
  1946. stack.Push(vb);
  1947. stack.Push(vc);
  1948. var (argCount, variableArgumentCount) = PrepareForFunctionCall(thread, func, newBase);
  1949. newBase += variableArgumentCount;
  1950. var newFrame = new CallStackFrame() { Base = newBase, VariableArgumentCount = variableArgumentCount, Function = func, ReturnBase = newBase };
  1951. var access = thread.PushCallStackFrame(newFrame);
  1952. try
  1953. {
  1954. var functionContext = new LuaFunctionExecutionContext() { Access = access, ArgumentCount = argCount, ReturnFrameBase = newBase };
  1955. if (thread.CallOrReturnHookMask.Value != 0 && !thread.IsInHook)
  1956. {
  1957. await ExecuteCallHook(functionContext, cancellationToken);
  1958. }
  1959. else
  1960. {
  1961. await func.Func(functionContext, cancellationToken);
  1962. }
  1963. thread.ThrowIfCancellationRequested(cancellationToken);
  1964. var results = stack.AsSpan()[newFrame.ReturnBase..];
  1965. var result = results.Length == 0 ? default : results[0];
  1966. results.Clear();
  1967. return result.ToBoolean();
  1968. }
  1969. finally
  1970. {
  1971. thread.PopCallStackFrame();
  1972. }
  1973. }
  1974. if (opCode == OpCode.Le)
  1975. {
  1976. reverseLe = true;
  1977. name = Metamethods.Lt;
  1978. (vb, vc) = (vc, vb);
  1979. goto ReCheck;
  1980. }
  1981. if (opCode != OpCode.Eq)
  1982. {
  1983. if (reverseLe)
  1984. {
  1985. (vb, vc) = (vc, vb);
  1986. }
  1987. LuaRuntimeException.AttemptInvalidOperation(thread, description, vb, vc);
  1988. }
  1989. return default;
  1990. }
  1991. // 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.
  1992. // see: https://wubingzheng.github.io/build-lua-in-rust/en/ch08-02.arguments.html
  1993. [MethodImpl(MethodImplOptions.NoInlining)]
  1994. internal static void PrepareVariableArgument(LuaStack stack, int argumentCount,
  1995. int variableArgumentCount)
  1996. {
  1997. var top = stack.Count;
  1998. var newBase = stack.Count - argumentCount;
  1999. var temp = newBase;
  2000. newBase += variableArgumentCount;
  2001. stack.EnsureCapacity(newBase + argumentCount);
  2002. stack.NotifyTop(newBase + argumentCount);
  2003. var stackBuffer = stack.GetBuffer()[temp..];
  2004. stackBuffer[..argumentCount].CopyTo(stackBuffer[variableArgumentCount..]);
  2005. stackBuffer.Slice(argumentCount, variableArgumentCount).CopyTo(stackBuffer);
  2006. stack.PopUntil(top);
  2007. }
  2008. // 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.
  2009. // see: https://wubingzheng.github.io/build-lua-in-rust/en/ch08-02.arguments.html
  2010. [MethodImpl(MethodImplOptions.NoInlining)]
  2011. static (int ArgumentCount, int VariableArgumentCount) PrepareVariableArgument(LuaStack stack, int newBase, int argumentCount,
  2012. int variableArgumentCount)
  2013. {
  2014. var temp = newBase;
  2015. newBase += variableArgumentCount;
  2016. stack.EnsureCapacity(newBase + argumentCount);
  2017. stack.NotifyTop(newBase + argumentCount);
  2018. var stackBuffer = stack.GetBuffer()[temp..];
  2019. stackBuffer[..argumentCount].CopyTo(stackBuffer[variableArgumentCount..]);
  2020. stackBuffer.Slice(argumentCount, variableArgumentCount).CopyTo(stackBuffer);
  2021. return (argumentCount, variableArgumentCount);
  2022. }
  2023. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2024. static (int ArgumentCount, int VariableArgumentCount) PrepareForFunctionCall(LuaThread thread, LuaFunction function,
  2025. Instruction instruction, int newBase, bool isMetamethod)
  2026. {
  2027. var argumentCount = instruction.B - 1;
  2028. if (argumentCount == -1)
  2029. {
  2030. argumentCount = (ushort)(thread.Stack.Count - newBase);
  2031. }
  2032. else
  2033. {
  2034. if (isMetamethod)
  2035. {
  2036. argumentCount += 1;
  2037. }
  2038. thread.Stack.SetTop(newBase + argumentCount);
  2039. }
  2040. var variableArgumentCount = function.GetVariableArgumentCount(argumentCount);
  2041. if (variableArgumentCount < 0)
  2042. {
  2043. thread.Stack.SetTop(thread.Stack.Count - variableArgumentCount);
  2044. argumentCount -= variableArgumentCount;
  2045. variableArgumentCount = 0;
  2046. }
  2047. if (variableArgumentCount == 0)
  2048. {
  2049. return (argumentCount, 0);
  2050. }
  2051. return PrepareVariableArgument(thread.Stack, newBase, argumentCount, variableArgumentCount);
  2052. }
  2053. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2054. static (int ArgumentCount, int VariableArgumentCount) PrepareForFunctionCall(LuaThread thread, LuaFunction function,
  2055. int newBase)
  2056. {
  2057. var argumentCount = (int)(thread.Stack.Count - newBase);
  2058. var variableArgumentCount = function.GetVariableArgumentCount(argumentCount);
  2059. if (variableArgumentCount < 0)
  2060. {
  2061. thread.Stack.SetTop(thread.Stack.Count - variableArgumentCount);
  2062. argumentCount -= variableArgumentCount;
  2063. variableArgumentCount = 0;
  2064. }
  2065. if (variableArgumentCount == 0)
  2066. {
  2067. return (argumentCount, 0);
  2068. }
  2069. return PrepareVariableArgument(thread.Stack, newBase, argumentCount, variableArgumentCount);
  2070. }
  2071. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2072. static (int ArgumentCount, int VariableArgumentCount) PrepareForFunctionTailCall(LuaThread thread, LuaFunction function,
  2073. Instruction instruction, int newBase, bool isMetamethod)
  2074. {
  2075. var stack = thread.Stack;
  2076. var argumentCount = instruction.B - 1;
  2077. if (instruction.B == 0)
  2078. {
  2079. argumentCount = (ushort)(stack.Count - newBase);
  2080. }
  2081. else
  2082. {
  2083. if (isMetamethod)
  2084. {
  2085. argumentCount += 1;
  2086. }
  2087. thread.Stack.SetTop(newBase + argumentCount);
  2088. }
  2089. // In the case of tailcall, the local variables of the caller are immediately discarded, so there is no need to retain them.
  2090. // Therefore, a call can be made without allocating new registers.
  2091. var currentBase = thread.GetCurrentFrame().Base;
  2092. {
  2093. var stackBuffer = stack.GetBuffer();
  2094. if (argumentCount > 0)
  2095. stackBuffer.Slice(newBase, argumentCount).CopyTo(stackBuffer.Slice(currentBase, argumentCount));
  2096. newBase = currentBase;
  2097. }
  2098. var variableArgumentCount = function.GetVariableArgumentCount(argumentCount);
  2099. if (variableArgumentCount <= 0)
  2100. {
  2101. return (argumentCount, 0);
  2102. }
  2103. return PrepareVariableArgument(thread.Stack, newBase, argumentCount, variableArgumentCount);
  2104. }
  2105. static LuaThread GetThreadWithCurrentPc(VirtualMachineExecutionContext context)
  2106. {
  2107. GetThreadWithCurrentPc(context.Thread, context.Pc);
  2108. return context.Thread;
  2109. }
  2110. static void GetThreadWithCurrentPc(LuaThread thread, int pc)
  2111. {
  2112. var frame = thread.GetCurrentFrame();
  2113. thread.PushCallStackFrame(frame with { CallerInstructionIndex = pc, Flags = frame.Flags & (0 ^ CallStackFrameFlags.TailCall) });
  2114. }
  2115. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2116. static CallStackFrame CreateNewFrame(this LuaFunction function, VirtualMachineExecutionContext context, int newBase)
  2117. {
  2118. return new()
  2119. {
  2120. Base = newBase,
  2121. ReturnBase = newBase,
  2122. Function = function,
  2123. VariableArgumentCount = 0,
  2124. CallerInstructionIndex = context.Pc,
  2125. };
  2126. }
  2127. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2128. static CallStackFrame CreateNewFrame(this LuaFunction function, VirtualMachineExecutionContext context, int newBase, int returnBase, int variableArgumentCount)
  2129. {
  2130. return new()
  2131. {
  2132. Base = newBase,
  2133. ReturnBase = returnBase,
  2134. Function = function,
  2135. VariableArgumentCount = variableArgumentCount,
  2136. CallerInstructionIndex = context.Pc,
  2137. };
  2138. }
  2139. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2140. static CallStackFrame CreateNewTailCallFrame(this LuaFunction function, VirtualMachineExecutionContext context, int newBase, int returnBase, int variableArgumentCount)
  2141. {
  2142. return new()
  2143. {
  2144. Base = newBase,
  2145. ReturnBase = returnBase,
  2146. Function = function,
  2147. VariableArgumentCount = variableArgumentCount,
  2148. CallerInstructionIndex = context.Pc,
  2149. Flags = CallStackFrameFlags.TailCall
  2150. };
  2151. }
  2152. }