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
414
415
416
417
418
use core::ptr::NonNull;

use crate::VmErrorResult;
use crate::call::ThreadStack;
use crate::function::FunctionRuntime;
use crate::gc::{GcBarrier, GcRuntime};
use crate::handle::RawHandle;
use crate::state::{
    BASIC_CI_SIZE, BASIC_STACK_SIZE, GlobalState, INITIAL_STACK_SIZE, LuaCallbacks, RawLuaState,
    THREAD_STATUS_BREAK, THREAD_STATUS_OK, THREAD_STATUS_YIELD, ThreadLifecycle, ThreadState,
};
use crate::value::nil_object;

#[allow(
    clippy::missing_safety_doc,
    reason = "Thread's shared unsafe auxiliary API contract is documented on Thread"
)]
mod auxiliary;
#[allow(
    clippy::missing_safety_doc,
    reason = "Thread's shared unsafe call API contract is documented on Thread"
)]
mod call;
#[allow(
    clippy::missing_safety_doc,
    reason = "Thread's shared unsafe debug API contract is documented on Thread"
)]
mod debug;
#[allow(
    clippy::missing_safety_doc,
    reason = "Thread's shared unsafe GC API contract is documented on Thread"
)]
mod gc;
#[allow(
    clippy::missing_safety_doc,
    reason = "Thread's shared unsafe stack API contract is documented on Thread"
)]
pub(crate) mod stack;
#[allow(
    clippy::missing_safety_doc,
    reason = "Thread's shared unsafe string builder contract is documented on Thread"
)]
mod string_builder;
#[allow(
    clippy::missing_safety_doc,
    reason = "Thread's shared unsafe table API contract is documented on Thread"
)]
mod table;
#[allow(
    clippy::missing_safety_doc,
    reason = "Thread's shared unsafe userdata API contract is documented on Thread"
)]
mod userdata;

pub use crate::types::{
    LUA_TBOOLEAN, LUA_TBUFFER, LUA_TCLASS, LUA_TFUNCTION, LUA_TINTEGER, LUA_TLIGHTUSERDATA,
    LUA_TNIL, LUA_TNUMBER, LUA_TOBJECT, LUA_TSTRING, LUA_TTABLE, LUA_TTHREAD, LUA_TUSERDATA,
    LUA_TVECTOR,
};
pub use string_builder::{LuaStringBuilder, LuaStringBuilderStorage};

#[derive(PartialEq, Eq)]
#[repr(transparent)]
/// A non-owning Luau thread handle.
///
/// `Thread` does not keep the VM alive and does not encode exclusive access
/// to the VM stack. It is deliberately `!Send` and `!Sync` through its raw
/// state representation.
///
/// # Safety model for unsafe methods
///
/// Unless a method documents stricter requirements, every unsafe `Thread`
/// operation requires a live thread belonging to a live VM. Stack indices,
/// stack shapes, counts, tags, and pointer arguments must satisfy the
/// corresponding Luau API operation's contract. The caller must provide
/// sufficient stack capacity where the operation does not grow the stack,
/// prevent reentrant or concurrent access to VM-owned records, and treat any
/// operation that can allocate or execute code as a possible GC transition.
/// Returned pointers and raw handles are non-owning and may be invalidated by
/// stack relocation, collection, closure, reset, or VM destruction.
pub struct Thread {
    pub(crate) raw: NonNull<RawLuaState>,
}

impl crate::handle::sealed::Sealed for Thread {}

impl RawHandle for Thread {
    type Raw = RawLuaState;

    fn as_ptr(&self) -> *mut RawLuaState {
        self.raw.as_ptr()
    }
}

impl AsRef<Thread> for Thread {
    fn as_ref(&self) -> &Thread {
        self
    }
}

impl Thread {
    /// Returns a non-owning handle to this thread's global VM state.
    ///
    /// # Safety
    ///
    /// This thread and its owning VM must still be live. The returned handle
    /// does not extend the global state's lifetime or establish a borrow of
    /// the underlying record.
    pub unsafe fn global(&self) -> GlobalState {
        unsafe {
            GlobalState::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().global,
            ))
        }
    }
}

/// Restores a thread's stack height when the guard is dropped.
///
/// Values intentionally left on the stack can be accounted for with
/// [`keep`](Self::keep), or restoration can be disabled with
/// [`into_top`](Self::into_top) or [`dismiss`](Self::dismiss).
#[must_use = "dropping the guard restores the captured stack height"]
pub struct StackGuard<'thread> {
    thread: &'thread Thread,
    top: i32,
    restore_on_drop: bool,
}

impl<'thread> StackGuard<'thread> {
    /// Captures the thread's current stack height.
    ///
    /// # Safety
    ///
    /// `thread` must remain a live VM thread for the guard's lifetime. While
    /// the guard is active, callers must not shrink the stack below the
    /// captured height or otherwise invalidate that saved stack position.
    pub unsafe fn new(thread: &'thread Thread) -> Self {
        Self {
            thread,
            top: unsafe { thread.get_top() },
            restore_on_drop: true,
        }
    }

    pub const fn top(&self) -> i32 {
        self.top
    }

    pub fn keep(&mut self, count: i32) {
        debug_assert!(count >= 0);
        self.top += count;
    }

    pub fn into_top(mut self) -> i32 {
        self.restore_on_drop = false;
        self.top
    }

    pub fn dismiss(mut self) {
        self.restore_on_drop = false;
    }
}

impl Drop for StackGuard<'_> {
    fn drop(&mut self) {
        if self.restore_on_drop {
            unsafe { self.thread.restore_top(self.top) };
        }
    }
}

/// `LUA_MINSTACK`
pub const LUA_MIN_STACK: usize = 20;

/// `LUAI_MAXCSTACK`
pub const LUAI_MAX_C_STACK: i32 = 8000;

/// `LUAI_MAXCALLS`
pub const LUAI_MAX_CALLS: usize = 20_000;

/// `LUAI_MAXCCALLS`
pub const LUAI_MAX_NATIVE_CALLS: u16 = 200;

/// `LUA_BUFFERSIZE`
pub const LUA_BUFFER_SIZE: usize = 512;

pub const LUA_MULTRET: i32 = -1;
pub const LUA_TNONE: i32 = -1;

pub const LUA_REGISTRY_INDEX: i32 = -LUAI_MAX_C_STACK - 2000;
pub const LUA_ENVIRON_INDEX: i32 = -LUAI_MAX_C_STACK - 2001;
pub const LUA_GLOBALS_INDEX: i32 = -LUAI_MAX_C_STACK - 2002;

pub const LUA_NOREF: i32 = -1;
pub const LUA_REFNIL: i32 = 0;

pub const LUA_CORUN: i32 = 0;
pub const LUA_COSUS: i32 = 1;
pub const LUA_CONOR: i32 = 2;
pub const LUA_COFIN: i32 = 3;
pub const LUA_COERR: i32 = 4;

/// `lua_upvalueindex`
pub const fn upvalue_index(index: i32) -> i32 {
    LUA_GLOBALS_INDEX - index
}

/// `lua_ispseudo`
pub const fn is_pseudo(index: i32) -> bool {
    index <= LUA_REGISTRY_INDEX
}

// Thread lifecycle and host state
#[allow(
    clippy::missing_safety_doc,
    reason = "Thread's shared unsafe lifecycle API contract is documented on Thread"
)]
impl Thread {
    /// Returns whether both handles belong to the same VM.
    ///
    /// # Safety
    ///
    /// Both threads and their owning VMs must still be live.
    pub unsafe fn same_vm(&self, other: impl AsRef<Thread>) -> bool {
        unsafe { self.global() == other.as_ref().global() }
    }

    /// `lua_encodepointer`
    pub unsafe fn encode_pointer(&self, pointer: usize) -> usize {
        unsafe { self.global().encode_pointer(pointer) }
    }

    /// `lua_setpointerencodekey`
    pub unsafe fn set_pointer_encode_key(&self, a: u64, b: u64, c: u64, d: u64) {
        unsafe {
            self.global()
                .as_ptr()
                .as_mut()
                .unwrap_unchecked()
                .ptr_enc_key = [a & !1, b | 1, c, d];
        }
    }

    /// `lua_resetthread`
    pub unsafe fn reset(&self) -> VmErrorResult {
        unsafe {
            debug_assert!(!self.as_ptr().as_ref().unwrap_unchecked().is_active);
            debug_assert!(
                self.as_ptr().as_ref().unwrap_unchecked().status != THREAD_STATUS_OK
                    || self.as_ptr().as_ref().unwrap_unchecked().ci
                        == self.as_ptr().as_ref().unwrap_unchecked().base_ci
            );

            self.close(self.base_call_info().function().value_unchecked());

            let function = self.stack();
            let ci = self.base_call_info();
            ci.function().value_unchecked().set_nil();
            ci.init_call(function, function.add(1 + LUA_MIN_STACK), 0, None);

            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.status = THREAD_STATUS_OK;
            raw.native_call_depth = 0;
            raw.base_native_call_depth = 0;
            self.set_current_call_info(self.base_call_info_cursor());
            self.set_stack_base(ci.base());
            self.set_stack_top(ci.base());

            if self.as_ptr().as_ref().unwrap_unchecked().size_ci as usize != BASIC_CI_SIZE {
                self.realloc_ci(BASIC_CI_SIZE as i32)?;
            }

            let target_stack_size = INITIAL_STACK_SIZE as i32;
            if self.as_ptr().as_ref().unwrap_unchecked().stack_size != target_stack_size {
                self.realloc_stack(BASIC_STACK_SIZE as i32, false)?;
            }

            let stack = self.stack();
            let stack_size = self.as_ptr().as_ref().unwrap_unchecked().stack_size as usize;
            for index in 0..stack_size {
                stack.add(index).value_unchecked().set_nil();
            }
        }
        Ok(())
    }

    /// `lua_isthreadreset`
    pub unsafe fn is_reset(&self) -> bool {
        unsafe {
            self.current_call_info() == self.base_call_info()
                && self.as_ptr().as_ref().unwrap_unchecked().base
                    == self.as_ptr().as_ref().unwrap_unchecked().top
                && self.as_ptr().as_ref().unwrap_unchecked().status == THREAD_STATUS_OK
        }
    }

    /// `lua_status`
    pub unsafe fn status(&self) -> i32 {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().status as i32 }
    }

    /// `lua_isyieldable`
    pub unsafe fn is_yieldable(&self) -> i32 {
        i32::from(unsafe {
            self.as_ptr().as_ref().unwrap_unchecked().native_call_depth
                <= self
                    .as_ptr()
                    .as_ref()
                    .unwrap_unchecked()
                    .base_native_call_depth
        })
    }

    /// `lua_getthreaddata`
    pub unsafe fn thread_data(&self) -> *mut () {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().userdata }
    }

    /// `lua_setthreaddata`
    pub unsafe fn set_thread_data(&self, data: *mut ()) {
        unsafe {
            self.as_ptr().as_mut().unwrap_unchecked().userdata = data;
        }
    }

    /// `lua_callbacks`
    ///
    /// Returns the VM-owned callback record address. Mutating this record is
    /// only valid while the VM is quiescent, and the update must not be
    /// observable in a partially written state. The record is non-atomic and
    /// the pointer is not a cross-thread interruption mechanism.
    ///
    /// # Safety
    ///
    /// The thread and its VM must remain live. The caller must not dereference
    /// a stale pointer or read or write the record concurrently with VM
    /// execution.
    pub unsafe fn callbacks(&self) -> *mut LuaCallbacks {
        unsafe { self.global().callbacks() }
    }
}

// Thread values
#[allow(
    clippy::missing_safety_doc,
    reason = "Thread's shared unsafe thread-value API contract is documented on Thread"
)]
impl Thread {
    /// `lua_pushthread`
    pub unsafe fn push_thread(&self) -> VmErrorResult<i32> {
        unsafe {
            self.thread_barrier();
            self.ensure_stack(self, 1)?;

            let top = self.stack_top();
            top.value_unchecked().set_thread_value(self);
            debug_assert!(top < self.current_call_info().top());
            self.set_stack_top(top.add(1));
        }

        Ok(i32::from(unsafe { self.global().main_thread() == *self }))
    }

    /// `lua_tothread`
    pub unsafe fn to_thread(&self, index: i32) -> Option<Thread> {
        let object = unsafe { self.index_to_addr(index) };
        if object == nil_object() || !object.is_thread() {
            None
        } else {
            Some(object.thread_value())
        }
    }

    /// `lua_newthread`
    pub unsafe fn new_thread(&self) -> VmErrorResult<Thread> {
        unsafe {
            self.check_gc()?;
            self.thread_barrier();
            self.ensure_stack(self, 1)?;
            let thread = self.new_thread_internal()?;

            let top = self.stack_top();
            top.value_unchecked().set_thread_value(&thread);
            debug_assert!(top < self.current_call_info().top());
            self.set_stack_top(top.add(1));

            if let Some(user_thread) = self.global().user_thread_callback() {
                user_thread(Some(self), &thread);
            }

            Ok(thread)
        }
    }

    /// `lua_costatus`
    pub unsafe fn co_status(&self, thread: &Thread) -> i32 {
        unsafe {
            debug_assert!(self.global() == thread.global());

            if *thread == *self {
                LUA_CORUN
            } else if thread.as_ptr().as_ref().unwrap_unchecked().status == THREAD_STATUS_YIELD {
                LUA_COSUS
            } else if thread.as_ptr().as_ref().unwrap_unchecked().status == THREAD_STATUS_BREAK {
                LUA_CONOR
            } else if thread.as_ptr().as_ref().unwrap_unchecked().status != THREAD_STATUS_OK {
                LUA_COERR
            } else if thread.current_call_info() != thread.base_call_info() {
                LUA_CONOR
            } else if thread.stack_top() == thread.stack_base() {
                LUA_COFIN
            } else {
                LUA_COSUS
            }
        }
    }
}