-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbytecode_test.go
More file actions
9948 lines (9276 loc) · 298 KB
/
Copy pathbytecode_test.go
File metadata and controls
9948 lines (9276 loc) · 298 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
package ember
import (
"errors"
"fmt"
"go/ast"
goparser "go/parser"
"go/token"
"reflect"
"runtime"
"strconv"
"strings"
"testing"
)
func TestDisassembleProtoNamesInstructions(t *testing.T) {
var builder bytecodeBuilder
builder.emitLoadConst(0, NumberValue(2))
builder.emitLoadConst(1, NumberValue(3))
builder.emit(instruction{op: opAdd, a: 2, b: 0, c: 1})
builder.emit(instruction{op: opReturn, a: 2, b: 1})
proto := builder.proto(nil, 3, 0, false)
got := disassembleProto(proto)
want := []string{
"0000 LOAD_CONST r0 k0(number 2)",
"0001 LOAD_CONST r1 k1(number 3)",
"0002 ADD r2 r0 r1",
"0003 RETURN r2 1",
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("disassembleProto() = %#v, want %#v", got, want)
}
}
func TestInstructionSizeBudget(t *testing.T) {
if got, want := reflect.TypeOf(wordcodeWord(0)).Size(), uintptr(4); got > want {
t.Fatalf("instruction size is %d bytes, want at most %d", got, want)
}
}
func TestFixedCallCountEncodingBoundaries(t *testing.T) {
for _, count := range []int{0, 1, 32767} {
for _, borrow := range []bool{false, true} {
raw := encodeFixedCallCount(count, borrow)
decoded, gotBorrow := decodeFixedCallCount(raw)
if decoded != count || gotBorrow != borrow {
t.Fatalf("fixed call count (%d, %t) encoded as %d and decoded as (%d, %t)", count, borrow, raw, decoded, gotBorrow)
}
if _, err := wordcodeEncodeInstruction(
instruction{op: opCallOne, a: 0, b: 0, c: raw, d: 1},
0, 2, []int{0, 2},
); err != nil {
t.Fatalf("fixed call count (%d, %t) did not fit wordcode operand: %v", count, borrow, err)
}
}
}
if got := encodeFixedCallCount(2, false); got < 0 {
t.Fatalf("ordinary fixed call count encoded as negative %d", got)
}
if got, borrow := decodeFixedCallCount(-32769); got != 32768 || !borrow {
t.Fatalf("corrupt negative count decoded as (%d, %t), want (32768, true)", got, borrow)
}
if _, _, err := verifyFixedCallCount(-32769, "fixed one-result call"); err == nil {
t.Fatal("verifier accepted a negative count outside the packed int16 range")
}
if _, _, err := verifyFixedCallCount(32768, "fixed one-result call"); err == nil {
t.Fatal("verifier accepted a positive count outside the packed int16 range")
}
}
func TestDisassembleFixedCallBorrowMarker(t *testing.T) {
proto := newProto(nil, []instruction{{op: opCallLocalOne, a: 0, b: 1, c: 2, d: encodeFixedCallCount(3, true)}}, nil, nil, 8, 0, false)
got := disassembleProto(proto)
if len(got) != 1 || !strings.Contains(got[0], "CALL_LOCAL_ONE r0 r1 r2 3 borrow") {
t.Fatalf("fixed-call borrow disassembly = %#v", got)
}
}
func TestFinalizeProtoRejectsWordcodeRegisterOverflow(t *testing.T) {
proto := newProto(
[]Value{NumberValue(1)},
[]instruction{
{op: opLoadConst, a: 32768, b: 0},
{op: opReturnOne, a: 0},
},
nil,
nil,
1,
0,
false,
)
if proto.verifyErr == nil {
t.Fatal("newProto accepted an instruction register outside the wordcode range")
}
if got := proto.verifyErr.Error(); !strings.Contains(got, "instruction 0 LOAD_CONST") || !strings.Contains(got, "register index 32768 out of range") {
t.Fatalf("wordcode register overflow error is %q", got)
}
}
func TestValueSizeBudgetSafeLayout(t *testing.T) {
want := expectedArchitectureLayoutSize(12, 16)
if got := reflect.TypeOf(Value{}).Size(); got != want {
t.Fatalf("Value size is %d bytes, want exactly %d for this pointer width", got, want)
}
}
func TestValueRoundTripsAllKinds(t *testing.T) {
table := NewTable()
userdata := NewUserData("payload")
proto := newProto(nil, []instruction{{op: opReturn}}, nil, nil, 0, 0, false)
closureValue := functionValue(proto, nil)
hostFn := func(args []Value) ([]Value, error) { return args, nil }
nativeValue := nativeFuncValueWithID(baseRawLenNative, nativeFuncRawLen)
if !NilValue().IsNil() {
t.Fatal("NilValue did not round-trip nil kind")
}
if got, ok := BoolValue(true).Bool(); !ok || !got {
t.Fatalf("BoolValue round trip = %v, %t; want true, true", got, ok)
}
if got, ok := NumberValue(12.5).Number(); !ok || got != 12.5 {
t.Fatalf("NumberValue round trip = %v, %t; want 12.5, true", got, ok)
}
if got, ok := StringValue("ember").String(); !ok || got != "ember" {
t.Fatalf("StringValue round trip = %q, %t; want ember, true", got, ok)
}
if got, ok := TableValue(table).Table(); !ok || got != table {
t.Fatalf("TableValue round trip = %p, %t; want %p, true", got, ok, table)
}
if got, ok := UserDataValue(userdata).UserData(); !ok || got != userdata {
t.Fatalf("UserDataValue round trip = %p, %t; want %p, true", got, ok, userdata)
}
if got, ok := closureValue.scriptFunction(); !ok || got == nil || got.proto != proto {
t.Fatalf("functionValue round trip = %#v, %t; want closure for proto", got, ok)
}
if got, ok := HostFuncValue(hostFn).hostFunction(); !ok || got == nil {
t.Fatalf("HostFuncValue round trip = %v, %t; want host function", got, ok)
}
if got, ok := nativeValue.nativeFunction(); !ok || got == nil {
t.Fatalf("nativeFuncValueWithID round trip = %v, %t; want native function", got, ok)
}
}
func TestStringValuesCompareAndHashAcrossBoxingBoundaries(t *testing.T) {
left := StringValue("ember")
right := StringValue(strings.Join([]string{"em", "ber"}, ""))
if !valuesEqual(left, right) {
t.Fatalf("boxed strings with equal text did not compare equal: %#v %#v", left, right)
}
leftKey, leftOK := tableKeyFromValue(left)
rightKey, rightOK := tableKeyFromValue(right)
if !leftOK || !rightOK {
t.Fatalf("tableKeyFromValue ok = %t, %t; want true, true", leftOK, rightOK)
}
if !tableKeysEqual(leftKey, rightKey) {
t.Fatalf("table keys from separately boxed strings are not equal: %#v != %#v", leftKey, rightKey)
}
table := NewTable()
if err := table.Set(left, NumberValue(7)); err != nil {
t.Fatalf("table.Set returned error: %v", err)
}
got, err := table.Get(right)
if err != nil {
t.Fatalf("table.Get returned error: %v", err)
}
if number, ok := got.Number(); !ok || number != 7 {
t.Fatalf("table lookup across string boxes = %v (%t), want 7", got, ok)
}
}
func TestValueConstructorsDoNotAllocateForScalars(t *testing.T) {
var sink Value
allocs := testing.AllocsPerRun(1000, func() {
sink = NilValue()
sink = BoolValue(true)
sink = NumberValue(1)
sink = nativeFuncValueWithID(baseRawLenNative, nativeFuncRawLen)
})
if allocs != 0 {
t.Fatalf("scalar value constructors allocated %.2f times, want 0", allocs)
}
_ = sink
}
func TestRunMinimalScriptAllocationBudget(t *testing.T) {
if allocationInstrumentedTest() {
t.Skip("allocation budgets run only with the normal compiler/runtime instrumentation")
}
proto, err := Compile(`return 1`)
if err != nil {
t.Fatalf("Compile returned error: %v", err)
}
if results, err := Run(proto); err != nil {
t.Fatalf("warm Run returned error: %v", err)
} else if got, ok := results[0].Number(); !ok || got != 1 {
t.Fatalf("warm Run result is %v (%t), want number 1", results[0], ok)
}
allocs := testing.AllocsPerRun(1000, func() {
results, err := Run(proto)
if err != nil {
t.Fatalf("Run returned error: %v", err)
}
got, ok := results[0].Number()
if !ok || got != 1 {
t.Fatalf("Run result is %v (%t), want number 1", results[0], ok)
}
})
if allocs > 1 {
t.Fatalf("minimal Run allocated %.0f times, want only the public result slice allocation", allocs)
}
}
func TestRunWithGlobalsDoesNotCopyHostMapPerRun(t *testing.T) {
proto, err := Compile(`return target`)
if err != nil {
t.Fatalf("Compile returned error: %v", err)
}
globals := make(map[string]Value, 512)
for i := 0; i < 512; i++ {
globals[fmt.Sprintf("unused_%03d", i)] = NumberValue(float64(i))
}
globals["target"] = NumberValue(42)
bytes := measuredRunWithGlobalsAllocBytes(t, proto, globals, 42, 40)
if bytes > 8192 {
t.Fatalf("RunWithGlobals allocated %d bytes per run with a large host map, want no per-run host map copy", bytes)
}
}
func TestGlobalReadsDoNotAllocateOrRehashPerAccess(t *testing.T) {
proto, err := Compile(`
local total = 0
for i = 1, 80 do
total = total + score
end
return total
`)
if err != nil {
t.Fatalf("Compile returned error: %v", err)
}
results, snapshot, err := runWithDirectFrameMechanismCounters(proto, map[string]Value{
"score": NumberValue(3),
})
if err != nil {
t.Fatalf("RunWithGlobals returned error: %v", err)
}
if got, ok := results[0].Number(); !ok || got != 240 {
t.Fatalf("RunWithGlobals result is %v (%t), want 240", results[0], ok)
}
if got := snapshot.opcodeCounts.count(opLoadGlobal); got < 80 {
t.Fatalf("LOAD_GLOBAL executed %d times, want repeated global reads in the loop", got)
}
if got := snapshot.picCounts.globalSlotMisses; got != 1 {
t.Fatalf("global slot misses = %d, want one name resolution", got)
}
if got := snapshot.picCounts.globalSlotHits; got < 79 {
t.Fatalf("global slot hits = %d, want repeated reads to use the resolved slot", got)
}
}
func TestConcatChainAllocatesOnceForRawOperands(t *testing.T) {
if allocationInstrumentedTest() {
t.Skip("allocation budgets run only with the normal compiler/runtime instrumentation")
}
proto, err := Compile(`
local left = "hp"
local current = 25
local max = 100
return left .. ":" .. current .. "/" .. max
`)
if err != nil {
t.Fatalf("Compile returned error: %v", err)
}
if joined := strings.Join(disassembleProto(proto), "\n"); !strings.Contains(joined, "CONCAT_CHAIN") {
t.Fatalf("compiled concat program is missing CONCAT_CHAIN:\n%s", joined)
}
if results, err := Run(proto); err != nil {
t.Fatalf("warm Run returned error: %v", err)
} else if got, ok := results[0].String(); !ok || got != "hp:25/100" {
t.Fatalf("warm Run result is %v (%t), want hp:25/100", results[0], ok)
}
allocs := testing.AllocsPerRun(1000, func() {
results, err := Run(proto)
if err != nil {
t.Fatalf("Run returned error: %v", err)
}
if got, ok := results[0].String(); !ok || got != "hp:25/100" {
t.Fatalf("Run result is %v (%t), want hp:25/100", results[0], ok)
}
})
if allocs > 2 {
t.Fatalf("raw concat chain allocated %.0f times per run, want result slice plus one final string allocation", allocs)
}
}
func TestTostringSmallIntegerDoesNotAllocate(t *testing.T) {
if allocationInstrumentedTest() {
t.Skip("allocation budgets run only with the normal compiler/runtime instrumentation")
}
globals := runtimeGlobals(nil)
thread := newVMThread(globals)
restore := thread.activate()
defer restore()
if result, err := baseToStringValue(globals, NumberValue(25)); err != nil {
t.Fatalf("warm baseToStringValue returned error: %v", err)
} else if got, ok := result.String(); !ok || got != "25" {
t.Fatalf("warm baseToStringValue result is %v (%t), want 25", result, ok)
}
allocs := testing.AllocsPerRun(1000, func() {
result, err := baseToStringValue(globals, NumberValue(25))
if err != nil {
t.Fatalf("baseToStringValue returned error: %v", err)
}
if got, ok := result.String(); !ok || got != "25" {
t.Fatalf("baseToStringValue result is %v (%t), want 25", result, ok)
}
})
if allocs != 0 {
t.Fatalf("tostring small integer allocated %.0f times, want static formatting and warmed string intern", allocs)
}
}
func TestLoopTableLiteralAllocationBudget(t *testing.T) {
if allocationInstrumentedTest() {
t.Skip("allocation budgets run only with the normal compiler/runtime instrumentation")
}
proto, err := Compile(`
local total = 0
for i = 1, 80 do
local values = {i, i + 1, hp = i + 2, mp = i + 3}
total = total + values[1] + values[2] + values.hp + values.mp
end
return total
`)
if err != nil {
t.Fatalf("Compile returned error: %v", err)
}
if joined := strings.Join(disassembleProto(proto), "\n"); !strings.Contains(joined, "NEW_TABLE") {
t.Fatalf("compiled loop literal program is missing NEW_TABLE:\n%s", joined)
}
thread := newVMThread(runtimeGlobals(nil))
restore := thread.activate()
defer restore()
if results, err := thread.runScript(proto, nil, nil); err != nil {
t.Fatalf("warm thread.runScript returned error: %v", err)
} else if got, ok := results[0].Number(); !ok || got != 13440 {
t.Fatalf("warm result is %v (%t), want 13440", results[0], ok)
}
allocs := testing.AllocsPerRun(100, func() {
results, err := thread.runScript(proto, nil, nil)
if err != nil {
t.Fatalf("thread.runScript returned error: %v", err)
}
if got, ok := results[0].Number(); !ok || got != 13440 {
t.Fatalf("thread.runScript result is %v (%t), want 13440", results[0], ok)
}
})
if allocs > 90 {
t.Fatalf("loop table literals allocated %.0f times per run, want one table allocation per iteration plus run-boundary allocations", allocs)
}
}
func measuredRunWithGlobalsAllocBytes(t *testing.T, proto *Proto, globals map[string]Value, want float64, runs int) uint64 {
t.Helper()
runtime.GC()
var before runtime.MemStats
runtime.ReadMemStats(&before)
for i := 0; i < runs; i++ {
results, err := RunWithGlobals(proto, globals)
if err != nil {
t.Fatalf("RunWithGlobals returned error: %v", err)
}
got, ok := results[0].Number()
if !ok || got != want {
t.Fatalf("RunWithGlobals result is %v (%t), want number %v", results[0], ok, want)
}
}
var after runtime.MemStats
runtime.ReadMemStats(&after)
return (after.TotalAlloc - before.TotalAlloc) / uint64(runs)
}
func TestValueUnsafeLayoutSizeBudget(t *testing.T) {
want := expectedArchitectureLayoutSize(12, 16)
if got := reflect.TypeOf(Value{}).Size(); got != want {
t.Fatalf("unsafe Value size is %d bytes, want exactly %d for this pointer width", got, want)
}
}
func TestTableHeaderSizeBudget(t *testing.T) {
if got, want := reflect.TypeOf(Table{}).Size(), uintptr(128); got > want {
t.Fatalf("Table size is %d bytes, want at most %d", got, want)
}
}
func TestTableGenericKeyLookupDoesNotAllocate(t *testing.T) {
table := NewTable()
key := BoolValue(true)
if err := table.rawSet(key, NumberValue(42)); err != nil {
t.Fatalf("rawSet returned error: %v", err)
}
var sink Value
allocs := testing.AllocsPerRun(1000, func() {
value, err := table.rawGet(key)
if err != nil {
t.Fatalf("rawGet returned error: %v", err)
}
sink = value
})
if allocs != 0 {
t.Fatalf("generic key lookup allocated %.2f times, want 0", allocs)
}
if got, ok := sink.Number(); !ok || got != 42 {
t.Fatalf("generic key lookup result = %v (%t), want 42", got, ok)
}
}
func TestValueUnsafeAccessorsRoundTripAllKinds(t *testing.T) {
TestValueRoundTripsAllKinds(t)
}
func TestValueUnsafeLayoutMatchesSafeSemantics(t *testing.T) {
table := NewTable()
userdata := NewUserData("payload")
proto := newProto(nil, []instruction{{op: opReturn}}, nil, nil, 0, 0, false)
closureValue := functionValue(proto, nil)
hostValue := HostFuncValue(func(args []Value) ([]Value, error) { return args, nil })
if got, ok := TableValue(table).Table(); !ok || got != table {
t.Fatalf("unsafe table accessor = %p, %t; want %p, true", got, ok, table)
}
if got, ok := UserDataValue(userdata).UserData(); !ok || got != userdata {
t.Fatalf("unsafe userdata accessor = %p, %t; want %p, true", got, ok, userdata)
}
if got, ok := closureValue.scriptFunction(); !ok || got == nil || got.proto != proto {
t.Fatalf("unsafe closure accessor = %#v, %t; want closure for proto", got, ok)
}
if got, ok := hostValue.hostFunction(); !ok || got == nil {
t.Fatalf("unsafe host accessor = %v, %t; want host function", got, ok)
}
}
func TestSmallTableStringFieldsUseInlineStorage(t *testing.T) {
var sink *Table
allocs := testing.AllocsPerRun(1000, func() {
table := newTableWithCapacity(0, 0)
table.setRawStringField("a", NumberValue(1))
table.setRawStringField("b", NumberValue(2))
sink = table
})
if allocs > 1 {
t.Fatalf("small table with inline string fields allocated %.2f times, want only table allocation", allocs)
}
if sink == nil {
t.Fatal("sink table is nil")
}
if sink.hasStringOverflow() {
t.Fatal("small table used string field map, want inline string fields")
}
const wantInlineStringFieldCapacity = 2
if got := cap(sink.stringFields); got != wantInlineStringFieldCapacity {
t.Fatalf("small table inline string field capacity = %d, want %d", got, wantInlineStringFieldCapacity)
}
}
func TestBytecodeFinalizerReturnsVerifiedProto(t *testing.T) {
var builder bytecodeBuilder
builder.emitLoadConst(0, NumberValue(2))
builder.emit(instruction{op: opReturn, a: 0, b: 1})
proto, err := builder.finalizeProto(nil, 1, 0, false)
if err != nil {
t.Fatalf("finalizeProto returned error: %v", err)
}
if proto.verifyErr != nil {
t.Fatalf("finalized proto has verifyErr %v, want nil", proto.verifyErr)
}
}
func TestExecutionArtifactFinalizerRebuildsDerivedProtoFacts(t *testing.T) {
var builder bytecodeBuilder
builder.emitLoadConst(0, NumberValue(2))
builder.emit(instruction{op: opReturnOne, a: 0})
proto := builder.proto(nil, 1, 0, false)
proto.constantKeys = nil
proto.constantKeyOK = nil
proto.constantNumbers = nil
proto.constantNumberOK = nil
proto.capturedLocals = []bool{true}
proto.entryNilRegisters = []int{99}
proto.verifyErr = fmt.Errorf("stale")
if err := finalizeProtoExecutionArtifact(proto); err != nil {
t.Fatalf("finalizeProtoExecutionArtifact returned error: %v", err)
}
if proto.verifyErr != nil {
t.Fatalf("finalized proto verifyErr = %v, want nil", proto.verifyErr)
}
if proto.constantKeys == nil || proto.constantKeyOK == nil {
t.Fatal("finalized proto did not rebuild constant key facts")
}
if proto.constantNumbers == nil || proto.constantNumberOK == nil {
t.Fatal("finalized proto did not rebuild constant number facts")
}
if len(proto.capturedLocals) != 0 {
t.Fatalf("capturedLocals = %#v, want rebuilt empty facts", proto.capturedLocals)
}
if len(proto.entryNilRegisters) != 0 {
t.Fatalf("entryNilRegisters = %#v, want rebuilt empty facts", proto.entryNilRegisters)
}
}
func TestBytecodeFinalizerRejectsInvalidCompilerProto(t *testing.T) {
var builder bytecodeBuilder
builder.emit(instruction{op: opJump, b: 99})
proto, err := builder.finalizeProto(nil, 1, 0, false)
if err == nil {
t.Fatal("finalizeProto succeeded, want invalid finalized prototype error")
}
if proto != nil {
t.Fatalf("finalizeProto returned proto %#v, want nil", proto)
}
if !strings.Contains(err.Error(), "invalid finalized prototype") {
t.Fatalf("finalizeProto error is %q, want invalid finalized prototype", err)
}
if !strings.Contains(err.Error(), "jump target 99 out of range") {
t.Fatalf("finalizeProto error is %q, want jump target detail", err)
}
}
func TestBytecodeFinalizerRejectsNonStringGlobalName(t *testing.T) {
var builder bytecodeBuilder
builder.emitLoadConst(0, NumberValue(1))
builder.emit(instruction{op: opLoadGlobal, a: 0, b: 0})
_, err := builder.finalizeProto(nil, 1, 0, false)
if err == nil {
t.Fatal("finalizeProto succeeded, want non-string global name error")
}
if !strings.Contains(err.Error(), "invalid finalized prototype") {
t.Fatalf("finalizeProto error is %q, want invalid finalized prototype", err)
}
if !strings.Contains(err.Error(), "constant index 0 is number, want string") {
t.Fatalf("finalizeProto error is %q, want non-string global detail", err)
}
}
func TestBytecodeFinalizerRejectsInvalidFieldConstantOperand(t *testing.T) {
var builder bytecodeBuilder
builder.emit(instruction{op: opNewTable, a: 0})
builder.emitLoadConst(1, NumberValue(2))
builder.emit(instruction{op: opSetField, a: 0, b: 99, c: 1})
_, err := builder.finalizeProto(nil, 2, 0, false)
if err == nil {
t.Fatal("finalizeProto succeeded, want invalid field constant operand error")
}
if !strings.Contains(err.Error(), "invalid finalized prototype") {
t.Fatalf("finalizeProto error is %q, want invalid finalized prototype", err)
}
if !strings.Contains(err.Error(), "constant index 99 out of range") {
t.Fatalf("finalizeProto error is %q, want constant range detail", err)
}
}
func TestBytecodeFinalizerRejectsInvalidStringFieldNumericBranchConstants(t *testing.T) {
t.Run("field", func(t *testing.T) {
var builder bytecodeBuilder
field := builder.addConstant(NumberValue(1))
value := builder.addConstant(NumberValue(0))
builder.emit(instruction{op: opGetStringField, a: 1, b: 0, c: field})
builder.emit(instruction{op: opJumpIfNotGreaterK, a: 1, b: value, d: 2})
_, err := builder.finalizeProto(nil, 2, 0, false)
if err == nil {
t.Fatal("finalizeProto succeeded, want non-string field error")
}
if !strings.Contains(err.Error(), "constant index 0 is number, want string") {
t.Fatalf("finalizeProto error is %q, want non-string field detail", err)
}
})
}
func TestBytecodeFinalizerRejectsInvalidCanonicalFieldConstant(t *testing.T) {
var builder bytecodeBuilder
field := builder.addConstant(NumberValue(1))
builder.emit(instruction{op: opSetStringField, a: 0, b: field, c: 1})
_, err := builder.finalizeProto(nil, 2, 0, false)
if err == nil {
t.Fatal("finalizeProto succeeded, want non-string field error")
}
if !strings.Contains(err.Error(), "constant index 0 is number, want string") {
t.Fatalf("finalizeProto error is %q, want non-string field detail", err)
}
}
func TestBytecodeFinalizerRejectsInvalidArithmeticRegister(t *testing.T) {
var builder bytecodeBuilder
builder.emitLoadConst(0, NumberValue(1))
builder.emit(instruction{op: opAdd, a: 0, b: 0, c: 99})
_, err := builder.finalizeProto(nil, 1, 0, false)
if err == nil {
t.Fatal("finalizeProto succeeded, want invalid arithmetic register error")
}
if !strings.Contains(err.Error(), "invalid finalized prototype") {
t.Fatalf("finalizeProto error is %q, want invalid finalized prototype", err)
}
if !strings.Contains(err.Error(), "register index 99 out of range") {
t.Fatalf("finalizeProto error is %q, want register range detail", err)
}
}
func TestBytecodeFinalizerRejectsInvalidCallArgumentSpan(t *testing.T) {
var builder bytecodeBuilder
builder.emit(instruction{op: opCall, a: 0, b: 1, c: 1, d: 1})
_, err := builder.finalizeProto(nil, 2, 0, false)
if err == nil {
t.Fatal("finalizeProto succeeded, want invalid call argument span error")
}
if !strings.Contains(err.Error(), "invalid finalized prototype") {
t.Fatalf("finalizeProto error is %q, want invalid finalized prototype", err)
}
if !strings.Contains(err.Error(), "call argument register range out of range") {
t.Fatalf("finalizeProto error is %q, want call argument range detail", err)
}
}
func TestCallValueNativeDoesNotAllocateCycleMap(t *testing.T) {
fn := nativeFuncValue(func(_ *globalEnv, _ []Value) ([]Value, error) {
return nil, nil
})
allocs := testing.AllocsPerRun(100, func() {
if _, err := callValue(fn, nil, nil); err != nil {
t.Fatalf("callValue returned error: %v", err)
}
})
if allocs != 0 {
t.Fatalf("native call allocated %.0f times, want no cycle-map allocation", allocs)
}
}
func TestMetatableWalkCommonCaseDoesNotAllocate(t *testing.T) {
if allocationInstrumentedTest() {
t.Skip("allocation budgets run only with the normal compiler/runtime instrumentation")
}
fallback := NewTable()
if err := fallback.Set(StringValue("hp"), NumberValue(25)); err != nil {
t.Fatalf("fallback.Set returned error: %v", err)
}
index := NewTable()
if err := index.Set(StringValue("__index"), TableValue(fallback)); err != nil {
t.Fatalf("index.Set returned error: %v", err)
}
object := NewTable()
object.setMetatable(index)
access := publicTableAccess()
key := StringValue("hp")
allocs := testing.AllocsPerRun(100, func() {
value, err := access.get(object, key)
if err != nil {
t.Fatalf("table access returned error: %v", err)
}
got, ok := value.Number()
if !ok || got != 25 {
t.Fatalf("table access returned %v (%t), want number 25", value, ok)
}
})
if allocs != 0 {
t.Fatalf("metatable walk allocated %.0f times, want no common-case allocation", allocs)
}
}
func TestMetatableWalkStillRejectsCycles(t *testing.T) {
left := NewTable()
right := NewTable()
leftMeta := NewTable()
rightMeta := NewTable()
if err := leftMeta.Set(StringValue("__index"), TableValue(right)); err != nil {
t.Fatalf("leftMeta.Set returned error: %v", err)
}
if err := rightMeta.Set(StringValue("__index"), TableValue(left)); err != nil {
t.Fatalf("rightMeta.Set returned error: %v", err)
}
left.setMetatable(leftMeta)
right.setMetatable(rightMeta)
_, err := publicTableAccess().get(left, StringValue("missing"))
if err == nil {
t.Fatal("table access succeeded, want cyclic __index error")
}
if !strings.Contains(err.Error(), "cyclic __index chain") {
t.Fatalf("table access error is %q, want cyclic __index detail", err)
}
}
func TestFunctionIndexFallbackResolvesOncePerShape(t *testing.T) {
first := nativeFuncValueWithID(baseToString, nativeFuncToString)
second := nativeFuncValueWithID(baseRawLenNative, nativeFuncRawLen)
metatable := NewTable()
metatable.setRawStringField("__index", first)
object := NewTable()
object.setMetatable(metatable)
index, ok, err := object.cachedIndexFallback()
if err != nil {
t.Fatalf("cachedIndexFallback returned error: %v", err)
}
if !ok || valueNativeID(index) != nativeFuncToString {
t.Fatalf("cachedIndexFallback = %#v (%t), want first function", index, ok)
}
index, ok, err = object.cachedIndexFallback()
if err != nil {
t.Fatalf("cachedIndexFallback second call returned error: %v", err)
}
if !ok || valueNativeID(index) != nativeFuncToString {
t.Fatalf("cachedIndexFallback second call = %#v (%t), want cached first function", index, ok)
}
metatable.setRawStringField("__index", second)
index, ok, err = object.cachedIndexFallback()
if err != nil {
t.Fatalf("cachedIndexFallback after mutation returned error: %v", err)
}
if !ok || valueNativeID(index) != nativeFuncRawLen {
t.Fatalf("cachedIndexFallback after mutation = %#v (%t), want refreshed second function", index, ok)
}
}
func TestNewindexFallbackChainMatchesLuauOrder(t *testing.T) {
proto, err := Compile(`
local log = {}
local root = {}
local middle = {}
setmetatable(root, {__newindex = middle})
setmetatable(middle, {__newindex = function(self, key, value)
log[#log + 1] = self == middle
log[#log + 1] = key
log[#log + 1] = value
end})
root.hp = 25
return log[1], log[2], log[3], rawget(root, "hp"), rawget(middle, "hp")
`)
if err != nil {
t.Fatalf("Compile returned error: %v", err)
}
results, err := Run(proto)
if err != nil {
t.Fatalf("Run returned error: %v", err)
}
if len(results) != 5 {
t.Fatalf("Run returned %d results, want 5", len(results))
}
if got, ok := results[0].Bool(); !ok || !got {
t.Fatalf("first result is %v (%t), want true", results[0], ok)
}
if got, ok := results[1].String(); !ok || got != "hp" {
t.Fatalf("second result is %v (%t), want hp", results[1], ok)
}
if got, ok := results[2].Number(); !ok || got != 25 {
t.Fatalf("third result is %v (%t), want 25", results[2], ok)
}
if !results[3].IsNil() {
t.Fatalf("fourth result is %s, want nil", results[3].Kind())
}
if !results[4].IsNil() {
t.Fatalf("fifth result is %s, want nil", results[4].Kind())
}
}
func TestBytecodeFinalizerRejectsInvalidClosureUpvalue(t *testing.T) {
child := newProto(
nil,
[]instruction{{op: opReturn, a: 0, b: 1}},
nil,
[]upvalueDesc{{local: true, index: 2}},
1,
0,
false,
)
var builder bytecodeBuilder
prototype := builder.addPrototype(child)
builder.emit(instruction{op: opClosure, a: 0, b: prototype})
builder.emit(instruction{op: opReturn, a: 0, b: 1})
_, err := builder.finalizeProto(nil, 1, 0, false)
if err == nil {
t.Fatal("finalizeProto succeeded, want invalid closure upvalue error")
}
if !strings.Contains(err.Error(), "invalid finalized prototype") {
t.Fatalf("finalizeProto error is %q, want invalid finalized prototype", err)
}
if !strings.Contains(err.Error(), "upvalue 0 local register index 2 out of range") {
t.Fatalf("finalizeProto error is %q, want closure upvalue range detail", err)
}
}
func TestBytecodeVerifierRejectsStaleEntryNilRegisters(t *testing.T) {
proto := newProto(
nil,
[]instruction{{op: opReturnOne, a: 1}},
nil,
nil,
2,
0,
false,
)
proto.entryNilRegisters = nil
err := verifyProto(proto)
if err == nil {
t.Fatal("verifyProto succeeded, want stale entry nil register error")
}
if !strings.Contains(err.Error(), "entry nil registers [] do not match finalized plan [1]") {
t.Fatalf("verifyProto error is %q, want entry nil register detail", err)
}
}
func TestRunDirectFrameArrayNextJumpUsesInlineArrayIterator(t *testing.T) {
proto, err := Compile(`
local values = {1, 2, 3, 4}
local total = 0
for _, value in values do
total = total + value * 2 + value % 2
end
return total
`)
if err != nil {
t.Fatalf("Compile returned error: %v", err)
}
var counts directFramePICCounts
thread := newVMThread(runtimeGlobals(nil))
thread.directFrameInstrumented = true
thread.directFramePICCounts = &counts
results, err := thread.run(proto, nil, nil)
if err != nil {
t.Fatalf("thread.run returned error: %v", err)
}
got, ok := results[0].Number()
if !ok || got != 22 {
t.Fatalf("thread.run result is %v (%t), want 22", got, ok)
}
if counts.arrayIteratorFastSteps == 0 {
t.Fatalf("array iterator fast steps = 0, want direct array iterator handling")
}
}
func TestRunDirectFrameArrayRowLoopMutationSideExitsBeforeMismatchedSlot(t *testing.T) {
proto, err := Compile(`
local rows = {
{cooldown = 2},
{other = 99, cooldown = 3},
{cooldown = 1},
}
local total = 0
for _, row in rows do
if row.cooldown > 0 then
row.cooldown = row.cooldown - 1
end
total = total + row.cooldown
end
return total
`)
if err != nil {
t.Fatalf("Compile returned error: %v", err)
}
var counts directFramePICCounts
thread := newVMThread(runtimeGlobals(nil))
thread.directFrameInstrumented = true
thread.directFramePICCounts = &counts
results, err := thread.run(proto, nil, nil)
if err != nil {
t.Fatalf("thread.run returned error: %v", err)
}
got, ok := results[0].Number()
if !ok || got != 3 {
t.Fatalf("thread.run result is %v (%t), want 3", got, ok)
}
}
func TestVMFrameAllocatesCellsOnlyForCapturedLocals(t *testing.T) {
child := newProto(
nil,
[]instruction{{op: opReturn, a: 0, b: 1}},
nil,
[]upvalueDesc{{local: true, index: 1}},
1,
0,
false,
)
proto := newProto(
nil,
[]instruction{
{op: opClosure, a: 2, b: 0},
{op: opReturn, a: 0, b: 1},
},
[]*Proto{child},
nil,
3,
0,
false,
)
frame := newVMFrame(proto, []Value{NumberValue(7)}, nil)
if got, want := len(frame.registers), 3; got != want {
t.Fatalf("frame has %d value registers, want %d", got, want)
}
if got, want := len(frame.cells), 3; got != want {
t.Fatalf("frame has %d capture cell slots, want %d", got, want)
}
if frame.cells[0] != nil {
t.Fatalf("register 0 has cell %#v, want ordinary value slot", frame.cells[0])
}
if frame.cells[1] == nil {
t.Fatal("register 1 has nil cell, want captured local cell")
}
if frame.cells[2] != nil {
t.Fatalf("register 2 has cell %#v, want ordinary value slot", frame.cells[2])
}
frame.setRegister(1, NumberValue(9))
got, ok := frame.cells[1].get().Number()
if !ok || got != 9 {
t.Fatalf("captured register cell is %v (%t), want number 9", got, ok)
}
}
func TestVMFrameAppliesDirectFixedResultDestinations(t *testing.T) {
proto := newProto(nil, []instruction{{op: opReturn, a: 0, b: 1}}, nil, nil, 3, 0, false)
frame := newVMFrame(proto, nil, nil)
frame.applyResultDestination(vmResultDestination{register: 1, count: 2}, []Value{NumberValue(7)})
first, firstOK := frame.registers[1].Number()
if !firstOK || first != 7 {
t.Fatalf("first fixed result is %v (%t), want number 7", first, firstOK)
}
if !frame.registers[2].IsNil() {
t.Fatalf("second fixed result is %s, want nil padding", frame.registers[2].Kind())
}
frame.applyInlineResultDestination(
vmResultDestination{register: 0, count: 1},
[2]Value{NumberValue(11), NumberValue(13)},
0,
)
if !frame.registers[0].IsNil() {
t.Fatalf("zero inline result is %s, want nil padding", frame.registers[0].Kind())
}
}
func TestVMFrameOwnsVarargArgumentWindow(t *testing.T) {
proto := newProto(
nil,
[]instruction{{op: opReturn, a: 0, b: 1}},
nil,
nil,
1,
1,
true,
)
args := []Value{StringValue("head"), NumberValue(1), NumberValue(2)}
frame := newVMFrame(proto, args, nil)
args[1] = NumberValue(99)
if got, want := frame.varargLen(), 2; got != want {
t.Fatalf("vararg frame count is %d, want %d", got, want)
}
got, ok := frame.varargAt(0).Number()
if !ok || got != 1 {
t.Fatalf("vararg frame value is %v (%t), want owned number 1 after input mutation", got, ok)
}
}
func TestRunVarargWindowPreservesNilFillAndCount(t *testing.T) {
proto, err := Compile(`
local function collect(...)
local a, b, c, d = ...
return a, b, c, d, select("#", ...)
end
return collect(1, nil, 3)
`)