1use std::cell::RefCell;
13use std::hash::{BuildHasherDefault, Hasher};
14use std::rc::Rc;
15
16pub use lua_types::error::LuaError;
17pub use lua_types::{CallInfoIdx, StackIdx};
18
19pub struct StackIdxConv(pub StackIdx);
22
23#[inline(always)]
26pub fn stack_idx_to_i32(i: StackIdx) -> i32 {
27 i.0 as i32
28}
29
30impl From<u32> for StackIdxConv {
31 #[inline(always)]
32 fn from(v: u32) -> Self {
33 StackIdxConv(StackIdx(v))
34 }
35}
36impl From<i32> for StackIdxConv {
37 #[inline(always)]
38 fn from(v: i32) -> Self {
39 StackIdxConv(StackIdx(v.max(0) as u32))
40 }
41}
42impl From<usize> for StackIdxConv {
43 #[inline(always)]
44 fn from(v: usize) -> Self {
45 StackIdxConv(StackIdx(v as u32))
46 }
47}
48impl From<StackIdx> for StackIdxConv {
49 #[inline(always)]
50 fn from(v: StackIdx) -> Self {
51 StackIdxConv(v)
52 }
53}
54pub use lua_types::closure::{
55 LuaCClosure as LuaClosureC, LuaCFnPtr, LuaClosure, LuaLClosure as LuaClosureLua,
56};
57pub use lua_types::gc::GcRef;
58pub use lua_types::proto::LuaProto;
59pub use lua_types::string::LuaString;
60pub use lua_types::upval::UpVal;
61pub use lua_types::userdata::LuaUserData;
62pub use lua_types::value::{F2Imod, LuaTable, LuaValue};
63
64pub struct LuaByteHasher {
65 hash: u64,
66}
67
68impl Default for LuaByteHasher {
69 fn default() -> Self {
70 Self {
71 hash: 0xcbf2_9ce4_8422_2325,
72 }
73 }
74}
75
76impl Hasher for LuaByteHasher {
77 #[inline]
78 fn write(&mut self, bytes: &[u8]) {
79 const PRIME: u64 = 0x0000_0100_0000_01b3;
80 for &byte in bytes {
81 self.hash ^= u64::from(byte);
82 self.hash = self.hash.wrapping_mul(PRIME);
83 }
84 }
85
86 #[inline]
87 fn write_u8(&mut self, i: u8) {
88 self.write(&[i]);
89 }
90
91 #[inline]
92 fn write_usize(&mut self, i: usize) {
93 self.write(&i.to_ne_bytes());
94 }
95
96 #[inline]
97 fn finish(&self) -> u64 {
98 self.hash
99 }
100}
101
102pub type LuaByteBuildHasher = BuildHasherDefault<LuaByteHasher>;
103
104pub struct InternedStringMap {
119 buckets: Vec<Vec<GcRef<LuaString>>>,
120 count: usize,
121}
122
123impl Default for InternedStringMap {
124 fn default() -> Self {
125 InternedStringMap {
126 buckets: (0..64).map(|_| Vec::new()).collect(),
127 count: 0,
128 }
129 }
130}
131
132impl InternedStringMap {
133 #[inline]
134 fn mask(&self) -> usize {
135 self.buckets.len() - 1
136 }
137
138 pub fn len(&self) -> usize {
139 self.count
140 }
141
142 pub fn is_empty(&self) -> bool {
143 self.count == 0
144 }
145
146 pub fn bucket_count(&self) -> usize {
151 self.buckets.len()
152 }
153
154 #[inline]
155 pub fn find(&self, bytes: &[u8], hash: u32) -> Option<GcRef<LuaString>> {
156 let bucket = &self.buckets[hash as usize & self.mask()];
157 bucket
158 .iter()
159 .find(|s| s.hash() == hash && s.as_bytes() == bytes)
160 .cloned()
161 }
162
163 pub fn insert(&mut self, s: GcRef<LuaString>) {
165 if self.count >= self.buckets.len() {
166 self.resize(self.buckets.len() * 2);
167 }
168 let m = self.mask();
169 self.buckets[s.hash() as usize & m].push(s);
170 self.count += 1;
171 }
172
173 fn resize(&mut self, new_len: usize) {
174 let old = std::mem::replace(
175 &mut self.buckets,
176 (0..new_len).map(|_| Vec::new()).collect(),
177 );
178 let m = self.mask();
179 for bucket in old {
180 for s in bucket {
181 self.buckets[s.hash() as usize & m].push(s);
182 }
183 }
184 }
185
186 pub fn shrink_if_sparse(&mut self) {
198 if self.count * 4 >= self.buckets.len() {
199 return;
200 }
201 let target = self.count.next_power_of_two().max(64);
202 if target < self.buckets.len() {
203 self.resize(target);
204 }
205 }
206
207 pub fn remove(&mut self, hash: u32, identity: usize) {
209 let m = self.mask();
210 let bucket = &mut self.buckets[hash as usize & m];
211 if let Some(pos) = bucket.iter().position(|s| s.identity() == identity) {
212 bucket.swap_remove(pos);
213 self.count -= 1;
214 }
215 }
216
217 pub fn iter(&self) -> impl Iterator<Item = &GcRef<LuaString>> {
218 self.buckets.iter().flatten()
219 }
220
221 pub fn contains_key(&self, bytes: &[u8]) -> bool {
222 self.find(bytes, LuaString::hash_bytes(bytes, 0)).is_some()
223 }
224}
225
226pub type LuaCFunction = fn(&mut LuaState) -> Result<usize, LuaError>;
232
233pub type LuaRustFunction = Rc<dyn Fn(&mut LuaState) -> Result<usize, LuaError>>;
234
235#[derive(Clone)]
236pub enum LuaCallable {
237 Bare(LuaCFunction),
238 Rust(LuaRustFunction),
239}
240
241impl std::fmt::Debug for LuaCallable {
242 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243 match self {
244 LuaCallable::Bare(_) => f.write_str("LuaCallable::Bare(..)"),
245 LuaCallable::Rust(_) => f.write_str("LuaCallable::Rust(..)"),
246 }
247 }
248}
249
250impl LuaCallable {
251 pub fn bare(f: LuaCFunction) -> Self {
252 LuaCallable::Bare(f)
253 }
254
255 pub fn rust(f: LuaRustFunction) -> Self {
256 LuaCallable::Rust(f)
257 }
258
259 pub fn as_bare(&self) -> Option<LuaCFunction> {
260 match self {
261 LuaCallable::Bare(f) => Some(*f),
262 LuaCallable::Rust(_) => None,
263 }
264 }
265
266 pub fn call(&self, state: &mut LuaState) -> Result<usize, LuaError> {
267 match self {
268 LuaCallable::Bare(f) => f(state),
269 LuaCallable::Rust(f) => f(state),
270 }
271 }
272}
273
274#[derive(Clone, Debug)]
275pub enum FinalizerObject {
276 Table(GcRef<LuaTable>),
277 UserData(GcRef<LuaUserData>),
278}
279
280impl FinalizerObject {
281 pub fn identity(&self) -> usize {
282 match self {
283 FinalizerObject::Table(t) => t.identity(),
284 FinalizerObject::UserData(u) => u.identity(),
285 }
286 }
287
288 pub fn metatable(&self) -> Option<GcRef<LuaTable>> {
289 match self {
290 FinalizerObject::Table(t) => t.metatable(),
291 FinalizerObject::UserData(u) => u.metatable(),
292 }
293 }
294
295 pub fn as_lua_value(&self) -> LuaValue {
296 match self {
297 FinalizerObject::Table(t) => LuaValue::Table(t.clone()),
298 FinalizerObject::UserData(u) => LuaValue::UserData(u.clone()),
299 }
300 }
301
302 pub fn mark(&self, marker: &mut lua_gc::Marker) {
303 match self {
304 FinalizerObject::Table(t) => marker.mark(t.0),
305 FinalizerObject::UserData(u) => marker.mark(u.0),
306 }
307 }
308
309 pub fn heap_ptr(&self) -> Option<std::ptr::NonNull<lua_gc::GcBox<dyn lua_gc::Trace>>> {
310 Some(match self {
311 FinalizerObject::Table(t) => t.0.as_trace_ptr(),
312 FinalizerObject::UserData(u) => u.0.as_trace_ptr(),
313 })
314 }
315
316 pub fn age(&self) -> lua_gc::GcAge {
317 match self {
318 FinalizerObject::Table(t) => t.0.age(),
319 FinalizerObject::UserData(u) => u.0.age(),
320 }
321 }
322
323 pub fn is_finalized(&self) -> bool {
324 match self {
325 FinalizerObject::Table(t) => t.0.is_finalized(),
326 FinalizerObject::UserData(u) => u.0.is_finalized(),
327 }
328 }
329
330 pub fn set_finalized(&self, finalized: bool) {
331 match self {
332 FinalizerObject::Table(t) => t.0.set_finalized(finalized),
333 FinalizerObject::UserData(u) => u.0.set_finalized(finalized),
334 }
335 }
336}
337
338impl lua_gc::FinalizerEntry for FinalizerObject {
339 fn identity(&self) -> usize {
340 FinalizerObject::identity(self)
341 }
342
343 fn heap_ptr(&self) -> Option<std::ptr::NonNull<lua_gc::GcBox<dyn lua_gc::Trace>>> {
344 FinalizerObject::heap_ptr(self)
345 }
346
347 fn age(&self) -> lua_gc::GcAge {
348 FinalizerObject::age(self)
349 }
350
351 fn is_finalized(&self) -> bool {
352 FinalizerObject::is_finalized(self)
353 }
354
355 fn set_finalized(&self, finalized: bool) {
356 FinalizerObject::set_finalized(self, finalized);
357 }
358}
359
360#[derive(Clone, Debug)]
361pub struct WeakTableEntry {
362 table: lua_types::gc::GcWeak<LuaTable>,
363 kind: lua_gc::WeakListKind,
364}
365
366impl WeakTableEntry {
367 pub fn new(table: &GcRef<LuaTable>) -> Self {
368 let mode = table.weak_mode();
369 let weak_keys = (mode & (1 << 0)) != 0;
370 let weak_values = (mode & (1 << 1)) != 0;
371 let kind = match (weak_keys, weak_values) {
372 (true, true) => lua_gc::WeakListKind::AllWeak,
373 (true, false) => lua_gc::WeakListKind::Ephemeron,
374 (false, true) => lua_gc::WeakListKind::WeakValues,
375 (false, false) => lua_gc::WeakListKind::WeakValues,
376 };
377 Self {
378 table: table.downgrade(),
379 kind,
380 }
381 }
382}
383
384impl lua_gc::WeakEntry for WeakTableEntry {
385 type Strong = GcRef<LuaTable>;
386
387 fn identity(&self) -> usize {
388 self.table.identity()
389 }
390
391 fn list_kind(&self) -> lua_gc::WeakListKind {
392 self.kind
393 }
394
395 fn upgrade(&self) -> Option<Self::Strong> {
396 self.table.upgrade()
397 }
398}
399
400pub(crate) const EXTRA_STACK: usize = 5;
403
404pub(crate) const LUA_MINSTACK: usize = 20;
405
406pub(crate) const BASIC_STACK_SIZE: usize = 2 * LUA_MINSTACK;
407
408pub(crate) const LUAI_MAXCCALLS: u32 = 200;
428
429pub(crate) const CIST_C: u16 = 1 << 1;
430
431pub(crate) const CIST_OAH: u16 = 1 << 0;
432pub(crate) const CIST_FRESH: u16 = 1 << 2;
433pub(crate) const CIST_HOOKED: u16 = 1 << 3;
434pub(crate) const CIST_YPCALL: u16 = 1 << 4;
435pub(crate) const CIST_TAIL: u16 = 1 << 5;
436pub(crate) const CIST_HOOKYIELD: u16 = 1 << 6;
437pub(crate) const CIST_FIN: u16 = 1 << 7;
438pub(crate) const CIST_TRAN: u16 = 1 << 8;
439pub(crate) const CIST_RECST: u32 = 10;
440pub(crate) const CIST_LEQ: u16 = 1 << 13;
446
447pub(crate) const CIST_TRAP: u16 = 1 << 14;
455
456const LUA_NUMTYPES: usize = 9;
457
458const GCSTPUSR: u8 = 1;
459const GCSTPGC: u8 = 2;
460
461const GCS_PAUSE: u8 = 0;
462
463const LUAI_GCPAUSE: u32 = 200;
464const LUAI_GCMUL: u32 = 100;
465const LUAI_GCSTEPSIZE: u8 = 13;
466const LUAI_GENMAJORMUL: u32 = 100;
467const LUAI_GENMINORMUL: u8 = 20;
468
469const WHITE0BIT: u8 = 0;
470
471const STRCACHE_N: usize = 53;
472const STRCACHE_M: usize = 2;
473
474const LUA_RIDX_MAINTHREAD: i64 = 1;
478
479const LUA_RIDX_GLOBALS: i64 = 2;
482
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487pub enum GcKind {
488 Incremental = 0,
489 Generational = 1,
490}
491
492#[derive(Debug, Clone, Copy, PartialEq, Eq)]
500pub enum WarnMode {
501 Off,
502 On,
503 Cont,
504}
505
506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
508pub enum TestWarnMode {
509 Normal,
510 Allow,
511 Store,
512}
513
514pub use lua_types::status::LuaStatus;
519
520#[derive(Clone)]
532pub struct StackValue {
533 pub val: LuaValue,
534}
535
536impl Default for StackValue {
537 fn default() -> Self {
538 StackValue {
539 val: LuaValue::Nil,
540 }
541 }
542}
543
544#[derive(Clone)]
551pub struct CallInfo {
552 pub func: StackIdx,
553
554 pub top: StackIdx,
555
556 pub previous: Option<CallInfoIdx>,
557
558 pub next: Option<CallInfoIdx>,
559
560 pub u: CallInfoFrame,
561
562 pub u2: CallInfoExtra,
563
564 pub nresults: i16,
565
566 pub callstatus: u16,
568
569 pub call_metamethods: u8,
573
574 pub tailcalls: u16,
583}
584
585#[cfg(target_pointer_width = "64")]
594const _: () = {
595 assert!(core::mem::size_of::<CallInfoFrame>() == 32);
596 assert!(core::mem::size_of::<CallInfo>() == 72);
597};
598
599#[derive(Clone, Copy)]
616pub struct CallInfoFrame {
617 pub savedpc: u32,
619 pub nextraargs: i32,
621 pub k: Option<LuaKFunction>,
623 pub old_errfunc: isize,
625 pub ctx: isize,
627}
628
629pub type LuaKFunction = fn(&mut LuaState, status: i32, ctx: isize) -> Result<usize, LuaError>;
631
632#[derive(Default, Clone, Copy)]
634pub struct CallInfoExtra {
635 pub value: i32,
636 pub ftransfer: u16,
637 pub ntransfer: u16,
638}
639
640impl CallInfoFrame {
641 pub fn c_default() -> Self {
645 CallInfoFrame {
646 savedpc: 0,
647 nextraargs: 0,
648 k: None,
649 old_errfunc: 0,
650 ctx: 0,
651 }
652 }
653
654 pub fn lua_default() -> Self {
661 CallInfoFrame {
662 savedpc: 0,
663 nextraargs: 0,
664 k: None,
665 old_errfunc: 0,
666 ctx: 0,
667 }
668 }
669}
670
671impl Default for CallInfo {
672 fn default() -> Self {
673 CallInfo {
674 func: StackIdx(0),
675 top: StackIdx(0),
676 previous: None,
677 next: None,
678 u: CallInfoFrame::c_default(),
679 u2: CallInfoExtra::default(),
680 nresults: 0,
681 callstatus: 0,
682 call_metamethods: 0,
683 tailcalls: 0,
684 }
685 }
686}
687
688impl CallInfo {
689 pub fn is_lua(&self) -> bool {
690 (self.callstatus & CIST_C) == 0
691 }
692 pub fn is_lua_code(&self) -> bool {
693 self.is_lua()
694 }
695 pub fn is_vararg_func(&self) -> bool {
700 false
701 }
702 pub fn saved_pc(&self) -> u32 {
707 debug_assert!(self.is_lua(), "saved_pc on a C frame");
708 self.u.savedpc
709 }
710 pub fn set_saved_pc(&mut self, pc: u32) {
712 debug_assert!(self.is_lua(), "set_saved_pc on a C frame");
713 self.u.savedpc = pc;
714 }
715 pub fn nextra_args(&self) -> i32 {
717 debug_assert!(self.is_lua(), "nextra_args on a C frame");
718 self.u.nextraargs
719 }
720 pub fn set_nextra_args(&mut self, n: i32) {
722 debug_assert!(self.is_lua(), "set_nextra_args on a C frame");
723 self.u.nextraargs = n;
724 }
725 pub fn transfer_ftransfer(&self) -> u16 {
726 self.u2.ftransfer
727 }
728 pub fn transfer_ntransfer(&self) -> u16 {
729 self.u2.ntransfer
730 }
731 pub fn set_trap(&mut self, t: bool) {
739 debug_assert!(self.is_lua(), "set_trap on a C frame");
740 if t {
741 self.callstatus |= CIST_TRAP;
742 } else {
743 self.callstatus &= !CIST_TRAP;
744 }
745 }
746 #[inline(always)]
750 pub fn trap(&self) -> bool {
751 (self.callstatus & CIST_TRAP) != 0
752 }
753 pub fn recover_status(&self) -> i32 {
756 ((self.callstatus >> CIST_RECST) & 7) as i32
757 }
758 pub fn set_recover_status<T: Into<i32>>(&mut self, status: T) {
761 let st = (status.into() & 7) as u16;
762 self.callstatus = (self.callstatus & !(7u16 << CIST_RECST)) | (st << CIST_RECST);
763 }
764 pub fn get_oah(&self) -> bool {
765 (self.callstatus & CIST_OAH) != 0
766 }
767 pub fn set_oah(&mut self, allow: bool) {
770 self.callstatus = (self.callstatus & !CIST_OAH) | (if allow { CIST_OAH } else { 0 });
771 }
772 pub fn u_c_old_errfunc(&self) -> isize {
777 debug_assert!(!self.is_lua(), "u_c_old_errfunc on a Lua frame");
778 self.u.old_errfunc
779 }
780 pub fn u_c_ctx(&self) -> isize {
782 debug_assert!(!self.is_lua(), "u_c_ctx on a Lua frame");
783 self.u.ctx
784 }
785 pub fn u_c_k(&self) -> Option<LuaKFunction> {
787 debug_assert!(!self.is_lua(), "u_c_k on a Lua frame");
788 self.u.k
789 }
790 pub fn set_u_c_k(&mut self, k: Option<LuaKFunction>) {
796 debug_assert!(!self.is_lua(), "set_u_c_k on a Lua frame");
797 self.u.k = k;
798 }
799 pub fn set_u_c_ctx(&mut self, ctx: isize) {
801 debug_assert!(!self.is_lua(), "set_u_c_ctx on a Lua frame");
802 self.u.ctx = ctx;
803 }
804 pub fn set_u_c_old_errfunc(&mut self, old_errfunc: isize) {
806 debug_assert!(!self.is_lua(), "set_u_c_old_errfunc on a Lua frame");
807 self.u.old_errfunc = old_errfunc;
808 }
809 pub fn set_u2_funcidx(&mut self, idx: i32) {
812 self.u2.value = idx;
813 }
814}
815
816pub trait LuaValueExt {
821 fn base_type(&self) -> lua_types::LuaType;
822 fn to_number_no_strconv(&self) -> Option<f64>;
823 fn to_number_with_strconv(&self) -> Option<f64>;
824 fn to_integer_no_strconv(&self) -> Option<i64>;
825 fn to_integer_with_strconv(&self) -> Option<i64>;
826 fn full_type_tag(&self) -> u8;
827}
828
829impl LuaValueExt for LuaValue {
830 fn base_type(&self) -> lua_types::LuaType {
831 self.type_tag()
832 }
833 fn to_number_no_strconv(&self) -> Option<f64> {
834 match self {
835 LuaValue::Float(f) => Some(*f),
836 LuaValue::Int(i) => Some(*i as f64),
837 _ => None,
838 }
839 }
840 fn to_number_with_strconv(&self) -> Option<f64> {
841 if let Some(n) = self.to_number_no_strconv() {
842 return Some(n);
843 }
844 if let LuaValue::Str(s) = self {
845 let mut tmp = LuaValue::Nil;
846 let sz = crate::object::str2num(s.as_bytes(), &mut tmp);
847 if sz == 0 {
848 return None;
849 }
850 return match tmp {
851 LuaValue::Int(i) => Some(i as f64),
852 LuaValue::Float(f) => Some(f),
853 _ => None,
854 };
855 }
856 None
857 }
858 fn to_integer_no_strconv(&self) -> Option<i64> {
859 match self {
860 LuaValue::Int(i) => Some(*i),
861 LuaValue::Float(f) if f.fract() == 0.0 && f.is_finite() => {
862 let min_f = i64::MIN as f64;
866 let max_plus1_f = -(i64::MIN as f64);
867 if *f >= min_f && *f < max_plus1_f {
868 Some(*f as i64)
869 } else {
870 None
871 }
872 }
873 _ => None,
874 }
875 }
876 fn to_integer_with_strconv(&self) -> Option<i64> {
877 if let Some(i) = self.to_integer_no_strconv() {
878 return Some(i);
879 }
880 if let LuaValue::Str(s) = self {
881 let mut tmp = LuaValue::Nil;
882 let sz = crate::object::str2num(s.as_bytes(), &mut tmp);
883 if sz == 0 {
884 return None;
885 }
886 return tmp.to_integer_no_strconv();
887 }
888 None
889 }
890 fn full_type_tag(&self) -> u8 {
891 match self {
892 LuaValue::Nil => 0x00,
893 LuaValue::Bool(false) => 0x01,
894 LuaValue::Bool(true) => 0x11,
895 LuaValue::Int(_) => 0x03,
896 LuaValue::Float(_) => 0x13,
897 LuaValue::Str(s) if s.is_short() => 0x04,
898 LuaValue::Str(_) => 0x14,
899 LuaValue::LightUserData(_) => 0x02,
900 LuaValue::Table(_) => 0x05,
901 LuaValue::Function(LuaClosure::Lua(_)) => 0x06,
902 LuaValue::Function(LuaClosure::LightC(_)) => 0x16,
903 LuaValue::Function(LuaClosure::C(_)) => 0x26,
904 LuaValue::UserData(_) => 0x07,
905 LuaValue::Thread(_) => 0x08,
906 }
907 }
908}
909
910pub trait LuaTypeExt {
912 fn type_name(&self) -> &'static [u8];
913}
914
915impl LuaTypeExt for lua_types::LuaType {
916 fn type_name(&self) -> &'static [u8] {
917 use lua_types::LuaType::*;
918 match self {
919 None => b"no value",
920 Nil => b"nil",
921 Boolean => b"boolean",
922 LightUserData => b"userdata",
923 Number => b"number",
924 String => b"string",
925 Table => b"table",
926 Function => b"function",
927 UserData => b"userdata",
928 Thread => b"thread",
929 }
930 }
931}
932
933pub trait StackIdxExt {
937 fn saturating_sub(self, n: impl Into<StackIdxConv>) -> u32;
938 fn wrapping_sub(self, n: impl Into<StackIdxConv>) -> u32;
939 fn raw(self) -> u32;
940}
941impl StackIdxExt for StackIdx {
942 #[inline(always)]
943 fn saturating_sub(self, n: impl Into<StackIdxConv>) -> u32 {
944 self.0.saturating_sub(n.into().0 .0)
945 }
946 #[inline(always)]
947 fn wrapping_sub(self, n: impl Into<StackIdxConv>) -> u32 {
948 self.0.wrapping_sub(n.into().0 .0)
949 }
950 #[inline(always)]
951 fn raw(self) -> u32 {
952 self.0
953 }
954}
955
956pub trait LuaTableRefExt {
963 fn metatable(&self) -> Option<GcRef<LuaTable>>;
964 fn has_metatable(&self) -> bool;
965 fn as_ptr(&self) -> *const ();
966 fn get(&self, _k: &LuaValue) -> LuaValue;
967 fn get_int(&self, _k: i64) -> LuaValue;
968 fn get_short_str(&self, _k: &GcRef<LuaString>) -> LuaValue;
969 fn raw_set(&self, _state: &mut LuaState, _k: LuaValue, _v: LuaValue) -> Result<(), LuaError>;
970 fn raw_set_int(&self, _state: &mut LuaState, _k: i64, _v: LuaValue) -> Result<(), LuaError>;
971 fn raw_set_short_str(
972 &self,
973 _state: &mut LuaState,
974 _k: GcRef<LuaString>,
975 _v: LuaValue,
976 ) -> Result<(), LuaError>;
977 fn invalidate_tm_cache(&self);
978 fn resize(&self, _state: &mut LuaState, _na: usize, _nh: usize) -> Result<(), LuaError>;
979 fn next(&self, _k: LuaValue) -> Result<Option<(LuaValue, LuaValue)>, LuaError>;
980}
981impl LuaTableRefExt for GcRef<LuaTable> {
982 #[inline]
983 fn metatable(&self) -> Option<GcRef<LuaTable>> {
984 (**self).metatable()
985 }
986 #[inline]
987 fn has_metatable(&self) -> bool {
988 (**self).has_metatable()
989 }
990 #[inline]
991 fn as_ptr(&self) -> *const () {
992 GcRef::identity(self) as *const ()
993 }
994 #[inline]
995 fn get(&self, k: &LuaValue) -> LuaValue {
996 (**self).get(k)
997 }
998 #[inline]
999 fn get_int(&self, k: i64) -> LuaValue {
1000 (**self).get_int(k)
1001 }
1002 #[inline]
1003 fn get_short_str(&self, k: &GcRef<LuaString>) -> LuaValue {
1004 (**self).get_short_str(k)
1005 }
1006 #[inline(always)]
1015 fn raw_set(&self, state: &mut LuaState, k: LuaValue, v: LuaValue) -> Result<(), LuaError> {
1016 match k {
1017 LuaValue::Int(i) => return self.raw_set_int(state, i, v),
1018 LuaValue::Str(s) if s.is_short() => return self.raw_set_short_str(state, s, v),
1019 k => {
1020 if k.is_collectable() {
1021 state.gc_table_barrier_back(self, &k);
1022 }
1023 let before = (**self).buffer_bytes();
1024 let result = (**self).try_raw_set(k, v);
1025 if result.is_ok() {
1026 account_table_buffer_delta(self, before);
1027 }
1028 result
1029 }
1030 }
1031 }
1032 #[inline(always)]
1033 fn raw_set_int(&self, _state: &mut LuaState, k: i64, v: LuaValue) -> Result<(), LuaError> {
1034 match (**self).try_update_int(k, v) {
1035 Ok(()) => Ok(()),
1036 Err(v) => {
1037 let before = (**self).buffer_bytes();
1038 let result = (**self).try_raw_set_int(k, v);
1039 if result.is_ok() {
1040 account_table_buffer_delta(self, before);
1041 }
1042 result
1043 }
1044 }
1045 }
1046 #[inline(always)]
1050 fn raw_set_short_str(
1051 &self,
1052 state: &mut LuaState,
1053 k: GcRef<LuaString>,
1054 v: LuaValue,
1055 ) -> Result<(), LuaError> {
1056 match (**self).try_update_short_str(&k, v) {
1057 Ok(()) => Ok(()),
1058 Err(v) => {
1059 state.gc_table_barrier_back(self, &LuaValue::Str(k));
1060 let before = (**self).buffer_bytes();
1061 let result = (**self).try_raw_set(LuaValue::Str(k), v);
1062 if result.is_ok() {
1063 account_table_buffer_delta(self, before);
1064 }
1065 result
1066 }
1067 }
1068 }
1069 fn invalidate_tm_cache(&self) {}
1070 fn resize(&self, _state: &mut LuaState, na: usize, nh: usize) -> Result<(), LuaError> {
1071 let before = (**self).buffer_bytes();
1072 let na32 = na.min(u32::MAX as usize) as u32;
1073 let nh32 = nh.min(u32::MAX as usize) as u32;
1074 let result = (**self).resize(na32, nh32);
1075 if result.is_ok() {
1076 account_table_buffer_delta(self, before);
1077 }
1078 result
1079 }
1080 fn next(&self, k: LuaValue) -> Result<Option<(LuaValue, LuaValue)>, LuaError> {
1081 (**self).try_next_pair(&k)
1082 }
1083}
1084
1085#[inline]
1086fn account_table_buffer_delta(t: &GcRef<LuaTable>, before: usize) {
1087 let after = (**t).buffer_bytes();
1088 if after > before {
1089 t.account_buffer((after - before) as isize);
1090 } else if before > after {
1091 t.account_buffer(-((before - after) as isize));
1092 }
1093}
1094
1095pub trait LuaUserDataRefExt {
1096 fn metatable(&self) -> Option<GcRef<LuaTable>>;
1097 fn set_metatable(&self, mt: Option<GcRef<LuaTable>>);
1098 fn as_ptr(&self) -> *const ();
1099 fn len(&self) -> usize;
1100}
1101impl LuaUserDataRefExt for GcRef<LuaUserData> {
1102 fn metatable(&self) -> Option<GcRef<LuaTable>> {
1103 (**self).metatable()
1104 }
1105 fn set_metatable(&self, mt: Option<GcRef<LuaTable>>) {
1106 (**self).set_metatable(mt);
1107 }
1108 fn as_ptr(&self) -> *const () {
1109 GcRef::identity(self) as *const ()
1110 }
1111 fn len(&self) -> usize {
1112 self.0.data.len()
1113 }
1114}
1115
1116pub trait LuaStringRefExt {
1117 fn is_white(&self) -> bool;
1118 fn hash(&self) -> u32;
1119 fn as_gc_ref(&self) -> GcRef<LuaString>;
1120}
1121impl LuaStringRefExt for GcRef<LuaString> {
1122 fn is_white(&self) -> bool {
1123 false
1124 }
1125 fn hash(&self) -> u32 {
1126 self.0.hash()
1127 }
1128 fn as_gc_ref(&self) -> GcRef<LuaString> {
1129 self.clone()
1130 }
1131}
1132
1133pub trait LuaLClosureRefExt {
1134 fn proto(&self) -> &GcRef<LuaProto>;
1135 fn nupvalues(&self) -> usize;
1136}
1137impl LuaLClosureRefExt for GcRef<lua_types::closure::LuaLClosure> {
1138 fn proto(&self) -> &GcRef<LuaProto> {
1139 &self.0.proto
1140 }
1141 fn nupvalues(&self) -> usize {
1142 self.0.upvals.len()
1143 }
1144}
1145
1146pub trait LuaClosureExt {
1148 fn nupvalues(&self) -> usize;
1149}
1150impl LuaClosureExt for LuaClosure {
1151 fn nupvalues(&self) -> usize {
1152 match self {
1153 LuaClosure::Lua(l) => l.0.upvals.len(),
1154 LuaClosure::C(c) => c.0.upvalues.borrow().len(),
1155 LuaClosure::LightC(_) => 0,
1156 }
1157 }
1158}
1159
1160pub trait LuaProtoExt {
1162 fn source_bytes(&self) -> &[u8];
1163 fn source_string(&self) -> Option<&GcRef<LuaString>>;
1164}
1165impl LuaProtoExt for LuaProto {
1166 fn source_bytes(&self) -> &[u8] {
1167 match &self.source {
1168 Some(s) => s.0.as_bytes(),
1169 None => &[],
1170 }
1171 }
1172 fn source_string(&self) -> Option<&GcRef<LuaString>> {
1173 self.source.as_ref()
1174 }
1175}
1176
1177pub trait Collectable: std::fmt::Debug {}
1181
1182impl std::fmt::Debug for LuaState {
1183 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1184 write!(f, "LuaState")
1185 }
1186}
1187impl Collectable for LuaState {}
1188
1189pub type ParserHook = fn(
1203 state: &mut LuaState,
1204 z: &mut crate::zio::ZIO,
1205 name: &[u8],
1206 firstchar: i32,
1207) -> Result<GcRef<lua_types::closure::LuaLClosure>, LuaError>;
1208
1209pub type FileLoaderHook = fn(filename: &[u8]) -> Result<Vec<u8>, LuaError>;
1217
1218pub type FileOpenHook =
1237 fn(filename: &[u8], mode: &[u8]) -> std::io::Result<Box<dyn lua_types::LuaFileHandle>>;
1238
1239pub type OutputHook = fn(bytes: &[u8]) -> std::io::Result<()>;
1247
1248pub type InputHook = fn(buf: &mut [u8]) -> std::io::Result<usize>;
1251
1252pub type EnvHook = fn(name: &[u8]) -> Option<Vec<u8>>;
1258
1259pub type UnixTimeHook = fn() -> i64;
1261
1262pub type CpuClockHook = fn() -> f64;
1270
1271pub type LocalOffsetHook = fn(timestamp: i64) -> i64;
1283
1284pub type EntropyHook = fn() -> u64;
1288
1289pub type TempNameHook = fn() -> Result<Vec<u8>, LuaError>;
1294
1295pub type PopenHook =
1306 fn(cmd: &[u8], mode: &[u8]) -> Result<Box<dyn lua_types::LuaFileHandle>, LuaError>;
1307
1308pub type FileRemoveHook = fn(filename: &[u8]) -> std::io::Result<()>;
1318
1319pub type FileRenameHook = fn(from: &[u8], to: &[u8]) -> std::io::Result<()>;
1328
1329#[derive(Clone, Copy, Debug)]
1335pub enum OsExecuteReason {
1336 Exit,
1338 Signal,
1340}
1341
1342#[derive(Debug)]
1345pub struct OsExecuteResult {
1346 pub success: bool,
1348 pub reason: OsExecuteReason,
1350 pub code: i32,
1352}
1353
1354pub type OsExecuteHook = fn(cmd: &[u8]) -> Result<OsExecuteResult, LuaError>;
1361
1362#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1369pub struct DynLibId(pub u64);
1370
1371pub enum DynamicSymbol {
1379 RustNative(LuaCFunction),
1382 LuaCAbi(*const ()),
1388 Unsupported { reason: Vec<u8> },
1391}
1392
1393pub type DynLibLoadHook =
1404 fn(state: &mut LuaState, path: &[u8], see_global: bool) -> Result<DynLibId, LuaError>;
1405
1406pub type DynLibSymbolHook =
1414 fn(state: &mut LuaState, handle: DynLibId, symbol: &[u8]) -> Result<DynamicSymbol, LuaError>;
1415
1416pub type DynLibUnloadHook = fn(handle: DynLibId);
1424
1425pub struct ThreadRegistryEntry {
1431 pub state: Rc<RefCell<LuaState>>,
1436 pub value: GcRef<lua_types::value::LuaThread>,
1439}
1440
1441#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1446pub struct ExternalRootKey {
1447 index: usize,
1448 generation: u64,
1449}
1450
1451#[derive(Debug)]
1452struct ExternalRootSlot {
1453 value: Option<LuaValue>,
1454 generation: u64,
1455}
1456
1457#[derive(Debug, Default)]
1463pub struct ExternalRootSet {
1464 slots: Vec<ExternalRootSlot>,
1465 free: Vec<usize>,
1466 live: usize,
1467}
1468
1469impl ExternalRootSet {
1470 pub fn insert(&mut self, value: LuaValue) -> ExternalRootKey {
1471 if let Some(index) = self.free.pop() {
1472 let slot = &mut self.slots[index];
1473 debug_assert!(slot.value.is_none(), "free external-root slot is occupied");
1474 slot.generation = slot.generation.wrapping_add(1).max(1);
1475 slot.value = Some(value);
1476 self.live += 1;
1477 ExternalRootKey {
1478 index,
1479 generation: slot.generation,
1480 }
1481 } else {
1482 let index = self.slots.len();
1483 self.slots.push(ExternalRootSlot {
1484 value: Some(value),
1485 generation: 1,
1486 });
1487 self.live += 1;
1488 ExternalRootKey {
1489 index,
1490 generation: 1,
1491 }
1492 }
1493 }
1494
1495 pub fn get(&self, key: ExternalRootKey) -> Option<&LuaValue> {
1496 let slot = self.slots.get(key.index)?;
1497 if slot.generation == key.generation {
1498 slot.value.as_ref()
1499 } else {
1500 None
1501 }
1502 }
1503
1504 pub fn replace(&mut self, key: ExternalRootKey, value: LuaValue) -> Option<LuaValue> {
1505 let slot = self.slots.get_mut(key.index)?;
1506 if slot.generation != key.generation || slot.value.is_none() {
1507 return None;
1508 }
1509 slot.value.replace(value)
1510 }
1511
1512 pub fn remove(&mut self, key: ExternalRootKey) -> Option<LuaValue> {
1513 let slot = self.slots.get_mut(key.index)?;
1514 if slot.generation != key.generation {
1515 return None;
1516 }
1517 let old = slot.value.take()?;
1518 self.free.push(key.index);
1519 self.live -= 1;
1520 Some(old)
1521 }
1522
1523 pub fn iter_values(&self) -> impl Iterator<Item = &LuaValue> {
1524 self.slots.iter().filter_map(|slot| slot.value.as_ref())
1525 }
1526
1527 pub fn len(&self) -> usize {
1528 self.live
1529 }
1530
1531 pub fn is_empty(&self) -> bool {
1532 self.live == 0
1533 }
1534
1535 pub fn vacant_len(&self) -> usize {
1536 self.free.len()
1537 }
1538}
1539
1540pub struct GlobalState {
1544 pub parser_hook: Option<ParserHook>,
1550
1551 pub cli_argv: Option<Vec<Vec<u8>>>,
1558
1559 pub cli_preload: Option<fn(&mut LuaState) -> Result<(), LuaError>>,
1563
1564 pub lua_version: lua_types::LuaVersion,
1571
1572 pub file_loader_hook: Option<FileLoaderHook>,
1577
1578 pub file_open_hook: Option<FileOpenHook>,
1583
1584 pub stdout_hook: Option<OutputHook>,
1588
1589 pub stderr_hook: Option<OutputHook>,
1591
1592 pub stdin_hook: Option<InputHook>,
1595
1596 pub env_hook: Option<EnvHook>,
1598
1599 pub unix_time_hook: Option<UnixTimeHook>,
1602
1603 pub cpu_clock_hook: Option<CpuClockHook>,
1606
1607 pub local_offset_hook: Option<LocalOffsetHook>,
1612
1613 pub entropy_hook: Option<EntropyHook>,
1616
1617 pub temp_name_hook: Option<TempNameHook>,
1619
1620 pub popen_hook: Option<PopenHook>,
1625
1626 pub io_streams: Option<std::rc::Rc<dyn std::any::Any>>,
1636
1637 pub file_remove_hook: Option<FileRemoveHook>,
1640
1641 pub file_rename_hook: Option<FileRenameHook>,
1644
1645 pub os_execute_hook: Option<OsExecuteHook>,
1649
1650 pub dynlib_load_hook: Option<DynLibLoadHook>,
1655
1656 pub dynlib_symbol_hook: Option<DynLibSymbolHook>,
1660
1661 pub dynlib_unload_hook: Option<DynLibUnloadHook>,
1665
1666 pub sandbox: SandboxLimits,
1669
1670 pub gc_debt: isize,
1671
1672 pub gc_estimate: usize,
1673
1674 pub lastatomic: usize,
1675
1676 pub l_registry: LuaValue,
1677
1678 pub external_roots: ExternalRootSet,
1681
1682 pub globals: LuaValue,
1688 pub loaded: LuaValue,
1689
1690 pub nilvalue: LuaValue,
1693
1694 pub seed: u32,
1695
1696 pub currentwhite: u8,
1697
1698 pub gcstate: u8,
1699
1700 pub gckind: u8,
1701
1702 pub gcstopem: bool,
1703
1704 pub genminormul: u8,
1705
1706 pub genmajormul: u8,
1707
1708 pub gcstp: u8,
1709
1710 pub gcemergency: bool,
1711
1712 pub gcpause: u8,
1713
1714 pub gcstepmul: u8,
1715
1716 pub gcstepsize: u8,
1717
1718 pub gc55_params: [i64; 6],
1727
1728 pub sweepgc_cursor: usize,
1731
1732 pub weak_tables_registry: lua_gc::WeakRegistry<WeakTableEntry>,
1741
1742 pub finalizers: lua_gc::FinalizerRegistry<FinalizerObject>,
1745
1746 pub gc_finalizer_error: Option<LuaValue>,
1757
1758 pub twups: Vec<GcRef<LuaState>>,
1759
1760 pub panic: Option<LuaCFunction>,
1761
1762 pub mainthread: Option<GcRef<LuaState>>,
1766
1767 pub threads: std::collections::HashMap<u64, ThreadRegistryEntry>,
1779
1780 pub main_thread_value: GcRef<lua_types::value::LuaThread>,
1785
1786 pub current_thread_id: u64,
1790
1791 pub closing_thread_id: Option<u64>,
1794
1795 pub main_thread_id: u64,
1798
1799 pub next_thread_id: u64,
1802
1803 pub thread_globals: std::collections::HashMap<u64, LuaValue>,
1820
1821 pub closure_envs: std::collections::HashMap<usize, LuaValue>,
1833
1834 pub memerrmsg: GcRef<LuaString>,
1835
1836 pub tmname: Vec<GcRef<LuaString>>,
1837
1838 pub mt: [Option<GcRef<LuaTable>>; LUA_NUMTYPES],
1839
1840 pub strcache: [[GcRef<LuaString>; STRCACHE_M]; STRCACHE_N],
1841
1842 pub interned_lt: InternedStringMap,
1847
1848 pub warnf: Option<Box<dyn FnMut(&[u8], bool)>>,
1849
1850 pub warn_mode: WarnMode,
1855
1856 pub test_warn_enabled: bool,
1861 pub test_warn_on: bool,
1862 pub test_warn_mode: TestWarnMode,
1863 pub test_warn_last_to_cont: bool,
1864 pub test_warn_buffer: Vec<u8>,
1865
1866 pub c_functions: Vec<LuaCallable>,
1871
1872 pub heap: std::rc::Rc<lua_gc::Heap>,
1876
1877 pub cross_thread_upvals: std::collections::HashMap<(u64, StackIdx), LuaValue>,
1891
1892 pub suspended_parent_stacks: Vec<Vec<LuaValue>>,
1906
1907 pub suspended_parent_open_upvals: Vec<Vec<GcRef<UpVal>>>,
1913
1914 pub snapshot_stack_pool: Vec<Vec<LuaValue>>,
1922 pub snapshot_upval_pool: Vec<Vec<GcRef<UpVal>>>,
1923
1924 pub resume_value_pool: Vec<Vec<LuaValue>>,
1932
1933 pub resume_upval_slot_pool: Vec<Vec<(u64, StackIdx)>>,
1939
1940 pub resume_flush_pool: Vec<Vec<(StackIdx, LuaValue)>>,
1944}
1945
1946const SANDBOX_COUNT_MASK: u8 = 1 << 3;
1949
1950pub const SANDBOX_TRIP_NONE: u8 = 0;
1952pub const SANDBOX_TRIP_INSTRUCTIONS: u8 = 1;
1954pub const SANDBOX_TRIP_MEMORY: u8 = 2;
1956
1957#[derive(Default)]
1964pub struct SandboxLimits {
1965 pub interval: std::cell::Cell<i32>,
1967 pub instr_limited: std::cell::Cell<bool>,
1969 pub instr_remaining: std::cell::Cell<u64>,
1971 pub instr_limit: std::cell::Cell<u64>,
1973 pub mem_limit: std::cell::Cell<Option<usize>>,
1975 pub tripped: std::cell::Cell<u8>,
1977 pub aborting: std::cell::Cell<bool>,
1982}
1983
1984impl GlobalState {
1985 pub fn sandbox_active(&self) -> bool {
1987 self.sandbox.interval.get() != 0
1988 }
1989
1990 pub fn total_bytes(&self) -> usize {
1993 self.heap.bytes_used().max(1)
1994 }
1995
1996 pub fn get_thread(&self, id: u64) -> Option<&ThreadRegistryEntry> {
2001 self.threads.get(&id)
2002 }
2003
2004 pub fn thread_value_for(&self, id: u64) -> Option<GcRef<lua_types::value::LuaThread>> {
2008 if id == self.main_thread_id {
2009 Some(self.main_thread_value.clone())
2010 } else {
2011 self.threads.get(&id).map(|e| e.value.clone())
2012 }
2013 }
2014
2015 pub fn is_complete(&self) -> bool {
2018 matches!(self.nilvalue, LuaValue::Nil)
2019 }
2020
2021 pub fn current_white(&self) -> u8 {
2027 self.currentwhite
2028 }
2029
2030 pub fn other_white(&self) -> u8 {
2032 self.currentwhite ^ 0x03
2033 }
2034
2035 pub fn is_gen_mode(&self) -> bool {
2037 self.gckind == GcKind::Generational as u8 || self.lastatomic != 0
2038 }
2039
2040 pub fn gc_running(&self) -> bool {
2042 self.gcstp == 0
2043 }
2044
2045 pub fn keep_invariant(&self) -> bool {
2047 self.heap.gc_state().is_invariant()
2048 }
2049
2050 pub fn is_sweep_phase(&self) -> bool {
2052 self.heap.gc_state().is_sweep()
2053 }
2054
2055 pub fn gc_debt(&self) -> isize {
2057 self.gc_debt
2058 }
2059 pub fn set_gc_debt(&mut self, d: isize) {
2060 self.gc_debt = d;
2061 }
2062 pub fn gc_at_pause(&self) -> bool {
2063 self.heap.gc_state().is_pause()
2064 }
2065 fn get_gc_param(p: u8) -> i32 {
2066 (p as i32) * 4
2067 }
2068 fn set_gc_param_slot(slot: &mut u8, p: i32) {
2069 *slot = (p / 4) as u8;
2070 }
2071 pub fn gc_pause_param(&self) -> i32 {
2072 Self::get_gc_param(self.gcpause)
2073 }
2074 pub fn set_gc_pause_param(&mut self, p: i32) {
2075 Self::set_gc_param_slot(&mut self.gcpause, p);
2076 }
2077 pub fn gc_stepmul_param(&self) -> i32 {
2078 Self::get_gc_param(self.gcstepmul)
2079 }
2080 pub fn set_gc_stepmul_param(&mut self, p: i32) {
2081 Self::set_gc_param_slot(&mut self.gcstepmul, p);
2082 }
2083 pub fn gc_genmajormul_param(&self) -> i32 {
2084 Self::get_gc_param(self.genmajormul)
2085 }
2086 pub fn set_gc_genmajormul(&mut self, p: i32) {
2087 Self::set_gc_param_slot(&mut self.genmajormul, p);
2088 }
2089 pub fn gc55_param(&mut self, idx: usize, value: i64) -> i64 {
2093 let old = self.gc55_params[idx];
2094 if value >= 0 {
2095 self.gc55_params[idx] = value;
2096 }
2097 old
2098 }
2099 pub fn gc_stop_flags(&self) -> u8 {
2100 self.gcstp
2101 }
2102 pub fn set_gc_stop_flags(&mut self, f: u8) {
2103 self.gcstp = f;
2104 }
2105 pub fn stop_gc_internal(&mut self) -> u8 {
2106 let old = self.gcstp;
2107 self.gcstp |= GCSTPGC;
2108 old
2109 }
2110 pub fn set_gc_stop_user(&mut self) {
2111 self.gcstp = GCSTPUSR;
2113 }
2114 pub fn clear_gc_stop(&mut self) {
2115 self.gcstp = 0;
2116 }
2117 pub fn is_gc_running(&self) -> bool {
2118 self.gcstp == 0
2119 }
2120 pub fn is_gc_stopped_internally(&self) -> bool {
2125 (self.gcstp & GCSTPGC) != 0
2126 }
2127
2128 pub fn tm_name<T: TmIndex>(&self, tm: T) -> Option<GcRef<LuaString>> {
2136 self.tmname.get(tm.tm_index()).cloned()
2137 }
2138}
2139
2140pub trait TmIndex: Copy {
2146 fn tm_index(self) -> usize;
2147}
2148impl TmIndex for lua_types::tagmethod::TagMethod {
2149 fn tm_index(self) -> usize {
2150 self as u8 as usize
2151 }
2152}
2153impl TmIndex for crate::tagmethods::TagMethod {
2154 fn tm_index(self) -> usize {
2155 self as u8 as usize
2156 }
2157}
2158impl TmIndex for usize {
2159 fn tm_index(self) -> usize {
2160 self
2161 }
2162}
2163impl TmIndex for u8 {
2164 fn tm_index(self) -> usize {
2165 self as usize
2166 }
2167}
2168
2169use lua_types::tagmethod::TagMethod;
2170
2171pub struct LuaState {
2189 pub status: u8,
2192
2193 pub allowhook: bool,
2194
2195 pub nci: u32,
2196
2197 pub top: StackIdx,
2200
2201 pub stack_last: StackIdx,
2204
2205 pub stack: Vec<StackValue>,
2206
2207 pub ci: CallInfoIdx,
2210
2211 pub call_info: Vec<CallInfo>,
2213
2214 pub openupval: Vec<GcRef<UpVal>>,
2217
2218 pub legacy_open_upval_touched: std::cell::Cell<bool>,
2230
2231 pub tbclist: Vec<StackIdx>,
2232
2233 pub(crate) global: Rc<RefCell<GlobalState>>,
2239
2240 pub hook: Option<Box<dyn FnMut(&mut LuaState, &crate::debug::LuaDebug)>>,
2243
2244 pub hookmask: u8,
2245
2246 pub basehookcount: i32,
2247
2248 pub hookcount: i32,
2249
2250 pub errfunc: isize,
2256
2257 pub n_ccalls: u32,
2260
2261 pub oldpc: u32,
2264
2265 pub marked: u8,
2268
2269 pub cached_thread_id: u64,
2285
2286 pub gc_check_needed: bool,
2291}
2292
2293impl LuaState {
2294 pub fn global(&self) -> std::cell::Ref<'_, GlobalState> {
2300 self.global.borrow()
2301 }
2302
2303 pub fn global_mut(&self) -> std::cell::RefMut<'_, GlobalState> {
2305 self.global.borrow_mut()
2306 }
2307
2308 pub fn global_rc(&self) -> Rc<RefCell<GlobalState>> {
2312 Rc::clone(&self.global)
2313 }
2314
2315 pub fn v51_thread_lgt(&self, id: u64) -> LuaValue {
2324 let g = self.global();
2325 if id == g.main_thread_id {
2326 g.globals.clone()
2327 } else {
2328 g.thread_globals
2329 .get(&id)
2330 .expect("v51 coroutine l_gt must be seeded in new_thread")
2331 .clone()
2332 }
2333 }
2334
2335 pub fn v51_set_thread_lgt(&self, id: u64, t: LuaValue) {
2340 let mut g = self.global_mut();
2341 if id == g.main_thread_id {
2342 g.globals = t;
2343 } else {
2344 g.thread_globals.insert(id, t);
2345 }
2346 }
2347
2348 pub fn enable_test_warning_handler(&mut self) -> Result<(), LuaError> {
2350 {
2351 let mut g = self.global_mut();
2352 g.test_warn_enabled = true;
2353 g.test_warn_on = false;
2354 g.test_warn_mode = TestWarnMode::Normal;
2355 g.test_warn_last_to_cont = false;
2356 g.test_warn_buffer.clear();
2357 }
2358 self.push(LuaValue::Bool(false));
2359 crate::api::set_global(self, b"_WARN")
2360 }
2361
2362 pub fn c_calls(&self) -> u32 {
2364 self.n_ccalls & 0xffff
2365 }
2366
2367 pub fn inc_nny(&mut self) {
2369 self.n_ccalls += 0x10000;
2370 }
2371
2372 pub fn dec_nny(&mut self) {
2374 self.n_ccalls -= 0x10000;
2375 }
2376
2377 pub fn is_yieldable(&self) -> bool {
2379 (self.n_ccalls & 0xffff0000) == 0
2380 }
2381
2382 pub fn reset_hook_count(&mut self) {
2384 self.hookcount = self.basehookcount;
2385 }
2386
2387 pub fn install_sandbox_limits(
2396 &mut self,
2397 interval: i32,
2398 instr_limit: Option<u64>,
2399 mem_limit: Option<usize>,
2400 ) {
2401 let interval = interval.max(1);
2402 {
2403 let g = self.global();
2404 g.sandbox.interval.set(interval);
2405 g.sandbox.instr_limited.set(instr_limit.is_some());
2406 g.sandbox.instr_remaining.set(instr_limit.unwrap_or(0));
2407 g.sandbox.instr_limit.set(instr_limit.unwrap_or(0));
2408 g.sandbox.mem_limit.set(mem_limit);
2409 g.sandbox.tripped.set(SANDBOX_TRIP_NONE);
2410 }
2411 self.hookmask |= SANDBOX_COUNT_MASK;
2412 self.basehookcount = interval;
2413 self.hookcount = interval;
2414 crate::debug::arm_traps(self);
2415 }
2416
2417 pub fn sandbox_charge_interval(&self) -> Option<LuaError> {
2422 let interval = self.global().sandbox.interval.get();
2423 self.sandbox_charge(interval as u64)
2424 }
2425
2426 pub fn sandbox_charge(&self, amount: u64) -> Option<LuaError> {
2435 let g = self.global();
2436 if g.sandbox.interval.get() == 0 {
2437 return None;
2438 }
2439 if g.sandbox.instr_limited.get() {
2440 let rem = g.sandbox.instr_remaining.get().saturating_sub(amount);
2441 g.sandbox.instr_remaining.set(rem);
2442 if rem == 0 {
2443 g.sandbox.tripped.set(SANDBOX_TRIP_INSTRUCTIONS);
2444 g.sandbox.aborting.set(true);
2445 return Some(LuaError::runtime(format_args!(
2446 "sandbox: instruction budget exhausted"
2447 )));
2448 }
2449 }
2450 if let Some(limit) = g.sandbox.mem_limit.get() {
2451 if g.total_bytes() > limit {
2452 g.sandbox.tripped.set(SANDBOX_TRIP_MEMORY);
2453 g.sandbox.aborting.set(true);
2454 return Some(LuaError::runtime(format_args!(
2455 "sandbox: memory limit exceeded"
2456 )));
2457 }
2458 }
2459 None
2460 }
2461
2462 pub fn sandbox_reserve(&self, additional: usize) -> Option<LuaError> {
2470 let g = self.global();
2471 if g.sandbox.interval.get() == 0 {
2472 return None;
2473 }
2474 if let Some(limit) = g.sandbox.mem_limit.get() {
2475 let projected = g.total_bytes().saturating_add(additional);
2476 if projected > limit {
2477 g.sandbox.tripped.set(SANDBOX_TRIP_MEMORY);
2478 g.sandbox.aborting.set(true);
2479 return Some(LuaError::runtime(format_args!(
2480 "sandbox: memory limit exceeded"
2481 )));
2482 }
2483 }
2484 None
2485 }
2486
2487 pub fn sandbox_match_step_limit(&self) -> u64 {
2492 let g = self.global();
2493 if g.sandbox.interval.get() != 0 && g.sandbox.instr_limited.get() {
2494 g.sandbox.instr_remaining.get()
2495 } else {
2496 0
2497 }
2498 }
2499
2500 pub fn sandbox_aborting(&self) -> bool {
2504 self.global().sandbox.aborting.get()
2505 }
2506
2507 pub fn sandbox_instr_limited(&self) -> bool {
2509 self.global().sandbox.instr_limited.get()
2510 }
2511
2512 pub fn sandbox_instr_remaining(&self) -> u64 {
2515 self.global().sandbox.instr_remaining.get()
2516 }
2517
2518 pub fn sandbox_instr_limit(&self) -> u64 {
2520 self.global().sandbox.instr_limit.get()
2521 }
2522
2523 pub fn sandbox_tripped_code(&self) -> u8 {
2525 self.global().sandbox.tripped.get()
2526 }
2527
2528 pub fn sandbox_reset(&self) {
2531 let g = self.global();
2532 if g.sandbox.instr_limited.get() {
2533 g.sandbox.instr_remaining.set(g.sandbox.instr_limit.get());
2534 }
2535 g.sandbox.tripped.set(SANDBOX_TRIP_NONE);
2536 g.sandbox.aborting.set(false);
2537 }
2538
2539 pub fn stack_size(&self) -> usize {
2541 self.stack_last.0 as usize
2542 }
2543
2544 #[inline(always)]
2546 pub fn push(&mut self, val: LuaValue) {
2547 let top = self.top.0 as usize;
2548 if top < self.stack.len() {
2549 self.stack[top] = StackValue { val };
2550 } else {
2551 self.stack.push(StackValue { val });
2552 }
2553 self.top = StackIdx(self.top.0 + 1);
2554 }
2555
2556 #[inline(always)]
2559 pub fn pop(&mut self) -> LuaValue {
2560 if self.top.0 == 0 {
2561 return LuaValue::Nil;
2562 }
2563 self.top = StackIdx(self.top.0 - 1);
2564 self.stack[self.top.0 as usize].val.clone()
2565 }
2566
2567 #[inline(always)]
2569 pub fn stack_val(&self, idx: StackIdx) -> &LuaValue {
2570 &self.stack[idx.0 as usize].val
2571 }
2572
2573 #[inline(always)]
2575 pub fn set_stack_val(&mut self, idx: StackIdx, val: LuaValue) {
2576 self.stack[idx.0 as usize].val = val;
2577 }
2578
2579 pub fn gc(&mut self) -> GcHandle<'_> {
2582 GcHandle { _state: self }
2583 }
2584
2585 pub fn external_root_value(&mut self, value: LuaValue) -> ExternalRootKey {
2587 self.global_mut().external_roots.insert(value)
2588 }
2589
2590 pub fn external_rooted_value(&self, key: ExternalRootKey) -> Option<LuaValue> {
2592 self.global().external_roots.get(key).cloned()
2593 }
2594
2595 pub fn external_replace_root(
2597 &mut self,
2598 key: ExternalRootKey,
2599 value: LuaValue,
2600 ) -> Option<LuaValue> {
2601 self.global_mut().external_roots.replace(key, value)
2602 }
2603
2604 pub fn external_unroot_value(&mut self, key: ExternalRootKey) -> Option<LuaValue> {
2606 self.global_mut().external_roots.remove(key)
2607 }
2608
2609 pub fn try_external_unroot_value(
2612 &mut self,
2613 key: ExternalRootKey,
2614 ) -> std::result::Result<Option<LuaValue>, std::cell::BorrowMutError> {
2615 self.global
2616 .try_borrow_mut()
2617 .map(|mut global| global.external_roots.remove(key))
2618 }
2619
2620 pub fn new_table(&mut self) -> GcRef<LuaTable> {
2622 self.mark_gc_check_needed();
2623 GcRef::new(LuaTable::placeholder())
2624 }
2625
2626 pub fn new_table_with_sizes(
2631 &mut self,
2632 array_size: u32,
2633 hash_size: u32,
2634 ) -> Result<GcRef<LuaTable>, LuaError> {
2635 self.mark_gc_check_needed();
2636 let t = GcRef::new(LuaTable::placeholder());
2637 self.table_resize(&t, array_size as usize, hash_size as usize)?;
2638 Ok(t)
2639 }
2640
2641 pub fn intern_str(&mut self, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
2655 if bytes.len() <= crate::string::MAX_SHORT_LEN {
2656 let hash = LuaString::hash_bytes(bytes, 0);
2657 {
2658 let global = self.global();
2659 if let Some(existing) = global.interned_lt.find(bytes, hash) {
2660 return Ok(existing);
2661 }
2662 }
2663 let new_ref = GcRef::new(LuaString::from_slice(bytes));
2664 new_ref.account_buffer(new_ref.buffer_bytes() as isize);
2665 self.global_mut().interned_lt.insert(new_ref.clone());
2666 self.mark_gc_check_needed();
2667 Ok(new_ref)
2668 } else {
2669 self.mark_gc_check_needed();
2670 let new_ref = GcRef::new(LuaString::from_slice(bytes));
2671 new_ref.account_buffer(new_ref.buffer_bytes() as isize);
2672 Ok(new_ref)
2673 }
2674 }
2675
2676 #[inline(always)]
2678 pub fn top_idx(&self) -> StackIdx {
2679 self.top
2680 }
2681}
2682
2683impl LuaState {
2688 #[inline(always)]
2689 pub fn get_at(&self, idx: impl Into<StackIdxConv>) -> LuaValue {
2690 let i: StackIdx = idx.into().0;
2691 match self.stack.get(i.0 as usize) {
2692 Some(slot) => slot.val.clone(),
2693 None => LuaValue::Nil,
2694 }
2695 }
2696 #[inline(always)]
2697 pub fn set_at(&mut self, idx: impl Into<StackIdxConv>, v: LuaValue) {
2698 let i: StackIdx = idx.into().0;
2699 self.stack[i.0 as usize].val = v;
2700 }
2701
2702 pub fn clear_stack_range(&mut self, start: StackIdx, end: StackIdx) {
2716 if end.0 <= start.0 {
2717 return;
2718 }
2719 let end_u = end.0 as usize;
2720 if end_u > self.stack.len() {
2721 self.stack.resize_with(end_u, StackValue::default);
2722 }
2723 for i in start.0..end.0 {
2724 self.stack[i as usize].val = LuaValue::Nil;
2725 }
2726 }
2727 #[inline(always)]
2735 pub fn get_int_at(&self, idx: impl Into<StackIdxConv>) -> Option<i64> {
2736 let i: StackIdx = idx.into().0;
2737 match self.stack.get(i.0 as usize) {
2738 Some(slot) => match &slot.val {
2739 LuaValue::Int(v) => Some(*v),
2740 _ => None,
2741 },
2742 None => None,
2743 }
2744 }
2745 #[inline(always)]
2752 pub fn get_int_pair_at(
2753 &self,
2754 rb: impl Into<StackIdxConv>,
2755 rc: impl Into<StackIdxConv>,
2756 ) -> Option<(i64, i64)> {
2757 let rb: StackIdx = rb.into().0;
2758 let rc: StackIdx = rc.into().0;
2759 match (self.stack[rb.0 as usize].val, self.stack[rc.0 as usize].val) {
2760 (LuaValue::Int(ib), LuaValue::Int(ic)) => Some((ib, ic)),
2761 _ => None,
2762 }
2763 }
2764 #[inline(always)]
2769 pub fn get_num_at(&self, idx: impl Into<StackIdxConv>) -> Option<f64> {
2770 let i: StackIdx = idx.into().0;
2771 match self.stack.get(i.0 as usize) {
2772 Some(slot) => match &slot.val {
2773 LuaValue::Float(f) => Some(*f),
2774 LuaValue::Int(v) => Some(*v as f64),
2775 _ => None,
2776 },
2777 None => None,
2778 }
2779 }
2780 #[inline(always)]
2785 pub fn get_float_at(&self, idx: impl Into<StackIdxConv>) -> Option<f64> {
2786 let i: StackIdx = idx.into().0;
2787 match self.stack.get(i.0 as usize) {
2788 Some(slot) => match &slot.val {
2789 LuaValue::Float(f) => Some(*f),
2790 _ => None,
2791 },
2792 None => None,
2793 }
2794 }
2795 #[inline(always)]
2800 pub fn get_num_pair_at(
2801 &self,
2802 rb: impl Into<StackIdxConv>,
2803 rc: impl Into<StackIdxConv>,
2804 ) -> Option<(f64, f64)> {
2805 let rb: StackIdx = rb.into().0;
2806 let rc: StackIdx = rc.into().0;
2807 match (self.stack[rb.0 as usize].val, self.stack[rc.0 as usize].val) {
2808 (LuaValue::Float(nb), LuaValue::Float(nc)) => Some((nb, nc)),
2809 (LuaValue::Int(ib), LuaValue::Int(ic)) => Some((ib as f64, ic as f64)),
2810 (LuaValue::Int(ib), LuaValue::Float(nc)) => Some((ib as f64, nc)),
2811 (LuaValue::Float(nb), LuaValue::Int(ic)) => Some((nb, ic as f64)),
2812 _ => None,
2813 }
2814 }
2815 #[inline(always)]
2828 pub fn set_top(&mut self, idx: impl Into<StackIdxConv>) {
2829 let new_top: StackIdx = idx.into().0;
2830 let new_top_u = new_top.0 as usize;
2831 if new_top_u > self.stack.len() {
2832 self.stack.resize_with(new_top_u, StackValue::default);
2833 }
2834 self.top = new_top;
2835 }
2836 #[inline(always)]
2842 pub fn set_top_idx(&mut self, idx: impl Into<StackIdxConv>) {
2843 let new_top: StackIdx = idx.into().0;
2844 self.top = new_top;
2845 }
2846 #[inline(always)]
2849 pub fn dec_top(&mut self) {
2850 if self.top.0 > 0 {
2851 self.top = StackIdx(self.top.0 - 1);
2852 }
2853 }
2854 #[inline(always)]
2855 pub fn pop_n(&mut self, n: usize) {
2856 let cur = self.top.0 as usize;
2857 let new = cur.saturating_sub(n);
2858 self.top = StackIdx(new as u32);
2859 }
2860 #[inline(always)]
2863 pub fn peek_at(&mut self, idx: impl Into<StackIdxConv>) -> LuaValue {
2864 let i: StackIdx = idx.into().0;
2865 match self.stack.get(i.0 as usize) {
2866 Some(slot) => slot.val.clone(),
2867 None => LuaValue::Nil,
2868 }
2869 }
2870 #[inline(always)]
2874 pub fn peek_top(&mut self) -> LuaValue {
2875 if self.top.0 == 0 {
2876 return LuaValue::Nil;
2877 }
2878 self.stack[(self.top.0 - 1) as usize].val.clone()
2879 }
2880 pub fn peek_string_at_top(&mut self) -> GcRef<LuaString> {
2885 match self.peek_top() {
2886 LuaValue::Str(s) => s,
2887 _ => panic!("peek_string_at_top: top of stack is not a string"),
2888 }
2889 }
2890 pub fn stack_at(&mut self, idx: impl Into<StackIdxConv>) -> &mut LuaValue {
2893 let i: StackIdx = idx.into().0;
2894 &mut self.stack[i.0 as usize].val
2895 }
2896 pub fn stack_set_nil(&mut self, idx: impl Into<StackIdxConv>) {
2899 let i: StackIdx = idx.into().0;
2900 let slot = i.0 as usize;
2901 if slot < self.stack.len() {
2902 self.stack[slot].val = LuaValue::Nil;
2903 }
2904 }
2905 pub fn stack_resize(&mut self, size: usize) -> Result<(), LuaError> {
2913 self.stack.resize_with(size, StackValue::default);
2914 Ok(())
2915 }
2916 pub fn stack_available(&mut self) -> usize {
2917 (self.stack_last.0 as usize).saturating_sub(self.top.0 as usize)
2918 }
2919 pub fn check_stack(&mut self, n: i32) -> Result<(), LuaError> {
2920 let free = (self.stack_last.0 as i32) - (self.top.0 as i32);
2921 if free <= n {
2922 self.grow_stack(n, true)?;
2923 }
2924 Ok(())
2925 }
2926 pub fn grow_stack(&mut self, n: i32, raise_error: bool) -> Result<(), LuaError> {
2935 crate::do_::grow_stack(self, n, raise_error).map(|_| ())
2936 }
2937
2938 #[inline(always)]
2939 pub fn get_ci(&self, idx: CallInfoIdx) -> &CallInfo {
2940 &self.call_info[idx.as_usize()]
2941 }
2942 #[inline(always)]
2943 pub fn get_ci_mut(&mut self, idx: CallInfoIdx) -> &mut CallInfo {
2944 &mut self.call_info[idx.as_usize()]
2945 }
2946 #[inline(always)]
2947 pub fn current_call_info(&self) -> &CallInfo {
2948 &self.call_info[self.ci.as_usize()]
2949 }
2950 #[inline(always)]
2951 pub fn current_call_info_mut(&mut self) -> &mut CallInfo {
2952 let i = self.ci.as_usize();
2953 &mut self.call_info[i]
2954 }
2955 #[inline(always)]
2956 pub fn current_ci_idx(&self) -> CallInfoIdx {
2957 self.ci
2958 }
2959 pub fn call_stack_mut(&mut self) -> &mut Vec<CallInfo> {
2960 &mut self.call_info
2961 }
2962 #[inline(always)]
2963 pub fn next_ci(&mut self) -> Result<CallInfoIdx, LuaError> {
2964 let idx = match self.call_info[self.ci.as_usize()].next {
2965 Some(idx) => idx,
2966 None => extend_ci(self),
2967 };
2968 self.call_info[idx.as_usize()].tailcalls = 0;
2969 Ok(idx)
2970 }
2971
2972 #[inline(always)]
2979 pub fn note_lua_tailcall(&mut self, ci: CallInfoIdx) {
2980 if self.global().lua_version == lua_types::LuaVersion::V51 {
2981 self.call_info[ci.as_usize()].tailcalls =
2982 self.call_info[ci.as_usize()].tailcalls.saturating_add(1);
2983 }
2984 }
2985 #[inline(always)]
2986 pub fn prev_ci(&self, idx: CallInfoIdx) -> Option<CallInfoIdx> {
2987 self.call_info[idx.as_usize()].previous
2988 }
2989 pub fn get_prev_ci(&self, idx: CallInfoIdx) -> Option<&CallInfo> {
2990 self.call_info[idx.as_usize()]
2991 .previous
2992 .map(|p| &self.call_info[p.as_usize()])
2993 }
2994 #[inline(always)]
2995 pub fn is_base_ci(&self, idx: CallInfoIdx) -> bool {
2996 idx.as_usize() == 0
2997 }
2998 #[inline(always)]
2999 pub fn is_current_ci(&self, idx: CallInfoIdx) -> bool {
3000 idx == self.ci
3001 }
3002 pub fn ci_next_func(&self, idx: CallInfoIdx) -> StackIdx {
3003 let next = self.call_info[idx.as_usize()]
3004 .next
3005 .expect("ci_next_func: no next CallInfo");
3006 self.call_info[next.as_usize()].func
3007 }
3008 #[inline(always)]
3009 pub fn ci_top(&self, idx: CallInfoIdx) -> StackIdx {
3010 self.call_info[idx.as_usize()].top
3011 }
3012 #[inline(always)]
3017 pub fn ci_trap(&mut self, idx: CallInfoIdx) -> bool {
3018 self.call_info[idx.as_usize()].trap()
3019 }
3020 #[inline(always)]
3021 pub fn ci_savedpc(&self, idx: CallInfoIdx) -> u32 {
3022 self.call_info[idx.as_usize()].saved_pc()
3023 }
3024 #[inline(always)]
3025 pub fn set_ci_savedpc(&mut self, idx: CallInfoIdx, pc: u32) {
3026 self.call_info[idx.as_usize()].set_saved_pc(pc);
3027 }
3028 #[inline(always)]
3029 pub fn set_ci_previous(&mut self, idx: CallInfoIdx) {
3030 self.ci = self.call_info[idx.as_usize()]
3031 .previous
3032 .expect("set_ci_previous: returning frame has no previous CallInfo");
3033 }
3034 #[inline(always)]
3035 pub fn ci_previous(&self, idx: CallInfoIdx) -> Option<CallInfoIdx> {
3036 self.call_info[idx.as_usize()].previous
3037 }
3038 #[inline(always)]
3039 pub fn ci_adjust_func(&mut self, idx: CallInfoIdx, delta: i32) {
3040 let ci = &mut self.call_info[idx.as_usize()];
3041 ci.func = StackIdx((ci.func.0 as i32 - delta) as u32);
3042 }
3043 #[inline(always)]
3044 pub fn ci_base(&self, idx: CallInfoIdx) -> StackIdx {
3045 self.call_info[idx.as_usize()].func + 1
3046 }
3047 #[inline(always)]
3048 pub fn ci_is_fresh(&self, idx: CallInfoIdx) -> bool {
3049 (self.call_info[idx.as_usize()].callstatus & CIST_FRESH) != 0
3050 }
3051 #[inline(always)]
3052 pub fn ci_lua_closure(
3053 &self,
3054 idx: CallInfoIdx,
3055 ) -> Option<GcRef<lua_types::closure::LuaLClosure>> {
3056 let func_idx = self.call_info[idx.as_usize()].func;
3057 match self.stack.get(func_idx.0 as usize).map(|slot| slot.val) {
3058 Some(LuaValue::Function(lua_types::closure::LuaClosure::Lua(cl))) => Some(cl),
3059 _ => None,
3060 }
3061 }
3062 #[inline(always)]
3063 pub fn ci_nextraargs(&self, idx: CallInfoIdx) -> i32 {
3064 self.call_info[idx.as_usize()].nextra_args()
3065 }
3066 #[inline(always)]
3067 pub fn ci_nres(&self, idx: CallInfoIdx) -> i32 {
3068 self.call_info[idx.as_usize()].u2.value
3069 }
3070 #[inline(always)]
3071 pub fn ci_nres_set(&mut self, idx: CallInfoIdx, n: i32) {
3072 self.call_info[idx.as_usize()].u2.value = n;
3073 }
3074 #[inline(always)]
3075 pub fn ci_nresults(&self, idx: CallInfoIdx) -> i32 {
3076 self.call_info[idx.as_usize()].nresults as i32
3077 }
3078 pub fn ci_prev_instruction(&self, idx: CallInfoIdx) -> lua_types::opcode::Instruction {
3079 let pc = self.call_info[idx.as_usize()].saved_pc();
3080 let cl = self
3081 .ci_lua_closure(idx)
3082 .expect("ci_prev_instruction: CallInfo does not hold a Lua closure");
3083 cl.proto.code[(pc - 1) as usize]
3084 }
3085 pub fn ci_prev2_instruction(&self, idx: CallInfoIdx) -> lua_types::opcode::Instruction {
3086 let pc = self.call_info[idx.as_usize()].saved_pc();
3087 let cl = self
3088 .ci_lua_closure(idx)
3089 .expect("ci_prev2_instruction: CallInfo does not hold a Lua closure");
3090 cl.proto.code[(pc - 2) as usize]
3091 }
3092 pub fn ci_skip_next_instruction(&mut self, idx: CallInfoIdx) {
3093 let pc = self.call_info[idx.as_usize()].saved_pc();
3094 self.call_info[idx.as_usize()].set_saved_pc(pc + 1);
3095 }
3096 pub fn ci_step_pc_back(&mut self, idx: CallInfoIdx) {
3097 let pc = self.call_info[idx.as_usize()].saved_pc();
3098 self.call_info[idx.as_usize()].set_saved_pc(pc - 1);
3099 }
3100 pub fn get_ci_pcrel(&mut self, idx: CallInfoIdx) -> u32 {
3101 self.call_info[idx.as_usize()].saved_pc().saturating_sub(1)
3102 }
3103 pub fn get_ci_u2_funcidx(&mut self, idx: CallInfoIdx) -> i32 {
3104 self.call_info[idx.as_usize()].u2.value
3105 }
3106 pub fn get_ci_u2_nres(&mut self, idx: CallInfoIdx) -> i32 {
3107 self.call_info[idx.as_usize()].u2.value
3108 }
3109 pub fn get_ci_u2_nyield(&mut self, idx: CallInfoIdx) -> i32 {
3110 self.call_info[idx.as_usize()].u2.value
3111 }
3112 pub fn get_ci_vararg_info(&mut self, idx: CallInfoIdx) -> (bool, i32, i32) {
3113 let nextraargs = self.call_info[idx.as_usize()].nextra_args();
3114 match self.ci_lua_closure(idx) {
3115 Some(cl) => (cl.proto.is_vararg, nextraargs, cl.proto.numparams as i32),
3116 None => (false, nextraargs, 0),
3117 }
3118 }
3119 pub fn get_ci_lua_proto_numparams(&mut self, idx: CallInfoIdx) -> u8 {
3120 self.ci_lua_closure(idx)
3121 .map(|cl| cl.proto.numparams)
3122 .unwrap_or(0)
3123 }
3124 pub fn set_ci_u2_nres(&mut self, idx: CallInfoIdx, n: i32) {
3125 self.call_info[idx.as_usize()].u2.value = n;
3126 }
3127 pub fn set_ci_u2_nyield(&mut self, idx: CallInfoIdx, n: i32) {
3128 self.call_info[idx.as_usize()].u2.value = n;
3129 }
3130 pub fn set_ci_transfer_info(&mut self, idx: CallInfoIdx, ftransfer: u16, ntransfer: u16) {
3131 let ci = &mut self.call_info[idx.as_usize()];
3132 ci.u2.ftransfer = ftransfer;
3133 ci.u2.ntransfer = ntransfer;
3134 }
3135 pub fn shrink_ci(&mut self) {
3136 shrink_ci(self)
3137 }
3138 pub fn check_c_stack(&mut self) -> Result<(), LuaError> {
3139 check_c_stack(self)
3140 }
3141
3142 pub fn status(&mut self) -> LuaStatus {
3143 LuaStatus::from_raw(self.status as i32)
3144 }
3145 pub fn errfunc(&mut self) -> isize {
3146 self.errfunc
3147 }
3148 pub fn old_pc(&mut self) -> u32 {
3149 self.oldpc
3150 }
3151 pub fn set_old_pc(&mut self, pc: u32) {
3152 self.oldpc = pc;
3153 }
3154 pub fn set_oldpc(&mut self, pc: u32) {
3155 self.oldpc = pc;
3156 }
3157 pub fn _hook_call_noargs(&mut self) {}
3158 pub fn hook(&self) -> Option<&Box<dyn FnMut(&mut LuaState, &crate::debug::LuaDebug)>> {
3159 self.hook.as_ref()
3160 }
3161 pub fn has_hook(&mut self) -> bool {
3162 self.hook.is_some()
3163 }
3164 pub fn hook_count(&mut self) -> i32 {
3165 self.hookcount
3166 }
3167 pub fn set_hook_count(&mut self, n: i32) {
3168 self.hookcount = n;
3169 }
3170 pub fn hook_mask(&self) -> u8 {
3171 self.hookmask
3172 }
3173 pub fn set_hook_mask(&mut self, m: u8) {
3174 self.hookmask = m;
3175 }
3176 pub fn base_hook_count(&self) -> i32 {
3177 self.basehookcount
3178 }
3179 pub fn set_base_hook_count(&mut self, n: i32) {
3180 self.basehookcount = n;
3181 }
3182 pub fn set_hook(&mut self, h: Option<Box<dyn FnMut(&mut LuaState, &crate::debug::LuaDebug)>>) {
3183 self.hook = h;
3184 }
3185 pub fn call_hook_event(&mut self, event: i32, line: i32) -> Result<(), LuaError> {
3204 let saved_ci = self.ci;
3205 let r = crate::do_::hook(self, event, line, 0, 0);
3206 self.ci = saved_ci;
3207 r
3208 }
3209
3210 pub fn registry_value(&self) -> LuaValue {
3211 self.global().l_registry.clone()
3212 }
3213 pub fn registry_get(&self, key: usize) -> LuaValue {
3214 let reg = self.global().l_registry.clone();
3215 match reg {
3216 LuaValue::Table(t) => t.get(&LuaValue::Int(key as i64)),
3217 _ => LuaValue::Nil,
3218 }
3219 }
3220
3221 pub fn new_string(&mut self, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
3222 self.intern_or_create_str(bytes)
3223 }
3224
3225 pub fn new_proto(&mut self) -> GcRef<LuaProto> {
3236 self.mark_gc_check_needed();
3237 GcRef::new(LuaProto::placeholder())
3238 }
3239
3240 pub fn new_lclosure(&mut self, proto: GcRef<LuaProto>, nupvals: usize) -> GcRef<LuaClosureLua> {
3242 self.mark_gc_check_needed();
3243 let mut upvals = Vec::with_capacity(nupvals);
3244 for _ in 0..nupvals {
3245 upvals.push(std::cell::Cell::new(self.new_upval_closed(LuaValue::Nil)));
3246 }
3247 let upvals = upvals.into_boxed_slice();
3248 let closure = GcRef::new(LuaClosureLua { proto, upvals });
3249 closure.account_buffer(closure.buffer_bytes() as isize);
3250 closure
3251 }
3252
3253 pub fn new_upval_closed(&mut self, v: LuaValue) -> GcRef<UpVal> {
3255 self.mark_gc_check_needed();
3256 GcRef::new(UpVal::closed(v))
3257 }
3258
3259 pub fn new_upval_open(&mut self, thread_id: u64, level: StackIdx) -> GcRef<UpVal> {
3261 self.mark_gc_check_needed();
3262 self.legacy_open_upval_touched.set(true);
3263 GcRef::new(UpVal::open(thread_id, level))
3264 }
3265 pub fn intern_or_create_str(&mut self, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
3272 self.intern_str(bytes)
3273 }
3274 pub fn new_userdata(
3281 &mut self,
3282 size: usize,
3283 nuvalue: usize,
3284 ) -> Result<GcRef<LuaUserData>, LuaError> {
3285 debug_assert!(nuvalue < u16::MAX as usize, "invalid value");
3286 self.mark_gc_check_needed();
3287 let u = GcRef::new(LuaUserData {
3288 data: vec![0u8; size].into_boxed_slice(),
3289 uv: std::cell::RefCell::new(vec![LuaValue::Nil; nuvalue]),
3290 metatable: std::cell::RefCell::new(None),
3291 host_value: std::cell::RefCell::new(None),
3292 });
3293 u.account_buffer(u.buffer_bytes() as isize);
3294 Ok(u)
3295 }
3296
3297 pub fn register_c_function(&mut self, f: LuaCFunction, dedup: bool) -> LuaCFnPtr {
3305 let mut g = self.global_mut();
3306 if dedup {
3307 if let Some(i) = g.c_functions.iter().position(|existing| {
3308 existing
3309 .as_bare()
3310 .is_some_and(|existing| std::ptr::fn_addr_eq(existing, f))
3311 }) {
3312 return i;
3313 }
3314 }
3315 let i = g.c_functions.len();
3316 g.c_functions.push(LuaCallable::bare(f));
3317 i
3318 }
3319
3320 pub fn new_c_closure(&mut self, f: LuaCFunction, n: i32) -> Result<LuaClosure, LuaError> {
3330 if n < 0 || n as i64 > crate::api::MAX_UPVAL as i64 {
3331 return Err(LuaError::runtime(format_args!(
3332 "C closure upvalue count {n} out of range (0..={})",
3333 crate::api::MAX_UPVAL
3334 )));
3335 }
3336 let idx = self.register_c_function(f, n == 0);
3337 if n == 0 {
3338 return Ok(LuaClosure::LightC(idx));
3339 }
3340 self.mark_gc_check_needed();
3341 let cl = LuaClosure::C(GcRef::new(lua_types::closure::LuaCClosure {
3342 func: idx,
3343 upvalues: std::cell::RefCell::new(vec![LuaValue::Nil; n as usize]),
3344 }));
3345 if let LuaClosure::C(ccl) = &cl {
3346 ccl.account_buffer(ccl.buffer_bytes() as isize);
3347 }
3348 Ok(cl)
3349 }
3350 pub fn push_closure(
3351 &mut self,
3352 proto_idx: usize,
3353 ci: CallInfoIdx,
3354 base: StackIdx,
3355 ra: StackIdx,
3356 ) -> Result<(), LuaError> {
3357 let parent_cl = self
3358 .ci_lua_closure(ci)
3359 .expect("push_closure: current frame is not a Lua closure");
3360 let child_proto = parent_cl.proto.p[proto_idx].clone();
3361 let nup = child_proto.upvalues.len();
3362 let mut upvals: Vec<std::cell::Cell<GcRef<UpVal>>> = Vec::with_capacity(nup);
3363 for i in 0..nup {
3364 let desc = &child_proto.upvalues[i];
3365 let uv = if desc.instack {
3366 let level = base + desc.idx as i32;
3367 crate::func::find_upval(self, level)
3368 } else {
3369 parent_cl.upval(desc.idx as usize)
3370 };
3371 upvals.push(std::cell::Cell::new(uv));
3372 }
3373 let cache_enabled = matches!(
3377 self.global().lua_version,
3378 lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3379 );
3380 if cache_enabled {
3381 if let Some(cached) = child_proto.cache.borrow().as_ref() {
3382 if cached.upvals.len() == nup
3383 && (0..nup).all(|i| GcRef::ptr_eq(&cached.upvals[i].get(), &upvals[i].get()))
3384 {
3385 let reused = cached.clone();
3386 self.set_at(ra, LuaValue::Function(LuaClosure::Lua(reused)));
3387 return Ok(());
3388 }
3389 }
3390 }
3391 self.mark_gc_check_needed();
3395 let new_cl = GcRef::new(LuaClosureLua {
3396 proto: child_proto.clone(),
3397 upvals: upvals.into_boxed_slice(),
3398 });
3399 new_cl.account_buffer(new_cl.buffer_bytes() as isize);
3400 if cache_enabled {
3401 *child_proto.cache.borrow_mut() = Some(new_cl.clone());
3402 }
3403 self.set_at(ra, LuaValue::Function(LuaClosure::Lua(new_cl)));
3404 Ok(())
3405 }
3406 pub fn new_tbc_upval(&mut self, idx: StackIdx) -> Result<(), LuaError> {
3407 crate::func::new_tbc_upval(self, idx)
3408 }
3409
3410 #[inline(always)]
3431 pub fn upvalue_get(&self, cl: &GcRef<LuaClosureLua>, n: usize) -> LuaValue {
3432 let uv = cl.upval(n);
3433 let (thread_id, idx) = match uv.try_open_payload() {
3434 Some(p) => p,
3435 None => return uv.closed_value(),
3436 };
3437 let current = self.cached_thread_id;
3438 if thread_id == current {
3439 return self.stack[idx.0 as usize].val;
3440 }
3441 self.upvalue_get_cross_thread(thread_id, idx)
3442 }
3443
3444 #[cold]
3445 #[inline(never)]
3446 fn upvalue_get_cross_thread(&self, tid: u64, idx: StackIdx) -> LuaValue {
3447 let entry_rc = {
3448 let g = self.global();
3449 g.threads.get(&tid).map(|e| e.state.clone())
3450 };
3451 if let Some(rc) = entry_rc {
3452 if let Ok(home_state) = rc.try_borrow() {
3453 return home_state.get_at(idx);
3454 }
3455 }
3456 let g = self.global();
3457 match g.cross_thread_upvals.get(&(tid, idx)) {
3458 Some(v) => *v,
3459 None => LuaValue::Nil,
3460 }
3461 }
3462 #[inline(always)]
3471 pub fn upvalue_set(
3472 &mut self,
3473 cl: &GcRef<LuaClosureLua>,
3474 n: usize,
3475 val: LuaValue,
3476 ) -> Result<(), LuaError> {
3477 let uv = cl.upval(n);
3478 match uv.try_open_payload() {
3479 Some((thread_id, idx)) => {
3480 let current = self.cached_thread_id;
3481 if thread_id == current {
3482 self.stack[idx.0 as usize].val = val;
3483 } else {
3484 self.upvalue_set_cross_thread(thread_id, idx, val)?;
3485 }
3486 }
3487 None => {
3488 uv.set_closed_value(val);
3489 }
3490 }
3491 if val.is_collectable() {
3492 self.gc_barrier_upval(&uv, &val);
3493 }
3494 Ok(())
3495 }
3496
3497 #[cold]
3498 #[inline(never)]
3499 fn upvalue_set_cross_thread(
3500 &mut self,
3501 tid: u64,
3502 idx: StackIdx,
3503 val: LuaValue,
3504 ) -> Result<(), LuaError> {
3505 let entry_rc = {
3506 let g = self.global();
3507 g.threads.get(&tid).map(|e| e.state.clone())
3508 };
3509 if let Some(rc) = entry_rc {
3510 if let Ok(mut home_state) = rc.try_borrow_mut() {
3511 home_state.set_at(idx, val);
3512 return Ok(());
3513 }
3514 }
3515 let mut g = self.global_mut();
3516 g.cross_thread_upvals.insert((tid, idx), val);
3517 Ok(())
3518 }
3519
3520 pub fn protected_call_raw(
3521 &mut self,
3522 func: StackIdx,
3523 nresults: i32,
3524 errfunc: StackIdx,
3525 ) -> Result<(), LuaError> {
3526 let ef = errfunc.0 as isize;
3527 let status = crate::do_::pcall(self, |s| s.call_no_yield(func, nresults), func, ef);
3528 match status {
3529 LuaStatus::Ok => Ok(()),
3530 LuaStatus::ErrSyntax => {
3531 let err_val = self.get_at(func);
3532 self.set_top(func);
3533 Err(LuaError::Syntax(err_val))
3534 }
3535 LuaStatus::Yield => {
3536 self.set_top(func);
3537 Err(LuaError::Yield)
3538 }
3539 _ => {
3540 let err_val = self.get_at(func);
3541 self.set_top(func);
3542 Err(LuaError::Runtime(err_val))
3543 }
3544 }
3545 }
3546 pub fn protected_parser(
3547 &mut self,
3548 z: crate::zio::ZIO,
3549 name: &[u8],
3550 mode: Option<&[u8]>,
3551 ) -> LuaStatus {
3552 crate::do_::protected_parser(self, z, name, mode)
3553 }
3554 pub fn do_call(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
3555 crate::do_::call(self, func, nresults)
3556 }
3557 pub fn do_call_no_yield(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
3558 crate::do_::callnoyield(self, func, nresults)
3559 }
3560 pub fn call_no_yield(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
3561 crate::do_::callnoyield(self, func, nresults)
3562 }
3563 pub fn call_at(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
3564 crate::do_::call(self, func, nresults)
3565 }
3566 #[inline(always)]
3567 pub fn call_known_c_at(&mut self, func: StackIdx, nresults: i32) -> Result<bool, LuaError> {
3568 crate::do_::call_known_c(self, func, nresults)
3569 }
3570 #[inline(always)]
3571 pub fn precall(
3572 &mut self,
3573 func: StackIdx,
3574 nresults: i32,
3575 ) -> Result<Option<CallInfoIdx>, LuaError> {
3576 crate::do_::precall(self, func, nresults)
3577 }
3578 #[inline(always)]
3579 pub fn pretailcall(
3580 &mut self,
3581 ci: CallInfoIdx,
3582 func: StackIdx,
3583 narg1: i32,
3584 delta: i32,
3585 ) -> Result<i32, LuaError> {
3586 crate::do_::pretailcall(self, ci, func, narg1, delta)
3587 }
3588 #[inline(always)]
3589 pub fn poscall<N: TryInto<i32>>(&mut self, ci: CallInfoIdx, nres: N) -> Result<(), LuaError>
3590 where
3591 <N as TryInto<i32>>::Error: std::fmt::Debug,
3592 {
3593 let n = nres.try_into().expect("poscall: nres out of i32 range");
3594 crate::do_::poscall(self, ci, n)
3595 }
3596 pub fn adjust_results(&mut self, nresults: i32) {
3597 const LUA_MULTRET: i32 = -1;
3598 if nresults <= LUA_MULTRET {
3599 let ci_idx = self.ci.as_usize();
3600 if self.call_info[ci_idx].top.0 < self.top.0 {
3601 self.call_info[ci_idx].top = self.top;
3602 }
3603 }
3604 }
3605 pub fn adjust_varargs(
3606 &mut self,
3607 ci: CallInfoIdx,
3608 nfixparams: i32,
3609 cl: &GcRef<lua_types::closure::LuaLClosure>,
3610 ) -> Result<(), LuaError> {
3611 crate::tagmethods::adjust_varargs(self, nfixparams, ci, &cl.0.proto)
3612 }
3613 pub fn get_varargs(&mut self, ci: CallInfoIdx, ra: StackIdx, n: i32) -> Result<i32, LuaError> {
3614 crate::tagmethods::get_varargs(self, ci, ra, n)?;
3615 Ok(0)
3616 }
3617
3618 pub fn close_upvals(&mut self, level: StackIdx) -> Result<(), LuaError> {
3619 crate::func::close_upval(self, level);
3620 Ok(())
3621 }
3622 pub fn close_upvals_status(&mut self, level: StackIdx, _status: i32) -> Result<(), LuaError> {
3623 crate::func::close_upval(self, level);
3624 Ok(())
3625 }
3626 pub fn close_upvals_from_base(&mut self, ci: CallInfoIdx) -> Result<(), LuaError> {
3627 let base = self.ci_base(ci);
3628 crate::func::close_upval(self, base);
3629 Ok(())
3630 }
3631
3632 pub fn arith_op(
3633 &mut self,
3634 op: i32,
3635 p1: &LuaValue,
3636 p2: &LuaValue,
3637 ) -> Result<LuaValue, LuaError> {
3638 let arith_op = match op {
3639 0 => lua_types::arith::ArithOp::Add,
3640 1 => lua_types::arith::ArithOp::Sub,
3641 2 => lua_types::arith::ArithOp::Mul,
3642 3 => lua_types::arith::ArithOp::Mod,
3643 4 => lua_types::arith::ArithOp::Pow,
3644 5 => lua_types::arith::ArithOp::Div,
3645 6 => lua_types::arith::ArithOp::Idiv,
3646 7 => lua_types::arith::ArithOp::Band,
3647 8 => lua_types::arith::ArithOp::Bor,
3648 9 => lua_types::arith::ArithOp::Bxor,
3649 10 => lua_types::arith::ArithOp::Shl,
3650 11 => lua_types::arith::ArithOp::Shr,
3651 12 => lua_types::arith::ArithOp::Unm,
3652 13 => lua_types::arith::ArithOp::Bnot,
3653 _ => return Err(LuaError::runtime(format_args!("invalid arith op {}", op))),
3654 };
3655 let mut res = LuaValue::Nil;
3656 if crate::object::raw_arith(self, arith_op, p1, p2, &mut res)? {
3657 Ok(res)
3658 } else {
3659 Err(LuaError::arith_error(p1, p2, "perform arithmetic on"))
3660 }
3661 }
3662 pub fn concat(&mut self, n: i32) -> Result<(), LuaError> {
3663 crate::vm::concat(self, n)
3664 }
3665 pub fn less_than(&mut self, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
3666 crate::vm::less_than(self, l, r)
3667 }
3668 pub fn less_equal(&mut self, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
3669 crate::vm::less_equal(self, l, r)
3670 }
3671 pub fn equal_obj(&self, _ctx: Option<&LuaValue>, l: &LuaValue, r: &LuaValue) -> bool {
3672 crate::vm::equal_obj(None, l, r).unwrap_or(false)
3673 }
3674 pub fn equal_obj_with_tm(&mut self, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
3675 crate::vm::equal_obj(Some(self), l, r)
3676 }
3677 pub fn obj_len(&mut self, v: &LuaValue) -> Result<LuaValue, LuaError> {
3678 match v {
3679 LuaValue::Table(_) => {
3680 let consult_len_tm =
3683 !matches!(self.global().lua_version, lua_types::LuaVersion::V51);
3684 let tm = if consult_len_tm {
3685 let mt = self.table_metatable(v);
3686 self.fast_tm_table(mt.as_ref(), TagMethod::Len)
3687 } else {
3688 LuaValue::Nil
3689 };
3690 if matches!(tm, LuaValue::Nil) {
3691 let n = self.table_length(v)?;
3692 return Ok(LuaValue::Int(n));
3693 }
3694 self.push(LuaValue::Nil);
3695 let slot = StackIdx(self.top.0 - 1);
3696 crate::tagmethods::call_tm_res(self, tm, v.clone(), v.clone(), slot)?;
3697 Ok(self.pop())
3698 }
3699 LuaValue::Str(s) => Ok(LuaValue::Int(s.len() as i64)),
3700 other => {
3701 let tm = crate::tagmethods::get_tm_by_obj(
3702 self,
3703 other,
3704 crate::tagmethods::TagMethod::Len,
3705 );
3706 if matches!(tm, LuaValue::Nil) {
3707 let mut msg = b"attempt to get length of a ".to_vec();
3708 msg.extend_from_slice(&self.obj_type_name(other));
3709 msg.extend_from_slice(b" value");
3710 return Err(crate::debug::prefixed_runtime_pub(self, msg));
3711 }
3712 self.push(LuaValue::Nil);
3713 let slot = StackIdx(self.top.0 - 1);
3714 crate::tagmethods::call_tm_res(self, tm, v.clone(), v.clone(), slot)?;
3715 Ok(self.pop())
3716 }
3717 }
3718 }
3719 pub fn obj_to_string(&mut self, idx: i32) -> Result<GcRef<LuaString>, LuaError> {
3720 let slot: StackIdx = if idx > 0 {
3721 let ci_func = self.current_call_info().func;
3722 ci_func + idx
3723 } else {
3724 debug_assert!(idx != 0, "invalid index");
3725 StackIdx((self.top_idx().0 as i32 + idx) as u32)
3726 };
3727 let val = self.get_at(slot);
3728 match val {
3729 LuaValue::Str(s) => Ok(s),
3730 LuaValue::Int(_) | LuaValue::Float(_) => {
3731 let s = crate::object::num_to_string(self, &val)?;
3732 self.set_at(slot, LuaValue::Str(s.clone()));
3733 Ok(s)
3734 }
3735 _ => Err(LuaError::type_error(&val, "convert to string")),
3736 }
3737 }
3738 pub fn coerce_to_string(&mut self, idx: StackIdx) -> Result<GcRef<LuaString>, LuaError> {
3739 let val = self.get_at(idx);
3740 match val {
3741 LuaValue::Str(s) => Ok(s),
3742 LuaValue::Int(_) | LuaValue::Float(_) => {
3743 let s = crate::object::num_to_string(self, &val)?;
3744 self.set_at(idx, LuaValue::Str(s.clone()));
3745 Ok(s)
3746 }
3747 _ => Err(LuaError::type_error(&val, "convert to string")),
3748 }
3749 }
3750 pub fn str_to_num(&mut self, s: &[u8]) -> Option<(LuaValue, usize)> {
3758 let mut out = LuaValue::Nil;
3759 let float_only =
3760 self.global().lua_version.number_model() == lua_types::NumberModel::FloatOnly;
3761 let sz = if float_only {
3762 crate::object::str2num_float_only(s, &mut out)
3763 } else {
3764 crate::object::str2num(s, &mut out)
3765 };
3766 if sz == 0 {
3767 return None;
3768 }
3769 Some((out, sz))
3770 }
3771
3772 #[inline(always)]
3773 pub fn fast_get(&mut self, t: &LuaValue, k: &LuaValue) -> Result<Option<LuaValue>, LuaError> {
3774 let LuaValue::Table(tbl) = t else {
3775 return Ok(None);
3776 };
3777 let v = tbl.get(k);
3778 if matches!(v, LuaValue::Nil) {
3779 Ok(None)
3780 } else {
3781 Ok(Some(v))
3782 }
3783 }
3784 #[inline(always)]
3785 pub fn fast_get_int(&mut self, t: &LuaValue, k: i64) -> Result<Option<LuaValue>, LuaError> {
3786 let LuaValue::Table(tbl) = t else {
3787 return Ok(None);
3788 };
3789 let v = tbl.get_int(k);
3790 if matches!(v, LuaValue::Nil) {
3791 Ok(None)
3792 } else {
3793 Ok(Some(v))
3794 }
3795 }
3796 #[inline(always)]
3797 pub fn fast_get_short_str(
3798 &mut self,
3799 t: &LuaValue,
3800 k: &LuaValue,
3801 ) -> Result<Option<LuaValue>, LuaError> {
3802 let LuaValue::Table(tbl) = t else {
3803 return Ok(None);
3804 };
3805 let LuaValue::Str(s) = k else {
3806 return Ok(None);
3807 };
3808 let v = tbl.get_short_str(s);
3809 if matches!(v, LuaValue::Nil) {
3810 Ok(None)
3811 } else {
3812 Ok(Some(v))
3813 }
3814 }
3815 #[inline(always)]
3816 pub fn fast_tm_table(&mut self, t: Option<&GcRef<LuaTable>>, tm: TagMethod) -> LuaValue {
3817 let Some(mt) = t else {
3818 return LuaValue::Nil;
3819 };
3820 debug_assert!((tm as u8) <= TagMethod::Eq as u8);
3821 let ename = self.global().tmname[tm as usize].clone();
3822 mt.get_short_str(&ename)
3823 }
3824 pub fn fast_tm_ud(&mut self, u: &GcRef<LuaUserData>, tm: TagMethod) -> LuaValue {
3825 let mt = u.metatable();
3827 self.fast_tm_table(mt.as_ref(), tm)
3828 }
3829
3830 pub fn table_get_with_tm(&mut self, t: &LuaValue, k: &LuaValue) -> Result<LuaValue, LuaError> {
3831 if let LuaValue::Table(tbl) = t {
3837 if !tbl.has_metatable() {
3838 return Ok(tbl.get(k));
3839 }
3840 }
3841 if let Some(v) = self.fast_get(t, k)? {
3842 return Ok(v);
3843 }
3844 let res = self.top_idx();
3845 self.push(LuaValue::Nil);
3846 crate::vm::finish_get(self, t.clone(), k.clone(), res, true, None, None)?;
3847 let value = self.get_at(res);
3848 self.pop();
3849 Ok(value)
3850 }
3851 #[inline]
3866 pub fn table_set_with_tm(
3867 &mut self,
3868 t: &LuaValue,
3869 k: LuaValue,
3870 v: LuaValue,
3871 ) -> Result<(), LuaError> {
3872 if let LuaValue::Table(tbl) = t {
3873 if !tbl.has_metatable() {
3874 self.gc_table_barrier_back(tbl, &v);
3875 return self.table_raw_set(t, k, v);
3876 }
3877 }
3878 if self.fast_get(t, &k)?.is_some() {
3879 self.gc_value_barrier_back(t, &v);
3880 return self.table_raw_set(t, k, v);
3881 }
3882 crate::vm::finish_set(self, t.clone(), k, v, true, None, None)
3883 }
3884 #[inline]
3885 pub fn table_raw_set(
3886 &mut self,
3887 t: &LuaValue,
3888 k: LuaValue,
3889 v: LuaValue,
3890 ) -> Result<(), LuaError> {
3891 let LuaValue::Table(tbl) = t else {
3892 return Err(LuaError::type_error(t, "index"));
3893 };
3894 let tbl = tbl.clone();
3895 tbl.raw_set(self, k, v)
3896 }
3897 #[inline]
3898 pub fn table_array_set(
3899 &mut self,
3900 t: &LuaValue,
3901 idx: usize,
3902 v: LuaValue,
3903 ) -> Result<(), LuaError> {
3904 let LuaValue::Table(tbl) = t else {
3905 return Err(LuaError::type_error(t, "index"));
3906 };
3907 let tbl = tbl.clone();
3908 tbl.raw_set_int(self, idx as i64 + 1, v)
3909 }
3910 pub fn table_ensure_array(&mut self, t: &LuaValue, n: usize) -> Result<(), LuaError> {
3911 let LuaValue::Table(tbl) = t else {
3912 return Err(LuaError::type_error(t, "index"));
3913 };
3914 if n > tbl.array_len() {
3915 tbl.resize(self, n, 0)?;
3916 }
3917 Ok(())
3918 }
3919 pub fn table_length(&mut self, t: &LuaValue) -> Result<i64, LuaError> {
3920 let LuaValue::Table(tbl) = t else {
3921 return Err(LuaError::type_error(t, "get length of"));
3922 };
3923 Ok(tbl.getn() as i64)
3924 }
3925 pub fn table_metatable(&mut self, v: &LuaValue) -> Option<GcRef<LuaTable>> {
3926 match v {
3927 LuaValue::Table(t) => t.metatable(),
3928 LuaValue::UserData(u) => u.metatable(),
3929 other => {
3930 let idx = other.base_type() as usize;
3931 self.global().mt[idx].clone()
3932 }
3933 }
3934 }
3935 pub fn table_resize(
3936 &mut self,
3937 t: &GcRef<LuaTable>,
3938 na: usize,
3939 nh: usize,
3940 ) -> Result<(), LuaError> {
3941 self.mark_gc_check_needed();
3942 t.resize(self, na, nh)
3943 }
3944 pub fn table_getn(&self, t: &GcRef<LuaTable>) -> i64 {
3945 let mut i: i64 = 1;
3951 loop {
3952 let v = t.get_int(i);
3953 if matches!(v, LuaValue::Nil) {
3954 return i - 1;
3955 }
3956 i += 1;
3957 }
3958 }
3959
3960 pub fn try_bin_tm(
3961 &mut self,
3962 p1: &LuaValue,
3963 p1_idx: Option<StackIdx>,
3964 p2: &LuaValue,
3965 p2_idx: Option<StackIdx>,
3966 res: StackIdx,
3967 tm: lua_types::tagmethod::TagMethod,
3968 ) -> Result<(), LuaError> {
3969 let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
3970 crate::tagmethods::try_bin_tm(self, p1, p1_idx, p2, p2_idx, res, event)
3971 }
3972 pub fn try_bin_i_tm(
3973 &mut self,
3974 p1: &LuaValue,
3975 p1_idx: Option<StackIdx>,
3976 imm: i64,
3977 flip: bool,
3978 res: StackIdx,
3979 tm: lua_types::tagmethod::TagMethod,
3980 ) -> Result<(), LuaError> {
3981 let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
3982 crate::tagmethods::try_bini_tm(self, p1, p1_idx, imm, flip, res, event)
3983 }
3984 pub fn try_bin_assoc_tm(
3985 &mut self,
3986 p1: &LuaValue,
3987 p1_idx: Option<StackIdx>,
3988 p2: &LuaValue,
3989 p2_idx: Option<StackIdx>,
3990 flip: bool,
3991 res: StackIdx,
3992 tm: lua_types::tagmethod::TagMethod,
3993 ) -> Result<(), LuaError> {
3994 let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
3995 crate::tagmethods::try_bin_assoc_tm(self, p1, p1_idx, p2, p2_idx, flip, res, event)
3996 }
3997 pub fn try_concat_tm(&mut self, _p1: &LuaValue, _p2: &LuaValue) -> Result<(), LuaError> {
3998 crate::tagmethods::try_concat_tm(self)
3999 }
4000 pub fn call_tm(
4001 &mut self,
4002 f: LuaValue,
4003 p1: &LuaValue,
4004 p2: &LuaValue,
4005 p3: &LuaValue,
4006 ) -> Result<(), LuaError> {
4007 crate::tagmethods::call_tm(self, f, p1.clone(), p2.clone(), p3.clone())
4008 }
4009 pub fn call_tm_res(
4010 &mut self,
4011 f: LuaValue,
4012 p1: &LuaValue,
4013 p2: &LuaValue,
4014 res: StackIdx,
4015 ) -> Result<(), LuaError> {
4016 crate::tagmethods::call_tm_res(self, f, p1.clone(), p2.clone(), res)
4017 }
4018 pub fn call_tm_res_bool(
4019 &mut self,
4020 f: LuaValue,
4021 p1: &LuaValue,
4022 p2: &LuaValue,
4023 ) -> Result<bool, LuaError> {
4024 let res = self.top_idx();
4025 self.push(LuaValue::Nil);
4026 crate::tagmethods::call_tm_res(self, f, p1.clone(), p2.clone(), res)?;
4027 let result = self.get_at(res).clone();
4028 self.pop();
4029 Ok(!matches!(result, LuaValue::Nil | LuaValue::Bool(false)))
4030 }
4031 pub fn call_order_tm(
4032 &mut self,
4033 p1: &LuaValue,
4034 p2: &LuaValue,
4035 tm: lua_types::tagmethod::TagMethod,
4036 ) -> Result<bool, LuaError> {
4037 let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
4038 crate::tagmethods::call_order_tm(self, p1, p2, event)
4039 }
4040 pub fn call_order_i_tm(
4041 &mut self,
4042 p1: &LuaValue,
4043 v2: i64,
4044 flip: bool,
4045 isfloat: bool,
4046 tm: lua_types::tagmethod::TagMethod,
4047 ) -> Result<bool, LuaError> {
4048 let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
4049 crate::tagmethods::call_orderi_tm(self, p1, v2 as i32, flip, isfloat, event)
4050 }
4051
4052 #[inline(always)]
4053 pub fn proto_code(
4054 &self,
4055 cl: &GcRef<lua_types::closure::LuaLClosure>,
4056 pc: u32,
4057 ) -> lua_types::opcode::Instruction {
4058 cl.proto.code[pc as usize]
4059 }
4060 #[inline(always)]
4061 pub fn proto_const(&self, cl: &GcRef<lua_types::closure::LuaLClosure>, idx: usize) -> LuaValue {
4062 cl.proto.k[idx].clone()
4063 }
4064 #[inline(always)]
4070 pub fn proto_const_int(
4071 &self,
4072 cl: &GcRef<lua_types::closure::LuaLClosure>,
4073 idx: usize,
4074 ) -> Option<i64> {
4075 match &cl.proto.k[idx] {
4076 LuaValue::Int(v) => Some(*v),
4077 _ => None,
4078 }
4079 }
4080 #[inline(always)]
4084 pub fn proto_const_num(
4085 &self,
4086 cl: &GcRef<lua_types::closure::LuaLClosure>,
4087 idx: usize,
4088 ) -> Option<f64> {
4089 match &cl.proto.k[idx] {
4090 LuaValue::Float(f) => Some(*f),
4091 LuaValue::Int(v) => Some(*v as f64),
4092 _ => None,
4093 }
4094 }
4095 pub fn get_proto_instr(&self, ci: CallInfoIdx, pc: u32) -> lua_types::opcode::Instruction {
4096 let cl = self
4097 .ci_lua_closure(ci)
4098 .expect("get_proto_instr: CallInfo does not hold a Lua closure");
4099 cl.proto.code[pc as usize]
4100 }
4101 pub fn trace_call(&mut self, _idx: CallInfoIdx) -> Result<bool, LuaError> {
4106 Ok(crate::debug::trace_call(self)? != 0)
4107 }
4108 pub fn trace_exec(&mut self, _idx: CallInfoIdx, pc: u32) -> Result<bool, LuaError> {
4111 Ok(crate::debug::trace_exec(self, pc)? != 0)
4112 }
4113 pub fn hook_call(&mut self, idx: CallInfoIdx) -> Result<(), LuaError> {
4124 if self.global().lua_version == lua_types::LuaVersion::V51 {
4125 let had_tail = self.call_info[idx.as_usize()].callstatus & CIST_TAIL;
4126 self.call_info[idx.as_usize()].callstatus &= !CIST_TAIL;
4127 let r = crate::do_::hookcall(self, idx);
4128 self.call_info[idx.as_usize()].callstatus |= had_tail;
4129 return r;
4130 }
4131 crate::do_::hookcall(self, idx)
4132 }
4133 #[inline(always)]
4134 fn gc_step_flags(&self) -> Option<(bool, bool)> {
4135 let g = self.global();
4136 if !g.is_gc_running() {
4137 return None;
4138 }
4139 let should_collect = g.heap.would_collect();
4140 let has_finalizers = g.finalizers.has_to_be_finalized();
4141 if should_collect || has_finalizers {
4142 Some((should_collect, has_finalizers))
4143 } else {
4144 None
4145 }
4146 }
4147
4148 #[inline(always)]
4149 fn should_check_gc(&mut self) -> bool {
4150 if self.gc_check_needed {
4151 return true;
4152 }
4153 if self.global().finalizers.has_to_be_finalized() {
4154 self.gc_check_needed = true;
4155 return true;
4156 }
4157 false
4158 }
4159
4160 #[inline(always)]
4161 pub(crate) fn mark_gc_check_needed(&mut self) {
4162 self.gc_check_needed = true;
4163 }
4164
4165 pub fn gc_trace_bound(&self) -> usize {
4179 (self.top.0 as usize).min(self.stack.len())
4180 }
4181
4182 pub fn clear_dead_stack_tail(&mut self) {
4189 let bound = self.gc_trace_bound();
4190 for slot in &mut self.stack[bound..] {
4191 slot.val = LuaValue::Nil;
4192 }
4193 }
4194
4195 pub fn gc_clear_dead_stack_tails(&mut self) {
4202 self.clear_dead_stack_tail();
4203 let global = self.global.clone();
4204 let g = global.borrow();
4205 for entry in g.threads.values() {
4206 if let Ok(mut t) = entry.state.try_borrow_mut() {
4207 t.clear_dead_stack_tail();
4208 }
4209 }
4210 }
4211
4212 pub fn gc_pre_collect_clear(&mut self) {
4216 if self.global().heap.would_collect() {
4217 self.gc_clear_dead_stack_tails();
4218 }
4219 }
4220
4221 #[inline(always)]
4222 pub fn gc_check_step(&mut self) {
4223 if !self.allowhook {
4224 return;
4225 }
4226 if !self.should_check_gc() {
4227 return;
4228 }
4229 let Some((should_collect, has_finalizers)) = self.gc_step_flags() else {
4230 self.gc_check_needed = false;
4231 return;
4232 };
4233 if should_collect || has_finalizers {
4234 if should_collect {
4235 self.gc_clear_dead_stack_tails();
4236 self.gc().check_step();
4237 }
4238 crate::api::run_pending_finalizers(self);
4239 self.gc_check_needed = true;
4240 }
4241 let should_keep_checking = {
4242 let g = self.global();
4243 g.heap.would_collect() || g.finalizers.has_to_be_finalized()
4244 };
4245 self.gc_check_needed = should_keep_checking;
4246 }
4247 #[inline(always)]
4248 pub fn gc_cond_step(&mut self) {
4249 if !self.allowhook {
4250 return;
4251 }
4252 if !self.should_check_gc() {
4253 return;
4254 }
4255 let Some((should_collect, has_finalizers)) = self.gc_step_flags() else {
4256 self.gc_check_needed = false;
4257 return;
4258 };
4259 if should_collect || has_finalizers {
4260 if should_collect {
4261 self.gc_clear_dead_stack_tails();
4262 self.gc().check_step();
4263 }
4264 crate::api::run_pending_finalizers(self);
4265 self.gc_check_needed = true;
4266 }
4267 let should_keep_checking = {
4268 let g = self.global();
4269 g.heap.would_collect() || g.finalizers.has_to_be_finalized()
4270 };
4271 self.gc_check_needed = should_keep_checking;
4272 }
4273 pub fn gc_barrier_back(&mut self, t: &dyn std::any::Any, v: &LuaValue) {
4274 self.gc().barrier_back(t, v);
4275 }
4276 #[inline(always)]
4277 pub fn gc_value_barrier_back(&mut self, t: &LuaValue, v: &LuaValue) {
4278 if !v.is_collectable() {
4279 return;
4280 }
4281 if let LuaValue::Table(tbl) = t {
4282 self.gc_table_barrier_back(tbl, v);
4283 } else {
4284 self.gc_barrier_back(t, v);
4285 }
4286 }
4287 #[inline(always)]
4288 pub fn gc_table_barrier_back(&mut self, t: &GcRef<LuaTable>, v: &LuaValue) {
4289 if !v.is_collectable() {
4290 return;
4291 }
4292 self.gc().table_barrier_back(t, v);
4293 }
4294 pub fn gc_barrier_upval(&mut self, uv: &GcRef<UpVal>, v: &LuaValue) {
4295 self.gc().barrier(uv, v);
4296 }
4297 pub fn is_main_thread(&mut self) -> bool {
4301 let g = self.global();
4302 g.current_thread_id == g.main_thread_id
4303 }
4304 pub fn obj_type_name<'v>(&self, v: &'v LuaValue) -> std::borrow::Cow<'static, [u8]> {
4305 let honors_name = self.global().lua_version.honors_name_metafield();
4306 match v {
4307 LuaValue::LightUserData(_) => std::borrow::Cow::Borrowed(b"light userdata"),
4308 LuaValue::Table(t) => {
4309 if honors_name {
4310 if let Some(mt) = t.metatable() {
4311 if let LuaValue::Str(s) = mt.get_str_bytes(b"__name") {
4312 return std::borrow::Cow::Owned(s.as_bytes().to_vec());
4313 }
4314 }
4315 }
4316 std::borrow::Cow::Borrowed(crate::tagmethods::type_name(v.base_type()))
4317 }
4318 LuaValue::UserData(u) => {
4319 if honors_name {
4320 if let Some(mt) = u.metatable() {
4321 if let LuaValue::Str(s) = mt.get_str_bytes(b"__name") {
4322 return std::borrow::Cow::Owned(s.as_bytes().to_vec());
4323 }
4324 }
4325 }
4326 std::borrow::Cow::Borrowed(crate::tagmethods::type_name(v.base_type()))
4327 }
4328 _ => std::borrow::Cow::Borrowed(crate::tagmethods::type_name(v.base_type())),
4329 }
4330 }
4331
4332 pub fn full_type_name(&mut self, v: &LuaValue) -> Result<Vec<u8>, LuaError> {
4333 crate::tagmethods::obj_type_name(self, v)
4334 }
4335 pub fn emit_warning(&mut self, _msg: &[u8], _to_cont: bool) {
4336 warning(self, _msg, _to_cont)
4337 }
4338}
4339
4340pub struct GcHandle<'a> {
4344 _state: &'a mut LuaState,
4345}
4346
4347struct CollectRoots<'a> {
4354 global: &'a GlobalState,
4355 thread: &'a LuaState,
4356}
4357
4358#[derive(Clone, Copy)]
4359enum HeapCollectMode {
4360 Full,
4361 Step,
4362 Minor,
4363}
4364
4365impl<'a> lua_gc::Trace for CollectRoots<'a> {
4366 fn trace(&self, m: &mut lua_gc::Marker) {
4367 self.global.trace(m);
4368 self.thread.trace(m);
4369 }
4370}
4371
4372#[derive(Clone, Copy)]
4373enum BarrierKind {
4374 Forward,
4375 Backward,
4376}
4377
4378fn barrier_lua_value<P>(
4379 heap: &lua_gc::Heap,
4380 parent: GcRef<P>,
4381 child: &LuaValue,
4382 generational: bool,
4383 kind: BarrierKind,
4384) where
4385 P: lua_gc::Trace + 'static,
4386{
4387 if !child.is_collectable() {
4388 return;
4389 }
4390 if generational && matches!(kind, BarrierKind::Backward) {
4391 heap.generational_backward_barrier(parent.0);
4392 }
4393 match child {
4394 LuaValue::Str(c) => barrier_gc_child(heap, parent, *c, generational, kind),
4395 LuaValue::Table(c) => barrier_gc_child(heap, parent, *c, generational, kind),
4396 LuaValue::Function(LuaClosure::Lua(c)) => {
4397 barrier_gc_child(heap, parent, *c, generational, kind)
4398 }
4399 LuaValue::Function(LuaClosure::C(c)) => {
4400 barrier_gc_child(heap, parent, *c, generational, kind)
4401 }
4402 LuaValue::UserData(c) => barrier_gc_child(heap, parent, *c, generational, kind),
4403 LuaValue::Thread(c) => barrier_gc_child(heap, parent, *c, generational, kind),
4404 LuaValue::Nil
4405 | LuaValue::Bool(_)
4406 | LuaValue::Int(_)
4407 | LuaValue::Float(_)
4408 | LuaValue::LightUserData(_)
4409 | LuaValue::Function(LuaClosure::LightC(_)) => {}
4410 }
4411}
4412
4413fn barrier_gc_child<P, C>(
4414 heap: &lua_gc::Heap,
4415 parent: GcRef<P>,
4416 child: GcRef<C>,
4417 generational: bool,
4418 kind: BarrierKind,
4419) where
4420 P: lua_gc::Trace + 'static,
4421 C: lua_gc::Trace + 'static,
4422{
4423 if generational && matches!(kind, BarrierKind::Forward) {
4424 heap.generational_forward_barrier(parent.0, child.0);
4425 } else if matches!(kind, BarrierKind::Backward) {
4426 heap.barrier_back(parent.0, child.0);
4427 } else {
4428 heap.barrier(parent.0, child.0);
4429 }
4430}
4431
4432fn barrier_child_any<P>(
4433 heap: &lua_gc::Heap,
4434 parent: GcRef<P>,
4435 child: &dyn std::any::Any,
4436 generational: bool,
4437 kind: BarrierKind,
4438) where
4439 P: lua_gc::Trace + 'static,
4440{
4441 if let Some(v) = child.downcast_ref::<LuaValue>() {
4442 barrier_lua_value(heap, parent, v, generational, kind);
4443 } else if let Some(c) = child.downcast_ref::<GcRef<LuaString>>() {
4444 barrier_gc_child(heap, parent, c.clone(), generational, kind);
4445 } else if let Some(c) = child.downcast_ref::<GcRef<LuaTable>>() {
4446 barrier_gc_child(heap, parent, c.clone(), generational, kind);
4447 } else if let Some(c) = child.downcast_ref::<GcRef<LuaClosureLua>>() {
4448 barrier_gc_child(heap, parent, c.clone(), generational, kind);
4449 } else if let Some(c) = child.downcast_ref::<GcRef<LuaClosureC>>() {
4450 barrier_gc_child(heap, parent, c.clone(), generational, kind);
4451 } else if let Some(c) = child.downcast_ref::<GcRef<LuaUserData>>() {
4452 barrier_gc_child(heap, parent, c.clone(), generational, kind);
4453 } else if let Some(c) = child.downcast_ref::<GcRef<lua_types::value::LuaThread>>() {
4454 barrier_gc_child(heap, parent, c.clone(), generational, kind);
4455 } else if let Some(c) = child.downcast_ref::<GcRef<LuaProto>>() {
4456 barrier_gc_child(heap, parent, c.clone(), generational, kind);
4457 } else if let Some(c) = child.downcast_ref::<GcRef<UpVal>>() {
4458 barrier_gc_child(heap, parent, c.clone(), generational, kind);
4459 }
4460}
4461
4462fn barrier_any(
4463 heap: &lua_gc::Heap,
4464 parent: &dyn std::any::Any,
4465 child: &dyn std::any::Any,
4466 generational: bool,
4467 kind: BarrierKind,
4468) {
4469 if let Some(v) = parent.downcast_ref::<LuaValue>() {
4470 match v {
4471 LuaValue::Str(p) => barrier_child_any(heap, *p, child, generational, kind),
4472 LuaValue::Table(p) => barrier_child_any(heap, *p, child, generational, kind),
4473 LuaValue::Function(LuaClosure::Lua(p)) => {
4474 barrier_child_any(heap, *p, child, generational, kind)
4475 }
4476 LuaValue::Function(LuaClosure::C(p)) => {
4477 barrier_child_any(heap, *p, child, generational, kind)
4478 }
4479 LuaValue::UserData(p) => barrier_child_any(heap, *p, child, generational, kind),
4480 LuaValue::Thread(p) => barrier_child_any(heap, *p, child, generational, kind),
4481 LuaValue::Nil
4482 | LuaValue::Bool(_)
4483 | LuaValue::Int(_)
4484 | LuaValue::Float(_)
4485 | LuaValue::LightUserData(_)
4486 | LuaValue::Function(LuaClosure::LightC(_)) => {}
4487 }
4488 } else if let Some(p) = parent.downcast_ref::<GcRef<LuaString>>() {
4489 barrier_child_any(heap, p.clone(), child, generational, kind);
4490 } else if let Some(p) = parent.downcast_ref::<GcRef<LuaTable>>() {
4491 barrier_child_any(heap, p.clone(), child, generational, kind);
4492 } else if let Some(p) = parent.downcast_ref::<GcRef<LuaClosureLua>>() {
4493 barrier_child_any(heap, p.clone(), child, generational, kind);
4494 } else if let Some(p) = parent.downcast_ref::<GcRef<LuaClosureC>>() {
4495 barrier_child_any(heap, p.clone(), child, generational, kind);
4496 } else if let Some(p) = parent.downcast_ref::<GcRef<LuaUserData>>() {
4497 barrier_child_any(heap, p.clone(), child, generational, kind);
4498 } else if let Some(p) = parent.downcast_ref::<GcRef<lua_types::value::LuaThread>>() {
4499 barrier_child_any(heap, p.clone(), child, generational, kind);
4500 } else if let Some(p) = parent.downcast_ref::<GcRef<LuaProto>>() {
4501 barrier_child_any(heap, p.clone(), child, generational, kind);
4502 } else if let Some(p) = parent.downcast_ref::<GcRef<UpVal>>() {
4503 barrier_child_any(heap, p.clone(), child, generational, kind);
4504 }
4505}
4506
4507fn trace_reachable_threads(
4519 global: &GlobalState,
4520 _current_thread_id: u64,
4521 marker: &mut lua_gc::Marker,
4522) {
4523 use lua_gc::Trace;
4524
4525 #[cfg(debug_assertions)]
4526 let mut uncovered_borrowed: Vec<u64> = Vec::new();
4527
4528 loop {
4529 let visited_before = marker.visited_count();
4530 for (id, entry) in global.threads.iter() {
4531 if thread_entry_marked_alive(marker, *id, entry) {
4532 match entry.state.try_borrow() {
4533 Ok(thread) => thread.trace(marker),
4534 Err(_) => {
4535 #[cfg(debug_assertions)]
4536 if *id != _current_thread_id && !uncovered_borrowed.contains(id) {
4537 uncovered_borrowed.push(*id);
4538 }
4539 }
4540 }
4541 }
4542 }
4543 marker.drain_gray_queue();
4544 if marker.visited_count() == visited_before {
4545 break;
4546 }
4547 }
4548
4549 remark_legacy_open_upvalues(global, marker);
4550
4551 #[cfg(debug_assertions)]
4552 debug_assert!(
4553 uncovered_borrowed.len() <= global.suspended_parent_stacks.len(),
4554 "GC root loss: {} marked-alive coroutine(s) (ids {:?}) were mutably \
4555 borrowed at collect time with only {} parent snapshot(s) covering \
4556 them — their stacks were NOT traced this cycle, so anything only \
4557 reachable from them will be swept (issue #140 bug-A class). A borrow \
4558 of a coroutine's state must not be held across an allocation \
4559 checkpoint without pushing a parent GC snapshot.",
4560 uncovered_borrowed.len(),
4561 uncovered_borrowed,
4562 global.suspended_parent_stacks.len()
4563 );
4564}
4565
4566fn remark_legacy_open_upvalues(global: &GlobalState, marker: &mut lua_gc::Marker) {
4586 use lua_gc::Trace;
4587
4588 let legacy = matches!(
4589 global.lua_version,
4590 lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
4591 );
4592 if !legacy {
4593 return;
4594 }
4595
4596 let mut remarked_any = false;
4597 for (id, entry) in global.threads.iter() {
4598 if entry.value.id != *id {
4599 continue;
4600 }
4601 if thread_entry_marked_alive(marker, *id, entry) {
4602 continue;
4603 }
4604 let Ok(thread) = entry.state.try_borrow() else {
4605 continue;
4606 };
4607 if thread.openupval.is_empty() || !thread.legacy_open_upval_touched.get() {
4608 continue;
4609 }
4610 thread.legacy_open_upval_touched.set(false);
4611 for uv in thread.openupval.iter() {
4612 let Some((_tid, idx)) = uv.try_open_payload() else {
4613 continue;
4614 };
4615 let slot = idx.0 as usize;
4616 if slot < thread.stack.len() {
4617 thread.stack[slot].val.trace(marker);
4618 remarked_any = true;
4619 }
4620 }
4621 }
4622
4623 if !remarked_any {
4624 return;
4625 }
4626 marker.drain_gray_queue();
4627
4628 loop {
4629 let visited_before = marker.visited_count();
4630 for (id, entry) in global.threads.iter() {
4631 if thread_entry_marked_alive(marker, *id, entry) {
4632 if let Ok(thread) = entry.state.try_borrow() {
4633 thread.trace(marker);
4634 }
4635 }
4636 }
4637 marker.drain_gray_queue();
4638 if marker.visited_count() == visited_before {
4639 break;
4640 }
4641 }
4642}
4643
4644fn thread_entry_marked_alive(
4645 marker: &lua_gc::Marker,
4646 id: u64,
4647 entry: &ThreadRegistryEntry,
4648) -> bool {
4649 marker.is_marked_or_old(entry.value.0) && entry.value.id == id
4650}
4651
4652fn lua_value_marked_or_old(marker: &lua_gc::Marker, value: &LuaValue) -> bool {
4653 match value {
4654 LuaValue::Str(v) => marker.is_marked_or_old(v.0),
4655 LuaValue::Table(v) => marker.is_marked_or_old(v.0),
4656 LuaValue::Function(LuaClosure::Lua(v)) => marker.is_marked_or_old(v.0),
4657 LuaValue::Function(LuaClosure::C(v)) => marker.is_marked_or_old(v.0),
4658 LuaValue::UserData(v) => marker.is_marked_or_old(v.0),
4659 LuaValue::Thread(v) => marker.is_marked_or_old(v.0),
4660 LuaValue::Nil
4661 | LuaValue::Bool(_)
4662 | LuaValue::Int(_)
4663 | LuaValue::Float(_)
4664 | LuaValue::LightUserData(_)
4665 | LuaValue::Function(LuaClosure::LightC(_)) => true,
4666 }
4667}
4668
4669fn finalizer_marked_or_old(marker: &lua_gc::Marker, object: &FinalizerObject) -> bool {
4670 match object {
4671 FinalizerObject::Table(t) => marker.is_marked_or_old(t.0),
4672 FinalizerObject::UserData(u) => marker.is_marked_or_old(u.0),
4673 }
4674}
4675
4676fn weak_snapshot_tables<'a>(
4677 snapshot: &'a lua_gc::WeakRegistrySnapshot<GcRef<LuaTable>>,
4678) -> impl Iterator<Item = &'a GcRef<LuaTable>> {
4679 snapshot
4680 .weak_values
4681 .iter()
4682 .chain(snapshot.ephemeron.iter())
4683 .chain(snapshot.all_weak.iter())
4684}
4685
4686fn close_open_upvalues_for_unreachable_threads(global: &GlobalState, marker: &mut lua_gc::Marker) {
4687 use lua_gc::Trace;
4688
4689 let mut closed_values = Vec::<LuaValue>::new();
4690 for (id, entry) in global.threads.iter() {
4691 if entry.value.id != *id {
4692 continue;
4693 }
4694 if thread_entry_marked_alive(marker, *id, entry) {
4695 continue;
4696 }
4697 let Ok(thread) = entry.state.try_borrow() else {
4698 continue;
4699 };
4700 for uv in thread.openupval.iter() {
4701 if !marker.is_visited(uv.identity()) {
4702 continue;
4703 }
4704 let Some((thread_id, idx)) = uv.try_open_payload() else {
4705 continue;
4706 };
4707 if thread_id != *id {
4708 continue;
4709 }
4710 let value = thread.get_at(idx);
4711 uv.close_with(value.clone());
4712 closed_values.push(value);
4713 }
4714 }
4715 for value in closed_values {
4716 value.trace(marker);
4717 }
4718 marker.drain_gray_queue();
4719}
4720
4721fn record_dead_interned_strings(
4728 global: &GlobalState,
4729 marker: &lua_gc::Marker,
4730 dead_pairs: &std::cell::RefCell<Vec<(u32, usize)>>,
4731) {
4732 let mut dead = dead_pairs.borrow_mut();
4733 for s in global.interned_lt.iter() {
4734 let id = s.identity();
4735 if !marker.is_visited(id) {
4736 dead.push((s.hash(), id));
4737 }
4738 }
4739}
4740
4741fn remove_dead_interned_strings(global: &mut GlobalState, dead_pairs: Vec<(u32, usize)>) {
4753 for (hash, id) in dead_pairs {
4754 global.interned_lt.remove(hash, id);
4755 }
4756 global.interned_lt.shrink_if_sparse();
4757}
4758
4759impl<'a> GcHandle<'a> {
4760 pub fn check_step(&self) {
4765 if !self._state.global().is_gc_running() {
4766 return;
4767 }
4768 if self._state.global().is_gen_mode() {
4769 let should_collect = {
4770 let g = self._state.global();
4771 g.heap.would_collect() || g.gc_debt() > 0
4772 };
4773 if should_collect {
4774 self.generational_step();
4775 }
4776 } else {
4777 self.collect_via_heap(false);
4778 }
4779 }
4780
4781 pub fn full_collect(&self) {
4782 if self._state.global().is_gen_mode() {
4783 self.fullgen();
4784 } else {
4785 self.collect_via_heap(true);
4786 }
4787 }
4788
4789 fn negative_debt(bytes: usize) -> isize {
4790 -(bytes.min(isize::MAX as usize) as isize)
4791 }
4792
4793 fn set_minor_debt(&self) {
4794 let mut g = self._state.global_mut();
4795 let total = g.total_bytes();
4796 let growth = (total / 100).saturating_mul(g.genminormul as usize);
4797 g.heap
4798 .set_threshold_bytes(total.saturating_add(growth.max(1)));
4799 set_debt(&mut *g, Self::negative_debt(growth));
4800 }
4801
4802 fn set_pause_debt(&self) {
4803 let mut g = self._state.global_mut();
4804 let total = g.total_bytes();
4805 let pause = g.gc_pause_param().max(0) as usize;
4806 let threshold = g.gc_estimate.max(1).saturating_mul(pause) / 100;
4807 let debt = if threshold > total {
4808 Self::negative_debt(threshold - total)
4809 } else {
4810 0
4811 };
4812 let heap_threshold = if threshold > total {
4813 threshold
4814 } else {
4815 total.saturating_add(1)
4816 };
4817 g.heap.set_threshold_bytes(heap_threshold);
4818 set_debt(&mut *g, debt);
4819 }
4820
4821 fn enter_incremental_mode(&self) {
4822 let mut g = self._state.global_mut();
4823 g.heap.reset_all_ages();
4824 g.finalizers.reset_generation_boundaries();
4825 g.gckind = GcKind::Incremental as u8;
4826 g.lastatomic = 0;
4827 }
4828
4829 fn enter_generational_mode(&self) -> usize {
4830 self.collect_via_heap_mode(HeapCollectMode::Full);
4831 let numobjs = {
4832 let mut g = self._state.global_mut();
4833 g.heap.promote_all_to_old();
4834 g.finalizers.promote_all_pending_to_old();
4835 g.heap.allgc_count()
4836 };
4837 let total = self._state.global().total_bytes();
4838 {
4839 let mut g = self._state.global_mut();
4840 g.gckind = GcKind::Generational as u8;
4841 g.lastatomic = 0;
4842 g.gc_estimate = total;
4843 }
4844 self.set_minor_debt();
4845 numobjs
4846 }
4847
4848 fn fullgen(&self) -> usize {
4849 self.enter_incremental_mode();
4850 self.enter_generational_mode()
4851 }
4852
4853 fn stepgenfull(&self, lastatomic: usize) {
4854 if self._state.global().gckind == GcKind::Generational as u8 {
4855 self.enter_incremental_mode();
4856 }
4857 self.collect_via_heap_mode(HeapCollectMode::Full);
4858 let newatomic = self._state.global().heap.allgc_count().max(1);
4859 if newatomic < lastatomic.saturating_add(lastatomic >> 3) {
4860 {
4861 let mut g = self._state.global_mut();
4862 g.heap.promote_all_to_old();
4863 g.finalizers.promote_all_pending_to_old();
4864 }
4865 let total = self._state.global().total_bytes();
4866 {
4867 let mut g = self._state.global_mut();
4868 g.gckind = GcKind::Generational as u8;
4869 g.lastatomic = 0;
4870 g.gc_estimate = total;
4871 }
4872 self.set_minor_debt();
4873 } else {
4874 {
4875 let mut g = self._state.global_mut();
4876 g.heap.reset_all_ages();
4877 g.finalizers.reset_generation_boundaries();
4878 }
4879 let total = self._state.global().total_bytes();
4880 {
4881 let mut g = self._state.global_mut();
4882 g.gckind = GcKind::Incremental as u8;
4883 g.lastatomic = newatomic;
4884 g.gc_estimate = total;
4885 }
4886 self.set_pause_debt();
4887 }
4888 }
4889
4890 fn collect_via_heap(&self, force: bool) {
4899 self.collect_via_heap_mode(if force {
4900 HeapCollectMode::Full
4901 } else {
4902 HeapCollectMode::Step
4903 });
4904 }
4905
4906 fn collect_via_heap_mode(&self, mode: HeapCollectMode) {
4907 use lua_gc::Trace;
4908 let state_ref: &LuaState = &*self._state;
4909
4910 if matches!(mode, HeapCollectMode::Step) {
4916 let g = state_ref.global.borrow();
4917 if !g.heap.would_collect() {
4918 return;
4919 }
4920 }
4921
4922 let weak_tables_snapshot: lua_gc::WeakRegistrySnapshot<GcRef<LuaTable>> = {
4926 let mut g = state_ref.global.borrow_mut();
4927 g.weak_tables_registry.live_snapshot_by_kind()
4928 };
4929
4930 let weak_table_capacity = weak_tables_snapshot.len();
4935 let (pending_snapshot, thread_capacity, _interned_capacity): (
4936 Vec<FinalizerObject>,
4937 usize,
4938 usize,
4939 ) = {
4940 let g = state_ref.global.borrow();
4941 let pending = match mode {
4942 HeapCollectMode::Minor => g.finalizers.pending_minor_snapshot(),
4943 HeapCollectMode::Full | HeapCollectMode::Step => g.finalizers.pending_snapshot(),
4944 };
4945 (pending, g.threads.len(), g.interned_lt.len())
4946 };
4947 let finalizer_capacity = pending_snapshot.len();
4948
4949 let alive_ids: std::cell::RefCell<std::collections::HashSet<usize>> =
4950 std::cell::RefCell::new(std::collections::HashSet::new());
4951 let newly_unreachable: std::cell::RefCell<Vec<FinalizerObject>> =
4952 std::cell::RefCell::new(Vec::new());
4953 let alive_thread_ids: std::cell::RefCell<std::collections::HashSet<u64>> =
4954 std::cell::RefCell::new(std::collections::HashSet::new());
4955 let alive_closure_env_ids: std::cell::RefCell<std::collections::HashSet<usize>> =
4956 std::cell::RefCell::new(std::collections::HashSet::new());
4957 let dead_interned: std::cell::RefCell<Vec<(u32, usize)>> = std::cell::RefCell::new(Vec::new());
4958 let collect_ran = std::cell::Cell::new(false);
4959
4960 {
4961 let global = state_ref.global.borrow();
4962 global.heap.unpause();
4963 let roots = CollectRoots {
4964 global: &*global,
4965 thread: state_ref,
4966 };
4967 let hook = |marker: &mut lua_gc::Marker| {
4968 collect_ran.set(true);
4969 alive_ids.borrow_mut().reserve(weak_table_capacity);
4970 newly_unreachable.borrow_mut().reserve(finalizer_capacity);
4971 alive_thread_ids.borrow_mut().reserve(thread_capacity);
4972 trace_reachable_threads(&*global, global.current_thread_id, marker);
4973 close_open_upvalues_for_unreachable_threads(&*global, marker);
4974 let legacy_weak_key_values =
4981 matches!(global.lua_version, lua_types::LuaVersion::V51);
4982 loop {
4983 let visited_before = marker.visited_count();
4984 for t in &weak_tables_snapshot.ephemeron {
4985 if !marker.is_marked_or_old(t.0) {
4986 continue;
4987 }
4988 if legacy_weak_key_values {
4989 let mut to_mark = Vec::new();
4990 t.for_each_entry(|_k, v| to_mark.push(v.clone()));
4991 for v in &to_mark {
4992 v.trace(marker);
4993 }
4994 } else {
4995 let to_mark = t.ephemeron_values_to_mark_with_value(&|v| {
4996 lua_value_marked_or_old(marker, v)
4997 });
4998 for v in &to_mark {
4999 v.trace(marker);
5000 }
5001 }
5002 }
5003 marker.drain_gray_queue();
5004 if marker.visited_count() == visited_before {
5005 break;
5006 }
5007 }
5008 for t in weak_tables_snapshot
5028 .weak_values
5029 .iter()
5030 .chain(weak_tables_snapshot.all_weak.iter())
5031 {
5032 let to_mark = t.prune_weak_dead_with_value(
5033 &|_| true,
5034 &|v| lua_value_marked_or_old(marker, v),
5035 );
5036 if marker.is_marked_or_old(t.0) {
5037 for v in &to_mark {
5038 v.trace(marker);
5039 }
5040 }
5041 }
5042 marker.drain_gray_queue();
5043 for pf in &pending_snapshot {
5044 if !finalizer_marked_or_old(marker, pf) {
5045 pf.mark(marker);
5046 newly_unreachable.borrow_mut().push(pf.clone());
5047 }
5048 }
5049 marker.drain_gray_queue();
5050 loop {
5051 let visited_before = marker.visited_count();
5052 for t in &weak_tables_snapshot.ephemeron {
5053 if !marker.is_marked_or_old(t.0) {
5054 continue;
5055 }
5056 if legacy_weak_key_values {
5057 let mut to_mark = Vec::new();
5058 t.for_each_entry(|_k, v| to_mark.push(v.clone()));
5059 for v in &to_mark {
5060 v.trace(marker);
5061 }
5062 } else {
5063 let to_mark = t.ephemeron_values_to_mark_with_value(&|v| {
5064 lua_value_marked_or_old(marker, v)
5065 });
5066 for v in &to_mark {
5067 v.trace(marker);
5068 }
5069 }
5070 }
5071 marker.drain_gray_queue();
5072 if marker.visited_count() == visited_before {
5073 break;
5074 }
5075 }
5076 for t in weak_tables_snapshot
5089 .ephemeron
5090 .iter()
5091 .chain(weak_tables_snapshot.all_weak.iter())
5092 {
5093 if !marker.is_marked_or_old(t.0) {
5094 continue;
5095 }
5096 let to_mark = t.prune_weak_dead_with_value(
5097 &|v| lua_value_marked_or_old(marker, v),
5098 &|_| true,
5099 );
5100 for v in &to_mark {
5101 v.trace(marker);
5102 }
5103 }
5104 for t in weak_snapshot_tables(&weak_tables_snapshot) {
5105 if marker.is_marked_or_old(t.0) {
5106 alive_ids.borrow_mut().insert(t.identity());
5107 }
5108 }
5109 marker.drain_gray_queue();
5110 {
5111 let mut alive = alive_thread_ids.borrow_mut();
5112 for (id, entry) in global.threads.iter() {
5113 if thread_entry_marked_alive(marker, *id, entry) {
5114 alive.insert(*id);
5115 }
5116 }
5117 }
5118 {
5119 let mut alive = alive_closure_env_ids.borrow_mut();
5120 for id in global.closure_envs.keys() {
5121 if marker.is_visited(*id) {
5122 alive.insert(*id);
5123 }
5124 }
5125 }
5126 record_dead_interned_strings(&*global, marker, &dead_interned);
5127 };
5128 match mode {
5129 HeapCollectMode::Full => global.heap.full_collect_with_post_mark(&roots, hook),
5130 HeapCollectMode::Step => global.heap.step_with_post_mark(&roots, hook),
5131 HeapCollectMode::Minor => global.heap.minor_collect_with_post_mark(&roots, hook),
5132 }
5133 }
5134
5135 if !collect_ran.get() {
5136 return;
5137 }
5138
5139 let alive_set = alive_ids.into_inner();
5143 let promote: Vec<FinalizerObject> = newly_unreachable.into_inner();
5144 let alive_thread_ids = alive_thread_ids.into_inner();
5145 let alive_closure_env_ids = alive_closure_env_ids.into_inner();
5146 let dead_interned = dead_interned.into_inner();
5147 let mut g = state_ref.global.borrow_mut();
5148 remove_dead_interned_strings(&mut *g, dead_interned);
5149 g.weak_tables_registry.retain_identities(&alive_set);
5150 let main_thread_id = g.main_thread_id;
5151 g.threads.retain(|id, _| alive_thread_ids.contains(id));
5152 g.cross_thread_upvals
5153 .retain(|(id, _), _| *id == main_thread_id || alive_thread_ids.contains(id));
5154 g.thread_globals
5158 .retain(|id, _| alive_thread_ids.contains(id));
5159 g.closure_envs
5160 .retain(|id, _| alive_closure_env_ids.contains(id));
5161 let promoted = g.finalizers.promote_pending_to_finalized(promote);
5165 for object in &promoted {
5166 if let Some(ptr) = object.heap_ptr() {
5167 g.heap.move_finobj_to_tobefnz(ptr);
5168 }
5169 }
5170 if matches!(mode, HeapCollectMode::Minor) {
5171 g.finalizers.finish_minor_collection();
5172 }
5173 }
5174
5175 pub fn generational_step(&self) -> bool {
5177 self.generational_step_with_major(true)
5178 }
5179
5180 pub fn generational_step_minor_only(&self) -> bool {
5186 self.generational_step_with_major(false)
5187 }
5188
5189 fn generational_step_with_major(&self, allow_major: bool) -> bool {
5190 let (lastatomic, majorbase, majorinc, should_major) = {
5191 let g = self._state.global();
5192 let majorbase = if g.gc_estimate == 0 {
5193 g.total_bytes()
5194 } else {
5195 g.gc_estimate
5196 };
5197 let majormul = g.gc_genmajormul_param().max(0) as usize;
5198 let majorinc = (majorbase / 100).saturating_mul(majormul);
5199 let debt_due = g.gc_debt() > 0 || g.heap.would_collect();
5200 let should_major =
5201 allow_major && debt_due && g.total_bytes() > majorbase.saturating_add(majorinc);
5202 (g.lastatomic, majorbase, majorinc, should_major)
5203 };
5204
5205 if lastatomic != 0 {
5206 self.stepgenfull(lastatomic);
5207 debug_assert!(self._state.global().is_gen_mode());
5208 return true;
5209 }
5210
5211 if should_major {
5212 let numobjs = self.fullgen();
5213 let after = self._state.global().total_bytes();
5214 if after < majorbase.saturating_add(majorinc / 2) {
5215 self.set_minor_debt();
5216 } else {
5217 {
5218 let mut g = self._state.global_mut();
5219 g.lastatomic = numobjs.max(1);
5220 }
5221 self.set_pause_debt();
5222 }
5223 } else {
5224 self.collect_via_heap_mode(HeapCollectMode::Minor);
5225 self.set_minor_debt();
5226 self._state.global_mut().gc_estimate = majorbase;
5227 }
5228
5229 debug_assert!(self._state.global().is_gen_mode());
5230 true
5231 }
5232
5233 pub fn step(&self) { }
5237
5238 pub fn incremental_step(&self, work_units: isize) -> bool {
5251 self.incremental_step_to_state(work_units, None)
5252 }
5253
5254 pub fn run_until_gc_state_for_test(&self, target: lua_gc::GcState) -> bool {
5259 self.incremental_step_to_state(isize::MAX / 4, Some(target));
5260 self._state.global().heap.gc_state() == target
5261 }
5262
5263 fn incremental_step_to_state(
5264 &self,
5265 work_units: isize,
5266 target: Option<lua_gc::GcState>,
5267 ) -> bool {
5268 use lua_gc::{StepBudget, StepOutcome, Trace};
5269 let state_ref: &LuaState = &*self._state;
5270
5271 let weak_tables_snapshot: lua_gc::WeakRegistrySnapshot<GcRef<LuaTable>> = {
5272 let mut g = state_ref.global.borrow_mut();
5273 g.weak_tables_registry.live_snapshot_by_kind()
5274 };
5275
5276 let weak_table_capacity = weak_tables_snapshot.len();
5277 let (pending_snapshot, thread_capacity, _interned_capacity): (
5278 Vec<FinalizerObject>,
5279 usize,
5280 usize,
5281 ) = {
5282 let g = state_ref.global.borrow();
5283 (
5284 g.finalizers.pending_snapshot(),
5285 g.threads.len(),
5286 g.interned_lt.len(),
5287 )
5288 };
5289 let finalizer_capacity = pending_snapshot.len();
5290
5291 let alive_ids: std::cell::RefCell<std::collections::HashSet<usize>> =
5292 std::cell::RefCell::new(std::collections::HashSet::new());
5293 let newly_unreachable: std::cell::RefCell<Vec<FinalizerObject>> =
5294 std::cell::RefCell::new(Vec::new());
5295 let alive_thread_ids: std::cell::RefCell<std::collections::HashSet<u64>> =
5296 std::cell::RefCell::new(std::collections::HashSet::new());
5297 let alive_closure_env_ids: std::cell::RefCell<std::collections::HashSet<usize>> =
5298 std::cell::RefCell::new(std::collections::HashSet::new());
5299 let dead_interned: std::cell::RefCell<Vec<(u32, usize)>> = std::cell::RefCell::new(Vec::new());
5300 let atomic_ran = std::cell::Cell::new(false);
5301
5302 let stop_target = {
5303 let g = state_ref.global.borrow();
5304 match (target, g.heap.gc_state()) {
5305 (Some(target), _) => Some(target),
5306 (None, lua_gc::GcState::CallFin) => None,
5307 (None, _) => Some(lua_gc::GcState::CallFin),
5308 }
5309 };
5310
5311 let outcome = {
5312 let global = state_ref.global.borrow();
5313 global.heap.unpause();
5314 let roots = CollectRoots {
5315 global: &*global,
5316 thread: state_ref,
5317 };
5318 let hook = |marker: &mut lua_gc::Marker| {
5319 atomic_ran.set(true);
5320 alive_ids.borrow_mut().reserve(weak_table_capacity);
5321 newly_unreachable.borrow_mut().reserve(finalizer_capacity);
5322 alive_thread_ids.borrow_mut().reserve(thread_capacity);
5323 trace_reachable_threads(&*global, global.current_thread_id, marker);
5324 close_open_upvalues_for_unreachable_threads(&*global, marker);
5325 let legacy_weak_key_values =
5329 matches!(global.lua_version, lua_types::LuaVersion::V51);
5330 loop {
5331 let visited_before = marker.visited_count();
5332 for t in &weak_tables_snapshot.ephemeron {
5333 let t_id = t.identity();
5334 if !marker.is_visited(t_id) {
5335 continue;
5336 }
5337 if legacy_weak_key_values {
5338 let mut to_mark = Vec::new();
5339 t.for_each_entry(|_k, v| to_mark.push(v.clone()));
5340 for v in &to_mark {
5341 v.trace(marker);
5342 }
5343 } else {
5344 let to_mark = t.ephemeron_values_to_mark(&|id| marker.is_visited(id));
5345 for v in &to_mark {
5346 v.trace(marker);
5347 }
5348 }
5349 }
5350 marker.drain_gray_queue();
5351 if marker.visited_count() == visited_before {
5352 break;
5353 }
5354 }
5355 for t in weak_tables_snapshot
5368 .weak_values
5369 .iter()
5370 .chain(weak_tables_snapshot.all_weak.iter())
5371 {
5372 let to_mark =
5373 t.prune_weak_dead_with(&|_| true, &|id| marker.is_visited(id));
5374 if marker.is_visited(t.identity()) {
5375 for v in &to_mark {
5376 v.trace(marker);
5377 }
5378 }
5379 }
5380 marker.drain_gray_queue();
5381 for pf in &pending_snapshot {
5382 if !marker.is_visited(pf.identity()) {
5383 pf.mark(marker);
5384 newly_unreachable.borrow_mut().push(pf.clone());
5385 }
5386 }
5387 marker.drain_gray_queue();
5388 loop {
5389 let visited_before = marker.visited_count();
5390 for t in &weak_tables_snapshot.ephemeron {
5391 let t_id = t.identity();
5392 if !marker.is_visited(t_id) {
5393 continue;
5394 }
5395 if legacy_weak_key_values {
5396 let mut to_mark = Vec::new();
5397 t.for_each_entry(|_k, v| to_mark.push(v.clone()));
5398 for v in &to_mark {
5399 v.trace(marker);
5400 }
5401 } else {
5402 let to_mark = t.ephemeron_values_to_mark(&|id| marker.is_visited(id));
5403 for v in &to_mark {
5404 v.trace(marker);
5405 }
5406 }
5407 }
5408 marker.drain_gray_queue();
5409 if marker.visited_count() == visited_before {
5410 break;
5411 }
5412 }
5413 for t in weak_tables_snapshot
5420 .ephemeron
5421 .iter()
5422 .chain(weak_tables_snapshot.all_weak.iter())
5423 {
5424 if !marker.is_visited(t.identity()) {
5425 continue;
5426 }
5427 let to_mark =
5428 t.prune_weak_dead_with(&|id| marker.is_visited(id), &|_| true);
5429 for v in &to_mark {
5430 v.trace(marker);
5431 }
5432 }
5433 for t in weak_snapshot_tables(&weak_tables_snapshot) {
5434 if marker.is_visited(t.identity()) {
5435 alive_ids.borrow_mut().insert(t.identity());
5436 }
5437 }
5438 marker.drain_gray_queue();
5439 {
5440 let mut alive = alive_thread_ids.borrow_mut();
5441 for (id, entry) in global.threads.iter() {
5442 if thread_entry_marked_alive(marker, *id, entry) {
5443 alive.insert(*id);
5444 }
5445 }
5446 }
5447 {
5448 let mut alive = alive_closure_env_ids.borrow_mut();
5449 for id in global.closure_envs.keys() {
5450 if marker.is_visited(*id) {
5451 alive.insert(*id);
5452 }
5453 }
5454 }
5455 record_dead_interned_strings(&*global, marker, &dead_interned);
5456 };
5457 let budget = StepBudget::from_work(work_units);
5458 if let Some(target) = stop_target {
5459 global
5460 .heap
5461 .incremental_run_until_state_with_post_mark(&roots, target, work_units, hook)
5462 } else {
5463 global
5464 .heap
5465 .incremental_step_with_post_mark(&roots, budget, hook)
5466 }
5467 };
5468
5469 if atomic_ran.get() {
5470 let alive_set = alive_ids.into_inner();
5471 let promote: Vec<FinalizerObject> = newly_unreachable.into_inner();
5472 let alive_thread_ids = alive_thread_ids.into_inner();
5473 let alive_closure_env_ids = alive_closure_env_ids.into_inner();
5474 let dead_interned = dead_interned.into_inner();
5475 let mut g = state_ref.global.borrow_mut();
5476 remove_dead_interned_strings(&mut *g, dead_interned);
5477 g.weak_tables_registry.retain_identities(&alive_set);
5478 let main_thread_id = g.main_thread_id;
5479 g.threads.retain(|id, _| alive_thread_ids.contains(id));
5480 g.cross_thread_upvals
5481 .retain(|(id, _), _| *id == main_thread_id || alive_thread_ids.contains(id));
5482 g.thread_globals
5486 .retain(|id, _| alive_thread_ids.contains(id));
5487 g.closure_envs
5488 .retain(|id, _| alive_closure_env_ids.contains(id));
5489 let promoted = g.finalizers.promote_pending_to_finalized(promote);
5490 for object in &promoted {
5491 if let Some(ptr) = object.heap_ptr() {
5492 g.heap.move_finobj_to_tobefnz(ptr);
5493 }
5494 }
5495 }
5496
5497 let mut paused = matches!(outcome, StepOutcome::Paused);
5498 if target.is_none()
5499 && self._state.global().heap.gc_state() == lua_gc::GcState::CallFin
5500 && !self._state.global().finalizers.has_to_be_finalized()
5501 {
5502 paused = self._state.global().heap.finish_callfin_phase();
5503 }
5504
5505 paused
5506 }
5507
5508 pub fn prune_weak_tables_mark_only(&self) {
5515 use lua_gc::Trace;
5516 let state_ref: &LuaState = &*self._state;
5517
5518 let weak_tables_snapshot: lua_gc::WeakRegistrySnapshot<GcRef<LuaTable>> = {
5519 let mut g = state_ref.global.borrow_mut();
5520 g.weak_tables_registry.live_snapshot_by_kind()
5521 };
5522 let _interned_capacity = {
5523 let g = state_ref.global.borrow();
5524 g.interned_lt.len()
5525 };
5526
5527 let dead_interned: std::cell::RefCell<Vec<(u32, usize)>> = std::cell::RefCell::new(Vec::new());
5528
5529 {
5530 let global = state_ref.global.borrow();
5531 global.heap.unpause();
5532 let roots = CollectRoots {
5533 global: &*global,
5534 thread: state_ref,
5535 };
5536 let hook = |marker: &mut lua_gc::Marker| {
5537 trace_reachable_threads(&*global, global.current_thread_id, marker);
5538 loop {
5539 let visited_before = marker.visited_count();
5540 for t in &weak_tables_snapshot.ephemeron {
5541 let t_id = t.identity();
5542 if !marker.is_visited(t_id) {
5543 continue;
5544 }
5545 let to_mark = t.ephemeron_values_to_mark(&|id| marker.is_visited(id));
5546 for v in &to_mark {
5547 v.trace(marker);
5548 }
5549 }
5550 marker.drain_gray_queue();
5551 if marker.visited_count() == visited_before {
5552 break;
5553 }
5554 }
5555 for t in weak_snapshot_tables(&weak_tables_snapshot) {
5556 if marker.is_visited(t.identity()) {
5557 let to_mark = t.prune_weak_dead(&|id| marker.is_visited(id));
5558 for v in &to_mark {
5559 v.trace(marker);
5560 }
5561 }
5562 }
5563 marker.drain_gray_queue();
5564 record_dead_interned_strings(&*global, marker, &dead_interned);
5565 };
5566 global.heap.mark_only_with_post_mark(&roots, hook);
5567 }
5568
5569 let dead_interned = dead_interned.into_inner();
5570 let mut g = state_ref.global.borrow_mut();
5571 remove_dead_interned_strings(&mut *g, dead_interned);
5572 }
5573
5574 pub fn change_mode(&self, mode: GcKind) {
5576 let old = self._state.global().gckind;
5577 if old == mode as u8 {
5578 self._state.global_mut().lastatomic = 0;
5579 return;
5580 }
5581 match mode {
5582 GcKind::Generational => {
5583 self.enter_generational_mode();
5584 }
5585 GcKind::Incremental => {
5586 self.enter_incremental_mode();
5587 }
5588 }
5589 }
5590
5591 pub fn fix_object<T: lua_gc::Trace + 'static>(&self, _o: &GcRef<T>) { }
5597
5598 pub fn free_all_objects(&self) {
5634 let heap = self._state.global().heap.clone();
5635 {
5636 let _own_heap = lua_gc::HeapGuard::push(&heap);
5637 heap.drop_all();
5638 }
5639 let mut g = self._state.global_mut();
5640 g.weak_tables_registry = lua_gc::WeakRegistry::default();
5641 g.finalizers = lua_gc::FinalizerRegistry::default();
5642 g.external_roots = ExternalRootSet::default();
5643 g.threads.clear();
5644 g.thread_globals.clear();
5645 g.cross_thread_upvals.clear();
5646 g.suspended_parent_stacks.clear();
5647 g.suspended_parent_open_upvals.clear();
5648 g.twups.clear();
5649 }
5650
5651 pub fn barrier(&self, p: &dyn std::any::Any, v: &LuaValue) {
5653 let g = self._state.global();
5654 barrier_any(&g.heap, p, v, g.is_gen_mode(), BarrierKind::Forward);
5655 }
5656
5657 pub fn barrier_back(&self, p: &dyn std::any::Any, v: &LuaValue) {
5659 let g = self._state.global();
5660 barrier_any(&g.heap, p, v, g.is_gen_mode(), BarrierKind::Backward);
5661 }
5662
5663 pub fn table_barrier_back(&self, p: &GcRef<LuaTable>, v: &LuaValue) {
5665 let g = self._state.global();
5666 barrier_lua_value(&g.heap, *p, v, g.is_gen_mode(), BarrierKind::Backward);
5667 }
5668
5669 pub fn obj_barrier(&self, p: &dyn std::any::Any, o: &dyn std::any::Any) {
5671 let g = self._state.global();
5672 barrier_any(&g.heap, p, o, g.is_gen_mode(), BarrierKind::Forward);
5673 }
5674
5675 pub fn obj_barrier_back(&self, p: &dyn std::any::Any, o: &dyn std::any::Any) {
5678 let g = self._state.global();
5679 barrier_any(&g.heap, p, o, g.is_gen_mode(), BarrierKind::Backward);
5680 }
5681}
5682
5683fn make_seed() -> u32 {
5693 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
5694 {
5695 return crate::string::hash_bytes(b"lua-rs-wasm-seed", 0x9e37_79b9);
5696 }
5697
5698 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
5699 {
5700 use std::time::{SystemTime, UNIX_EPOCH};
5701 let t = SystemTime::now()
5702 .duration_since(UNIX_EPOCH)
5703 .map(|d| d.as_secs() as u32)
5704 .unwrap_or(0);
5705
5706 crate::string::hash_bytes(&t.to_le_bytes(), t)
5707 }
5708}
5709
5710pub(crate) fn set_debt(g: &mut GlobalState, mut debt: isize) {
5713 let tb = g.total_bytes() as isize;
5714 debug_assert!(tb > 0);
5715 if debt < tb.saturating_sub(isize::MAX) {
5717 debt = tb - isize::MAX;
5718 }
5719 g.gc_debt = debt;
5720}
5721
5722pub fn set_c_stack_limit(_state: &mut LuaState, _limit: u32) -> i32 {
5724 let _ = (_state, _limit);
5725 LUAI_MAXCCALLS as i32
5726}
5727
5728pub(crate) fn extend_ci(state: &mut LuaState) -> CallInfoIdx {
5730 debug_assert!(
5731 state.call_info[state.ci.0 as usize].next.is_none(),
5732 "extend_ci: current ci already has a cached next frame"
5733 );
5734
5735 let current_idx = state.ci;
5736 let new_idx = CallInfoIdx(state.call_info.len() as u32);
5738
5739 state.call_info.push(CallInfo {
5740 previous: Some(current_idx),
5741 next: None,
5742 u: CallInfoFrame::lua_default(),
5743 ..CallInfo::default()
5744 });
5745
5746 state.call_info[current_idx.0 as usize].next = Some(new_idx);
5747
5748 state.nci += 1;
5749
5750 new_idx
5751}
5752
5753fn free_ci(state: &mut LuaState) {
5761 let ci_idx = state.ci.0 as usize;
5762
5763 let mut next_opt = state.call_info[ci_idx].next.take();
5764
5765 while let Some(idx) = next_opt {
5766 next_opt = state.call_info[idx.0 as usize].next;
5767 state.nci = state.nci.saturating_sub(1);
5768 }
5769
5770 state.call_info.truncate(ci_idx + 1);
5773}
5774
5775pub(crate) fn shrink_ci(state: &mut LuaState) {
5784 let ci_idx = state.ci.0 as usize;
5785
5786 if state.call_info[ci_idx].next.is_none() {
5787 return;
5788 }
5789
5790 let free_count = state.call_info.len().saturating_sub(ci_idx + 1);
5791 if free_count <= 1 {
5792 return;
5793 }
5794
5795 let keep = free_count / 2;
5797 let removed = free_count - keep;
5798 let new_len = ci_idx + 1 + keep;
5799 state.call_info.truncate(new_len);
5800 state.nci = state.nci.saturating_sub(removed as u32);
5801
5802 if let Some(last) = state.call_info.last_mut() {
5804 last.next = None;
5805 }
5806}
5807
5808pub(crate) fn check_c_stack(state: &mut LuaState) -> Result<(), LuaError> {
5810 if state.c_calls() == LUAI_MAXCCALLS {
5812 return Err(LuaError::runtime(format_args!("C stack overflow")));
5813 }
5814 if state.c_calls() >= (LUAI_MAXCCALLS / 10 * 11) {
5816 return Err(LuaError::with_status(LuaStatus::ErrErr));
5817 }
5818 Ok(())
5819}
5820
5821pub fn inc_c_stack(state: &mut LuaState) -> Result<(), LuaError> {
5823 state.n_ccalls += 1;
5824 if state.c_calls() >= LUAI_MAXCCALLS {
5825 check_c_stack(state)?;
5826 }
5827 Ok(())
5828}
5829
5830fn stack_init(thread: &mut LuaState) {
5835 let total_slots = BASIC_STACK_SIZE + EXTRA_STACK;
5836 thread.stack = vec![StackValue::default(); total_slots];
5837
5838 thread.tbclist = Vec::new();
5841
5842 thread.top = StackIdx(0);
5846
5847 thread.stack_last = StackIdx(BASIC_STACK_SIZE as u32);
5848
5849 let base_ci = CallInfo {
5850 func: StackIdx(0),
5851 top: StackIdx(1 + LUA_MINSTACK as u32),
5852 previous: None,
5853 next: None,
5854 callstatus: CIST_C,
5855 call_metamethods: 0,
5856 tailcalls: 0,
5857 nresults: 0,
5858 u: CallInfoFrame::c_default(),
5859 u2: CallInfoExtra::default(),
5860 };
5861
5862 if thread.call_info.is_empty() {
5863 thread.call_info.push(base_ci);
5864 } else {
5865 thread.call_info[0] = base_ci;
5866 thread.call_info.truncate(1);
5867 }
5868
5869 thread.stack[0] = StackValue {
5870 val: LuaValue::Nil,
5871 };
5872
5873 thread.top = StackIdx(1);
5874
5875 thread.ci = CallInfoIdx(0);
5876}
5877
5878fn free_stack(state: &mut LuaState) {
5879 if state.stack.is_empty() {
5880 return;
5881 }
5882 state.ci = CallInfoIdx(0);
5883 free_ci(state);
5884 debug_assert_eq!(state.nci, 0, "nci should be 0 after free_ci");
5885 state.stack.clear();
5886 state.stack.shrink_to_fit();
5887}
5888
5889fn init_registry(state: &mut LuaState) -> Result<(), LuaError> {
5915 let registry = state.new_table();
5916 state.global_mut().l_registry = LuaValue::Table(registry);
5917
5918 let globals = state.new_table();
5919 state.global_mut().globals = LuaValue::Table(globals);
5920 let loaded = state.new_table();
5921 state.global_mut().loaded = LuaValue::Table(loaded);
5922
5923 set_versioned_registry_slots(state)?;
5924
5925 Ok(())
5926}
5927
5928pub fn set_versioned_registry_slots(state: &mut LuaState) -> Result<(), LuaError> {
5961 let registry = match state.global().l_registry.clone() {
5962 LuaValue::Table(t) => t,
5963 _ => return Ok(()),
5964 };
5965 let main_thread = LuaValue::Thread(state.global().main_thread_value.clone());
5966 let globals = state.global().globals.clone();
5967 let version = state.global().lua_version;
5968
5969 for idx in [1i64, LUA_RIDX_GLOBALS, 3] {
5970 let cur = registry.get_int(idx);
5971 if cur == main_thread || cur == globals {
5972 registry.raw_set_int(state, idx, LuaValue::Nil)?;
5973 }
5974 }
5975
5976 match version {
5977 lua_types::LuaVersion::V51 => {}
5978 lua_types::LuaVersion::V55 => {
5979 registry.raw_set_int(state, 1, LuaValue::Bool(false))?;
5980 registry.raw_set_int(state, LUA_RIDX_GLOBALS, globals)?;
5981 registry.raw_set_int(state, 3, main_thread)?;
5982 }
5983 _ => {
5984 registry.raw_set_int(state, LUA_RIDX_MAINTHREAD, main_thread)?;
5985 registry.raw_set_int(state, LUA_RIDX_GLOBALS, globals)?;
5986 }
5987 }
5988 Ok(())
5989}
5990
5991const MEMERR_MSG: &[u8] = b"not enough memory";
5994
5995fn init_memerrmsg(state: &mut LuaState) -> Result<(), LuaError> {
6011 let memerrmsg = state.intern_str(MEMERR_MSG)?;
6012 state.global_mut().memerrmsg = memerrmsg.clone();
6013
6014 for i in 0..STRCACHE_N {
6015 for j in 0..STRCACHE_M {
6016 state.global_mut().strcache[i][j] = memerrmsg.clone();
6017 }
6018 }
6019
6020 Ok(())
6021}
6022
6023fn lua_open(state: &mut LuaState) -> Result<(), LuaError> {
6031 stack_init(state);
6032 init_registry(state)?;
6033 init_memerrmsg(state)?;
6034 crate::tagmethods::init(state)?;
6035 state.global_mut().gcstp = 0;
6036 state.global().heap.unpause();
6037 state.global_mut().nilvalue = LuaValue::Nil;
6039 Ok(())
6040}
6041
6042fn preinit_thread(thread: &mut LuaState, global: Rc<RefCell<GlobalState>>) {
6043 thread.global = global;
6044 thread.stack = Vec::new();
6045 thread.call_info = Vec::new();
6046 thread.ci = CallInfoIdx(0);
6049 thread.nci = 0;
6050 thread.n_ccalls = 0;
6054 thread.hook = None;
6055 thread.hookmask = 0;
6056 thread.basehookcount = 0;
6057 thread.allowhook = true;
6058 thread.hookcount = thread.basehookcount;
6059
6060 {
6065 let (active, interval) = {
6066 let g = thread.global.borrow();
6067 (g.sandbox_active(), g.sandbox.interval.get())
6068 };
6069 if active {
6070 thread.hookmask = SANDBOX_COUNT_MASK;
6071 thread.basehookcount = interval;
6072 thread.hookcount = interval;
6073 }
6074 }
6075 thread.openupval = Vec::new();
6076 thread.status = LuaStatus::Ok as u8;
6077 thread.errfunc = 0;
6078 thread.oldpc = 0;
6079 thread.gc_check_needed = true;
6080}
6081
6082fn close_state(state: &mut LuaState) {
6094 let is_complete = state.global().is_complete();
6095
6096 if !is_complete {
6097 state.gc().free_all_objects();
6098 } else {
6099 state.ci = CallInfoIdx(0);
6100 crate::api::run_close_finalizers(state);
6101 state.gc().free_all_objects();
6102 }
6103
6104 free_stack(state);
6105
6106 }
6109
6110pub fn new_thread(state: &mut LuaState, initial_body: Option<LuaValue>) -> Result<(), LuaError> {
6119 state.gc_pre_collect_clear();
6120 state.gc().check_step();
6121
6122 let global_rc = state.global_rc();
6129 let hookmask = state.hookmask;
6130 let basehookcount = state.basehookcount;
6131
6132 let reserved_id = {
6133 let mut g = state.global_mut();
6134 let id = g.next_thread_id;
6135 g.next_thread_id += 1;
6136 id
6137 };
6138
6139 if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
6145 let creator_id = state.global().current_thread_id;
6146 let creator_lgt = state.v51_thread_lgt(creator_id);
6147 state
6148 .global_mut()
6149 .thread_globals
6150 .insert(reserved_id, creator_lgt);
6151 }
6152
6153 let mut new_thread = LuaState {
6154 status: LuaStatus::Ok as u8,
6155 allowhook: true,
6156 nci: 0,
6157 top: StackIdx(0),
6158 stack_last: StackIdx(0),
6159 stack: Vec::new(),
6160 ci: CallInfoIdx(0),
6161 call_info: Vec::new(),
6162 openupval: Vec::new(),
6163 legacy_open_upval_touched: std::cell::Cell::new(false),
6164 tbclist: Vec::new(),
6165 global: global_rc.clone(),
6166 hook: None,
6167 hookmask: 0,
6168 basehookcount: 0,
6169 hookcount: 0,
6170 errfunc: 0,
6171 n_ccalls: 0,
6172 oldpc: 0,
6173 marked: 0,
6174 cached_thread_id: reserved_id,
6175 gc_check_needed: false,
6176 };
6177
6178 preinit_thread(&mut new_thread, global_rc);
6179
6180 new_thread.hookmask = hookmask;
6181 new_thread.basehookcount = basehookcount;
6182 new_thread.reset_hook_count();
6186
6187 stack_init(&mut new_thread);
6188
6189 if let Some(body) = initial_body {
6190 new_thread.push(body);
6191 }
6192
6193 let thread_ref: Rc<RefCell<LuaState>> = Rc::new(RefCell::new(new_thread));
6194
6195 let value = {
6196 let mut g = state.global_mut();
6197 let id = reserved_id;
6198 let value = GcRef::new(lua_types::value::LuaThread::new(id));
6199 g.threads.insert(
6200 id,
6201 ThreadRegistryEntry {
6202 state: thread_ref,
6203 value: value.clone(),
6204 },
6205 );
6206 value
6207 };
6208
6209 state.push(LuaValue::Thread(value));
6210
6211 Ok(())
6212}
6213
6214pub fn reset_thread(state: &mut LuaState, status: i32) -> i32 {
6235 let _heap_guard = {
6239 let g = state.global.borrow();
6240 lua_gc::HeapGuard::push(&g.heap)
6241 };
6242 state.ci = CallInfoIdx(0);
6243 let ci_idx = 0usize;
6244
6245 if !state.stack.is_empty() {
6246 state.stack[0].val = LuaValue::Nil;
6247 }
6248
6249 state.call_info[ci_idx].func = StackIdx(0);
6250 state.call_info[ci_idx].call_metamethods = 0;
6251 state.call_info[ci_idx].callstatus = CIST_C;
6252
6253 let mut status = if status == LuaStatus::Yield as i32 {
6254 LuaStatus::Ok as i32
6255 } else {
6256 status
6257 };
6258
6259 state.status = LuaStatus::Ok as u8;
6260
6261 let close_status = crate::do_::close_protected(state, StackIdx(1), LuaStatus::from_raw(status));
6262 status = close_status as i32;
6263
6264 if status != LuaStatus::Ok as i32 {
6265 crate::do_::set_error_obj(state, LuaStatus::from_raw(status), StackIdx(1));
6266 } else {
6267 state.top = StackIdx(1);
6268 }
6269
6270 let new_ci_top = StackIdx(state.top.0 + LUA_MINSTACK as u32);
6271 state.call_info[ci_idx].top = new_ci_top;
6272
6273 let _ = crate::do_::realloc_stack(state, new_ci_top.0 as usize, false);
6274 state.stack.shrink_to_fit();
6275
6276 status
6277}
6278
6279pub fn close_thread(state: &mut LuaState, from: Option<&LuaState>) -> i32 {
6281 state.n_ccalls = match from {
6282 Some(f) => f.c_calls(),
6283 None => 0,
6284 };
6285 let current_status = state.status as i32;
6286 let result = reset_thread(state, current_status);
6287 result
6288}
6289
6290pub fn reset_thread_api(state: &mut LuaState) -> i32 {
6292 close_thread(state, None)
6293}
6294
6295pub fn new_state() -> Option<LuaState> {
6301 let heap = lua_gc::Heap::new();
6315 let placeholder_str = GcRef(heap.allocate_uncollected(LuaString::placeholder()));
6316 let main_thread_value = GcRef(heap.allocate_uncollected(lua_types::value::LuaThread::new(0)));
6317
6318 let initial_white = 1u8 << WHITE0BIT;
6319
6320 let global = GlobalState {
6323 parser_hook: None,
6324 cli_argv: None,
6325 cli_preload: None,
6326 lua_version: lua_types::LuaVersion::default(),
6327 file_loader_hook: None,
6328 file_open_hook: None,
6329 stdout_hook: None,
6330 stderr_hook: None,
6331 stdin_hook: None,
6332 env_hook: None,
6333 unix_time_hook: None,
6334 cpu_clock_hook: None,
6335 local_offset_hook: None,
6336 entropy_hook: None,
6337 temp_name_hook: None,
6338 popen_hook: None,
6339 io_streams: None,
6340 file_remove_hook: None,
6341 file_rename_hook: None,
6342 os_execute_hook: None,
6343 dynlib_load_hook: None,
6344 dynlib_symbol_hook: None,
6345 dynlib_unload_hook: None,
6346 sandbox: SandboxLimits::default(),
6347 gc_debt: 0,
6348 gc_estimate: 0,
6349 lastatomic: 0,
6350 l_registry: LuaValue::Nil,
6351 external_roots: ExternalRootSet::default(),
6352 globals: LuaValue::Nil,
6353 loaded: LuaValue::Nil,
6354 nilvalue: LuaValue::Int(0),
6355 seed: make_seed(),
6356 currentwhite: initial_white,
6357 gcstate: GCS_PAUSE,
6358 gckind: GcKind::Incremental as u8,
6359 gcstopem: false,
6360 genminormul: LUAI_GENMINORMUL,
6361 genmajormul: (LUAI_GENMAJORMUL / 4) as u8,
6362 gcstp: GCSTPGC,
6363 gcemergency: false,
6364 gcpause: (LUAI_GCPAUSE / 4) as u8,
6365 gcstepmul: (LUAI_GCMUL / 4) as u8,
6366 gcstepsize: LUAI_GCSTEPSIZE,
6367 gc55_params: [20, 50, 68, 250, 200, 9600],
6370 sweepgc_cursor: 0,
6371 weak_tables_registry: lua_gc::WeakRegistry::default(),
6372 finalizers: lua_gc::FinalizerRegistry::default(),
6373 gc_finalizer_error: None,
6374 twups: Vec::new(),
6375 panic: None,
6376 mainthread: None,
6377 threads: std::collections::HashMap::new(),
6378 main_thread_value,
6379 current_thread_id: 0,
6380 closing_thread_id: None,
6381 main_thread_id: 0,
6382 next_thread_id: 1,
6383 thread_globals: std::collections::HashMap::new(),
6384 closure_envs: std::collections::HashMap::new(),
6385 memerrmsg: placeholder_str.clone(),
6386 tmname: Vec::new(),
6387 mt: std::array::from_fn(|_| None),
6388 strcache: std::array::from_fn(|_| std::array::from_fn(|_| placeholder_str.clone())),
6389 interned_lt: InternedStringMap::default(),
6390 warnf: None,
6391 warn_mode: WarnMode::Off,
6392 test_warn_enabled: false,
6393 test_warn_on: false,
6394 test_warn_mode: TestWarnMode::Normal,
6395 test_warn_last_to_cont: false,
6396 test_warn_buffer: Vec::new(),
6397 c_functions: Vec::new(),
6398 heap,
6399 cross_thread_upvals: std::collections::HashMap::new(),
6400 suspended_parent_stacks: Vec::new(),
6401 suspended_parent_open_upvals: Vec::new(),
6402 snapshot_stack_pool: Vec::new(),
6403 snapshot_upval_pool: Vec::new(),
6404 resume_value_pool: Vec::new(),
6405 resume_upval_slot_pool: Vec::new(),
6406 resume_flush_pool: Vec::new(),
6407 };
6408
6409 let global_rc = Rc::new(RefCell::new(global));
6410
6411 let _bootstrap_scope = global_rc.borrow().heap.bootstrap_scope();
6425 let _bootstrap_guard = lua_gc::HeapGuard::push(&global_rc.borrow().heap);
6426
6427 let initial_marked = initial_white;
6428
6429 let mut main_thread = LuaState {
6430 status: LuaStatus::Ok as u8,
6431 allowhook: true,
6432 nci: 0,
6433 top: StackIdx(0),
6434 stack_last: StackIdx(0),
6435 stack: Vec::new(),
6436 ci: CallInfoIdx(0),
6437 call_info: Vec::new(),
6438 openupval: Vec::new(),
6439 legacy_open_upval_touched: std::cell::Cell::new(false),
6440 tbclist: Vec::new(),
6441 global: global_rc.clone(),
6442 hook: None,
6443 hookmask: 0,
6444 basehookcount: 0,
6445 hookcount: 0,
6446 errfunc: 0,
6447 n_ccalls: 0,
6448 oldpc: 0,
6449 marked: initial_marked,
6450 cached_thread_id: 0,
6451 gc_check_needed: false,
6452 };
6453
6454 preinit_thread(&mut main_thread, global_rc.clone());
6455
6456 main_thread.inc_nny();
6457
6458 match lua_open(&mut main_thread) {
6465 Ok(()) => {}
6466 Err(_) => {
6467 close_state(&mut main_thread);
6468 return None;
6469 }
6470 }
6471
6472 Some(main_thread)
6473}
6474
6475pub fn close(mut state: LuaState) {
6483 close_state(&mut state);
6484}
6485
6486pub(crate) fn warning(state: &mut LuaState, msg: &[u8], to_cont: bool) {
6488 let test_warn_enabled = state.global().test_warn_enabled;
6489 if test_warn_enabled {
6490 test_warn(state, msg, to_cont);
6491 return;
6492 }
6493
6494 let has_warnf = state.global().warnf.is_some();
6498 if has_warnf {
6499 let mut warnf = state.global_mut().warnf.take();
6501 if let Some(ref mut f) = warnf {
6502 f(msg, to_cont);
6503 }
6504 state.global_mut().warnf = warnf;
6506 return;
6507 }
6508 default_warn(state, msg, to_cont);
6509}
6510
6511fn test_warn(state: &mut LuaState, msg: &[u8], to_cont: bool) {
6512 let is_control = {
6513 let g = state.global();
6514 !g.test_warn_last_to_cont && !to_cont && msg.first() == Some(&b'@')
6515 };
6516 if is_control {
6517 let mut g = state.global_mut();
6518 match &msg[1..] {
6519 b"off" => g.test_warn_on = false,
6520 b"on" => g.test_warn_on = true,
6521 b"normal" => g.test_warn_mode = TestWarnMode::Normal,
6522 b"allow" => g.test_warn_mode = TestWarnMode::Allow,
6523 b"store" => g.test_warn_mode = TestWarnMode::Store,
6524 _ => {}
6525 }
6526 return;
6527 }
6528
6529 let finished = {
6530 let mut g = state.global_mut();
6531 g.test_warn_last_to_cont = to_cont;
6532 g.test_warn_buffer.extend_from_slice(msg);
6533 if to_cont {
6534 None
6535 } else {
6536 Some((
6537 std::mem::take(&mut g.test_warn_buffer),
6538 g.test_warn_mode,
6539 g.test_warn_on,
6540 ))
6541 }
6542 };
6543
6544 let Some((message, mode, warn_on)) = finished else {
6545 return;
6546 };
6547 match mode {
6548 TestWarnMode::Normal => {
6549 if warn_on && message.first() == Some(&b'#') {
6550 write_warning_message(&message);
6551 }
6552 }
6553 TestWarnMode::Allow => {
6554 if warn_on {
6555 write_warning_message(&message);
6556 }
6557 }
6558 TestWarnMode::Store => {
6559 if let Ok(s) = state.intern_str(&message) {
6560 state.push(LuaValue::Str(s));
6561 let _ = crate::api::set_global(state, b"_WARN");
6562 }
6563 }
6564 }
6565}
6566
6567fn write_warning_message(message: &[u8]) {
6568 use std::io::Write;
6569 let stderr = std::io::stderr();
6570 let mut h = stderr.lock();
6571 let _ = h.write_all(b"Lua warning: ");
6572 let _ = h.write_all(message);
6573 let _ = h.write_all(b"\n");
6574}
6575
6576fn default_warn(state: &mut LuaState, msg: &[u8], to_cont: bool) {
6581 use std::io::Write;
6582 if !to_cont && msg.first() == Some(&b'@') {
6584 match &msg[1..] {
6585 b"off" => state.global_mut().warn_mode = WarnMode::Off,
6586 b"on" => state.global_mut().warn_mode = WarnMode::On,
6587 _ => {}
6588 }
6589 return;
6590 }
6591 let mode = state.global().warn_mode;
6592 match mode {
6593 WarnMode::Off => {}
6594 WarnMode::On | WarnMode::Cont => {
6595 let stderr = std::io::stderr();
6596 let mut h = stderr.lock();
6597 if mode == WarnMode::On {
6598 let _ = h.write_all(b"Lua warning: ");
6599 }
6600 let _ = h.write_all(msg);
6601 if to_cont {
6602 state.global_mut().warn_mode = WarnMode::Cont;
6603 } else {
6604 let _ = h.write_all(b"\n");
6605 state.global_mut().warn_mode = WarnMode::On;
6606 }
6607 }
6608 }
6609}
6610
6611#[cfg(test)]
6612mod tests {
6613 use super::*;
6614
6615 fn test_noop_cclosure(_: &mut LuaState) -> Result<usize, LuaError> {
6616 Ok(0)
6617 }
6618
6619 #[test]
6623 fn new_userdata_builds_untyped_full_userdata() {
6624 let mut state = new_state().expect("state should initialize");
6625 let _heap_guard = {
6626 let g = state.global();
6627 lua_gc::HeapGuard::push(&g.heap)
6628 };
6629 let ud = state
6630 .new_userdata(16, 2)
6631 .expect("new_userdata should build, not error");
6632 assert_eq!(ud.data.len(), 16);
6633 assert_eq!(ud.uv.borrow().len(), 2);
6634 assert!(ud.uv.borrow().iter().all(|v| matches!(v, LuaValue::Nil)));
6635 assert!(ud.metatable.borrow().is_none());
6636 }
6637
6638 #[test]
6642 fn new_c_closure_builds_light_and_full_closures() {
6643 let mut state = new_state().expect("state should initialize");
6644 let _heap_guard = {
6645 let g = state.global();
6646 lua_gc::HeapGuard::push(&g.heap)
6647 };
6648 let light = state
6649 .new_c_closure(test_noop_cclosure, 0)
6650 .expect("light closure should build");
6651 assert!(
6652 matches!(light, LuaClosure::LightC(_)),
6653 "n==0 must yield a light C function"
6654 );
6655
6656 let full = state
6657 .new_c_closure(test_noop_cclosure, 3)
6658 .expect("full closure should build");
6659 match full {
6660 LuaClosure::C(ccl) => {
6661 let ups = ccl.upvalues.borrow();
6662 assert_eq!(ups.len(), 3);
6663 assert!(ups.iter().all(|v| matches!(v, LuaValue::Nil)));
6664 }
6665 _ => panic!("n>0 must yield a full C closure"),
6666 }
6667 }
6668
6669 #[test]
6673 fn register_c_function_dedups_only_when_requested() {
6674 let mut state = new_state().expect("state should initialize");
6675 let _heap_guard = {
6676 let g = state.global();
6677 lua_gc::HeapGuard::push(&g.heap)
6678 };
6679 let a = state.register_c_function(test_noop_cclosure, true);
6680 let b = state.register_c_function(test_noop_cclosure, true);
6681 assert_eq!(a, b, "dedup=true should reuse the identical fn's slot");
6682 let c = state.register_c_function(test_noop_cclosure, false);
6683 assert_ne!(a, c, "dedup=false must always allocate a fresh slot");
6684 }
6685
6686 #[test]
6692 fn to_display_string_renders_distinct_real_table_addresses() {
6693 let mut state = new_state().expect("state should initialize");
6694 let _heap_guard = {
6695 let g = state.global();
6696 lua_gc::HeapGuard::push(&g.heap)
6697 };
6698
6699 let t1 = state.new_table();
6700 state.push(LuaValue::Table(t1));
6701 let s1 = state
6702 .to_display_string(-1)
6703 .expect("to_display_string on table 1");
6704
6705 let t2 = state.new_table();
6706 state.push(LuaValue::Table(t2));
6707 let s2 = state
6708 .to_display_string(-1)
6709 .expect("to_display_string on table 2");
6710
6711 assert!(
6712 s1.starts_with(b"table: 0x"),
6713 "expected a real address, got {:?}",
6714 String::from_utf8_lossy(&s1)
6715 );
6716 assert!(
6717 !s1.windows(3).any(|w| w == b"0x?"),
6718 "the fixed '0x?' placeholder must be gone, got {:?}",
6719 String::from_utf8_lossy(&s1)
6720 );
6721 assert_ne!(s1, s2, "two distinct tables must render distinct addresses");
6722 }
6723
6724 #[test]
6729 fn raw_constructors_flag_gc_check_needed() {
6730 let mut state = new_state().expect("state should initialize");
6731 let _heap_guard = {
6732 let g = state.global();
6733 lua_gc::HeapGuard::push(&g.heap)
6734 };
6735
6736 state.gc_check_needed = false;
6737 let _ = state.new_userdata(32, 1).expect("new_userdata");
6738 assert!(state.gc_check_needed, "new_userdata must flag a GC check");
6739
6740 state.gc_check_needed = false;
6741 let _ = state
6742 .new_c_closure(test_noop_cclosure, 2)
6743 .expect("new_c_closure n>0");
6744 assert!(
6745 state.gc_check_needed,
6746 "new_c_closure(n>0) must flag a GC check"
6747 );
6748 }
6749
6750 #[test]
6754 fn to_display_string_light_userdata_uses_plain_userdata_name() {
6755 let mut state = new_state().expect("state should initialize");
6756 let _heap_guard = {
6757 let g = state.global();
6758 lua_gc::HeapGuard::push(&g.heap)
6759 };
6760 let ptr = 0x1234usize as *mut core::ffi::c_void;
6761 state.push(LuaValue::LightUserData(ptr));
6762 let s = state
6763 .to_display_string(-1)
6764 .expect("display light userdata");
6765 assert!(
6766 s.starts_with(b"userdata: 0x"),
6767 "expected 'userdata: 0x...', got {:?}",
6768 String::from_utf8_lossy(&s)
6769 );
6770 assert!(
6771 !s.starts_with(b"light userdata"),
6772 "must not use the error-message name 'light userdata'"
6773 );
6774 }
6775
6776 #[test]
6779 fn to_pointer_lightc_is_real_address_not_index() {
6780 let mut state = new_state().expect("state should initialize");
6781 let _heap_guard = {
6782 let g = state.global();
6783 lua_gc::HeapGuard::push(&g.heap)
6784 };
6785 let cl = state
6786 .new_c_closure(test_noop_cclosure, 0)
6787 .expect("light C function");
6788 let idx = match cl {
6789 LuaClosure::LightC(i) => i,
6790 _ => panic!("n==0 must yield LightC"),
6791 };
6792 state.push(LuaValue::Function(cl));
6793 let ptr = crate::api::to_pointer(&state, -1).expect("LightC must have a pointer");
6794 assert!(
6795 ptr > u16::MAX as usize,
6796 "expected a real address, got {ptr:#x} (registry index was {idx})"
6797 );
6798 assert_eq!(
6799 ptr, test_noop_cclosure as usize,
6800 "must resolve to the registered fn's real address"
6801 );
6802 }
6803
6804 #[test]
6807 fn to_cfunction_resolves_registered_fn() {
6808 let mut state = new_state().expect("state should initialize");
6809 let _heap_guard = {
6810 let g = state.global();
6811 lua_gc::HeapGuard::push(&g.heap)
6812 };
6813 let cl = state
6814 .new_c_closure(test_noop_cclosure, 0)
6815 .expect("light C function");
6816 state.push(LuaValue::Function(cl));
6817 let f = crate::api::to_cfunction(&state, -1).expect("to_cfunction must resolve");
6818 assert_eq!(f as usize, test_noop_cclosure as usize);
6819
6820 state.push(LuaValue::Int(7));
6821 assert!(
6822 crate::api::to_cfunction(&state, -1).is_none(),
6823 "non-function must yield None"
6824 );
6825 }
6826
6827 #[test]
6831 fn new_c_closure_rejects_out_of_range_upvalue_count() {
6832 let mut state = new_state().expect("state should initialize");
6833 let _heap_guard = {
6834 let g = state.global();
6835 lua_gc::HeapGuard::push(&g.heap)
6836 };
6837 let before = state.global().c_functions.len();
6838 assert!(
6839 state.new_c_closure(test_noop_cclosure, 256).is_err(),
6840 "n>255 must error"
6841 );
6842 assert!(
6843 state.new_c_closure(test_noop_cclosure, -1).is_err(),
6844 "negative n must error"
6845 );
6846 assert_eq!(
6847 before,
6848 state.global().c_functions.len(),
6849 "an invalid upvalue count must not pollute c_functions"
6850 );
6851 assert!(
6852 state.new_c_closure(test_noop_cclosure, 255).is_ok(),
6853 "n==255 (MAX_UPVAL) must succeed"
6854 );
6855 }
6856
6857 #[test]
6867 fn registry_versioned_slots_match_version() {
6868 let mut state = new_state().expect("state should initialize");
6869 let _heap_guard = {
6870 let g = state.global();
6871 lua_gc::HeapGuard::push(&g.heap)
6872 };
6873
6874 let registry = match state.global().l_registry.clone() {
6875 LuaValue::Table(t) => t,
6876 other => panic!("l_registry should be a table, got {other:?}"),
6877 };
6878 let main_thread = LuaValue::Thread(state.global().main_thread_value.clone());
6879 let globals = state.global().globals.clone();
6880 assert!(matches!(globals, LuaValue::Table(_)), "globals should be a table");
6881
6882 assert_eq!(registry.get_int(1), main_thread);
6883 assert_eq!(registry.get_int(LUA_RIDX_GLOBALS), globals);
6884 assert_eq!(registry.get_int(3), LuaValue::Nil);
6885
6886 state.global_mut().lua_version = lua_types::LuaVersion::V51;
6887 set_versioned_registry_slots(&mut state).expect("V51 slot update should succeed");
6888 assert_eq!(registry.get_int(1), LuaValue::Nil);
6889 assert_eq!(registry.get_int(LUA_RIDX_GLOBALS), LuaValue::Nil);
6890 assert_eq!(registry.get_int(3), LuaValue::Nil);
6891
6892 state.global_mut().lua_version = lua_types::LuaVersion::V55;
6893 set_versioned_registry_slots(&mut state).expect("V55 slot update should succeed");
6894 assert_eq!(registry.get_int(1), LuaValue::Bool(false));
6895 assert_eq!(registry.get_int(LUA_RIDX_GLOBALS), globals);
6896 assert_eq!(registry.get_int(3), main_thread);
6897
6898 state.global_mut().lua_version = lua_types::LuaVersion::V52;
6899 set_versioned_registry_slots(&mut state).expect("V52 slot update should succeed");
6900 assert_eq!(registry.get_int(1), main_thread);
6901 assert_eq!(registry.get_int(LUA_RIDX_GLOBALS), globals);
6902 assert_eq!(registry.get_int(3), LuaValue::Nil);
6903 }
6904
6905 #[test]
6913 fn versioned_registry_slots_preserve_foreign_entries_on_rerun() {
6914 let mut state = new_state().expect("state should initialize");
6915 let _heap_guard = {
6916 let g = state.global();
6917 lua_gc::HeapGuard::push(&g.heap)
6918 };
6919
6920 let registry = match state.global().l_registry.clone() {
6921 LuaValue::Table(t) => t,
6922 other => panic!("l_registry should be a table, got {other:?}"),
6923 };
6924 let main_thread = LuaValue::Thread(state.global().main_thread_value.clone());
6925 let globals = state.global().globals.clone();
6926
6927 registry
6928 .raw_set_int(&mut state, 3, LuaValue::Int(99))
6929 .expect("seeding a foreign registry entry should succeed");
6930
6931 set_versioned_registry_slots(&mut state).expect("V54 re-run should succeed");
6932
6933 assert_eq!(registry.get_int(3), LuaValue::Int(99));
6934 assert_eq!(registry.get_int(1), main_thread);
6935 assert_eq!(registry.get_int(LUA_RIDX_GLOBALS), globals);
6936 }
6937
6938 #[test]
6951 fn reset_thread_shrinks_stack_and_updates_stack_last() {
6952 let mut state = new_state().expect("state should initialize");
6953 let _heap_guard = {
6954 let g = state.global();
6955 lua_gc::HeapGuard::push(&g.heap)
6956 };
6957
6958 let grown_size = state.stack_size() + 500;
6959 crate::do_::realloc_stack(&mut state, grown_size, false)
6960 .expect("growing the stack should succeed");
6961 assert_eq!(state.stack_size(), grown_size);
6962 assert_eq!(state.stack.len(), grown_size + EXTRA_STACK);
6963 let grown_capacity = state.stack.capacity();
6964
6965 let status = reset_thread(&mut state, LuaStatus::Ok as i32);
6966 assert_eq!(status, LuaStatus::Ok as i32);
6967
6968 let expected_size = (state.top.0 + LUA_MINSTACK as u32) as usize;
6969 assert_eq!(
6970 state.stack_size(),
6971 expected_size,
6972 "stack_last should track reset_thread's realloc instead of the stale pre-reset size"
6973 );
6974 assert_eq!(
6975 state.stack.len(),
6976 expected_size + EXTRA_STACK,
6977 "reset_thread should shrink the stack length back down, matching C's luaE_resetthread"
6978 );
6979 assert!(
6980 state.stack.capacity() < grown_capacity,
6981 "reset_thread should reclaim the backing capacity (was {}, now {})",
6982 grown_capacity,
6983 state.stack.capacity()
6984 );
6985 }
6986
6987 #[test]
6988 fn memerrmsg_is_the_same_object_a_matching_intern_str_call_returns() {
6989 let mut state = new_state().expect("state should initialize");
6990 let _heap_guard = {
6991 let g = state.global();
6992 lua_gc::HeapGuard::push(&g.heap)
6993 };
6994
6995 let memerrmsg = state.global().memerrmsg.clone();
6996 let interned = state
6997 .intern_str(crate::string::MAX_SHORT_LEN.to_string().as_bytes())
6998 .expect("interning a short string should not fail");
6999 assert!(!GcRef::ptr_eq(&memerrmsg, &interned));
7000
7001 let same_bytes = state
7002 .intern_str(memerrmsg.as_bytes())
7003 .expect("interning the memerrmsg bytes should not fail");
7004 assert!(
7005 GcRef::ptr_eq(&memerrmsg, &same_bytes),
7006 "memerrmsg must be a member of the same intern table as every other \
7007 short string, matching upstream Lua's `eqshrstr` identity semantics \
7008 (a script string spelling the OOM message aliases memerrmsg)"
7009 );
7010 }
7011
7012 #[test]
7013 fn external_root_keys_reject_stale_slot_after_reuse() {
7014 let mut roots = ExternalRootSet::default();
7015
7016 let first = roots.insert(LuaValue::Int(1));
7017 assert_eq!(roots.len(), 1);
7018 assert_eq!(roots.get(first), Some(&LuaValue::Int(1)));
7019
7020 assert_eq!(roots.remove(first), Some(LuaValue::Int(1)));
7021 assert!(roots.get(first).is_none());
7022 assert!(roots.remove(first).is_none());
7023 assert_eq!(roots.len(), 0);
7024 assert_eq!(roots.vacant_len(), 1);
7025 assert!(roots.replace(first, LuaValue::Int(9)).is_none());
7026 assert!(roots.is_empty());
7027
7028 let second = roots.insert(LuaValue::Int(2));
7029 assert_eq!(first.index, second.index);
7030 assert_ne!(first, second);
7031 assert!(roots.get(first).is_none());
7032 assert_eq!(roots.get(second), Some(&LuaValue::Int(2)));
7033 assert!(roots.replace(first, LuaValue::Int(3)).is_none());
7034 }
7035
7036 #[test]
7037 fn external_roots_keep_heap_value_alive_until_unrooted() {
7038 let mut state = new_state().expect("state should initialize");
7039 let _heap_guard = {
7040 let g = state.global();
7041 lua_gc::HeapGuard::push(&g.heap)
7042 };
7043
7044 let table = state.new_table();
7045 assert_eq!(state.global().heap.allgc_count(), 1);
7046
7047 let key = state.external_root_value(LuaValue::Table(table));
7048 state.gc().full_collect();
7049 assert_eq!(state.global().heap.allgc_count(), 1);
7050 assert_eq!(state.global().external_roots.len(), 1);
7051
7052 assert!(state.external_unroot_value(key).is_some());
7053 state.gc().full_collect();
7054 assert_eq!(state.global().heap.allgc_count(), 0);
7055 assert!(state.global().external_roots.is_empty());
7056 }
7057
7058 #[test]
7064 fn free_all_objects_kills_weak_handle_while_guard_and_heap_alive() {
7065 let mut state = new_state().expect("state should initialize");
7066 let heap_rc = state.global().heap.clone();
7067 let guard = lua_gc::HeapGuard::push(&heap_rc);
7068
7069 let table = state.new_table();
7070 let weak = table.downgrade();
7071 assert!(
7072 weak.upgrade().is_some(),
7073 "weak handle upgrades while the table is live"
7074 );
7075
7076 state.gc().free_all_objects();
7077
7078 assert!(
7079 weak.upgrade().is_none(),
7080 "free_all_objects must free the table and drop its weak token during \
7081 the close call, with the outer HeapGuard and a strong heap Rc still alive"
7082 );
7083 assert!(state.global().heap.is_closed());
7084 assert!(std::rc::Rc::strong_count(&heap_rc) >= 1);
7085
7086 drop(guard);
7087 drop(state);
7088 }
7089
7090 thread_local! {
7091 static CLOSE_GC_RUNS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7092 }
7093
7094 fn close_gc_probe(_state: &mut LuaState) -> Result<usize, LuaError> {
7095 CLOSE_GC_RUNS.with(|c| c.set(c.get() + 1));
7096 Ok(0)
7097 }
7098
7099 fn install_finalizable_table_with(state: &mut LuaState, gc_fn: LuaCFunction) {
7104 let heap = state.global().heap.clone();
7105 let _guard = lua_gc::HeapGuard::push(&heap);
7106 crate::api::create_table(state, 0, 0).expect("object table");
7107 crate::api::create_table(state, 0, 1).expect("metatable");
7108 crate::api::push_cclosure(state, gc_fn, 0).expect("push __gc");
7109 crate::api::set_field(state, -2, b"__gc").expect("mt.__gc");
7110 crate::api::set_metatable(state, -2).expect("setmetatable");
7111 }
7112
7113 fn install_finalizable_table(state: &mut LuaState) {
7114 install_finalizable_table_with(state, close_gc_probe);
7115 }
7116
7117 #[test]
7122 fn state_close_runs_gc_finalizer_exactly_once() {
7123 CLOSE_GC_RUNS.with(|c| c.set(0));
7124 let mut state = new_state().expect("state should initialize");
7125 install_finalizable_table(&mut state);
7126 assert_eq!(
7127 CLOSE_GC_RUNS.with(|c| c.get()),
7128 0,
7129 "finalizer must not fire while the object is live"
7130 );
7131
7132 close(state);
7133 assert_eq!(
7134 CLOSE_GC_RUNS.with(|c| c.get()),
7135 1,
7136 "close must run the pending __gc exactly once before freeing"
7137 );
7138 }
7139
7140 #[test]
7145 fn manual_close_finalizer_pass_then_close_runs_gc_exactly_once() {
7146 CLOSE_GC_RUNS.with(|c| c.set(0));
7147 let mut state = new_state().expect("state should initialize");
7148 install_finalizable_table(&mut state);
7149
7150 crate::api::run_close_finalizers(&mut state);
7151 assert_eq!(CLOSE_GC_RUNS.with(|c| c.get()), 1);
7152
7153 close(state);
7154 assert_eq!(
7155 CLOSE_GC_RUNS.with(|c| c.get()),
7156 1,
7157 "close after a manual run_close_finalizers pass must not double-run __gc"
7158 );
7159 }
7160
7161 #[test]
7166 fn close_runs_queue_only_finalizer_leftovers() {
7167 CLOSE_GC_RUNS.with(|c| c.set(0));
7168 let mut state = new_state().expect("state should initialize");
7169 install_finalizable_table(&mut state);
7170
7171 {
7172 let mut g = state.global_mut();
7173 let pending: Vec<FinalizerObject> = g.finalizers.take_pending();
7174 assert!(!pending.is_empty());
7175 for object in pending.into_iter().rev() {
7176 let heap_ptr = object.heap_ptr();
7177 g.finalizers.push_to_be_finalized(object);
7178 if let Some(ptr) = heap_ptr {
7179 g.heap.move_finobj_to_tobefnz(ptr);
7180 }
7181 }
7182 assert_eq!(g.finalizers.pending_len(), 0);
7183 assert!(g.finalizers.has_to_be_finalized());
7184 }
7185
7186 close(state);
7187 assert_eq!(
7188 CLOSE_GC_RUNS.with(|c| c.get()),
7189 1,
7190 "a finalizer parked in to_be_finalized with pending empty must \
7191 still run at close"
7192 );
7193 }
7194
7195 fn self_reregister_gc_probe(state: &mut LuaState) -> Result<usize, LuaError> {
7200 CLOSE_GC_RUNS.with(|c| c.set(c.get() + 1));
7201 crate::api::push_value(state, 1);
7202 crate::api::create_table(state, 0, 1)?;
7203 crate::api::push_cclosure(state, self_reregister_gc_probe, 0)?;
7204 crate::api::set_field(state, -2, b"__gc")?;
7205 crate::api::set_metatable(state, -2)?;
7206 state.pop();
7207 Ok(0)
7208 }
7209
7210 #[test]
7216 fn queue_only_self_reregistering_finalizer_runs_exactly_once() {
7217 CLOSE_GC_RUNS.with(|c| c.set(0));
7218 let mut state = new_state().expect("state should initialize");
7219 install_finalizable_table_with(&mut state, self_reregister_gc_probe);
7220
7221 {
7222 let mut g = state.global_mut();
7223 let pending: Vec<FinalizerObject> = g.finalizers.take_pending();
7224 assert!(!pending.is_empty());
7225 for object in pending.into_iter().rev() {
7226 let heap_ptr = object.heap_ptr();
7227 g.finalizers.push_to_be_finalized(object);
7228 if let Some(ptr) = heap_ptr {
7229 g.heap.move_finobj_to_tobefnz(ptr);
7230 }
7231 }
7232 assert_eq!(g.finalizers.pending_len(), 0);
7233 assert!(g.finalizers.has_to_be_finalized());
7234 }
7235
7236 close(state);
7237 assert_eq!(
7238 CLOSE_GC_RUNS.with(|c| c.get()),
7239 1,
7240 "a self-re-registering queue-only finalizer must run exactly \
7241 once at close — seen must be seeded from to_be_finalized"
7242 );
7243 }
7244
7245 fn regen_gc_probe(state: &mut LuaState) -> Result<usize, LuaError> {
7246 CLOSE_GC_RUNS.with(|c| c.set(c.get() + 1));
7247 crate::api::create_table(state, 0, 0)?;
7248 crate::api::create_table(state, 0, 1)?;
7249 crate::api::push_cclosure(state, close_gc_probe, 0)?;
7250 crate::api::set_field(state, -2, b"__gc")?;
7251 crate::api::set_metatable(state, -2)?;
7252 state.pop();
7253 Ok(0)
7254 }
7255
7256 #[test]
7261 fn finalizer_registering_new_finalizable_during_close_runs_it() {
7262 CLOSE_GC_RUNS.with(|c| c.set(0));
7263 let mut state = new_state().expect("state should initialize");
7264 install_finalizable_table_with(&mut state, regen_gc_probe);
7265
7266 close(state);
7267 assert_eq!(
7268 CLOSE_GC_RUNS.with(|c| c.get()),
7269 2,
7270 "regen_gc_probe runs once, and the fresh finalizable it registered \
7271 during the drain runs exactly once on a later pass"
7272 );
7273 }
7274
7275 #[test]
7281 fn close_with_live_coroutine_lets_heap_drop() {
7282 let mut state = new_state().expect("state should initialize");
7283 let heap_weak = std::rc::Rc::downgrade(&state.global().heap);
7284 {
7285 let heap = state.global().heap.clone();
7286 let _guard = lua_gc::HeapGuard::push(&heap);
7287 new_thread(&mut state, None).expect("coroutine creation");
7288 }
7289 assert_eq!(state.global().threads.len(), 1);
7290
7291 close(state);
7292 assert!(
7293 heap_weak.upgrade().is_none(),
7294 "the heap must actually drop once the outer state drops after \
7295 close — a lingering threads-map cycle would keep it alive"
7296 );
7297 }
7298
7299 struct VmDropFlag(std::rc::Rc<std::cell::Cell<bool>>);
7302 impl lua_gc::Trace for VmDropFlag {
7303 fn trace(&self, _m: &mut lua_gc::Marker) {}
7304 }
7305 impl Drop for VmDropFlag {
7306 fn drop(&mut self) {
7307 self.0.set(true);
7308 }
7309 }
7310
7311 struct VmAllocOnDrop {
7317 flag: std::rc::Rc<std::cell::Cell<bool>>,
7318 inner: std::rc::Rc<std::cell::Cell<bool>>,
7319 }
7320 impl lua_gc::Trace for VmAllocOnDrop {
7321 fn trace(&self, _m: &mut lua_gc::Marker) {}
7322 }
7323 impl Drop for VmAllocOnDrop {
7324 fn drop(&mut self) {
7325 self.flag.set(true);
7326 let _ = GcRef::new(VmDropFlag(self.inner.clone()));
7327 }
7328 }
7329
7330 #[test]
7331 fn free_all_objects_provides_own_heap_guard_with_no_ambient_guard() {
7332 let mut state = new_state().expect("state should initialize");
7333 let heap = state.global().heap.clone();
7334 let outer = std::rc::Rc::new(std::cell::Cell::new(false));
7335 let inner = std::rc::Rc::new(std::cell::Cell::new(false));
7336 let _gc = heap.allocate(VmAllocOnDrop {
7337 flag: outer.clone(),
7338 inner: inner.clone(),
7339 });
7340
7341 state.gc().free_all_objects();
7342
7343 assert!(outer.get(), "the destructor itself must have run");
7344 assert!(
7345 inner.get(),
7346 "GcRef::new inside a teardown destructor must land in the closing \
7347 heap (via free_all_objects's own guard) and be drained, even with \
7348 no ambient HeapGuard"
7349 );
7350 assert!(heap.is_closed());
7351 }
7352
7353 #[test]
7354 fn free_all_objects_targets_own_heap_under_foreign_guard() {
7355 let mut state1 = new_state().expect("state 1 should initialize");
7356 let state2 = new_state().expect("state 2 should initialize");
7357 let heap1 = state1.global().heap.clone();
7358 let heap2 = state2.global().heap.clone();
7359 let _foreign = lua_gc::HeapGuard::push(&heap2);
7360
7361 let outer = std::rc::Rc::new(std::cell::Cell::new(false));
7362 let inner = std::rc::Rc::new(std::cell::Cell::new(false));
7363 let _gc = heap1.allocate(VmAllocOnDrop {
7364 flag: outer.clone(),
7365 inner: inner.clone(),
7366 });
7367 let heap2_baseline = heap2.allgc_count();
7368
7369 state1.gc().free_all_objects();
7370
7371 assert!(outer.get());
7372 assert!(
7373 inner.get(),
7374 "the teardown allocation must land in (and be drained from) the \
7375 heap being closed, not the foreign heap on the TLS guard stack"
7376 );
7377 assert_eq!(
7378 heap2.allgc_count(),
7379 heap2_baseline,
7380 "the foreign heap must be untouched by another state's close"
7381 );
7382 assert!(heap1.is_closed());
7383 assert!(!heap2.is_closed());
7384 drop(state2);
7385 }
7386
7387 #[test]
7388 fn interned_string_table_grows_then_shrinks_on_collection() {
7389 let mut state = new_state().expect("state should initialize");
7390 let _heap_guard = {
7391 let g = state.global();
7392 lua_gc::HeapGuard::push(&g.heap)
7393 };
7394
7395 let initial_buckets = state.global().interned_lt.bucket_count();
7396 assert_eq!(
7397 initial_buckets, 64,
7398 "the intern table starts at C's MINSTRTABSIZE-equivalent of 64"
7399 );
7400 let baseline_live = state.global().interned_lt.len();
7401
7402 let mut anchors: Vec<GcRef<LuaString>> = Vec::with_capacity(2000);
7403 for i in 0..2000usize {
7404 let key = format!("intern-shrink-probe-{i:08}");
7405 let s = state
7406 .intern_str(key.as_bytes())
7407 .expect("short string interns");
7408 anchors.push(s);
7409 }
7410
7411 let grown_buckets = state.global().interned_lt.bucket_count();
7412 assert_eq!(
7413 state.global().interned_lt.len(),
7414 baseline_live + 2000,
7415 "all 2000 distinct short strings are interned and live alongside \
7416 the runtime's own rooted strings"
7417 );
7418 assert!(
7419 grown_buckets >= 2048,
7420 "interning 2000 strings must force several bucket doublings past \
7421 the initial 64 (saw {grown_buckets})"
7422 );
7423
7424 drop(anchors);
7425 state.gc().full_collect();
7426
7427 let shrunk_buckets = state.global().interned_lt.bucket_count();
7428 let surviving_live = state.global().interned_lt.len();
7429 assert!(
7430 surviving_live <= baseline_live,
7431 "every probe string is unreachable and must be swept out of the \
7432 intern table, leaving at most the runtime's own strings (baseline \
7433 {baseline_live}, surviving {surviving_live})"
7434 );
7435 assert!(
7436 surviving_live < 2000,
7437 "the 2000 probe strings must not survive collection (surviving \
7438 {surviving_live})"
7439 );
7440 assert_eq!(
7441 shrunk_buckets, 64,
7442 "the batch-end shrink check must reclaim the stale buckets back to \
7443 the 64-bucket floor (saw {shrunk_buckets}, grew to {grown_buckets})"
7444 );
7445 assert!(
7446 shrunk_buckets < grown_buckets,
7447 "shrink must strictly reduce the bucket array"
7448 );
7449 }
7450
7451 #[test]
7452 fn table_buffer_accounting_refunds_on_sweep() {
7453 let mut state = new_state().expect("state should initialize");
7454 let _heap_guard = {
7455 let g = state.global();
7456 lua_gc::HeapGuard::push(&g.heap)
7457 };
7458
7459 let table = state.new_table();
7460 let key = state.external_root_value(LuaValue::Table(table));
7461 let header_bytes = state.global().heap.bytes_used();
7462 assert!(header_bytes > 0);
7463
7464 for i in 1..=128 {
7465 table
7466 .raw_set_int(&mut state, i, LuaValue::Int(i))
7467 .expect("integer table insert should succeed");
7468 }
7469 let grown_bytes = state.global().heap.bytes_used();
7470 assert!(
7471 grown_bytes > header_bytes,
7472 "table array/hash buffer growth must be charged to the GC heap"
7473 );
7474
7475 state.gc().full_collect();
7476 assert_eq!(
7477 state.global().heap.bytes_used(),
7478 grown_bytes,
7479 "rooted table buffer bytes should remain charged after collection"
7480 );
7481
7482 assert!(state.external_unroot_value(key).is_some());
7483 state.gc().full_collect();
7484 assert_eq!(state.global().heap.bytes_used(), 0);
7485 assert_eq!(state.global().heap.allgc_count(), 0);
7486 }
7487
7488 #[test]
7489 fn userdata_buffer_accounting_refunds_on_sweep() {
7490 let mut state = new_state().expect("state should initialize");
7491 let _heap_guard = {
7492 let g = state.global();
7493 lua_gc::HeapGuard::push(&g.heap)
7494 };
7495
7496 let payload_len = 4096;
7497 let userdata = state
7498 .new_userdata_typed(b"accounting", payload_len, 3)
7499 .expect("userdata allocation should succeed");
7500 state.pop_n(1);
7501 let key = state.external_root_value(LuaValue::UserData(userdata));
7502 let allocated_bytes = state.global().heap.bytes_used();
7503 assert!(
7504 allocated_bytes > payload_len,
7505 "userdata payload bytes must be charged to the GC heap"
7506 );
7507
7508 state.gc().full_collect();
7509 assert_eq!(
7510 state.global().heap.bytes_used(),
7511 allocated_bytes,
7512 "rooted userdata payload bytes should remain charged after collection"
7513 );
7514
7515 assert!(state.external_unroot_value(key).is_some());
7516 state.gc().full_collect();
7517 assert_eq!(state.global().heap.bytes_used(), 0);
7518 assert_eq!(state.global().heap.allgc_count(), 0);
7519 }
7520
7521 #[test]
7522 fn cclosure_upvalue_accounting_refunds_on_sweep() {
7523 let mut state = new_state().expect("state should initialize");
7524 let _heap_guard = {
7525 let g = state.global();
7526 lua_gc::HeapGuard::push(&g.heap)
7527 };
7528
7529 let nupvalues = 64;
7530 for i in 0..nupvalues {
7531 state.push(LuaValue::Int(i as i64));
7532 }
7533 crate::api::push_cclosure(&mut state, test_noop_cclosure, nupvalues as i32)
7534 .expect("C closure creation should succeed");
7535 let LuaValue::Function(LuaClosure::C(ccl)) = state.get_at(state.top_idx() - 1) else {
7536 panic!("expected heavy C closure");
7537 };
7538 let expected_payload = ccl.buffer_bytes();
7539 let key = state.external_root_value(LuaValue::Function(LuaClosure::C(ccl)));
7540 state.pop_n(1);
7541 let allocated_bytes = state.global().heap.bytes_used();
7542 assert!(
7543 allocated_bytes >= expected_payload,
7544 "C closure upvalue vector bytes must be charged to the GC heap"
7545 );
7546
7547 state.gc().full_collect();
7548 assert_eq!(
7549 state.global().heap.bytes_used(),
7550 allocated_bytes,
7551 "rooted C closure payload bytes should remain charged after collection"
7552 );
7553
7554 assert!(state.external_unroot_value(key).is_some());
7555 state.gc().full_collect();
7556 assert_eq!(state.global().heap.bytes_used(), 0);
7557 assert_eq!(state.global().heap.allgc_count(), 0);
7558 }
7559
7560 #[test]
7561 fn proto_and_lclosure_accounting_refunds_on_sweep() {
7562 let mut state = new_state().expect("state should initialize");
7563 let _heap_guard = {
7564 let g = state.global();
7565 lua_gc::HeapGuard::push(&g.heap)
7566 };
7567
7568 let mut proto = LuaProto::placeholder();
7569 proto.code = vec![lua_types::opcode::Instruction(0); 2048];
7570 proto.lineinfo = vec![0; 2048];
7571 proto.k = vec![LuaValue::Int(1); 512];
7572 let expected_proto_payload = proto.buffer_bytes();
7573 let proto = GcRef::new(proto);
7574 proto.account_buffer(expected_proto_payload as isize);
7575
7576 let closure = state.new_lclosure(proto, 16);
7577 let expected_closure_payload = closure.buffer_bytes();
7578 let key = state.external_root_value(LuaValue::Function(LuaClosure::Lua(closure)));
7579 let allocated_bytes = state.global().heap.bytes_used();
7580 assert!(
7581 allocated_bytes >= expected_proto_payload + expected_closure_payload,
7582 "proto and Lua closure vector bytes must be charged to the GC heap"
7583 );
7584
7585 state.gc().full_collect();
7586 assert_eq!(
7587 state.global().heap.bytes_used(),
7588 allocated_bytes,
7589 "rooted proto and Lua closure payload bytes should remain charged after collection"
7590 );
7591
7592 assert!(state.external_unroot_value(key).is_some());
7593 state.gc().full_collect();
7594 assert_eq!(state.global().heap.bytes_used(), 0);
7595 assert_eq!(state.global().heap.allgc_count(), 0);
7596 }
7597
7598 #[test]
7599 fn string_buffer_accounting_refunds_on_sweep() {
7600 let mut state = new_state().expect("state should initialize");
7601 let _heap_guard = {
7602 let g = state.global();
7603 lua_gc::HeapGuard::push(&g.heap)
7604 };
7605
7606 let payload = vec![b'x'; crate::string::MAX_SHORT_LEN + 4096];
7607 let string = state
7608 .intern_str(&payload)
7609 .expect("long string should allocate");
7610 let key = state.external_root_value(LuaValue::Str(string));
7611 let allocated_bytes = state.global().heap.bytes_used();
7612 assert!(
7613 allocated_bytes > payload.len(),
7614 "long string backing bytes must be charged to the GC heap"
7615 );
7616
7617 state.gc().full_collect();
7618 assert_eq!(
7619 state.global().heap.bytes_used(),
7620 allocated_bytes,
7621 "rooted string buffer bytes should remain charged after collection"
7622 );
7623
7624 assert!(state.external_unroot_value(key).is_some());
7625 state.gc().full_collect();
7626 assert_eq!(state.global().heap.bytes_used(), 0);
7627 assert_eq!(state.global().heap.allgc_count(), 0);
7628 }
7629
7630 #[test]
7631 fn interned_short_string_cache_does_not_root_unreferenced_string() {
7632 let mut state = new_state().expect("state should initialize");
7633 let _heap_guard = {
7634 let g = state.global();
7635 lua_gc::HeapGuard::push(&g.heap)
7636 };
7637
7638 let payload = b"weak-cache-probe-a";
7639 let string = state
7640 .intern_str(payload)
7641 .expect("short string should intern");
7642 let id = string.identity();
7643 assert!(state.global().interned_lt.contains_key(&payload[..]));
7644 assert_eq!(
7645 state.global().heap.register_allocation_token(id),
7646 state.global().heap.register_allocation_token(id),
7647 "token registration is get-or-insert while the string is provably live"
7648 );
7649 assert!(state.global().heap.allocation_token(id).is_some());
7650
7651 state.gc().full_collect();
7652 assert!(!state.global().interned_lt.contains_key(&payload[..]));
7653 assert_eq!(state.global().heap.allocation_token(id), None);
7654 }
7655
7656 #[test]
7657 fn interned_short_string_cache_keeps_reachable_string_until_unrooted() {
7658 let mut state = new_state().expect("state should initialize");
7659 let _heap_guard = {
7660 let g = state.global();
7661 lua_gc::HeapGuard::push(&g.heap)
7662 };
7663
7664 let payload = b"weak-cache-probe-b";
7665 let string = state
7666 .intern_str(payload)
7667 .expect("short string should intern");
7668 let id = string.identity();
7669 state.global().heap.register_allocation_token(id);
7670 let key = state.external_root_value(LuaValue::Str(string));
7671
7672 state.gc().full_collect();
7673 assert!(state.global().interned_lt.contains_key(&payload[..]));
7674 assert!(state.global().heap.allocation_token(id).is_some());
7675
7676 assert!(state.external_unroot_value(key).is_some());
7677 state.gc().full_collect();
7678 assert!(!state.global().interned_lt.contains_key(&payload[..]));
7679 assert_eq!(state.global().heap.allocation_token(id), None);
7680 }
7681
7682 #[test]
7683 fn gc_phase_predicates_follow_heap_state() {
7684 let mut state = new_state().expect("state should initialize");
7685 let _heap_guard = {
7686 let g = state.global();
7687 lua_gc::HeapGuard::push(&g.heap)
7688 };
7689
7690 {
7691 let mut g = state.global_mut();
7692 g.gckind = GcKind::Incremental as u8;
7693 g.lastatomic = 0;
7694 assert!(!g.is_gen_mode());
7695 g.lastatomic = 1;
7696 assert!(g.is_gen_mode());
7697 g.lastatomic = 0;
7698 }
7699
7700 let mut roots = Vec::new();
7701 for _ in 0..16 {
7702 let table = state.new_table();
7703 roots.push(state.external_root_value(LuaValue::Table(table)));
7704 }
7705
7706 let mut saw_keep = false;
7707 let mut saw_sweep = false;
7708 for _ in 0..128 {
7709 state.gc().incremental_step(1);
7710 let g = state.global();
7711 let heap_state = g.heap.gc_state();
7712 assert_eq!(g.keep_invariant(), heap_state.is_invariant());
7713 assert_eq!(g.is_sweep_phase(), heap_state.is_sweep());
7714 saw_keep |= g.keep_invariant();
7715 saw_sweep |= g.is_sweep_phase();
7716 if heap_state.is_pause() && saw_keep && saw_sweep {
7717 break;
7718 }
7719 }
7720
7721 assert!(
7722 saw_keep,
7723 "incremental cycle should expose an invariant phase"
7724 );
7725 assert!(saw_sweep, "incremental cycle should expose a sweep phase");
7726
7727 for key in roots {
7728 assert!(state.external_unroot_value(key).is_some());
7729 }
7730 state.gc().full_collect();
7731 }
7732
7733 #[test]
7734 fn gc_barrier_keeps_new_child_stored_in_black_parent() {
7735 let mut state = new_state().expect("state should initialize");
7736 let _heap_guard = {
7737 let g = state.global();
7738 lua_gc::HeapGuard::push(&g.heap)
7739 };
7740
7741 let parent = state.new_table();
7742 let parent_key = state.external_root_value(LuaValue::Table(parent));
7743 state.gc().incremental_step(1);
7744 assert!(
7745 state.global().keep_invariant(),
7746 "test setup should leave the parent marked during an active cycle"
7747 );
7748
7749 let child = state.new_table();
7750 let parent_value = LuaValue::Table(parent);
7751 let child_value = LuaValue::Table(child);
7752 parent
7753 .raw_set_int(&mut state, 1, child_value)
7754 .expect("table store should succeed");
7755 state.gc_barrier_back(&parent_value, &child_value);
7756
7757 for _ in 0..128 {
7758 if state.gc().incremental_step(1) {
7759 break;
7760 }
7761 }
7762
7763 assert_eq!(state.global().heap.allgc_count(), 2);
7764 assert_eq!(
7765 parent.get_int(1).as_table().map(|t| t.identity()),
7766 Some(child.identity())
7767 );
7768
7769 assert!(state.external_unroot_value(parent_key).is_some());
7770 state.gc().full_collect();
7771 assert_eq!(state.global().heap.allgc_count(), 0);
7772 }
7773
7774 #[test]
7775 fn generational_mode_promotes_and_barriers_age_objects() {
7776 let mut state = new_state().expect("state should initialize");
7777 let _heap_guard = {
7778 let g = state.global();
7779 lua_gc::HeapGuard::push(&g.heap)
7780 };
7781
7782 let parent = state.new_table();
7783 let parent_key = state.external_root_value(LuaValue::Table(parent));
7784
7785 state.gc().change_mode(GcKind::Generational);
7786 assert_eq!(parent.0.age(), lua_gc::GcAge::Old);
7787 assert_eq!(parent.0.color(), lua_gc::Color::Black);
7788 let majorbase = state.global().gc_estimate;
7789 assert!(majorbase > 0);
7790 assert!(state.global().gc_debt() <= 0);
7791
7792 let child = state.new_table();
7793 let parent_value = LuaValue::Table(parent);
7794 let child_value = LuaValue::Table(child);
7795 parent
7796 .raw_set_int(&mut state, 1, child_value.clone())
7797 .expect("table store should succeed");
7798 state.gc_barrier_back(&parent_value, &child_value);
7799 assert_eq!(parent.0.age(), lua_gc::GcAge::Touched1);
7800 assert_eq!(parent.0.color(), lua_gc::Color::Gray);
7801 assert_eq!(child.0.age(), lua_gc::GcAge::New);
7802
7803 let metatable = state.new_table();
7804 parent.set_metatable(Some(metatable));
7805 state.gc().obj_barrier(&parent, &metatable);
7806 assert_eq!(metatable.0.age(), lua_gc::GcAge::Old0);
7807
7808 assert!(state.gc().generational_step_minor_only());
7809 assert_eq!(parent.0.age(), lua_gc::GcAge::Touched2);
7810 assert_eq!(child.0.age(), lua_gc::GcAge::Survival);
7811 assert_eq!(metatable.0.age(), lua_gc::GcAge::Old1);
7812 assert_eq!(state.global().gc_estimate, majorbase);
7813 assert!(state.global().gc_debt() <= 0);
7814
7815 state.gc().change_mode(GcKind::Incremental);
7816 assert_eq!(parent.0.age(), lua_gc::GcAge::New);
7817 assert_eq!(child.0.age(), lua_gc::GcAge::New);
7818 assert_eq!(metatable.0.age(), lua_gc::GcAge::New);
7819
7820 assert!(state.external_unroot_value(parent_key).is_some());
7821 state.gc().full_collect();
7822 }
7823
7824 #[test]
7825 fn generational_upvalue_write_barrier_marks_young_child_old0() {
7826 let mut state = new_state().expect("state should initialize");
7827 let _heap_guard = {
7828 let g = state.global();
7829 lua_gc::HeapGuard::push(&g.heap)
7830 };
7831
7832 let proto = state.new_proto();
7833 let closure = state.new_lclosure(proto, 1);
7834 let closure_key = state.external_root_value(LuaValue::Function(LuaClosure::Lua(closure)));
7835 state.gc().change_mode(GcKind::Generational);
7836 let uv = closure.upval(0);
7837 assert_eq!(uv.0.age(), lua_gc::GcAge::Old);
7838
7839 let child = state.new_table();
7840 state
7841 .upvalue_set(&closure, 0, LuaValue::Table(child))
7842 .expect("closed upvalue write should succeed");
7843 assert_eq!(child.0.age(), lua_gc::GcAge::Old0);
7844
7845 assert!(state.external_unroot_value(closure_key).is_some());
7846 state.gc().full_collect();
7847 }
7848
7849 #[test]
7850 fn cclosure_setupvalue_replaces_upvalue() {
7851 let mut state = new_state().expect("state should initialize");
7852 let _heap_guard = {
7853 let g = state.global();
7854 lua_gc::HeapGuard::push(&g.heap)
7855 };
7856
7857 let first = state.new_table();
7858 state.push(LuaValue::Table(first));
7859 crate::api::push_cclosure(&mut state, test_noop_cclosure, 1)
7860 .expect("C closure creation should succeed");
7861 let LuaValue::Function(LuaClosure::C(ccl)) = state.get_at(state.top_idx() - 1) else {
7862 panic!("expected heavy C closure");
7863 };
7864
7865 let second = state.new_table();
7866 state.push(LuaValue::Table(second));
7867 let name =
7868 crate::api::setup_value(&mut state, -2, 1).expect("C closure upvalue should exist");
7869
7870 assert!(name.is_empty());
7871 let upvalues = ccl.upvalues.borrow();
7872 let LuaValue::Table(actual) = upvalues[0].clone() else {
7873 panic!("expected table upvalue");
7874 };
7875 assert_eq!(actual.identity(), second.identity());
7876 }
7877
7878 #[test]
7879 fn generational_cclosure_setupvalue_barrier_marks_young_child_old0() {
7880 let mut state = new_state().expect("state should initialize");
7881 let _heap_guard = {
7882 let g = state.global();
7883 lua_gc::HeapGuard::push(&g.heap)
7884 };
7885
7886 state.push(LuaValue::Nil);
7887 crate::api::push_cclosure(&mut state, test_noop_cclosure, 1)
7888 .expect("C closure creation should succeed");
7889 let LuaValue::Function(LuaClosure::C(ccl)) = state.get_at(state.top_idx() - 1) else {
7890 panic!("expected heavy C closure");
7891 };
7892 let closure_key = state.external_root_value(LuaValue::Function(LuaClosure::C(ccl)));
7893
7894 state.gc().change_mode(GcKind::Generational);
7895 assert_eq!(ccl.0.age(), lua_gc::GcAge::Old);
7896
7897 let child = state.new_table();
7898 state.push(LuaValue::Table(child));
7899 crate::api::setup_value(&mut state, -2, 1).expect("C closure upvalue should exist");
7900
7901 assert_eq!(child.0.age(), lua_gc::GcAge::Old0);
7902
7903 assert!(state.external_unroot_value(closure_key).is_some());
7904 state.gc().full_collect();
7905 }
7906
7907 #[test]
7908 fn generational_closure_upvalue_slot_barrier_marks_new_upval_old0() {
7909 let mut state = new_state().expect("state should initialize");
7910 let _heap_guard = {
7911 let g = state.global();
7912 lua_gc::HeapGuard::push(&g.heap)
7913 };
7914
7915 let proto = state.new_proto();
7916 let closure = state.new_lclosure(proto, 1);
7917 let closure_key = state.external_root_value(LuaValue::Function(LuaClosure::Lua(closure)));
7918 state.gc().change_mode(GcKind::Generational);
7919 assert_eq!(closure.0.age(), lua_gc::GcAge::Old);
7920
7921 let replacement = state.new_upval_closed(LuaValue::Nil);
7922 closure.set_upval(0, replacement);
7923 state.gc().obj_barrier(&closure, &replacement);
7924 assert_eq!(replacement.0.age(), lua_gc::GcAge::Old0);
7925
7926 assert!(state.external_unroot_value(closure_key).is_some());
7927 state.gc().full_collect();
7928 }
7929
7930 #[test]
7931 fn cross_thread_upvalue_mirror_traces_values_as_roots() {
7932 let mut state = new_state().expect("state should initialize");
7933 let _heap_guard = {
7934 let g = state.global();
7935 lua_gc::HeapGuard::push(&g.heap)
7936 };
7937
7938 let mirrored = state.new_table();
7939 state
7940 .global_mut()
7941 .cross_thread_upvals
7942 .insert((999, StackIdx(0)), LuaValue::Table(mirrored));
7943
7944 state.gc().full_collect();
7945 assert_eq!(state.global().heap.allgc_count(), 1);
7946
7947 state.global_mut().cross_thread_upvals.clear();
7948 state.gc().full_collect();
7949 assert_eq!(state.global().heap.allgc_count(), 0);
7950 }
7951
7952 #[test]
7953 fn generational_full_collect_promotes_new_survivors_to_old() {
7954 let mut state = new_state().expect("state should initialize");
7955 let _heap_guard = {
7956 let g = state.global();
7957 lua_gc::HeapGuard::push(&g.heap)
7958 };
7959
7960 state.gc().change_mode(GcKind::Generational);
7961 let table = state.new_table();
7962 let table_key = state.external_root_value(LuaValue::Table(table));
7963 assert_eq!(table.0.age(), lua_gc::GcAge::New);
7964
7965 state.gc().full_collect();
7966 assert_eq!(table.0.age(), lua_gc::GcAge::Old);
7967 assert_eq!(table.0.color(), lua_gc::Color::Black);
7968
7969 assert!(state.external_unroot_value(table_key).is_some());
7970 state.gc().full_collect();
7971 }
7972
7973 #[test]
7974 fn gc_packed_params_return_user_visible_values() {
7975 let mut state = new_state().expect("state should initialize");
7976 assert_eq!(
7977 crate::api::gc(&mut state, crate::api::GcArgs::SetPause { value: 200 }),
7978 200
7979 );
7980 assert_eq!(state.global().gc_pause_param(), 200);
7981 assert_eq!(
7982 crate::api::gc(&mut state, crate::api::GcArgs::SetStepMul { value: 200 }),
7983 100
7984 );
7985 assert_eq!(state.global().gc_stepmul_param(), 200);
7986
7987 crate::api::gc(
7988 &mut state,
7989 crate::api::GcArgs::Gen {
7990 minormul: 0,
7991 majormul: 200,
7992 },
7993 );
7994 assert_eq!(state.global().gc_genmajormul_param(), 200);
7995 }
7996
7997 #[test]
7998 fn generational_step_runs_bad_major_when_growth_exceeds_genmajormul() {
7999 let mut state = new_state().expect("state should initialize");
8000 let _heap_guard = {
8001 let g = state.global();
8002 lua_gc::HeapGuard::push(&g.heap)
8003 };
8004
8005 let root = state.new_table();
8006 let root_key = state.external_root_value(LuaValue::Table(root));
8007 state.gc().change_mode(GcKind::Generational);
8008
8009 let root_value = LuaValue::Table(root);
8010 for i in 1..=64 {
8011 let child = state.new_table();
8012 let child_value = LuaValue::Table(child);
8013 root.raw_set_int(&mut state, i, child_value.clone())
8014 .expect("table store should succeed");
8015 state.gc_barrier_back(&root_value, &child_value);
8016 }
8017
8018 {
8019 let mut g = state.global_mut();
8020 g.gc_estimate = 1;
8021 set_debt(&mut *g, 1);
8022 }
8023
8024 assert!(state.gc().generational_step());
8025 let g = state.global();
8026 assert!(g.is_gen_mode());
8027 assert!(
8028 g.lastatomic > 0,
8029 "bad major collection should arm stepgenfull"
8030 );
8031 assert!(g.gc_estimate > 1);
8032 assert!(g.gc_debt() <= 0);
8033 assert_eq!(root.0.age(), lua_gc::GcAge::Old);
8034 drop(g);
8035
8036 assert!(state.external_unroot_value(root_key).is_some());
8037 state.gc().full_collect();
8038 }
8039
8040 #[test]
8041 fn generational_implicit_step_runs_major_when_heap_threshold_exceeded() {
8042 let mut state = new_state().expect("state should initialize");
8043 let _heap_guard = {
8044 let g = state.global();
8045 lua_gc::HeapGuard::push(&g.heap)
8046 };
8047
8048 let root = state.new_table();
8049 let root_key = state.external_root_value(LuaValue::Table(root));
8050 state.gc().change_mode(GcKind::Generational);
8051
8052 let root_value = LuaValue::Table(root);
8053 for i in 1..=64 {
8054 let child = state.new_table();
8055 let child_value = LuaValue::Table(child);
8056 root.raw_set_int(&mut state, i, child_value.clone())
8057 .expect("table store should succeed");
8058 state.gc_barrier_back(&root_value, &child_value);
8059 }
8060
8061 {
8062 let mut g = state.global_mut();
8063 g.gc_estimate = 1;
8064 set_debt(&mut *g, -1);
8065 g.heap.set_threshold_bytes(1);
8066 }
8067
8068 assert!(state.gc().generational_step());
8069 let g = state.global();
8070 assert!(g.is_gen_mode());
8071 assert!(
8072 g.lastatomic > 0,
8073 "implicit threshold-triggered growth should arm a bad major"
8074 );
8075 assert!(g.gc_debt() <= 0);
8076 drop(g);
8077
8078 assert!(state.external_unroot_value(root_key).is_some());
8079 state.gc().full_collect();
8080 }
8081
8082 #[test]
8083 fn generational_stepgenfull_returns_to_gen_after_good_collection() {
8084 let mut state = new_state().expect("state should initialize");
8085 let _heap_guard = {
8086 let g = state.global();
8087 lua_gc::HeapGuard::push(&g.heap)
8088 };
8089
8090 let root = state.new_table();
8091 let root_key = state.external_root_value(LuaValue::Table(root));
8092 state.gc().change_mode(GcKind::Generational);
8093 {
8094 let mut g = state.global_mut();
8095 g.lastatomic = 1024;
8096 }
8097
8098 assert!(state.gc().generational_step());
8099 let g = state.global();
8100 assert_eq!(g.gckind, GcKind::Generational as u8);
8101 assert_eq!(g.lastatomic, 0);
8102 assert!(g.gc_debt() <= 0);
8103 assert_eq!(root.0.age(), lua_gc::GcAge::Old);
8104 assert_eq!(root.0.color(), lua_gc::Color::Black);
8105 drop(g);
8106
8107 assert!(state.external_unroot_value(root_key).is_some());
8108 state.gc().full_collect();
8109 }
8110
8111 #[test]
8112 fn generational_step_zero_reports_false_without_positive_debt() {
8113 let mut state = new_state().expect("state should initialize");
8114 let _heap_guard = {
8115 let g = state.global();
8116 lua_gc::HeapGuard::push(&g.heap)
8117 };
8118
8119 state.gc().change_mode(GcKind::Generational);
8120 assert_eq!(
8121 crate::api::gc(&mut state, crate::api::GcArgs::Step { data: 0 }),
8122 0
8123 );
8124 assert_eq!(
8125 crate::api::gc(&mut state, crate::api::GcArgs::Step { data: 1 }),
8126 1
8127 );
8128 }
8129}