slew 0.2.0

A suspendable Lua interpreter with strict, embedder-controlled execution budgets
Documentation
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
//! M4: string (patterns, format), table, math, and the Lua prelude
//! (gmatch/gsub/sort).

use slew::{Lua, Step, Value};
use test_case::test_case;

fn run(lua: &mut Lua, src: &str) -> Vec<Value> {
    let chunk = lua
        .load(src)
        .unwrap_or_else(|e| panic!("{e}\nsource:\n{src}"));
    let mut exec = lua.execute(&chunk);
    for _ in 0..10_000 {
        match exec.step(lua, 1_000_000) {
            Ok(Step::Done(vals)) => return vals,
            Ok(Step::Pending) => {}
            Ok(Step::Waiting(_)) => panic!("unexpected native wait"),
            Err(e) => panic!("{e}\nsource:\n{src}"),
        }
    }
    panic!("script did not finish: {src}");
}

fn eval(src: &str) -> String {
    let mut lua = Lua::new();
    let vals = run(&mut lua, src);
    assert!(!vals.is_empty(), "expected a return value from: {src}");
    lua.display_value(vals[0])
}

fn eval_multi(src: &str) -> Vec<String> {
    let mut lua = Lua::new();
    let vals = run(&mut lua, src);
    vals.iter().map(|v| lua.display_value(*v)).collect()
}

fn run_err(src: &str) -> String {
    let mut lua = Lua::new();
    let chunk = lua
        .load(src)
        .unwrap_or_else(|e| panic!("{e}\nsource:\n{src}"));
    let mut exec = lua.execute(&chunk);
    loop {
        match exec.step(&mut lua, 1_000_000) {
            Ok(Step::Done(_)) => panic!("expected error: {src}"),
            Ok(Step::Pending) => {}
            Ok(Step::Waiting(_)) => panic!("unexpected native wait"),
            Err(e) => return e.to_string(),
        }
    }
}

// ---- string ----

#[test]
fn string_basics() {
    assert_eq!(eval("return string.len('hello')"), "5");
    assert_eq!(eval("return string.sub('hello world', 1, 5)"), "hello");
    assert_eq!(eval("return string.sub('hello', -3)"), "llo");
    assert_eq!(eval("return string.sub('hello', 2, -2)"), "ell");
    assert_eq!(
        eval("return string.upper('mixed Case 42')"),
        "MIXED CASE 42"
    );
    assert_eq!(eval("return string.lower('MIXED Case')"), "mixed case");
    assert_eq!(eval("return string.rep('ab', 3)"), "ababab");
    assert_eq!(eval("return string.rep('x', 3, '-')"), "x-x-x");
    assert_eq!(eval("return string.reverse('abc')"), "cba");
    assert_eq!(eval("return string.byte('A')"), "65");
    assert_eq!(
        eval_multi("return string.byte('ABC', 1, 3)"),
        ["65", "66", "67"]
    );
    assert_eq!(eval("return string.char(104, 105)"), "hi");
}

// strings share a metatable with __index = string
#[test_case("return ('hello'):upper()" => "HELLO"; "upper_method")]
#[test_case("local s = 'a,b,c' return s:sub(1, 1) .. s:len()" => "a5"; "sub_and_len_method")]
#[test_case("return ('%d!'):format(42)" => "42!"; "format_method")]
fn string_method_syntax(src: &str) -> String {
    eval(src)
}

#[test]
fn string_find_and_match() {
    assert_eq!(
        eval_multi("return string.find('hello world', 'world')"),
        ["7", "11"]
    );
    assert_eq!(eval("return (string.find('abc', 'x'))"), "nil");
    assert_eq!(
        eval_multi("return string.find('key=val', '(%w+)=(%w+)')"),
        ["1", "7", "key", "val"]
    );
    // plain find ignores pattern chars
    assert_eq!(
        eval_multi("return string.find('a.b', '.', 1, true)"),
        ["2", "2"]
    );
    assert_eq!(eval("return string.match('hello 42 world', '%d+')"), "42");
    assert_eq!(
        eval_multi("return string.match('2026-06-10', '(%d+)-(%d+)-(%d+)')"),
        ["2026", "06", "10"]
    );
    assert_eq!(eval("return tostring(string.match('abc', '%d'))"), "nil");
    // init offset
    assert_eq!(eval("return string.match('aXbXc', 'X.', 3)"), "Xc");
}

#[test_case("local words = {} for w in string.gmatch('the quick brown fox', '%a+') do words[#words+1] = w end return table.concat(words, '|')" => "the|quick|brown|fox"; "gmatch_words")]
#[test_case("local sum = 0 for n in ('10,20,30'):gmatch('%d+') do sum = sum + tonumber(n) end return sum" => "60"; "gmatch_sum")]
#[test_case("local t = {} for k, v in ('a=1,b=2'):gmatch('(%w+)=(%w+)') do t[k] = v end return t.a .. t.b" => "12"; "captures_in_gmatch")]
fn string_gmatch(src: &str) -> String {
    eval(src)
}

#[test]
fn string_gsub() {
    assert_eq!(
        eval_multi("return string.gsub('hello world', 'o', '0')"),
        ["hell0 w0rld", "2"]
    );
    assert_eq!(eval_multi("return ('aaa'):gsub('a', 'b', 2)"), ["bba", "2"]);
    // %1 capture reference in replacement
    assert_eq!(
        eval("return (string.gsub('hello world', '(%w+)', '<%1>'))"),
        "<hello> <world>"
    );
    // %0 whole match
    assert_eq!(eval("return (string.gsub('abc', '%a', '%0%0'))"), "aabbcc");
    // function replacement (runs through the VM)
    assert_eq!(
        eval("return (string.gsub('1 2 3', '%d', function(d) return tonumber(d) * 2 end))"),
        "2 4 6"
    );
    // table replacement
    assert_eq!(
        eval("return (string.gsub('$name is $age', '%$(%w+)', {name = 'lua', age = 30}))"),
        "lua is 30"
    );
    // nil replacement keeps the match
    assert_eq!(
        eval("return (string.gsub('keep these', '%a+', function() return nil end))"),
        "keep these"
    );
    // anchored pattern replaces only at the start
    assert_eq!(eval_multi("return ('aaa'):gsub('^a', 'b')"), ["baa", "1"]);
    // empty matches advance correctly
    assert_eq!(
        eval_multi("return ('abc'):gsub('x*', '-')"),
        ["-a-b-c-", "4"]
    );
}

#[test_case("return string.format('%d/%d', 7, -3)" => "7/-3"; "format_d_negative")]
#[test_case("return string.format('%5d|', 42)" => "   42|"; "format_width_d")]
#[test_case("return string.format('%-5d|', 42)" => "42   |"; "format_left_align_d")]
#[test_case("return string.format('%05d', 42)" => "00042"; "format_zero_pad_d")]
#[test_case("return string.format('%+d %+d', 5, -5)" => "+5 -5"; "format_plus_flag_d")]
#[test_case("return string.format('%x %X %o', 255, 255, 8)" => "ff FF 10"; "format_x_X_o")]
#[test_case("return string.format('%#x', 255)" => "0xff"; "format_alt_x")]
#[test_case("return string.format('%c%c', 104, 105)" => "hi"; "format_c")]
#[test_case("return string.format('%.2f', 3.14159)" => "3.14"; "format_precision_f")]
#[test_case("return string.format('%f', 1)" => "1.000000"; "format_f_from_integer")]
#[test_case("return string.format('%e', 1500.0)" => "1.500000e+03"; "format_e")]
#[test_case("return string.format('%g', 0.00001)" => "1e-05"; "format_g_small")]
#[test_case("return string.format('%g', 100000.0)" => "100000"; "format_g_large")]
#[test_case("return string.format('%s=%s', 'a', 1)" => "a=1"; "format_s_values")]
#[test_case("return string.format('%.3s', 'hello')" => "hel"; "format_precision_s")]
#[test_case("return string.format('%10s|', 'hi')" => "        hi|"; "format_width_s")]
#[test_case("return string.format('%q', 'he said \"hi\"\\n')" => "\"he said \\\"hi\\\"\\\n\""; "format_q")]
#[test_case("return string.format('%%')" => "%"; "format_percent")]
// C flag/precision behaviour required by strings.lua.
#[test_case("return string.format('%#12o', 10)" => "         012"; "format_alt_width_o")]
#[test_case("return string.format('%2.5d', -100)" => "-00100"; "format_width_precision_d_negative")]
#[test_case("return string.format('%.u', 0)" => ""; "format_precision_u_zero")]
#[test_case("return string.format('%+#014.0f', 100)" => "+000000000100."; "format_plus_alt_zero_width_precision_f")]
fn string_format(src: &str) -> String {
    eval(src)
}

// `%s` follows PUC's `luaL_tolstring`: `__tostring`, then `__name`, then
// the default rendering; precision truncates the rendered bytes.
#[test_case("local m = setmetatable({}, {__tostring = function() return 'hello' end,__name = 'hi'})\nreturn string.format('%s %.10s', m, m)" => "hello hello"; "tostring_metamethod_preferred_over_name")]
#[test_case("local m = setmetatable({}, {__name = 'hi'})\nreturn string.format('%.4s', m)" => "hi: "; "name_fallback_truncated")]
#[test_case("return string.format('%s %s', nil, true)" => "nil true"; "nil_and_boolean")]
#[test_case("return string.format('%.3s %.3s', false, true)" => "fal tru"; "boolean_precision")]
#[test_case("local m = setmetatable({}, {__tostring = function() return {} end})\nlocal ok, err = pcall(string.format, '%s', m)\nreturn tostring(not ok and err:find(\"'__tostring' must return a string\") ~= nil)" => "true"; "tostring_not_returning_string_raises_catchable_by_pcall")]
fn string_format_s_uses_tolstring(src: &str) -> String {
    eval(src)
}

#[test]
fn tostring_checks_metamethod_result() {
    assert_eq!(
        eval(
            "local m = setmetatable({}, {__tostring = function() return {} end})\n\
             local ok, err = pcall(tostring, m)\n\
             return tostring(not ok and err:find('must return a string') ~= nil)"
        ),
        "true"
    );
}

#[test]
fn string_format_validation() {
    // PUC's `checkformat`/`getformat` rules (strings.lua lines 364-385).
    for (fmt, msg) in [
        ("%100.3d", "invalid conversion"),
        ("%1.100d", "invalid conversion"),
        ("%t", "invalid conversion"),
        ("%010c", "invalid conversion"),
        ("%.10c", "invalid conversion"),
        ("%0.34s", "invalid conversion"),
        ("%#i", "invalid conversion"),
        ("%3.1p", "invalid conversion"),
        ("%0.s", "invalid conversion"),
        ("%10q", "cannot have modifiers"),
        ("%F", "invalid conversion"),
        ("%d %d", "no value"),
    ] {
        let src = format!(
            "local ok, err = pcall(string.format, {fmt:?}, 10)\n\
             return tostring(not ok and err:find({msg:?}) ~= nil)"
        );
        assert_eq!(eval(&src), "true", "format {fmt:?}");
    }
    let aux = "0".repeat(600);
    let src = format!(
        "local ok, err = pcall(string.format, \"%1{aux}.3d\", 10)\n\
         return tostring(not ok and err:find('too long') ~= nil)"
    );
    assert_eq!(eval(&src), "true");
}

#[test_case("return string.format('%a', 1.0)" => "0x1p+0"; "hex_float_a_one")]
#[test_case("return string.format('%a', 0.5)" => "0x1p-1"; "hex_float_a_half")]
#[test_case("return string.format('%a', 0.0)" => "0x0p+0"; "hex_float_a_zero")]
#[test_case("return string.format('%a', -0.0)" => "-0x0p+0"; "hex_float_a_negative_zero")]
#[test_case("return string.format('%A', 12)" => "0X1.8P+3"; "hex_float_upper_A")]
#[test_case("return string.format('%+.2A', 12)" => "+0X1.80P+3"; "hex_float_plus_precision_upper_A")]
#[test_case("return string.format('%.4A', -12)" => "-0X1.8000P+3"; "hex_float_precision_upper_A_negative")]
// full precision round-trips
#[test_case("return tonumber(string.format('%a', 0.1)) == 0.1" => "true"; "hex_float_round_trip_zero_point_one")]
#[test_case("return tonumber(string.format('%a', 1e30)) == 1e30" => "true"; "hex_float_round_trip_1e30")]
#[test_case("return tonumber(string.format('%a', 1/3)) == 1/3" => "true"; "hex_float_round_trip_one_third")]
#[test_case("return string.format('%a', 1/0)" => "inf"; "hex_float_a_infinity")]
#[test_case("return string.format('%A', -1/0)" => "-INF"; "hex_float_upper_A_negative_infinity")]
fn string_format_hex_float(src: &str) -> String {
    eval(src)
}

#[test]
fn string_format_pointer_validation() {
    // '%p' only accepts the '-' flag and no precision (PUC checkformat)
    let e = run_err("return string.format('%+p', {})");
    assert!(e.contains("invalid conversion specification"), "{e}");
    let e = run_err("return string.format('%.3p', {})");
    assert!(e.contains("invalid conversion specification"), "{e}");
    let e = run_err("return string.format('%#p', {})");
    assert!(e.contains("invalid conversion specification"), "{e}");
    // widths and '-' flag remain valid
    assert_eq!(eval("return #string.format('%90p', {})"), "90");
    assert_eq!(eval("return #string.format('%-60p', {})"), "60");
    assert_eq!(eval("return string.format('%p', nil)"), "(null)");
}

#[test]
fn string_rep_overflow() {
    assert_eq!(eval("return string.rep('teste', 0)"), "");
    let e = run_err("return string.rep('ab', math.maxinteger)");
    assert!(e.contains("resulting string too large"), "{e}");
    let e = run_err("return string.rep('a', math.maxinteger)");
    assert!(e.contains("resulting string too large"), "{e}");
}

// ---- string.pack / unpack / packsize ----

#[test]
fn string_pack_round_trips() {
    assert_eq!(eval("return string.packsize('j')"), "8");
    assert_eq!(eval("return string.packsize('n')"), "8");
    assert_eq!(eval("return string.packsize('i4i4')"), "8");
    // no alignment by default (PUC's `initheader` sets maxalign = 1)
    assert_eq!(eval("return string.packsize('i1i8')"), "9");
    assert_eq!(eval("return string.packsize('i3')"), "3");
    assert_eq!(eval("return string.packsize('xxi4')"), "6");
    // `!n` enables alignment (PUC stores it directly in maxalign)
    assert_eq!(eval("return string.packsize('!8i1i8')"), "16");
    assert_eq!(eval("return string.packsize('!4i1i4')"), "8");
    assert_eq!(eval("return string.packsize('!8i1d')"), "16");
    // a later `!n` replaces the previous maximum (PUC semantics)
    assert_eq!(eval("return string.packsize('!8 i1 !2 i8')"), "10");
    assert_eq!(eval("return string.packsize('xx')"), "2");
    assert_eq!(eval("return string.packsize('<i4>i4')"), "8");
    let bytes = "return string.byte(string.pack('>i4', 0x01020304), 1, 4)";
    assert_eq!(eval_multi(bytes), ["1", "2", "3", "4"]);
    let bytes_le = "return string.byte(string.pack('<i4', 0x01020304), 1, 4)";
    assert_eq!(eval_multi(bytes_le), ["4", "3", "2", "1"]);
    // no padding is inserted between unaligned fields by default
    assert_eq!(
        eval_multi("return string.byte(string.pack('<i1i2', 2, 3), 1, 3)"),
        ["2", "3", "0"]
    );
    assert_eq!(
        eval_multi("return string.unpack('i4', string.pack('i4', -42))"),
        ["-42", "5"]
    );
    assert_eq!(
        eval_multi("return string.unpack('>i2', string.pack('>i2', -2))"),
        ["-2", "3"]
    );
    assert_eq!(
        eval_multi("return string.unpack('J', string.pack('J', -1))"),
        ["-1", "9"]
    );
    assert_eq!(
        eval("return string.unpack('z', string.pack('z', 'abc'))"),
        "abc"
    );
    assert_eq!(
        eval_multi("return string.unpack('z', string.pack('z', 'abc'))"),
        ["abc", "5"]
    );
    assert_eq!(
        eval_multi("return string.unpack('s1', string.pack('s1', 'hey'))"),
        ["hey", "5"]
    );
    assert_eq!(
        eval_multi("return string.unpack('i4i4', string.pack('i4i4', 7, 9), 1)"),
        ["7", "9", "9"]
    );
    assert_eq!(
        eval("return math.type(string.unpack('i4', string.pack('i4', 7)))"),
        "integer"
    );
    assert_eq!(
        eval("return math.type(string.unpack('d', string.pack('d', 7)))"),
        "float"
    );
    assert_eq!(
        eval("return string.unpack('d', string.pack('d', 1.5)) == 1.5"),
        "true"
    );
    assert_eq!(
        eval("return string.unpack('f', string.pack('f', 1.5)) == 1.5"),
        "true"
    );
}

#[test]
fn string_pack_errors() {
    assert!(run_err("return string.packsize('z')").contains("variable-length format"));
    assert!(run_err("return string.packsize('s')").contains("variable-length format"));
    assert!(run_err("return string.pack('b', 200)").contains("integer overflow"));
    assert!(run_err("return string.pack('B', -1)").contains("unsigned overflow"));
    assert!(run_err("return string.pack('c2', 'abc')").contains("string longer than given size"));
    assert!(run_err("return string.pack('z', 'a\\0b')").contains("string contains zeros"));
    assert!(
        run_err("return string.pack('s1', string.rep('a', 300))")
            .contains("string length does not fit in given size")
    );
    assert!(run_err("return string.unpack('i4', 'ab')").contains("data string too short"));
    assert!(run_err("return string.unpack('z', 'abc')").contains("unfinished string"));
    assert!(
        run_err("return string.unpack('i4', 'abcd', 9)").contains("initial position out of string")
    );
    assert!(
        run_err("return string.unpack('i4', 'abcd', math.maxinteger)")
            .contains("initial position out of string")
    );
    // PUC's posrelatI clips positions below -len to the start rather than erroring
    assert_eq!(
        eval_multi("return string.unpack('i4', 'abcd', math.mininteger)"),
        ["1684234849", "5"]
    );
    // position len+1 is the one-past-the-end sentinel and unpacks zero fields
    assert_eq!(
        eval_multi("return string.unpack('c0', 'abcd', 5)"),
        ["", "5"]
    );
    assert!(run_err("return string.packsize('i0')").contains("integral size (0) out of limits"));
    assert!(run_err("return string.packsize('Q')").contains("invalid format option 'Q'"));
    assert!(run_err("return string.packsize('c')").contains("missing size for format option 'c'"));
    assert!(run_err("return string.packsize('Xz')").contains("invalid next option for option 'X'"));
}

// ---- table ----

#[test_case("local t = {1, 2} table.insert(t, 3) return table.concat(t, ',')" => "1,2,3"; "insert_append")]
#[test_case("local t = {1, 3} table.insert(t, 2, 2) return table.concat(t, ',')" => "1,2,3"; "insert_at_position")]
#[test_case("local t = {1, 2, 3} local v = table.remove(t) return v .. ':' .. table.concat(t, ',')" => "3:1,2"; "remove_last")]
#[test_case("local t = {1, 2, 3} local v = table.remove(t, 1) return v .. ':' .. table.concat(t, ',')" => "1:2,3"; "remove_first")]
#[test_case("return tostring(table.remove({}))" => "nil"; "remove_empty_is_nil")]
fn table_insert_remove(src: &str) -> String {
    eval(src)
}

#[test]
fn table_concat_pack_unpack() {
    assert_eq!(eval("return table.concat({1, 'a', 2.5}, '-')"), "1-a-2.5");
    assert_eq!(eval("return table.concat({}, ',')"), "");
    assert_eq!(eval("return table.concat({1, 2, 3, 4}, ',', 2, 3)"), "2,3");
    assert_eq!(
        eval("local t = table.pack(10, 20, 30) return t.n .. ':' .. t[1] .. t[2] .. t[3]"),
        "3:102030"
    );
    assert_eq!(
        eval_multi("return table.unpack({1, 2, 3})"),
        ["1", "2", "3"]
    );
    assert_eq!(
        eval_multi("return table.unpack({1, 2, 3, 4}, 2, 3)"),
        ["2", "3"]
    );
    assert_eq!(
        eval("local function f(...) return select('#', ...) end return f(table.unpack({1,2,3}))"),
        "3"
    );
    // a range wider than the result cap must error, not overflow the host
    assert!(
        run_err("return table.unpack({}, math.mininteger, math.maxinteger)")
            .contains("too many results")
    );
    assert!(run_err("return table.unpack({}, 0, (1 << 31) - 1)").contains("too many results"));
    // empty ranges still return nothing
    assert_eq!(eval("return select('#', table.unpack({}, 10, 6))"), "0");
}

#[test]
fn ipairs_wraps_at_maxinteger() {
    assert_eq!(
        eval(
            "local t = {[math.mininteger] = 10} \
             local f = ipairs{} \
             local k, v = f(t, math.maxinteger) \
             assert(k == math.mininteger and v == 10) \
             return tostring(f(t, k))"
        ),
        "nil"
    );
}

#[test]
fn table_insert_respects_len_metamethod() {
    // `table.insert` lives in the Lua prelude so `#t` and `t[k] = v` go
    // through __len/__newindex; maxinteger + 1 wraps like PUC.
    assert_eq!(
        eval(
            "local t = setmetatable({}, {__len = function() return math.maxinteger end}) \
             table.insert(t, 20) \
             local k, v = next(t) \
             return k .. ':' .. v"
        ),
        "-9223372036854775808:20"
    );
    assert_eq!(
        eval(
            "local t = setmetatable({}, {__len = function() return 2 end}) \
             table.insert(t, 5) \
             return t[3]"
        ),
        "5"
    );
    assert_eq!(
        eval(
            "local t = setmetatable({}, {__len = function() return 2 end, \
              __newindex = function(t, k, v) rawset(t, k, v) end}) \
             table.insert(t, 1, 5) \
             return t[1]"
        ),
        "5"
    );
    assert!(run_err("table.insert({}, 0, 1)").contains("position out of bounds"));
    assert!(run_err("table.insert({}, 1, 2, 3)").contains("wrong number of arguments"));
}

#[test_case("local t = {5, 2, 8, 1, 9, 3} table.sort(t) return table.concat(t, ',')" => "1,2,3,5,8,9"; "default_order_numbers")]
#[test_case("local t = {5, 2, 8, 1} table.sort(t, function(a, b) return a > b end) return table.concat(t, ',')" => "8,5,2,1"; "custom_comparator_descending")]
#[test_case("local t = {'banana', 'apple', 'cherry'} table.sort(t) return table.concat(t, ',')" => "apple,banana,cherry"; "default_order_strings")]
#[test_case("local t = {} for i = 1, 200 do t[i] = (i * 7919) % 1000 end table.sort(t) for i = 2, 200 do assert(t[i-1] <= t[i]) end return 'sorted'" => "sorted"; "large_ish_sort_quicksort_path_comparator_through_vm")]
fn table_sort(src: &str) -> String {
    eval(src)
}

#[test]
fn table_sort_length_rules() {
    // PUC skips the sort entirely when the length is at most 1, so a
    // comparator that would blow up is never called.
    assert_eq!(
        eval(
            "local a = setmetatable({}, {__len = function() return -1 end}) \
             table.sort(a, error) return 'ok'"
        ),
        "ok"
    );
    // An oversized length is rejected up front, before any comparison.
    let e = run_err(
        "local a = setmetatable({}, {__len = function() return math.maxinteger end}) \
         table.sort(a, function() error('compared') end)",
    );
    assert!(e.contains("too big"), "unexpected error: {e}");
}

#[test]
fn table_sort_invalid_order_guard_small_arrays() {
    // PUC's small-range fast paths stop after sorting two or three elements,
    // so an always-true comparator is only detected from four elements up.
    let always = "function(a, b) assert(a and b); return true end";
    for n in 1..=3 {
        let src = format!(
            "local t = {{}} for i = 1, {n} do t[i] = i end table.sort(t, {always}) return 'ok'"
        );
        assert_eq!(eval(&src), "ok", "n={n} must not raise");
    }
    for n in 4..=6 {
        let src = format!("local t = {{}} for i = 1, {n} do t[i] = i end table.sort(t, {always})");
        let e = run_err(&src);
        assert!(e.contains("invalid order function"), "n={n} produced: {e}");
    }
}

#[test]
fn table_move() {
    // forward, overlapping, backward, and explicit-destination forms
    assert_eq!(
        eval("local a = {10,20,30} table.move(a,1,3,2) return table.concat(a, ',')"),
        "10,10,20,30"
    );
    assert_eq!(
        eval("local a = {10,20,30} table.move(a,1,3,3) return table.concat(a, ',')"),
        "10,20,10,20,30"
    );
    assert_eq!(
        eval("local a = {10,20,30} table.move(a,2,3,1) return table.concat(a, ',')"),
        "20,30,30"
    );
    assert_eq!(
        eval(
            "local a = {} \
             assert(table.move({10,20,30}, 1, 3, 1, a) == a) \
             return table.concat(a, ',')"
        ),
        "10,20,30"
    );
    // empty range and same-place move leave the table alone
    assert_eq!(
        eval(
            "local a = {1,2,3} \
             assert(table.move({10,20,30}, 1, 0, 3, a) == a) \
             table.move(a, 1, 10, 1) \
             return table.concat(a, ',')"
        ),
        "1,2,3"
    );
    // fringes of the integer range
    assert_eq!(
        eval(
            "local a = table.move({[math.maxinteger] = 100}, math.maxinteger, \
             math.maxinteger, math.mininteger) \
             return a[math.mininteger]"
        ),
        "100"
    );
    // bounds / overflow errors
    assert!(run_err("table.move(1, 2, 3, 4)").contains("table expected"));
    assert!(run_err("table.move({}, 1, math.maxinteger, 2)").contains("wrap around"));
    assert!(run_err("table.move({}, math.mininteger, math.maxinteger, 1)").contains("too many"));
}

#[test]
fn table_move_respects_metamethods() {
    // __index on the source, __newindex never touched (writes go to the dest)
    assert_eq!(
        eval(
            "local a = setmetatable({}, {__index = function(_, k) return k * 10 end, \
                                        __newindex = error}) \
             local b = table.move(a, 1, 10, 3, {}) \
             return b[3] .. ',' .. b[12]"
        ),
        "10,100"
    );
    // overlapping move into the source itself is done backwards
    assert_eq!(
        eval(
            "local t = {1, 2, 3} \
             local p = setmetatable({}, {__len = function() return #t end, \
                                        __index = t, __newindex = t}) \
             table.move(p, 1, 3, 2) \
             return table.concat(t, ',')"
        ),
        "1,1,2,3"
    );
}

#[test]
fn table_remove_concat_unpack_respect_metamethods() {
    // remove drives __len/__index/__newindex
    assert_eq!(
        eval(
            "local t = {1, 2, 3} \
             local p = setmetatable({}, {__len = function() return #t end, \
                                        __index = t, __newindex = t}) \
             local v = table.remove(p, 1) \
             return v .. ':' .. #t .. ':' .. table.concat(t, ',')"
        ),
        "1:2:2,3"
    );
    // concat drives __len/__index
    assert_eq!(
        eval(
            "local p = setmetatable({}, {__len = function() return 5 end, \
                                        __index = function(_, k) return k + 1 end}) \
             return table.concat(p, ';')"
        ),
        "2;3;4;5;6"
    );
    // unpack drives __len/__index
    assert_eq!(
        eval(
            "local t = {9, 10} \
             local p = setmetatable({}, {__len = function() return #t end, __index = t}) \
             local a, b, c = table.unpack(p) \
             return a .. ',' .. b .. ',' .. tostring(c)"
        ),
        "9,10,nil"
    );
    // plain tables keep the raw fast-path behavior
    assert_eq!(eval("return table.concat({1, 2, 3}, '-')"), "1-2-3");
    assert_eq!(eval("return tostring(table.remove({}))"), "nil");
    assert!(run_err("table.remove({1, 2}, 0)").contains("position out of bounds"));
    // border-0 element is returned and cleared, as in PUC
    assert_eq!(
        eval("local a = {[0] = 'ban'} return table.remove(a)"),
        "ban"
    );
    assert_eq!(
        eval("local a = {[0] = 'ban'} table.remove(a) return tostring(a[0])"),
        "nil"
    );
}

// ---- math ----

#[test]
fn math_basics() {
    assert_eq!(eval("return math.floor(3.7)"), "3");
    assert_eq!(eval("return math.floor(-3.2)"), "-4");
    assert_eq!(eval("return math.ceil(3.2)"), "4");
    assert_eq!(eval("return math.abs(-5)"), "5");
    assert_eq!(eval("return math.abs(-5.5)"), "5.5");
    assert_eq!(eval("return math.sqrt(16)"), "4.0");
    assert_eq!(eval("return math.max(3, 1, 4, 1, 5)"), "5");
    assert_eq!(eval("return math.min(3, 1, 4)"), "1");
    assert_eq!(eval("return math.fmod(7, 3)"), "1");
    assert_eq!(eval_multi("return math.modf(3.7)"), ["3", "0.7"]);
    assert_eq!(eval("return math.tointeger(42.0)"), "42");
    assert_eq!(eval("return tostring(math.tointeger(42.5))"), "nil");
    assert_eq!(
        eval("return math.type(1) .. '/' .. math.type(1.0)"),
        "integer/float"
    );
    assert_eq!(eval("return tostring(math.type('x'))"), "nil");
    assert_eq!(eval("return math.huge > 1e308"), "true");
    assert_eq!(eval("return math.maxinteger"), i64::MAX.to_string());
    assert_eq!(eval("return math.ult(-1, 0)"), "false"); // -1 as unsigned is huge
    assert_eq!(eval("return math.log(8, 2)"), "3.0");
    assert_eq!(eval("return math.sin(0)"), "0.0");
    assert_eq!(
        eval("return math.abs(math.deg(math.pi) - 180) < 1e-9"),
        "true"
    );
    assert_eq!(
        eval("return math.abs(math.rad(180) - math.pi) < 1e-9"),
        "true"
    );
    assert_eq!(eval("return math.deg(0)"), "0.0");
    assert_eq!(eval("return math.rad(0)"), "0.0");
}

#[test]
fn math_max_min_no_args_and_ordering() {
    // PUC math.lua lines 747-759: no args is "value expected" (named after
    // the full `math.max`/`math.min`, not the bare function).
    let emax = run_err("return math.max()");
    assert!(emax.contains("value expected"), "got: {emax}");
    assert!(emax.contains("math.max"), "got: {emax}");
    let emin = run_err("return math.min()");
    assert!(emin.contains("value expected"), "got: {emin}");
    assert!(emin.contains("math.min"), "got: {emin}");

    assert_eq!(eval("return math.max(3)"), "3");
    assert_eq!(eval("return math.max(3, 5, 9, 1)"), "9");
    assert_eq!(eval("return math.min(3)"), "3");
    assert_eq!(eval("return math.min(3, 5, 9, 1)"), "1");
    assert_eq!(eval("return math.min(3.2, 5.9, -9.2, 1.1)"), "-9.2");
    assert_eq!(eval("return math.min(1.9, 1.7, 1.72)"), "1.7");
    // Integer/float mixed ordering is exact (no f64 rounding).
    assert_eq!(
        eval("return math.max(math.maxinteger, 10e60) == 10e60"),
        "true"
    );
    assert_eq!(
        eval("return math.max(math.mininteger, math.mininteger + 1) == math.mininteger + 1"),
        "true"
    );
    assert_eq!(
        eval("return math.min(-10e60, math.mininteger) == -10e60"),
        "true"
    );
    assert_eq!(
        eval("return math.min(math.maxinteger, math.maxinteger - 1) == math.maxinteger - 1"),
        "true"
    );
}

#[test]
fn integer_representation_errors() {
    // PUC 5.4: these are runtime errors (the chunk loads fine), matching
    // math.lua's `checkcompt` helper which pcalls the loaded function.
    assert_eq!(eval("return type(load('return 2 // 0'))"), "function");
    assert!(run_err("return (load('return 2 // 0'))()").contains("attempt to divide by zero"));
    assert!(run_err("return 2.3 >> 0").contains("has no integer representation"));
    assert!(run_err("return 2.3 ~ 0.0").contains("has no integer representation"));
    assert!(run_err("return 1 | 2.0^63").contains("has no integer representation"));
    // PUC names the offending operand's provenance (varinfo).
    assert!(run_err("return math.huge << 1").contains("field 'huge'"));
    assert!(run_err("return math.huge | math.huge").contains("field 'huge'"));
}

#[test]
fn math_random_deterministic() {
    // fixed default seed: two fresh states agree
    let a = eval_multi("return math.random(100), math.random(100), math.random()");
    let b = eval_multi("return math.random(100), math.random(100), math.random()");
    assert_eq!(a, b);
    // ranges respected
    assert_eq!(
        eval(
            "for i = 1, 1000 do local r = math.random(10) assert(r >= 1 and r <= 10) end \
             for i = 1, 1000 do local r = math.random(-5, 5) assert(r >= -5 and r <= 5) end \
             for i = 1, 1000 do local r = math.random() assert(r >= 0 and r < 1) end \
             return 'ok'"
        ),
        "ok"
    );
    // reseeding changes the stream deterministically
    let c = eval_multi("math.randomseed(7) return math.random(1000), math.random(1000)");
    let d = eval_multi("math.randomseed(7) return math.random(1000), math.random(1000)");
    assert_eq!(c, d);
    assert_ne!(a[0], c[0]); // overwhelmingly likely
}

// PUC 5.4's `math.randomseed(1007)` then `math.random(0)` is
// 0x7a7040a5a323c9d6 (asserted by upstream math.lua).
#[test_case("math.randomseed(1007) return math.random(0)" => (0x7a70_40a5_a323_c9d6_u64 as i64).to_string(); "seed_1007_first_random_zero")]
#[test_case("math.randomseed(1007) local a = math.random(0) math.randomseed(1007, 0) return math.random(0) == a" => "true"; "one_seed_word_defaults_second_to_zero")]
#[test_case("local x, y = math.randomseed(123, 456) local a = math.random(0) math.randomseed(x, y) return math.random(0) == a and type(x) == 'number' and type(y) == 'number'" => "true"; "randomseed_returns_seed_words_and_reseeding_repeats")]
#[test_case("math.randomseed(1) for i = 1, 500 do local r = math.random(7) assert(r >= 1 and r <= 7) end for i = 1, 500 do local r = math.random(-3, 3) assert(r >= -3 and r <= 3) end return 'ok'" => "ok"; "single_arg_bound_projects_into_range")]
#[test_case("return (pcall(math.random, 1, 2, 3))" => "false"; "more_than_two_args_is_error")]
#[test_case("return (pcall(math.random, math.maxinteger, math.maxinteger - 1))" => "false"; "reversed_maxinteger_bounds_is_error")]
fn math_random_matches_puc_xoshiro(src: &str) -> String {
    eval(src)
}

// ---- integration: stdlib under strict fuel ----

#[test]
fn gsub_with_function_suspends() {
    // gsub's function-replacement path runs through the VM and must be
    // suspendable mid-replacement
    let mut lua = Lua::new();
    let chunk = lua
        .load(
            "local s = string.rep('x', 200) \
             local n = 0 \
             local r = s:gsub('x', function() n = n + 1 return tostring(n % 10) end) \
             return #r",
        )
        .unwrap();
    let mut exec = lua.execute(&chunk);
    let mut pendings = 0;
    loop {
        match exec.step(&mut lua, 500).unwrap() {
            Step::Done(vals) => {
                assert_eq!(vals, vec![Value::Int(200)]);
                break;
            }
            Step::Pending => {
                pendings += 1;
                assert!(pendings < 100_000, "runaway");
            }
            Step::Waiting(_) => panic!("unexpected native wait"),
        }
    }
    assert!(pendings > 5, "expected several suspensions, got {pendings}");
}

#[test]
fn sort_comparator_suspends() {
    let mut lua = Lua::new();
    let chunk = lua
        .load(
            "local t = {} \
             for i = 1, 100 do t[i] = (i * 31) % 100 end \
             table.sort(t, function(a, b) return a < b end) \
             return t[1], t[100]",
        )
        .unwrap();
    let mut exec = lua.execute(&chunk);
    loop {
        match exec.step(&mut lua, 100).unwrap() {
            Step::Done(vals) => {
                assert_eq!(vals[0], Value::Int(0));
                break;
            }
            Step::Pending => {}
            Step::Waiting(_) => panic!("unexpected native wait"),
        }
    }
}