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
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
use core::ptr::NonNull;

use crate::Table;
use crate::buffer::Buffer;
use crate::function::{Closure, Proto, UpVal};
use crate::handle::RawHandle;
use crate::state::ThreadState;
use crate::string::TString;
use crate::thread::Thread;
use crate::types::{
    LUA_EXTRA_SIZE, LUA_TBOOLEAN, LUA_TBUFFER, LUA_TCLASS, LUA_TFUNCTION, LUA_TINTEGER,
    LUA_TLIGHTUSERDATA, LUA_TNIL, LUA_TNUMBER, LUA_TOBJECT, LUA_TPROTO, LUA_TSTRING, LUA_TTABLE,
    LUA_TTHREAD, LUA_TUPVALUE, LUA_TUSERDATA, LUA_TVECTOR, LUA_VECTOR_SIZE,
};
use crate::userdata::Userdata;
use crate::{Class, Object};

use crate::gc::{GcObject, RawGcObject};

#[derive(Clone, Copy)]
#[repr(C)]
pub union RawValue {
    pub gc: *mut RawGcObject,
    pub pointer: *mut (),
    pub number: f64,
    pub boolean: i32,
    pub integer: i64,
    pub vector: [f32; 2],
}

#[derive(Clone, Copy)]
#[repr(C)]
pub struct RawTValue {
    pub value: RawValue,
    pub extra: [i32; LUA_EXTRA_SIZE],
    pub tt: i32,
}

impl RawTValue {
    pub const fn nil() -> Self {
        Self {
            value: RawValue {
                pointer: core::ptr::null_mut(),
            },
            extra: [0; LUA_EXTRA_SIZE],
            tt: LUA_TNIL,
        }
    }

    pub const fn number(value: f64) -> Self {
        Self {
            value: RawValue { number: value },
            extra: [0; LUA_EXTRA_SIZE],
            tt: LUA_TNUMBER,
        }
    }

    pub fn string(value: TString) -> Self {
        Self {
            value: RawValue {
                gc: GcObject::from(value).as_ptr(),
            },
            extra: [0; LUA_EXTRA_SIZE],
            tt: LUA_TSTRING,
        }
    }

    pub const fn light_userdata(pointer: *mut (), tag: i32) -> Self {
        let mut extra = [0; LUA_EXTRA_SIZE];
        extra[0] = tag;
        Self {
            value: RawValue { pointer },
            extra,
            tt: LUA_TLIGHTUSERDATA,
        }
    }
}

pub const RAW_TVALUE_NIL: RawTValue = RawTValue::nil();

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
/// Nullable traversal position in a VM value array.
///
/// Unsafe access and navigation require a live owning array, an in-bounds
/// non-null position where applicable, and cursors from the same allocation.
/// Stack or array relocation invalidates every derived cursor.
pub struct TValueCursor(*mut RawTValue);

#[allow(
    clippy::missing_safety_doc,
    reason = "TValueCursor navigation is governed by its documented non-owning cursor contract"
)]
impl TValueCursor {
    /// Returns the current traversal address, which may be null.
    ///
    /// Stack growth and relocation invalidate cursors into the old stack.
    pub const fn as_ptr(&self) -> *mut RawTValue {
        self.0
    }

    pub const fn from_ptr(raw: *mut RawTValue) -> Self {
        Self(raw)
    }

    pub const fn is_null(&self) -> bool {
        self.0.is_null()
    }

    pub unsafe fn is_nil_unchecked(&self) -> bool {
        debug_assert!(!self.is_null());
        unsafe { (*self.as_ptr()).tt == LUA_TNIL }
    }

    pub unsafe fn value_unchecked(&self) -> TValue {
        debug_assert!(!self.is_null());
        unsafe { TValue::from_raw(NonNull::new_unchecked(self.0)) }
    }

    pub fn value(&self) -> Option<TValue> {
        NonNull::new(self.0).map(|raw| unsafe { TValue::from_raw(raw) })
    }

    pub unsafe fn add(self, count: usize) -> Self {
        unsafe { Self::from_ptr(self.0.add(count)) }
    }

    pub unsafe fn sub(self, count: usize) -> Self {
        unsafe { Self::from_ptr(self.0.sub(count)) }
    }

    pub unsafe fn offset(self, count: isize) -> Self {
        unsafe { Self::from_ptr(self.0.offset(count)) }
    }

    pub unsafe fn offset_from(self, other: Self) -> isize {
        unsafe { self.0.offset_from(other.0) }
    }

    pub fn addr_offset_from(self, other: Self) -> isize {
        let byte_offset = self.0 as isize - other.0 as isize;
        debug_assert_eq!(byte_offset % core::mem::size_of::<RawTValue>() as isize, 0);
        byte_offset / core::mem::size_of::<RawTValue>() as isize
    }
}

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

#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
/// Non-owning view of a live tagged VM value slot.
///
/// # Safety model for unsafe constructors
///
/// The source slot must remain live for every use of the copied view. It must
/// contain a valid VM tag/payload pair, and referenced collectable values must
/// belong to the same VM and remain rooted as required by the caller.
pub struct TValue {
    raw: NonNull<RawTValue>,
}

#[repr(transparent)]
pub struct NilObject(RawTValue);

unsafe impl Sync for NilObject {}

pub static LUA_O_NIL_OBJECT: NilObject = NilObject(RAW_TVALUE_NIL);
#[allow(
    clippy::missing_safety_doc,
    reason = "TValue's shared raw-view contract is documented on TValue"
)]
impl TValue {
    pub const unsafe fn from_raw(raw: NonNull<RawTValue>) -> Self {
        Self { raw }
    }

    pub unsafe fn from_ref(raw: &RawTValue) -> Self {
        Self {
            raw: NonNull::from(raw),
        }
    }

    pub unsafe fn from_mut(raw: &mut RawTValue) -> Self {
        Self {
            raw: NonNull::from(raw),
        }
    }

    /// `ttisnil`
    pub fn is_nil(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TNIL }
    }

    /// `ttisnumber`
    pub fn is_number(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TNUMBER }
    }

    /// `ttisinteger`
    pub fn is_integer(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TINTEGER }
    }

    /// `ttisstring`
    pub fn is_string(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TSTRING }
    }

    /// `ttistable`
    pub fn is_table(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TTABLE }
    }

    /// `ttisfunction`
    pub fn is_function(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TFUNCTION }
    }

    /// `iscfunction`
    pub fn is_native_function(&self) -> bool {
        if !self.is_function() {
            return false;
        }

        let closure = self.closure_value();
        unsafe { closure.is_native() }
    }

    /// `isLfunction`
    pub fn is_lua_function(&self) -> bool {
        if !self.is_function() {
            return false;
        }

        let closure = self.closure_value();
        unsafe { closure.is_lua() }
    }

    /// `ttisboolean`
    pub fn is_boolean(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TBOOLEAN }
    }

    /// `ttisuserdata`
    pub fn is_userdata(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TUSERDATA }
    }

    /// `ttisthread`
    pub fn is_thread(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TTHREAD }
    }

    /// `ttisbuffer`
    pub fn is_buffer(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TBUFFER }
    }

    /// `ttislightuserdata`
    pub fn is_light_userdata(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TLIGHTUSERDATA }
    }

    /// `ttisvector`
    pub fn is_vector(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TVECTOR }
    }

    /// `ttisclass`
    pub fn is_class(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TCLASS }
    }

    /// `ttisobject`
    pub fn is_object(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TOBJECT }
    }

    /// `ttisupval`
    pub fn is_upvalue(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TUPVALUE }
    }

    pub fn is_proto(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt == LUA_TPROTO }
    }

    /// `iscollectable`
    pub fn is_collectable(&self) -> bool {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt >= LUA_TSTRING }
    }

    /// `ttype`
    pub fn tt(&self) -> i32 {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().tt }
    }

    /// `l_isfalse`
    pub fn is_false(&self) -> bool {
        let value = unsafe { self.as_ptr().as_ref().unwrap_unchecked() };
        value.tt == LUA_TNIL || (value.tt == LUA_TBOOLEAN && unsafe { value.value.boolean } == 0)
    }

    /// `gcvalue`
    pub fn gc_value(&self) -> GcObject {
        debug_assert!(self.is_collectable());
        unsafe {
            GcObject::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().value.gc,
            ))
        }
    }

    /// `tsvalue`
    pub fn string_value(&self) -> TString {
        debug_assert!(self.is_string());
        unsafe {
            TString::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().value.gc.cast(),
            ))
        }
    }

    /// `hvalue`
    pub fn table_value(&self) -> Table {
        debug_assert!(self.is_table());
        unsafe {
            Table::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().value.gc.cast(),
            ))
        }
    }

    /// `uvalue`
    pub fn userdata_value(&self) -> Userdata {
        debug_assert!(self.is_userdata());
        unsafe {
            Userdata::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().value.gc.cast(),
            ))
        }
    }

    /// `clvalue`
    pub fn closure_value(&self) -> Closure {
        debug_assert!(self.is_function());
        unsafe {
            Closure::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().value.gc.cast(),
            ))
        }
    }

    /// `pvalue`
    pub fn pointer_value(&self) -> *mut () {
        debug_assert!(self.is_light_userdata());
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().value.pointer }
    }

    /// `nvalue`
    pub fn number_value(&self) -> f64 {
        debug_assert!(self.is_number());
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().value.number }
    }

    /// `lvalue`
    pub fn integer_value(&self) -> i64 {
        debug_assert!(self.is_integer());
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().value.integer }
    }

    /// `bvalue`
    pub fn boolean_value(&self) -> i32 {
        debug_assert!(self.is_boolean());
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().value.boolean }
    }

    /// `thvalue`
    pub fn thread_value(&self) -> Thread {
        debug_assert!(self.is_thread());
        unsafe {
            Thread::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().value.gc.cast(),
            ))
        }
    }

    /// `bufvalue`
    pub fn buffer_value(&self) -> Buffer {
        debug_assert!(self.is_buffer());
        unsafe {
            Buffer::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().value.gc.cast(),
            ))
        }
    }

    /// `upvalue`
    pub fn upvalue_value(&self) -> UpVal {
        debug_assert!(self.is_upvalue());
        unsafe {
            UpVal::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().value.gc.cast(),
            ))
        }
    }

    /// `classvalue`
    pub fn class_value(&self) -> Class {
        debug_assert!(self.is_class());
        unsafe {
            Class::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().value.gc.cast(),
            ))
        }
    }

    /// `objectvalue`
    pub fn object_value(&self) -> Object {
        debug_assert!(self.is_object());
        unsafe {
            Object::from_raw(NonNull::new_unchecked(
                self.as_ptr().as_ref().unwrap_unchecked().value.gc.cast(),
            ))
        }
    }

    /// `pvalue`
    pub fn proto_value(&self) -> Proto {
        debug_assert!(self.is_proto());
        unsafe { self.gc_value().to_proto() }
    }

    /// `lightuserdatatag`
    pub fn light_userdata_tag(&self) -> i32 {
        debug_assert!(self.is_light_userdata());
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().extra[0] }
    }

    /// `vvalue`
    pub fn vector_value(&self) -> [f32; LUA_VECTOR_SIZE] {
        debug_assert!(self.is_vector());
        let vector = self.as_ptr().cast::<f32>();
        #[cfg(not(feature = "vector4"))]
        unsafe {
            [*vector, *vector.add(1), *vector.add(2)]
        }
        #[cfg(feature = "vector4")]
        unsafe {
            [*vector, *vector.add(1), *vector.add(2), *vector.add(3)]
        }
    }

    /// `setnilvalue`
    pub fn set_nil(&self) {
        unsafe {
            self.as_ptr().as_mut().unwrap_unchecked().tt = LUA_TNIL;
        }
    }

    /// `setnvalue`
    pub fn set_number(&self, value: f64) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue { number: value };
            raw.tt = LUA_TNUMBER;
        }
    }

    /// `setlvalue`
    pub fn set_integer(&self, value: i64) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue { integer: value };
            raw.tt = LUA_TINTEGER;
        }
    }

    /// `setbvalue`
    pub fn set_boolean(&self, value: i32) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue { boolean: value };
            raw.tt = LUA_TBOOLEAN;
        }
    }

    /// `setpvalue`
    pub fn set_light_userdata(&self, pointer: *mut (), tag: i32) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue { pointer };
            raw.extra[0] = tag;
            raw.tt = LUA_TLIGHTUSERDATA;
        }
    }

    /// `setsvalue`
    pub fn set_string_value(&self, value: TString) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue {
                gc: GcObject::from(value).as_ptr(),
            };
            raw.tt = LUA_TSTRING;
        }
    }

    /// `setvvalue`
    pub fn set_vector(&self, value: [f32; LUA_VECTOR_SIZE]) {
        let vector = self.as_ptr().cast::<f32>();
        unsafe {
            *vector = value[0];
            *vector.add(1) = value[1];
            *vector.add(2) = value[2];
        }
        #[cfg(feature = "vector4")]
        unsafe {
            *vector.add(3) = value[3];
        }
        unsafe {
            (*self.as_ptr()).tt = LUA_TVECTOR;
        }
    }

    /// `setuvalue`
    pub fn set_userdata_value(&self, value: Userdata) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue {
                gc: GcObject::from(value).as_ptr(),
            };
            raw.tt = LUA_TUSERDATA;
        }
    }

    /// `setthvalue`
    pub fn set_thread_value(&self, value: &Thread) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue {
                gc: GcObject::from(value).as_ptr(),
            };
            raw.tt = LUA_TTHREAD;
        }
    }

    /// `setbufvalue`
    pub fn set_buffer_value(&self, value: Buffer) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue {
                gc: GcObject::from(value).as_ptr(),
            };
            raw.tt = LUA_TBUFFER;
        }
    }

    /// `setclvalue`
    pub fn set_closure_value(&self, value: Closure) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue {
                gc: GcObject::from(value).as_ptr(),
            };
            raw.tt = LUA_TFUNCTION;
        }
    }

    /// `sethvalue`
    pub fn set_table_value(&self, value: Table) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue {
                gc: GcObject::from(value).as_ptr(),
            };
            raw.tt = LUA_TTABLE;
        }
    }

    /// `setptvalue`
    pub fn set_proto_value(&self, value: Proto) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue {
                gc: GcObject::from(value).as_ptr(),
            };
            raw.tt = LUA_TPROTO;
        }
    }

    /// `setupvalue`
    pub fn set_upvalue_value(&self, value: UpVal) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue {
                gc: GcObject::from(value).as_ptr(),
            };
            raw.tt = LUA_TUPVALUE;
        }
    }

    /// `setclassvalue`
    pub fn set_class_value(&self, value: Class) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue {
                gc: GcObject::from(value).as_ptr(),
            };
            raw.tt = LUA_TCLASS;
        }
    }

    /// `setobjectvalue`
    pub fn set_object_value(&self, value: Object) {
        unsafe {
            let raw = self.as_ptr().as_mut().unwrap_unchecked();
            raw.value = RawValue {
                gc: GcObject::from(value).as_ptr(),
            };
            raw.tt = LUA_TOBJECT;
        }
    }

    /// `setobj`
    pub fn set_obj(&self, other: impl Into<TValue>) {
        let other = other.into();
        unsafe {
            core::ptr::copy(other.as_ptr(), self.as_ptr(), 1);
        }
    }

    /// `luaO_rawequalObj`
    pub fn raw_equal(&self, other: impl Into<TValue>) -> bool {
        let other = other.into();
        if self.tt() != other.tt() {
            return false;
        }

        match self.tt() {
            x if x == LUA_TNIL => true,
            x if x == LUA_TNUMBER => self.number_value() == other.number_value(),
            x if x == LUA_TINTEGER => self.integer_value() == other.integer_value(),
            x if x == LUA_TVECTOR => self.vector_value() == other.vector_value(),
            x if x == LUA_TBOOLEAN => self.boolean_value() == other.boolean_value(),
            x if x == LUA_TLIGHTUSERDATA => {
                self.pointer_value() == other.pointer_value()
                    && self.light_userdata_tag() == other.light_userdata_tag()
            }
            _ => {
                debug_assert!(self.is_collectable());
                self.gc_value() == other.gc_value()
            }
        }
    }
}

/// `luaO_nilobject`
pub fn nil_object() -> TValue {
    unsafe { TValue::from_ref(&LUA_O_NIL_OBJECT.0) }
}
impl crate::handle::sealed::Sealed for TValue {}
impl RawHandle for TValue {
    type Raw = RawTValue;

    fn as_ptr(&self) -> *mut Self::Raw {
        self.raw.as_ptr()
    }
}

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