-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathLuaVirtualMachine.cs
More file actions
3217 lines (2866 loc) · 104 KB
/
Copy pathLuaVirtualMachine.cs
File metadata and controls
3217 lines (2866 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Lua.Internal;
// ReSharper disable MethodHasAsyncOverload
// ReSharper disable InconsistentNaming
namespace Lua.Runtime;
[SuppressMessage("Reliability", "CA2012:Use ValueTasks correctly")]
public static partial class LuaVirtualMachine
{
class VirtualMachineExecutionContext : IPoolNode<VirtualMachineExecutionContext>
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VirtualMachineExecutionContext Get(
LuaState state,
in CallStackFrame frame,
CancellationToken cancellationToken
)
{
if (!pool.TryPop(out var executionContext))
{
executionContext = new();
}
executionContext.Init(state, frame, cancellationToken);
return executionContext;
}
void Init(LuaState state, in CallStackFrame frame, CancellationToken cancellationToken)
{
Stack = state.Stack;
State = state;
LuaClosure = (LuaClosure)frame.Function;
FrameBase = frame.Base;
VariableArgumentCount = frame.VariableArgumentCount;
CurrentReturnFrameBase = frame.ReturnBase;
CancellationToken = cancellationToken;
Pc = -1;
Instruction = default;
PostOperation = PostOperationType.None;
BaseCallStackCount = state.CallStackFrameCount;
LastHookPc = -1;
Task = default;
}
public LuaGlobalState GlobalState => State.GlobalState;
public LuaStack Stack = default!;
public LuaClosure LuaClosure = default!;
public LuaState State = default!;
public Prototype Prototype => LuaClosure.Proto;
public int FrameBase;
public int VariableArgumentCount;
public CancellationToken CancellationToken;
public int Pc;
public Instruction Instruction;
public int CurrentReturnFrameBase;
public ValueTask<int> Task;
public int LastHookPc;
public bool IsTopLevel => BaseCallStackCount == State.CallStackFrameCount;
public int BaseCallStackCount;
public PostOperationType PostOperation;
static LinkedPool<VirtualMachineExecutionContext> pool;
VirtualMachineExecutionContext? nextNode;
ref VirtualMachineExecutionContext? IPoolNode<VirtualMachineExecutionContext>.NextNode =>
ref nextNode;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Pop(Instruction instruction, int frameBase)
{
var count = instruction.B - 1;
var src = instruction.A + frameBase;
if (count == -1)
{
count = Stack.Count - src;
}
return PopFromBuffer(src, count);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public bool PopFromBuffer(int src, int srcCount)
{
var result = Stack.GetBuffer().Slice(src, srcCount);
Re:
var frames = State.GetCallStackFrames();
if (frames.Length == BaseCallStackCount)
{
var returnBase = frames[^1].ReturnBase;
if (src != returnBase)
{
result.CopyTo(Stack.AsSpan()[returnBase..]);
}
Stack.PopUntil(returnBase + srcCount);
return false;
}
ref readonly var frame = ref frames[^1];
Pc = frame.CallerInstructionIndex;
State.LastPc = Pc;
ref readonly var lastFrame = ref frames[^2];
LuaClosure = Unsafe.As<LuaClosure>(lastFrame.Function);
CurrentReturnFrameBase = frame.ReturnBase;
var callInstruction = Prototype.Code[Pc];
if (callInstruction.OpCode == OpCode.TailCall)
{
State.PopCallStackFrame();
goto Re;
}
FrameBase = lastFrame.Base;
VariableArgumentCount = lastFrame.VariableArgumentCount;
var opCode = callInstruction.OpCode;
if (opCode is OpCode.Eq or OpCode.Lt or OpCode.Le)
{
var compareResult = srcCount > 0 && result[0].ToBoolean();
if ((frame.Flags & CallStackFrameFlags.ReversedLe) != 0)
{
compareResult = !compareResult;
}
if (compareResult != (callInstruction.A == 1))
{
Pc++;
}
State.PopCallStackFrameWithStackPop();
return true;
}
var target = callInstruction.A + FrameBase;
var targetCount = result.Length;
switch (opCode)
{
case OpCode.Call:
{
var c = callInstruction.C;
if (c != 0)
{
targetCount = c - 1;
}
break;
}
case OpCode.TForCall:
target += 3;
targetCount = callInstruction.C;
break;
case OpCode.Self:
Stack.Get(target) = result.Length == 0 ? LuaValue.Nil : result[0];
State.PopCallStackFrameWithStackPop(target + 2);
return true;
case OpCode.SetTable or OpCode.SetTabUp:
target = frame.Base;
targetCount = 0;
break;
// Other opcodes has one result
default:
Stack.Get(target) = result.Length == 0 ? LuaValue.Nil : result[0];
State.PopCallStackFrameWithStackPop(Math.Max(target + 1, CurrentReturnFrameBase));
return true;
}
Stack.EnsureCapacity(target + targetCount);
if (0 < targetCount && src != target)
{
if (targetCount < result.Length)
{
result = result.Slice(0, targetCount);
}
result.CopyTo(Stack.GetBuffer().Slice(target, targetCount));
}
Stack.PopUntil(target + Math.Min(targetCount, srcCount));
Stack.NotifyTop(target + targetCount);
State.PopCallStackFrame();
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Push(in CallStackFrame frame)
{
Pc = -1;
LuaClosure = (LuaClosure)frame.Function;
FrameBase = frame.Base;
CurrentReturnFrameBase = frame.ReturnBase;
VariableArgumentCount = frame.VariableArgumentCount;
}
public void PopOnTopCallStackFrames()
{
var count = State.CallStackFrameCount;
if (count == BaseCallStackCount)
{
return;
}
State.PopCallStackFrameUntil(BaseCallStackCount);
}
bool ExecutePostOperation(int varArgs, PostOperationType postOperation)
{
var stackCount = Stack.Count;
var resultsSpan = Stack.GetBuffer()[CurrentReturnFrameBase..];
var lastTop = CurrentReturnFrameBase - varArgs;
switch (postOperation)
{
case PostOperationType.Nop:
break;
case PostOperationType.SetResult:
var RA = Instruction.A + FrameBase;
Stack.Get(RA) =
stackCount > CurrentReturnFrameBase
? Stack.Get(CurrentReturnFrameBase)
: LuaValue.Nil;
Stack.NotifyTop(RA + 1);
Stack.PopUntil(Math.Max(RA + 1, lastTop));
break;
case PostOperationType.TForCall:
TForCallPostOperation(this);
break;
case PostOperationType.Call:
CallPostOperation(this);
break;
case PostOperationType.TailCall:
if (
!PopFromBuffer(CurrentReturnFrameBase, Stack.Count - CurrentReturnFrameBase)
)
{
return false;
}
break;
case PostOperationType.Self:
SelfPostOperation(this, lastTop, resultsSpan);
break;
case PostOperationType.Compare:
ComparePostOperation(this, lastTop, resultsSpan);
break;
}
return true;
}
public async ValueTask<int> ExecuteClosureAsyncImpl()
{
var returnFrameBase = CurrentReturnFrameBase;
var toCatchFlag = false;
try
{
while (MoveNext(this))
{
toCatchFlag = true;
await Task;
Task = default;
ref readonly var frame = ref State.GetCurrentFrame();
CurrentReturnFrameBase = frame.ReturnBase;
var variableArgumentCount = frame.VariableArgumentCount;
if (
PostOperation
is not (PostOperationType.TailCall or PostOperationType.DontPop)
)
{
State.PopCallStackFrame();
}
if (!ExecutePostOperation(variableArgumentCount, PostOperation))
{
break;
}
toCatchFlag = false;
ThrowIfCancellationRequested();
}
return State.Stack.Count - returnFrameBase;
}
catch (Exception e)
{
if (toCatchFlag)
{
State.CloseUpValues(FrameBase);
if (e is not (LuaRuntimeException or LuaCanceledException))
{
Exception newException =
e is OperationCanceledException
? new LuaCanceledException(State, CancellationToken, e)
: new LuaRuntimeException(State, e);
PopOnTopCallStackFrames();
throw newException;
}
PopOnTopCallStackFrames();
}
throw;
}
finally
{
pool.TryPush(this);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ThrowIfCancellationRequested()
{
if (!CancellationToken.IsCancellationRequested)
{
return;
}
Throw();
void Throw()
{
GetstateWithCurrentPc(this).ThrowIfCancellationRequested(CancellationToken);
}
}
}
enum PostOperationType
{
None,
Nop,
SetResult,
TForCall,
Call,
TailCall,
Self,
Compare,
DontPop,
}
internal static ValueTask<int> ExecuteClosureAsync(
LuaState state,
CancellationToken cancellationToken
)
{
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
{
throw new LuaStackOverflowException();
}
ref readonly var frame = ref state.GetCurrentFrame();
var context = VirtualMachineExecutionContext.Get(state, in frame, cancellationToken);
return context.ExecuteClosureAsyncImpl();
}
static long DummyHookCount;
static bool DummyLineHookEnabled;
static bool MoveNext(VirtualMachineExecutionContext context)
{
try
{
// This is a label to restart the execution when new function is called or restarted
Restart:
ref var instructionsHead = ref Unsafe.AsRef(in context.Prototype.Code[0]);
var frameBase = context.FrameBase;
var stack = context.Stack;
stack.EnsureCapacity(frameBase + context.Prototype.MaxStackSize);
ref var constHead = ref MemoryMarshalEx.UnsafeElementAt(context.Prototype.Constants, 0);
ref var lineHookFlag = ref context.State.IsInHook
? ref DummyLineHookEnabled
: ref context.State.IsLineHookEnabled;
ref var hookCount = ref context.State.IsInHook
? ref DummyHookCount
: ref context.State.HookCount;
goto Loop;
LineHook:
{
context.LastHookPc = context.Pc;
if (ExecutePerInstructionHook(context))
{
{
context.PostOperation = PostOperationType.Nop;
return true;
}
}
--context.Pc;
}
Loop:
while (true)
{
var instruction = Unsafe.Add(ref instructionsHead, ++context.Pc);
context.Instruction = instruction;
if (--hookCount == 0 || (lineHookFlag && context.Pc != context.LastHookPc))
{
goto LineHook;
}
context.LastHookPc = -1;
var iA = instruction.A;
var opCode = instruction.OpCode;
switch (opCode)
{
case OpCode.Move:
Markers.Move();
ref var stackHead = ref stack.FastGet(frameBase);
Unsafe.Add(ref stackHead, iA) = Unsafe.Add(ref stackHead, instruction.B);
stack.NotifyTop(iA + frameBase + 1);
continue;
case OpCode.LoadK:
Markers.LoadK();
stack.GetWithNotifyTop(iA + frameBase) = Unsafe.Add(
ref constHead,
instruction.Bx
);
continue;
case OpCode.LoadKX:
Markers.LoadKX();
stack.GetWithNotifyTop(iA + frameBase) = Unsafe.Add(
ref constHead,
Unsafe.Add(ref instructionsHead, ++context.Pc).Ax
);
continue;
case OpCode.LoadBool:
Markers.LoadBool();
stack.GetWithNotifyTop(iA + frameBase) = instruction.B != 0;
if (instruction.C != 0)
{
context.Pc++;
}
continue;
case OpCode.LoadNil:
Markers.LoadNil();
var ra1 = iA + frameBase + 1;
var iB = instruction.B;
stackHead = ref stack.FastGet(ra1 - 1);
for (var i = 0; i <= iB; i++)
{
Unsafe.Add(ref stackHead, i) = default;
}
stack.NotifyTop(ra1 + iB);
continue;
case OpCode.GetUpVal:
Markers.GetUpVal();
stack.GetWithNotifyTop(iA + frameBase) = context.LuaClosure.GetUpValue(
instruction.B
);
continue;
case OpCode.GetTabUp:
case OpCode.GetTable:
Markers.GetTabUp();
Markers.GetTable();
stackHead = ref stack.FastGet(frameBase);
ref readonly var vc = ref RKC(ref stackHead, ref constHead, instruction);
ref readonly var vb = ref instruction.OpCode == OpCode.GetTable
? ref Unsafe.Add(ref stackHead, instruction.B)
: ref context.LuaClosure.GetUpValueRef(instruction.B);
var doRestart = false;
if (
(
vb.TryReadTable(out var luaTable)
&& luaTable.TryGetValue(vc, out var resultValue)
)
|| GetTableValueSlowPath(
vb,
vc,
context,
out resultValue,
out doRestart
)
)
{
if (doRestart)
{
goto Restart;
}
stack.GetWithNotifyTop(instruction.A + frameBase) = resultValue;
continue;
}
return true;
case OpCode.SetTabUp:
case OpCode.SetTable:
Markers.SetTabUp();
Markers.SetTable();
stackHead = ref stack.FastGet(frameBase);
vb = ref RKB(ref stackHead, ref constHead, instruction);
if (vb.TryReadNumber(out var numB))
{
if (double.IsNaN(numB))
{
ThrowLuaRuntimeException(context, "table index is NaN");
return true;
}
}
var table =
opCode == OpCode.SetTabUp
? context.LuaClosure.GetUpValue(iA)
: Unsafe.Add(ref stackHead, iA);
if (table.TryReadTable(out luaTable))
{
ref var valueRef = ref luaTable.FindValue(vb);
if (
!Unsafe.IsNullRef(ref valueRef)
&& valueRef.Type != LuaValueType.Nil
)
{
valueRef = RKC(ref stackHead, ref constHead, instruction);
continue;
}
}
vc = ref RKC(ref stackHead, ref constHead, instruction);
if (SetTableValueSlowPath(table, vb, vc, context, out doRestart))
{
if (doRestart)
{
goto Restart;
}
continue;
}
return true;
case OpCode.SetUpVal:
Markers.SetUpVal();
context.LuaClosure.SetUpValue(instruction.B, stack.FastGet(iA + frameBase));
continue;
case OpCode.NewTable:
Markers.NewTable();
stack.GetWithNotifyTop(iA + frameBase) = new LuaTable(
instruction.B,
instruction.C
);
continue;
case OpCode.Self:
Markers.Self();
stackHead = ref stack.FastGet(frameBase);
vc = ref RKC(ref stackHead, ref constHead, instruction);
table = Unsafe.Add(ref stackHead, instruction.B);
doRestart = false;
if (
(
table.TryReadTable(out luaTable)
&& luaTable.TryGetValue(vc, out resultValue)
)
|| GetTableValueSlowPath(
table,
vc,
context,
out resultValue,
out doRestart
)
)
{
if (doRestart)
{
goto Restart;
}
Unsafe.Add(ref stackHead, iA) = resultValue;
Unsafe.Add(ref stackHead, iA + 1) = table;
stack.NotifyTop(iA + frameBase + 2);
continue;
}
return true;
case OpCode.Add:
case OpCode.Sub:
case OpCode.Mul:
case OpCode.Div:
case OpCode.Mod:
case OpCode.Pow:
Markers.Add();
Markers.Sub();
Markers.Mul();
Markers.Div();
Markers.Mod();
Markers.Pow();
stackHead = ref stack.FastGet(frameBase);
vb = ref RKB(ref stackHead, ref constHead, instruction);
vc = ref RKC(ref stackHead, ref constHead, instruction);
[MethodImpl(MethodImplOptions.NoInlining)]
static double Mod(double a, double b)
{
var mod = a % b;
if ((b > 0 && mod < 0) || (b < 0 && mod > 0))
{
mod += b;
}
return mod;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double ArithmeticOperation(OpCode code, double a, double b)
{
return code switch
{
OpCode.Add => a + b,
OpCode.Sub => a - b,
OpCode.Mul => a * b,
OpCode.Div => a / b,
OpCode.Mod => Mod(a, b),
OpCode.Pow => Math.Pow(a, b),
_ => 0,
};
}
if (vb.Type == LuaValueType.Number && vc.Type == LuaValueType.Number)
{
Unsafe.Add(ref stackHead, iA) = ArithmeticOperation(
opCode,
vb.UnsafeReadDouble(),
vc.UnsafeReadDouble()
);
stack.NotifyTop(iA + frameBase + 1);
continue;
}
if (vb.TryReadDouble(out numB) && vc.TryReadDouble(out var numC))
{
Unsafe.Add(ref stackHead, iA) = ArithmeticOperation(opCode, numB, numC);
stack.NotifyTop(iA + frameBase + 1);
continue;
}
if (
ExecuteBinaryOperationMetaMethod(vb, vc, context, opCode, out doRestart)
)
{
if (doRestart)
{
goto Restart;
}
continue;
}
return true;
case OpCode.Unm:
Markers.Unm();
stackHead = ref stack.FastGet(frameBase);
vb = ref Unsafe.Add(ref stackHead, instruction.B);
if (vb.TryReadDouble(out numB))
{
ra1 = iA + frameBase + 1;
Unsafe.Add(ref stackHead, iA) = -numB;
stack.NotifyTop(ra1);
continue;
}
if (ExecuteUnaryOperationMetaMethod(vb, context, OpCode.Unm, out doRestart))
{
if (doRestart)
{
goto Restart;
}
continue;
}
return true;
case OpCode.Not:
Markers.Not();
stackHead = ref stack.FastGet(frameBase);
Unsafe.Add(ref stackHead, iA) = !Unsafe
.Add(ref stackHead, instruction.B)
.ToBoolean();
stack.NotifyTop(iA + frameBase + 1);
continue;
case OpCode.Len:
Markers.Len();
stackHead = ref stack.FastGet(frameBase);
vb = ref Unsafe.Add(ref stackHead, instruction.B);
if (vb.TryReadString(out var str))
{
ra1 = iA + frameBase + 1;
Unsafe.Add(ref stackHead, iA) = str.Length;
stack.NotifyTop(ra1);
continue;
}
if (ExecuteUnaryOperationMetaMethod(vb, context, OpCode.Len, out doRestart))
{
if (doRestart)
{
goto Restart;
}
continue;
}
return true;
case OpCode.Concat:
Markers.Concat();
if (Concat(context))
{
// if (doRestart) goto Restart;
continue;
}
return true;
case OpCode.Jmp:
Markers.Jmp();
context.Pc += instruction.SBx;
if (iA != 0)
{
context.State.CloseUpValues(frameBase + iA - 1);
}
context.ThrowIfCancellationRequested();
continue;
case OpCode.Eq:
Markers.Eq();
stackHead = ref stack.Get(frameBase);
vb = ref RKB(ref stackHead, ref constHead, instruction);
vc = ref RKC(ref stackHead, ref constHead, instruction);
if (vb == vc)
{
if (iA != 1)
{
context.Pc++;
}
continue;
}
if (
ExecuteCompareOperationMetaMethod(
vb,
vc,
context,
OpCode.Eq,
out doRestart
)
)
{
if (doRestart)
{
goto Restart;
}
continue;
}
return true;
case OpCode.Lt:
case OpCode.Le:
Markers.Lt();
Markers.Le();
stackHead = ref stack.Get(frameBase);
vb = ref RKB(ref stackHead, ref constHead, instruction);
vc = ref RKC(ref stackHead, ref constHead, instruction);
if (vb.TryReadNumber(out numB) && vc.TryReadNumber(out numC))
{
var compareResult = opCode == OpCode.Lt ? numB < numC : numB <= numC;
if (compareResult != (iA == 1))
{
context.Pc++;
}
continue;
}
if (vb.TryReadString(out var strB) && vc.TryReadString(out var strC))
{
var c = StringComparer.Ordinal.Compare(strB, strC);
var compareResult = opCode == OpCode.Lt ? c < 0 : c <= 0;
if (compareResult != (iA == 1))
{
context.Pc++;
}
continue;
}
if (
ExecuteCompareOperationMetaMethod(
vb,
vc,
context,
opCode,
out doRestart
)
)
{
if (doRestart)
{
goto Restart;
}
continue;
}
return true;
case OpCode.Test:
Markers.Test();
if (stack.Get(iA + frameBase).ToBoolean() != (instruction.C == 1))
{
context.Pc++;
}
continue;
case OpCode.TestSet:
Markers.TestSet();
vb = ref stack.Get(instruction.B + frameBase);
if (vb.ToBoolean() != (instruction.C == 1))
{
context.Pc++;
}
else
{
stack.GetWithNotifyTop(iA + frameBase) = vb;
}
continue;
case OpCode.Call:
Markers.Call();
if (Call(context, out doRestart))
{
if (doRestart)
{
goto Restart;
}
continue;
}
return true;
case OpCode.TailCall:
Markers.TailCall();
if (TailCall(context, out doRestart))
{
if (doRestart)
{
goto Restart;
}
if (context.IsTopLevel)
{
goto End;
}
continue;
}
return true;
case OpCode.Return:
Markers.Return();
context.State.CloseUpValues(frameBase);
if (context.Pop(instruction, frameBase))
{
goto Restart;
}
goto End;
case OpCode.ForLoop:
Markers.ForLoop();
ref var indexRef = ref stack.Get(iA + frameBase);
var limit = Unsafe.Add(ref indexRef, 1).UnsafeReadDouble();
var step = Unsafe.Add(ref indexRef, 2).UnsafeReadDouble();
var index = indexRef.UnsafeReadDouble() + step;
if (step >= 0 ? index <= limit : limit <= index)
{
context.Pc += instruction.SBx;
indexRef = index;
Unsafe.Add(ref indexRef, 3) = index;
stack.NotifyTop(iA + frameBase + 4);
context.ThrowIfCancellationRequested();
continue;
}
stack.NotifyTop(iA + frameBase + 1);
continue;
case OpCode.ForPrep:
Markers.ForPrep();
indexRef = ref stack.Get(iA + frameBase);
if (!indexRef.TryReadDouble(out var init))
{
ThrowLuaRuntimeException(
context,
"'for' initial value must be a number"
);
return true;
}
if (!LuaValue.TryReadOrSetDouble(ref Unsafe.Add(ref indexRef, 1), out _))
{
ThrowLuaRuntimeException(context, "'for' limit must be a number");
return true;
}
if (!LuaValue.TryReadOrSetDouble(ref Unsafe.Add(ref indexRef, 2), out step))
{
ThrowLuaRuntimeException(context, "'for' step must be a number");
return true;
}
indexRef = init - step;
stack.NotifyTop(iA + frameBase + 1);
context.Pc += instruction.SBx;
continue;
case OpCode.TForCall:
Markers.TForCall();
if (TForCall(context, out doRestart))
{
if (doRestart)
{
goto Restart;
}
continue;
}
return true;
case OpCode.TForLoop:
Markers.TForLoop();
ref var forState = ref stack.Get(iA + frameBase + 1);
if (forState.Type is not LuaValueType.Nil)
{
Unsafe.Add(ref forState, -1) = forState;
context.Pc += instruction.SBx;
}
continue;
case OpCode.SetList:
Markers.SetList();
SetList(context);
continue;
case OpCode.Closure:
Markers.Closure();
ra1 = iA + frameBase + 1;
stack.EnsureCapacity(ra1);
stack.Get(ra1 - 1) = new LuaClosure(
context.State,
context.Prototype.ChildPrototypes[instruction.Bx]
);
stack.NotifyTop(ra1);
continue;
case OpCode.VarArg:
Markers.VarArg();
VarArg(context);
[MethodImpl(MethodImplOptions.NoInlining)]
static void VarArg(VirtualMachineExecutionContext context)
{
var instruction = context.Instruction;
var iA = instruction.A;
var frameBase = context.FrameBase;
var frameVariableArgumentCount = context.VariableArgumentCount;
var count =
instruction.B == 0 ? frameVariableArgumentCount : instruction.B - 1;
var ra = iA + frameBase;
var stack = context.Stack;
stack.EnsureCapacity(ra + count);
ref var stackHead = ref stack.Get(0);
for (var i = 0; i < count; i++)
{
Unsafe.Add(ref stackHead, ra + i) =
frameVariableArgumentCount > i