| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122 |
- 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 callPosition = MemoryMarshalEx.UnsafeElementAt(chunk.SourcePositions, pc);
- var chunkName = chunk.Name ?? LuaState.DefaultChunkName;
- var rootChunkName = rootChunk.Name ?? LuaState.DefaultChunkName;
- thread.PushCallStackFrame(new CallStackFrame
- {
- Base = newBase,
- CallPosition = callPosition,
- ChunkName = chunkName,
- RootChunkName = rootChunkName,
- VariableArgumentCount = func is Closure cl ? Math.Max(argumentCount - cl.Proto.ParameterCount, 0) : 0,
- Function = func,
- });
- int rawResultCount;
- try
- {
- rawResultCount = await func.InternalInvokeAsyncCore(new()
- {
- State = state,
- Thread = thread,
- ArgumentCount = argumentCount,
- FrameBase = newBase,
- SourcePosition = callPosition,
- ChunkName = chunkName,
- RootChunkName = rootChunkName,
- }, resultBuffer.AsMemory(), cancellationToken);
- }
- finally
- {
- thread.PopCallStackFrame();
- }
- 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;
- }
- }
|