forked from Shopify/go-lua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.go
More file actions
591 lines (547 loc) · 14.1 KB
/
types.go
File metadata and controls
591 lines (547 loc) · 14.1 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
package lua
import (
"fmt"
"math"
"reflect"
"runtime"
"strings"
)
type (
value interface{}
float8 int
)
func debugValue(v value) string {
switch v := v.(type) {
case *table:
entry := func(x value) string {
if t, ok := x.(*table); ok {
return fmt.Sprintf("table %#v", t)
}
return debugValue(x)
}
s := fmt.Sprintf("table %#v {[", v)
for _, x := range v.array {
s += entry(x) + ", "
}
s += "], {"
for k, x := range v.hash {
s += entry(k) + ": " + entry(x) + ", "
}
return s + "}}"
case string:
return "'" + v + "'"
case float64:
return fmt.Sprintf("%f", v)
case int64:
return fmt.Sprintf("%d", v)
case *luaClosure:
return fmt.Sprintf("closure %s:%d %v", v.prototype.source, v.prototype.lineDefined, v)
case *goClosure:
return fmt.Sprintf("go closure %#v", v)
case *goFunction:
pc := reflect.ValueOf(v.Function).Pointer()
f := runtime.FuncForPC(pc)
file, line := f.FileLine(pc)
return fmt.Sprintf("go function %s %s:%d", f.Name(), file, line)
case *userData:
return fmt.Sprintf("userdata %#v", v)
case nil:
return "nil"
case bool:
return fmt.Sprintf("%#v", v)
}
return fmt.Sprintf("unknown %#v %s", v, reflect.TypeOf(v).Name())
}
func stack(s []value) string {
r := fmt.Sprintf("stack (len: %d, cap: %d):\n", len(s), cap(s))
for i, v := range s {
r = fmt.Sprintf("%s %d: %s\n", r, i, debugValue(v))
}
return r
}
func isFalse(s value) bool {
if s == nil || s == none {
return true
}
b, isBool := s.(bool)
return isBool && !b
}
// isInteger returns true if the value is a Lua integer (int64).
func isInteger(v value) bool {
_, ok := v.(int64)
return ok
}
// isFloat returns true if the value is a Lua float (float64).
func isFloat(v value) bool {
_, ok := v.(float64)
return ok
}
// isNumber returns true if the value is a Lua number (int64 or float64).
func isNumber(v value) bool {
switch v.(type) {
case int64, float64:
return true
}
return false
}
// toFloat converts a numeric value to float64.
// Returns the float value and true if successful.
func toFloat(v value) (float64, bool) {
switch n := v.(type) {
case float64:
return n, true
case int64:
return float64(n), true
}
return 0, false
}
// pow2_63 is 2^63 as float64, used for range checks.
// This is the smallest float64 that cannot be represented as int64.
const (
pow2_63Float = float64(1 << 63) // 9223372036854775808.0
maxInt64 = int64(1<<63 - 1) // 9223372036854775807
minInt64 = int64(-1 << 63) // -9223372036854775808
)
// toInteger converts a numeric value to int64.
// For float64, only succeeds if the value is integral and within int64 range.
// Returns the integer value and true if successful.
// NOTE: This does NOT convert strings. Use State.toIntegerString for that.
func toInteger(v value) (int64, bool) {
switch n := v.(type) {
case int64:
return n, true
case float64:
// Check range first: valid int64 range is [-2^63, 2^63-1]
// Due to float64 precision, n >= 2^63 means it's out of range
if n >= pow2_63Float || n < -pow2_63Float {
return 0, false
}
// Now safely convert and check round-trip
if i := int64(n); float64(i) == n {
return i, true
}
}
return 0, false
}
// toIntegerString converts a value to int64, including string coercion.
// In Lua 5.3, strings are coerced to integers for bitwise operations.
func (l *State) toIntegerString(v value) (int64, bool) {
// First try direct numeric conversion
if i, ok := toInteger(v); ok {
return i, ok
}
// Try string coercion
if s, ok := v.(string); ok {
if f, ok := l.toNumber(s); ok {
return floatToInteger(f)
}
}
return 0, false
}
// floatToInteger attempts to convert a float64 to int64.
// Returns the integer and true if the float represents an integer value
// that is within the valid int64 range.
func floatToInteger(f float64) (int64, bool) {
// Check range first: valid int64 range is [-2^63, 2^63-1]
if f >= pow2_63Float || f < -pow2_63Float {
return 0, false
}
i := int64(f)
if float64(i) == f {
return i, true
}
return 0, false
}
// forLimit tries to convert a for-loop limit to an integer.
// This implements Lua 5.3 semantics where the limit can be a float
// that represents an integer value, or can be out of integer range
// (in which case we use MaxInt64 or MinInt64 as appropriate).
// Returns the integer limit and true if we can use an integer loop.
func forLimit(limitVal value, step int64) (int64, bool) {
switch limit := limitVal.(type) {
case int64:
return limit, true
case float64:
// Try to convert float to integer
if i, ok := floatToInteger(limit); ok {
return i, true
}
// Float is out of integer range or not integral
// If step > 0 and limit > MaxInt64, use MaxInt64
// If step < 0 and limit < MinInt64, use MinInt64
if step > 0 {
if limit > 0 {
// limit is larger than MaxInt64
return maxInt64, true
}
// limit is smaller than MinInt64, loop won't run
return minInt64, true
}
if limit < 0 {
// limit is smaller than MinInt64
return minInt64, true
}
// limit is larger than MaxInt64
return maxInt64, true
}
return 0, false
}
type localVariable struct {
name string
startPC, endPC pc
kind byte // 0=regular, 1=const, 2=toclose, 3=CTC
val value // compile-time constant value (only for kind==varCTC)
}
type userData struct {
metaTable, env *table
data interface{}
}
type upValueDesc struct {
name string
isLocal bool
index int
kind byte // Lua 5.4: upvalue kind
}
type stackLocation struct {
state *State
index int
}
// absLineInfo stores absolute line info entries for Lua 5.4 split lineinfo
type absLineInfo struct {
pc, line int
}
type prototype struct {
constants []value
code []instruction
prototypes []prototype
lineInfo []int8 // Lua 5.4: relative line info
absLineInfos []absLineInfo // Lua 5.4: absolute line info
localVariables []localVariable
upValues []upValueDesc
cache *luaClosure
source string
lineDefined, lastLineDefined int
parameterCount, maxStackSize int
isVarArg bool
}
func (p *prototype) upValueName(index int) string {
if s := p.upValues[index].name; s != "" {
return s
}
return "?"
}
func (p *prototype) lastLoad(reg int, lastPC pc) (loadPC pc, found bool) {
// If the instruction at lastPC is a metamethod instruction (MMBIN, etc.),
// skip it — it was not actually executed, and the previous arithmetic
// instruction is what we want to look past. This matches C Lua's findsetreg.
if lastPC > 0 && testMMMode(p.code[lastPC].opCode()) {
lastPC--
}
var ip, jumpTarget pc
for ; ip < lastPC; ip++ {
i, maybe := p.code[ip], false
switch i.opCode() {
case opLoadNil:
maybe = i.a() <= reg && reg <= i.a()+i.b()
case opTForCall:
maybe = reg >= i.a()+2
case opCall, opTailCall:
maybe = reg >= i.a()
case opJump:
// Lua 5.4: JMP uses sJ format
if dest := ip + 1 + pc(i.sJ()); ip < dest && dest <= lastPC && dest > jumpTarget {
jumpTarget = dest
}
case opTest:
maybe = reg == i.a()
default:
maybe = testAMode(i.opCode()) && reg == i.a()
}
if maybe {
if ip < jumpTarget { // Can't know loading instruction because code is conditional.
found = false
} else {
loadPC, found = ip, true
}
}
}
return
}
func (p *prototype) objectName(reg int, lastPC pc) (name, kind string) {
if name, isLocal := p.localName(reg+1, lastPC); isLocal {
return name, "local"
}
if pc, found := p.lastLoad(reg, lastPC); found {
i := p.code[pc]
switch op := i.opCode(); op {
case opMove:
if b := i.b(); b < i.a() {
return p.objectName(b, pc)
}
case opGetTableUp:
name = p.constantName(i.c(), pc)
if p.upValueName(i.b()) == "_ENV" {
kind = "global"
} else {
kind = "field"
}
return
case opGetField:
// Lua 5.4: GETFIELD A B C — key is K[C]
name = p.constantName(i.c(), pc)
if v, ok := p.localName(i.b()+1, pc); ok && v == "_ENV" {
kind = "global"
} else {
kind = "field"
}
return
case opGetTable, opGetI:
// Lua 5.4: GETTABLE key=R[C], GETI key=integer C
kind = "field"
name = "?"
return
case opGetUpValue:
return p.upValueName(i.b()), "upvalue"
case opLoadConstant:
if s, ok := p.constants[i.bx()].(string); ok {
return s, "constant"
}
case opLoadConstantEx:
if s, ok := p.constants[p.code[pc+1].ax()].(string); ok {
return s, "constant"
}
case opSelf:
return p.constantName(i.c(), pc), "method"
}
}
return
}
func (p *prototype) constantName(k int, pc pc) string {
// Lua 5.4: k is always a constant index (no RK encoding)
if k >= 0 && k < len(p.constants) {
if s, ok := p.constants[k].(string); ok {
return s
}
}
return "?"
}
func (p *prototype) localName(index int, pc pc) (string, bool) {
for i := 0; i < len(p.localVariables) && p.localVariables[i].startPC <= pc; i++ {
if pc < p.localVariables[i].endPC {
if index--; index == 0 {
return p.localVariables[i].name, true
}
}
}
return "", false
}
// localKind returns the kind of local variable at the given 1-based index
// active at the given pc. Returns 0 (varRegular) if not found.
func (p *prototype) localKind(index int, pc pc) byte {
for i := 0; i < len(p.localVariables) && p.localVariables[i].startPC <= pc; i++ {
if pc < p.localVariables[i].endPC {
if index--; index == 0 {
return p.localVariables[i].kind
}
}
}
return varRegular
}
// Converts an integer to a "floating point byte", represented as
// (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
// eeeee != 0 and (xxx) otherwise.
func float8FromInt(x int) float8 {
if x < 8 {
return float8(x)
}
e := 0
for ; x >= 0x10; e++ {
x = (x + 1) >> 1
}
return float8(((e + 1) << 3) | (x - 8))
}
func intFromFloat8(x float8) int {
e := x >> 3 & 0x1f
if e == 0 {
return int(x)
}
return int(x&7+8) << uint(e-1)
}
func arith(op Operator, v1, v2 float64) float64 {
switch op {
case OpAdd:
return v1 + v2
case OpSub:
return v1 - v2
case OpMul:
return v1 * v2
case OpDiv:
return v1 / v2
case OpMod:
return v1 - math.Floor(v1/v2)*v2
case OpPow:
// Golang bug: math.Pow(10.0, 33.0) is incorrect by 1 bit.
if v1 == 10.0 && float64(int(v2)) == v2 {
return math.Pow10(int(v2))
}
return math.Pow(v1, v2)
case OpUnaryMinus:
return -v1
}
panic(fmt.Sprintf("not an arithmetic op code (%d)", op))
}
// parseNumberEx parses a number string and returns either an integer or float.
// Returns (intVal, floatVal, isInteger, ok). If ok is false, parsing failed.
// If ok is true and isInteger is true, use intVal; otherwise use floatVal.
func (l *State) parseNumberEx(s string) (intVal int64, floatVal float64, isInt bool, ok bool) {
if len(strings.Fields(s)) != 1 || strings.ContainsRune(s, 0) {
return 0, 0, false, false
}
// Special case: check for exact minint string representation before scanning
// This handles "-9223372036854775808" which can't be parsed by scanning
// the absolute value (since 9223372036854775808 overflows int64)
trimmed := strings.TrimSpace(s)
if trimmed == "-9223372036854775808" {
return minInt64, 0, true, true
}
// Use protectedCall to catch scanner errors (e.g., from invalid hex like "0x")
var success bool
err := l.protectedCall(func() {
scanner := scanner{l: l, r: strings.NewReader(s)}
t := scanner.scan()
neg := false
if t.t == '-' {
neg = true
t = scanner.scan()
} else if t.t == '+' {
t = scanner.scan()
}
switch t.t {
case tkInteger:
if scanner.scan().t != tkEOS {
return
}
if neg {
intVal = -t.i
} else {
intVal = t.i
}
isInt = true
success = true
case tkNumber:
if scanner.scan().t != tkEOS {
return
}
// NaN is not a valid number, but Inf is allowed in Lua 5.3
if math.IsNaN(t.n) {
return
}
if neg {
floatVal = -t.n
} else {
floatVal = t.n
}
success = true
}
}, l.top, l.errorFunction)
if err != nil {
l.pop() // Remove error message from the stack
return 0, 0, false, false
}
if !success {
return 0, 0, false, false
}
return intVal, floatVal, isInt, true
}
func (l *State) parseNumber(s string) (v float64, ok bool) { // TODO this is f*cking ugly - scanner.readNumber should be refactored.
if len(strings.Fields(s)) != 1 || strings.ContainsRune(s, 0) {
return
}
scanner := scanner{l: l, r: strings.NewReader(s)}
t := scanner.scan()
// Helper to extract numeric value from token
getNumber := func(tok token) (float64, bool) {
switch tok.t {
case tkNumber:
return tok.n, true
case tkInteger:
return float64(tok.i), true
default:
return 0, false
}
}
if t.t == '-' {
t = scanner.scan()
if n, numOk := getNumber(t); numOk {
v, ok = -n, true
}
} else if n, isNum := getNumber(t); isNum {
v, ok = n, true
} else if t.t == '+' {
t = scanner.scan()
if n, numOk := getNumber(t); numOk {
v, ok = n, true
}
}
if ok && scanner.scan().t != tkEOS {
ok = false
} else if math.IsNaN(v) {
// NaN is not valid, but Inf is allowed in Lua 5.3
ok = false
}
return
}
func (l *State) toNumber(r value) (v float64, ok bool) {
if v, ok = r.(float64); ok {
return
}
if i, isInt := r.(int64); isInt {
return float64(i), true
}
var s string
if s, ok = r.(string); ok {
if err := l.protectedCall(func() { v, ok = l.parseNumber(strings.TrimSpace(s)) }, l.top, l.errorFunction); err != nil {
l.pop() // Remove error message from the stack.
ok = false
}
}
return
}
func (l *State) toString(index int) (s string, ok bool) {
if s, ok = toString(l.stack[index]); ok {
l.stack[index] = s
}
return
}
func numberToString(f float64) string {
return fmt.Sprintf("%.14g", f)
}
func integerToString(i int64) string {
return fmt.Sprintf("%d", i)
}
func toString(r value) (string, bool) {
switch r := r.(type) {
case string:
return r, true
case float64:
return numberToString(r), true
case int64:
return integerToString(r), true
}
return "", false
}
func pairAsNumbers(p1, p2 value) (f1, f2 float64, ok bool) {
f1, ok = toFloat(p1)
if !ok {
return
}
f2, ok = toFloat(p2)
return
}
func pairAsStrings(p1, p2 value) (s1, s2 string, ok bool) {
if s1, ok = p1.(string); !ok {
return
}
s2, ok = p2.(string)
return
}