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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
use core::ptr;

use luau_common::{BStr, ByteSlice, flags};

use super::{
    LUA_ENVIRON_INDEX, LUA_GLOBALS_INDEX, LUA_REGISTRY_INDEX, LUA_TNONE, LUAI_MAX_C_STACK, Thread,
    is_pseudo,
};
use crate::buffer::BufferRuntime;
use crate::call::{ProtectedCall, ThreadStack};
use crate::debug::DebugRuntime;
use crate::gc::{GcBarrier, GcRuntime};
use crate::handle::RawHandle;
use crate::handle::sealed::Sealed;
use crate::state::ThreadState;
use crate::string::{LuaString, StringFormatting, StringRuntime, TString};
use crate::types::{
    LUA_T_COUNT, LUA_TBOOLEAN, LUA_TBUFFER, LUA_TCLASS, LUA_TFUNCTION, LUA_TLIGHTUSERDATA,
    LUA_TNIL, LUA_TNUMBER, LUA_TOBJECT, LUA_TSTRING, LUA_TTABLE, LUA_TTHREAD, LUA_TUSERDATA,
    LUA_TVECTOR,
};
use crate::value::{RAW_TVALUE_NIL, TValue, TValueCursor, nil_object};
use crate::vm::{VmConversions, VmOperations};
use crate::{Class, Table, VmErrorResult, VmResult};

// Raw stack capability
/// Unstable raw stack-address conversion capability.
///
/// # Safety
///
/// Indices must be valid for this thread under the corresponding Luau stack
/// rule. Returned views and cursors borrow no storage and are invalidated by
/// stack relocation, stack mutation, reset, close, or VM destruction.
#[allow(
    clippy::missing_safety_doc,
    reason = "all methods share the capability-level safety contract"
)]
pub trait RawStackAccess: Sealed {
    /// `luaA_toobject`
    unsafe fn to_object(&self, index: i32) -> Option<TValue>;

    /// `luaA_pushvalue`
    unsafe fn push_value_internal(&self, value: TValue) -> VmErrorResult;

    unsafe fn push_table(&self, table: Table) -> VmErrorResult;

    /// `luaA_pushclass`
    unsafe fn push_class(&self, class: Class) -> VmErrorResult;
}

// Stack addressing and movement
impl RawStackAccess for Thread {
    /// `luaA_toobject`
    unsafe fn to_object(&self, index: i32) -> Option<TValue> {
        let object = unsafe { self.index_to_addr(index) };
        if object == nil_object() {
            None
        } else {
            Some(object)
        }
    }

    /// `luaA_pushvalue`
    unsafe fn push_value_internal(&self, value: TValue) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            top.value_unchecked().set_obj(value);
            debug_assert!(top.offset_from(self.current_call_info().top()) < 0);
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    unsafe fn push_table(&self, table: Table) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            top.value_unchecked().set_table_value(table);
            debug_assert!(top.offset_from(self.current_call_info().top()) < 0);
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `luaA_pushclass`
    unsafe fn push_class(&self, class: Class) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            top.value_unchecked().set_class_value(class);
            debug_assert!(top.offset_from(self.current_call_info().top()) < 0);
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }
}

impl Thread {
    /// `pseudo2addr`
    unsafe fn pseudo_to_addr(&self, index: i32) -> TValue {
        debug_assert!(is_pseudo(index));

        unsafe {
            let global = self.global();

            match index {
                LUA_REGISTRY_INDEX => global.registry(),
                LUA_ENVIRON_INDEX => {
                    let pseudo_temp = global.pseudo_temp();
                    pseudo_temp.set_table_value(self.current_env());
                    pseudo_temp
                }
                LUA_GLOBALS_INDEX => {
                    let pseudo_temp = global.pseudo_temp();
                    pseudo_temp.set_table_value(self.globals());
                    pseudo_temp
                }
                _ => {
                    let closure = self.current_function();
                    let upvalue_index = (LUA_GLOBALS_INDEX - index) as usize;

                    if upvalue_index
                        <= closure.as_ptr().as_ref().unwrap_unchecked().n_upvalues as usize
                    {
                        closure.native_upvalue(upvalue_index - 1)
                    } else {
                        nil_object()
                    }
                }
            }
        }
    }

    pub(crate) unsafe fn stack_index_cursor(&self, index: i32) -> Option<TValueCursor> {
        debug_assert!(index != 0);

        unsafe {
            if index > 0 {
                let object = self.stack_base().add((index - 1) as usize);
                debug_assert!(
                    index
                        <= self
                            .current_call_info()
                            .top()
                            .offset_from(self.stack_base()) as i32
                );
                Some(object)
            } else if index > LUA_REGISTRY_INDEX {
                debug_assert!(-index <= self.stack_top().offset_from(self.stack_base()) as i32);
                Some(self.stack_top().offset(index as isize))
            } else {
                None
            }
        }
    }

    pub(crate) unsafe fn stack_index_to_cursor(&self, index: i32) -> TValueCursor {
        debug_assert!(!is_pseudo(index));
        unsafe { self.stack_index_cursor(index).unwrap_unchecked() }
    }

    /// `index2addr`
    pub(crate) unsafe fn index_to_addr(&self, index: i32) -> TValue {
        unsafe {
            if let Some(object) = self.stack_index_cursor(index) {
                if index > 0 && object.offset_from(self.stack_top()) >= 0 {
                    nil_object()
                } else {
                    object.value_unchecked()
                }
            } else {
                self.pseudo_to_addr(index)
            }
        }
    }

    /// `ensure_stack_impl`
    pub(crate) unsafe fn ensure_stack(&self, error_thread: &Thread, size: i32) -> VmErrorResult {
        unsafe {
            let available = self.current_call_info().top().offset_from(self.stack_top()) as i32;
            if flags::LuauAutoStack.get()
                && size > 0
                && size > available
                && self.check_stack(size) == 0
            {
                return crate::run_error!(error_thread, "stack overflow");
            }
        }
        Ok(())
    }

    /// `lua_absindex`
    pub unsafe fn abs_index(&self, index: i32) -> i32 {
        unsafe {
            debug_assert!(
                (index > 0 && index <= self.get_top())
                    || (index < 0 && -index <= self.get_top())
                    || is_pseudo(index)
            );
            if index > 0 || is_pseudo(index) {
                index
            } else {
                self.get_top() + index + 1
            }
        }
    }

    /// `lua_gettop`
    pub unsafe fn get_top(&self) -> i32 {
        unsafe { self.stack_top().offset_from(self.stack_base()) as i32 }
    }

    /// `lua_checkstack`
    pub unsafe fn check_stack(&self, size: i32) -> i32 {
        debug_assert!(size >= 0);
        unsafe {
            let top_offset = self.stack_top().offset_from(self.stack_base()) as i32;
            if size > LUAI_MAX_C_STACK || top_offset + size > LUAI_MAX_C_STACK {
                return 0;
            }

            if size > 0 {
                if self.stack_limit_reached(size) {
                    #[repr(C)]
                    struct GrowStackContext {
                        size: i32,
                    }

                    unsafe fn grow_stack_callback(
                        thread: &Thread,
                        context: &mut GrowStackContext,
                    ) -> VmResult {
                        unsafe { thread.grow_stack(context.size) }?;
                        Ok(())
                    }

                    let mut context = GrowStackContext { size };
                    if self
                        .raw_run_protected(grow_stack_callback, &mut context)
                        .is_err()
                    {
                        return 0;
                    }
                }

                let pointer = self.stack_top().add(size as usize);
                self.expand_stack_limit(pointer);
            }

            1
        }
    }

    /// `lua_rawcheckstack`
    pub unsafe fn raw_check_stack(&self, size: i32) -> VmErrorResult {
        debug_assert!(size >= 0);
        unsafe {
            self.check_stack_internal(size)?;
            let pointer = self.stack_top().add(size as usize);
            self.expand_stack_limit(pointer);
        }
        Ok(())
    }

    /// `lua_settop`
    pub unsafe fn set_top(&self, index: i32) -> VmErrorResult {
        debug_assert!(index >= 0);
        unsafe {
            let base = self.stack_base();
            let mut top = self.stack_top();
            self.ensure_stack(self, index - top.offset_from(base) as i32)?;
            debug_assert!(index <= self.stack_last().offset_from(base) as i32);
            let target = base.add(index as usize);
            while top < target {
                top.value_unchecked().set_nil();
                top = top.add(1);
            }
            self.set_stack_top(target);
        }
        Ok(())
    }

    /// Restores the stack top to a previous absolute top.
    pub unsafe fn restore_top(&self, top: i32) {
        unsafe {
            let current_top = self.get_top();
            debug_assert!((0..=current_top).contains(&top));
            self.set_stack_top(self.stack_base().add(top as usize));
        }
    }

    /// `lua_pop`
    pub unsafe fn pop(&self, count: i32) {
        debug_assert!(count >= 0);
        unsafe {
            let current_top = self.get_top();
            debug_assert!(count <= current_top);
            self.restore_top(current_top - count);
        }
    }

    /// `lua_pushvalue`
    pub unsafe fn push_value(&self, index: i32) -> VmErrorResult {
        unsafe {
            self.thread_barrier();
            self.ensure_stack(self, 1)?;

            let top = self.stack_top();
            let object = self.index_to_addr(index);
            top.value_unchecked().set_obj(object);
            debug_assert!(top.offset_from(self.current_call_info().top()) < 0);
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `lua_remove`
    pub unsafe fn remove(&self, index: i32) {
        unsafe {
            let object_cursor = self.stack_index_to_cursor(index);
            let next = object_cursor.add(1);
            ptr::copy(
                next.as_ptr(),
                object_cursor.as_ptr(),
                self.stack_top().offset_from(next) as usize,
            );
            self.set_stack_top(self.stack_top().sub(1));
        }
    }

    /// `lua_insert`
    pub unsafe fn insert(&self, index: i32) {
        unsafe {
            self.thread_barrier();

            let object_cursor = self.stack_index_to_cursor(index);

            let top = self.stack_top().as_ptr();
            let mut slot = top;
            while slot > object_cursor.as_ptr() {
                ptr::copy(slot.sub(1), slot, 1);
                slot = slot.sub(1);
            }

            ptr::copy(top, object_cursor.as_ptr(), 1);
        }
    }

    /// `lua_replace`
    pub unsafe fn replace(&self, index: i32) {
        unsafe {
            let top = self.stack_top();
            debug_assert!(top.offset_from(self.stack_base()) > 0);

            self.thread_barrier();

            let object = self.index_to_addr(index);
            debug_assert!(object != nil_object());

            let value = top.sub(1);
            if index == LUA_ENVIRON_INDEX {
                debug_assert!(self.current_call_info() != self.base_call_info());
                debug_assert!(value.value_unchecked().is_table());

                let function = self.current_function();
                function.set_env(value.value_unchecked().table_value());
                self.barrier_value(function.into(), value.value_unchecked());
            } else if index == LUA_GLOBALS_INDEX {
                debug_assert!(value.value_unchecked().is_table());
                self.set_globals(value.value_unchecked().table_value());
            } else {
                object.set_obj(value.value_unchecked());

                if index < LUA_GLOBALS_INDEX {
                    let function = self.current_function();
                    self.barrier_value(function.into(), value.value_unchecked());
                }
            }

            self.set_stack_top(top.sub(1));
        }
    }

    /// `lua_xmove`
    pub unsafe fn x_move(&self, to: &Thread, count: i32) -> VmErrorResult {
        unsafe {
            debug_assert!(count >= 0);

            if *self == *to {
                return Ok(());
            }

            debug_assert!(count <= self.stack_top().offset_from(self.stack_base()) as i32);
            debug_assert!(self.global() == to.global());

            to.thread_barrier();
            to.ensure_stack(self, count)?;

            let to_top = to.stack_top();
            let from_top = self.stack_top().sub(count as usize);
            for index in 0..count as usize {
                to_top
                    .add(index)
                    .value_unchecked()
                    .set_obj(from_top.add(index).value_unchecked());
            }

            self.set_stack_top(from_top);
            to.set_stack_top(to_top.add(count as usize));
        }
        Ok(())
    }

    /// `lua_xpush`
    pub unsafe fn x_push(&self, to: &Thread, index: i32) -> VmErrorResult {
        unsafe {
            debug_assert!(self.global() == to.global());

            to.thread_barrier();
            to.ensure_stack(self, 1)?;

            let top = to.stack_top();
            let object = self.index_to_addr(index);
            top.value_unchecked().set_obj(object);
            debug_assert!(top < to.current_call_info().top());
            to.set_stack_top(top.add(1));
        }
        Ok(())
    }
}

// Value pushes
impl Thread {
    /// `lua_pushnil`
    pub unsafe fn push_nil(&self) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            debug_assert!(top < self.current_call_info().top());
            top.value_unchecked().set_nil();
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `lua_pushnumber`
    pub unsafe fn push_number(&self, value: f64) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            debug_assert!(top < self.current_call_info().top());
            top.value_unchecked().set_number(value);
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `lua_pushinteger`
    pub unsafe fn push_integer(&self, value: i32) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            debug_assert!(top < self.current_call_info().top());
            top.value_unchecked().set_number(value as f64);
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `lua_pushinteger64`
    pub unsafe fn push_integer64(&self, value: i64) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            debug_assert!(top < self.current_call_info().top());
            top.value_unchecked().set_integer(value);
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `lua_pushunsigned`
    pub unsafe fn push_unsigned(&self, value: u32) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            debug_assert!(top < self.current_call_info().top());
            top.value_unchecked().set_number(value as f64);
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `lua_pushvector`
    pub unsafe fn push_vector(
        &self,
        components: [f32; crate::types::LUA_VECTOR_SIZE],
    ) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            debug_assert!(top < self.current_call_info().top());
            top.value_unchecked().set_vector(components);
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `lua_pushboolean`
    pub unsafe fn push_boolean(&self, value: i32) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            debug_assert!(top < self.current_call_info().top());
            top.value_unchecked().set_boolean(i32::from(value != 0));
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `lua_pushlightuserdatatagged`
    pub unsafe fn push_light_userdata_tagged(&self, pointer: *mut (), tag: i32) -> VmErrorResult {
        unsafe {
            self.ensure_stack(self, 1)?;
            let top = self.stack_top();
            debug_assert!(top < self.current_call_info().top());
            top.value_unchecked().set_light_userdata(pointer, tag);
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `lua_pushlightuserdata`
    pub unsafe fn push_light_userdata(&self, pointer: *mut ()) -> VmErrorResult {
        unsafe { self.push_light_userdata_tagged(pointer, 0) }
    }

    /// `lua_pushlstring`
    pub unsafe fn push_string(&self, bytes: impl AsRef<[u8]>) -> VmErrorResult {
        let bytes = bytes.as_ref();
        unsafe {
            self.check_gc()?;
            self.thread_barrier();
            self.ensure_stack(self, 1)?;

            let interned = self.intern_string(bytes.as_bstr())?;
            let top = self.stack_top();
            top.value_unchecked().set_string_value(interned);
            debug_assert!(top < self.current_call_info().top());
            self.set_stack_top(top.add(1));
        }
        Ok(())
    }

    /// `lua_pushstring`
    pub unsafe fn push_optional_string(&self, bytes: Option<impl AsRef<[u8]>>) -> VmErrorResult {
        if let Some(bytes) = bytes {
            unsafe { self.push_string(bytes) }
        } else {
            unsafe { self.push_nil() }
        }
    }

    /// `lua_pushvfstring`
    pub unsafe fn push_vfstring<'a>(
        &self,
        format: &str,
        args: impl AsMut<[luau_printf::Arg<'a>]>,
    ) -> VmErrorResult<LuaString> {
        unsafe {
            self.check_gc()?;
            self.thread_barrier();
            self.push_vfstring_internal(format, args)
        }
    }

    /// `lua_pushfstring`
    pub unsafe fn push_fstring<'a>(
        &self,
        format: &str,
        args: impl AsMut<[luau_printf::Arg<'a>]>,
    ) -> VmErrorResult<LuaString> {
        unsafe {
            self.check_gc()?;
            self.thread_barrier();
            self.push_fstring_internal(format, args)
        }
    }
}

// Value queries and conversions
impl Thread {
    /// Borrows bytes from an interned string owned by this thread's VM.
    ///
    /// The result is tied to the thread borrow rather than to the copied raw
    /// string handle. Callers of the surrounding unsafe API remain
    /// responsible for preventing collection while the borrow is live.
    unsafe fn borrow_interned_string(&self, string: TString) -> &BStr {
        unsafe {
            let raw = string.as_ptr().as_ref().unwrap_unchecked();
            core::slice::from_raw_parts(string.data_ptr(), raw.len as usize).as_bstr()
        }
    }

    /// `lua_isnumber`
    pub unsafe fn is_number(&self, index: i32) -> i32 {
        unsafe {
            let object = self.index_to_addr(index);
            let mut converted = RAW_TVALUE_NIL;
            let converted = TValue::from_mut(&mut converted);
            self.to_number_internal(object, converted).is_some() as i32
        }
    }

    /// `lua_isstring`
    pub unsafe fn is_string(&self, index: i32) -> i32 {
        let tag = unsafe { self.type_of(index) };
        (tag == LUA_TSTRING || tag == LUA_TNUMBER) as i32
    }

    /// `lua_islightuserdata`
    pub unsafe fn is_light_userdata(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TLIGHTUSERDATA) as i32
    }

    /// `lua_isfunction`
    pub unsafe fn is_function(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TFUNCTION) as i32
    }

    /// `lua_istable`
    pub unsafe fn is_table(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TTABLE) as i32
    }

    /// `lua_isnil`
    pub unsafe fn is_nil(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TNIL) as i32
    }

    /// `lua_isboolean`
    pub unsafe fn is_boolean(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TBOOLEAN) as i32
    }

    /// `lua_isvector`
    pub unsafe fn is_vector(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TVECTOR) as i32
    }

    /// `lua_isthread`
    pub unsafe fn is_thread(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TTHREAD) as i32
    }

    /// `lua_isbuffer`
    pub unsafe fn is_buffer(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TBUFFER) as i32
    }

    /// `lua_isnone`
    pub unsafe fn is_none(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TNONE) as i32
    }

    /// `lua_isnoneornil`
    pub unsafe fn is_none_or_nil(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } <= LUA_TNIL) as i32
    }

    /// `lua_isclass`
    pub unsafe fn is_class(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TCLASS) as i32
    }

    /// `lua_isobject`
    pub unsafe fn is_object(&self, index: i32) -> i32 {
        (unsafe { self.type_of(index) } == LUA_TOBJECT) as i32
    }

    /// `lua_isinteger64`
    pub unsafe fn is_integer64(&self, index: i32) -> i32 {
        let object = unsafe { self.index_to_addr(index) };
        (object != nil_object() && object.is_integer()) as i32
    }

    /// `lua_iscfunction`
    pub unsafe fn is_native_function(&self, index: i32) -> i32 {
        let object = unsafe { self.index_to_addr(index) };
        (object != nil_object()
            && object.is_function()
            && unsafe { object.closure_value().is_native() }) as i32
    }

    /// `lua_isLfunction`
    pub unsafe fn is_lua_function(&self, index: i32) -> i32 {
        let object = unsafe { self.index_to_addr(index) };
        (object != nil_object()
            && object.is_function()
            && unsafe { object.closure_value().is_lua() }) as i32
    }

    /// `lua_isuserdata`
    pub unsafe fn is_userdata(&self, index: i32) -> i32 {
        let object = unsafe { self.index_to_addr(index) };
        (object != nil_object() && (object.is_userdata() || object.is_light_userdata())) as i32
    }

    /// `lua_type`
    pub unsafe fn type_of(&self, index: i32) -> i32 {
        let object = unsafe { self.index_to_addr(index) };
        if object == nil_object() {
            LUA_TNONE
        } else {
            object.tt()
        }
    }

    /// `lua_typename`
    pub unsafe fn type_name(&self, tag: i32) -> LuaString {
        debug_assert!((LUA_TNONE..LUA_T_COUNT as i32).contains(&tag));

        if tag == LUA_TNONE {
            LuaString::from_static(b"no value".as_bstr())
        } else {
            LuaString::from_interned(unsafe { self.global().type_name(tag as usize) })
        }
    }

    /// `lua_equal`
    pub unsafe fn equal(&self, left: i32, right: i32) -> VmResult<i32> {
        unsafe {
            let left_object = self.index_to_addr(left);
            let right_object = self.index_to_addr(right);

            if left_object == nil_object()
                || right_object == nil_object()
                || left_object.tt() != right_object.tt()
            {
                Ok(0)
            } else {
                self.equal_value(left_object, right_object)
            }
        }
    }

    /// `lua_rawequal`
    pub unsafe fn raw_equal(&self, left: i32, right: i32) -> i32 {
        let left_object = unsafe { self.index_to_addr(left) };
        let right_object = unsafe { self.index_to_addr(right) };

        if left_object == nil_object() || right_object == nil_object() {
            0
        } else {
            left_object.raw_equal(right_object) as i32
        }
    }

    /// `lua_lessthan`
    pub unsafe fn less_than(&self, left: i32, right: i32) -> VmResult<i32> {
        unsafe {
            let left_object = self.index_to_addr(left);
            let right_object = self.index_to_addr(right);

            if left_object == nil_object() || right_object == nil_object() {
                Ok(0)
            } else {
                self.less_than_internal(left_object, right_object)
            }
        }
    }

    /// `lua_tonumberx`
    pub unsafe fn to_number(&self, index: i32) -> Option<f64> {
        unsafe {
            let object = self.index_to_addr(index);
            let mut converted = RAW_TVALUE_NIL;
            let converted = TValue::from_mut(&mut converted);
            self.to_number_internal(object, converted)
                .map(|value| value.number_value())
        }
    }

    /// `lua_tointegerx`
    pub unsafe fn to_integer(&self, index: i32) -> Option<i32> {
        unsafe {
            let object = self.index_to_addr(index);
            let mut converted = RAW_TVALUE_NIL;
            let converted = TValue::from_mut(&mut converted);
            self.to_number_internal(object, converted)
                .map(|value| value.number_value())
                .map(crate::number::num_to_int)
        }
    }

    /// `lua_tounsignedx`
    pub unsafe fn to_unsigned(&self, index: i32) -> Option<u32> {
        unsafe {
            let object = self.index_to_addr(index);
            let mut converted = RAW_TVALUE_NIL;
            let converted = TValue::from_mut(&mut converted);
            self.to_number_internal(object, converted)
                .map(|value| value.number_value())
                .map(crate::number::num_to_unsigned)
        }
    }

    /// `lua_tovector`
    pub unsafe fn to_vector(&self, index: i32) -> Option<[f32; crate::types::LUA_VECTOR_SIZE]> {
        let object = unsafe { self.index_to_addr(index) };
        if object == nil_object() || !object.is_vector() {
            None
        } else {
            Some(object.vector_value())
        }
    }

    /// `lua_toboolean`
    pub unsafe fn to_boolean(&self, index: i32) -> i32 {
        let object = unsafe { self.index_to_addr(index) };
        (!object.is_false()) as i32
    }

    /// `lua_tointeger64`
    pub unsafe fn to_integer64(&self, index: i32) -> Option<i64> {
        unsafe {
            let object = self.index_to_addr(index);

            if object != nil_object() && object.is_integer() {
                Some(object.integer_value())
            } else {
                None
            }
        }
    }

    /// `lua_tostring`
    pub unsafe fn to_string(&self, index: i32) -> VmErrorResult<Option<&BStr>> {
        unsafe {
            let mut object = self.index_to_addr(index);
            if !object.is_string() {
                self.thread_barrier();
                if self.to_string_internal(object)? == 0 {
                    return Ok(None);
                }

                self.check_gc()?;
                object = self.index_to_addr(index);
            }

            Ok(Some(self.borrow_interned_string(object.string_value())))
        }
    }

    /// `lua_tostringatom`
    pub unsafe fn to_string_atom(&self, index: i32) -> Option<(&BStr, i32)> {
        unsafe {
            let object = self.index_to_addr(index);
            if object == nil_object() || !object.is_string() {
                return None;
            }

            let string = object.string_value();
            self.update_atom(string);

            Some((
                self.borrow_interned_string(string),
                string.as_ptr().as_ref().unwrap_unchecked().atom as i32,
            ))
        }
    }

    /// `lua_namecallatom`
    pub unsafe fn namecall_atom(&self) -> Option<(&BStr, i32)> {
        unsafe {
            let string = self.name_call()?;

            self.update_atom(string);

            Some((
                self.borrow_interned_string(string),
                string.as_ptr().as_ref().unwrap_unchecked().atom as i32,
            ))
        }
    }

    /// Numeric result of the Luau length operator (`#`).
    pub unsafe fn len(&self, index: i32) -> VmResult<f64> {
        unsafe {
            self.ensure_stack(self, 1)?;
            let value = self.index_to_addr(index);
            let result = self.stack_top();
            self.do_len(result, value)?;
            debug_assert!(result < self.current_call_info().top());
            self.set_stack_top(result.add(1));
            Ok(result.value_unchecked().number_value())
        }
    }

    /// `lua_objlen`
    pub unsafe fn obj_len(&self, index: i32) -> i32 {
        unsafe {
            let object = self.index_to_addr(index);
            if object == nil_object() {
                return 0;
            }

            match object.tt() {
                x if x == LUA_TSTRING => {
                    object
                        .string_value()
                        .as_ptr()
                        .as_ref()
                        .unwrap_unchecked()
                        .len as i32
                }
                x if x == LUA_TUSERDATA => {
                    object
                        .userdata_value()
                        .as_ptr()
                        .as_ref()
                        .unwrap_unchecked()
                        .len
                }
                x if x == LUA_TBUFFER => {
                    object
                        .buffer_value()
                        .as_ptr()
                        .as_ref()
                        .unwrap_unchecked()
                        .len as i32
                }
                x if x == LUA_TTABLE => object.table_value().getn(),
                _ => 0,
            }
        }
    }

    /// `lua_topointer`
    pub unsafe fn to_pointer(&self, index: i32) -> *const () {
        let object = unsafe { self.index_to_addr(index) };
        if object == nil_object() {
            return ptr::null();
        }

        match object.tt() {
            LUA_TUSERDATA => object.userdata_value().data_ptr().cast(),
            LUA_TLIGHTUSERDATA => object.pointer_value(),
            _ if object.is_collectable() => object.gc_value().as_ptr().cast(),
            _ => ptr::null(),
        }
    }
}

// Buffer values
impl Thread {
    /// `lua_newbuffer`
    pub unsafe fn new_buffer(&self, size: usize) -> VmErrorResult<*mut u8> {
        unsafe {
            self.check_gc()?;
            self.thread_barrier();
            self.ensure_stack(self, 1)?;

            let buffer = self.new_buffer_internal(size)?;
            let data = buffer.data_mut_ptr();
            let top = self.stack_top();
            top.value_unchecked().set_buffer_value(buffer);
            debug_assert!(top < self.current_call_info().top());
            self.set_stack_top(top.add(1));

            Ok(data)
        }
    }

    /// `lua_tobuffer`
    pub unsafe fn to_buffer(&self, index: i32) -> Option<(*mut u8, usize)> {
        let object = unsafe { self.index_to_addr(index) };
        if object == nil_object() || !object.is_buffer() {
            return None;
        }

        let buffer = object.buffer_value();
        Some((unsafe { buffer.data_mut_ptr() }, unsafe {
            buffer.as_ptr().as_ref().unwrap_unchecked().len as usize
        }))
    }
}