#![allow(clippy::tests_outside_test_module)]
use std::sync::{Arc, Mutex};
use ruau::{
surface::{Surface, VmConfig},
typecheck::{Config, Diagnostics, Mode},
vm::{
Ambient, CallOptions, FromLuaMulti, HostType, HostTypeBuilder, Limits, MarshaledPair,
ModuleBinding, MultiValue, NativeModule, RuntimeError, Scope, ScopedHostFunction,
ScopedValue, ValueSnapshot,
module::{Installer as ModuleBuilder, InstallerExt as ModuleBuilderExt},
},
};
use serde_json::json;
const COUNTER_CLASS: &str = "\
declare class Counter
function get(self): number
function add(self, by: number): number
end";
const COUNTER_GLOBALS: &str = "\
declare counter: {
make: (number) -> Counter,
}";
struct Counter {
count: f64,
}
fn counter_get(_: &Scope<'_>, counter: &Counter, (): ()) -> Result<f64, RuntimeError> {
Ok(counter.count)
}
fn counter_add(_: &Scope<'_>, counter: &mut Counter, by: f64) -> Result<f64, RuntimeError> {
counter.count += by;
Ok(counter.count)
}
fn counter_type() -> HostType {
HostTypeBuilder::<Counter>::new("Counter")
.method("get", counter_get)
.method_mut("add", counter_add)
.marshal(|counter| {
ValueSnapshot::Table(vec![MarshaledPair {
key: ValueSnapshot::String(b"count".to_vec()),
value: ValueSnapshot::Number(counter.count),
}])
})
.tostring(|counter| format!("Counter({})", counter.count))
.declaration(COUNTER_CLASS)
.build()
}
struct MakeCounter;
impl ScopedHostFunction for MakeCounter {
fn call<'s>(
&self,
scope: &Scope<'s>,
args: MultiValue<'s>,
) -> Result<MultiValue<'s>, RuntimeError> {
let start = f64::from_lua_multi(args, scope)?;
let userdata = scope.create_userdata(Counter { count: start })?;
Ok(MultiValue::from_values(vec![ScopedValue::Userdata(
userdata,
)]))
}
}
struct CounterModule {
declaration: String,
}
impl CounterModule {
fn new() -> Self {
let class = counter_type();
Self {
declaration: format!(
"{}\n\n{}\n",
class
.declaration()
.expect("the Counter type carries a class"),
COUNTER_GLOBALS
),
}
}
}
impl NativeModule for CounterModule {
fn name(&self) -> &str {
"counter"
}
fn declaration(&self) -> ruau_declaration::DeclarationSource<'_> {
ruau_declaration::DeclarationSource::Text(&self.declaration)
}
fn install(&self, builder: &mut dyn ModuleBuilder) {
ModuleBuilderExt::host_type(builder, counter_type());
builder.scoped_function(
"make",
ModuleBinding::library("counter"),
Box::new(MakeCounter),
);
}
}
fn counter_surface() -> Surface {
Surface::builder()
.module(Arc::new(CounterModule::new()))
.build()
.expect("the counter surface validates")
}
fn check(surface: &Surface, source: &str, mode: Mode) -> Diagnostics {
let mut checker = surface.new_checker();
checker
.check_source_with_config(source, Config::with_source_mode(mode))
.diagnostics()
.clone()
}
#[test]
fn declared_userdata_methods_typecheck_via_the_module_declaration() {
let surface = counter_surface();
let clean = check(
&surface,
"local c = counter.make(5)\n\
local total: number = c:add(2)\n\
local read: number = c:get()\n\
local _ = total + read\n",
Mode::Strict,
);
assert!(clean.is_empty(), "unexpected diagnostics: {clean:?}");
let bad_argument = check(
&surface,
"local c = counter.make(5)\nlocal _ = c:add('nope')\n",
Mode::Strict,
);
assert!(
!bad_argument.is_empty(),
"c:add('nope') must fail the checker"
);
let unknown_method = check(
&surface,
"local c = counter.make(5)\nc:missing()\n",
Mode::Strict,
);
assert!(
!unknown_method.is_empty(),
"c:missing() must fail the checker"
);
}
#[test]
fn surface_conformance_check_uses_the_retained_surface() {
let surface = counter_surface();
let check = surface.check_conformance(
"--!strict\nreturn { count = 7, extra = true }",
"--!strict\ndeclare module: { count: number }",
);
assert!(check.is_ok(), "{:?}", check.diagnostics());
let bad = surface.check_conformance(
"--!strict\nreturn { count = \"bad\" }",
"--!strict\ndeclare module: { count: number }",
);
assert!(!bad.diagnostics().is_empty(), "{bad:?}");
}
#[tokio::test]
async fn a_sandboxed_script_exercises_a_registered_type_end_to_end() {
let surface = counter_surface();
let source = "--!nonstrict\n\
local c = counter.make(3)\n\
c:add(4)\n\
-- The shared metatable is protected: scripts see the type name, and\n\
-- cannot reach (or mutate) the dispatch table behind it.\n\
local meta = getmetatable(c)\n\
local ok = pcall(function() (meta :: any).__index = nil end)\n\
assert(not ok, 'metatable must not be writable')\n\
print(c)\n\
return c:get(), typeof(c), meta, tostring(c), c\n";
let diagnostics = check(&surface, source, Mode::Nonstrict);
assert!(
diagnostics.is_empty(),
"unexpected diagnostics: {diagnostics:?}"
);
let mut vm = surface
.vm_builder(&VmConfig::untrusted(
Ambient::deterministic(7),
Limits {
gas: Some(1_000_000),
max_memory_bytes: Some(8 * 1024 * 1024),
..Limits::unlimited()
},
))
.build()
.expect("sandboxed VM builds");
let chunk = surface
.compile(
&ruau::source::Source::text(
ruau::source::ModuleId::canonicalized("counter-e2e"),
source,
),
&ruau::bytecode::CompileOptions::default(),
)
.expect("compile");
let module = vm.load_named(&chunk, b"=counter_e2e.luau").expect("load");
let print_bytes = Arc::new(Mutex::new(Vec::new()));
let print_capture = Arc::clone(&print_bytes);
let values = vm
.exec_async(
&module,
CallOptions::new().print_sink(Box::new(move |bytes| {
print_capture
.lock()
.expect("print capture lock is not poisoned")
.extend_from_slice(bytes);
})),
)
.await
.expect("script runs");
match values.as_slice() {
[
ValueSnapshot::Number(total),
ValueSnapshot::String(type_name),
ValueSnapshot::String(meta),
ValueSnapshot::String(rendered),
counter,
] => {
assert_eq!(*total, 7.0);
assert_eq!(type_name.as_slice(), b"Counter");
assert_eq!(meta.as_slice(), b"Counter");
assert_eq!(rendered.as_slice(), b"Counter(7)");
assert_eq!(
ruau::vm::serde::marshaled_to_json(counter).expect("userdata hook is JSON"),
json!({ "count": 7 })
);
assert_eq!(
String::from_utf8(
print_bytes
.lock()
.expect("print capture lock is not poisoned")
.clone()
)
.expect("print output is utf-8"),
"Counter(7)\n"
);
}
other => panic!("unexpected result shape: {other:?}"),
}
}