LuaVirtualMachine.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. using System.Buffers;
  2. using System.Runtime.CompilerServices;
  3. using Lua.Internal;
  4. namespace Lua.Runtime;
  5. public static partial class LuaVirtualMachine
  6. {
  7. internal async static ValueTask<int> ExecuteClosureAsync(LuaState state, Closure closure, CallStackFrame frame, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  8. {
  9. var stack = state.Stack;
  10. var chunk = closure.Proto;
  11. for (var pc = 0; pc < chunk.Instructions.Length; pc++)
  12. {
  13. var instruction = chunk.Instructions[pc];
  14. var RA = instruction.A + frame.Base;
  15. var RB = instruction.B + frame.Base;
  16. switch (instruction.OpCode)
  17. {
  18. case OpCode.Move:
  19. stack.EnsureCapacity(RA + 1);
  20. stack.UnsafeGet(RA) = stack.UnsafeGet(RB);
  21. stack.NotifyTop(RA + 1);
  22. break;
  23. case OpCode.LoadK:
  24. stack.EnsureCapacity(RA + 1);
  25. stack.UnsafeGet(RA) = chunk.Constants[instruction.Bx];
  26. stack.NotifyTop(RA + 1);
  27. break;
  28. case OpCode.LoadKX:
  29. throw new NotImplementedException();
  30. case OpCode.LoadBool:
  31. stack.EnsureCapacity(RA + 1);
  32. stack.UnsafeGet(RA) = instruction.B != 0;
  33. stack.NotifyTop(RA + 1);
  34. if (instruction.C != 0) pc++;
  35. break;
  36. case OpCode.LoadNil:
  37. stack.EnsureCapacity(RA + instruction.B + 1);
  38. stack.GetBuffer().Slice(RA, instruction.B + 1).Clear();
  39. stack.NotifyTop(RA + instruction.B + 1);
  40. break;
  41. case OpCode.GetUpVal:
  42. {
  43. stack.EnsureCapacity(RA + 1);
  44. var upValue = closure.UpValues[instruction.B];
  45. stack.UnsafeGet(RA) = upValue.GetValue();
  46. stack.NotifyTop(RA + 1);
  47. break;
  48. }
  49. case OpCode.GetTabUp:
  50. {
  51. stack.EnsureCapacity(RA + 1);
  52. var vc = RK(stack, chunk, instruction.C, frame.Base);
  53. var upValue = closure.UpValues[instruction.B];
  54. var table = upValue.GetValue();
  55. var value = await GetTableValue(state, chunk, pc, table, vc, cancellationToken);
  56. stack.UnsafeGet(RA) = value;
  57. stack.NotifyTop(RA + 1);
  58. break;
  59. }
  60. case OpCode.GetTable:
  61. {
  62. stack.EnsureCapacity(RA + 1);
  63. var table = stack.UnsafeGet(RB);
  64. var vc = RK(stack, chunk, instruction.C, frame.Base);
  65. var value = await GetTableValue(state, chunk, pc, table, vc, cancellationToken);
  66. stack.UnsafeGet(RA) = value;
  67. stack.NotifyTop(RA + 1);
  68. }
  69. break;
  70. case OpCode.SetTabUp:
  71. {
  72. var vb = RK(stack, chunk, instruction.B, frame.Base);
  73. var vc = RK(stack, chunk, instruction.C, frame.Base);
  74. var upValue = closure.UpValues[instruction.A];
  75. var table = upValue.GetValue();
  76. await SetTableValue(state, chunk, pc, table, vb, vc, cancellationToken);
  77. break;
  78. }
  79. case OpCode.SetUpVal:
  80. {
  81. var upValue = closure.UpValues[instruction.B];
  82. upValue.SetValue(stack.UnsafeGet(RA));
  83. break;
  84. }
  85. case OpCode.SetTable:
  86. {
  87. var table = stack.UnsafeGet(RA);
  88. var vb = RK(stack, chunk, instruction.B, frame.Base);
  89. var vc = RK(stack, chunk, instruction.C, frame.Base);
  90. await SetTableValue(state, chunk, pc, table, vb, vc, cancellationToken);
  91. }
  92. break;
  93. case OpCode.NewTable:
  94. stack.EnsureCapacity(RA + 1);
  95. stack.UnsafeGet(RA) = new LuaTable(instruction.B, instruction.C);
  96. stack.NotifyTop(RA + 1);
  97. break;
  98. case OpCode.Self:
  99. {
  100. stack.EnsureCapacity(RA + 2);
  101. var table = stack.UnsafeGet(RB).Read<LuaTable>();
  102. var vc = RK(stack, chunk, instruction.C, frame.Base);
  103. stack.UnsafeGet(RA + 1) = table;
  104. stack.UnsafeGet(RA) = table[vc];
  105. stack.NotifyTop(RA + 2);
  106. }
  107. break;
  108. case OpCode.Add:
  109. {
  110. stack.EnsureCapacity(RA + 1);
  111. var vb = RK(stack, chunk, instruction.B, frame.Base);
  112. var vc = RK(stack, chunk, instruction.C, frame.Base);
  113. if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
  114. {
  115. stack.UnsafeGet(RA) = valueB + valueC;
  116. }
  117. else if (vb.TryGetMetamethod(Metamethods.Add, out var metamethod) || vc.TryGetMetamethod(Metamethods.Add, out metamethod))
  118. {
  119. if (!metamethod.TryRead<LuaFunction>(out var func))
  120. {
  121. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  122. }
  123. stack.Push(vb);
  124. stack.Push(vc);
  125. using var methodBuffer = new PooledArray<LuaValue>(1024);
  126. await func.InvokeAsync(new()
  127. {
  128. State = state,
  129. ArgumentCount = 2,
  130. SourcePosition = chunk.SourcePositions[pc],
  131. }, methodBuffer.AsMemory(), cancellationToken);
  132. stack.UnsafeGet(RA) = methodBuffer[0];
  133. }
  134. else
  135. {
  136. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "add", vb, vc);
  137. }
  138. stack.NotifyTop(RA + 1);
  139. }
  140. break;
  141. case OpCode.Sub:
  142. {
  143. stack.EnsureCapacity(RA + 1);
  144. var vb = RK(stack, chunk, instruction.B, frame.Base);
  145. var vc = RK(stack, chunk, instruction.C, frame.Base);
  146. if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
  147. {
  148. stack.UnsafeGet(RA) = valueB - valueC;
  149. }
  150. else if (vb.TryGetMetamethod(Metamethods.Sub, out var metamethod) || vc.TryGetMetamethod(Metamethods.Sub, out metamethod))
  151. {
  152. if (!metamethod.TryRead<LuaFunction>(out var func))
  153. {
  154. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  155. }
  156. stack.Push(vb);
  157. stack.Push(vc);
  158. using var methodBuffer = new PooledArray<LuaValue>(1024);
  159. await func.InvokeAsync(new()
  160. {
  161. State = state,
  162. ArgumentCount = 2,
  163. SourcePosition = chunk.SourcePositions[pc],
  164. }, methodBuffer.AsMemory(), cancellationToken);
  165. stack.UnsafeGet(RA) = methodBuffer[0];
  166. }
  167. else
  168. {
  169. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "sub", vb, vc);
  170. }
  171. stack.NotifyTop(RA + 1);
  172. }
  173. break;
  174. case OpCode.Mul:
  175. {
  176. stack.EnsureCapacity(RA + 1);
  177. var vb = RK(stack, chunk, instruction.B, frame.Base);
  178. var vc = RK(stack, chunk, instruction.C, frame.Base);
  179. if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
  180. {
  181. stack.UnsafeGet(RA) = valueB * valueC;
  182. }
  183. else if (vb.TryGetMetamethod(Metamethods.Mul, out var metamethod) || vc.TryGetMetamethod(Metamethods.Mul, out metamethod))
  184. {
  185. if (!metamethod.TryRead<LuaFunction>(out var func))
  186. {
  187. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  188. }
  189. stack.Push(vb);
  190. stack.Push(vc);
  191. using var methodBuffer = new PooledArray<LuaValue>(1024);
  192. await func.InvokeAsync(new()
  193. {
  194. State = state,
  195. ArgumentCount = 2,
  196. SourcePosition = chunk.SourcePositions[pc],
  197. }, methodBuffer.AsMemory(), cancellationToken);
  198. stack.UnsafeGet(RA) = methodBuffer[0];
  199. }
  200. else
  201. {
  202. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "mul", vb, vc);
  203. }
  204. stack.NotifyTop(RA + 1);
  205. }
  206. break;
  207. case OpCode.Div:
  208. {
  209. stack.EnsureCapacity(RA + 1);
  210. var vb = RK(stack, chunk, instruction.B, frame.Base);
  211. var vc = RK(stack, chunk, instruction.C, frame.Base);
  212. if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
  213. {
  214. stack.UnsafeGet(RA) = valueB / valueC;
  215. }
  216. else if (vb.TryGetMetamethod(Metamethods.Div, out var metamethod) || vc.TryGetMetamethod(Metamethods.Div, out metamethod))
  217. {
  218. if (!metamethod.TryRead<LuaFunction>(out var func))
  219. {
  220. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  221. }
  222. stack.Push(vb);
  223. stack.Push(vc);
  224. using var methodBuffer = new PooledArray<LuaValue>(1024);
  225. await func.InvokeAsync(new()
  226. {
  227. State = state,
  228. ArgumentCount = 2,
  229. SourcePosition = chunk.SourcePositions[pc],
  230. }, methodBuffer.AsMemory(), cancellationToken);
  231. stack.UnsafeGet(RA) = methodBuffer[0];
  232. }
  233. else
  234. {
  235. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "div", vb, vc);
  236. }
  237. stack.NotifyTop(RA + 1);
  238. }
  239. break;
  240. case OpCode.Mod:
  241. {
  242. stack.EnsureCapacity(RA + 1);
  243. var vb = RK(stack, chunk, instruction.B, frame.Base);
  244. var vc = RK(stack, chunk, instruction.C, frame.Base);
  245. if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
  246. {
  247. stack.UnsafeGet(RA) = valueB % valueC;
  248. }
  249. else if (vb.TryGetMetamethod(Metamethods.Mod, out var metamethod) || vc.TryGetMetamethod(Metamethods.Mod, out metamethod))
  250. {
  251. if (!metamethod.TryRead<LuaFunction>(out var func))
  252. {
  253. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  254. }
  255. stack.Push(vb);
  256. stack.Push(vc);
  257. using var methodBuffer = new PooledArray<LuaValue>(1024);
  258. await func.InvokeAsync(new()
  259. {
  260. State = state,
  261. ArgumentCount = 2,
  262. SourcePosition = chunk.SourcePositions[pc],
  263. }, methodBuffer.AsMemory(), cancellationToken);
  264. stack.UnsafeGet(RA) = methodBuffer[0];
  265. }
  266. else
  267. {
  268. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "mod", vb, vc);
  269. }
  270. stack.NotifyTop(RA + 1);
  271. }
  272. break;
  273. case OpCode.Pow:
  274. {
  275. stack.EnsureCapacity(RA + 1);
  276. var vb = RK(stack, chunk, instruction.B, frame.Base);
  277. var vc = RK(stack, chunk, instruction.C, frame.Base);
  278. if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
  279. {
  280. stack.UnsafeGet(RA) = Math.Pow(valueB, valueC);
  281. }
  282. else if (vb.TryGetMetamethod(Metamethods.Pow, out var metamethod) || vc.TryGetMetamethod(Metamethods.Pow, out metamethod))
  283. {
  284. if (!metamethod.TryRead<LuaFunction>(out var func))
  285. {
  286. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  287. }
  288. stack.Push(vb);
  289. stack.Push(vc);
  290. using var methodBuffer = new PooledArray<LuaValue>(1024);
  291. await func.InvokeAsync(new()
  292. {
  293. State = state,
  294. ArgumentCount = 2,
  295. SourcePosition = chunk.SourcePositions[pc],
  296. }, methodBuffer.AsMemory(), cancellationToken);
  297. stack.UnsafeGet(RA) = methodBuffer[0];
  298. }
  299. else
  300. {
  301. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "pow", vb, vc);
  302. }
  303. stack.NotifyTop(RA + 1);
  304. }
  305. break;
  306. case OpCode.Unm:
  307. {
  308. stack.EnsureCapacity(RA + 1);
  309. var vb = stack.UnsafeGet(RB);
  310. if (vb.TryRead<double>(out var valueB))
  311. {
  312. stack.UnsafeGet(RA) = -valueB;
  313. }
  314. else if (vb.TryGetMetamethod(Metamethods.Unm, out var metamethod))
  315. {
  316. if (!metamethod.TryRead<LuaFunction>(out var func))
  317. {
  318. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  319. }
  320. stack.Push(vb);
  321. using var methodBuffer = new PooledArray<LuaValue>(1024);
  322. await func.InvokeAsync(new()
  323. {
  324. State = state,
  325. ArgumentCount = 1,
  326. SourcePosition = chunk.SourcePositions[pc],
  327. }, methodBuffer.AsMemory(), cancellationToken);
  328. stack.UnsafeGet(RA) = methodBuffer[0];
  329. }
  330. else
  331. {
  332. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "unm", vb);
  333. }
  334. stack.NotifyTop(RA + 1);
  335. }
  336. break;
  337. case OpCode.Not:
  338. {
  339. stack.EnsureCapacity(RA + 1);
  340. var rb = stack.UnsafeGet(RB);
  341. if (rb.TryRead<bool>(out var valueB))
  342. {
  343. stack.UnsafeGet(RA) = !valueB;
  344. }
  345. else
  346. {
  347. stack.UnsafeGet(RA) = false;
  348. }
  349. stack.NotifyTop(RA + 1);
  350. }
  351. break;
  352. case OpCode.Len:
  353. {
  354. stack.EnsureCapacity(RA + 1);
  355. var vb = stack.UnsafeGet(RB);
  356. if (vb.TryRead<string>(out var str))
  357. {
  358. stack.UnsafeGet(RA) = str.Length;
  359. }
  360. else if (vb.TryGetMetamethod(Metamethods.Len, out var metamethod))
  361. {
  362. if (!metamethod.TryRead<LuaFunction>(out var func))
  363. {
  364. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  365. }
  366. stack.Push(vb);
  367. using var methodBuffer = new PooledArray<LuaValue>(1024);
  368. await func.InvokeAsync(new()
  369. {
  370. State = state,
  371. ArgumentCount = 1,
  372. SourcePosition = chunk.SourcePositions[pc],
  373. }, methodBuffer.AsMemory(), cancellationToken);
  374. stack.UnsafeGet(RA) = methodBuffer[0];
  375. }
  376. else if (vb.TryRead<LuaTable>(out var table))
  377. {
  378. stack.UnsafeGet(RA) = table.ArrayLength;
  379. }
  380. else
  381. {
  382. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "get length of", vb);
  383. }
  384. stack.NotifyTop(RA + 1);
  385. }
  386. break;
  387. case OpCode.Concat:
  388. {
  389. stack.EnsureCapacity(RA + 1);
  390. var vb = RK(stack, chunk, instruction.B, frame.Base);
  391. var vc = RK(stack, chunk, instruction.C, frame.Base);
  392. var bIsValid = vb.TryRead<string>(out var strB);
  393. var cIsValid = vc.TryRead<string>(out var strC);
  394. if (!bIsValid && vb.TryRead<double>(out var numB))
  395. {
  396. strB = numB.ToString();
  397. bIsValid = true;
  398. }
  399. if (!cIsValid && vc.TryRead<double>(out var numC))
  400. {
  401. strC = numC.ToString();
  402. cIsValid = true;
  403. }
  404. if (bIsValid && cIsValid)
  405. {
  406. stack.UnsafeGet(RA) = strB + strC;
  407. }
  408. else if (vb.TryGetMetamethod(Metamethods.Concat, out var metamethod) || vc.TryGetMetamethod(Metamethods.Concat, out metamethod))
  409. {
  410. if (!metamethod.TryRead<LuaFunction>(out var func))
  411. {
  412. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  413. }
  414. stack.Push(vb);
  415. stack.Push(vc);
  416. using var methodBuffer = new PooledArray<LuaValue>(1024);
  417. await func.InvokeAsync(new()
  418. {
  419. State = state,
  420. ArgumentCount = 2,
  421. SourcePosition = chunk.SourcePositions[pc],
  422. }, methodBuffer.AsMemory(), cancellationToken);
  423. stack.UnsafeGet(RA) = methodBuffer[0];
  424. }
  425. else
  426. {
  427. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "concat", vb, vc);
  428. }
  429. stack.NotifyTop(RA + 1);
  430. }
  431. break;
  432. case OpCode.Jmp:
  433. pc += instruction.SBx;
  434. if (instruction.A != 0)
  435. {
  436. state.CloseUpValues(instruction.A);
  437. }
  438. break;
  439. case OpCode.Eq:
  440. {
  441. var vb = RK(stack, chunk, instruction.B, frame.Base);
  442. var vc = RK(stack, chunk, instruction.C, frame.Base);
  443. var compareResult = vb == vc;
  444. if (!compareResult && (vb.TryGetMetamethod(Metamethods.Eq, out var metamethod) || vc.TryGetMetamethod(Metamethods.Eq, out metamethod)))
  445. {
  446. if (!metamethod.TryRead<LuaFunction>(out var func))
  447. {
  448. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  449. }
  450. stack.Push(vb);
  451. stack.Push(vc);
  452. var methodBuffer = ArrayPool<LuaValue>.Shared.Rent(1);
  453. methodBuffer.AsSpan().Clear();
  454. try
  455. {
  456. await func.InvokeAsync(new()
  457. {
  458. State = state,
  459. ArgumentCount = 2,
  460. SourcePosition = chunk.SourcePositions[pc],
  461. }, methodBuffer, cancellationToken);
  462. compareResult = methodBuffer[0].ToBoolean();
  463. }
  464. finally
  465. {
  466. ArrayPool<LuaValue>.Shared.Return(methodBuffer);
  467. }
  468. }
  469. if (compareResult != (instruction.A == 1))
  470. {
  471. pc++;
  472. }
  473. }
  474. break;
  475. case OpCode.Lt:
  476. {
  477. var vb = RK(stack, chunk, instruction.B, frame.Base);
  478. var vc = RK(stack, chunk, instruction.C, frame.Base);
  479. var compareResult = false;
  480. if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
  481. {
  482. compareResult = valueB < valueC;
  483. }
  484. else if (vb.TryGetMetamethod(Metamethods.Lt, out var metamethod) || vc.TryGetMetamethod(Metamethods.Lt, out metamethod))
  485. {
  486. if (!metamethod.TryRead<LuaFunction>(out var func))
  487. {
  488. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  489. }
  490. stack.Push(vb);
  491. stack.Push(vc);
  492. var methodBuffer = ArrayPool<LuaValue>.Shared.Rent(1);
  493. methodBuffer.AsSpan().Clear();
  494. try
  495. {
  496. await func.InvokeAsync(new()
  497. {
  498. State = state,
  499. ArgumentCount = 2,
  500. SourcePosition = chunk.SourcePositions[pc],
  501. }, methodBuffer, cancellationToken);
  502. compareResult = methodBuffer[0].ToBoolean();
  503. }
  504. finally
  505. {
  506. ArrayPool<LuaValue>.Shared.Return(methodBuffer);
  507. }
  508. }
  509. else
  510. {
  511. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "less than", vb, vc);
  512. }
  513. if (compareResult != (instruction.A == 1))
  514. {
  515. pc++;
  516. }
  517. }
  518. break;
  519. case OpCode.Le:
  520. {
  521. var vb = RK(stack, chunk, instruction.B, frame.Base);
  522. var vc = RK(stack, chunk, instruction.C, frame.Base);
  523. var compareResult = false;
  524. if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
  525. {
  526. compareResult = valueB <= valueC;
  527. }
  528. else if (vb.TryGetMetamethod(Metamethods.Le, out var metamethod) || vc.TryGetMetamethod(Metamethods.Le, out metamethod))
  529. {
  530. if (!metamethod.TryRead<LuaFunction>(out var func))
  531. {
  532. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  533. }
  534. stack.Push(vb);
  535. stack.Push(vc);
  536. var methodBuffer = ArrayPool<LuaValue>.Shared.Rent(1);
  537. methodBuffer.AsSpan().Clear();
  538. try
  539. {
  540. await func.InvokeAsync(new()
  541. {
  542. State = state,
  543. ArgumentCount = 2,
  544. SourcePosition = chunk.SourcePositions[pc],
  545. }, methodBuffer, cancellationToken);
  546. compareResult = methodBuffer[0].ToBoolean();
  547. }
  548. finally
  549. {
  550. ArrayPool<LuaValue>.Shared.Return(methodBuffer);
  551. }
  552. }
  553. else
  554. {
  555. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "less than or equals", vb, vc);
  556. }
  557. if (compareResult != (instruction.A == 1))
  558. {
  559. pc++;
  560. }
  561. }
  562. break;
  563. case OpCode.Test:
  564. {
  565. if (stack.UnsafeGet(RA).ToBoolean() != (instruction.C == 1))
  566. {
  567. pc++;
  568. }
  569. }
  570. break;
  571. case OpCode.TestSet:
  572. {
  573. if (stack.UnsafeGet(RB).ToBoolean() != (instruction.C == 1))
  574. {
  575. pc++;
  576. }
  577. else
  578. {
  579. stack.UnsafeGet(RA) = stack.UnsafeGet(RB);
  580. stack.NotifyTop(RA + 1);
  581. }
  582. }
  583. break;
  584. case OpCode.Call:
  585. {
  586. var va = stack.UnsafeGet(RA);
  587. if (!va.TryRead<LuaFunction>(out var func))
  588. {
  589. if (va.TryGetMetamethod(Metamethods.Call, out var metamethod) && metamethod.TryRead<LuaFunction>(out func))
  590. {
  591. }
  592. else
  593. {
  594. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  595. }
  596. }
  597. (var newBase, var argumentCount) = PrepareForFunctionCall(state, func, instruction, RA, false);
  598. var resultBuffer = ArrayPool<LuaValue>.Shared.Rent(1024);
  599. resultBuffer.AsSpan().Clear();
  600. try
  601. {
  602. var resultCount = await func.InvokeAsync(new()
  603. {
  604. State = state,
  605. ArgumentCount = argumentCount,
  606. StackPosition = newBase,
  607. SourcePosition = chunk.SourcePositions[pc],
  608. ChunkName = chunk.Name,
  609. RootChunkName = chunk.GetRoot().Name,
  610. }, resultBuffer.AsMemory(), cancellationToken);
  611. if (instruction.C != 0)
  612. {
  613. resultCount = instruction.C - 1;
  614. }
  615. stack.EnsureCapacity(RA + resultCount);
  616. for (int i = 0; i < resultCount; i++)
  617. {
  618. stack.UnsafeGet(RA + i) = resultBuffer[i];
  619. }
  620. stack.NotifyTop(RA + resultCount);
  621. }
  622. finally
  623. {
  624. ArrayPool<LuaValue>.Shared.Return(resultBuffer);
  625. }
  626. }
  627. break;
  628. case OpCode.TailCall:
  629. {
  630. state.CloseUpValues(frame.Base);
  631. var va = stack.UnsafeGet(RA);
  632. if (!va.TryRead<LuaFunction>(out var func))
  633. {
  634. if (!va.TryGetMetamethod(Metamethods.Call, out var metamethod) && !metamethod.TryRead<LuaFunction>(out func))
  635. {
  636. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  637. }
  638. }
  639. (var newBase, var argumentCount) = PrepareForFunctionCall(state, func, instruction, RA, true);
  640. return await func.InvokeAsync(new()
  641. {
  642. State = state,
  643. ArgumentCount = argumentCount,
  644. StackPosition = newBase,
  645. SourcePosition = chunk.SourcePositions[pc],
  646. ChunkName = chunk.Name,
  647. RootChunkName = chunk.GetRoot().Name,
  648. }, buffer, cancellationToken);
  649. }
  650. case OpCode.Return:
  651. {
  652. state.CloseUpValues(frame.Base);
  653. var retCount = instruction.B - 1;
  654. if (retCount == -1)
  655. {
  656. retCount = stack.Count - RA;
  657. }
  658. for (int i = 0; i < retCount; i++)
  659. {
  660. buffer.Span[i] = stack.UnsafeGet(RA + i);
  661. }
  662. return retCount;
  663. }
  664. case OpCode.ForLoop:
  665. {
  666. stack.EnsureCapacity(RA + 4);
  667. // TODO: add error message
  668. var variable = stack.UnsafeGet(RA).Read<double>();
  669. var limit = stack.UnsafeGet(RA + 1).Read<double>();
  670. var step = stack.UnsafeGet(RA + 2).Read<double>();
  671. var va = variable + step;
  672. stack.UnsafeGet(RA) = va;
  673. if (step >= 0 ? va <= limit : va >= limit)
  674. {
  675. pc += instruction.SBx;
  676. stack.UnsafeGet(RA + 3) = va;
  677. stack.NotifyTop(RA + 4);
  678. }
  679. else
  680. {
  681. stack.NotifyTop(RA + 1);
  682. }
  683. }
  684. break;
  685. case OpCode.ForPrep:
  686. {
  687. // TODO: add error message
  688. stack.UnsafeGet(RA) = stack.UnsafeGet(RA).Read<double>() - stack.UnsafeGet(RA + 2).Read<double>();
  689. stack.NotifyTop(RA + 1);
  690. pc += instruction.SBx;
  691. }
  692. break;
  693. case OpCode.TForCall:
  694. {
  695. var iterator = stack.UnsafeGet(RA).Read<LuaFunction>();
  696. var nextBase = RA + 3 + instruction.C;
  697. var resultBuffer = ArrayPool<LuaValue>.Shared.Rent(1024);
  698. resultBuffer.AsSpan().Clear();
  699. try
  700. {
  701. await iterator.InvokeAsync(new()
  702. {
  703. State = state,
  704. ArgumentCount = 2,
  705. StackPosition = nextBase,
  706. SourcePosition = chunk.SourcePositions[pc],
  707. ChunkName = chunk.Name,
  708. RootChunkName = chunk.GetRoot().Name,
  709. }, resultBuffer.AsMemory(), cancellationToken);
  710. stack.EnsureCapacity(RA + instruction.C + 3);
  711. for (int i = 1; i <= instruction.C; i++)
  712. {
  713. stack.UnsafeGet(RA + 2 + i) = resultBuffer[i - 1];
  714. }
  715. stack.NotifyTop(RA + instruction.C + 3);
  716. }
  717. finally
  718. {
  719. ArrayPool<LuaValue>.Shared.Return(resultBuffer);
  720. }
  721. }
  722. break;
  723. case OpCode.TForLoop:
  724. {
  725. var forState = stack.UnsafeGet(RA + 1);
  726. if (forState.Type is not LuaValueType.Nil)
  727. {
  728. stack.UnsafeGet(RA) = forState;
  729. pc += instruction.SBx;
  730. }
  731. }
  732. break;
  733. case OpCode.SetList:
  734. {
  735. var table = stack.UnsafeGet(RA).Read<LuaTable>();
  736. var count = instruction.B == 0
  737. ? stack.Count - (RA + 1)
  738. : instruction.B;
  739. table.EnsureArrayCapacity((instruction.C - 1) * 50 + count);
  740. stack.AsSpan().Slice(RA + 1, count)
  741. .CopyTo(table.GetArraySpan()[((instruction.C - 1) * 50)..]);
  742. }
  743. break;
  744. case OpCode.Closure:
  745. stack.EnsureCapacity(RA + 1);
  746. stack.UnsafeGet(RA) = new Closure(state, chunk.Functions[instruction.SBx]);
  747. stack.NotifyTop(RA + 1);
  748. break;
  749. case OpCode.VarArg:
  750. {
  751. var count = instruction.B == 0
  752. ? frame.VariableArgumentCount
  753. : instruction.B - 1;
  754. stack.EnsureCapacity(RA + count);
  755. for (int i = 0; i < count; i++)
  756. {
  757. stack.UnsafeGet(RA + i) = stack.UnsafeGet(frame.Base - (count - i));
  758. }
  759. stack.NotifyTop(RA + count);
  760. }
  761. break;
  762. case OpCode.ExtraArg:
  763. throw new NotImplementedException();
  764. default:
  765. break;
  766. }
  767. }
  768. return 0;
  769. }
  770. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  771. static LuaValue RK(LuaStack stack, Chunk chunk, ushort index, int frameBase)
  772. {
  773. return index >= 256 ? chunk.Constants[index - 256] : stack.UnsafeGet(index + frameBase);
  774. }
  775. #if NET6_0_OR_GREATER
  776. [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
  777. #endif
  778. static async ValueTask<LuaValue> GetTableValue(LuaState state, Chunk chunk, int pc, LuaValue table, LuaValue key, CancellationToken cancellationToken)
  779. {
  780. var stack = state.Stack;
  781. var isTable = table.TryRead<LuaTable>(out var t);
  782. if (isTable && t.TryGetValue(key, out var result))
  783. {
  784. return result;
  785. }
  786. else if (table.TryGetMetamethod(Metamethods.Index, out var metamethod))
  787. {
  788. if (!metamethod.TryRead<LuaFunction>(out var indexTable))
  789. {
  790. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  791. }
  792. stack.Push(table);
  793. stack.Push(key);
  794. var methodBuffer = ArrayPool<LuaValue>.Shared.Rent(1024);
  795. methodBuffer.AsSpan().Clear();
  796. try
  797. {
  798. await indexTable.InvokeAsync(new()
  799. {
  800. State = state,
  801. ArgumentCount = 2,
  802. SourcePosition = chunk.SourcePositions[pc],
  803. }, methodBuffer, cancellationToken);
  804. return methodBuffer[0];
  805. }
  806. finally
  807. {
  808. ArrayPool<LuaValue>.Shared.Return(methodBuffer);
  809. }
  810. }
  811. else if (isTable)
  812. {
  813. return LuaValue.Nil;
  814. }
  815. else
  816. {
  817. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "index", table);
  818. return default; // dummy
  819. }
  820. }
  821. #if NET6_0_OR_GREATER
  822. [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
  823. #endif
  824. static async ValueTask SetTableValue(LuaState state, Chunk chunk, int pc, LuaValue table, LuaValue key, LuaValue value, CancellationToken cancellationToken)
  825. {
  826. var stack = state.Stack;
  827. var isTable = table.TryRead<LuaTable>(out var t);
  828. if (isTable && t.ContainsKey(key))
  829. {
  830. t[key] = value;
  831. }
  832. else if (table.TryGetMetamethod(Metamethods.NewIndex, out var metamethod))
  833. {
  834. if (!metamethod.TryRead<LuaFunction>(out var indexTable))
  835. {
  836. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
  837. }
  838. stack.Push(table);
  839. stack.Push(key);
  840. stack.Push(value);
  841. var methodBuffer = ArrayPool<LuaValue>.Shared.Rent(1024);
  842. methodBuffer.AsSpan().Clear();
  843. try
  844. {
  845. await indexTable.InvokeAsync(new()
  846. {
  847. State = state,
  848. ArgumentCount = 3,
  849. SourcePosition = chunk.SourcePositions[pc],
  850. }, methodBuffer, cancellationToken);
  851. }
  852. finally
  853. {
  854. ArrayPool<LuaValue>.Shared.Return(methodBuffer);
  855. }
  856. }
  857. else if (isTable)
  858. {
  859. t[key] = value;
  860. }
  861. else
  862. {
  863. LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "index", table);
  864. }
  865. }
  866. static (int FrameBase, int ArgumentCount) PrepareForFunctionCall(LuaState state, LuaFunction function, Instruction instruction, int RA, bool isTailCall)
  867. {
  868. var stack = state.Stack;
  869. var argumentCount = instruction.B - 1;
  870. if (instruction.B == 0)
  871. {
  872. argumentCount = (ushort)(stack.Count - (RA + 1));
  873. }
  874. var newBase = RA + 1;
  875. // In the case of tailcall, the local variables of the caller are immediately discarded, so there is no need to retain them.
  876. // Therefore, a call can be made without allocating new registers.
  877. if (isTailCall)
  878. {
  879. var currentBase = state.GetCurrentFrame().Base;
  880. var stackBuffer = stack.GetBuffer();
  881. stackBuffer.Slice(newBase, argumentCount).CopyTo(stackBuffer.Slice(currentBase, argumentCount));
  882. newBase = currentBase;
  883. }
  884. var variableArgumentCount = function is Closure luaClosure && luaClosure.Proto.HasVariableArgments
  885. ? argumentCount - luaClosure.Proto.ParameterCount
  886. : 0;
  887. // 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.
  888. // see: https://wubingzheng.github.io/build-lua-in-rust/en/ch08-02.arguments.html
  889. if (variableArgumentCount > 0)
  890. {
  891. var temp = newBase;
  892. newBase += variableArgumentCount;
  893. var buffer = ArrayPool<LuaValue>.Shared.Rent(argumentCount);
  894. try
  895. {
  896. stack.EnsureCapacity(newBase + argumentCount);
  897. stack.NotifyTop(newBase + argumentCount);
  898. var stackBuffer = stack.GetBuffer();
  899. stackBuffer.Slice(temp, argumentCount).CopyTo(buffer);
  900. buffer.AsSpan(0, argumentCount).CopyTo(stackBuffer[newBase..]);
  901. buffer.AsSpan(argumentCount - variableArgumentCount, variableArgumentCount).CopyTo(stackBuffer[temp..]);
  902. }
  903. finally
  904. {
  905. ArrayPool<LuaValue>.Shared.Return(buffer);
  906. }
  907. }
  908. return (newBase, argumentCount);
  909. }
  910. static Tracebacks GetTracebacks(LuaState state, Chunk chunk, int pc)
  911. {
  912. var frame = state.GetCurrentFrame();
  913. state.PushCallStackFrame(frame with
  914. {
  915. CallPosition = chunk.SourcePositions[pc],
  916. ChunkName = chunk.Name,
  917. RootChunkName = chunk.GetRoot().Name,
  918. });
  919. var tracebacks = state.GetTracebacks();
  920. state.PopCallStackFrame();
  921. return tracebacks;
  922. }
  923. }