luau-vm 0.732.0

Pure-Rust Luau virtual machine, garbage collector, and standard libraries
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
404
405
406
407
408
409
410
411
412
413
use std::cell::{Ref, RefCell, RefMut};
use std::ops::{Deref, DerefMut};

use luau_common::BStr;
use luau_printf::Arg;

use crate::thread::Thread;
use crate::userdata::{TypedUserdataAccess, UserdataTypeRegistryAccess};
use crate::{VmErrorResult, VmResult};

pub type NativeCallResult = VmResult<usize>;

pub type RawNativeFunction = for<'call> fn(NativeCallContext<'call>) -> NativeCallResult;

pub type RawNativeContinuation = for<'call> fn(NativeCallContext<'call>, i32) -> NativeCallResult;

// Native function registration
#[derive(Clone, Copy)]
pub struct NativeFunction {
    pub name: &'static str,
    pub function: RawNativeFunction,
}

#[derive(Clone, Copy)]
pub struct NativeModule {
    pub name: Option<&'static str>,
    pub functions: &'static [NativeFunction],
}

impl NativeModule {
    #[inline]
    pub const fn new(name: Option<&'static str>, functions: &'static [NativeFunction]) -> Self {
        Self { name, functions }
    }
}

// Native call context
#[derive(PartialEq, Eq)]
#[repr(transparent)]
pub struct NativeCallContext<'call> {
    thread: &'call Thread,
}

impl<'call> NativeCallContext<'call> {
    /// The thread must be the active thread for a VM-native call or continuation.
    #[inline]
    pub(crate) const fn new(thread: &'call Thread) -> Self {
        Self { thread }
    }

    #[inline]
    pub const fn raw_thread(&self) -> &'call Thread {
        self.thread
    }

    #[inline]
    pub fn arg_count(&self) -> i32 {
        unsafe { self.thread.get_top() }
    }

    #[inline]
    pub fn top(&self) -> i32 {
        self.arg_count()
    }

    #[inline]
    pub fn pop(&self, count: i32) {
        unsafe { self.thread.pop(count) }
    }

    #[inline]
    pub fn arg(&self, index: i32) -> NativeArgument<'_, 'call> {
        NativeArgument {
            context: self,
            index,
        }
    }

    #[inline]
    pub fn argument(&self, index: i32) -> NativeArgument<'_, 'call> {
        self.arg(index)
    }

    #[inline]
    pub fn upvalue(&self, index: i32) -> NativeArgument<'_, 'call> {
        NativeArgument {
            context: self,
            index: crate::thread::upvalue_index(index),
        }
    }

    #[inline]
    pub fn args(&self) -> NativeArguments<'_, 'call> {
        NativeArguments {
            context: self,
            next: 1,
            end: self.arg_count(),
        }
    }

    #[inline]
    pub fn push_number(&self, value: f64) -> VmErrorResult {
        unsafe { self.thread.push_number(value) }
    }

    #[inline]
    pub fn push_nil(&self) -> VmErrorResult {
        unsafe { self.thread.push_nil() }
    }

    #[inline]
    pub fn push_integer(&self, value: i32) -> VmErrorResult {
        unsafe { self.thread.push_integer(value) }
    }

    #[inline]
    pub fn push_integer64(&self, value: i64) -> VmErrorResult {
        unsafe { self.thread.push_integer64(value) }
    }

    #[inline]
    pub fn push_unsigned(&self, value: u32) -> VmErrorResult {
        unsafe { self.thread.push_unsigned(value) }
    }

    #[inline]
    pub fn push_vector(&self, components: [f32; crate::types::LUA_VECTOR_SIZE]) -> VmErrorResult {
        unsafe { self.thread.push_vector(components) }
    }

    #[inline]
    pub fn push_boolean(&self, value: bool) -> VmErrorResult {
        unsafe { self.thread.push_boolean(i32::from(value)) }
    }

    #[inline]
    pub fn push_bool(&self, value: bool) -> VmErrorResult {
        self.push_boolean(value)
    }

    #[inline]
    pub fn push_string(&self, bytes: impl AsRef<[u8]>) -> VmErrorResult {
        unsafe { self.thread.push_string(bytes) }
    }

    #[inline]
    pub fn push_userdata<T: 'static>(&self, value: T) -> VmErrorResult {
        let Some(registration) = (unsafe { self.thread.userdata_type::<T>() }) else {
            return self.error("userdata type is not registered", []);
        };
        unsafe { self.thread.push_typed_userdata(value, &registration) }
    }

    #[inline]
    pub fn lua_error<'a, T>(
        &self,
        format: impl AsRef<[u8]>,
        args: impl AsMut<[Arg<'a>]>,
    ) -> VmErrorResult<T> {
        unsafe { self.thread.lua_error(format, args) }
    }

    #[inline]
    pub fn error<'a, T>(
        &self,
        format: impl AsRef<[u8]>,
        args: impl AsMut<[Arg<'a>]>,
    ) -> VmErrorResult<T> {
        self.lua_error(format, args)
    }
}

// Native arguments
#[derive(Clone, Copy)]
pub struct NativeArgument<'ctx, 'call> {
    pub(super) context: &'ctx NativeCallContext<'call>,
    pub(super) index: i32,
}

impl<'ctx, 'call> NativeArgument<'ctx, 'call> {
    #[inline]
    pub const fn index(&self) -> i32 {
        self.index
    }

    #[inline]
    pub fn integer(&self) -> VmErrorResult<i32> {
        unsafe { self.context.raw_thread().check_integer(self.index) }
    }

    #[inline]
    pub fn integer_or(&self, default: i32) -> VmErrorResult<i32> {
        unsafe { self.context.raw_thread().opt_integer(self.index, default) }
    }

    #[inline]
    pub fn number(&self) -> VmErrorResult<f64> {
        unsafe { self.context.raw_thread().check_number(self.index) }
    }

    #[inline]
    pub fn number_or(&self, default: f64) -> VmErrorResult<f64> {
        unsafe { self.context.raw_thread().opt_number(self.index, default) }
    }

    #[inline]
    pub fn integer64(&self) -> VmErrorResult<i64> {
        unsafe { self.context.raw_thread().check_integer64(self.index) }
    }

    #[inline]
    pub fn integer64_or(&self, default: i64) -> VmErrorResult<i64> {
        unsafe { self.context.raw_thread().opt_integer64(self.index, default) }
    }

    #[inline]
    pub fn unsigned(&self) -> VmErrorResult<u32> {
        unsafe { self.context.raw_thread().check_unsigned(self.index) }
    }

    #[inline]
    pub fn vector(&self) -> VmErrorResult<[f32; crate::types::LUA_VECTOR_SIZE]> {
        unsafe { self.context.raw_thread().check_vector(self.index) }
    }

    #[inline]
    /// Returns a borrowed string argument.
    ///
    /// # Safety
    ///
    /// The argument must remain rooted and no VM transition may pop, unroot,
    /// or collect it for the returned borrow's lifetime.
    pub unsafe fn string(&self) -> VmErrorResult<&'ctx BStr> {
        unsafe { self.context.raw_thread().check_string(self.index) }
    }

    #[inline]
    pub fn light_userdata(&self) -> VmErrorResult<*mut ()> {
        let pointer = unsafe { self.context.raw_thread().to_light_userdata(self.index) };
        if pointer.is_null() {
            return self.type_error("light userdata");
        }
        Ok(pointer)
    }

    /// Borrows this argument as userdata of the registered type.
    #[inline]
    /// # Safety
    ///
    /// The argument must remain rooted and no VM transition may pop, unroot,
    /// or collect it while the returned guard is alive.
    pub unsafe fn userdata<T: 'static>(&self) -> VmErrorResult<LuaUserdataRef<'ctx, T>> {
        let cell = unsafe { &*self.userdata_cell_ptr::<T>()? };
        let Ok(value) = cell.try_borrow() else {
            return self.error("userdata is already mutably borrowed");
        };
        let Ok(value) = Ref::filter_map(value, Option::as_ref) else {
            return self.error("userdata has been destructed");
        };
        Ok(LuaUserdataRef::new(value))
    }

    /// Mutably borrows this argument as userdata of the registered type.
    #[inline]
    /// # Safety
    ///
    /// The argument must remain rooted and no VM transition may pop, unroot,
    /// or collect it while the returned guard is alive. No other access to the
    /// same typed value may overlap the mutable guard.
    pub unsafe fn userdata_mut<T: 'static>(&self) -> VmErrorResult<LuaUserdataRefMut<'ctx, T>> {
        let cell = unsafe { &*self.userdata_cell_ptr::<T>()? };
        let Ok(value) = cell.try_borrow_mut() else {
            return self.error("userdata is already borrowed");
        };
        let Ok(value) = RefMut::filter_map(value, Option::as_mut) else {
            return self.error("userdata has been destructed");
        };
        Ok(LuaUserdataRefMut::new(value))
    }

    #[inline]
    unsafe fn userdata_cell_ptr<T: 'static>(&self) -> VmErrorResult<*mut RefCell<Option<T>>> {
        let expected_type = core::any::type_name::<T>();
        let Some(userdata) = (unsafe { self.context.raw_thread().typed_userdata_at(self.index) })
        else {
            return self.type_error(expected_type);
        };
        if userdata.is_destructed() {
            return self.error("userdata has been destructed");
        }
        let Some(cell) = (unsafe { userdata.cell_ptr::<T>() }) else {
            return self.type_error(expected_type);
        };

        Ok(cell)
    }

    #[inline]
    pub fn error<T>(&self, message: impl AsRef<[u8]>) -> VmErrorResult<T> {
        unsafe { self.context.raw_thread().lua_arg_error(self.index, message) }
    }

    #[inline]
    pub fn expected(&self, condition: bool, expected_type: &str) -> VmErrorResult {
        unsafe {
            self.context
                .raw_thread()
                .lua_arg_expected(condition, self.index, expected_type)
        }
    }

    #[inline]
    pub fn type_error<T>(&self, expected_type: &str) -> VmErrorResult<T> {
        unsafe {
            self.context
                .raw_thread()
                .lua_type_error(self.index, expected_type)
        }
    }
}

#[derive(Clone, Copy)]
pub struct NativeArguments<'ctx, 'call> {
    pub(super) context: &'ctx NativeCallContext<'call>,
    pub(super) next: i32,
    pub(super) end: i32,
}

impl NativeArguments<'_, '_> {
    #[inline]
    pub fn remaining(&self) -> i32 {
        (self.end - self.next + 1).max(0)
    }
}

impl<'ctx, 'call> Iterator for NativeArguments<'ctx, 'call> {
    type Item = NativeArgument<'ctx, 'call>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.next > self.end {
            None
        } else {
            let index = self.next;
            self.next += 1;
            Some(NativeArgument {
                context: self.context,
                index,
            })
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.remaining() as usize;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for NativeArguments<'_, '_> {}

/// Shared borrow of a Lua-owned userdata value.
///
/// The borrow is released when this guard is dropped.
pub struct LuaUserdataRef<'lua, T> {
    value: Ref<'lua, T>,
}

impl<'lua, T> LuaUserdataRef<'lua, T> {
    #[inline]
    pub(super) fn new(value: Ref<'lua, T>) -> Self {
        Self { value }
    }
}

impl<T> Deref for LuaUserdataRef<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

/// Mutable borrow of a Lua-owned userdata value.
///
/// The borrow is released when this guard is dropped.
pub struct LuaUserdataRefMut<'lua, T> {
    value: RefMut<'lua, T>,
}

impl<'lua, T> LuaUserdataRefMut<'lua, T> {
    #[inline]
    pub(super) fn new(value: RefMut<'lua, T>) -> Self {
        Self { value }
    }
}

impl<T> Deref for LuaUserdataRefMut<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> DerefMut for LuaUserdataRefMut<'_, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}