Skip to main content

lua_rs_hlua_shim/
lib.rs

1//! A drop-in subset of the `hlua` 0.4 embedding API, backed by the pure-Rust
2//! omniLua VM instead of the C library.
3//!
4//! The goal is source compatibility: a consumer that does
5//! `use lua_rs_hlua_shim as hlua;` should compile and run against omniLua without
6//! touching its own code. The implemented surface is the part exercised by
7//! `authoscope` — `Lua`, `functionN`, `AnyLuaValue` and friends, `LuaFunction`,
8//! and `StringInLua`. It is intentionally not the whole hlua API.
9//!
10//! Sandboxing note: omniLua's runtime opens the full standard library, whereas
11//! hlua consumers typically open only `string`. This is acceptable for a
12//! compatibility spike but widens the sandbox; restricting the opened libraries
13//! is tracked as future work.
14
15mod any;
16mod func;
17
18use std::cell::Cell;
19use std::marker::PhantomData;
20
21use lua_stdlib::auxlib::load_buffer;
22use lua_stdlib::init::open_libs;
23use lua_types::closure::LuaLClosure;
24use lua_types::gc::GcRef;
25use lua_types::upval::UpVal;
26use lua_types::value::LuaValue;
27use lua_vm::api;
28use lua_vm::state::{new_state, LuaState};
29
30pub use any::{AnyHashableLuaValue, AnyLuaString, AnyLuaValue};
31pub use func::{
32    function0, function1, function2, function3, function4, function5, function6, FnHandle,
33    LuaFunction, StringInLua,
34};
35
36use func::{registry_remove, Adapter, FromLuaGlobal, SetValue};
37
38/// Error returned by `Lua::execute` and `LuaFunction::call_with_args`.
39///
40/// Carries only an owned message so the type is `Send + Sync + 'static` and
41/// flows through `anyhow`'s `?` the way `hlua::LuaError` does for consumers.
42#[derive(Debug, Clone)]
43pub struct LuaError {
44    message: String,
45}
46
47impl LuaError {
48    pub(crate) fn from_vm(err: lua_types::LuaError) -> Self {
49        LuaError {
50            message: format!("{err}"),
51        }
52    }
53}
54
55impl std::fmt::Display for LuaError {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.write_str(&self.message)
58    }
59}
60
61impl std::error::Error for LuaError {}
62
63/// A Lua state with the standard libraries installed.
64///
65/// The `'lua` parameter mirrors hlua's signature so consumer code that writes
66/// `Lua<'a>` keeps compiling; the shim itself owns its state outright.
67pub struct Lua<'lua> {
68    state: LuaState,
69    owned_closures: Vec<usize>,
70    _marker: PhantomData<&'lua ()>,
71}
72
73impl Default for Lua<'_> {
74    fn default() -> Self {
75        Self::new()
76    }
77}
78
79impl<'lua> Lua<'lua> {
80    /// Create a new Lua state with the standard libraries installed. Panics
81    /// only on allocation failure, matching the effective behaviour of
82    /// `hlua::Lua::new()`.
83    ///
84    /// Stdlib install runs inside a heap bootstrap window (guard + scope),
85    /// mirroring the runtime crate's `bootstrap_state`: without it every
86    /// library table and closure allocates detached and outlives the state —
87    /// issue #249's leak class, which stayed live on this lane after the
88    /// main runtime was fixed.
89    pub fn new() -> Lua<'lua> {
90        let mut state = new_state().expect("omniLua state allocation failed");
91        state.global_mut().parser_hook = Some(parser_hook);
92        {
93            let _bootstrap_scope = state.global().heap.bootstrap_scope();
94            let _heap_guard = {
95                let g = state.global();
96                lua_gc::HeapGuard::push(&g.heap)
97            };
98            open_libs(&mut state).expect("opening omniLua standard libraries failed");
99        }
100        Lua {
101            state,
102            owned_closures: Vec::new(),
103            _marker: PhantomData,
104        }
105    }
106
107    /// Open the string library. omniLua already opens the full standard library
108    /// at construction, so this is a no-op kept for API compatibility.
109    pub fn open_string(&mut self) {}
110
111    /// Load and run a chunk of Lua source.
112    pub fn execute<T: FromExec>(&mut self, code: &str) -> Result<T, LuaError> {
113        let status =
114            load_buffer(&mut self.state, code.as_bytes(), b"=(load)").map_err(LuaError::from_vm)?;
115        if status != 0 {
116            let err = self.state.pop();
117            return Err(LuaError::from_vm(lua_types::LuaError::from_value(err)));
118        }
119        api::pcall_k(&mut self.state, 0, 0, 0, 0, None).map_err(LuaError::from_vm)?;
120        T::from_exec(self)
121    }
122
123    /// Set a global. Accepts the `functionN` wrappers from this crate.
124    pub fn set<V: SetValue>(&mut self, name: &str, value: V) {
125        value.set_into(self, name);
126    }
127
128    /// Read a global by name. The value type is chosen by the caller, e.g.
129    /// `lua.get::<StringInLua<_>, _>("descr")`.
130    pub fn get<'l, V>(&'l mut self, name: &str) -> Option<V>
131    where
132        V: FromLuaGlobal<'l>,
133    {
134        V::from_lua_global(self, name)
135    }
136
137    pub(crate) fn state_mut(&mut self) -> &mut LuaState {
138        &mut self.state
139    }
140
141    /// Register a hosted closure as a global named `name`. The adapter index is
142    /// recorded so it is freed when this `Lua` is dropped.
143    pub(crate) fn install_closure(&mut self, name: &str, adapter: Adapter) {
144        let index = func::registry_insert(adapter);
145        self.owned_closures.push(index);
146        let state = &mut self.state;
147        api::push_integer(state, index as i64);
148        api::push_cclosure(state, func::trampoline, 1).expect("push_cclosure failed");
149        api::set_global(state, name.as_bytes()).expect("set_global failed");
150    }
151}
152
153impl Drop for Lua<'_> {
154    fn drop(&mut self) {
155        for &index in &self.owned_closures {
156            registry_remove(index);
157        }
158    }
159}
160
161/// The result type produced by [`Lua::execute`]. Only `()` is supported, which
162/// is all `authoscope` requires.
163pub trait FromExec: Sized {
164    fn from_exec(lua: &mut Lua<'_>) -> Result<Self, LuaError>;
165}
166
167impl FromExec for () {
168    fn from_exec(_lua: &mut Lua<'_>) -> Result<Self, LuaError> {
169        Ok(())
170    }
171}
172
173/// Compile a chunk to a Lua closure. Installed on the state so `load_buffer`
174/// has a front end; this is the same bootstrap `lua-rs-runtime` performs,
175/// inlined here so the shim depends only on published crates.
176fn parser_hook(
177    state: &mut LuaState,
178    z: &mut lua_vm::zio::ZIO,
179    name: &[u8],
180    firstchar: i32,
181) -> Result<GcRef<LuaLClosure>, lua_types::LuaError> {
182    let proto = lua_parse::parse(
183        state,
184        lua_parse::DynData::default(),
185        z,
186        name,
187        firstchar,
188    )?;
189    let nupvals = proto.upvalues.len();
190    let mut upvals = Vec::with_capacity(nupvals);
191    for _ in 0..nupvals {
192        upvals.push(Cell::new(GcRef::new(UpVal::closed(LuaValue::Nil))));
193    }
194    Ok(GcRef::new(LuaLClosure {
195        proto: GcRef::new(*proto),
196        upvals: upvals.into_boxed_slice(),
197    }))
198}