luau 0.732.0

Safe lifetime-bound Rust embedding API for the Luau runtime
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use std::fmt;
use std::hash::{Hash, Hasher};
use std::mem;
use std::sync::{Arc, Mutex};

use luau_vm::Thread as VmThread;
use luau_vm::thread::{LUA_REFNIL, LUA_REGISTRY_INDEX, StackGuard};
use luau_vm::types::LUA_TNIL;

use super::{Lua, LuaRef};
use crate::error::Error;
use crate::thread::Thread;
use crate::value::{FromLua, IntoLua, Value};

#[derive(Clone, Default)]
pub(crate) struct RegistryState {
    unref_list: Arc<Mutex<Option<Vec<i32>>>>,
}

/// A key for a value stored in the Luau registry.
///
/// Dropping a key defers removal of its registry value until
/// [`Lua::expire_registry_values`] is called. A key can instead be removed
/// immediately with [`Lua::remove_registry_value`].
///
/// # Reference cycles
///
/// Storing a `RegistryKey` inside a [`crate::Userdata`] value or Rust callback
/// can create a cycle that Luau's garbage collector cannot resolve. For
/// example, a userdata that owns a key referring back to itself remains rooted
/// by that registry entry, so its Rust payload never reaches `Drop`. Remove
/// such keys explicitly. Use [`crate::AnyUserdata::set_user_value`] to
/// associate Luau values with userdata without creating a permanent root.
pub struct RegistryKey {
    reference: i32,
    unref_list: Arc<Mutex<Option<Vec<i32>>>>,
}

impl Lua {
    /// Stores a value in the registry under a generated key.
    pub fn create_registry_value<'lua>(
        &'lua self,
        value: impl IntoLua<'lua>,
    ) -> Result<RegistryKey, Error> {
        self.lua_ref().create_registry_value(value)
    }

    /// Stores a value in the registry under a byte-string key.
    pub fn set_named_registry_value<'lua>(
        &'lua self,
        key: impl AsRef<[u8]>,
        value: impl IntoLua<'lua>,
    ) -> Result<(), Error> {
        self.lua_ref().set_named_registry_value(key, value)
    }

    /// Retrieves a named registry value.
    pub fn named_registry_value<'lua, T>(&'lua self, key: impl AsRef<[u8]>) -> Result<T, Error>
    where
        T: FromLua<'lua>,
    {
        self.lua_ref().named_registry_value(key)
    }

    /// Removes a named registry value.
    pub fn unset_named_registry_value(&self, key: impl AsRef<[u8]>) -> Result<(), Error> {
        self.lua_ref().unset_named_registry_value(key)
    }

    /// Retrieves the value associated with a generated registry key.
    pub fn registry_value<'lua, T>(&'lua self, key: &RegistryKey) -> Result<T, Error>
    where
        T: FromLua<'lua>,
    {
        self.lua_ref().registry_value(key)
    }

    /// Removes a generated registry value immediately.
    pub fn remove_registry_value(&self, key: RegistryKey) -> Result<(), Error> {
        if !self.owns_registry_value(&key) {
            return Err(Error::mismatched_registry_key());
        }

        let reference = key.take();
        unsafe {
            self.state.main_thread().unref_value(reference);
        }
        Ok(())
    }

    /// Replaces the value associated with a generated registry key.
    pub fn replace_registry_value<'lua>(
        &'lua self,
        key: &mut RegistryKey,
        value: impl IntoLua<'lua>,
    ) -> Result<(), Error> {
        if !self.owns_registry_value(key) {
            return Err(Error::mismatched_registry_key());
        }

        self.lua_ref().replace_registry_value(key, value)
    }

    /// Returns whether this state created the registry key.
    pub fn owns_registry_value(&self, key: &RegistryKey) -> bool {
        self.lua_ref().owns_registry_value(key)
    }

    /// Removes registry values whose keys have been dropped.
    pub fn expire_registry_values(&self) {
        self.lua_ref().expire_registry_values();
    }
}

impl<'lua> LuaRef<'lua> {
    /// Stores a value in the registry under a generated key.
    pub fn create_registry_value(&self, value: impl IntoLua<'lua>) -> Result<RegistryKey, Error> {
        self.current_thread().create_registry_value(value)
    }

    /// Stores a value in the registry under a byte-string key.
    pub fn set_named_registry_value(
        &self,
        key: impl AsRef<[u8]>,
        value: impl IntoLua<'lua>,
    ) -> Result<(), Error> {
        unsafe {
            let thread = self.as_vm();
            let _stack = StackGuard::new(thread);
            value.push_into_stack(&self.current_thread())?;
            thread
                .raw_set_field(LUA_REGISTRY_INDEX, key)
                .map_err(|exit| Error::from_thread_exit(thread, exit))
        }
    }

    /// Retrieves a named registry value.
    pub fn named_registry_value<T>(&self, key: impl AsRef<[u8]>) -> Result<T, Error>
    where
        T: FromLua<'lua>,
    {
        unsafe {
            let thread = self.as_vm();
            let _stack = StackGuard::new(thread);
            let safe_thread = self.current_thread();
            thread
                .raw_get_field(LUA_REGISTRY_INDEX, key)
                .map_err(|exit| Error::from_thread_exit(thread, exit))?;
            T::from_stack(&safe_thread, -1)
        }
    }

    /// Removes a named registry value.
    pub fn unset_named_registry_value(&self, key: impl AsRef<[u8]>) -> Result<(), Error> {
        unsafe {
            let thread = self.as_vm();
            let _stack = StackGuard::new(thread);
            thread
                .push_nil()
                .map_err(|exit| Error::from_thread_exit(thread, exit))?;
            thread
                .raw_set_field(LUA_REGISTRY_INDEX, key)
                .map_err(|exit| Error::from_thread_exit(thread, exit))
        }
    }

    /// Retrieves the value associated with a generated registry key.
    pub fn registry_value<T>(&self, key: &RegistryKey) -> Result<T, Error>
    where
        T: FromLua<'lua>,
    {
        self.current_thread().registry_value(key)
    }

    /// Replaces the value associated with a generated registry key.
    pub fn replace_registry_value(
        &self,
        key: &mut RegistryKey,
        value: impl IntoLua<'lua>,
    ) -> Result<(), Error> {
        if !self.owns_registry_value(key) {
            return Err(Error::mismatched_registry_key());
        }

        unsafe {
            let thread = self.as_vm();
            let _stack = StackGuard::new(thread);
            let safe_thread = self.current_thread();

            value.push_into_stack(&safe_thread)?;
            let is_nil = thread.type_of(-1) == LUA_TNIL;
            match (key.id(), is_nil) {
                (LUA_REFNIL, true) => {}
                (reference, true) => {
                    thread.unref_value(reference);
                    key.set_id(LUA_REFNIL);
                }
                (LUA_REFNIL, false) => {
                    let replacement = safe_thread.create_registry_key_from_top()?;
                    key.set_id(replacement.take());
                }
                (reference, false) => {
                    thread
                        .raw_seti(LUA_REGISTRY_INDEX, reference)
                        .map_err(|exit| Error::from_thread_exit(thread, exit))?;
                }
            }
        }
        Ok(())
    }

    /// Returns whether this state created the registry key.
    pub fn owns_registry_value(&self, key: &RegistryKey) -> bool {
        self.runtime().registry().owns(key)
    }

    /// Removes registry values whose keys have been dropped.
    pub fn expire_registry_values(&self) {
        self.runtime().registry().expire(self.as_vm());
    }
}

impl<'lua> Thread<'lua> {
    pub(crate) fn create_registry_value(
        &self,
        value: impl IntoLua<'lua>,
    ) -> Result<RegistryKey, Error> {
        unsafe {
            let thread = self.as_vm();
            let _stack = StackGuard::new(thread);
            value.push_into_stack(self)?;
            self.create_registry_key_from_top()
        }
    }

    /// # Safety
    ///
    /// The current stack top must contain the value to store.
    pub(crate) unsafe fn create_registry_key_from_top(&self) -> Result<RegistryKey, Error> {
        unsafe {
            let thread = self.as_vm();
            let reference = if thread.type_of(-1) == LUA_TNIL {
                LUA_REFNIL
            } else if let Some(reference) = self.registry().take_dropped_reference() {
                if let Err(exit) = thread.raw_seti(LUA_REGISTRY_INDEX, reference) {
                    self.registry().restore_dropped_reference(reference);
                    return Err(Error::from_thread_exit(thread, exit));
                }
                reference
            } else {
                thread
                    .ref_value(-1)
                    .map_err(|exit| Error::from_thread_exit(thread, exit))?
            };
            Ok(self.registry().create_key(reference))
        }
    }

    pub(crate) fn registry_value<T>(&self, key: &RegistryKey) -> Result<T, Error>
    where
        T: FromLua<'lua>,
    {
        if !self.registry().owns(key) {
            return Err(Error::mismatched_registry_key());
        }

        if key.id() == LUA_REFNIL {
            return T::from_lua(Value::Nil, self.lua_ref());
        }

        unsafe {
            let thread = self.as_vm();
            let _stack = StackGuard::new(thread);
            thread
                .get_ref(key.id())
                .map_err(|exit| Error::from_thread_exit(thread, exit))?;
            T::from_stack(self, -1)
        }
    }

    pub(crate) fn push_registry_value(&self, key: &RegistryKey) -> Result<(), Error> {
        if !self.registry().owns(key) {
            return Err(Error::mismatched_registry_key());
        }

        unsafe {
            if key.id() == LUA_REFNIL {
                self.as_vm()
                    .push_nil()
                    .map_err(|exit| Error::from_thread_exit(self, exit))?;
            } else {
                self.as_vm()
                    .get_ref(key.id())
                    .map_err(|exit| Error::from_thread_exit(self, exit))?;
            }
        }
        Ok(())
    }
}

impl RegistryState {
    pub(crate) fn create_key(&self, reference: i32) -> RegistryKey {
        RegistryKey {
            reference,
            unref_list: Arc::clone(&self.unref_list),
        }
    }

    pub(crate) fn owns(&self, key: &RegistryKey) -> bool {
        Arc::ptr_eq(&self.unref_list, &key.unref_list)
    }

    pub(crate) fn take_dropped_reference(&self) -> Option<i32> {
        lock_unref_list(&self.unref_list).as_mut()?.pop()
    }

    pub(crate) fn restore_dropped_reference(&self, reference: i32) {
        if reference <= LUA_REFNIL {
            return;
        }

        if let Some(unref_list) = lock_unref_list(&self.unref_list).as_mut() {
            unref_list.push(reference);
        }
    }

    pub(crate) fn expire(&self, thread: &VmThread) {
        let references = {
            let mut unref_list = lock_unref_list(&self.unref_list);
            let Some(unref_list) = unref_list.as_mut() else {
                return;
            };
            mem::take(unref_list)
        };

        for reference in references {
            unsafe {
                thread.unref_value(reference);
            }
        }
    }

    pub(crate) fn close(&self, thread: &VmThread) {
        let references = {
            let mut unref_list = lock_unref_list(&self.unref_list);
            unref_list.take().unwrap_or_default()
        };

        for reference in references {
            unsafe {
                thread.unref_value(reference);
            }
        }
    }
}

impl RegistryKey {
    /// Returns the underlying registry reference.
    pub fn id(&self) -> i32 {
        self.reference
    }

    pub(crate) fn set_id(&mut self, reference: i32) {
        self.reference = reference;
    }

    pub(crate) fn take(mut self) -> i32 {
        let reference = self.reference;
        self.reference = LUA_REFNIL;
        reference
    }
}

impl Drop for RegistryKey {
    fn drop(&mut self) {
        if self.reference <= LUA_REFNIL {
            return;
        }

        let mut unref_list = lock_unref_list(&self.unref_list);
        if let Some(unref_list) = unref_list.as_mut() {
            unref_list.push(self.reference);
        }
    }
}

impl fmt::Debug for RegistryKey {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "RegistryKey({})", self.id())
    }
}

impl Hash for RegistryKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id().hash(state);
    }
}

impl PartialEq for RegistryKey {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id() && Arc::ptr_eq(&self.unref_list, &other.unref_list)
    }
}

impl Eq for RegistryKey {}

impl<'lua> IntoLua<'lua> for RegistryKey {
    fn into_lua(self, thread: crate::LuaRef<'lua>) -> Result<Value<'lua>, Error> {
        (&self).into_lua(thread)
    }

    unsafe fn push_into_stack(self, thread: &Thread<'lua>) -> Result<(), Error> {
        unsafe { (&self).push_into_stack(thread) }
    }
}

impl<'lua> IntoLua<'lua> for &RegistryKey {
    fn into_lua(self, thread: crate::LuaRef<'lua>) -> Result<Value<'lua>, Error> {
        thread.current_thread().registry_value(self)
    }

    unsafe fn push_into_stack(self, thread: &Thread<'lua>) -> Result<(), Error> {
        thread.push_registry_value(self)
    }
}

impl<'lua> FromLua<'lua> for RegistryKey {
    fn from_lua(value: Value<'lua>, thread: crate::LuaRef<'lua>) -> Result<Self, Error> {
        thread.create_registry_value(value)
    }
}

fn lock_unref_list(
    unref_list: &Mutex<Option<Vec<i32>>>,
) -> std::sync::MutexGuard<'_, Option<Vec<i32>>> {
    unref_list
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_send_sync<T: Send + Sync>() {}

    #[test]
    fn registry_key_is_send_sync() {
        assert_send_sync::<RegistryKey>();
    }
}