use slew::{Lua, NativeContext, NativeOutcome, NativeWait, 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..1000 {
match exec.step(lua, 100_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_eq!(vals.len(), 1, "expected 1 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, 100_000) {
Ok(Step::Done(_)) => panic!("expected error: {src}"),
Ok(Step::Pending) => {}
Ok(Step::Waiting(_)) => panic!("unexpected native wait"),
Err(e) => return e.to_string(),
}
}
}
#[test_case("return 1 + 2" => "3"; "integer_add")]
#[test_case("return 7 / 2" => "3.5"; "division_is_always_float")]
#[test_case("return 7 // 2" => "3"; "floor_division")]
#[test_case("return -7 // 2" => "-4"; "negative_floor_division")]
#[test_case("return 7 % 3" => "1"; "modulo")]
#[test_case("return -7 % 3" => "2"; "modulo_follows_divisor_sign")]
#[test_case("return 7.0 // 2" => "3.0"; "float_floor_division_stays_float")]
#[test_case("return 2 ^ 10" => "1024.0"; "power_is_always_float")]
#[test_case("return 1 + 0.5" => "1.5"; "mixed_int_float_add")]
#[test_case("return 9223372036854775807 + 1" => "-9223372036854775808"; "integer_overflow_wraps")]
#[test_case("return 1 == 1.0" => "true"; "int_float_equality")]
#[test_case("return 1 < 1.5" => "true"; "int_float_less_than")]
#[test_case("return 0.0 == -0.0" => "true"; "negative_zero_equals_zero")]
#[test_case("return 10 // 0.0" => "inf"; "float_division_by_zero_is_inf")]
#[test_case("return 3 & 5" => "1"; "bitwise_and")]
#[test_case("return 3 | 5" => "7"; "bitwise_or")]
#[test_case("return 3 ~ 5" => "6"; "bitwise_xor")]
#[test_case("return ~0" => "-1"; "bitwise_not")]
#[test_case("return 1 << 4" => "16"; "shift_left")]
#[test_case("return -1 >> 56" => "255"; "logical_shift_right")]
#[test_case("return 1 << 64" => "0"; "shift_left_past_width")]
#[test_case("return 2.0 & 3" => "2"; "exact_float_converts_to_integer")]
#[test_case("return 0/0 ~= 0/0" => "true"; "nan_not_equal_to_itself")]
#[test_case("return (0/0) < 1" => "false"; "nan_less_than_is_false")]
#[test_case("return 1 < (0/0)" => "false"; "less_than_nan_is_false")]
fn numbers_54_semantics(src: &str) -> String {
eval(src)
}
#[test_case("return 1 // 0", "attempt to divide by zero"; "integer_division_by_zero")]
#[test_case("return 1 % 0", "n%0"; "modulo_by_zero")]
#[test_case("return 1.5 & 2", "no integer representation"; "non_integer_bitwise_operand")]
#[test_case("return {} + 1", "arithmetic"; "table_arithmetic")]
fn integer_division_by_zero_errors(src: &str, needle: &str) {
assert!(run_err(src).contains(needle));
}
#[test]
fn numeric_string_arithmetic_coercion() {
assert_eq!(eval("return '2' + ' 3e0 '"), "5.0");
assert_eq!(eval("return ' -0xa ' + 1"), "-9");
assert_eq!(eval("return '10' - ' 10 '"), "0");
assert_eq!(
eval("return math.type('2' + 1) .. ':' .. math.type('2' + 1.0)"),
"integer:float"
);
assert_eq!(eval("return -' 10 '"), "-10");
assert_eq!(eval("return '2' ^ '3'"), "8.0");
assert_eq!(eval("return '7' % '3'"), "1");
assert!(run_err("return '2' | 1").contains("bitwise"));
assert!(run_err("return 'x' + 1").contains("arithmetic"));
assert_eq!(
eval(
"local t = setmetatable({}, {__add = function(a, b) return 42 end}) \
return '2' + t"
),
"42"
);
}
#[test]
fn next_rejects_invalid_keys() {
assert!(run_err("return next({10, 20}, 3)").contains("invalid key"));
assert!(run_err("return next({}, 0/0)").contains("invalid key"));
assert_eq!(
eval("local t = {10, 20} local k, v = next(t) return k .. ':' .. v"),
"1:10"
);
}
#[test]
fn local_env_declaration() {
assert_eq!(
eval(
"local e = {assert = assert, print = print} \
local _ENV = e \
x = 3 \
return e.x"
),
"3"
);
assert_eq!(
eval(
"local _ENV = {assert = assert, v = 7} \
local function f() return v end \
return f()"
),
"7"
);
}
#[test]
fn labels_are_invisible_to_enclosing_blocks() {
let mut lua = Lua::<()>::new();
for src in [
"do goto l end do ::l:: end",
"if true then goto l else ::l:: end",
"goto l do ::l:: end",
] {
let err = lua.load(src).unwrap_err().to_string();
assert!(err.contains("label"), "{src}: {err}");
}
assert_eq!(
eval(
"local x = 0 \
for i = 1, 3 do \
if i == 2 then goto continue end \
x = x + 1 \
::continue:: \
end \
return x"
),
"2"
);
}
#[test]
fn strings_and_concat() {
assert_eq!(eval("return 'a' .. 'b' .. 'c'"), "abc");
assert_eq!(eval("return 'x=' .. 1 .. ',' .. 1.5"), "x=1,1.5");
assert_eq!(eval("return #'hello'"), "5");
assert_eq!(eval("return 'abc' < 'abd'"), "true");
assert_eq!(eval("return 'Z' < 'a'"), "true"); assert_eq!(eval("return 'a' == 'a'"), "true");
assert!(run_err("return {} .. 'x'").contains("concatenate"));
}
#[test]
fn long_runtime_strings_have_distinct_identity() {
assert_eq!(
eval(
"local s1 = string.rep('a', 300)\n\
local s2 = string.rep('a', 300)\n\
return (s1 == s2) and (string.format('%p', s1) ~= string.format('%p', s2))"
),
"true"
);
}
#[test]
fn short_runtime_strings_are_interned() {
assert_eq!(
eval(
"local s1 = string.rep('a', 10)\n\
local s2 = string.rep('aa', 5)\n\
return (s1 == s2) and (string.format('%p', s1) == string.format('%p', s2))"
),
"true"
);
}
#[test]
fn long_literals_share_identity() {
assert_eq!(
eval(
"local function getadd(s) return string.format('%p', s) end\n\
local s1 <const> = '01234567890123456789012345678901234567890123456789'\n\
local s2 = '01234567890123456789012345678901234567890123456789'\n\
local function foo() return s1 end\n\
local a1 = getadd(s1)\n\
return (a1 == getadd(s2)) and (a1 == getadd(foo()))"
),
"true"
);
}
#[test]
fn concat_long_result_is_fresh() {
assert_eq!(
eval(
"local a = '01234567890123456789012345678901234567890123456789'\n\
local sd = '0123456789' .. '0123456789012345678901234567890123456789'\n\
return (sd == a) and (string.format('%p', sd) ~= string.format('%p', a))"
),
"true"
);
}
#[test]
fn table_keys_use_string_content() {
assert_eq!(
eval(
"local t = {}\n\
local k1 = string.rep('x', 300)\n\
local k2 = string.rep('x', 300)\n\
t[k1] = 1\n\
t[k2] = 2\n\
return (k1 == k2) and (t[k1] == 2) and (t[k2] == 2)"
),
"true"
);
}
#[test]
fn long_string_table_key_survives_gc() {
assert_eq!(
eval(
"local t = {}\n\
do local k = string.rep('y', 300) t[k] = 42 end\n\
collectgarbage()\n\
return t[string.rep('y', 300)]"
),
"42"
);
}
#[test]
fn rawequal_strings_by_content() {
assert_eq!(
eval(
"local a = string.rep('z', 300)\n\
local b = string.rep('z', 300)\n\
return rawequal(a, b) and a == b"
),
"true"
);
}
#[test]
fn gsub_reuses_original_when_unchanged() {
assert_eq!(
eval(
"local s = string.rep('a', 100)\n\
local r = string.gsub(s, 'b', 'c')\n\
local r2 = string.gsub(s, '.', function() return nil end)\n\
local r3 = string.gsub(s, '.', {x = 'y'})\n\
return (r == s) and (r2 == s) and (r3 == s)\n\
and (string.format('%p', r) == string.format('%p', s))\n\
and (string.format('%p', r2) == string.format('%p', s))\n\
and (string.format('%p', r3) == string.format('%p', s))"
),
"true"
);
}
#[test]
fn gsub_creates_fresh_string_on_substitution() {
assert_eq!(
eval(
"local s = string.rep('a', 100)\n\
local r = string.gsub(s, '.', function(x) return x end)\n\
return (r == s) and (string.format('%p', r) ~= string.format('%p', s))"
),
"true"
);
}
#[test]
fn rawget_rawset_use_long_string_content() {
assert_eq!(
eval(
"local t = {}\n\
local stored = string.rep('k', 300)\n\
rawset(t, stored, 7)\n\
local probe = string.rep('k', 300)\n\
return (string.format('%p', stored) ~= string.format('%p', probe))\n\
and (rawget(t, probe) == 7) and (next(t) == probe)"
),
"true"
);
}
#[test]
fn long_string_length_and_ordering() {
assert_eq!(
eval(
"local a = string.rep('a', 300)\n\
local b = string.rep('a', 300)\n\
local c = string.rep('a', 299) .. 'b'\n\
local d = string.rep('a', 301)\n\
return (#a == 300) and (a <= b) and (a >= b) and not (a < b)\n\
and (c > a) and (d > a) and (a < d)"
),
"true"
);
}
#[test_case("return tostring(nil)" => "nil"; "nil")]
#[test_case("return tostring(true)" => "true"; "boolean")]
#[test_case("return tostring(42)" => "42"; "integer")]
#[test_case("return tostring(1.0)" => "1.0"; "float_keeps_point_zero")]
#[test_case("return tostring(1/3)" => "0.33333333333333"; "float_precision")]
#[test_case("return tonumber('42')" => "42"; "tonumber_integer_string")]
#[test_case("return tonumber(' -0x10 ')" => "-16"; "tonumber_hex_with_whitespace")]
#[test_case("return tonumber('3.5e2')" => "350.0"; "tonumber_exponent")]
#[test_case("return tonumber('zz', 36)" => "1295"; "tonumber_base_36")]
#[test_case("return tonumber('hello')" => "nil"; "tonumber_invalid_returns_nil")]
#[test_case("return type(3) .. type('') .. type(nil)" => "numberstringnil"; "type_concatenation")]
fn tostring_conversions(src: &str) -> String {
eval(src)
}
#[test_case("return math.type(tonumber('-9223372036854775808'))" => "integer"; "signed_minimum_stays_integer")]
#[test_case("return tonumber('-9223372036854775808') == math.mininteger" => "true"; "signed_minimum_equals_mininteger")]
#[test_case("return math.type(tonumber('-9223372036854775809'))" => "float"; "one_past_signed_minimum_is_float")]
#[test_case("return math.type(tonumber('9223372036854775809'))" => "float"; "positive_one_past_signed_max_is_float")]
#[test_case("return tonumber('-9223372036854775809') == -9223372036854775809" => "true"; "negative_overflow_float_equality")]
#[test_case("return tonumber('9223372036854775809') == 9223372036854775809" => "true"; "positive_overflow_float_equality")]
#[test_case("return tonumber('+ 0.01')" => "nil"; "sign_space_rejected_plus")]
#[test_case("return tonumber('- 0.01')" => "nil"; "sign_space_rejected_minus")]
#[test_case("return tonumber('+0.01')" => "0.01"; "sign_without_space_accepted")]
fn tonumber_signed_integer_boundaries(src: &str) -> String {
eval(src)
}
#[test_case("local s = 0 for i = 1, 10 do s = s + i end return s" => "55"; "numeric_for_sums")]
#[test_case("local s = 0 for i = 10, 1, -2 do s = s + i end return s" => "30"; "numeric_for_negative_step")]
#[test_case("local s = 0 for i = 1, 0 do s = s + 1 end return s" => "0"; "numeric_for_empty_range")]
#[test_case("local s = 0.0 for i = 1.0, 2.0, 0.5 do s = s + i end return s" => "4.5"; "numeric_for_float_step")]
#[test_case("local n, i = 0, 1 while i <= 100 do n = n + i i = i + 1 end return n" => "5050"; "while_loop")]
#[test_case("local i = 0 repeat i = i + 1 until i >= 5 return i" => "5"; "repeat_until")]
#[test_case("local done repeat local x = 5 done = x until done return done" => "5"; "until_sees_body_locals")]
#[test_case("local r = '' for i = 1, 10 do if i % 2 == 0 then r = r .. i elseif i == 5 then break end end return r" => "24"; "break_in_loop")]
#[test_case("if false then return 1 elseif nil then return 2 else return 3 end" => "3"; "if_elseif_else")]
#[test_case("return false or nil" => "nil"; "or_returns_nil")]
#[test_case("return nil and 1 or 2" => "2"; "and_or_chain")]
#[test_case("return 0 and 'zero is truthy'" => "zero is truthy"; "zero_is_truthy")]
fn control_flow(src: &str) -> String {
eval(src)
}
#[test]
fn numeric_for_edge_cases() {
assert_eq!(
eval(
"local n = 0 for i = 9223372036854775805, 9223372036854775807 do n = n + 1 end return n"
),
"3"
);
assert_eq!(
eval("local n = 0 for i = 1, 3.5 do n = n + 1 end return n"),
"3"
);
assert!(run_err("for i = 1, 10, 0 do end").contains("step is zero"));
assert!(run_err("for i = 1, 'x' do end").contains("must be a number"));
}
#[test]
fn numeric_for_string_coercion() {
assert_eq!(
eval(r#"local a = 0 for i = "10", "1", "-2" do a = a + 1 end return a"#),
"5"
);
assert_eq!(
eval(r#"for i = "10", "1", "-2" do return math.type(i) end"#),
"float"
);
assert_eq!(
eval(r#"for i = 1, "3.5" do return math.type(i) end"#),
"integer"
);
assert_eq!(
eval(r#"for i = 1, 3, "1.0" do return math.type(i) end"#),
"float"
);
assert_eq!(
eval(r#"local n = 0 for i = 1, "3" do n = n + 1 end return n"#),
"3"
);
assert_eq!(
eval("local a = 0 for i = 10.0, 1, -1 do a = a + 1 end return a"),
"10"
);
assert_eq!(
eval(r#"local a = 0 for i = 1, 10 do a = a + 1; i = "x" end return a"#),
"10"
);
assert!(
run_err(r#"for i = 1, "x" do end"#).contains("'for' limit must be a number"),
"integer loop limit error"
);
assert!(
run_err(r#"for i = "x", 1 do end"#).contains("'for' initial value must be a number"),
"float loop initial-value error"
);
assert!(
run_err(r#"for i = 1, 10, "x" do end"#).contains("'for' step must be a number"),
"float loop step error"
);
}
#[test]
fn functions_and_recursion() {
assert_eq!(
eval(
"local function fib(n) if n < 2 then return n end return fib(n-1) + fib(n-2) end return fib(20)"
),
"6765"
);
assert_eq!(
eval("local function f(a, b) return b, a end local x, y = f(1, 2) return x * 10 + y"),
"21"
);
assert_eq!(
eval_multi("local function f() return 1, 2, 3 end return f()"),
["1", "2", "3"]
);
assert_eq!(
eval("local function f() return 1, 2, 3 end return (f())"),
"1"
); assert_eq!(
eval_multi("local function f() return 1, 2 end return f(), 10"),
["1", "10"] );
assert_eq!(
eval_multi("local function f() return 1, 2 end return 10, f()"),
["10", "1", "2"] );
assert_eq!(
eval("local function f(a, b) return tostring(b) end return f(1)"),
"nil"
);
assert_eq!(
eval("local function f(a) return a end return f(1, 2, 3)"),
"1"
);
}
#[test_case(
"local function counter() local n = 0 return function() n = n + 1 return n end end \
local c = counter() c() c() return c()" => "3"; "closure_state_persists"
)]
#[test_case(
"local function make() local n = 0 return function() n = n + 1 end, function() return n end end \
local inc, get = make() inc() inc() return get()" => "2"; "two_closures_share_upvalue"
)]
#[test_case(
"local fs = {} for i = 1, 3 do fs[i] = function() return i end end \
return fs[1]() * 100 + fs[2]() * 10 + fs[3]()" => "123"; "loop_iteration_captures_fresh_variable"
)]
#[test_case(
"local x = 1 local function outer() local function inner() x = x + 1 return x end return inner end \
return outer()()" => "2"; "upvalue_through_two_levels"
)]
fn closures_and_upvalues(src: &str) -> String {
eval(src)
}
#[test_case("local function f(...) return select('#', ...) end return f(1, nil, 3)" => "3"; "select_count")]
#[test_case("local function f(...) local a, b = ... return a + b end return f(10, 20, 30)" => "30"; "extra_args_ignored")]
#[test_case("local function f(...) return ... end return (select(2, f(1, 2, 3)))" => "2"; "select_from_second")]
#[test_case("local function f(a, ...) return a + select('#', ...) end return f(10, 1, 1, 1)" => "13"; "named_param_plus_count")]
#[test_case("local function f(...) local t = {...} return #t end return f(1, 2, 3)" => "3"; "pack_into_table")]
fn varargs(src: &str) -> String {
eval(src)
}
#[test]
fn tables() {
assert_eq!(eval("local t = {1, 2, 3} return #t"), "3");
assert_eq!(eval("local t = {a = 1, b = 2} return t.a + t.b"), "3");
assert_eq!(
eval("local t = {[2] = 'two', 'one'} return t[1] .. t[2]"),
"onetwo"
);
assert_eq!(eval("local t = {} t[1.0] = 'x' return t[1]"), "x"); assert_eq!(eval("local t = {} t.x = 10 t.x = t.x + 1 return t.x"), "11");
assert_eq!(
eval(
"local t = {10, 20, 30} local s = 0 for i, v in ipairs(t) do s = s + i * v end return s"
),
"140"
);
assert_eq!(
eval(
"local t = {a = 1, b = 2, c = 3} local s = 0 for k, v in pairs(t) do s = s + v end return s"
),
"6"
);
assert_eq!(
eval("local t = {1, 2, f = 3} local n = 0 for k in pairs(t) do n = n + 1 end return n"),
"3"
);
assert_eq!(
eval("local function f() return 2, 3, 4 end local t = {1, f()} return #t"),
"4"
);
assert_eq!(eval("local t = {x = {y = {z = 42}}} return t.x.y.z"), "42");
assert_eq!(
eval("local obj = {n = 10} function obj:get() return self.n end return obj:get()"),
"10"
);
assert!(run_err("local t = {} t[nil] = 1").contains("table index is nil"));
assert!(run_err("local x = nil return x.field").contains("attempt to index a nil value"));
assert!(run_err("local x = 5 x()").contains("attempt to call a number value"));
}
#[test]
fn multi_assignment_target_conflicts() {
assert_eq!(
eval(
"local a, i, j, b \
a = {'a', 'b'}; i = 1; j = 2; b = a \
i, a[i], a, j, a[j], a[i+j] = j, i, i, b, j, i \
return tostring(i == 2 and b[1] == 1 and a == 1 and j == b and \
b[2] == 2 and b[3] == 1)"
),
"true"
);
assert_eq!(
eval(
"local a, b = {}, nil \
local function foo() b, a.x, a = a, 10, 20 end \
foo() \
return tostring(a == 20 and b.x == 10)"
),
"true"
);
assert_eq!(
eval(
"local a, i, j, b \
a = {'a', 'b'}; i = 1; j = 2; b = a \
local function foo() \
i, a[i], a, j, a[j], a[i+j] = j, i, i, b, j, i \
end \
foo() \
return tostring(i == 2 and b[1] == 1 and a == 1 and j == b and \
b[2] == 2 and b[3] == 1)"
),
"true"
);
assert_eq!(
eval("local t = {} (function(a) t[a], a = 10, 20 end)(1) return t[1]"),
"10"
);
}
#[test]
fn big_table_constructor_flushes() {
let src = format!(
"local t = {{{}}} return #t + t[60]",
(1..=120)
.map(|i| i.to_string())
.collect::<Vec<_>>()
.join(", ")
);
assert_eq!(eval(&src), "180");
}
#[test]
fn globals() {
assert_eq!(eval("x = 42 return x"), "42");
assert_eq!(eval("return tostring(undefined_global)"), "nil");
assert_eq!(
eval("function double(n) return 2 * n end return double(21)"),
"42"
);
let mut lua = Lua::new();
run(&mut lua, "answer = 6 * 7");
assert_eq!(lua.get_global("answer"), Value::Int(42));
lua.set_global("from_rust", Value::Int(7));
let vals = run(&mut lua, "return from_rust * 6");
assert_eq!(vals, vec![Value::Int(42)]);
}
#[test]
fn const_attrib_enforced() {
let mut lua = Lua::<()>::new();
let err = lua.load("local x <const> = 1 x = 2").unwrap_err();
assert!(err.to_string().contains("const"));
}
#[test]
fn infinite_loop_suspends() {
let mut lua = Lua::new();
let chunk = lua.load("n = 0 while true do n = n + 1 end").unwrap();
let mut exec = lua.execute(&chunk);
for _ in 0..10 {
assert_eq!(exec.step(&mut lua, 1_000).unwrap(), Step::Pending);
}
let Value::Int(n) = lua.get_global("n") else {
panic!()
};
assert!(n > 100, "loop should have progressed, n = {n}");
assert!(!exec.is_finished());
}
#[test]
fn fuel_is_deterministic() {
let observe = |budgets: &[u64]| -> i64 {
let mut lua = Lua::new();
let chunk = lua
.load("n = 0 for i = 1, 1000000 do n = n + 1 end")
.unwrap();
let mut exec = lua.execute(&chunk);
for &b in budgets {
let _ = exec.step(&mut lua, b).unwrap();
}
match lua.get_global("n") {
Value::Int(n) => n,
_ => panic!(),
}
};
let a = observe(&[1000, 1000, 1000]);
let b = observe(&[1000, 1000, 1000]);
assert_eq!(a, b, "same fuel must reach the same state");
let c = observe(&[1000, 1000, 1000, 1000]);
assert!(c > a);
}
#[test]
fn fuel_proportional_progress() {
let progress = |fuel: u64| -> i64 {
let mut lua = Lua::new();
let chunk = lua.load("n = 0 while true do n = n + 1 end").unwrap();
let mut exec = lua.execute(&chunk);
assert_eq!(exec.step(&mut lua, fuel).unwrap(), Step::Pending);
match lua.get_global("n") {
Value::Int(n) => n,
_ => panic!(),
}
};
let p1 = progress(10_000);
let p2 = progress(20_000);
let ratio = p2 as f64 / p1 as f64;
assert!(
(1.9..=2.1).contains(&ratio),
"ratio {ratio}, p1 {p1}, p2 {p2}"
);
}
#[test]
fn suspension_mid_call_resumes_correctly() {
let mut lua = Lua::new();
let chunk = lua
.load(
"local function add(a, b) return a + b end \
local s = 0 \
for i = 1, 100 do s = add(s, i) end \
return s",
)
.unwrap();
let mut exec = lua.execute(&chunk);
let mut steps = 0u64;
loop {
match exec.step(&mut lua, 1).unwrap() {
Step::Done(vals) => {
assert_eq!(vals, vec![Value::Int(5050)]);
break;
}
Step::Pending => {
steps += 1;
assert!(steps < 1_000_000, "runaway");
}
Step::Waiting(_) => panic!("unexpected native wait"),
}
}
assert!(
steps > 1000,
"should have taken many single-instruction steps"
);
}
#[test]
fn zero_fuel_makes_no_progress() {
let mut lua = Lua::new();
let chunk = lua.load("n = 0 while true do n = n + 1 end").unwrap();
let mut exec = lua.execute(&chunk);
assert_eq!(exec.step(&mut lua, 0).unwrap(), Step::Pending);
assert_eq!(lua.get_global("n"), Value::Nil); }
#[test]
fn step_after_done_errors() {
let mut lua = Lua::new();
let chunk = lua.load("return 1").unwrap();
let mut exec = lua.execute(&chunk);
assert_eq!(
exec.step(&mut lua, 100).unwrap(),
Step::Done(vec![Value::Int(1)])
);
assert!(exec.step(&mut lua, 100).is_err());
}
#[test]
fn execution_location_tracks_current_line() {
let mut lua = Lua::new();
let chunk = lua.load("local n = 0\nn = n + 1\nreturn n").unwrap();
let mut exec = lua.execute(&chunk);
assert_eq!(exec.step(&mut lua, 1).unwrap(), Step::Pending);
let (source, line) = exec.current_location(&lua).expect("pending has a location");
assert_eq!(source, "chunk");
assert!((1..=3).contains(&line), "line out of range: {line}");
loop {
if let Step::Done(_) = exec.step(&mut lua, 100).unwrap() {
break;
}
}
assert!(exec.current_location(&lua).is_none());
}
#[test]
fn two_executions_share_globals_but_not_control() {
let mut lua = Lua::new();
let writer = lua
.load("i = (i or 0) while true do i = i + 1 end")
.unwrap();
let reader = lua.load("return i").unwrap();
let mut w = lua.execute(&writer);
let _ = w.step(&mut lua, 5_000).unwrap();
let mut r = lua.execute(&reader);
let Step::Done(vals) = r.step(&mut lua, 1_000).unwrap() else {
panic!("reader should finish")
};
let Value::Int(i) = vals[0] else { panic!() };
assert!(i > 0);
assert_eq!(w.step(&mut lua, 1_000).unwrap(), Step::Pending);
}
#[derive(Debug, PartialEq)]
struct RobotContext {
robot: u32,
moves: Vec<(u32, String)>,
}
fn move_robot(
ctx: &mut NativeContext<'_, RobotContext>,
args: &[Value],
) -> Result<NativeOutcome, String> {
let robot = ctx.context().robot;
let direction = ctx
.str_bytes(args.first().copied().unwrap_or(Value::Nil))
.ok_or("direction must be a string")?;
let direction = String::from_utf8(direction.to_vec()).unwrap();
ctx.context_mut().moves.push((robot, direction));
Ok(NativeOutcome::Wait(NativeWait(robot as u64)))
}
#[test]
fn suspendable_native_waits_for_host_completion() {
let mut lua = slew::Lua::<RobotContext>::new();
lua.register_suspendable_native("move", move_robot);
let chunk = lua
.load("local arrived = move('east'); return arrived, 'continued'")
.unwrap();
let mut exec = lua.execute_with_context(
&chunk,
RobotContext {
robot: 7,
moves: Vec::new(),
},
);
assert_eq!(
exec.step(&mut lua, 100_000).unwrap(),
Step::Waiting(NativeWait(7))
);
assert_eq!(exec.context().moves, vec![(7, "east".into())]);
assert_eq!(
exec.step(&mut lua, 100_000).unwrap(),
Step::Waiting(NativeWait(7))
);
exec.complete_native(&mut lua, NativeWait(7), Ok(vec![Value::Bool(true)]))
.unwrap();
let Step::Done(values) = exec.step(&mut lua, 100_000).unwrap() else {
panic!("execution should complete")
};
assert_eq!(values[0], Value::Bool(true));
assert_eq!(lua.display_value(values[1]), "continued");
}
#[test]
fn suspendable_native_resumes_inside_coroutine() {
let mut runtime = slew::Lua::<RobotContext>::new();
runtime.register_suspendable_native("move", move_robot);
let chunk = runtime
.load(
"local co = coroutine.create(function() return move('south') end)\n\
local ok, moved = coroutine.resume(co)\n\
return ok, moved, coroutine.status(co)",
)
.unwrap();
let mut exec = runtime.execute_with_context(
&chunk,
RobotContext {
robot: 11,
moves: Vec::new(),
},
);
assert_eq!(
exec.step(&mut runtime, 100_000).unwrap(),
Step::Waiting(NativeWait(11))
);
exec.complete_native(&mut runtime, NativeWait(11), Ok(vec![Value::Bool(true)]))
.unwrap();
let Step::Done(values) = exec.step(&mut runtime, 100_000).unwrap() else {
panic!("execution should complete")
};
assert_eq!(values[0], Value::Bool(true));
assert_eq!(values[1], Value::Bool(true));
assert_eq!(runtime.display_value(values[2]), "dead");
}
#[test]
fn native_completion_error_is_caught_by_pcall() {
let mut lua = slew::Lua::<RobotContext>::new();
lua.register_suspendable_native("move", move_robot);
let chunk = lua.load("return pcall(move, 'north')").unwrap();
let mut exec = lua.execute_with_context(
&chunk,
RobotContext {
robot: 9,
moves: Vec::new(),
},
);
assert_eq!(
exec.step(&mut lua, 100_000).unwrap(),
Step::Waiting(NativeWait(9))
);
exec.complete_native(&mut lua, NativeWait(9), Err("blocked".into()))
.unwrap();
let Step::Done(values) = exec.step(&mut lua, 100_000).unwrap() else {
panic!("pcall should catch completion error")
};
assert_eq!(values[0], Value::Bool(false));
assert_eq!(lua.display_value(values[1]), "blocked");
}
#[test]
fn execution_context_identifies_each_robot() {
let mut lua = slew::Lua::<RobotContext>::new();
lua.register_suspendable_native("move", move_robot);
let chunk = lua.load("return move('west')").unwrap();
let mut first = lua.execute_with_context(
&chunk,
RobotContext {
robot: 1,
moves: Vec::new(),
},
);
let mut second = lua.execute_with_context(
&chunk,
RobotContext {
robot: 2,
moves: Vec::new(),
},
);
assert_eq!(
first.step(&mut lua, 100_000).unwrap(),
Step::Waiting(NativeWait(1))
);
assert_eq!(
second.step(&mut lua, 100_000).unwrap(),
Step::Waiting(NativeWait(2))
);
assert_ne!(first.id(), second.id());
assert_eq!(first.context().moves[0].0, 1);
assert_eq!(second.context().moves[0].0, 2);
}
#[test]
fn runtime_error_reports_line() {
let err = run_err("local x = 1\nlocal y = 2\nreturn x + {}");
assert!(err.contains("chunk:3:"), "got: {err}");
}
#[test]
fn runtime_error_reports_root_line() {
let mut lua = Lua::new();
let chunk = lua
.load("local function boom()\n error('kaboom')\nend\nlocal x = boom()\nreturn x")
.unwrap();
let mut exec = lua.execute(&chunk);
let err = loop {
match exec.step(&mut lua, 100_000) {
Ok(Step::Done(_)) => panic!("expected error"),
Ok(Step::Pending) => {}
Ok(Step::Waiting(_)) => panic!("unexpected native wait"),
Err(e) => break e,
}
};
let slew::Error::Runtime(e) = err else {
panic!("expected runtime error: {err:?}")
};
assert_eq!(e.line, 2, "innermost raise site");
assert_eq!(e.root_line, 4, "call site in the root chunk");
}
#[test]
fn deep_recursion_hits_depth_limit_not_host_stack() {
let err = run_err("local function f() return f() + 1 end return f()");
assert!(err.contains("stack overflow"), "got: {err}");
}
#[test]
fn tail_recursion_is_constant_depth() {
assert_eq!(
eval(
"local function f(n) if n == 0 then return 101 else return f(n-1) end end return f(100000)"
),
"101"
);
}
#[test]
fn mutual_tail_recursion_is_constant_depth() {
assert_eq!(
eval(
"local ev, od\n\
function ev(n) if n == 0 then return true else return od(n-1) end end\n\
function od(n) if n == 0 then return false else return ev(n-1) end end\n\
return ev(100001)"
),
"false"
);
}
#[test_case("local function f() return 1 end return f()" => "1"; "plain_call")]
#[test_case("local t = {} function t.f() return 2 end return t.f()" => "2"; "dot_access")]
#[test_case("local t = {v = 3} function t:m() return self.v end return t:m()" => "3"; "method_call")]
#[test_case("local f = function() return 4 end return (f)()" => "4"; "parenthesized_callee")]
fn tail_call_shapes(src: &str) -> String {
eval(src)
}
#[test]
fn tail_call_with_varargs() {
assert_eq!(
eval(
"local function f(a, b, c) return a + b + c end\n\
local function g(...) return f(...) end\n\
return g(1, 2, 3)"
),
"6"
);
assert_eq!(
eval_multi("local function f(...) return ... end return f('a', 'b', 'c')"),
vec!["a", "b", "c"]
);
}
#[test]
fn tail_call_through_call_metamethod() {
assert_eq!(
eval(
"local t = setmetatable({}, {__call = function(self, n)\n\
if n == 0 then return 77 else return self(n - 1) end\n\
end})\n\
return t(100000)"
),
"77"
);
}
#[test]
fn tail_calls_inside_coroutine() {
assert_eq!(
eval(
"local function loop(n) if n == 0 then return 5 else return loop(n - 1) end end\n\
return coroutine.wrap(function() return loop(100000) end)()"
),
"5"
);
}
#[test]
fn deep_non_tail_recursion_still_errors() {
let err = run_err(
"local function f(n) if n == 0 then return 0 else return 1 + f(n - 1) end end return f(100000)",
);
assert!(err.contains("stack overflow"), "got: {err}");
}