forked from yuin/gopher-lua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_state.go
2093 lines (1853 loc) · 46.9 KB
/
_state.go
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 (
"context"
"fmt"
"io"
"math"
"os"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/yuin/gopher-lua/parse"
)
const MultRet = -1
const RegistryIndex = -10000
const EnvironIndex = -10001
const GlobalsIndex = -10002
/* ApiError {{{ */
type ApiError struct {
Type ApiErrorType
Object LValue
StackTrace string
// Underlying error. This attribute is set only if the Type is ApiErrorFile or ApiErrorSyntax
Cause error
}
func newApiError(code ApiErrorType, object LValue) *ApiError {
return &ApiError{code, object, "", nil}
}
func newApiErrorS(code ApiErrorType, message string) *ApiError {
return newApiError(code, LString(message))
}
func newApiErrorE(code ApiErrorType, err error) *ApiError {
return &ApiError{code, LString(err.Error()), "", err}
}
func (e *ApiError) Error() string {
if len(e.StackTrace) > 0 {
return fmt.Sprintf("%s\n%s", e.Object.String(), e.StackTrace)
}
return e.Object.String()
}
type ApiErrorType int
const (
ApiErrorSyntax ApiErrorType = iota
ApiErrorFile
ApiErrorRun
ApiErrorError
ApiErrorPanic
)
/* }}} */
/* ResumeState {{{ */
type ResumeState int
const (
ResumeOK ResumeState = iota
ResumeYield
ResumeError
)
/* }}} */
/* P {{{ */
type P struct {
Fn LValue
NRet int
Protect bool
Handler *LFunction
}
/* }}} */
/* Options {{{ */
// Options is a configuration that is used to create a new LState.
type Options struct {
// Call stack size. This defaults to `lua.CallStackSize`.
CallStackSize int
// Data stack size. This defaults to `lua.RegistrySize`.
RegistrySize int
// Allow the registry to grow from the registry size specified up to a value of RegistryMaxSize. A value of 0
// indicates no growth is permitted. The registry will not shrink again after any growth.
RegistryMaxSize int
// If growth is enabled, step up by an additional `RegistryGrowStep` each time to avoid having to resize too often.
// This defaults to `lua.RegistryGrowStep`
RegistryGrowStep int
// Controls whether or not libraries are opened by default
SkipOpenLibs bool
// Tells whether a Go stacktrace should be included in a Lua stacktrace when panics occur.
IncludeGoStackTrace bool
// If `MinimizeStackMemory` is set, the call stack will be automatically grown or shrank up to a limit of
// `CallStackSize` in order to minimize memory usage. This does incur a slight performance penalty.
MinimizeStackMemory bool
}
/* }}} */
/* Debug {{{ */
type Debug struct {
frame *callFrame
Name string
What string
Source string
CurrentLine int
NUpvalues int
LineDefined int
LastLineDefined int
}
/* }}} */
/* callFrame {{{ */
type callFrame struct {
Idx int
Fn *LFunction
Parent *callFrame
Pc int
Base int
LocalBase int
ReturnBase int
NArgs int
NRet int
TailCall int
}
type callFrameStack interface {
Push(v callFrame)
Pop() *callFrame
Last() *callFrame
SetSp(sp int)
Sp() int
At(sp int) *callFrame
IsFull() bool
IsEmpty() bool
FreeAll()
}
type fixedCallFrameStack struct {
array []callFrame
sp int
}
func newFixedCallFrameStack(size int) callFrameStack {
return &fixedCallFrameStack{
array: make([]callFrame, size),
sp: 0,
}
}
func (cs *fixedCallFrameStack) IsEmpty() bool { return cs.sp == 0 }
func (cs *fixedCallFrameStack) IsFull() bool { return cs.sp == len(cs.array) }
func (cs *fixedCallFrameStack) Clear() {
cs.sp = 0
}
func (cs *fixedCallFrameStack) Push(v callFrame) {
cs.array[cs.sp] = v
cs.array[cs.sp].Idx = cs.sp
cs.sp++
}
func (cs *fixedCallFrameStack) Sp() int {
return cs.sp
}
func (cs *fixedCallFrameStack) SetSp(sp int) {
cs.sp = sp
}
func (cs *fixedCallFrameStack) Last() *callFrame {
if cs.sp == 0 {
return nil
}
return &cs.array[cs.sp-1]
}
func (cs *fixedCallFrameStack) At(sp int) *callFrame {
return &cs.array[sp]
}
func (cs *fixedCallFrameStack) Pop() *callFrame {
cs.sp--
return &cs.array[cs.sp]
}
func (cs *fixedCallFrameStack) FreeAll() {
// nothing to do for fixed callframestack
}
// FramesPerSegment should be a power of 2 constant for performance reasons. It will allow the go compiler to change
// the divs and mods into bitshifts. Max is 256 due to current use of uint8 to count how many frames in a segment are
// used.
const FramesPerSegment = 8
type callFrameStackSegment struct {
array [FramesPerSegment]callFrame
}
type segIdx uint16
type autoGrowingCallFrameStack struct {
segments []*callFrameStackSegment
segIdx segIdx
// segSp is the number of frames in the current segment which are used. Full 'sp' value is segIdx * FramesPerSegment + segSp.
// It points to the next stack slot to use, so 0 means to use the 0th element in the segment, and a value of
// FramesPerSegment indicates that the segment is full and cannot accommodate another frame.
segSp uint8
}
var segmentPool sync.Pool
func newCallFrameStackSegment() *callFrameStackSegment {
seg := segmentPool.Get()
if seg == nil {
return &callFrameStackSegment{}
}
return seg.(*callFrameStackSegment)
}
func freeCallFrameStackSegment(seg *callFrameStackSegment) {
segmentPool.Put(seg)
}
// newCallFrameStack allocates a new stack for a lua state, which will auto grow up to a max size of at least maxSize.
// it will actually grow up to the next segment size multiple after maxSize, where the segment size is dictated by
// FramesPerSegment.
func newAutoGrowingCallFrameStack(maxSize int) callFrameStack {
cs := &autoGrowingCallFrameStack{
segments: make([]*callFrameStackSegment, (maxSize+(FramesPerSegment-1))/FramesPerSegment),
segIdx: 0,
}
cs.segments[0] = newCallFrameStackSegment()
return cs
}
func (cs *autoGrowingCallFrameStack) IsEmpty() bool {
return cs.segIdx == 0 && cs.segSp == 0
}
// IsFull returns true if the stack cannot receive any more stack pushes without overflowing
func (cs *autoGrowingCallFrameStack) IsFull() bool {
return int(cs.segIdx) == len(cs.segments) && cs.segSp >= FramesPerSegment
}
func (cs *autoGrowingCallFrameStack) Clear() {
for i := segIdx(1); i <= cs.segIdx; i++ {
freeCallFrameStackSegment(cs.segments[i])
cs.segments[i] = nil
}
cs.segIdx = 0
cs.segSp = 0
}
func (cs *autoGrowingCallFrameStack) FreeAll() {
for i := segIdx(0); i <= cs.segIdx; i++ {
freeCallFrameStackSegment(cs.segments[i])
cs.segments[i] = nil
}
}
// Push pushes the passed callFrame onto the stack. it panics if the stack is full, caller should call IsFull() before
// invoking this to avoid this.
func (cs *autoGrowingCallFrameStack) Push(v callFrame) {
curSeg := cs.segments[cs.segIdx]
if cs.segSp >= FramesPerSegment {
// segment full, push new segment if allowed
if cs.segIdx < segIdx(len(cs.segments)-1) {
curSeg = newCallFrameStackSegment()
cs.segIdx++
cs.segments[cs.segIdx] = curSeg
cs.segSp = 0
} else {
panic("lua callstack overflow")
}
}
curSeg.array[cs.segSp] = v
curSeg.array[cs.segSp].Idx = int(cs.segSp) + FramesPerSegment*int(cs.segIdx)
cs.segSp++
}
// Sp retrieves the current stack depth, which is the number of frames currently pushed on the stack.
func (cs *autoGrowingCallFrameStack) Sp() int {
return int(cs.segSp) + int(cs.segIdx)*FramesPerSegment
}
// SetSp can be used to rapidly unwind the stack, freeing all stack frames on the way. It should not be used to
// allocate new stack space, use Push() for that.
func (cs *autoGrowingCallFrameStack) SetSp(sp int) {
desiredSegIdx := segIdx(sp / FramesPerSegment)
desiredFramesInLastSeg := uint8(sp % FramesPerSegment)
for {
if cs.segIdx <= desiredSegIdx {
break
}
freeCallFrameStackSegment(cs.segments[cs.segIdx])
cs.segments[cs.segIdx] = nil
cs.segIdx--
}
cs.segSp = desiredFramesInLastSeg
}
func (cs *autoGrowingCallFrameStack) Last() *callFrame {
curSeg := cs.segments[cs.segIdx]
segSp := cs.segSp
if segSp == 0 {
if cs.segIdx == 0 {
return nil
}
curSeg = cs.segments[cs.segIdx-1]
segSp = FramesPerSegment
}
return &curSeg.array[segSp-1]
}
func (cs *autoGrowingCallFrameStack) At(sp int) *callFrame {
segIdx := segIdx(sp / FramesPerSegment)
frameIdx := uint8(sp % FramesPerSegment)
return &cs.segments[segIdx].array[frameIdx]
}
// Pop pops off the most recent stack frame and returns it
func (cs *autoGrowingCallFrameStack) Pop() *callFrame {
curSeg := cs.segments[cs.segIdx]
if cs.segSp == 0 {
if cs.segIdx == 0 {
// stack empty
return nil
}
freeCallFrameStackSegment(curSeg)
cs.segments[cs.segIdx] = nil
cs.segIdx--
cs.segSp = FramesPerSegment
curSeg = cs.segments[cs.segIdx]
}
cs.segSp--
return &curSeg.array[cs.segSp]
}
/* }}} */
/* registry {{{ */
type registryHandler interface {
registryOverflow()
}
type registry struct {
array []LValue
top int
growBy int
maxSize int
alloc *allocator
handler registryHandler
}
func newRegistry(handler registryHandler, initialSize int, growBy int, maxSize int, alloc *allocator) *registry {
return ®istry{make([]LValue, initialSize), 0, growBy, maxSize, alloc, handler}
}
func (rg *registry) checkSize(requiredSize int) { // +inline-start
if requiredSize > cap(rg.array) {
rg.resize(requiredSize)
}
} // +inline-end
func (rg *registry) resize(requiredSize int) { // +inline-start
newSize := requiredSize + rg.growBy // give some padding
if newSize > rg.maxSize {
newSize = rg.maxSize
}
if newSize < requiredSize {
rg.handler.registryOverflow()
return
}
rg.forceResize(newSize)
} // +inline-end
func (rg *registry) forceResize(newSize int) {
newSlice := make([]LValue, newSize)
copy(newSlice, rg.array[:rg.top]) // should we copy the area beyond top? there shouldn't be any valid values there so it shouldn't be necessary.
rg.array = newSlice
}
func (rg *registry) SetTop(topi int) { // +inline-start
// +inline-call rg.checkSize topi
oldtopi := rg.top
rg.top = topi
for i := oldtopi; i < rg.top; i++ {
rg.array[i] = LNil
}
// values beyond top don't need to be valid LValues, so setting them to nil is fine
// setting them to nil rather than LNil lets us invoke the golang memclr opto
if rg.top < oldtopi {
nilRange := rg.array[rg.top:oldtopi]
for i := range nilRange {
nilRange[i] = nil
}
}
//for i := rg.top; i < oldtop; i++ {
// rg.array[i] = LNil
//}
} // +inline-end
func (rg *registry) Top() int {
return rg.top
}
func (rg *registry) Push(v LValue) {
newSize := rg.top + 1
// +inline-call rg.checkSize newSize
rg.array[rg.top] = v
rg.top++
}
func (rg *registry) Pop() LValue {
v := rg.array[rg.top-1]
rg.array[rg.top-1] = LNil
rg.top--
return v
}
func (rg *registry) Get(reg int) LValue {
return rg.array[reg]
}
// CopyRange will move a section of values from index `start` to index `regv`
// It will move `n` values.
// `limit` specifies the maximum end range that can be copied from. If it's set to -1, then it defaults to stopping at
// the top of the registry (values beyond the top are not initialized, so if specifying an alternative `limit` you should
// pass a value <= rg.top.
// If start+n is beyond the limit, then nil values will be copied to the destination slots.
// After the copy, the registry is truncated to be at the end of the copied range, ie the original of the copied values
// are nilled out. (So top will be regv+n)
// CopyRange should ideally be renamed to MoveRange.
func (rg *registry) CopyRange(regv, start, limit, n int) { // +inline-start
newSize := regv + n
// +inline-call rg.checkSize newSize
if limit == -1 || limit > rg.top {
limit = rg.top
}
for i := 0; i < n; i++ {
srcIdx := start + i
if srcIdx >= limit || srcIdx < 0 {
rg.array[regv+i] = LNil
} else {
rg.array[regv+i] = rg.array[srcIdx]
}
}
// values beyond top don't need to be valid LValues, so setting them to nil is fine
// setting them to nil rather than LNil lets us invoke the golang memclr opto
oldtop := rg.top
rg.top = regv + n
if rg.top < oldtop {
nilRange := rg.array[rg.top:oldtop]
for i := range nilRange {
nilRange[i] = nil
}
}
} // +inline-end
// FillNil fills the registry with nil values from regm to regm+n and then sets the registry top to regm+n
func (rg *registry) FillNil(regm, n int) { // +inline-start
newSize := regm + n
// +inline-call rg.checkSize newSize
for i := 0; i < n; i++ {
rg.array[regm+i] = LNil
}
// values beyond top don't need to be valid LValues, so setting them to nil is fine
// setting them to nil rather than LNil lets us invoke the golang memclr opto
oldtop := rg.top
rg.top = regm + n
if rg.top < oldtop {
nilRange := rg.array[rg.top:oldtop]
for i := range nilRange {
nilRange[i] = nil
}
}
} // +inline-end
func (rg *registry) Insert(value LValue, reg int) {
top := rg.Top()
if reg >= top {
// +inline-call rg.Set reg value
return
}
top--
for ; top >= reg; top-- {
// FIXME consider using copy() here if Insert() is called enough
// +inline-call rg.Set top+1 rg.Get(top)
}
// +inline-call rg.Set reg value
}
func (rg *registry) Set(regi int, vali LValue) { // +inline-start
newSize := regi + 1
// +inline-call rg.checkSize newSize
rg.array[regi] = vali
if regi >= rg.top {
rg.top = regi + 1
}
} // +inline-end
func (rg *registry) SetNumber(regi int, vali LNumber) { // +inline-start
newSize := regi + 1
// +inline-call rg.checkSize newSize
rg.array[regi] = rg.alloc.LNumber2I(vali)
if regi >= rg.top {
rg.top = regi + 1
}
} // +inline-end
func (rg *registry) IsFull() bool {
return rg.top >= cap(rg.array)
}
/* }}} */
/* Global {{{ */
func newGlobal() *Global {
return &Global{
MainThread: nil,
Registry: newLTable(0, 32),
Global: newLTable(0, 64),
builtinMts: make(map[int]LValue),
tempFiles: make([]*os.File, 0, 10),
}
}
/* }}} */
/* package local methods {{{ */
func panicWithTraceback(L *LState) {
err := newApiError(ApiErrorRun, L.Get(-1))
err.StackTrace = L.stackTrace(0)
panic(err)
}
func panicWithoutTraceback(L *LState) {
err := newApiError(ApiErrorRun, L.Get(-1))
panic(err)
}
func newLState(options Options) *LState {
al := newAllocator(32)
ls := &LState{
G: newGlobal(),
Parent: nil,
Panic: panicWithTraceback,
Dead: false,
Options: options,
stop: 0,
alloc: al,
currentFrame: nil,
wrapped: false,
uvcache: nil,
hasErrorFunc: false,
mainLoop: mainLoop,
ctx: nil,
}
if options.MinimizeStackMemory {
ls.stack = newAutoGrowingCallFrameStack(options.CallStackSize)
} else {
ls.stack = newFixedCallFrameStack(options.CallStackSize)
}
ls.reg = newRegistry(ls, options.RegistrySize, options.RegistryGrowStep, options.RegistryMaxSize, al)
ls.Env = ls.G.Global
return ls
}
func (ls *LState) printReg() {
println("-------------------------")
println("thread:", ls)
println("top:", ls.reg.Top())
if ls.currentFrame != nil {
println("function base:", ls.currentFrame.Base)
println("return base:", ls.currentFrame.ReturnBase)
} else {
println("(vm not started)")
}
println("local base:", ls.currentLocalBase())
for i := 0; i < ls.reg.Top(); i++ {
println(i, ls.reg.Get(i).String())
}
println("-------------------------")
}
func (ls *LState) printCallStack() {
println("-------------------------")
for i := 0; i < ls.stack.Sp(); i++ {
print(i)
print(" ")
frame := ls.stack.At(i)
if frame == nil {
break
}
if frame.Fn.IsG {
println("IsG:", true, "Frame:", frame, "Fn:", frame.Fn)
} else {
println("IsG:", false, "Frame:", frame, "Fn:", frame.Fn, "pc:", frame.Pc)
}
}
println("-------------------------")
}
func (ls *LState) closeAllUpvalues() { // +inline-start
for cf := ls.currentFrame; cf != nil; cf = cf.Parent {
if !cf.Fn.IsG {
ls.closeUpvalues(cf.LocalBase)
}
}
} // +inline-end
func (ls *LState) raiseError(level int, format string, args ...interface{}) {
if !ls.hasErrorFunc {
ls.closeAllUpvalues()
}
message := format
if len(args) > 0 {
message = fmt.Sprintf(format, args...)
}
if level > 0 {
message = fmt.Sprintf("%v %v", ls.where(level-1, true), message)
}
if ls.reg.IsFull() {
// if the registry is full then it won't be possible to push a value, in this case, force a larger size
ls.reg.forceResize(ls.reg.Top() + 1)
}
ls.reg.Push(LString(message))
ls.Panic(ls)
}
func (ls *LState) findLocal(frame *callFrame, no int) string {
fn := frame.Fn
if !fn.IsG {
if name, ok := fn.LocalName(no, frame.Pc-1); ok {
return name
}
}
var top int
if ls.currentFrame == frame {
top = ls.reg.Top()
} else if frame.Idx+1 < ls.stack.Sp() {
top = ls.stack.At(frame.Idx + 1).Base
} else {
return ""
}
if top-frame.LocalBase >= no {
return "(*temporary)"
}
return ""
}
func (ls *LState) where(level int, skipg bool) string {
dbg, ok := ls.GetStack(level)
if !ok {
return ""
}
cf := dbg.frame
proto := cf.Fn.Proto
sourcename := "[G]"
if proto != nil {
sourcename = proto.SourceName
} else if skipg {
return ls.where(level+1, skipg)
}
line := ""
if proto != nil {
line = fmt.Sprintf("%v:", proto.DbgSourcePositions[cf.Pc-1])
}
return fmt.Sprintf("%v:%v", sourcename, line)
}
func (ls *LState) stackTrace(level int) string {
buf := []string{}
header := "stack traceback:"
if ls.currentFrame != nil {
i := 0
for dbg, ok := ls.GetStack(i); ok; dbg, ok = ls.GetStack(i) {
cf := dbg.frame
buf = append(buf, fmt.Sprintf("\t%v in %v", ls.Where(i), ls.formattedFrameFuncName(cf)))
if !cf.Fn.IsG && cf.TailCall > 0 {
for tc := cf.TailCall; tc > 0; tc-- {
buf = append(buf, "\t(tailcall): ?")
i++
}
}
i++
}
}
buf = append(buf, fmt.Sprintf("\t%v: %v", "[G]", "?"))
buf = buf[intMax(0, intMin(level, len(buf))):len(buf)]
if len(buf) > 20 {
newbuf := make([]string, 0, 20)
newbuf = append(newbuf, buf[0:7]...)
newbuf = append(newbuf, "\t...")
newbuf = append(newbuf, buf[len(buf)-7:len(buf)]...)
buf = newbuf
}
return fmt.Sprintf("%s\n%s", header, strings.Join(buf, "\n"))
}
func (ls *LState) formattedFrameFuncName(fr *callFrame) string {
name, ischunk := ls.frameFuncName(fr)
if ischunk {
return name
}
if name[0] != '(' && name[0] != '<' {
return fmt.Sprintf("function '%s'", name)
}
return fmt.Sprintf("function %s", name)
}
func (ls *LState) rawFrameFuncName(fr *callFrame) string {
name, _ := ls.frameFuncName(fr)
return name
}
func (ls *LState) frameFuncName(fr *callFrame) (string, bool) {
frame := fr.Parent
if frame == nil {
if ls.Parent == nil {
return "main chunk", true
} else {
return "corountine", true
}
}
if !frame.Fn.IsG {
pc := frame.Pc - 1
for _, call := range frame.Fn.Proto.DbgCalls {
if call.Pc == pc {
name := call.Name
if (name == "?" || fr.TailCall > 0) && !fr.Fn.IsG {
name = fmt.Sprintf("<%v:%v>", fr.Fn.Proto.SourceName, fr.Fn.Proto.LineDefined)
}
return name, false
}
}
}
if !fr.Fn.IsG {
return fmt.Sprintf("<%v:%v>", fr.Fn.Proto.SourceName, fr.Fn.Proto.LineDefined), false
}
return "(anonymous)", false
}
func (ls *LState) isStarted() bool {
return ls.currentFrame != nil
}
func (ls *LState) kill() {
ls.Dead = true
if ls.ctxCancelFn != nil {
ls.ctxCancelFn()
}
}
func (ls *LState) indexToReg(idx int) int {
base := ls.currentLocalBase()
if idx > 0 {
return base + idx - 1
} else if idx == 0 {
return -1
} else {
tidx := ls.reg.Top() + idx
if tidx < base {
return -1
}
return tidx
}
}
func (ls *LState) currentLocalBase() int {
base := 0
if ls.currentFrame != nil {
base = ls.currentFrame.LocalBase
}
return base
}
func (ls *LState) currentEnv() *LTable {
return ls.Env
/*
if ls.currentFrame == nil {
return ls.Env
}
return ls.currentFrame.Fn.Env
*/
}
func (ls *LState) rkValue(idx int) LValue {
/*
if OpIsK(idx) {
return ls.currentFrame.Fn.Proto.Constants[opIndexK(idx)]
}
return ls.reg.Get(ls.currentFrame.LocalBase + idx)
*/
if (idx & opBitRk) != 0 {
return ls.currentFrame.Fn.Proto.Constants[idx & ^opBitRk]
}
return ls.reg.array[ls.currentFrame.LocalBase+idx]
}
func (ls *LState) rkString(idx int) string {
if (idx & opBitRk) != 0 {
return ls.currentFrame.Fn.Proto.stringConstants[idx & ^opBitRk]
}
return string(ls.reg.array[ls.currentFrame.LocalBase+idx].(LString))
}
func (ls *LState) closeUpvalues(idx int) { // +inline-start
if ls.uvcache != nil {
var prev *Upvalue
for uv := ls.uvcache; uv != nil; uv = uv.next {
if uv.index >= idx {
if prev != nil {
prev.next = nil
} else {
ls.uvcache = nil
}
uv.Close()
}
prev = uv
}
}
} // +inline-end
func (ls *LState) findUpvalue(idx int) *Upvalue {
var prev *Upvalue
var next *Upvalue
if ls.uvcache != nil {
for uv := ls.uvcache; uv != nil; uv = uv.next {
if uv.index == idx {
return uv
}
if uv.index > idx {
next = uv
break
}
prev = uv
}
}
uv := &Upvalue{reg: ls.reg, index: idx, closed: false}
if prev != nil {
prev.next = uv
} else {
ls.uvcache = uv
}
if next != nil {
uv.next = next
}
return uv
}
func (ls *LState) metatable(lvalue LValue, rawget bool) LValue {
var metatable LValue = LNil
switch obj := lvalue.(type) {
case *LTable:
metatable = obj.Metatable
case *LUserData:
metatable = obj.Metatable
default:
if table, ok := ls.G.builtinMts[int(obj.Type())]; ok {
metatable = table
}
}
if !rawget && metatable != LNil {
oldmt := metatable
if tb, ok := metatable.(*LTable); ok {
metatable = tb.RawGetString("__metatable")
if metatable == LNil {
metatable = oldmt
}
}
}
return metatable
}
func (ls *LState) metaOp1(lvalue LValue, event string) LValue {
if mt := ls.metatable(lvalue, true); mt != LNil {
if tb, ok := mt.(*LTable); ok {
return tb.RawGetString(event)
}
}
return LNil
}
func (ls *LState) metaOp2(value1, value2 LValue, event string) LValue {
if mt := ls.metatable(value1, true); mt != LNil {
if tb, ok := mt.(*LTable); ok {
if ret := tb.RawGetString(event); ret != LNil {
return ret
}
}
}
if mt := ls.metatable(value2, true); mt != LNil {
if tb, ok := mt.(*LTable); ok {
return tb.RawGetString(event)
}
}
return LNil
}
func (ls *LState) metaCall(lvalue LValue) (*LFunction, bool) {
if fn, ok := lvalue.(*LFunction); ok {
return fn, false
}
if fn, ok := ls.metaOp1(lvalue, "__call").(*LFunction); ok {
return fn, true
}
return nil, false
}
func (ls *LState) initCallFrame(cf *callFrame) { // +inline-start
if cf.Fn.IsG {
ls.reg.SetTop(cf.LocalBase + cf.NArgs)
} else {
proto := cf.Fn.Proto
nargs := cf.NArgs
np := int(proto.NumParameters)
if nargs < np {
// default any missing arguments to nil
newSize := cf.LocalBase + np
// +inline-call ls.reg.checkSize newSize
for i := nargs; i < np; i++ {
ls.reg.array[cf.LocalBase+i] = LNil
}
nargs = np
ls.reg.top = newSize
}
if (proto.IsVarArg & VarArgIsVarArg) == 0 {
if nargs < int(proto.NumUsedRegisters) {
nargs = int(proto.NumUsedRegisters)
}
newSize := cf.LocalBase + nargs
// +inline-call ls.reg.checkSize newSize
for i := np; i < nargs; i++ {
ls.reg.array[cf.LocalBase+i] = LNil
}
ls.reg.top = cf.LocalBase + int(proto.NumUsedRegisters)
} else {
/* swap vararg positions:
closure
namedparam1 <- lbase
namedparam2
vararg1
vararg2
TO
closure
nil
nil
vararg1
vararg2
namedparam1 <- lbase
namedparam2
*/
nvarargs := nargs - np
if nvarargs < 0 {
nvarargs = 0
}
ls.reg.SetTop(cf.LocalBase + nargs + np)
for i := 0; i < np; i++ {
//ls.reg.Set(cf.LocalBase+nargs+i, ls.reg.Get(cf.LocalBase+i))
ls.reg.array[cf.LocalBase+nargs+i] = ls.reg.array[cf.LocalBase+i]
//ls.reg.Set(cf.LocalBase+i, LNil)
ls.reg.array[cf.LocalBase+i] = LNil
}
if CompatVarArg {
ls.reg.SetTop(cf.LocalBase + nargs + np + 1)
if (proto.IsVarArg & VarArgNeedsArg) != 0 {
argtb := newLTable(nvarargs, 0)
for i := 0; i < nvarargs; i++ {
argtb.RawSetInt(i+1, ls.reg.Get(cf.LocalBase+np+i))