Skip to main content

luaur_rt/
function.rs

1//! The [`Function`] handle. Mirrors `mlua::Function`.
2
3use crate::error::Result;
4use crate::multi::MultiValue;
5use crate::state::{Lua, LuaRef};
6use crate::sync::{MaybeSend, NotSync, XRc, NOT_SYNC};
7use crate::sys::*;
8use crate::traits::{FromLuaMulti, IntoLuaMulti};
9
10/// A handle to a callable Lua value (a Lua closure or a Rust function).
11///
12/// Mirrors `mlua::Function`. Under the `send` feature it is `Send` but never
13/// `Sync` — see [`crate::sync::NotSync`].
14#[derive(Clone)]
15pub struct Function {
16    pub(crate) reference: XRc<LuaRef>,
17    pub(crate) _not_sync: NotSync,
18}
19
20impl Function {
21    pub(crate) fn from_ref(reference: LuaRef) -> Function {
22        Function {
23            reference: XRc::new(reference),
24            _not_sync: NOT_SYNC,
25        }
26    }
27
28    pub(crate) unsafe fn push_to_stack(&self) {
29        self.reference.push();
30    }
31
32    /// The owning [`Lua`].
33    pub fn lua(&self) -> Lua {
34        self.reference.lua()
35    }
36
37    /// Call the function with `args`, converting the results to `R`.
38    ///
39    /// Mirrors `mlua::Function::call`. Runs under `lua_pcall`, so a Lua runtime
40    /// error (or a Rust callback returning `Err`) becomes `Err(Error)` rather
41    /// than unwinding.
42    pub fn call<R: FromLuaMulti>(&self, args: impl IntoLuaMulti) -> Result<R> {
43        let lua = self.lua();
44        let state = lua.state();
45        let args: MultiValue = args.into_lua_multi(&lua)?;
46
47        unsafe {
48            let base = lua_gettop(state);
49            let nargs = args.len() as c_int;
50            // Guard against pushing more values than the Lua stack can hold:
51            // an unprotected overflow would abort the VM. We need room for the
52            // function + all arguments (+1 slack for the call machinery).
53            if lua_checkstack(state, nargs.saturating_add(2)) == 0 {
54                return Err(crate::error::Error::RuntimeError(
55                    "stack overflow: too many arguments to function call".to_string(),
56                ));
57            }
58            // Push the function, then the arguments.
59            self.reference.push();
60            for v in args.iter() {
61                lua.push_value(v)?;
62            }
63            // LUA_MULTRET == -1: keep every result.
64            let status = lua_pcall(state, nargs, -1, 0);
65            if status != 0 {
66                return Err(lua.pop_error(status));
67            }
68            // The result-collection loop below reads each reference-typed result
69            // via `value_from_stack`, which DUPLICATES it onto the stack
70            // (`lua_pushvalue`) before popping it into a registry ref. After a
71            // LUA_MULTRET call the results can fill the C frame's stack exactly to
72            // `ci->top` (LUA_MINSTACK), so that duplicating push would overrun the
73            // frame — the `api_incr_top` assert in `lua_pushvalue`. Reserve a slot
74            // of headroom for it. (Found by the `run` fuzzer:
75            // `local t={a=1}; return <~20 values including t>`.)
76            if lua_checkstack(state, 2) == 0 {
77                lua_settop(state, base);
78                return Err(crate::error::Error::RuntimeError(
79                    "stack overflow: too many return values".to_string(),
80                ));
81            }
82            // Collect every value pushed above `base` as the results. Hand
83            // them to `R::from_stack_multi` so types with a stack fast path
84            // (floats) can read the raw values without materializing `Value`s
85            // (the `Value` normalization folds `-0.0` into a positive zero;
86            // mlua avoids the same problem via `FromLuaMulti::from_stack_multi`).
87            let top = lua_gettop(state);
88            let nresults = top - base;
89            let result = R::from_stack_multi(base, nresults, &lua);
90            lua_settop(state, base);
91            result
92        }
93    }
94
95    /// Return a new function that, when called, prepends `args` to its own
96    /// arguments and forwards to `self`.
97    ///
98    /// Mirrors `mlua::Function::bind`. Implemented as a Rust closure that
99    /// captures the bound prefix and the target function.
100    #[cfg(not(feature = "async"))]
101    pub fn bind(&self, args: impl IntoLuaMulti) -> Result<Function> {
102        let lua = self.lua();
103        let bound: MultiValue = args.into_lua_multi(&lua)?;
104        let target = self.clone();
105        let bound_vec: Vec<crate::value::Value> = bound.into_vec();
106        lua.create_function(move |_, extra: MultiValue| {
107            let mut all = MultiValue::with_capacity(bound_vec.len() + extra.len());
108            for v in &bound_vec {
109                all.push_back(v.clone());
110            }
111            for v in extra {
112                all.push_back(v);
113            }
114            target.call::<MultiValue>(all)
115        })
116    }
117
118    /// Return a new function that, when called, prepends `args` to its own
119    /// arguments and forwards to `self`.
120    ///
121    /// Mirrors `mlua::Function::bind`. Under the `async` feature this is built as
122    /// a **pure-Lua closure** (`function(...) return func(prepend(...)) end`)
123    /// rather than a Rust trampoline, so the forwarded call is a Lua-level call
124    /// and remains **yield-transparent**: a bound async function can still yield
125    /// while its future is pending. (The `prepend` helper only rearranges
126    /// arguments and returns, so it never yields across a C boundary.) Behavior
127    /// is identical to the non-async implementation for ordinary functions.
128    #[cfg(feature = "async")]
129    pub fn bind(&self, args: impl IntoLuaMulti) -> Result<Function> {
130        let lua = self.lua();
131        let bound: MultiValue = args.into_lua_multi(&lua)?;
132        let bound_vec: Vec<crate::value::Value> = bound.into_vec();
133
134        // `prepend(...)` returns the bound prefix followed by the call args.
135        let prepend = lua.create_function(move |_, extra: MultiValue| {
136            let mut all = MultiValue::with_capacity(bound_vec.len() + extra.len());
137            for v in &bound_vec {
138                all.push_back(v.clone());
139            }
140            for v in extra {
141                all.push_back(v);
142            }
143            Ok(all)
144        })?;
145
146        // Build the wrapper closure in Lua so the inner `func(...)` is a Lua
147        // call (yield-transparent), capturing `func` and `prepend` as upvalues.
148        let builder: Function = lua
149            .load(
150                r#"
151                local func, prepend = ...
152                return function(...)
153                    return func(prepend(...))
154                end
155                "#,
156            )
157            .set_name("__luaur_bind")
158            .into_function()?;
159        builder.call::<Function>((self.clone(), prepend))
160    }
161
162    /// Call the function asynchronously: run it on a fresh coroutine and drive
163    /// that coroutine to completion as a Rust [`Future`](std::future::Future).
164    ///
165    /// Mirrors `mlua::Function::call_async`. Works for both async functions
166    /// (created via [`Lua::create_async_function`](crate::Lua::create_async_function))
167    /// — which yield while their inner future is pending — and ordinary
168    /// functions (which simply run to completion). Calling an async function
169    /// with the *synchronous* [`Function::call`] instead raises a runtime error,
170    /// matching mlua.
171    #[cfg(feature = "async")]
172    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
173    pub fn call_async<R>(
174        &self,
175        args: impl IntoLuaMulti,
176    ) -> impl std::future::Future<Output = Result<R>>
177    where
178        R: FromLuaMulti,
179    {
180        let lua = self.lua();
181        // Build the driver eagerly so argument-conversion / thread-creation
182        // errors surface when awaited (wrapped in a ready future).
183        let setup: Result<crate::async_support::AsyncThread<R>> = (|| {
184            let thread = lua.create_thread(self.clone())?;
185            // The coroutine is *implicit* (created by `call_async`): register it
186            // so `Lua::current_thread` running on it resolves to the owner (the
187            // thread that issued this call). Mirrors mlua's thread-ownership map.
188            crate::async_support::register_implicit_thread(thread.state(), lua.state());
189            let mut th = thread.into_async(args)?;
190            th.set_implicit(true);
191            Ok(th)
192        })();
193        async move { setup?.await }
194    }
195
196    /// Wrap a Rust async function/closure as a value convertible into a Lua
197    /// function.
198    ///
199    /// Mirrors `mlua::Function::wrap_async`. Unlike
200    /// [`Lua::create_async_function`](crate::Lua::create_async_function) the
201    /// closure does not receive the [`Lua`] and its arity is free (0, 1, … args
202    /// mapped from the Lua call arguments). The returned value is
203    /// [`IntoLua`](crate::IntoLua) so it can be stored directly (e.g.
204    /// `globals().set("f", Function::wrap_async(..))`). A returned `Err` is
205    /// raised as a Lua error.
206    #[cfg(feature = "async")]
207    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
208    pub fn wrap_async<F, A, R, E>(func: F) -> impl crate::traits::IntoLua
209    where
210        F: crate::async_support::LuaNativeAsyncFn<A, Output = std::result::Result<R, E>>
211            + crate::sync::MaybeSend
212            + 'static,
213        A: FromLuaMulti,
214        R: IntoLuaMulti + 'static,
215        E: crate::error::ExternalError + 'static,
216    {
217        crate::async_support::WrappedAsync::new(move |_lua: Lua, a: A| {
218            let fut = func.call(a);
219            async move { fut.await.map_err(crate::error::ExternalError::into_lua_err) }
220        })
221    }
222
223    /// Like [`Function::wrap_async`] but the closure's output is passed through
224    /// to Lua as-is (a returned `Result` becomes an `(ok, err)`-style multi
225    /// value rather than being raised).
226    ///
227    /// Mirrors `mlua::Function::wrap_raw_async`.
228    #[cfg(feature = "async")]
229    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
230    pub fn wrap_raw_async<F, A>(func: F) -> impl crate::traits::IntoLua
231    where
232        F: crate::async_support::LuaNativeAsyncFn<A> + crate::sync::MaybeSend + 'static,
233        F::Output: IntoLuaMulti + 'static,
234        A: FromLuaMulti,
235    {
236        crate::async_support::WrappedAsync::new(move |_lua: Lua, a: A| {
237            let fut = func.call(a);
238            async move { Ok(fut.await) }
239        })
240    }
241
242    /// Wrap a plain Rust closure as a value convertible into a Lua function.
243    ///
244    /// Mirrors `mlua::Function::wrap`. Unlike
245    /// [`Lua::create_function`](crate::Lua::create_function), the closure does
246    /// **not** receive the [`Lua`] and its arity is free (`||`, `|a|`, `|a, b|`,
247    /// … mapped from the Lua call arguments). The returned value is
248    /// [`IntoLua`](crate::IntoLua) so it can be stored directly (e.g.
249    /// `table.set("f", Function::wrap(|a, b| Ok::<_, Error>(a + b)))`). A
250    /// returned `Err` is raised as a Lua error.
251    pub fn wrap<F, A, R, E>(func: F) -> impl crate::traits::IntoLua
252    where
253        F: LuaNativeFn<A, Output = std::result::Result<R, E>> + MaybeSend + 'static,
254        A: FromLuaMulti,
255        R: IntoLuaMulti,
256        E: crate::error::ExternalError,
257    {
258        WrappedFunction {
259            func,
260            _marker: std::marker::PhantomData,
261        }
262    }
263
264    /// A raw pointer identifying this function (for identity comparison).
265    /// Mirrors `mlua::Function::to_pointer`.
266    pub fn to_pointer(&self) -> *const std::ffi::c_void {
267        let state = self.reference.state();
268        unsafe {
269            self.reference.push();
270            let p = lua_topointer(state, -1);
271            lua_pop(state, 1);
272            p
273        }
274    }
275
276    /// The function's environment table (its globals), or `None` for a Rust
277    /// (C) function. Mirrors `mlua::Function::environment`.
278    pub fn environment(&self) -> Option<crate::table::Table> {
279        let lua = self.lua();
280        let state = lua.state();
281        unsafe {
282            self.reference.push();
283            // `lua_getfenv` only applies to Lua closures; a C function has no
284            // accessible environment.
285            if !self.is_lua_closure() {
286                lua_pop(state, 1);
287                return None;
288            }
289            lua_getfenv(state, -1);
290            // stack: [func, env]
291            if lua_type(state, -1) != ttype::TABLE {
292                lua_pop(state, 2);
293                return None;
294            }
295            let env = crate::table::Table::from_ref(lua.pop_ref());
296            lua_pop(state, 1); // pop func
297            Some(env)
298        }
299    }
300
301    /// Set the function's environment table. Returns `Ok(false)` for a Rust
302    /// (C) function (which has no settable environment) and `Ok(true)` for a
303    /// Lua closure. Mirrors `mlua::Function::set_environment`.
304    pub fn set_environment(&self, env: crate::table::Table) -> Result<bool> {
305        let lua = self.lua();
306        let state = lua.state();
307        unsafe {
308            self.reference.push();
309            if !self.is_lua_closure() {
310                lua_pop(state, 1);
311                return Ok(false);
312            }
313            // stack: [func]; push env, then lua_setfenv(func_index).
314            env.push_to_stack();
315            let ok = lua_setfenv(state, -2);
316            // lua_setfenv pops the env table; pop the function too.
317            lua_pop(state, 1);
318            Ok(ok != 0)
319        }
320    }
321
322    /// Whether the value on top of the stack (this function, just pushed) is a
323    /// Lua closure (vs a C function). Determined via the debug `what` field.
324    unsafe fn is_lua_closure(&self) -> bool {
325        let state = self.reference.state();
326        unsafe {
327            // The function is on top of the stack (index -1). Ask lua_getinfo
328            // about it via the ">" level convention: push the function and use
329            // option ">" so it pops the function and reads its info.
330            lua_pushvalue(state, -1);
331            let mut ar: LuaDebug = core::mem::zeroed();
332            let opt = c">s";
333            let ok = lua_getinfo(state, -1, opt.as_ptr() as *const c_char, &mut ar);
334            if ok == 0 {
335                return false;
336            }
337            if ar.what.is_null() {
338                return false;
339            }
340            let what = std::ffi::CStr::from_ptr(ar.what).to_bytes();
341            // "Lua" and "main" are Lua closures; "C" is a native function.
342            what == b"Lua" || what == b"main"
343        }
344    }
345
346    /// Debug information about this function. Mirrors `mlua::Function::info`.
347    pub fn info(&self) -> FunctionInfo {
348        let lua = self.lua();
349        let state = lua.state();
350        unsafe {
351            self.reference.push();
352            let mut ar: LuaDebug = core::mem::zeroed();
353            // Options: n=name, s=source/what/linedefined, a=params/vararg,
354            // u=upvalues. The ">" prefix pops the function from the stack and
355            // reads info about it.
356            let opt = c">nsau";
357            let ok = lua_getinfo(state, -1, opt.as_ptr() as *const c_char, &mut ar);
358            if ok == 0 {
359                return FunctionInfo::default();
360            }
361            let cstr = |p: *const c_char| -> Option<String> {
362                if p.is_null() {
363                    None
364                } else {
365                    Some(std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned())
366                }
367            };
368            let what = cstr(ar.what).unwrap_or_default();
369            let line_defined = if ar.linedefined > 0 {
370                Some(ar.linedefined as i64)
371            } else {
372                None
373            };
374            // Lua chunks are loaded with a `=<name>` chunkname marker; mlua
375            // reports the bare name in `source`, so strip a single leading
376            // `=`/`@` for Lua/main functions. C functions keep their VM-reported
377            // source verbatim (e.g. `=[C]`), matching mlua.
378            let source = cstr(ar.source).map(|s| {
379                if (what == "Lua" || what == "main") && (s.starts_with('=') || s.starts_with('@')) {
380                    s[1..].to_string()
381                } else {
382                    s
383                }
384            });
385            FunctionInfo {
386                name: cstr(ar.name),
387                source,
388                short_src: cstr(ar.short_src),
389                line_defined,
390                last_line_defined: None, // Luau does not report it.
391                what,
392                num_upvalues: ar.nupvals,
393                num_params: ar.nparams,
394                is_vararg: ar.isvararg != 0,
395            }
396        }
397    }
398}
399
400/// Debug information about a [`Function`]. Mirrors `mlua::debug::FunctionInfo`
401/// (the subset Luau reports).
402#[derive(Clone, Debug, Default)]
403pub struct FunctionInfo {
404    /// The function's name, if known (Luau records the call-site name).
405    pub name: Option<String>,
406    /// The chunk source name (e.g. `"=[C]"` for native functions).
407    pub source: Option<String>,
408    /// A short, human-readable source description.
409    pub short_src: Option<String>,
410    /// The line where the function was defined, if it is a Lua function.
411    pub line_defined: Option<i64>,
412    /// The last line of the function's definition. Always `None` in Luau.
413    pub last_line_defined: Option<i64>,
414    /// `"Lua"`, `"C"`, or `"main"`.
415    pub what: String,
416    /// The number of upvalues.
417    pub num_upvalues: u8,
418    /// The number of fixed parameters.
419    pub num_params: u8,
420    /// Whether the function is variadic.
421    pub is_vararg: bool,
422}
423
424impl std::fmt::Debug for Function {
425    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
426        write!(f, "Function")
427    }
428}
429
430impl PartialEq for Function {
431    fn eq(&self, other: &Self) -> bool {
432        // Pointer identity (matches mlua): same underlying function object.
433        self.to_pointer() == other.to_pointer()
434    }
435}
436
437// ---------------------------------------------------------------------------
438// LuaNativeFn: arity-abstracting sync closure trait (mirrors mlua)
439// ---------------------------------------------------------------------------
440
441/// A function/closure callable with a tuple of `FromLuaMulti` arguments,
442/// abstracting over arity. Mirrors `mlua::LuaNativeFn`. Lets
443/// [`Function::wrap`] accept `||`, `|a|`, `|a, b|`, … closures uniformly (the
444/// closure receives the converted args directly, not the [`Lua`]).
445pub trait LuaNativeFn<A: FromLuaMulti> {
446    /// The closure's return type (typically `Result<R, E>`).
447    type Output;
448
449    /// Invoke the closure with the converted arguments.
450    fn call(&self, args: A) -> Self::Output;
451}
452
453macro_rules! impl_lua_native_fn {
454    ($($A:ident),*) => {
455        impl<FN, $($A,)* R> LuaNativeFn<($($A,)*)> for FN
456        where
457            FN: Fn($($A,)*) -> R,
458            ($($A,)*): FromLuaMulti,
459        {
460            type Output = R;
461
462            #[allow(non_snake_case)]
463            fn call(&self, args: ($($A,)*)) -> R {
464                let ($($A,)*) = args;
465                self($($A,)*)
466            }
467        }
468    };
469}
470
471impl_lua_native_fn!();
472impl_lua_native_fn!(A);
473impl_lua_native_fn!(A, B);
474impl_lua_native_fn!(A, B, C);
475impl_lua_native_fn!(A, B, C, D);
476impl_lua_native_fn!(A, B, C, D, E);
477impl_lua_native_fn!(A, B, C, D, E, F);
478impl_lua_native_fn!(A, B, C, D, E, F, G);
479impl_lua_native_fn!(A, B, C, D, E, F, G, H);
480
481/// A plain closure not yet bound to a [`Lua`]. Becomes a Lua function (via
482/// [`Lua::create_function`]) when converted with [`IntoLua`]. Backs
483/// [`Function::wrap`].
484struct WrappedFunction<F, A, R, E> {
485    func: F,
486    _marker: std::marker::PhantomData<fn(A) -> (R, E)>,
487}
488
489impl<F, A, R, E> crate::traits::IntoLua for WrappedFunction<F, A, R, E>
490where
491    F: LuaNativeFn<A, Output = std::result::Result<R, E>> + MaybeSend + 'static,
492    A: FromLuaMulti,
493    R: IntoLuaMulti,
494    E: crate::error::ExternalError,
495{
496    fn into_lua(self, lua: &Lua) -> Result<crate::value::Value> {
497        let func = self.func;
498        let f = lua.create_function(move |_lua, args: A| {
499            func.call(args)
500                .map_err(crate::error::ExternalError::into_lua_err)
501        })?;
502        Ok(crate::value::Value::Function(f))
503    }
504}