| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100 |
- using System.Buffers;
- using System.Runtime.CompilerServices;
- using Lua.Internal;
- namespace Lua.Runtime;
- public static partial class LuaVirtualMachine
- {
- internal async static ValueTask<int> ExecuteClosureAsync(LuaState state, Closure closure, CallStackFrame frame, Memory<LuaValue> buffer, CancellationToken cancellationToken)
- {
- var thread = state.CurrentThread;
- var stack = thread.Stack;
- var chunk = closure.Proto;
- var rootChunk = chunk.GetRoot();
- var resultBuffer = ArrayPool<LuaValue>.Shared.Rent(1024);
- try
- {
- for (var pc = 0; pc < chunk.Instructions.Length; pc++)
- {
- var instruction = chunk.Instructions[pc];
- var RA = instruction.A + frame.Base;
- var RB = instruction.B + frame.Base;
- switch (instruction.OpCode)
- {
- case OpCode.Move:
- stack.EnsureCapacity(RA + 1);
- stack.UnsafeGet(RA) = stack.UnsafeGet(RB);
- stack.NotifyTop(RA + 1);
- break;
- case OpCode.LoadK:
- stack.EnsureCapacity(RA + 1);
- stack.UnsafeGet(RA) = chunk.Constants[instruction.Bx];
- stack.NotifyTop(RA + 1);
- break;
- case OpCode.LoadKX:
- throw new NotImplementedException();
- case OpCode.LoadBool:
- stack.EnsureCapacity(RA + 1);
- stack.UnsafeGet(RA) = instruction.B != 0;
- stack.NotifyTop(RA + 1);
- if (instruction.C != 0) pc++;
- break;
- case OpCode.LoadNil:
- stack.EnsureCapacity(RA + instruction.B + 1);
- stack.GetBuffer().Slice(RA, instruction.B + 1).Clear();
- stack.NotifyTop(RA + instruction.B + 1);
- break;
- case OpCode.GetUpVal:
- {
- stack.EnsureCapacity(RA + 1);
- var upValue = closure.UpValues[instruction.B];
- stack.UnsafeGet(RA) = upValue.GetValue();
- stack.NotifyTop(RA + 1);
- break;
- }
- case OpCode.GetTabUp:
- {
- stack.EnsureCapacity(RA + 1);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- var upValue = closure.UpValues[instruction.B];
- var table = upValue.GetValue();
- await GetTableValue(state, thread, chunk, rootChunk, pc, table, vc, resultBuffer.AsMemory(), cancellationToken);
- var value = resultBuffer[0];
- stack.UnsafeGet(RA) = value;
- stack.NotifyTop(RA + 1);
- break;
- }
- case OpCode.GetTable:
- {
- stack.EnsureCapacity(RA + 1);
- var table = stack.UnsafeGet(RB);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- await GetTableValue(state, thread, chunk, rootChunk, pc, table, vc, resultBuffer.AsMemory(), cancellationToken);
- var value = resultBuffer[0];
- stack.UnsafeGet(RA) = value;
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.SetTabUp:
- {
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- var upValue = closure.UpValues[instruction.A];
- var table = upValue.GetValue();
- await SetTableValue(state, thread, chunk, rootChunk, pc, table, vb, vc, resultBuffer.AsMemory(), cancellationToken);
- break;
- }
- case OpCode.SetUpVal:
- {
- var upValue = closure.UpValues[instruction.B];
- upValue.SetValue(stack.UnsafeGet(RA));
- break;
- }
- case OpCode.SetTable:
- {
- var table = stack.UnsafeGet(RA);
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- await SetTableValue(state, thread, chunk, rootChunk, pc, table, vb, vc, resultBuffer.AsMemory(), cancellationToken);
- }
- break;
- case OpCode.NewTable:
- stack.EnsureCapacity(RA + 1);
- stack.UnsafeGet(RA) = new LuaTable(instruction.B, instruction.C);
- stack.NotifyTop(RA + 1);
- break;
- case OpCode.Self:
- {
- stack.EnsureCapacity(RA + 2);
- var table = stack.UnsafeGet(RB);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- await GetTableValue(state, thread, chunk, rootChunk, pc, table, vc, resultBuffer.AsMemory(), cancellationToken);
- var value = resultBuffer[0];
- stack.UnsafeGet(RA + 1) = table;
- stack.UnsafeGet(RA) = value;
- stack.NotifyTop(RA + 2);
- }
- break;
- case OpCode.Add:
- {
- stack.EnsureCapacity(RA + 1);
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
- {
- stack.UnsafeGet(RA) = valueB + valueC;
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Add, out var metamethod) || vc.TryGetMetamethod(state, Metamethods.Add, out metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- stack.Push(vc);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = stack.Count - 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- stack.UnsafeGet(RA) = resultBuffer[0];
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "add", vb, vc);
- }
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.Sub:
- {
- stack.EnsureCapacity(RA + 1);
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
- {
- stack.UnsafeGet(RA) = valueB - valueC;
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Sub, out var metamethod) || vc.TryGetMetamethod(state, Metamethods.Sub, out metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- stack.Push(vc);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = stack.Count - 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- stack.UnsafeGet(RA) = resultBuffer[0];
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "sub", vb, vc);
- }
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.Mul:
- {
- stack.EnsureCapacity(RA + 1);
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
- {
- stack.UnsafeGet(RA) = valueB * valueC;
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Mul, out var metamethod) || vc.TryGetMetamethod(state, Metamethods.Mul, out metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- stack.Push(vc);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = stack.Count - 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- stack.UnsafeGet(RA) = resultBuffer[0];
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "mul", vb, vc);
- }
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.Div:
- {
- stack.EnsureCapacity(RA + 1);
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
- {
- stack.UnsafeGet(RA) = valueB / valueC;
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Div, out var metamethod) || vc.TryGetMetamethod(state, Metamethods.Div, out metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- stack.Push(vc);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = stack.Count - 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- stack.UnsafeGet(RA) = resultBuffer[0];
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "div", vb, vc);
- }
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.Mod:
- {
- stack.EnsureCapacity(RA + 1);
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
- {
- var mod = valueB % valueC;
- if ((valueC > 0 && mod < 0) || (valueC < 0 && mod > 0))
- {
- mod += valueC;
- }
- stack.UnsafeGet(RA) = mod;
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Mod, out var metamethod) || vc.TryGetMetamethod(state, Metamethods.Mod, out metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- stack.Push(vc);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = stack.Count - 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- stack.UnsafeGet(RA) = resultBuffer[0];
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "mod", vb, vc);
- }
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.Pow:
- {
- stack.EnsureCapacity(RA + 1);
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
- {
- stack.UnsafeGet(RA) = Math.Pow(valueB, valueC);
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Pow, out var metamethod) || vc.TryGetMetamethod(state, Metamethods.Pow, out metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- stack.Push(vc);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = stack.Count - 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- stack.UnsafeGet(RA) = resultBuffer[0];
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "pow", vb, vc);
- }
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.Unm:
- {
- stack.EnsureCapacity(RA + 1);
- var vb = stack.UnsafeGet(RB);
- if (vb.TryRead<double>(out var valueB))
- {
- stack.UnsafeGet(RA) = -valueB;
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Unm, out var metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 1,
- FrameBase = stack.Count - 1,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- stack.UnsafeGet(RA) = resultBuffer[0];
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "unm", vb);
- }
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.Not:
- {
- stack.EnsureCapacity(RA + 1);
- stack.UnsafeGet(RA) = !stack.UnsafeGet(RB).ToBoolean();
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.Len:
- {
- stack.EnsureCapacity(RA + 1);
- var vb = stack.UnsafeGet(RB);
- if (vb.TryRead<string>(out var str))
- {
- stack.UnsafeGet(RA) = str.Length;
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Len, out var metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 1,
- FrameBase = stack.Count - 1,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- stack.UnsafeGet(RA) = resultBuffer[0];
- }
- else if (vb.TryRead<LuaTable>(out var table))
- {
- stack.UnsafeGet(RA) = table.ArrayLength;
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "get length of", vb);
- }
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.Concat:
- {
- stack.EnsureCapacity(RA + 1);
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- var bIsValid = vb.TryRead<string>(out var strB);
- var cIsValid = vc.TryRead<string>(out var strC);
- if (!bIsValid && vb.TryRead<double>(out var numB))
- {
- strB = numB.ToString();
- bIsValid = true;
- }
- if (!cIsValid && vc.TryRead<double>(out var numC))
- {
- strC = numC.ToString();
- cIsValid = true;
- }
- if (bIsValid && cIsValid)
- {
- stack.UnsafeGet(RA) = strB + strC;
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Concat, out var metamethod) || vc.TryGetMetamethod(state, Metamethods.Concat, out metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- stack.Push(vc);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = stack.Count - 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- stack.UnsafeGet(RA) = resultBuffer[0];
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "concat", vb, vc);
- }
- stack.NotifyTop(RA + 1);
- }
- break;
- case OpCode.Jmp:
- pc += instruction.SBx;
- if (instruction.A != 0)
- {
- state.CloseUpValues(thread, instruction.A - 1);
- }
- break;
- case OpCode.Eq:
- {
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- var compareResult = vb == vc;
- if (!compareResult && (vb.TryGetMetamethod(state, Metamethods.Eq, out var metamethod) || vc.TryGetMetamethod(state, Metamethods.Eq, out metamethod)))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- stack.Push(vc);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = stack.Count - 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- compareResult = resultBuffer[0].ToBoolean();
- }
- if (compareResult != (instruction.A == 1))
- {
- pc++;
- }
- }
- break;
- case OpCode.Lt:
- {
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- var compareResult = false;
- if (vb.TryRead<string>(out var strB) && vc.TryRead<string>(out var strC))
- {
- compareResult = StringComparer.Ordinal.Compare(strB, strC) < 0;
- }
- else if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
- {
- compareResult = valueB < valueC;
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Lt, out var metamethod) || vc.TryGetMetamethod(state, Metamethods.Lt, out metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- stack.Push(vc);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = stack.Count - 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- compareResult = resultBuffer[0].ToBoolean();
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "less than", vb, vc);
- }
- if (compareResult != (instruction.A == 1))
- {
- pc++;
- }
- }
- break;
- case OpCode.Le:
- {
- var vb = RK(stack, chunk, instruction.B, frame.Base);
- var vc = RK(stack, chunk, instruction.C, frame.Base);
- var compareResult = false;
- if (vb.TryRead<string>(out var strB) && vc.TryRead<string>(out var strC))
- {
- compareResult = StringComparer.Ordinal.Compare(strB, strC) <= 0;
- }
- else if (vb.TryRead<double>(out var valueB) && vc.TryRead<double>(out var valueC))
- {
- compareResult = valueB <= valueC;
- }
- else if (vb.TryGetMetamethod(state, Metamethods.Le, out var metamethod) || vc.TryGetMetamethod(state, Metamethods.Le, out metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(vb);
- stack.Push(vc);
- await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = stack.Count - 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- compareResult = resultBuffer[0].ToBoolean();
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "less than or equals", vb, vc);
- }
- if (compareResult != (instruction.A == 1))
- {
- pc++;
- }
- }
- break;
- case OpCode.Test:
- {
- if (stack.UnsafeGet(RA).ToBoolean() != (instruction.C == 1))
- {
- pc++;
- }
- }
- break;
- case OpCode.TestSet:
- {
- if (stack.UnsafeGet(RB).ToBoolean() != (instruction.C == 1))
- {
- pc++;
- }
- else
- {
- stack.UnsafeGet(RA) = stack.UnsafeGet(RB);
- stack.NotifyTop(RA + 1);
- }
- }
- break;
- case OpCode.Call:
- {
- var va = stack.UnsafeGet(RA);
- if (!va.TryRead<LuaFunction>(out var func))
- {
- if (va.TryGetMetamethod(state, Metamethods.Call, out var metamethod) && metamethod.TryRead<LuaFunction>(out func))
- {
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- }
- (var newBase, var argumentCount) = PrepareForFunctionCall(thread, func, instruction, RA, resultBuffer.AsSpan(), false);
- var rawResultCount = await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = argumentCount,
- FrameBase = newBase,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- var resultCount = rawResultCount;
- if (instruction.C != 0)
- {
- resultCount = instruction.C - 1;
- }
- if (resultCount == 0)
- {
- stack.Pop();
- }
- else
- {
- stack.EnsureCapacity(RA + resultCount);
- for (int i = 0; i < resultCount; i++)
- {
- stack.UnsafeGet(RA + i) = i >= rawResultCount
- ? LuaValue.Nil
- : resultBuffer[i];
- }
- stack.NotifyTop(RA + resultCount);
- }
- }
- break;
- case OpCode.TailCall:
- {
- state.CloseUpValues(thread, frame.Base);
- var va = stack.UnsafeGet(RA);
- if (!va.TryRead<LuaFunction>(out var func))
- {
- if (!va.TryGetMetamethod(state, Metamethods.Call, out var metamethod) && !metamethod.TryRead<LuaFunction>(out func))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- }
- (var newBase, var argumentCount) = PrepareForFunctionCall(thread, func, instruction, RA, resultBuffer.AsSpan(), true);
- return await func.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = argumentCount,
- FrameBase = newBase,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, buffer, cancellationToken);
- }
- case OpCode.Return:
- {
- state.CloseUpValues(thread, frame.Base);
- var retCount = instruction.B - 1;
- if (retCount == -1)
- {
- retCount = stack.Count - RA;
- }
- for (int i = 0; i < retCount; i++)
- {
- buffer.Span[i] = stack.UnsafeGet(RA + i);
- }
- return retCount;
- }
- case OpCode.ForLoop:
- {
- stack.EnsureCapacity(RA + 4);
- if (!stack.UnsafeGet(RA).TryRead<double>(out var init))
- {
- throw new LuaRuntimeException(state.GetTraceback(), "'for' initial value must be a number");
- }
- if (!stack.UnsafeGet(RA + 1).TryRead<double>(out var limit))
- {
- throw new LuaRuntimeException(state.GetTraceback(), "'for' limit must be a number");
- }
- if (!stack.UnsafeGet(RA + 2).TryRead<double>(out var step))
- {
- throw new LuaRuntimeException(state.GetTraceback(), "'for' step must be a number");
- }
- var va = init + step;
- stack.UnsafeGet(RA) = va;
- if (step >= 0 ? va <= limit : va >= limit)
- {
- pc += instruction.SBx;
- stack.UnsafeGet(RA + 3) = va;
- stack.NotifyTop(RA + 4);
- }
- else
- {
- stack.NotifyTop(RA + 1);
- }
- }
- break;
- case OpCode.ForPrep:
- {
- if (!stack.UnsafeGet(RA).TryRead<double>(out var init))
- {
- throw new LuaRuntimeException(state.GetTraceback(), "'for' initial value must be a number");
- }
- if (!stack.UnsafeGet(RA + 2).TryRead<double>(out var step))
- {
- throw new LuaRuntimeException(state.GetTraceback(), "'for' step must be a number");
- }
- stack.UnsafeGet(RA) = init - step;
- stack.NotifyTop(RA + 1);
- pc += instruction.SBx;
- }
- break;
- case OpCode.TForCall:
- {
- var iteratorRaw = stack.UnsafeGet(RA);
- if (!iteratorRaw.TryRead<LuaFunction>(out var iterator))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", iteratorRaw);
- }
- var nextBase = RA + 3 + instruction.C;
- stack.UnsafeGet(nextBase) = stack.UnsafeGet(RA + 1);
- stack.UnsafeGet(nextBase + 1) = stack.UnsafeGet(RA + 2);
- stack.NotifyTop(nextBase + 2);
- var resultCount = await iterator.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- FrameBase = nextBase,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, resultBuffer.AsMemory(), cancellationToken);
- stack.EnsureCapacity(RA + instruction.C + 3);
- for (int i = 1; i <= instruction.C; i++)
- {
- var index = i - 1;
- stack.UnsafeGet(RA + 2 + i) = index >= resultCount
- ? LuaValue.Nil
- : resultBuffer[i - 1];
- }
- stack.NotifyTop(RA + instruction.C + 3);
- }
- break;
- case OpCode.TForLoop:
- {
- var forState = stack.UnsafeGet(RA + 1);
- if (forState.Type is not LuaValueType.Nil)
- {
- stack.UnsafeGet(RA) = forState;
- pc += instruction.SBx;
- }
- }
- break;
- case OpCode.SetList:
- {
- if (!stack.UnsafeGet(RA).TryRead<LuaTable>(out var table))
- {
- throw new LuaException("internal error");
- }
- var count = instruction.B == 0
- ? stack.Count - (RA + 1)
- : instruction.B;
- table.EnsureArrayCapacity((instruction.C - 1) * 50 + count);
- stack.AsSpan().Slice(RA + 1, count)
- .CopyTo(table.GetArraySpan()[((instruction.C - 1) * 50)..]);
- }
- break;
- case OpCode.Closure:
- stack.EnsureCapacity(RA + 1);
- stack.UnsafeGet(RA) = new Closure(state, chunk.Functions[instruction.SBx]);
- stack.NotifyTop(RA + 1);
- break;
- case OpCode.VarArg:
- {
- var count = instruction.B == 0
- ? frame.VariableArgumentCount
- : instruction.B - 1;
- stack.EnsureCapacity(RA + count);
- for (int i = 0; i < count; i++)
- {
- stack.UnsafeGet(RA + i) = frame.VariableArgumentCount > i
- ? stack.UnsafeGet(frame.Base - (frame.VariableArgumentCount - i))
- : LuaValue.Nil;
- }
- stack.NotifyTop(RA + count);
- }
- break;
- case OpCode.ExtraArg:
- throw new NotImplementedException();
- default:
- break;
- }
- }
- }
- catch (Exception)
- {
- state.CloseUpValues(thread, frame.Base);
- throw;
- }
- finally
- {
- ArrayPool<LuaValue>.Shared.Return(resultBuffer);
- }
- return 0;
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static ref LuaValue RK(LuaStack stack, Chunk chunk, ushort index, int frameBase)
- {
- if (index >= 256)
- {
- return ref MemoryMarshalEx.UnsafeElementAt(chunk.Constants, index - 256);
- }
- else
- {
- return ref stack.UnsafeGet(index + frameBase);
- }
- }
- static ValueTask<int> GetTableValue(LuaState state, LuaThread thread, Chunk chunk, Chunk rootChunk, int pc, LuaValue table, LuaValue key, Memory<LuaValue> buffer, CancellationToken cancellationToken)
- {
- var stack = thread.Stack;
- var isTable = table.TryRead<LuaTable>(out var t);
- if (isTable && t.TryGetValue(key, out var result))
- {
- buffer.Span[0] = result;
- return new(1);
- }
- else if (table.TryGetMetamethod(state, Metamethods.Index, out var metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var indexTable))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(table);
- stack.Push(key);
- return indexTable.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 2,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- FrameBase = stack.Count - 2,
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, buffer, cancellationToken);
- }
- else if (isTable)
- {
- buffer.Span[0] = LuaValue.Nil;
- return new(1);
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "index", table);
- return default; // dummy
- }
- }
- 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)
- {
- var stack = thread.Stack;
- var isTable = table.TryRead<LuaTable>(out var t);
- if (key.Type is LuaValueType.Number)
- {
- var d = key.UnsafeRead<double>();
- if (double.IsNaN(d))
- {
- throw new LuaRuntimeException(GetTracebacks(state, chunk, pc), "table index is NaN");
- }
- }
- if (isTable)
- {
- t[key] = value;
- return new(1);
- }
- else if (table.TryGetMetamethod(state, Metamethods.NewIndex, out var metamethod))
- {
- if (!metamethod.TryRead<LuaFunction>(out var indexTable))
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "call", metamethod);
- }
- stack.Push(table);
- stack.Push(key);
- stack.Push(value);
- return indexTable.InvokeAsync(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = 3,
- FrameBase = stack.Count - 3,
- SourcePosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = rootChunk.Name,
- }, buffer, cancellationToken);
- }
- else
- {
- LuaRuntimeException.AttemptInvalidOperation(GetTracebacks(state, chunk, pc), "index", table);
- return default; // dummy
- }
- }
- static (int FrameBase, int ArgumentCount) PrepareForFunctionCall(LuaThread thread, LuaFunction function, Instruction instruction, int RA, Span<LuaValue> buffer, bool isTailCall)
- {
- var stack = thread.Stack;
- var argumentCount = instruction.B - 1;
- if (instruction.B == 0)
- {
- argumentCount = (ushort)(stack.Count - (RA + 1));
- }
- var newBase = RA + 1;
- // In the case of tailcall, the local variables of the caller are immediately discarded, so there is no need to retain them.
- // Therefore, a call can be made without allocating new registers.
- if (isTailCall)
- {
- var currentBase = thread.GetCurrentFrame().Base;
- var stackBuffer = stack.GetBuffer();
- stackBuffer.Slice(newBase, argumentCount).CopyTo(stackBuffer.Slice(currentBase, argumentCount));
- newBase = currentBase;
- }
- var variableArgumentCount = function.GetVariableArgumentCount(argumentCount);
- // 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.
- // see: https://wubingzheng.github.io/build-lua-in-rust/en/ch08-02.arguments.html
- if (variableArgumentCount > 0)
- {
- var temp = newBase;
- newBase += variableArgumentCount;
- stack.EnsureCapacity(newBase + argumentCount);
- stack.NotifyTop(newBase + argumentCount);
- var stackBuffer = stack.GetBuffer();
- stackBuffer.Slice(temp, argumentCount).CopyTo(buffer);
- buffer.Slice(0, argumentCount).CopyTo(stackBuffer[newBase..]);
- buffer.Slice(argumentCount - variableArgumentCount, variableArgumentCount).CopyTo(stackBuffer[temp..]);
- }
- return (newBase, argumentCount);
- }
- static Traceback GetTracebacks(LuaState state, Chunk chunk, int pc)
- {
- var frame = state.CurrentThread.GetCurrentFrame();
- state.CurrentThread.PushCallStackFrame(frame with
- {
- CallPosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc),
- ChunkName = chunk.Name,
- RootChunkName = chunk.GetRoot().Name,
- });
- var tracebacks = state.GetTraceback();
- state.CurrentThread.PopCallStackFrame();
- return tracebacks;
- }
- }
|