gmodx 0.25.0

A swiss army knife for creating binary modules for Garry's Mod in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#[cfg(feature = "tokio")]
use std::sync::Mutex;
use std::{ffi::CStr, fmt::Display, mem};

use crate::lua::{
    self, FromLuaMulti, StackGuard, ToLuaMulti, Value, ffi,
    traits::{FromLua, ToLua},
    types::{Callback, MaybeSend},
};

#[cfg(feature = "tokio")]
static THREAD_WRAP: Mutex<Option<Function>> = Mutex::new(None);

#[cfg(feature = "tokio")]
fn get_thread_wrap() -> Function {
    THREAD_WRAP
        .lock()
        .unwrap()
        .clone()
        .expect("THREAD_WRAP is not initialized")
}

#[cfg(feature = "tokio")]
inventory::submit! {
    crate::open_close::new(
        0,
        "async_thread_wrap",
        |l| {
            // 😉 ;-)
            let chunk = l.load_buffer(b"
                local co_resume = coroutine.resume
                local xpcall = xpcall
                local debug_traceback = debug.traceback
                return function(done, f, ...)
                    return done(xpcall(f, debug_traceback, ...))
                end
            ", c"async_thread_wrap").expect("failed to load async thread wrap chunk");
            let func = chunk.call::<Function>(l, ()).expect("failed to get async thread wrap function");
            *THREAD_WRAP.lock().unwrap() = Some(func);
        },
        |_| {
            *THREAD_WRAP.lock().unwrap() = None;
        },
    )
}

#[derive(Clone, Debug)]
pub struct Function(pub(crate) Value);

impl Function {
    pub fn call<R: FromLuaMulti>(&self, l: &lua::State, args: impl ToLuaMulti) -> lua::Result<R> {
        let stack_start = ffi::lua_gettop(l.0);
        let _sg = StackGuard::with_top(l.0, stack_start);
        #[allow(clippy::needless_borrow)]
        (&self.0).push_to_stack(l); // Push the function onto the stack
        args.push_to_stack_multi(l);
        let nargs = ffi::lua_gettop(l.0) - stack_start - 1;
        match ffi::lua_pcall(l.0, nargs, ffi::LUA_MULTRET, 0) {
            ffi::LUA_OK => {}
            res => return Err(l.pop_error(res)),
        }
        let nresults = ffi::lua_gettop(l.0) - stack_start;
        R::try_from_stack_multi(l, stack_start + 1, nresults).map(|(v, _)| v)
    }

    #[cfg(feature = "tokio")]
    pub async fn call_async<R: FromLuaMulti + Send + 'static>(
        &self,
        args: impl ToLuaMulti,
    ) -> lua::Result<R> {
        use std::sync::{Arc, Mutex};
        use tokio::sync::Notify;

        use crate::lua::State;

        struct Shared<R> {
            result: Mutex<Option<lua::Result<R>>>,
            notify: Notify,
        }

        let shared = Arc::new(Shared {
            result: Mutex::new(None),
            notify: Notify::new(),
        });
        let notified = shared.notify.notified();

        {
            let Some(l) = lua::lock_async().await else {
                return Err(lua::Error::StateUnavailable);
            };

            let thread = l.create_thread(get_thread_wrap());
            let done = l.create_function({
                let shared = shared.clone();
                move |l: &State| {
                    let nargs = ffi::lua_gettop(l.0);
                    let res = match bool::try_from_stack(l, 1) {
                        Ok(true) => R::try_from_stack_multi(l, 2, nargs - 1).map(|(v, _)| v),
                        Ok(false) => {
                            let err_msg = lua::String::try_from_stack(l, 2)
                                .unwrap_or_else(|e| e.to_string().into());
                            Err(lua::Error::Runtime(err_msg))
                        }
                        Err(e) => Err(e),
                    };
                    *shared.result.lock().unwrap() = Some(res);
                    shared.notify.notify_one();
                }
            });

            let func = self.clone();
            thread.resume::<()>(&l, (done, func, args))?;
        }

        if shared.result.lock().unwrap().is_none() {
            notified.await;
        }

        shared.result.lock().unwrap().take().unwrap()
    }
}

const CLOSURE_GC_METATABLE_NAME: &CStr = gmodx_macros::unique_id!(cstr);

impl lua::State {
    pub fn create_function<F, Marker>(&self, func: F) -> Function
    where
        F: IntoLuaFunction<Marker>,
    {
        func.into_function()
    }

    pub(crate) fn create_function_impl(&self, func: Callback) -> Function {
        let callback_ptr =
            ffi::lua_newuserdata(self.0, mem::size_of::<Callback>()).cast::<Callback>();

        debug_assert_eq!(
            (callback_ptr as usize) % mem::align_of::<Callback>(),
            0,
            "Lua userdata has insufficient alignment for Callback"
        );

        unsafe {
            callback_ptr.write(func);
        }

        if ffi::luaL_newmetatable(self.0, CLOSURE_GC_METATABLE_NAME.as_ptr()) {
            extern "C-unwind" fn gc_rust_function(l: *mut lua::ffi::lua_State) -> i32 {
                let l = lua::State(l);
                let data_ptr = ffi::lua_touserdata(l.0, 1).cast::<Callback>();
                if !data_ptr.is_null() {
                    unsafe {
                        // Read the Box out and drop it
                        std::ptr::drop_in_place(data_ptr);
                    }
                }
                0
            }
            ffi::lua_pushcclosure(self.0, Some(gc_rust_function), 0);
            ffi::lua_setfield(self.0, -2, c"__gc".as_ptr());
        }
        ffi::lua_setmetatable(self.0, -2);

        ffi::lua_pushcclosure(self.0, Some(rust_closure_callback), 1);

        Function(Value::pop_from_stack(self))
    }

    fn arg_error(&self, mut narg: i32, err: lua::Error) -> lua::Error {
        let mut fname = "?".to_string();
        let mut namewhat: Option<&str> = None;
        let mut location = String::new();

        // Level 0 for function name
        if let Some(ar) = self.debug_getinfo_at(0, c"n") {
            if let Some(name) = &ar.name {
                fname = name.to_string();
            }
            if let Some(nw) = &ar.namewhat {
                if nw == "method" {
                    namewhat = Some("method");
                }
            }
        }

        // Level 1 for source/line (the Lua caller)
        if let Some(ar) = self.debug_getinfo_at(1, c"Sl") {
            let line = ar.currentline;
            if line > 0 {
                location = format!("{}:{}: ", ar.short_src, line);
            }
        }

        if narg < 0 && narg > ffi::LUA_REGISTRYINDEX {
            narg = ffi::lua_gettop(self.0) + narg + 1;
        }

        if let Some("method") = namewhat {
            if narg == 1 {
                return lua::Error::Message(format!(
                    "{}bad self parameter in method '{}' ({})",
                    location, fname, err
                ));
            }
            narg -= 1;
        }

        lua::Error::Message(format!(
            "{}bad argument #{} to '{}' ({})",
            location, narg, fname, err
        ))
    }
}

extern "C-unwind" fn rust_closure_callback(l: *mut ffi::lua_State) -> i32 {
    {
        let l = lua::State(l);
        let data_ptr = ffi::lua_touserdata(l.0, ffi::lua_upvalueindex(1)) as *const Callback;
        if data_ptr.is_null() {
            ffi::lua_pushstring(l.0, c"attempt to call a nil value".as_ptr());
        } else {
            let func = unsafe { &*data_ptr };
            match func(&l) {
                Ok(v) => return v,
                Err(err) => {
                    let err_str = err.to_string();
                    ffi::lua_pushlstring(l.0, err_str.as_ptr().cast::<i8>(), err_str.len());
                    drop(err_str); // make sure to drop before lua_error
                }
            }
        }
    }
    ffi::lua_error(l);
}

impl ToLua for Function {
    fn push_to_stack(self, l: &lua::State) {
        self.0.push_to_stack(l);
    }

    fn to_value(self, _: &lua::State) -> Value {
        self.0
    }
}

impl ToLua for &Function {
    fn push_to_stack(self, l: &lua::State) {
        #[allow(clippy::needless_borrow)]
        (&self.0).push_to_stack(l);
    }

    fn to_value(self, _: &lua::State) -> Value {
        self.0.clone()
    }
}

impl FromLua for Function {
    fn try_from_stack(l: &lua::State, index: i32) -> lua::Result<Self> {
        match ffi::lua_type(l.0, index) {
            ffi::LUA_TFUNCTION => Ok(Self(Value::from_stack(l, index))),
            _ => Err(l.type_error(index, "function")),
        }
    }
}

pub trait IntoLuaCallbackResult {
    type Value: ToLuaMulti;
    fn into_callback_result(self) -> Result<Self::Value, String>;
}

impl<T, E> IntoLuaCallbackResult for Result<T, E>
where
    T: ToLuaMulti,
    E: Display,
{
    type Value = T;
    fn into_callback_result(self) -> Result<T, String> {
        self.map_err(|e| e.to_string())
    }
}

impl<T> IntoLuaCallbackResult for T
where
    T: ToLuaMulti,
{
    type Value = Self;
    fn into_callback_result(self) -> Result<Self, String> {
        Ok(self)
    }
}

pub trait IntoLuaFunction<Marker> {
    fn into_function(self) -> Function;
}

impl IntoLuaFunction<()> for Function {
    fn into_function(self) -> Function {
        self
    }
}

#[cfg(feature = "tokio")]
pub struct AsyncMarker<T>(std::marker::PhantomData<T>);

macro_rules! impl_into_lua_function {
    ($($name:ident),*) => {
        impl<FF, $($name,)* RR, Ret> IntoLuaFunction<($($name,)*)> for FF
        where
            FF: Fn(&lua::State, $($name,)*) -> Ret + MaybeSend + 'static,
            $($name: FromLuaMulti,)*
            Ret: IntoLuaCallbackResult<Value = RR>,
            RR: ToLuaMulti,
        {
            fn into_function(self) -> Function {
                #[allow(unused)]
                #[allow(non_snake_case)]
                let callback = Box::new(move |l: &lua::State| {
                    let nargs = ffi::lua_gettop(l.0);
                    let mut index = 1;
                    let mut remaining = nargs;
                    $(
                        let ($name, consumed) = $name::try_from_stack_multi(l, index, remaining)
                            .map_err(|e| l.arg_error(index, e))?;
                        index += consumed;
                        remaining -= consumed;
                    )*
                    let ret = self(l, $($name,)*).into_callback_result()?;
                    Ok(ret.push_to_stack_multi_count(l))
                });
                let l = lua::lock().unwrap();
                l.create_function_impl(callback)
            }
        }

        #[cfg(feature = "tokio")]
        impl<FF, Fut, $($name,)* RR, Ret> IntoLuaFunction<AsyncMarker<($($name,)*)>> for FF
            where
                FF: Fn(&lua::State, $($name,)*) -> Fut + MaybeSend + 'static,
                Fut: Future<Output = Ret> + Send + 'static,
                $($name: FromLuaMulti,)*
                Ret: IntoLuaCallbackResult<Value = RR>,
                RR: ToLuaMulti + Send + 'static,
            {
                fn into_function(self) -> Function {
                    use crate::lua::Nil;

                    #[allow(unused, non_snake_case)]
                    let callback = Box::new(move |thread_state: &lua::State| {
                        if !thread_state.is_thread() {
                            Err(lua::Error::Runtime("async functions can only be called from within a Lua coroutine".into()))?;
                        }

                        let nargs = ffi::lua_gettop(thread_state.0);
                        let mut index = 1;
                        let mut remaining = nargs;
                        $(
                            let ($name, consumed) = $name::try_from_stack_multi(thread_state, index, remaining)
                                .map_err(|e| thread_state.arg_error(index, e))?;
                            index += consumed;
                            remaining -= consumed;
                        )*

                        let fut = self(thread_state, $($name,)*);

                        let thread_state_ptr = thread_state.as_usize();
                        crate::tokio_tasks::spawn(async move {
                            let result = fut.await.into_callback_result();
                            crate::next_tick(move |l| {
                                let thread_state = lua::State::from_usize(thread_state_ptr);
                                match result {
                                    Ok(ret) => { lua::thread::Thread::resume_impl(&thread_state, l, (Nil, ret)).ok(); }
                                    Err(e) => { lua::thread::Thread::resume_impl(&thread_state, l, e.to_string()).ok(); }
                                }
                            });
                        });

                        Ok(ffi::lua_yield(thread_state.0, 0))
                    });
                    let l = lua::lock().unwrap();
                    l.create_function_impl(callback)
                }
            }

    };
}

impl_into_lua_function!();
impl_into_lua_function!(A);
impl_into_lua_function!(A, B);
impl_into_lua_function!(A, B, C);
impl_into_lua_function!(A, B, C, D);
impl_into_lua_function!(A, B, C, D, E);
impl_into_lua_function!(A, B, C, D, E, F);
impl_into_lua_function!(A, B, C, D, E, F, G);
impl_into_lua_function!(A, B, C, D, E, F, G, H);
impl_into_lua_function!(A, B, C, D, E, F, G, H, I);
impl_into_lua_function!(A, B, C, D, E, F, G, H, I, J);
impl_into_lua_function!(A, B, C, D, E, F, G, H, I, J, K);
impl_into_lua_function!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_into_lua_function!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_into_lua_function!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_into_lua_function!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_into_lua_function!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);