forked from Shopify/go-lua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.go
More file actions
1809 lines (1665 loc) · 48 KB
/
code.go
File metadata and controls
1809 lines (1665 loc) · 48 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 lua
import (
"fmt"
"math"
)
const (
oprMinus = iota
oprBNot // Lua 5.3: bitwise NOT ~
oprNot
oprLength
oprNoUnary
)
const (
noJump = -1
noRegister = maxArgA
maxLocalVariables = 200
)
// Variable declaration kinds (Lua 5.4 attributes)
const (
varRegular = 0 // VDKREG: regular variable
varConst = 1 // RDKCONST: <const> variable
varToClose = 2 // RDKTOCLOSE: <close> variable
varCTC = 3 // RDKCTC: compile-time constant
)
const (
oprAdd = iota
oprSub
oprMul
oprMod // Lua 5.3: MOD before DIV
oprPow
oprDiv
oprIDiv // Lua 5.3: integer division //
oprBAnd // Lua 5.3: bitwise AND &
oprBOr // Lua 5.3: bitwise OR |
oprBXor // Lua 5.3: bitwise XOR ~
oprShl // Lua 5.3: shift left <<
oprShr // Lua 5.3: shift right >>
oprConcat
oprEq
oprLT
oprLE
oprNE
oprGT
oprGE
oprAnd
oprOr
oprNoBinary
)
const (
kindVoid = iota // no value
kindNil
kindTrue
kindFalse
kindConstant // info = index of constant
kindNumber // value = numerical value
kindInteger // ivalue = integer value (Lua 5.3)
kindString // strVal = string value (Lua 5.4)
kindNonRelocatable // info = result register
kindLocal // info = local register
kindUpValue // info = index of upvalue
kindIndexed // table = register, index = register
kindIndexUp // table = upvalue index, index = string constant index
kindIndexInt // table = register, index = integer key
kindIndexStr // table = register, index = string constant index
kindJump // info = instruction pc
kindRelocatable // info = instruction pc
kindCall // info = instruction pc
kindVarArg // info = instruction pc
)
var kinds []string = []string{
"void",
"nil",
"true",
"false",
"constant",
"number",
"integer",
"string",
"nonrelocatable",
"local",
"upvalue",
"indexed",
"indexup",
"indexint",
"indexstr",
"jump",
"relocatable",
"call",
"vararg",
}
type exprDesc struct {
kind int
index int // register/constant index
table int // register or upvalue
info int
t, f int // patch lists for 'exit when true/false'
value float64 // for kindNumber
ivalue int64 // for kindInteger (Lua 5.3)
strVal string // for kindString (Lua 5.4)
ctcName string // variable name for CTC constants (for checkReadOnly error messages)
}
type assignmentTarget struct {
previous *assignmentTarget
exprDesc
}
type label struct {
name string
pc, line int
activeVariableCount int
close bool // 5.4: needs CLOSE when goto is resolved
}
type block struct {
previous *block
firstLabel, firstGoto int
activeVariableCount int
hasUpValue, isLoop bool
insidetbc bool // Lua 5.4: inside scope of TBC variable (inherited by child blocks)
}
type function struct {
constantLookup map[value]int
f *prototype
previous *function
p *parser
block *block
jumpPC, lastTarget int
freeRegisterCount int
activeVariableCount int
firstLocal int
firstLabel int // Lua 5.4: first label index for this function (like C Lua's fs->firstlabel)
previousLine int // Lua 5.4: for relative line info encoding (per-function, like C Lua's FuncState)
iwthabs int // instructions without absolute line info
needClose bool // Lua 5.4: function has TBC variables (affects RETURN k-bit)
}
func (f *function) OpenFunction(line int) {
f.f.prototypes = append(f.f.prototypes, prototype{source: f.p.source, maxStackSize: 2, lineDefined: line})
f.p.function = &function{f: &f.f.prototypes[len(f.f.prototypes)-1], constantLookup: make(map[value]int), previous: f, p: f.p, jumpPC: noJump, firstLocal: len(f.p.activeVariables), firstLabel: len(f.p.activeLabels), previousLine: line}
f.p.function.EnterBlock(false)
}
func (f *function) CloseFunction() exprDesc {
e := f.previous.ExpressionToNextRegister(makeExpression(kindRelocatable, f.previous.encodeABx(opClosure, 0, len(f.previous.f.prototypes)-1)))
f.ReturnNone()
f.LeaveBlock()
f.assert(f.block == nil)
f.finish()
f.p.function = f.previous
return e
}
func (f *function) EnterBlock(isLoop bool) {
// TODO www.lua.org uses a trick here to stack allocate the block, and chain blocks in the stack
parentTBC := f.block != nil && f.block.insidetbc
f.block = &block{previous: f.block, firstLabel: len(f.p.activeLabels), firstGoto: len(f.p.pendingGotos), activeVariableCount: f.activeVariableCount, isLoop: isLoop, insidetbc: parentTBC}
f.assert(f.freeRegisterCount == f.regLevel())
}
func (f *function) undefinedGotoError(g label) {
if isReserved(g.name) {
f.semanticError(fmt.Sprintf("<%s> at line %d not inside a loop", g.name, g.line))
} else {
f.semanticError(fmt.Sprintf("no visible label '%s' for <goto> at line %d", g.name, g.line))
}
}
func (f *function) LocalVariable(i int) *localVariable {
index := f.p.activeVariables[f.firstLocal+i]
return &f.f.localVariables[index]
}
func (f *function) AdjustLocalVariables(n int) {
for f.activeVariableCount += n; n != 0; n-- {
f.LocalVariable(f.activeVariableCount - n).startPC = pc(len(f.f.code))
}
}
func (f *function) removeLocalVariables(level int) {
for i := level; i < f.activeVariableCount; i++ {
f.LocalVariable(i).endPC = pc(len(f.f.code))
}
f.p.activeVariables = f.p.activeVariables[:len(f.p.activeVariables)-(f.activeVariableCount-level)]
f.activeVariableCount = level
}
func (f *function) MakeLocalVariable(name string) {
r := len(f.f.localVariables)
f.f.localVariables = append(f.f.localVariables, localVariable{name: name})
f.p.checkLimit(len(f.p.activeVariables)+1-f.firstLocal, maxLocalVariables, "local variables")
f.p.activeVariables = append(f.p.activeVariables, r)
}
// markToBeClose marks the current block as having a to-be-closed variable.
// This matches C Lua 5.4's marktobeclosed: only marks the current block,
// plus sets the function-level needClose flag for RETURN k-bit.
func (f *function) markToBeClose() {
bl := f.block
bl.hasUpValue = true // ensures OP_CLOSE at block exit
bl.insidetbc = true
f.needClose = true // function-level: affects RETURN k-bit
}
// regLevelAt returns the register level at variable scope level nvar.
// CTC variables don't occupy registers, so they are skipped.
func (f *function) regLevelAt(nvar int) int {
count := 0
for i := 0; i < nvar; i++ {
if f.LocalVariable(i).kind != varCTC {
count++
}
}
return count
}
// regLevel returns the current register level (number of register-occupying variables).
func (f *function) regLevel() int {
return f.regLevelAt(f.activeVariableCount)
}
// varToReg converts a variable index to its register index by counting
// non-CTC variables before it.
func (f *function) varToReg(vidx int) int {
reg := 0
for i := 0; i < vidx; i++ {
if f.LocalVariable(i).kind != varCTC {
reg++
}
}
return reg
}
// exp2const checks if an expression is a compile-time constant and returns its value.
func (f *function) exp2const(e exprDesc) (value, bool) {
if e.hasJumps() {
return nil, false
}
switch e.kind {
case kindNil:
return nil, true
case kindTrue:
return true, true
case kindFalse:
return false, true
case kindInteger:
return e.ivalue, true
case kindNumber:
return e.value, true
case kindString:
return e.strVal, true
default:
return nil, false
}
}
// const2exp converts a compile-time constant value back to an expression.
func const2exp(v value) exprDesc {
switch v := v.(type) {
case nil:
return makeExpression(kindNil, 0)
case bool:
if v {
return makeExpression(kindTrue, 0)
}
return makeExpression(kindFalse, 0)
case int64:
e := makeExpression(kindInteger, 0)
e.ivalue = v
return e
case float64:
e := makeExpression(kindNumber, 0)
e.value = v
return e
case string:
e := makeExpression(kindString, 0)
e.strVal = v
return e
default:
return makeExpression(kindNil, 0)
}
}
// isConstantKind returns true if the expression kind is a compile-time constant.
func isConstantKind(k int) bool {
return k == kindNil || k == kindTrue || k == kindFalse ||
k == kindInteger || k == kindNumber || k == kindString
}
// checkReadOnly checks if an expression refers to a read-only variable (<const> or <close>).
func (f *function) checkReadOnly(e exprDesc) {
// CTC constant expressions carry their variable name for error messages
if e.ctcName != "" {
f.semanticError(fmt.Sprintf(
"attempt to assign to const variable '%s'", e.ctcName))
}
switch e.kind {
case kindLocal:
lv := f.LocalVariable(e.info)
if lv.kind != varRegular {
f.semanticError(fmt.Sprintf(
"attempt to assign to const variable '%s'", lv.name))
}
case kindUpValue:
uv := f.f.upValues[e.info]
if uv.kind != varRegular {
f.semanticError(fmt.Sprintf(
"attempt to assign to const variable '%s'", uv.name))
}
}
}
func (f *function) MakeGoto(name string, line, pc int) {
f.p.pendingGotos = append(f.p.pendingGotos, label{name: name, line: line, pc: pc, activeVariableCount: f.activeVariableCount})
f.findLabel(len(f.p.pendingGotos) - 1)
}
func (f *function) MakeLabel(name string, line int) int {
// Mark current position as a jump target to prevent LOADNIL optimization
// from merging across labels (bug fix for 5.2 -> 5.3.2)
f.lastTarget = len(f.f.code)
f.p.activeLabels = append(f.p.activeLabels, label{name: name, line: line, pc: len(f.f.code), activeVariableCount: f.activeVariableCount})
return len(f.p.activeLabels) - 1
}
func (f *function) closeGoto(i int, l label) {
g := f.p.pendingGotos[i]
if f.assert(g.name == l.name); g.activeVariableCount < l.activeVariableCount {
f.semanticError(fmt.Sprintf("<goto %s> at line %d jumps into the scope of local '%s'", g.name, g.line, f.LocalVariable(g.activeVariableCount).name))
}
f.PatchList(g.pc, l.pc)
copy(f.p.pendingGotos[i:], f.p.pendingGotos[i+1:])
f.p.pendingGotos = f.p.pendingGotos[:len(f.p.pendingGotos)-1]
}
func (f *function) findLabel(i int) int {
g, b := f.p.pendingGotos[i], f.block
// Lua 5.4: search all labels in the entire function (not just current block)
for _, l := range f.p.activeLabels[f.firstLabel:] {
if l.name == g.name {
if g.activeVariableCount > l.activeVariableCount && (b.hasUpValue || len(f.p.activeLabels) > b.firstLabel) {
f.p.pendingGotos[i].close = true
}
f.closeGoto(i, l)
return 0
}
}
return 1
}
// findExistingLabel searches for an already-declared label with the given name
// in the current function. Returns a pointer to the label or nil if not found.
// Used by gotoStatement to detect backward jumps (Lua 5.4: C Lua's findlabel).
func (f *function) findExistingLabel(name string) *label {
for i := f.firstLabel; i < len(f.p.activeLabels); i++ {
if f.p.activeLabels[i].name == name {
return &f.p.activeLabels[i]
}
}
return nil
}
func (f *function) CheckRepeatedLabel(name string) {
// Lua 5.4: check all labels in the entire function (not just current block)
for _, l := range f.p.activeLabels[f.firstLabel:] {
if l.name == name {
f.semanticError(fmt.Sprintf("label '%s' already defined on line %d", name, l.line))
}
}
}
func (f *function) FindGotos(label int) bool {
needClose := false
for i, l := f.block.firstGoto, f.p.activeLabels[label]; i < len(f.p.pendingGotos); {
if f.p.pendingGotos[i].name == l.name {
needClose = needClose || f.p.pendingGotos[i].close
f.closeGoto(i, l)
} else {
i++
}
}
return needClose
}
func (f *function) moveGotosOut(b block) {
for i := b.firstGoto; i < len(f.p.pendingGotos); i += f.findLabel(i) {
if f.p.pendingGotos[i].activeVariableCount > b.activeVariableCount {
if b.hasUpValue {
f.p.pendingGotos[i].close = true
}
f.p.pendingGotos[i].activeVariableCount = b.activeVariableCount
}
}
}
func (f *function) LeaveBlock() {
b := f.block
hasClose := false
stklevel := f.regLevelAt(b.activeVariableCount)
f.removeLocalVariables(b.activeVariableCount)
f.assert(b.activeVariableCount == f.activeVariableCount)
if b.isLoop {
hasClose = f.breakLabel() // close pending breaks
}
if !hasClose && b.previous != nil && b.hasUpValue {
f.EncodeABC(opClose, stklevel, 0, 0)
}
f.freeRegisterCount = stklevel
f.p.activeLabels = f.p.activeLabels[:b.firstLabel]
f.block = b.previous
if b.previous != nil { // inner block
f.moveGotosOut(*b) // update pending gotos to outer block
} else if b.firstGoto < len(f.p.pendingGotos) { // pending gotos in outer block
f.undefinedGotoError(f.p.pendingGotos[b.firstGoto])
}
}
func abs(i int) int {
if i < 0 {
return -i
}
return i
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func not(b int) int {
if b == 0 {
return 1
}
return 0
}
func makeExpression(kind, info int) exprDesc {
return exprDesc{f: noJump, t: noJump, kind: kind, info: info}
}
func (f *function) semanticError(message string) {
f.p.t = 0 // remove "near to" from final message
f.p.syntaxError(message)
}
func (f *function) breakLabel() bool {
needClose := f.FindGotos(f.MakeLabel("break", 0))
if needClose {
f.EncodeABC(opClose, f.regLevel(), 0, 0)
}
return needClose
}
func (f *function) unreachable() { f.assert(false) }
func (f *function) assert(cond bool) { f.p.l.assert(cond) }
func (f *function) Instruction(e exprDesc) *instruction { return &f.f.code[e.info] }
func (e exprDesc) hasJumps() bool { return e.t != e.f }
func (e exprDesc) isNumeral() bool {
return (e.kind == kindNumber || e.kind == kindInteger) && e.t == noJump && e.f == noJump
}
func (e exprDesc) isVariable() bool {
return kindLocal <= e.kind && e.kind <= kindIndexStr
}
func (e exprDesc) hasMultipleReturns() bool { return e.kind == kindCall || e.kind == kindVarArg }
func (f *function) assertEqual(a, b interface{}) {
if a != b {
panic(fmt.Sprintf("%v != %v", a, b))
}
}
const (
lineInfoAbs = -0x80 // marker for absolute line info in lineInfo
limLineDiff = 0x80 // max absolute delta that fits in int8
maxIWthAbs = 128 // max instructions without absolute line info
)
func (f *function) encode(i instruction) int {
f.assert(len(f.f.code) == len(f.f.lineInfo))
f.dischargeJumpPC()
f.f.code = append(f.f.code, i)
f.saveLineInfo(f.p.lastLine)
return len(f.f.code) - 1
}
func (f *function) saveLineInfo(line int) {
lineDiff := line - f.previousLine
pc := len(f.f.code) - 1
if lineDiff < -limLineDiff+1 || lineDiff >= limLineDiff || f.iwthabs >= maxIWthAbs {
// Need absolute line info entry
f.f.absLineInfos = append(f.f.absLineInfos, absLineInfo{pc: pc, line: line})
lineDiff = lineInfoAbs
f.iwthabs = 1
} else {
f.iwthabs++
}
f.f.lineInfo = append(f.f.lineInfo, int8(lineDiff))
f.previousLine = line
}
func (f *function) dropLastInstruction() {
f.assert(len(f.f.code) == len(f.f.lineInfo))
// Remove line info for the last instruction (like C Lua's removelastlineinfo)
lastIdx := len(f.f.lineInfo) - 1
if f.f.lineInfo[lastIdx] != lineInfoAbs {
// Relative line info: restore previousLine
f.previousLine -= int(f.f.lineInfo[lastIdx])
f.iwthabs--
} else {
// Absolute line info: remove the entry
f.f.absLineInfos = f.f.absLineInfos[:len(f.f.absLineInfos)-1]
// Force next line info to be absolute
f.iwthabs = maxIWthAbs + 1
}
f.f.code = f.f.code[:len(f.f.code)-1]
f.f.lineInfo = f.f.lineInfo[:len(f.f.lineInfo)-1]
}
func (f *function) EncodeABC(op opCode, a, b, c int) int {
f.assert(opMode(op) == iABC)
f.assert(a <= maxArgA && b <= maxArgB && c <= maxArgC)
return f.encode(createABCk(op, a, b, c, 0))
}
func (f *function) EncodeABCk(op opCode, a, b, c, k int) int {
f.assert(opMode(op) == iABC)
f.assert(a <= maxArgA && b <= maxArgB && c <= maxArgC)
return f.encode(createABCk(op, a, b, c, k))
}
func (f *function) encodeABx(op opCode, a, bx int) int {
f.assert(opMode(op) == iABx || opMode(op) == iAsBx)
f.assert(a <= maxArgA && bx <= maxArgBx)
return f.encode(createABx(op, a, bx))
}
func (f *function) encodeAsBx(op opCode, a, sbx int) int { return f.encodeABx(op, a, sbx+maxArgSBx) }
func (f *function) encodeExtraArg(a int) int {
f.assert(a <= maxArgAx)
return f.encode(createAx(opExtraArg, a))
}
func (f *function) EncodeConstant(r, constant int) int {
if constant <= maxArgBx {
return f.encodeABx(opLoadConstant, r, constant)
}
// Use opLoadConstantEx (LOADKX) for constants with index > maxArgBx
// The constant index is stored in the following EXTRAARG instruction
pc := f.encodeABx(opLoadConstantEx, r, 0)
f.encodeExtraArg(constant)
return pc
}
func (f *function) EncodeString(s string) exprDesc {
e := makeExpression(kindString, 0)
e.strVal = s
return e
}
func (f *function) loadNil(from, n int) {
if len(f.f.code) > f.lastTarget { // no jumps to current position
if previous := &f.f.code[len(f.f.code)-1]; previous.opCode() == opLoadNil {
if pf, pl, l := previous.a(), previous.a()+previous.b(), from+n-1; pf <= from && from <= pl+1 || from <= pf && pf <= l+1 { // can connect both
from, l = min(from, pf), max(l, pl)
previous.setA(from)
previous.setB(l - from)
return
}
}
}
f.EncodeABC(opLoadNil, from, n-1, 0)
}
func (f *function) encodeJ(op opCode, j int) int {
f.assert(opMode(op) == isJ)
return f.encode(createSJ(op, j, 0))
}
func (f *function) Jump() int {
f.assert(f.isJumpListWalkable(f.jumpPC))
jumpPC := f.jumpPC
f.jumpPC = noJump
return f.Concatenate(f.encodeJ(opJump, noJump), jumpPC)
}
func (f *function) JumpTo(target int) { f.PatchList(f.Jump(), target) }
func (f *function) ReturnNone() {
k := 0
if f.needClose {
k = 1
}
f.EncodeABCk(opReturn0, f.regLevel(), 1, 0, k)
}
func (f *function) SetMultipleReturns(e exprDesc) { f.setReturns(e, MultipleReturns) }
func (f *function) Return(e exprDesc, resultCount int) {
k := 0
if f.needClose {
k = 1
}
if e.hasMultipleReturns() {
if f.SetMultipleReturns(e); e.kind == kindCall && resultCount == 1 && !f.needClose {
f.Instruction(e).setOpCode(opTailCall)
f.assert(f.Instruction(e).a() == f.regLevel())
}
f.EncodeABCk(opReturn, f.regLevel(), MultipleReturns+1, 0, k)
} else if resultCount == 1 {
first := f.ExpressionToAnyRegister(e).info
f.EncodeABCk(opReturn1, first, 2, 0, k)
} else {
_ = f.ExpressionToNextRegister(e)
f.assert(resultCount == f.freeRegisterCount-f.regLevel())
f.EncodeABCk(opReturn, f.regLevel(), resultCount+1, 0, k)
}
}
func (f *function) conditionalJump(op opCode, a, b, c, k int) int {
f.EncodeABCk(op, a, b, c, k)
return f.Jump()
}
func (f *function) fixJump(pc, dest int) {
f.assert(f.isJumpListWalkable(pc))
f.assert(dest != noJump)
offset := dest - (pc + 1)
if abs(offset) > offsetSJ {
f.p.syntaxError("control structure too long")
}
f.assert(f.f.code[pc].opCode() == opJump)
f.f.code[pc].setSJ(offset)
}
func (f *function) Label() int {
f.lastTarget = len(f.f.code)
return f.lastTarget
}
func (f *function) jump(pc int) int {
f.assert(f.isJumpListWalkable(pc))
if offset := f.f.code[pc].sJ(); offset != noJump {
return pc + 1 + offset
}
return noJump
}
func (f *function) isJumpListWalkable(list int) bool {
if list == noJump {
return true
}
if list < 0 || list >= len(f.f.code) {
return false
}
offset := f.f.code[list].sJ()
return offset == noJump || f.isJumpListWalkable(list+1+offset)
}
func (f *function) jumpControl(pc int) *instruction {
if pc >= 1 && testTMode(f.f.code[pc-1].opCode()) {
return &f.f.code[pc-1]
}
return &f.f.code[pc]
}
func (f *function) needValue(list int) bool {
f.assert(f.isJumpListWalkable(list))
for ; list != noJump; list = f.jump(list) {
if f.jumpControl(list).opCode() != opTestSet {
return true
}
}
return false
}
func (f *function) patchTestRegister(node, register int) bool {
if i := f.jumpControl(node); i.opCode() != opTestSet {
return false
} else if register != noRegister && register != i.b() {
i.setA(register)
} else {
*i = createABCk(opTest, i.b(), 0, 0, i.k())
}
return true
}
func (f *function) removeValues(list int) {
f.assert(f.isJumpListWalkable(list))
for ; list != noJump; list = f.jump(list) {
_ = f.patchTestRegister(list, noRegister)
}
}
func (f *function) patchListHelper(list, target, register, defaultTarget int) {
f.assert(f.isJumpListWalkable(list))
for list != noJump {
next := f.jump(list)
if f.patchTestRegister(list, register) {
f.fixJump(list, target)
} else {
f.fixJump(list, defaultTarget)
}
list = next
}
}
func (f *function) dischargeJumpPC() {
f.assert(f.isJumpListWalkable(f.jumpPC))
f.patchListHelper(f.jumpPC, len(f.f.code), noRegister, len(f.f.code))
f.jumpPC = noJump
}
func (f *function) PatchList(list, target int) {
if target == len(f.f.code) {
f.PatchToHere(list)
} else {
f.assert(target < len(f.f.code))
f.patchListHelper(list, target, noRegister, target)
}
}
// PatchClose is a no-op in 5.4. In 5.3, it patched JMP's A register for closing
// upvalues. In 5.4, JMP has isJ format (no A register), and explicit OP_CLOSE
// instructions are emitted instead.
func (f *function) PatchClose(list, level int) {
// No-op: callers now emit opClose directly or set close flags on gotos
}
func (f *function) PatchToHere(list int) {
f.assert(f.isJumpListWalkable(list))
f.assert(f.isJumpListWalkable(f.jumpPC))
f.Label()
f.jumpPC = f.Concatenate(f.jumpPC, list)
f.assert(f.isJumpListWalkable(f.jumpPC))
}
func (f *function) Concatenate(l1, l2 int) int {
f.assert(f.isJumpListWalkable(l1))
switch {
case l2 == noJump:
case l1 == noJump:
return l2
default:
list := l1
for next := f.jump(list); next != noJump; list, next = next, f.jump(next) {
}
f.fixJump(list, l2)
}
return l1
}
func (f *function) addConstant(k, v value) int {
if index, ok := f.constantLookup[k]; ok && f.f.constants[index] == v {
return index
}
index := len(f.f.constants)
f.constantLookup[k] = index
f.f.constants = append(f.f.constants, v)
return index
}
func (f *function) NumberConstant(n float64) int {
if n == 0.0 || math.IsNaN(n) {
return f.addConstant(math.Float64bits(n), n)
}
return f.addConstant(n, n)
}
// IntegerConstant adds an integer constant to the constant table (Lua 5.3)
func (f *function) IntegerConstant(n int64) int {
// Use a distinct key type to differentiate int64 from float64
type intKey struct{ v int64 }
return f.addConstant(intKey{n}, n)
}
func (f *function) CheckStack(n int) {
if n += f.freeRegisterCount; n >= maxStack {
f.p.syntaxError("function or expression too complex")
} else if n > f.f.maxStackSize {
f.f.maxStackSize = n
}
}
func (f *function) ReserveRegisters(n int) {
f.CheckStack(n)
f.freeRegisterCount += n
}
func (f *function) freeRegister(r int) {
if r >= f.regLevel() {
f.freeRegisterCount--
f.assertEqual(r, f.freeRegisterCount)
}
}
func (f *function) freeExpression(e exprDesc) {
if e.kind == kindNonRelocatable {
f.freeRegister(e.info)
}
}
// freeExpressions frees two expressions in the correct LIFO order (higher register first).
func (f *function) freeExpressions(e1, e2 exprDesc) {
r1 := -1
r2 := -1
if e1.kind == kindNonRelocatable {
r1 = e1.info
}
if e2.kind == kindNonRelocatable {
r2 = e2.info
}
if r1 > r2 {
f.freeRegister(r1)
if r2 >= 0 {
f.freeRegister(r2)
}
} else {
if r2 >= 0 {
f.freeRegister(r2)
}
if r1 >= 0 {
f.freeRegister(r1)
}
}
}
func (f *function) stringConstant(s string) int { return f.addConstant(s, s) }
func (f *function) booleanConstant(b bool) int { return f.addConstant(b, b) }
func (f *function) nilConstant() int { return f.addConstant(f, nil) }
func (f *function) setReturns(e exprDesc, resultCount int) {
if e.kind == kindCall {
f.Instruction(e).setC(resultCount + 1)
} else if e.kind == kindVarArg {
f.Instruction(e).setC(resultCount + 1) // 5.4: VARARG uses C field
f.Instruction(e).setA(f.freeRegisterCount)
f.ReserveRegisters(1)
}
}
func (f *function) SetReturn(e exprDesc) exprDesc {
if e.kind == kindCall {
e.kind, e.info = kindNonRelocatable, f.Instruction(e).a()
} else if e.kind == kindVarArg {
f.Instruction(e).setC(2) // 5.4: VARARG uses C field
e.kind = kindRelocatable
}
return e
}
func (f *function) DischargeVariables(e exprDesc) exprDesc {
switch e.kind {
case kindLocal:
e.info = f.varToReg(e.info) // convert variable index to register
e.kind = kindNonRelocatable
case kindUpValue:
e.kind, e.info = kindRelocatable, f.EncodeABC(opGetUpValue, 0, e.info, 0)
case kindString:
e.kind, e.info = kindConstant, f.stringConstant(e.strVal)
case kindIndexUp:
e.kind, e.info = kindRelocatable, f.EncodeABC(opGetTableUp, 0, e.table, e.index)
case kindIndexInt:
f.freeRegister(e.table)
e.kind, e.info = kindRelocatable, f.EncodeABC(opGetI, 0, e.table, e.index)
case kindIndexStr:
f.freeRegister(e.table)
e.kind, e.info = kindRelocatable, f.EncodeABC(opGetField, 0, e.table, e.index)
case kindIndexed:
// Free in LIFO order (higher register first), like C Lua's freeregs()
if e.table > e.index {
f.freeRegister(e.table)
f.freeRegister(e.index)
} else {
f.freeRegister(e.index)
f.freeRegister(e.table)
}
e.kind, e.info = kindRelocatable, f.EncodeABC(opGetTable, 0, e.table, e.index)
case kindVarArg, kindCall:
e = f.SetReturn(e)
}
return e
}
func (f *function) dischargeToRegister(e exprDesc, r int) exprDesc {
switch e = f.DischargeVariables(e); e.kind {
case kindNil:
f.loadNil(r, 1)
case kindFalse:
f.EncodeABC(opLoadFalse, r, 0, 0)
case kindTrue:
f.EncodeABC(opLoadTrue, r, 0, 0)
case kindConstant:
f.EncodeConstant(r, e.info)
case kindNumber:
if fi, ok := floatToInteger(e.value); ok && fi >= -maxArgSBx && fi <= maxArgSBx+1 && !(fi == 0 && math.Signbit(e.value)) {
f.encodeAsBx(opLoadF, r, int(fi))
} else {
f.EncodeConstant(r, f.NumberConstant(e.value))
}
case kindInteger:
if e.ivalue >= -maxArgSBx && e.ivalue <= maxArgSBx+1 {
f.encodeAsBx(opLoadI, r, int(e.ivalue))
} else {
f.EncodeConstant(r, f.IntegerConstant(e.ivalue))
}
case kindString:
f.EncodeConstant(r, f.stringConstant(e.strVal))
case kindRelocatable:
f.Instruction(e).setA(r)
case kindNonRelocatable:
if r != e.info {
f.EncodeABC(opMove, r, e.info, 0)
}
default:
f.assert(e.kind == kindVoid || e.kind == kindJump)
return e
}
e.kind, e.info = kindNonRelocatable, r
return e
}
func (f *function) dischargeToAnyRegister(e exprDesc) exprDesc {
if e.kind != kindNonRelocatable {
f.ReserveRegisters(1)
e = f.dischargeToRegister(e, f.freeRegisterCount-1)
}
return e
}
func (f *function) encodeLabel(a, b, jump int) int {
f.Label()
// Lua 5.4: opLoadFalseSkip produces false and skips next,
// opLoadTrue produces true. Used for boolean coercion.
if b != 0 {
return f.EncodeABC(opLoadTrue, a, 0, 0)
}
if jump != 0 {
return f.EncodeABC(opLoadFalseSkip, a, 0, 0)
}
return f.EncodeABC(opLoadFalse, a, 0, 0)
}
func (f *function) expressionToRegister(e exprDesc, r int) exprDesc {
if e = f.dischargeToRegister(e, r); e.kind == kindJump {
e.t = f.Concatenate(e.t, e.info)
}
if e.hasJumps() {
loadFalse, loadTrue := noJump, noJump
if f.needValue(e.t) || f.needValue(e.f) {
jump := noJump
if e.kind != kindJump {
jump = f.Jump()
}
loadFalse, loadTrue = f.encodeLabel(r, 0, 1), f.encodeLabel(r, 1, 0)
f.PatchToHere(jump)
}
end := f.Label()
f.patchListHelper(e.f, end, r, loadFalse)
f.patchListHelper(e.t, end, r, loadTrue)
}
e.f, e.t, e.info, e.kind = noJump, noJump, r, kindNonRelocatable
return e
}
func (f *function) ExpressionToNextRegister(e exprDesc) exprDesc {
e = f.DischargeVariables(e)
f.freeExpression(e)
f.ReserveRegisters(1)
return f.expressionToRegister(e, f.freeRegisterCount-1)
}
func (f *function) ExpressionToAnyRegister(e exprDesc) exprDesc {
if e = f.DischargeVariables(e); e.kind == kindNonRelocatable {
if !e.hasJumps() {
return e
}
if e.info >= f.regLevel() {
return f.expressionToRegister(e, e.info)
}
}
return f.ExpressionToNextRegister(e)
}
func (f *function) ExpressionToAnyRegisterOrUpValue(e exprDesc) exprDesc {