LuaVirtualMachine.cs 51 KB

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