Let modules decide their own name via #[cdef] macro

This commit is contained in:
2025-06-26 17:47:21 +10:00
parent 1c1753234d
commit 0cafac0948
11 changed files with 113 additions and 50 deletions

View File

@@ -158,16 +158,16 @@ impl Registry {
self
}
pub fn preload<T: Type>(&mut self, name: impl Display) -> &mut Self {
pub fn preload<T: Module>(&mut self) -> &mut Self {
assert!(T::ty() != TypeType::Void, "cannot declare void type");
self.include::<T>();
let ct = T::name();
let name = <T as Module>::name();
let ct = <T as Type>::name();
writeln!(
self.lua,
r#"__preload["{name}"] = function(...) return __ct.{ct}(...); end;"#,
)
.unwrap();
self
self.include::<T>()
}
pub fn build(&self) -> String {
@@ -240,6 +240,10 @@ impl<'r> TypeBuilder<'r> {
}
}
pub trait Module: Type {
fn name() -> impl Display;
}
pub unsafe trait Cdef: Type {
fn build(b: &mut CdefBuilder);
}
@@ -320,6 +324,7 @@ pub struct MetatypeBuilder<'r> {
ct: String,
cdef: String,
lua: String,
lua_includes: Vec<&'static str>,
}
impl<'r> MetatypeBuilder<'r> {
@@ -329,6 +334,7 @@ impl<'r> MetatypeBuilder<'r> {
ct: T::Target::name().to_string(),
cdef: String::new(),
lua: r#"do local __mt, __idx = {}, {}; __mt.__index = __idx; "#.into(),
lua_includes: vec![],
}
}
@@ -337,6 +343,11 @@ impl<'r> MetatypeBuilder<'r> {
self
}
pub fn include_lua(&mut self, lua: &'static str) -> &mut Self {
self.lua_includes.push(lua);
self
}
pub fn index(
&mut self,
name: impl Display,
@@ -377,12 +388,15 @@ impl<'r> Drop for MetatypeBuilder<'r> {
ct,
cdef,
lua,
..
lua_includes: lua_postlude,
} = self;
registry.cdef.push_str(cdef);
registry.lua.push_str(lua);
writeln!(registry.lua, r#"__metatype(__ct.{ct}, __mt); end;"#).unwrap();
for lua in lua_postlude {
writeln!(registry.lua, r#"do {lua} end;"#).unwrap();
}
}
}