1use std::sync::{Arc, Weak};
12
13use crate::bytecode::{ArithOp, Instr, MULTI, Proto, Rk};
14use crate::heap::{CoStatus, Func, Heap, Pending, STEP_SIZE, ThreadState, UPVAL_SIZE, Upval};
15use crate::number;
16use crate::table::SetError;
17use crate::value::{FuncRef, StrRef, TableRef, ThreadRef, Value};
18use crate::{LimitKind, Limits};
19
20pub(crate) type NativeFn = fn(&mut Lua, Args) -> Result<Flow, LuaError>;
22
23#[derive(Clone, Copy, Debug)]
25pub struct Args {
26 pub(crate) func: usize,
27 pub(crate) base: usize,
28 pub(crate) n: usize,
29}
30
31pub(crate) enum Flow {
33 Return,
35 PCall { handler: Option<Value>, nargs: usize },
37 Yield,
39 Resume { co: ThreadRef, wrap: bool },
41 Call3 { f: Value, arg: Value },
44}
45
46#[derive(Debug)]
48pub(crate) enum ErrorKind {
49 Value(Value),
51 Msg(String),
53 Plain(String),
56 Type { op: &'static str, ty: String, operand: u8 },
58 Call { ty: String },
60 Arg(usize, String),
62 IntRepr { operand: u8 },
64 Limit(LimitKind),
66 Pending,
69}
70
71#[derive(Clone, Copy, Debug)]
73pub(crate) enum Settled {
74 Plain,
76 Found,
78 Absent(Option<(u32, usize)>),
81}
82
83#[derive(Debug)]
87pub(crate) struct LuaError(Box<ErrorKind>);
88
89const _: () = assert!(std::mem::size_of::<Result<Value, LuaError>>() == 16);
90
91#[derive(Clone, Copy, Debug)]
94pub(crate) struct PendingCall {
95 pos: usize,
96 bthread: ThreadRef,
97 bdepth: usize,
98 keep: bool,
99 ntop: usize,
100}
101
102impl From<ErrorKind> for LuaError {
103 #[cold]
104 fn from(k: ErrorKind) -> Self {
105 LuaError(Box::new(k))
106 }
107}
108
109#[allow(non_snake_case, reason = "built as the `ErrorKind` variants they stand for")]
110impl LuaError {
111 pub(crate) fn msg(s: impl Into<String>) -> Self {
112 ErrorKind::Msg(s.into()).into()
113 }
114 pub(crate) fn Value(v: Value) -> Self {
115 ErrorKind::Value(v).into()
116 }
117 pub(crate) fn Msg(s: String) -> Self {
118 ErrorKind::Msg(s).into()
119 }
120 pub(crate) fn Plain(s: String) -> Self {
121 ErrorKind::Plain(s).into()
122 }
123 pub(crate) fn Arg(n: usize, s: String) -> Self {
124 ErrorKind::Arg(n, s).into()
125 }
126 pub(crate) fn Limit(k: LimitKind) -> Self {
127 ErrorKind::Limit(k).into()
128 }
129 pub(crate) fn kind(&self) -> &ErrorKind {
130 &self.0
131 }
132 pub(crate) fn into_kind(self) -> ErrorKind {
133 *self.0
134 }
135 pub(crate) fn plain(mut self) -> Self {
137 if let ErrorKind::Msg(m) = &mut *self.0 {
138 *self.0 = ErrorKind::Plain(std::mem::take(m));
139 }
140 self
141 }
142 pub(crate) fn is_pending(&self) -> bool {
145 matches!(*self.0, ErrorKind::Pending)
146 }
147
148 pub(crate) fn limit(&self) -> Option<LimitKind> {
149 match *self.0 {
150 ErrorKind::Limit(k) => Some(k),
151 _ => None,
152 }
153 }
154}
155
156#[derive(Clone, Copy, PartialEq, Eq, Debug)]
158#[repr(u8)]
159pub(crate) enum Tm {
160 Index = 0,
161 NewIndex,
162 Gc,
163 Mode,
164 Len,
165 Eq,
166 Add,
167 Sub,
168 Mul,
169 Mod,
170 Pow,
171 Div,
172 IDiv,
173 BAnd,
174 BOr,
175 BXor,
176 Shl,
177 Shr,
178 Unm,
179 BNot,
180 Lt,
181 Le,
182 Concat,
183 Call,
184 Close,
185 ToString,
186 Name,
187 Metatable,
188 Pairs,
189}
190
191pub(crate) const TM_NAMES: [&str; 29] = [
192 "__index",
193 "__newindex",
194 "__gc",
195 "__mode",
196 "__len",
197 "__eq",
198 "__add",
199 "__sub",
200 "__mul",
201 "__mod",
202 "__pow",
203 "__div",
204 "__idiv",
205 "__band",
206 "__bor",
207 "__bxor",
208 "__shl",
209 "__shr",
210 "__unm",
211 "__bnot",
212 "__lt",
213 "__le",
214 "__concat",
215 "__call",
216 "__close",
217 "__tostring",
218 "__name",
219 "__metatable",
220 "__pairs",
221];
222
223fn arith_tm(op: ArithOp) -> Tm {
224 match op {
225 ArithOp::Add => Tm::Add,
226 ArithOp::Sub => Tm::Sub,
227 ArithOp::Mul => Tm::Mul,
228 ArithOp::Mod => Tm::Mod,
229 ArithOp::Pow => Tm::Pow,
230 ArithOp::Div => Tm::Div,
231 ArithOp::IDiv => Tm::IDiv,
232 ArithOp::BAnd => Tm::BAnd,
233 ArithOp::BOr => Tm::BOr,
234 ArithOp::BXor => Tm::BXor,
235 ArithOp::Shl => Tm::Shl,
236 ArithOp::Shr => Tm::Shr,
237 }
238}
239
240fn is_bitwise(op: ArithOp) -> bool {
241 matches!(op, ArithOp::BAnd | ArithOp::BOr | ArithOp::BXor | ArithOp::Shl | ArithOp::Shr)
242}
243
244fn c_level(e: LuaError) -> LuaError {
247 match e.into_kind() {
248 ErrorKind::Call { ty } => LuaError::Plain(format!("attempt to call a {ty} value")),
249 other => other.into(),
250 }
251}
252
253#[inline]
256fn tfor_wanted(c: u16) -> i32 {
257 if c == MULTI { -1 } else { i32::from(c) }
258}
259
260#[derive(Clone, Copy, Debug)]
262pub(crate) enum Cont {
263 Store(usize),
265 Discard,
267 Cond { k: bool },
269 Concat { a: usize, n: usize },
271 Closing { level: usize, then: AfterClose },
273 Three { wanted: i32 },
276 ErrClosing { frame: usize },
279 Nest { dest: usize, bits: NestBits, wanted: i32, back: u32, n: u32 },
295}
296
297#[derive(Clone, Copy, Debug, PartialEq, Eq)]
299pub(crate) enum Then {
300 None = 0,
301 Store = 1,
302 Discard = 2,
303 CondFalse = 3,
304 CondTrue = 4,
305 Concat = 5,
306}
307
308#[derive(Clone, Copy, Debug, PartialEq, Eq)]
311pub(crate) struct NestBits(u32);
312
313impl NestBits {
314 fn new(levels: u32, then: Then, three: bool) -> Option<NestBits> {
317 (levels < 1 << 27).then_some(NestBits(levels << 4 | (then as u32) << 1 | u32::from(three)))
318 }
319 #[inline]
320 pub(crate) fn levels(self) -> u32 {
321 self.0 >> 4
322 }
323 #[inline]
324 pub(crate) fn three(self) -> bool {
325 self.0 & 1 != 0
326 }
327 #[inline]
328 pub(crate) fn then(self) -> Then {
329 match (self.0 >> 1) & 7 {
330 1 => Then::Store,
331 2 => Then::Discard,
332 3 => Then::CondFalse,
333 4 => Then::CondTrue,
334 5 => Then::Concat,
335 _ => Then::None,
336 }
337 }
338 fn with_levels(self, levels: u32) -> Option<NestBits> {
339 NestBits::new(levels, self.then(), self.three())
340 }
341 fn with_three(self) -> NestBits {
342 NestBits(self.0 | 1)
343 }
344}
345
346fn pack_then(c: Cont, dest: usize) -> Option<(Then, u32, u32)> {
351 let back = |slot: usize| dest.checked_sub(slot).and_then(|d| u32::try_from(d).ok());
352 match c {
353 Cont::Store(slot) => Some((Then::Store, back(slot)?, 0)),
354 Cont::Discard => Some((Then::Discard, 0, 0)),
355 Cont::Cond { k } => Some((if k { Then::CondTrue } else { Then::CondFalse }, 0, 0)),
356 Cont::Concat { a, n } => Some((Then::Concat, back(a)?, u32::try_from(n).ok()?)),
357 _ => None,
358 }
359}
360
361fn unpack_then(then: Then, dest: usize, back: u32, n: u32) -> Option<Cont> {
363 let slot = dest.saturating_sub(back as usize);
364 match then {
365 Then::None => None,
366 Then::Store => Some(Cont::Store(slot)),
367 Then::Discard => Some(Cont::Discard),
368 Then::CondFalse => Some(Cont::Cond { k: false }),
369 Then::CondTrue => Some(Cont::Cond { k: true }),
370 Then::Concat => Some(Cont::Concat { a: slot, n: n as usize }),
371 }
372}
373
374impl Cont {
375 pub(crate) fn is_metamethod(self) -> bool {
378 matches!(self, Cont::Store(_) | Cont::Discard | Cont::Cond { .. } | Cont::Concat { .. } | Cont::Closing { .. })
379 }
380}
381
382#[derive(Clone, Copy, Debug)]
384pub(crate) enum AfterClose {
385 Nothing,
387 Return { src: usize, n: usize },
389}
390
391const _: () = assert!(std::mem::size_of::<Cont>() <= 32 && std::mem::size_of::<FrameKind>() <= 48);
393const _: () = assert!(std::mem::size_of::<Frame>() <= 128);
396
397fn nest_of(kind: FrameKind, func: usize) -> Option<Cont> {
403 let FrameKind::Protected { dest, wanted, cont } = kind else { return None };
404 let nest = match cont {
405 Some(Cont::Nest { dest, bits, wanted, back, n }) if !bits.three() => {
406 Cont::Nest { dest, bits: bits.with_levels(bits.levels().checked_add(1)?)?, wanted, back, n }
407 }
408 None => Cont::Nest { dest, bits: NestBits::new(1, Then::None, false)?, wanted, back: 0, n: 0 },
409 Some(c) => {
410 let (then, back, n) = pack_then(c, dest)?;
411 Cont::Nest { dest, bits: NestBits::new(1, then, false)?, wanted, back, n }
412 }
413 };
414 let Cont::Nest { dest, bits, .. } = nest else { return None };
415 (dest.checked_add(bits.levels() as usize) == Some(func)).then_some(nest)
416}
417
418#[inline]
421pub(crate) fn pcall_levels(kind: FrameKind) -> usize {
422 match kind {
423 FrameKind::Protected { cont: Some(Cont::Nest { bits, .. }), .. } => 1 + bits.levels() as usize,
424 FrameKind::Protected { .. } => 1,
425 _ => 0,
426 }
427}
428
429#[inline]
432fn under_pairs(kind: FrameKind) -> bool {
433 match kind {
434 FrameKind::Cont(Cont::Three { .. }) | FrameKind::Protected { cont: Some(Cont::Three { .. }), .. } => true,
435 FrameKind::Cont(Cont::Nest { bits, .. }) | FrameKind::Protected { cont: Some(Cont::Nest { bits, .. }), .. } => bits.three(),
436 _ => false,
437 }
438}
439
440#[inline]
445pub(crate) fn c_calls(kind: FrameKind) -> usize {
446 let meta = match kind {
447 FrameKind::Cont(Cont::Three { .. }) | FrameKind::Normal => false,
448 FrameKind::Cont(Cont::Nest { bits, .. }) => bits.then() != Then::None,
449 FrameKind::Cont(_) => true,
450 FrameKind::Protected { cont: Some(Cont::Nest { bits, .. }), .. } => bits.then() != Then::None,
451 FrameKind::Protected { cont, dest, .. } => cont.is_some_and(|c| pack_then(c, dest).is_some()),
452 };
453 pcall_levels(kind) + usize::from(meta) + usize::from(under_pairs(kind))
454}
455
456struct Dead {
460 ec: Option<(usize, usize)>,
462 min_lo: usize,
464 los: std::collections::BinaryHeap<usize>,
466}
467
468impl Dead {
469 fn add(&mut self, lo: usize) {
471 self.min_lo = self.min_lo.min(lo);
472 self.los.push(lo);
473 }
474
475 fn activate(&mut self, t: usize) {
477 if let Some((lo, hi)) = self.ec
478 && hi > t
479 {
480 self.ec = None;
481 self.add(lo);
482 }
483 }
484
485 fn gone(&self, t: usize) -> bool {
486 self.min_lo < t
487 }
488
489 fn is_lo(&mut self, t: usize) -> bool {
491 while self.los.peek().is_some_and(|&l| l > t) {
492 self.los.pop();
493 }
494 self.los.peek() == Some(&t)
495 }
496}
497
498fn pass_rust(back: &mut Option<usize>, level: usize, k: usize) -> Option<String> {
501 let b = *back.get_or_insert(level);
502 match b.checked_sub(k) {
503 Some(left) => {
504 *back = Some(left);
505 None
506 }
507 None => Some(String::new()),
508 }
509}
510
511#[derive(Clone, Copy, Debug, Default)]
512pub(crate) enum FrameKind {
513 #[default]
514 Normal,
515 Protected { dest: usize, wanted: i32, cont: Option<Cont> },
518 Cont(Cont),
519}
520
521pub(crate) struct Frame {
523 pub closure: FuncRef,
524 pub proto: u32,
527 pub func: usize,
529 pub base: usize,
531 pub pc: usize,
532 pub nresults: i32,
533 pub vstart: usize,
534 pub vcount: usize,
535 pub kind: FrameKind,
536 pub from_lua: bool,
538 pub tail: bool,
540 pub handler: Option<Value>,
542}
543
544#[derive(Clone, Copy, Debug, PartialEq, Eq)]
546pub(crate) enum Act {
547 Lua(usize),
549 C(Option<usize>),
551 Base,
554}
555
556#[derive(Clone, Copy, Debug)]
558enum Run {
559 Lua(usize),
561 C { slot: Option<usize>, count: usize },
563 Base,
565}
566
567pub(crate) enum Called {
568 Lua,
570 Done,
572 Switched,
574}
575
576#[derive(Clone, Copy)]
580pub(crate) struct NestedCall {
581 pub func: usize,
582 pub nargs: usize,
583 pub kind: FrameKind,
584 pub handler: Option<Value>,
585}
586
587pub(crate) use crate::bytecode::{WIDE_WINDOW, WINDOW};
589pub(crate) const EXTRA_STACK: usize = 24;
591
592const SPARE_STACKS: usize = 8;
594const SPARE_STACK_SLOTS: usize = 2048;
595const SLOT_BYTES: usize = crate::table::SLOT_SIZE;
597pub(crate) const COROUTINE_COST: u64 =
601 ((crate::heap::THREAD_BASE + (256 + EXTRA_STACK + 1) * SLOT_BYTES) / 128) as u64;
602const MAX_TAG_LOOP: usize = 2000;
604const MAX_NAME: usize = 256;
606pub(crate) const LINK_COST: u64 = 2;
616
617pub(crate) const SHALLOW_LINKS: usize = 4;
623pub(crate) const DEEP_LINK_COST: u64 = 8;
624
625#[inline]
627pub(crate) const fn link_cost(n: usize) -> u64 {
628 if n < SHALLOW_LINKS { LINK_COST } else { DEEP_LINK_COST }
629}
630
631pub(crate) const FUEL_SLICE: i64 = 1 << 14;
632
633const ERROR_FUEL: u64 = 24;
636
637pub(crate) const WORK_PER_FUEL: usize = 4;
639
640const ATOMIC_DEFERRALS: u32 = 16;
643const FULL_GC_CHUNK: usize = 1 << 14;
645
646pub(crate) const FLOAT_TEXT_FUEL: u64 = 8;
649
650pub struct Lua {
653 pub(crate) heap: Heap,
654 pub(crate) cur: Box<ThreadState>,
655 pub(crate) cur_ref: ThreadRef,
656 pub(crate) main_ref: ThreadRef,
657 pub(crate) top: usize,
659 pub(crate) ntop: usize,
661 pub(crate) rets: Vec<Value>,
662 pub(crate) globals: TableRef,
663 pub(crate) registry: TableRef,
664 pub(crate) string_meta: Option<TableRef>,
665 pub(crate) tm_names: Vec<StrRef>,
666 pub(crate) ctx_epoch: u64,
670 pub(crate) match_state: Option<Box<crate::stdlib::pattern::MatchState>>,
673 pub(crate) spare_stacks: Vec<Vec<Value>>,
678 pub(crate) fuel: i64,
679 pub(crate) stopped_left: Option<u64>,
682 pub(crate) limits: Limits,
683 pub(crate) c_depth: usize,
685 pub(crate) native_depth: u32,
686 pub(crate) native_calls: u64,
688 pub(crate) native_from_lua: bool,
689 pub(crate) native_event: Option<&'static str>,
692 pub(crate) pending_event: Option<&'static str>,
694 pub(crate) native_name: &'static str,
696 pub(crate) stack_base: usize,
698 pub(crate) resume_depth: usize,
700 pub(crate) protected_natives: usize,
703 pub(crate) gc_work_carry: usize,
707 pub(crate) gc_mark_over: usize,
713 pub(crate) atomic_owed: usize,
715 pub(crate) gc_owed_probe: (u64, u64),
719 pub(crate) gc_pending: Option<(usize, usize, usize)>,
724 pub(crate) pending_call: Option<PendingCall>,
726 pub(crate) due_skip: bool,
728 pub(crate) gc_atomic_pre: Option<(usize, usize)>,
731 pub(crate) atomic_deferred: u32,
736 pub(crate) pending_start: Option<(Value, Vec<Value>)>,
739 pub(crate) gc_call_before: Option<u32>,
742 pub(crate) rewound: bool,
746 pub(crate) err_closing: Option<(usize, usize)>,
750 pub(crate) nested_pending: Option<NestedCall>,
754 pub(crate) native_stack: Vec<(ThreadRef, usize, usize, usize)>,
760 pub(crate) err_native: Option<((ThreadRef, usize, usize), usize, Value)>,
763 pub(crate) handler_native: Option<((ThreadRef, usize, usize), usize)>,
766 pub(crate) handler_raise: HandlerWatch,
771 pub(crate) roots: Vec<(Weak<()>, Value)>,
772 pub(crate) fast: bool,
774 pub(crate) full_steps: u64,
776 pub(crate) roots_pruned_at: usize,
778 pub(crate) scratch: Vec<Value>,
780 pub(crate) held: Vec<Value>,
783 pub(crate) scratch_floor: usize,
786 pub(crate) scratch_compact_at: usize,
788 pub(crate) held_compact_at: usize,
790 pub(crate) host_rets: Vec<Value>,
794 pub(crate) host_rets_base: usize,
795 pub(crate) libs: crate::Libs,
796 pub(crate) rng: [u64; 4],
797 pub(crate) output: Vec<u8>,
799 pub(crate) output_used: usize,
801 pub(crate) output_charged: usize,
803 pub(crate) warn_on: bool,
805 pub(crate) gc_generational: bool,
807 pub(crate) last_error: Option<(String, Value)>,
809 pub(crate) limit_hit: Option<LimitKind>,
812 pub(crate) reserve: i64,
815 pub(crate) interrupt: std::sync::Arc<std::sync::atomic::AtomicBool>,
817 pub(crate) time_limit: Option<(crate::Clock, std::time::Duration)>,
819 pub(crate) deadline: Option<std::time::Duration>,
821 pub(crate) app_data: std::collections::HashMap<std::any::TypeId, Box<dyn std::any::Any + Send>>,
823 pub(crate) print_sink: Option<Box<dyn FnMut(&str) + Send>>,
824 pub(crate) entry: u32,
826 pub(crate) poisoned: bool,
829 pub(crate) deferred: crate::diag::Deferred,
831 pub(crate) last_trace: Option<Vec<(usize, u32, u32)>>,
836 pub(crate) trace_sources: Vec<Arc<str>>,
838 pub(crate) os_clocks: (Option<crate::Clock>, Option<crate::Clock>),
841 pub(crate) utc_offset: i64,
843 pub(crate) names: crate::stdlib::Names,
845 pub(crate) modules: std::collections::HashMap<Vec<u8>, crate::ModuleSource>,
847 pub(crate) env: std::collections::HashMap<Vec<u8>, std::sync::Arc<[u8]>>,
850 pub(crate) env_name_max: usize,
852 pub(crate) io_std: [Option<crate::stdlib::io::FileState>; 3],
855 pub(crate) io_opener: Option<crate::IoOpener>,
857 pub(crate) io_meta: Option<TableRef>,
859 pub(crate) module_loader: Option<crate::ModuleLoader>,
861}
862
863pub(crate) type Vm = Lua;
864
865#[derive(Default, Clone)]
867pub(crate) struct HandlerWatch {
868 thread: Option<ThreadRef>,
870 raised: Option<usize>,
872 cross: Option<(usize, usize)>,
875 pos: Option<String>,
878}
879
880const RESUMER_FRAMES_PER_FUEL: usize = 1;
889
890const HANDLER_BASE_LEVELS: usize = 2;
893const C_HANDLER_LEVELS: usize = 200;
895const RESUME_LEVELS: usize = 1;
897
898const COMPACT_MIN: usize = 1024;
900
901pub(crate) fn compact_values(v: &mut Vec<Value>, from: usize) -> usize {
905 fn key(v: Value) -> Option<(u8, u32, u32)> {
906 match v {
907 Value::Str(r) => Some((0, r.idx, r.generation)),
908 Value::Table(r) => Some((1, r.idx, r.generation)),
909 Value::Func(r) => Some((2, r.idx, r.generation)),
910 Value::UserData(r) => Some((4, r.idx, r.generation)),
911 Value::Thread(r) => Some((5, r.idx, r.generation)),
912 _ => None,
913 }
914 }
915 let tail = v.split_off(from.min(v.len()));
916 let mut seen = std::collections::HashSet::with_capacity_and_hasher(tail.len(), MixHash);
917 v.extend(tail.into_iter().filter(|x| key(*x).is_some_and(|k| seen.insert(k))));
918 v.len() - from.min(v.len())
919}
920
921
922#[derive(Clone, Copy, Default)]
926struct MixHash;
927
928impl std::hash::BuildHasher for MixHash {
929 type Hasher = MixHasher;
930 fn build_hasher(&self) -> MixHasher {
931 MixHasher(0)
932 }
933}
934
935struct MixHasher(u64);
936
937impl std::hash::Hasher for MixHasher {
938 fn finish(&self) -> u64 {
939 let mut z = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
940 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
941 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
942 z ^ (z >> 31)
943 }
944 fn write(&mut self, bytes: &[u8]) {
945 for &b in bytes {
946 self.0 = self.0.rotate_left(8) ^ u64::from(b);
947 }
948 }
949 fn write_u8(&mut self, n: u8) {
950 self.0 = self.0.rotate_left(8) ^ u64::from(n);
951 }
952 fn write_u32(&mut self, n: u32) {
953 self.0 = self.0.rotate_left(32) ^ u64::from(n);
954 }
955}
956
957pub(crate) fn native_dead(_: &mut Lua, _: Args) -> Result<Flow, LuaError> {
958 Err(LuaError::msg("attempt to call a function that was collected"))
959}
960
961impl Lua {
962 pub(crate) fn new_vm(mut limits: Limits, libs: crate::Libs) -> Lua {
963 limits.stack_bytes = limits.stack_bytes.min(crate::test_stack_cap());
964 let base = limits.hash_seed.unwrap_or_else(crate::heap::random_seed);
966 let mut heap = Heap::new(limits.memory, crate::heap::mix_seed(base, 1));
967 heap.table_seed = crate::heap::mix_seed(base, 2);
968 heap.mem.headroom = 1 << 20;
970 heap.blocked += 1;
971 let main_ref = heap.new_thread(ThreadState::default()).unwrap_or(ThreadRef { idx: 0, generation: 0 });
972 let globals = heap.new_table(0, 64).unwrap_or(TableRef { idx: 0, generation: 0 });
973 let registry = heap.new_table(0, 8).unwrap_or(TableRef { idx: 0, generation: 0 });
974 let tm_names: Vec<StrRef> =
975 TM_NAMES.iter().map(|n| heap.intern(n.as_bytes()).unwrap_or(StrRef { idx: 0, generation: 0 })).collect();
976 heap.mode_key = tm_names.get(Tm::Mode as usize).copied();
977 let names = crate::stdlib::Names::new(&mut heap);
978 let seed = crate::heap::oneway_seed(base, 3);
982 let mut lua = Lua {
983 heap,
984 cur: Box::new(ThreadState { status: CoStatus::Running, ..ThreadState::default() }),
985 cur_ref: main_ref,
986 main_ref,
987 top: 0,
988 ntop: 0,
989 rets: Vec::new(),
990 globals,
991 registry,
992 string_meta: None,
993 tm_names,
994 ctx_epoch: 0,
995 match_state: None,
996 spare_stacks: Vec::new(),
997 fuel: i64::MAX,
998 stopped_left: None,
999 limits,
1000 c_depth: 0,
1001 native_depth: 0,
1002 native_calls: 0,
1003 native_from_lua: false,
1004 native_event: None,
1005 pending_event: None,
1006 native_name: "?",
1007 native_stack: Vec::new(),
1008 err_native: None,
1009 handler_native: None,
1010 handler_raise: HandlerWatch::default(),
1011 stack_base: crate::stack_pos(),
1012 resume_depth: 0,
1013 protected_natives: 0,
1014 gc_work_carry: 0,
1015 gc_mark_over: 0,
1016 atomic_owed: 0,
1017 gc_owed_probe: (0, 0),
1018 gc_pending: None,
1019 pending_call: None,
1020 due_skip: false,
1021 gc_atomic_pre: None,
1022 atomic_deferred: 0,
1023 pending_start: None,
1024 gc_call_before: None,
1025 rewound: false,
1026 err_closing: None,
1027 nested_pending: None,
1028 roots: Vec::new(),
1029 scratch: Vec::new(),
1030 held: Vec::new(),
1031 scratch_floor: 0,
1032 scratch_compact_at: COMPACT_MIN,
1033 held_compact_at: COMPACT_MIN,
1034 host_rets: Vec::new(),
1035 host_rets_base: 0,
1036 roots_pruned_at: 0,
1037 fast: std::env::var_os("REMEDYLUA_TEST_NO_FAST_LOOP").is_none(),
1038 full_steps: 0,
1039 libs,
1040 rng: [0; 4],
1041 output: Vec::new(),
1042 output_used: 0,
1043 output_charged: 0,
1044 warn_on: false,
1045 limit_hit: None,
1046 reserve: 0,
1047 interrupt: std::sync::Arc::default(),
1048 time_limit: None,
1049 deadline: None,
1050 app_data: std::collections::HashMap::new(),
1051 last_error: None,
1052 gc_generational: false,
1053 print_sink: None,
1054 entry: 0,
1055 poisoned: false,
1056 deferred: Vec::new(),
1057 last_trace: None,
1058 trace_sources: Vec::new(),
1059 os_clocks: crate::default_os_clocks(),
1060 utc_offset: 0,
1061 names,
1062 modules: std::collections::HashMap::new(),
1063 env: std::collections::HashMap::new(),
1064 env_name_max: 0,
1065 io_std: [None, None, None],
1066 io_opener: None,
1067 io_meta: None,
1068 module_loader: None,
1069 };
1070 lua.seed_random(seed, seed.rotate_left(32));
1074 crate::stdlib::open(&mut lua, libs);
1075 lua.heap.blocked -= 1;
1076 lua.heap.mem.headroom = 0;
1077 lua
1078 }
1079
1080 #[inline]
1083 pub(crate) fn st(&self, i: usize) -> Value {
1084 self.cur.stack.get(i).copied().unwrap_or(Value::Nil)
1085 }
1086
1087 #[inline]
1088 pub(crate) fn set_st(&mut self, i: usize, v: Value) {
1089 if let Some(s) = self.cur.stack.get_mut(i) {
1090 *s = v;
1091 }
1092 }
1093
1094 #[inline]
1096 pub(crate) fn ensure_stack(&mut self, n: usize) -> Result<(), LuaError> {
1097 if n <= self.cur.stack.len() {
1098 return Ok(());
1099 }
1100 self.grow_stack(n)
1101 }
1102
1103 #[inline(never)]
1105 fn grow_stack(&mut self, n: usize) -> Result<(), LuaError> {
1106 self.stack_room(n)?;
1107 self.cur.stack.resize(n, Value::Nil);
1108 Ok(())
1109 }
1110
1111 fn stack_room(&mut self, n: usize) -> Result<(), LuaError> {
1114 if n > self.limits.stack_slots {
1115 return Err(LuaError::msg("stack overflow"));
1116 }
1117 let old_cap = self.cur.stack.capacity();
1118 if n > old_cap {
1119 let new_cap = n.max(old_cap * 2).max(64).min(self.limits.stack_slots.max(n));
1120 self.charge_stack((new_cap - old_cap) * 16)?;
1121 self.cur.stack.reserve_exact(new_cap - self.cur.stack.len());
1122 }
1123 Ok(())
1124 }
1125
1126 #[cold]
1130 fn grow_frames(&mut self) -> Result<(), LuaError> {
1131 let cap = self.cur.frames.capacity();
1132 let want = (cap * 2).max(2);
1133 let charged = (want - cap) * crate::heap::FRAME_BYTES;
1134 self.charge_stack(charged)?;
1135 self.cur.frames.reserve_exact(want - self.cur.frames.len());
1136 let got = self.cur.frames.capacity().saturating_sub(cap) * crate::heap::FRAME_BYTES;
1137 self.heap.mem.settle(charged, got);
1138 Ok(())
1139 }
1140
1141 #[inline]
1145 pub(crate) fn ensure_window(&mut self, base: usize, width: usize) -> Result<(), LuaError> {
1146 let n = base + width + EXTRA_STACK;
1147 if n <= self.cur.stack.len() {
1148 return Ok(());
1149 }
1150 if base > self.limits.stack_slots {
1151 return Err(LuaError::msg("stack overflow"));
1152 }
1153 let old_cap = self.cur.stack.capacity();
1154 if n > old_cap {
1155 let new_cap = n.max(old_cap * 2).max(64);
1156 self.charge_stack((new_cap - old_cap) * 16)?;
1157 self.cur.stack.reserve_exact(new_cap - self.cur.stack.len());
1158 }
1159 self.cur.stack.resize(n, Value::Nil);
1160 Ok(())
1161 }
1162
1163 fn frame_top(&self) -> usize {
1165 self.cur.frames.last().map_or(0, |f| f.base + self.proto(f.proto).map_or(0, Proto::frame_size))
1166 }
1167
1168 fn call_top(&self) -> usize {
1170 let frame_top = self.frame_top();
1171 if self.native_depth > 0 || self.ntop > frame_top { self.ntop.max(frame_top) } else { frame_top }
1172 }
1173
1174 #[cold]
1186 fn memory_error(&mut self, own: bool) -> LuaError {
1187 let e = if self.c_levels().0 > C_HANDLER_LEVELS {
1188 LuaError::msg("C stack overflow")
1189 } else if self.cur.stack.len() > 1_000_000 || own && self.cur.mem_size().saturating_mul(4) >= self.heap.mem.cap {
1190 LuaError::msg("stack overflow")
1191 } else {
1192 return LuaError::Limit(LimitKind::Memory);
1193 };
1194 self.heap.mem.headroom = self.heap.mem.headroom.max(1 << 10);
1195 e
1196 }
1197
1198 pub(crate) fn charge_mem(&mut self, n: usize) -> Result<(), LuaError> {
1200 self.charge_room(n, false)
1201 }
1202
1203 fn charge_stack(&mut self, n: usize) -> Result<(), LuaError> {
1205 self.charge_room(n, true)
1206 }
1207
1208 fn charge_room(&mut self, n: usize, own: bool) -> Result<(), LuaError> {
1209 if self.heap.mem.charge(n).is_ok() {
1210 return Ok(());
1211 }
1212 self.emergency_gc()?;
1213 if self.heap.mem.charge(n).is_ok() || (self.release_held()? && self.heap.mem.charge(n).is_ok()) {
1214 return Ok(());
1215 }
1216 Err(self.memory_error(own))
1217 }
1218
1219 fn emergency_gc(&mut self) -> Result<(), LuaError> {
1220 if self.heap.blocked > 0 {
1221 return Err(LuaError::Limit(LimitKind::Memory));
1222 }
1223 self.full_gc()
1224 }
1225
1226 fn release_held(&mut self) -> Result<bool, LuaError> {
1229 if self.c_depth > 0 || self.held.is_empty() || self.heap.blocked > 0 {
1230 return Ok(false);
1231 }
1232 self.held.clear();
1233 self.full_gc()?;
1234 Ok(true)
1235 }
1236
1237 fn alloc<T>(&mut self, f: impl Fn(&mut Heap) -> Result<T, ()>) -> Result<T, LuaError> {
1239 if let Ok(v) = f(&mut self.heap) {
1240 return Ok(v);
1241 }
1242 self.emergency_gc()?;
1243 if let Ok(v) = f(&mut self.heap) {
1244 return Ok(v);
1245 }
1246 if self.release_held()? && let Ok(v) = f(&mut self.heap) {
1247 return Ok(v);
1248 }
1249 Err(self.memory_error(false))
1250 }
1251
1252 pub(crate) fn set_chunk_name(&mut self, f: Value, name: Value) {
1256 let Value::Func(fr) = f else { return };
1257 let Some(Func::Lua { proto, .. }) = self.heap.funcs.get(fr.idx) else { return };
1258 let mut todo = vec![*proto];
1259 while let Some(i) = todo.pop() {
1260 if let Some(p) = self.heap.protos.get_mut(i) {
1261 p.chunk_name = name;
1262 todo.extend_from_slice(&p.protos);
1263 }
1264 }
1265 if name.is_collectable() && self.heap.phase == crate::heap::Phase::Propagate {
1267 self.heap.mark(name);
1268 }
1269 }
1270
1271 pub(crate) fn prune_roots(&mut self) {
1273 let before = self.roots.len();
1274 self.roots.retain(|(w, _)| w.strong_count() > 0);
1275 self.heap.mem.release((before - self.roots.len()) * crate::heap::ROOT_BYTES);
1276 }
1277
1278 #[inline]
1280 pub(crate) fn hold(&mut self, v: Value) {
1281 if self.native_depth > 0 && v.is_collectable() {
1282 self.push_scratch(v);
1283 }
1284 }
1285
1286 #[inline]
1294 pub(crate) fn push_scratch(&mut self, v: Value) {
1295 self.scratch.push(v);
1296 if self.scratch.len() >= self.scratch_compact_at {
1297 let floor = self.scratch_floor.min(self.scratch.len());
1298 let kept = compact_values(&mut self.scratch, floor);
1299 self.scratch_compact_at = floor + kept + kept.max(COMPACT_MIN);
1300 }
1301 }
1302
1303 pub(crate) fn push_held(&mut self, v: Value) {
1307 self.held.push(v);
1308 if self.held.len() >= self.held_compact_at {
1309 let kept = compact_values(&mut self.held, 0);
1310 self.held_compact_at = kept + kept.max(COMPACT_MIN);
1311 }
1312 }
1313
1314 pub(crate) fn new_str(&mut self, b: &[u8]) -> Result<Value, LuaError> {
1316 if b.len() > self.limits.string_len {
1317 return Err(LuaError::Limit(LimitKind::Memory));
1318 }
1319 let r = self.alloc(|h| h.new_str(b))?;
1320 let v = Value::Str(r);
1321 self.hold(v);
1322 if self.native_depth > 0 {
1323 self.charge_probes()?;
1326 }
1327 Ok(v)
1328 }
1329
1330 pub(crate) fn new_table(&mut self, arr: usize, hash: usize) -> Result<TableRef, LuaError> {
1331 self.new_table_sized(arr, arr, hash)
1332 }
1333
1334 pub(crate) fn new_table_sized(&mut self, room: usize, asize: usize, hash: usize) -> Result<TableRef, LuaError> {
1337 let t = self.alloc(|h| h.new_table(room, hash))?;
1338 if let Some(tab) = self.heap.tables.get_mut(t.idx) {
1339 tab.init_sizes(asize, hash);
1340 }
1341 self.hold(Value::Table(t));
1342 Ok(t)
1343 }
1344
1345 pub(crate) fn new_native(&mut self, f: NativeFn, name: &'static str, upvals: Vec<Value>) -> Result<Value, LuaError> {
1346 let up: Box<[Value]> = upvals.into_boxed_slice();
1347 let size = crate::heap::FUNC_BASE + crate::heap::boxed(up.len() * 16);
1348 self.charge_mem(size)?;
1349 let r = self.heap.new_func_charged(Func::Native { f, upvals: up, name, in_place: 0 });
1350 let v = Value::Func(r);
1351 self.hold(v);
1352 Ok(v)
1353 }
1354
1355 #[inline]
1357 pub(crate) fn bytes(&self, s: StrRef) -> &[u8] {
1358 self.heap.str_bytes(s)
1359 }
1360
1361 pub(crate) fn charge_probes(&mut self) -> Result<(), LuaError> {
1366 self.charge(crate::table::take_probes())
1367 }
1368
1369 #[inline]
1372 pub(crate) fn charge(&mut self, n: u64) -> Result<(), LuaError> {
1373 self.fuel = self.fuel.saturating_sub(i64::try_from(n).unwrap_or(i64::MAX));
1374 if self.fuel < 0 || self.interrupt.load(std::sync::atomic::Ordering::Relaxed) {
1375 return self.refuel();
1376 }
1377 Ok(())
1378 }
1379
1380 #[cold]
1384 pub(crate) fn check_time(&mut self) -> Result<(), LuaError> {
1385 if self.interrupt.load(std::sync::atomic::Ordering::Relaxed) {
1386 return Err(LuaError::Limit(LimitKind::Interrupted));
1387 }
1388 if let (Some(at), Some((clock, _))) = (self.deadline, &self.time_limit)
1389 && clock() >= at
1390 {
1391 return Err(LuaError::Limit(LimitKind::Time));
1392 }
1393 Ok(())
1394 }
1395
1396 #[inline]
1407 pub(crate) fn settle_key(&mut self, k: Value) -> Result<Settled, LuaError> {
1408 match k {
1409 Value::Str(r) if self.heap.key_needs_settling(r) => self.settle_long_key(r),
1410 _ => Ok(Settled::Plain),
1411 }
1412 }
1413
1414 #[cold]
1415 #[inline(never)]
1416 fn settle_long_key(&mut self, r: crate::value::StrRef) -> Result<Settled, LuaError> {
1417 let mut run = None;
1418 while self.heap.strings.get(r.idx).is_some_and(|s| s.hash.get() == 0) {
1419 match self.heap.hash_piece(self.heap.str_bytes(r), &mut run) {
1420 Some(h) => self.heap.strings.get(r.idx).map_or((), |s| s.hash.set(h)),
1421 None => self.check_time()?,
1422 }
1423 }
1424 let Some(c) = self.heap.key_best(r) else { return Ok(Settled::Absent(None)) };
1425 let len = self.heap.str_bytes(r).len();
1426 let mut at = 0;
1427 while at < len {
1428 self.check_time()?;
1429 let end = at.saturating_add(crate::stdlib::COPY_PIECE).min(len);
1430 let found = self.heap.diff_piece(r.idx, c, at, end);
1431 self.charge_bytes(found.unwrap_or(end).saturating_sub(at))?;
1437 if let Some(d) = found {
1438 return Ok(Settled::Absent(Some((c, d))));
1439 }
1440 at = end;
1441 }
1442 self.heap.set_twin(r, c);
1443 Ok(Settled::Found)
1444 }
1445
1446 #[inline]
1449 pub(crate) fn get_in_settled(&mut self, t: u32, key: Value) -> Result<Value, LuaError> {
1450 let Some(tab) = self.heap.tables.get(t) else { return Ok(Value::Nil) };
1451 let v = tab.get(key);
1452 if !v.is_nil() {
1453 return Ok(v);
1454 }
1455 if let Settled::Absent(_) = self.settle_key(key)? {
1456 return Ok(v);
1458 }
1459 let Some(tab) = self.heap.tables.get(t) else { return Ok(Value::Nil) };
1460 Ok(self.heap.retry_key(key).map_or(v, |k| tab.get(k)))
1461 }
1462
1463 #[cold]
1468 pub(crate) fn refuel(&mut self) -> Result<(), LuaError> {
1469 if let Some(k) = self.limit_hit {
1470 return Err(LuaError::Limit(k));
1471 }
1472 if self.interrupt.load(std::sync::atomic::Ordering::Relaxed) {
1473 return Err(LuaError::Limit(LimitKind::Interrupted));
1474 }
1475 if let (Some(at), Some((clock, _))) = (self.deadline, &self.time_limit)
1476 && clock() >= at
1477 {
1478 return Err(LuaError::Limit(LimitKind::Time));
1479 }
1480 if !self.heap.mem.freeing.is_empty() {
1481 self.heap.mem.unpark();
1482 }
1483 if self.fuel >= 0 {
1484 return Ok(());
1485 }
1486 let give = self.reserve.min(FUEL_SLICE.saturating_add(self.fuel.saturating_neg()));
1487 self.reserve -= give;
1488 self.fuel = self.fuel.saturating_add(give);
1489 if self.fuel < 0 { Err(LuaError::Limit(LimitKind::Fuel)) } else { Ok(()) }
1490 }
1491
1492 fn mark_roots(&mut self) -> usize {
1496 let h = &mut self.heap;
1497 h.mark(Value::Table(self.registry));
1506 if let Some(l) = self.names.loaded {
1507 h.mark(Value::Table(l));
1508 }
1509 h.mark(Value::Table(self.globals));
1510 if let Some(m) = self.string_meta {
1511 h.mark(Value::Table(m));
1512 }
1513 for &n in &self.tm_names {
1514 h.mark(Value::Str(n));
1515 }
1516 self.names.mark(h);
1517 h.mark(Value::Thread(self.main_ref));
1518 h.mark(Value::Thread(self.cur_ref));
1519 let walked = h.mark_thread_state(&self.cur);
1520 let before = self.roots.len();
1522 self.roots.retain(|(w, _)| w.strong_count() > 0);
1523 h.mem.release((before - self.roots.len()) * crate::heap::ROOT_BYTES);
1524 for (_, v) in &self.roots {
1525 h.mark(*v);
1526 }
1527 for v in &self.scratch {
1528 h.mark(*v);
1529 }
1530 for v in &self.rets {
1531 h.mark(*v);
1532 }
1533 for v in &self.held {
1534 h.mark(*v);
1535 }
1536 for v in &self.host_rets {
1537 h.mark(*v);
1538 }
1539 if let Some((_, v)) = &self.last_error {
1540 h.mark(*v);
1541 }
1542 walked
1543 }
1544
1545 #[inline]
1547 pub(crate) fn gc_step(&mut self) -> Result<(), LuaError> {
1548 if self.heap.mem.trace.is_none() { self.gc_step_now() } else { self.gc_step_traced() }
1549 }
1550
1551 #[cold]
1553 #[inline(never)]
1554 fn gc_step_traced(&mut self) -> Result<(), LuaError> {
1555 use crate::gctrace::TraceOp;
1556 let op = match self.heap.phase {
1557 crate::heap::Phase::Pause => TraceOp::Start,
1558 crate::heap::Phase::Propagate if self.heap.atomic_suspended() => TraceOp::Atomic,
1559 crate::heap::Phase::Propagate => TraceOp::Mark,
1560 crate::heap::Phase::Sweep => TraceOp::Sweep,
1561 };
1562 let (scanned, fuel) = (self.heap.scanned, self.fuel.saturating_add(self.reserve));
1563 let resumed = self.gc_pending.is_some();
1564 let start = self.heap.mem.trace.as_mut().map(|t| {
1565 t.step += u32::from(!resumed);
1567 (t.now(), t.step)
1568 });
1569 let r = self.gc_step_now();
1570 let used = fuel.saturating_sub(self.fuel.max(-1).saturating_add(self.reserve.max(0)));
1571 if let (Some(t), Some((start, step))) = (self.heap.mem.trace.as_mut(), start) {
1572 t.note(op, step, self.heap.scanned.wrapping_sub(scanned) as u64, 0, u64::try_from(used).unwrap_or(0), start);
1573 }
1574 r
1575 }
1576
1577 fn gc_step_now(&mut self) -> Result<(), LuaError> {
1578 let resumed = self.gc_pending.take();
1580 let (born_step, full, budget) = if let Some(p) = resumed {
1581 p
1582 } else {
1583 let born_step = self.heap.born.take_step();
1584 if self.heap.blocked > 0 {
1585 return Ok(());
1586 }
1587 if self.heap.stopped {
1588 return self.charge_born();
1589 }
1590 if self.heap.mem.stress {
1591 let (fuel, reserve) = (self.fuel, self.reserve);
1594 self.fuel = i64::MAX;
1595 let r = self.full_gc();
1596 (self.fuel, self.reserve) = (fuel, reserve);
1597 return r;
1598 }
1599 let full = self.heap.step_budget();
1605 (born_step, full, full.min(self.gc_allow(self.heap.born.pending()).max(1)))
1607 };
1608 let mut unspent = 0;
1610 let mut work = if resumed.is_none() && self.heap.atomic_suspended() { std::mem::take(&mut self.atomic_owed) } else { 0 };
1614 match self.heap.phase {
1615 crate::heap::Phase::Pause => {
1616 let over = std::mem::take(&mut self.gc_mark_over);
1621 let pay = over.min(budget);
1622 work += pay;
1623 self.gc_mark_over = over - pay;
1624 self.gc_owed_probe.1 += pay as u64;
1625 work += self.clear_dead_stack();
1626 self.heap.start_cycle();
1627 work += self.mark_roots();
1628 work += 64;
1629 }
1630 crate::heap::Phase::Propagate => {
1631 let stop = crate::heap::Stop {
1633 interrupt: &self.interrupt,
1634 deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
1635 };
1636 let mut stopped = false;
1637 let done = if self.heap.atomic_suspended() {
1638 true
1639 } else {
1640 let mark = budget.saturating_sub(born_step);
1643 let (empty, w, cut, _) = if resumed.is_some() {
1644 self.heap.propagate_resume(&stop)
1645 } else {
1646 self.heap.step_slots = crate::heap::STEP_SLOTS;
1647 self.heap.propagate(mark.saturating_sub(self.gc_mark_over), &stop)
1648 };
1649 if std::mem::take(&mut self.heap.paused) {
1650 self.gc_pending = Some((born_step, full, budget));
1654 return Err(ErrorKind::Pending.into());
1655 }
1656 stopped = cut;
1657 let owed = self.gc_mark_over + w;
1658 let done = empty && owed <= mark;
1659 if done {
1660 self.gc_mark_over = 0;
1661 work += owed;
1662 } else {
1663 self.gc_mark_over = owed.saturating_sub(mark);
1664 work += mark.min(owed);
1665 unspent = full - budget;
1666 }
1667 done
1668 };
1669 if stopped {
1670 self.heap.mem.debt = -STEP_SIZE;
1673 let work = work + std::mem::take(&mut self.gc_work_carry);
1674 self.charge_gc(work / WORK_PER_FUEL)?;
1675 return Err(LuaError::Limit(self.stop_kind()));
1676 }
1677 let defer = done
1683 && self.native_depth > 0
1684 && self.gc_atomic_pre.is_none()
1685 && !self.heap.atomic_suspended()
1686 && self.atomic_deferred < ATOMIC_DEFERRALS;
1687 if defer {
1688 self.atomic_deferred += 1;
1689 } else if done {
1690 self.atomic_deferred = 0;
1691 let (pre, allow) = match self.gc_atomic_pre.take() {
1692 Some(p) => p,
1694 None => {
1695 work += self.clear_dead_stack();
1696 work += self.mark_roots();
1697 (work, self.gc_allow(work))
1698 }
1699 };
1700 work = pre;
1701 let stop = crate::heap::Stop {
1702 interrupt: &self.interrupt,
1703 deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
1704 };
1705 match self.heap.atomic(&stop, allow) {
1706 crate::heap::Atomic::Paused => {
1707 self.gc_atomic_pre = Some((pre, allow));
1709 self.gc_pending = Some((born_step, full, budget));
1710 return Err(ErrorKind::Pending.into());
1711 }
1712 crate::heap::Atomic::Done(w) => work += w,
1713 crate::heap::Atomic::Interrupted(w) => {
1714 self.charge_gc((work + w) / WORK_PER_FUEL)?;
1715 return Err(LuaError::Limit(LimitKind::Interrupted));
1716 }
1717 crate::heap::Atomic::Suspended(w) => return self.atomic_suspended(work + w, LimitKind::Fuel),
1718 crate::heap::Atomic::TimedOut(w) => return self.atomic_suspended(work + w, LimitKind::Time),
1719 }
1720 }
1721 }
1722 crate::heap::Phase::Sweep => {
1723 let stop = crate::heap::Stop {
1724 interrupt: &self.interrupt,
1725 deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
1726 };
1727 let (done, w, cut) = self.heap.sweep_step(budget, &stop);
1728 work += w;
1729 if cut {
1730 self.heap.mem.debt = -STEP_SIZE;
1733 let work = work + std::mem::take(&mut self.gc_work_carry);
1734 self.charge_gc(work / WORK_PER_FUEL)?;
1735 return Err(LuaError::Limit(self.stop_kind()));
1736 }
1737 if done {
1738 self.end_cycle();
1739 } else {
1740 unspent = full - budget;
1741 }
1742 }
1743 }
1744 if self.heap.phase != crate::heap::Phase::Pause {
1745 let owed = (unspent as u64).saturating_mul(800) / (self.heap.stepmul.max(1) as u64);
1747 self.heap.mem.debt = (-STEP_SIZE).saturating_add(isize::try_from(owed).unwrap_or(isize::MAX));
1748 }
1749 let work = work + std::mem::take(&mut self.gc_work_carry) + self.heap.born.take_work();
1755 self.gc_work_carry = work % WORK_PER_FUEL;
1756 self.charge_gc(work / WORK_PER_FUEL)
1757 }
1758
1759 #[inline]
1762 fn charge_gc(&mut self, units: usize) -> Result<(), LuaError> {
1763 let left = self.call_fuel();
1764 if units > left {
1765 return self.owe_gc(units - left, left);
1766 }
1767 self.charge(units as u64)
1768 }
1769
1770 #[cold]
1773 fn owe_gc(&mut self, owed: usize, left: usize) -> Result<(), LuaError> {
1774 self.gc_mark_over += owed * WORK_PER_FUEL;
1775 self.gc_owed_probe.0 += (owed * WORK_PER_FUEL) as u64;
1776 self.charge(left as u64)?;
1777 self.fuel = -1;
1778 self.reserve = 0;
1779 Err(LuaError::Limit(LimitKind::Fuel))
1780 }
1781
1782 fn charge_or_owe(&mut self, work: usize, charged: &mut usize) -> Result<(), LuaError> {
1791 let pay = work / WORK_PER_FUEL - *charged;
1792 let left = self.call_fuel();
1793 if pay <= left {
1794 self.charge(pay as u64)?;
1795 *charged += pay;
1796 return Ok(());
1797 }
1798 self.gc_mark_over += work % WORK_PER_FUEL;
1800 *charged += left;
1801 self.owe_gc(pay - left, left)
1802 }
1803
1804 fn gc_allow(&self, done: usize) -> usize {
1808 self.call_fuel().saturating_mul(WORK_PER_FUEL).saturating_sub(done + self.gc_work_carry)
1809 }
1810
1811 fn call_fuel(&self) -> usize {
1813 if self.entry == 0 {
1814 return usize::MAX;
1815 }
1816 usize::try_from(self.fuel.max(0).saturating_add(self.reserve.max(0))).unwrap_or(usize::MAX)
1817 }
1818
1819 #[cold]
1827 fn atomic_suspended(&mut self, work: usize, kind: LimitKind) -> Result<(), LuaError> {
1828 let work = work + std::mem::take(&mut self.gc_work_carry);
1829 let left = self.call_fuel();
1830 self.atomic_owed = work.saturating_sub(left.saturating_mul(WORK_PER_FUEL));
1831 let _ = self.charge((work - self.atomic_owed) as u64 / WORK_PER_FUEL as u64);
1832 if kind == LimitKind::Fuel {
1833 self.fuel = -1;
1834 self.reserve = 0;
1835 }
1836 Err(LuaError::Limit(kind))
1837 }
1838
1839 #[cold]
1841 fn stop_kind(&self) -> LimitKind {
1842 if self.interrupt.load(std::sync::atomic::Ordering::Relaxed) { LimitKind::Interrupted } else { LimitKind::Time }
1843 }
1844
1845 fn basic_step_call(&self, func: usize, nargs: usize) -> bool {
1851 let is_step = matches!(self.st(func + 1), Value::Str(r) if self.heap.strings.get(r.idx).is_some_and(|s| &*s.bytes == b"step"));
1852 is_step && (nargs == 1 || (nargs == 2 && matches!(self.st(func + 2), Value::Int(0) | Value::Nil)))
1853 }
1854
1855 fn collect_step(&mut self) -> Result<(), LuaError> {
1859 self.gc_call_before = Some(self.heap.cycle);
1860 let stopped = std::mem::replace(&mut self.heap.stopped, false);
1861 self.heap.mem.debt = self.heap.mem.debt.max(crate::heap::STEP_SIZE);
1862 let r = self.gc_step_pausable();
1863 self.heap.stopped = stopped;
1864 r
1865 }
1866
1867 pub(crate) fn resume_atomic_pausable(&mut self) -> Result<(), LuaError> {
1871 self.heap.pause_ok = self.heap.poll_allow.is_some() && self.entry == 1;
1872 let r = self.resume_atomic();
1873 self.heap.pause_ok = false;
1874 r
1875 }
1876
1877 pub(crate) fn resume_atomic(&mut self) -> Result<(), LuaError> {
1878 if !self.heap.atomic_suspended() {
1879 return Ok(());
1880 }
1881 let stopped = std::mem::replace(&mut self.heap.stopped, false);
1883 let r = self.gc_step();
1884 self.heap.stopped = stopped;
1885 r
1886 }
1887
1888 fn clear_dead_stack(&mut self) -> usize {
1896 let live = if self.native_depth > 0 {
1900 let mut live = self.ntop;
1901 if let Some(&(i, _)) = self.cur.open_upvals.last() {
1902 live = live.max(i + 1);
1903 }
1904 if let Some(&i) = self.cur.tbc.last() {
1905 live = live.max(i + 1);
1906 }
1907 live
1908 } else {
1909 let frame_top = self.frame_top();
1910 frame_top.max(self.top).max(self.ntop)
1911 };
1912 if self.cur.frames.is_empty() {
1913 return 0;
1914 }
1915 self.cur.stack.get_mut(live..).unwrap_or_default().fill(Value::Nil);
1916 self.cur.stack.len()
1917 }
1918
1919 pub(crate) fn clear_idle_stack(&mut self) {
1921 if self.cur.frames.is_empty() && self.c_depth == 0 {
1922 self.cur.stack.clear();
1926 self.top = 0;
1927 }
1928 }
1929
1930 fn shrink_stack(&mut self) {
1933 let frame_top = self.cur.frames.last().map_or(0, |f| f.base + self.proto(f.proto).map_or(WINDOW, |p| p.window().max(p.frame_size())));
1934 let mut live = frame_top.max(self.top).max(self.ntop);
1935 if let Some(&(i, _)) = self.cur.open_upvals.last() {
1936 live = live.max(i + 1);
1937 }
1938 if let Some(&i) = self.cur.tbc.last() {
1939 live = live.max(i + 1);
1940 }
1941 crate::heap::shrink_frames(&mut self.cur.frames, &mut self.heap.mem);
1942 let want = (live * 2).max(64) + EXTRA_STACK;
1943 let cap = self.cur.stack.capacity();
1944 if cap <= want * 2 {
1945 return;
1946 }
1947 let keep = (live + EXTRA_STACK).min(self.cur.stack.len());
1948 self.cur.stack.truncate(keep);
1949 self.cur.stack.shrink_to(want);
1950 let now = self.cur.stack.capacity();
1951 self.heap.mem.release(cap.saturating_sub(now) * 16);
1952 self.top = self.top.min(keep);
1953 }
1954
1955 fn end_cycle(&mut self) {
1956 self.shrink_stack();
1957 self.heap.shrink_parked();
1958 self.heap.trim_scratch();
1959 let est = self.heap.mem.live();
1960 self.heap.estimate = est;
1961 let cap = self.heap.mem.cap;
1964 let pause = self.heap.pause;
1965 let mut grow = est.saturating_mul(pause) / 100;
1966 if pause >= 200 {
1967 grow = grow.max(est + 256 * 1024);
1968 }
1969 let threshold = grow.min(cap - cap / 8).max(est + STEP_SIZE as usize);
1970 self.heap.mem.debt = est as isize - threshold as isize;
1971 }
1972
1973 pub(crate) fn full_gc(&mut self) -> Result<(), LuaError> {
1975 if self.heap.mem.trace.is_none() { self.full_gc_now() } else { self.full_gc_traced() }
1976 }
1977
1978 #[cold]
1980 #[inline(never)]
1981 fn full_gc_traced(&mut self) -> Result<(), LuaError> {
1982 let (scanned, fuel) = (self.heap.scanned, self.fuel.saturating_add(self.reserve));
1983 let began = match self.heap.phase {
1984 crate::heap::Phase::Pause => crate::gctrace::FULL_BEGAN_PAUSE,
1985 crate::heap::Phase::Propagate => crate::gctrace::FULL_BEGAN_MARK,
1986 crate::heap::Phase::Sweep => crate::gctrace::FULL_BEGAN_SWEEP,
1987 };
1988 let start = self.heap.mem.trace.as_mut().map(|t| {
1989 t.step += 1;
1990 (t.now(), t.step)
1991 });
1992 let r = self.full_gc_now();
1993 let used = fuel.saturating_sub(self.fuel.max(-1).saturating_add(self.reserve.max(0)));
1994 if let (Some(t), Some((start, step))) = (self.heap.mem.trace.as_mut(), start) {
1995 t.note(crate::gctrace::TraceOp::Full, step, self.heap.scanned.wrapping_sub(scanned) as u64, began, u64::try_from(used).unwrap_or(0), start);
1996 }
1997 r
1998 }
1999
2000 fn full_gc_now(&mut self) -> Result<(), LuaError> {
2001 if self.heap.blocked > 0 {
2002 return Ok(());
2003 }
2004 let mut work = self.clear_dead_stack() + std::mem::take(&mut self.gc_mark_over) + std::mem::take(&mut self.atomic_owed) + self.heap.born.take_work();
2008 let mut charged = 0;
2009 let mut cycles = 0;
2010 loop {
2014 match self.heap.phase {
2015 crate::heap::Phase::Pause => {
2016 if cycles == 1 {
2017 break;
2018 }
2019 cycles += 1;
2020 self.heap.start_cycle();
2021 work += self.mark_roots();
2022 }
2023 crate::heap::Phase::Propagate => {
2024 let stop = crate::heap::Stop {
2025 interrupt: &self.interrupt,
2026 deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
2027 };
2028 let done = if self.heap.atomic_suspended() {
2029 true
2030 } else {
2031 self.heap.step_slots = usize::MAX;
2032 let piece = FULL_GC_CHUNK.min(self.gc_allow(work - charged * WORK_PER_FUEL).max(1));
2034 let (done, w, cut, _) = self.heap.propagate(piece, &stop);
2035 work += w;
2036 if cut {
2037 self.charge_or_owe(work, &mut charged)?;
2038 return Err(LuaError::Limit(self.stop_kind()));
2039 }
2040 done
2041 };
2042 if done {
2043 work += self.mark_roots();
2044 let allow = self.gc_allow(work - charged * WORK_PER_FUEL);
2045 let stop = crate::heap::Stop {
2046 interrupt: &self.interrupt,
2047 deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
2048 };
2049 match self.heap.atomic(&stop, allow) {
2050 crate::heap::Atomic::Done(w) => work += w,
2051 crate::heap::Atomic::Paused => {}
2054 crate::heap::Atomic::Interrupted(w) => {
2055 self.charge_or_owe(work + w, &mut charged)?;
2056 return Err(LuaError::Limit(LimitKind::Interrupted));
2057 }
2058 crate::heap::Atomic::Suspended(w) => {
2059 return self.atomic_suspended(work + w - charged * WORK_PER_FUEL, LimitKind::Fuel);
2060 }
2061 crate::heap::Atomic::TimedOut(w) => {
2062 return self.atomic_suspended(work + w - charged * WORK_PER_FUEL, LimitKind::Time);
2063 }
2064 }
2065 }
2066 }
2067 crate::heap::Phase::Sweep => {
2068 let stop = crate::heap::Stop {
2069 interrupt: &self.interrupt,
2070 deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
2071 };
2072 let piece = FULL_GC_CHUNK.min(self.gc_allow(work - charged * WORK_PER_FUEL).max(1));
2073 let (done, w, cut) = self.heap.sweep_step(piece, &stop);
2074 work += w;
2075 if cut {
2076 self.charge_or_owe(work, &mut charged)?;
2077 return Err(LuaError::Limit(self.stop_kind()));
2078 }
2079 if done {
2080 self.end_cycle();
2081 }
2082 }
2083 }
2084 self.charge_or_owe(work, &mut charged)?;
2085 }
2086 self.heap.mem.drain_pool();
2089 let stop = crate::heap::Stop {
2090 interrupt: &self.interrupt,
2091 deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
2092 };
2093 if self.heap.trim_slabs(&stop) {
2094 return Err(LuaError::Limit(self.stop_kind()));
2095 }
2096 self.drop_spare_stacks();
2097 Ok(())
2098 }
2099
2100 fn gc_due_step(&mut self) -> Result<(), LuaError> {
2102 if self.heap.mem.debt > 0 { self.gc_step_pausable() } else { self.charge_born() }
2103 }
2104
2105 fn gc_step_pausable(&mut self) -> Result<(), LuaError> {
2110 self.heap.pause_ok = self.heap.poll_allow.is_some() && self.entry == 1 && self.c_depth == 1 && self.native_depth == 0 && self.resume_depth == 0;
2111 let r = self.gc_step();
2112 let over = r.is_ok() && self.gc_pending.is_none() && self.heap.poll_over();
2116 self.heap.pause_ok = false;
2117 if over {
2118 return Err(ErrorKind::Pending.into());
2119 }
2120 r
2121 }
2122
2123 fn charge_born(&mut self) -> Result<(), LuaError> {
2125 let work = self.heap.born.take_work() + std::mem::take(&mut self.gc_work_carry);
2126 self.gc_work_carry = work % WORK_PER_FUEL;
2127 self.charge_gc(work / WORK_PER_FUEL)
2128 }
2129
2130 pub(crate) fn metatable(&self, v: Value) -> Option<TableRef> {
2133 match v {
2134 Value::Table(t) => self.heap.tables.get(t.idx).and_then(|t| t.meta),
2135 Value::UserData(u) => self.heap.uds.get(u.idx).and_then(|u| u.meta),
2136 Value::Str(_) => self.string_meta,
2137 _ => None,
2138 }
2139 }
2140
2141 #[inline]
2142 pub(crate) fn tm_in(&self, mt: TableRef, e: Tm) -> Value {
2143 let Some(t) = self.heap.tables.get(mt.idx) else { return Value::Nil };
2144 let bit = 1u32 << (e as u8);
2145 if t.absent.get() & bit != 0 {
2146 return Value::Nil;
2147 }
2148 let name = self.tm_names.get(e as usize).copied();
2149 let v = name.map_or(Value::Nil, |n| t.get_str(Value::Str(n)));
2150 if v.is_nil() {
2151 t.absent.set(t.absent.get() | bit);
2152 }
2153 v
2154 }
2155
2156 #[inline]
2157 pub(crate) fn tm(&self, v: Value, e: Tm) -> Value {
2158 match self.metatable(v) {
2159 Some(mt) => self.tm_in(mt, e),
2160 None => Value::Nil,
2161 }
2162 }
2163
2164 #[inline]
2166 pub(crate) fn tm2(&self, x: Value, y: Value, e: Tm) -> Value {
2167 let mm = self.tm(x, e);
2168 if mm.is_nil() { self.tm(y, e) } else { mm }
2169 }
2170
2171 pub(crate) fn obj_type_name(&self, v: Value) -> String {
2175 if matches!(v, Value::Table(_) | Value::UserData(_)) { self.named_type(v) } else { v.type_name().to_owned() }
2176 }
2177
2178 pub(crate) fn arg_type_name(&self, v: Value) -> String {
2184 self.named_type(v)
2185 }
2186
2187 fn named_type(&self, v: Value) -> String {
2188 if let Some(mt) = self.metatable(v)
2189 && let Value::Str(s) = self.tm_in(mt, Tm::Name)
2190 {
2191 let b = self.bytes(s);
2193 return String::from_utf8_lossy(b.get(..b.len().min(MAX_NAME)).unwrap_or_default()).into_owned();
2194 }
2195 v.type_name().to_owned()
2196 }
2197
2198 #[inline]
2201 pub(crate) fn raw_get(&self, t: TableRef, k: Value) -> Value {
2202 self.heap.tables.get(t.idx).map_or(Value::Nil, |t| self.heap.get_in(t, k))
2203 }
2204
2205 pub(crate) fn raw_set(&mut self, t: TableRef, k: Value, v: Value) -> Result<(), LuaError> {
2206 let settled = self.settle_key(k)?;
2207 let k = match (k, settled) {
2209 (Value::Str(r), Settled::Absent(best)) => Value::Str(self.heap.canon_absent(r, best)),
2210 (Value::Str(r), _) => Value::Str(self.heap.canon(r)),
2211 _ => k,
2212 };
2213 let part = t.idx == self.heap.part;
2216 let held = if part { self.heap.part_writing(t.idx, k) } else { k };
2217 self.heap.mem.fuel = self.call_fuel();
2218 self.heap.mem.fuel_watchable = true;
2219 let r = match self.heap.tables.get_mut(t.idx) {
2220 Some(tab) => tab.set(k, v, &mut self.heap.mem),
2221 None => Ok(()),
2222 };
2223 self.heap.mem.fuel_watchable = false;
2224 match r {
2225 Ok(()) => {}
2226 Err(SetError::NilKey) => return Err(LuaError::msg("table index is nil")),
2227 Err(SetError::NanKey) => return Err(LuaError::msg("table index is NaN")),
2228 Err(SetError::Stopped(k)) => {
2231 if part {
2232 self.heap.part_written(t.idx, held, Value::Nil);
2233 }
2234 let heap = &mut self.heap;
2236 let units = heap.tables.get_mut(t.idx).map_or(0, |tab| tab.take_units(&heap.mem));
2237 let _ = self.charge(units);
2238 return Err(LuaError::Limit(k));
2239 }
2240 Err(SetError::Fuel) => {
2241 if part {
2242 self.heap.part_written(t.idx, held, Value::Nil);
2243 }
2244 (self.fuel, self.reserve) = (-1, 0);
2245 return Err(LuaError::Limit(LimitKind::Fuel));
2246 }
2247 Err(SetError::Memory) => {
2248 self.emergency_gc()?;
2249 let r = match self.heap.tables.get_mut(t.idx) {
2250 Some(tab) => tab.set(k, v, &mut self.heap.mem),
2251 None => Ok(()),
2252 };
2253 if r.is_err() {
2254 if part {
2255 self.heap.part_written(t.idx, held, Value::Nil);
2256 }
2257 return Err(self.memory_error(false));
2258 }
2259 }
2260 }
2261 if part {
2262 self.heap.part_written(t.idx, held, v);
2263 }
2264 if v.is_collectable() || k.is_collectable() {
2265 self.heap.barrier_table(t);
2266 }
2267 let heap = &mut self.heap;
2269 let resized = heap.tables.get_mut(t.idx).map_or(0, |tab| tab.take_resized(&heap.mem));
2270 if resized >= 16 {
2271 self.charge(resized as u64 / 16)?;
2272 }
2273 Ok(())
2274 }
2275
2276 pub(crate) fn raw_len(&self, t: TableRef) -> i64 {
2277 self.heap.tables.get(t.idx).map_or(0, |t| t.border())
2278 }
2279
2280 #[inline]
2283 fn upval_ref(&self, closure: FuncRef, u: u16) -> Option<u32> {
2284 match self.heap.funcs.get(closure.idx) {
2285 Some(Func::Lua { upvals, .. }) => upvals.get(usize::from(u)).map(|r| r.idx),
2286 _ => None,
2287 }
2288 }
2289
2290 #[inline]
2291 pub(crate) fn upval_get(&self, closure: FuncRef, u: u16) -> Value {
2292 let Some(r) = self.upval_ref(closure, u) else { return Value::Nil };
2293 self.upval_read(r)
2294 }
2295
2296 pub(crate) fn upval_read(&self, r: u32) -> Value {
2297 match self.heap.upvals.get(r) {
2298 Some(Upval::Closed(v)) => *v,
2299 Some(Upval::Open { thread, idx }) => {
2300 if *thread == self.cur_ref {
2301 self.st(*idx)
2302 } else {
2303 self.heap.threads.get(thread.idx).and_then(|t| t.stack.get(*idx).copied()).unwrap_or_default()
2304 }
2305 }
2306 None => Value::Nil,
2307 }
2308 }
2309
2310 fn upval_set(&mut self, closure: FuncRef, u: u16, v: Value) {
2311 let Some(r) = self.upval_ref(closure, u) else { return };
2312 match self.heap.upvals.get(r).copied() {
2313 Some(Upval::Closed(_)) => {
2314 if let Some(slot) = self.heap.upvals.get_mut(r) {
2315 *slot = Upval::Closed(v);
2316 }
2317 if v.is_collectable() {
2318 self.heap.barrier_upval(r);
2319 }
2320 }
2321 Some(Upval::Open { thread, idx }) => {
2322 if thread == self.cur_ref {
2323 self.set_st(idx, v);
2324 } else if let Some(t) = self.heap.threads.get_mut(thread.idx)
2325 && let Some(s) = t.stack.get_mut(idx)
2326 {
2327 *s = v;
2328 }
2329 }
2330 None => {}
2331 }
2332 }
2333
2334 fn pop_tbc(&mut self, level: usize) -> Option<Value> {
2336 let slot = self.cur.tbc.last().copied().filter(|&slot| slot >= level)?;
2337 self.cur.tbc.pop();
2338 Some(self.st(slot))
2339 }
2340
2341 pub(crate) fn close_upvals(&mut self, level: usize) {
2343 while let Some(&(idx, r)) = self.cur.open_upvals.last() {
2344 if idx < level {
2345 break;
2346 }
2347 self.cur.open_upvals.pop();
2348 let v = self.st(idx);
2349 if let Some(slot) = self.heap.upvals.get_mut(r) {
2350 *slot = Upval::Closed(v);
2351 }
2352 if v.is_collectable() {
2353 self.heap.barrier_upval(r);
2354 }
2355 }
2356 }
2357
2358 pub(crate) fn close_level(&mut self, level: usize) -> Result<(), LuaError> {
2360 self.close_upvals(level);
2361 while let Some(v) = self.pop_tbc(level) {
2362 self.call_close(v, Value::Nil)?;
2363 }
2364 Ok(())
2365 }
2366
2367 pub(crate) fn close_with_error(&mut self, level: usize, mut err: Value) -> Result<Value, LuaError> {
2370 self.close_upvals(level);
2371 while let Some(v) = self.pop_tbc(level) {
2372 match self.call_close(v, err) {
2373 Ok(()) => {}
2374 Err(e) if e.limit().is_some() => return Err(e),
2375 Err(e) => err = self.normalize(e)?,
2376 }
2377 }
2378 Ok(err)
2379 }
2380
2381 fn close_error_async(&mut self, i: usize) -> Result<(), LuaError> {
2387 let Some(fr) = self.cur.frames.get(i) else { return Ok(()) };
2388 let FrameKind::Protected { dest, wanted, cont } = fr.kind else { return Ok(()) };
2389 let level = fr.func;
2390 let mut err = self.st(dest + 1);
2391 self.close_upvals(level);
2392 while let Some(v) = self.pop_tbc(level) {
2393 let mm = self.tm(v, Tm::Close);
2394 if matches!(mm, Value::Func(f) if matches!(self.heap.funcs.get(f.idx), Some(Func::Lua { .. }))) {
2395 let pos = self.call_top();
2396 let called = self.place_call(pos, mm, &[v, err]).and_then(|()| {
2397 self.precall_event(Some("close"), pos, 2, 0, FrameKind::Cont(Cont::ErrClosing { frame: i }))
2398 });
2399 match called {
2400 Ok(_) => return Ok(()),
2401 Err(e) if e.limit().is_some() => return Err(e),
2402 Err(e) => {
2403 err = self.normalize(e)?;
2404 err = self.close_error_handled(i, err)?;
2405 self.set_st(dest + 1, err);
2406 continue;
2407 }
2408 }
2409 }
2410 let outer = self.err_closing.replace((i, self.cur.frames.len()));
2411 let r = if self.tm(v, Tm::Close).is_nil() {
2412 Err(LuaError::Plain("attempt to call a nil value".into()))
2414 } else {
2415 self.call_close(v, err)
2416 };
2417 let r = match r {
2418 Ok(()) => Ok(None),
2419 Err(e) if e.limit().is_some() => Err(e),
2420 Err(e) => self.normalize(e).map(Some),
2421 };
2422 self.err_closing = outer;
2423 if let Some(e) = r? {
2424 err = self.close_error_handled(i, e)?;
2425 self.set_st(dest + 1, err);
2426 }
2427 }
2428 self.cur.frames.truncate(i);
2429 self.set_st(dest, Value::Bool(false));
2430 self.set_st(dest + 1, err);
2431 self.move_results(dest, dest, 2, wanted)?;
2432 if let Some(c) = cont {
2433 self.apply_cont(c, Value::Bool(false))?;
2434 }
2435 Ok(())
2436 }
2437
2438 fn close_error_handled(&mut self, i: usize, err: Value) -> Result<Value, LuaError> {
2441 match self.cur.frames.get(i).and_then(|f| f.handler) {
2442 Some(h) => self.call_handler(h, err),
2443 None => Ok(err),
2444 }
2445 }
2446
2447 fn call_close(&mut self, v: Value, err: Value) -> Result<(), LuaError> {
2448 let mm = self.tm(v, Tm::Close);
2449 if mm.is_nil() {
2450 return Err(LuaError::msg("attempt to call a nil value (metamethod 'close')"));
2452 }
2453 self.call_nested(mm, &[v, err]).map(|_| ())
2454 }
2455
2456 #[inline]
2460 pub(crate) fn precall(
2461 &mut self,
2462 func: usize,
2463 nargs: usize,
2464 nres: i32,
2465 kind: FrameKind,
2466 from_lua: bool,
2467 ) -> Result<Called, LuaError> {
2468 match self.precall_one(func, nargs, nres, kind, from_lua) {
2469 Ok(Called::Done) if self.nested_pending.is_some() => self.precall_nested(),
2470 r => r,
2471 }
2472 }
2473
2474 #[cold]
2479 fn precall_nested(&mut self) -> Result<Called, LuaError> {
2480 loop {
2481 let Some(NestedCall { func, nargs, kind, handler }) = self.nested_pending.take() else {
2482 return Err(LuaError::msg("internal: no nested call"));
2483 };
2484 let FrameKind::Protected { dest, cont: Some(nest), .. } = kind else {
2485 return Err(LuaError::msg("internal: nested call without its protected calls"));
2486 };
2487 match self.precall_one(func, nargs, -1, kind, false) {
2488 Ok(Called::Done) if self.nested_pending.is_some() => {}
2489 Ok(Called::Lua) => {
2490 self.set_handler(dest, handler);
2491 return Ok(Called::Lua);
2492 }
2493 Ok(other) => return Ok(other),
2495 Err(e) if e.limit().is_some() => return Err(e),
2496 Err(e) => {
2497 self.pcall_failed(e, handler, dest, -1)?;
2498 self.complete_nest(nest, false)?;
2500 return Ok(Called::Done);
2501 }
2502 }
2503 }
2504 }
2505
2506 fn set_handler(&mut self, dest: usize, handler: Option<Value>) {
2510 if let Some(f) = self.cur.frames.last_mut()
2511 && matches!(f.kind, FrameKind::Protected { dest: d, .. } if d == dest)
2512 {
2513 f.handler = handler;
2514 }
2515 }
2516
2517 fn pcall_failed(&mut self, e: LuaError, handler: Option<Value>, dest: usize, wanted: i32) -> Result<(), LuaError> {
2520 let mut ev = self.normalize(c_level(e))?;
2521 if let Some(h) = handler {
2522 ev = self.call_handler(h, ev)?;
2523 }
2524 self.set_st(dest, Value::Bool(false));
2525 self.set_st(dest + 1, ev);
2526 self.move_results(dest, dest, 2, wanted)
2527 }
2528
2529 #[inline]
2531 fn precall_one(
2532 &mut self,
2533 func: usize,
2534 nargs: usize,
2535 nres: i32,
2536 kind: FrameKind,
2537 from_lua: bool,
2538 ) -> Result<Called, LuaError> {
2539 let mut nargs = nargs;
2540 let mut fv = self.st(func);
2541 for _ in 0..MAX_TAG_LOOP {
2542 let Value::Func(f) = fv else {
2543 let mm = self.tm(fv, Tm::Call);
2544 if mm.is_nil() {
2545 return Err(ErrorKind::Call { ty: self.obj_type_name(fv) }.into());
2546 }
2547 self.charge(1 + nargs as u64 / 8)?;
2549 self.ensure_stack(func + nargs + 2 + EXTRA_STACK)?;
2550 self.cur.stack.copy_within(func..func + 1 + nargs, func + 1);
2551 self.set_st(func, mm);
2552 nargs += 1;
2553 fv = mm;
2554 continue;
2555 };
2556 enum K {
2557 Lua(u32),
2558 Native(NativeFn, &'static str),
2559 Host(crate::heap::HostFn, &'static str),
2560 }
2561 let k = match self.heap.funcs.get(f.idx) {
2562 Some(Func::Lua { proto, .. }) => K::Lua(*proto),
2563 Some(Func::Native { f, name, .. }) => K::Native(*f, name),
2564 Some(Func::Host { f, .. }) => K::Host(Arc::clone(f), "?"),
2565 None => return Err(LuaError::msg("attempt to call a dead function")),
2566 };
2567 return match k {
2568 K::Lua(proto) => self.push_frame(f, proto, func, nargs, nres, kind, from_lua),
2569 K::Native(nf, name) => self.call_native(func, nargs, nres, kind, from_lua, name, |l, a| nf(l, a)),
2570 K::Host(hf, name) => self.call_native(func, nargs, nres, kind, from_lua, name, |l, a| hf(l, a)),
2571 };
2572 }
2573 Err(LuaError::msg("'__call' chain too long; possible loop"))
2574 }
2575
2576 #[allow(clippy::too_many_arguments, reason = "the call protocol's own state")]
2577 fn push_frame(
2578 &mut self,
2579 closure: FuncRef,
2580 proto: u32,
2581 func: usize,
2582 nargs: usize,
2583 nres: i32,
2584 kind: FrameKind,
2585 from_lua: bool,
2586 ) -> Result<Called, LuaError> {
2587 if self.cur.frames.len() >= self.limits.call_depth {
2588 return Err(LuaError::msg("stack overflow"));
2589 }
2590 if !matches!(kind, FrameKind::Normal) && self.cur.frames.len() < self.cur.unrolled {
2591 self.cur.unrolled = self.cur.frames.len();
2593 }
2594 if self.cur.frames.len() == self.cur.frames.capacity() {
2597 self.grow_frames()?;
2598 }
2599 let Some(p) = self.proto(proto) else { return Err(LuaError::msg("internal: no prototype")) };
2600 let np = p.num_params as usize;
2601 let is_vararg = p.is_vararg;
2602 let width = p.window();
2603 let (base, vstart, vcount) = if is_vararg && nargs > np {
2604 if nargs > 16 {
2606 self.charge(nargs as u64 / 8)?;
2607 }
2608 let nb = func + 1 + nargs;
2609 self.ensure_window(nb, width.max(np))?;
2611 for i in 0..np {
2612 let v = self.st(func + 1 + i);
2613 self.set_st(nb + i, v);
2614 }
2615 (nb, func + 1 + np, nargs - np)
2616 } else {
2617 self.ensure_window(func + 1, width.max(np))?;
2618 self.charge(list_fuel(np.saturating_sub(nargs)))?;
2620 for i in nargs..np {
2621 self.set_st(func + 1 + i, Value::Nil);
2622 }
2623 (func + 1, func + 1 + np, 0)
2624 };
2625 self.cur.frames.push(Frame {
2626 closure,
2627 proto,
2628 func,
2629 base,
2630 pc: 0,
2631 nresults: nres,
2632 vstart,
2633 vcount,
2634 kind,
2635 from_lua,
2636 tail: false,
2637 handler: None,
2638 });
2639 Ok(Called::Lua)
2640 }
2641
2642 #[allow(clippy::too_many_arguments, reason = "the call protocol's own state")]
2643 #[inline]
2644 fn call_native(
2645 &mut self,
2646 func: usize,
2647 nargs: usize,
2648 nres: i32,
2649 kind: FrameKind,
2650 from_lua: bool,
2651 name: &'static str,
2652 f: impl Fn(&mut Lua, Args) -> Result<Flow, LuaError>,
2653 ) -> Result<Called, LuaError> {
2654 self.ensure_stack(func + 1 + nargs + EXTRA_STACK)?;
2655 self.native_calls = self.native_calls.wrapping_add(1);
2656 self.rets.clear();
2657 let saved = (self.ntop, self.native_from_lua, self.native_name);
2658 let saved_event = std::mem::replace(&mut self.native_event, self.pending_event.take());
2659 self.ntop = func + 1 + nargs;
2660 self.native_from_lua = from_lua;
2661 self.native_name = name;
2662 let mark = self.scratch.len();
2663 let floor = std::mem::replace(&mut self.scratch_floor, mark);
2664 self.native_depth += 1;
2665 let under_pcall = if from_lua { 0 } else { pcall_levels(kind) };
2669 let c_levels = if from_lua { 0 } else { c_calls(kind) };
2672 self.protected_natives += c_levels;
2673 self.native_stack.push((self.cur_ref, self.cur.frames.len(), func, under_pcall));
2674 let owed_before = crate::stdlib::owed();
2675 let held_before = crate::stdlib::held_back();
2676 let r = f(self, Args { func, base: func + 1, n: nargs });
2677 let back = crate::stdlib::held_back().saturating_sub(held_before);
2679 if back > 0 {
2680 crate::stdlib::set_held_back(held_before);
2681 self.heap.mem.release(back);
2682 }
2683 let done = crate::stdlib::owed().saturating_sub(owed_before);
2686 crate::stdlib::set_owed(owed_before);
2687 let r = match (done, r) {
2688 (0, r) => r,
2689 (n, r) => match self.charge(n) {
2690 Err(e) => Err(e),
2691 Ok(()) => r,
2692 },
2693 };
2694 self.native_depth -= 1;
2695 self.scratch.truncate(mark);
2696 self.scratch_floor = floor;
2697 let flow = match (r, self.limit_hit) {
2700 (Ok(fl), None) => fl,
2701 (Ok(_), Some(k)) => {
2702 let e = self.native_failed(LuaError::Limit(k), saved, (under_pcall, c_levels));
2703 self.native_event = saved_event;
2704 return Err(e);
2705 }
2706 (Err(e), _) => {
2707 let e = self.native_failed(e, saved, (under_pcall, c_levels));
2708 self.native_event = saved_event;
2709 return Err(e);
2710 }
2711 };
2712 self.native_stack.pop();
2713 self.protected_natives -= c_levels;
2714 (self.ntop, self.native_from_lua, self.native_name) = saved;
2715 self.native_event = saved_event;
2716 match (flow, kind) {
2717 (Flow::Return, FrameKind::Normal) => {
2719 let n = self.rets.len();
2720 let want = if nres < 0 { n } else { nres as usize };
2721 self.charge(list_fuel(n.max(want)))?;
2723 let need = func + n.max(want) + 2;
2724 match self.rets.first() {
2727 Some(&v) if n == 1 && need <= self.cur.stack.len() => {
2728 if let Some(d) = self.cur.stack.get_mut(func) {
2729 *d = v;
2730 }
2731 }
2732 _ => self.place_rets(func, need)?,
2733 }
2734 if let Some(rest) = self.cur.stack.get_mut(func + n..func + want) {
2735 rest.fill(Value::Nil);
2736 }
2737 if nres < 0 {
2738 self.top = func + n;
2739 }
2740 self.rets.clear();
2741 Ok(Called::Done)
2742 }
2743 (flow, kind) => self.native_flow(flow, func, nres, kind, from_lua),
2744 }
2745 }
2746
2747 #[inline(never)]
2752 fn call_in_place(&mut self, op: u8, func: usize, nargs: usize, nres: i32) -> Option<Result<Called, LuaError>> {
2753 let want = usize::try_from(nres).unwrap_or(0);
2754 if !self.fast || self.limit_hit.is_some() || nargs > 4 || want > 16 || self.cur.stack.len() < (func + 1 + nargs + EXTRA_STACK).max(func + want.max(2) + 2) {
2758 return None;
2759 }
2760 let mut args = [Value::Nil; 4];
2761 for (i, a) in args.iter_mut().enumerate().take(nargs) {
2762 *a = self.st(func + 1 + i);
2763 }
2764 let (r, n, cost) = crate::stdlib::string::in_place(&mut self.heap, self.names.types(), &mut self.match_state, usize::from(op - 1), args.get(..nargs)?, self.fuel + 1, self.limits.string_len)?;
2766 self.pending_event = None;
2767 self.fuel -= cost;
2768 for i in 0..n.max(want) {
2769 self.set_st(func + i, r.get(i).copied().unwrap_or(Value::Nil));
2770 }
2771 if nres < 0 {
2772 self.top = func + n;
2773 }
2774 if self.fuel < 0
2777 && let Err(e) = self.refuel()
2778 {
2779 return Some(Err(e));
2780 }
2781 Some(Ok(Called::Done))
2782 }
2783
2784 fn yield_from_lua(&mut self, func: usize, nargs: usize, nres: i32) -> Result<Called, LuaError> {
2796 self.ensure_stack(func + 1 + nargs + EXTRA_STACK)?;
2797 self.pending_event = None;
2798 self.rets.clear();
2799 for i in 0..nargs {
2800 let v = self.st(func + 1 + i);
2801 self.rets.push(v);
2802 }
2803 self.native_flow(Flow::Yield, func, nres, FrameKind::Normal, true)
2804 }
2805
2806 fn place_rets(&mut self, func: usize, need: usize) -> Result<(), LuaError> {
2811 let n = self.rets.len();
2812 if n <= crate::stdlib::NATIVE_CHUNK {
2813 self.ensure_stack(need)?;
2814 if let Some(dst) = self.cur.stack.get_mut(func..func + n) {
2815 for (d, v) in dst.iter_mut().zip(&self.rets) {
2817 *d = *v;
2818 }
2819 }
2820 return Ok(());
2821 }
2822 let mut hold = crate::stdlib::MemHold::default();
2827 let rets = std::mem::take(&mut self.rets);
2828 let bytes = rets.capacity().saturating_mul(std::mem::size_of::<Value>());
2829 let r = hold.cover(self, bytes).and_then(|()| self.stack_room(need));
2830 if let Err(e) = r {
2831 hold.give_back(self);
2832 return Err(e);
2833 }
2834 let mut stopped = Ok(());
2835 let mut at = func;
2836 for part in rets.chunks(crate::stdlib::NATIVE_CHUNK) {
2837 let end = at + part.len();
2838 if let Some(dst) = self.cur.stack.get_mut(at..end) {
2839 dst.copy_from_slice(part);
2840 } else {
2841 self.cur.stack.truncate(at);
2842 self.cur.stack.resize(at, Value::Nil);
2843 self.cur.stack.extend_from_slice(part);
2844 }
2845 at = end;
2846 if let Err(e) = self.check_time() {
2847 stopped = Err(e);
2848 break;
2849 }
2850 }
2851 drop(rets);
2852 hold.give_back(self);
2853 stopped?;
2856 if self.cur.stack.len() < need {
2857 self.cur.stack.resize(need, Value::Nil);
2858 }
2859 Ok(())
2860 }
2861
2862 #[cold]
2865 fn native_failed(&mut self, e: LuaError, saved: (usize, bool, &'static str), (under_pcall, c_levels): (usize, usize)) -> LuaError {
2866 clear_list(&mut self.rets);
2869 let e = match e.kind() {
2870 ErrorKind::Limit(_) | ErrorKind::Value(_) => e,
2871 _ => match self.normalize(e) {
2872 Ok(v) => LuaError::Value(v),
2873 Err(e) => e,
2874 },
2875 };
2876 if let ErrorKind::Value(v) = *e.kind() {
2879 self.err_native = self.native_stack.last().map(|&(t, d, slot, _)| ((t, d, slot), under_pcall, v));
2880 }
2881 self.native_stack.pop();
2882 self.protected_natives -= c_levels;
2883 (self.ntop, self.native_from_lua, self.native_name) = saved;
2884 e
2885 }
2886
2887 fn native_flow(&mut self, flow: Flow, func: usize, nres: i32, kind: FrameKind, from_lua: bool) -> Result<Called, LuaError> {
2890 match flow {
2891 Flow::Return => {
2892 let n = self.rets.len();
2893 self.place_rets(func, func + n.max(nres.max(0) as usize) + 2)?;
2894 self.rets.clear();
2895 match kind {
2896 FrameKind::Cont(_) => self.move_results(func, func, n, nres)?,
2897 k => self.finish_call(k, func, func, n, nres, false)?,
2898 }
2899 Ok(Called::Done)
2900 }
2901 Flow::PCall { handler, nargs: fnargs } if let Some(nest) = nest_of(kind, func) => {
2902 let pkind = FrameKind::Protected { dest: func, wanted: -1, cont: Some(nest) };
2908 self.nested_pending = Some(NestedCall { func: func + 1, nargs: fnargs, kind: pkind, handler });
2910 Ok(Called::Done)
2911 }
2912 Flow::PCall { handler, nargs: fnargs } if matches!(kind, FrameKind::Protected { .. }) => {
2913 let me = self.st(func);
2918 let mut args = Vec::with_capacity(fnargs + 2);
2919 args.push(self.st(func + 1));
2920 if let Some(h) = handler {
2921 args.push(h);
2922 }
2923 args.extend((0..fnargs).map(|i| self.st(func + 2 + i)));
2924 let out = self.call_nested(me, &args)?;
2925 self.rets.clear();
2926 self.rets.extend_from_slice(&out);
2927 self.native_flow(Flow::Return, func, nres, kind, from_lua)
2928 }
2929 Flow::PCall { handler, nargs: fnargs } => {
2930 let cont = match kind {
2931 FrameKind::Cont(c) => Some(c),
2932 _ => None,
2933 };
2934 let pkind = FrameKind::Protected { dest: func, wanted: nres, cont };
2935 match self.precall(func + 1, fnargs, -1, pkind, false) {
2936 Ok(Called::Lua) => {
2937 self.set_handler(func, handler);
2938 Ok(Called::Lua)
2939 }
2940 Ok(other) => Ok(other),
2941 Err(e) if e.limit().is_some() => Err(e),
2942 Err(e) => {
2943 self.pcall_failed(e, handler, func, nres)?;
2944 Ok(Called::Done)
2945 }
2946 }
2947 }
2948 Flow::Yield => {
2949 self.do_yield(func, nres, kind)?;
2950 Ok(Called::Switched)
2951 }
2952 Flow::Resume { co, wrap } => self.do_resume(func, nres, co, wrap, from_lua, kind),
2953 Flow::Call3 { f, arg } => {
2954 let is_lua = matches!(f, Value::Func(r) if matches!(self.heap.funcs.get(r.idx), Some(Func::Lua { .. })));
2957 if is_lua && matches!(kind, FrameKind::Normal) {
2958 self.ensure_stack(func + 2 + EXTRA_STACK)?;
2959 self.set_st(func, f);
2960 self.set_st(func + 1, arg);
2961 return self.precall(func, 1, -1, FrameKind::Cont(Cont::Three { wanted: nres }), false);
2962 }
2963 let three = match kind {
2969 _ if !is_lua => None,
2970 FrameKind::Protected { dest, wanted, cont: None } => {
2971 Some(FrameKind::Protected { dest, wanted, cont: Some(Cont::Three { wanted }) })
2972 }
2973 FrameKind::Protected { dest, wanted, cont: Some(Cont::Nest { dest: d, bits, wanted: w, back, n }) } => {
2974 let nest = Cont::Nest { dest: d, bits: bits.with_three(), wanted: w, back, n };
2976 Some(FrameKind::Protected { dest, wanted, cont: Some(nest) })
2977 }
2978 FrameKind::Protected { dest, wanted, cont: Some(c) } => pack_then(c, dest).and_then(|(then, back, n)| {
2979 let nest = Cont::Nest { dest, bits: NestBits::new(0, then, true)?, wanted, back, n };
2980 Some(FrameKind::Protected { dest, wanted: -1, cont: Some(nest) })
2981 }),
2982 FrameKind::Cont(c) => pack_then(c, func).and_then(|(then, back, n)| {
2983 let nest = Cont::Nest { dest: func, bits: NestBits::new(0, then, true)?, wanted: nres, back, n };
2984 Some(FrameKind::Cont(nest))
2985 }),
2986 FrameKind::Normal => None,
2987 };
2988 if let Some(kind) = three {
2989 self.ensure_stack(func + 2 + EXTRA_STACK)?;
2990 self.set_st(func, f);
2991 self.set_st(func + 1, arg);
2992 return self.precall(func, 1, -1, kind, false);
2993 }
2994 let mut out = self.call_nested(f, &[arg])?;
2997 out.resize(3, Value::Nil);
2998 self.rets.clear();
2999 self.rets.extend_from_slice(&out);
3000 self.native_flow(Flow::Return, func, nres, kind, from_lua)
3001 }
3002 }
3003 }
3004
3005 fn c_levels(&self) -> (usize, usize) {
3010 let protected = |t: &ThreadState| {
3014 t.frames.iter().skip(t.unrolled).map(|f| c_calls(f.kind)).sum::<usize>()
3015 };
3016 let mut walked = self.cur.frames.len();
3017 let mut level = self.c_depth + self.protected_natives + HANDLER_BASE_LEVELS + protected(&self.cur);
3018 let mut next = self.cur.resumer;
3019 while let Some(r) = next {
3020 if level > 2 * C_HANDLER_LEVELS {
3021 break;
3022 }
3023 let Some(t) = self.heap.threads.get(r.idx) else { break };
3024 let pcall_of_resume = t.resume_pending.as_ref().map_or(0, |p| if p.from_lua { 0 } else { c_calls(p.kind) });
3027 level += RESUME_LEVELS + protected(t) + pcall_of_resume;
3028 walked += t.frames.len();
3029 next = t.resumer;
3030 }
3031 (level, walked)
3032 }
3033
3034 #[inline]
3041 fn c_bound_here(&self, func: usize) -> usize {
3042 4 * (func + 1) + self.cur.c_bound
3043 }
3044
3045 fn cross_where(&self, from: usize, at: usize) -> Option<String> {
3051 let mut held = 0;
3052 for i in from..self.cur.frames.len() {
3053 let f = self.cur.frames.get(i)?;
3054 let natives = self.native_stack.iter().filter(|&&(t, d, ..)| t == self.cur_ref && d == i).count();
3055 if natives > 0 && held + natives >= at {
3056 return None;
3057 }
3058 held += natives + c_calls(f.kind);
3059 if held >= at {
3060 if held != at || !matches!(f.kind, FrameKind::Cont(_)) {
3061 return None;
3062 }
3063 let caller = self.cur.frames.get(i.checked_sub(1)?)?;
3064 let w = self.frame_where(caller);
3065 return (!w.is_empty()).then_some(w);
3066 }
3067 }
3068 None
3069 }
3070
3071 fn call_handler(&mut self, h: Value, err: Value) -> Result<Value, LuaError> {
3080 let raised = match self.err_native.take() {
3083 Some((n, under, v)) if self.raw_equal(&v, &err) => Some((n, under)),
3084 _ => None,
3085 };
3086 let saved = std::mem::replace(&mut self.handler_native, raised);
3087 let watch = std::mem::replace(&mut self.handler_raise, HandlerWatch { thread: Some(self.cur_ref), ..HandlerWatch::default() });
3088 let r = self.call_handler_at(h, err);
3089 self.handler_native = saved;
3090 self.handler_raise = watch;
3091 r
3092 }
3093
3094 fn call_handler_at(&mut self, h: Value, err: Value) -> Result<Value, LuaError> {
3095 const C_LEVELS: usize = C_HANDLER_LEVELS;
3096 const ERRERR_AT: usize = C_LEVELS / 10 * 11;
3097 let mut err = err;
3098 let (level, walked) = self.c_levels();
3099 let base = level;
3101 let mut level = level.min(C_LEVELS - 1);
3106 self.charge((walked / RESUMER_FRAMES_PER_FUEL) as u64)?;
3111 loop {
3112 if level + 1 >= ERRERR_AT {
3113 return self.new_str(b"error in error handling");
3114 }
3115 if level == C_LEVELS {
3116 let msg = match self.handler_raise.pos.take() {
3118 Some(w) => format!("{w}C stack overflow"),
3119 None => "C stack overflow".into(),
3120 };
3121 err = self.new_str(msg.as_bytes())?;
3122 }
3123 self.handler_raise.raised = None;
3124 self.handler_raise.pos = None;
3125 self.handler_raise.cross = (level < C_LEVELS).then(|| (self.cur.frames.len(), C_LEVELS - level));
3127 let r = match self.call_nested(h, &[err]) {
3128 Ok(v) => return Ok(v.first().copied().unwrap_or_default()),
3129 Err(e) if e.limit().is_some() => return Err(e),
3130 Err(e) => self.normalize(e),
3131 };
3132 err = r?;
3133 let next = level + self.handler_raise.raised.map_or(1, |r| r.saturating_sub(base).max(1));
3137 level = if level < C_LEVELS && next > C_LEVELS { C_LEVELS } else { next };
3141 }
3142 }
3143
3144 pub(crate) fn move_results(&mut self, dst: usize, src: usize, n: usize, wanted: i32) -> Result<(), LuaError> {
3147 let want = if wanted < 0 { n } else { wanted as usize };
3148 let written = n.max(want);
3151 if written > 16 {
3152 self.charge(written as u64 / 8)?;
3153 }
3154 self.ensure_stack(dst + want.max(n) + 1)?;
3155 if dst != src && n > 0 {
3156 self.cur.stack.copy_within(src..src + n, dst);
3157 }
3158 for i in n..want {
3159 self.set_st(dst + i, Value::Nil);
3160 }
3161 if wanted < 0 {
3162 self.top = dst + n;
3163 }
3164 Ok(())
3165 }
3166
3167 fn finish_call(
3172 &mut self,
3173 kind: FrameKind,
3174 func: usize,
3175 src: usize,
3176 n: usize,
3177 nres: i32,
3178 apply_cont: bool,
3179 ) -> Result<(), LuaError> {
3180 match kind {
3181 FrameKind::Normal => self.move_results(func, src, n, nres),
3182 FrameKind::Protected { dest, wanted, cont } => {
3183 let n = if matches!(cont, Some(Cont::Three { .. })) || matches!(cont, Some(Cont::Nest { bits, .. }) if bits.three()) {
3185 self.move_results(dest + 1, src, n.min(3), 3)?;
3186 3
3187 } else {
3188 self.move_results(dest + 1, src, n, -1)?;
3189 n
3190 };
3191 self.set_st(dest, Value::Bool(true));
3192 self.move_results(dest, dest, n + 1, wanted)?;
3193 match cont {
3194 Some(nest @ Cont::Nest { .. }) => self.complete_nest(nest, apply_cont),
3197 Some(c) if apply_cont => self.apply_cont(c, Value::Bool(true)),
3198 _ => Ok(()),
3199 }
3200 }
3201 FrameKind::Cont(nest @ Cont::Nest { dest, .. }) => {
3202 self.move_results(dest, src, n.min(3), 3)?;
3204 self.move_results(dest, dest, 3, -1)?;
3205 self.complete_nest(nest, apply_cont)
3206 }
3207 FrameKind::Cont(Cont::Three { wanted }) => {
3208 self.move_results(func, src, n.min(3), 3)?;
3209 self.move_results(func, func, 3, wanted)
3210 }
3211 FrameKind::Cont(c) => {
3212 let v = if n > 0 { self.st(src) } else { Value::Nil };
3213 self.apply_cont(c, v)
3214 }
3215 }
3216 }
3217
3218 fn complete_nest(&mut self, nest: Cont, apply_then: bool) -> Result<(), LuaError> {
3223 let Cont::Nest { dest, bits, wanted, back, n: then_n } = nest else { return Ok(()) };
3224 let levels = bits.levels() as usize;
3225 let n = self.top.saturating_sub(dest + levels);
3226 for j in 0..levels {
3227 self.set_st(dest + j, Value::Bool(true));
3228 }
3229 self.move_results(dest, dest, n + levels, wanted)?;
3230 match unpack_then(bits.then(), dest, back, then_n) {
3231 Some(c) if apply_then => {
3232 let v = self.st(dest);
3233 self.apply_cont(c, v)
3234 }
3235 _ => Ok(()),
3236 }
3237 }
3238
3239 fn apply_cont(&mut self, c: Cont, v: Value) -> Result<(), LuaError> {
3240 match c {
3241 Cont::Store(slot) => self.set_st(slot, v),
3242 Cont::Discard | Cont::Three { .. } => {}
3243 Cont::ErrClosing { frame } => self.close_error_async(frame)?,
3244 Cont::Nest { .. } => self.complete_nest(c, true)?,
3245 Cont::Cond { k } => {
3246 if v.truthy() != k
3247 && let Some(f) = self.cur.frames.last_mut()
3248 {
3249 f.pc += 1;
3250 }
3251 }
3252 Cont::Concat { a, n } => {
3253 self.set_st(a + n - 1, v);
3254 match self.concat(a, n).map_err(LuaError::into_kind) {
3257 Ok(_) => {}
3258 Err(ErrorKind::Type { op, ty, operand }) => {
3259 let Some(&Frame { proto, pc, base, .. }) = self.cur.frames.last() else {
3260 return Err(ErrorKind::Type { op, ty, operand }.into());
3261 };
3262 let r = u16::try_from((a + usize::from(operand)).saturating_sub(base)).unwrap_or(u16::MAX);
3263 let at = pc.saturating_sub(1);
3264 return Err(self.annotate(ErrorKind::Type { op, ty, operand: 0 }.into(), proto, at, &[crate::debug::Operand::Reg(r)]));
3265 }
3266 Err(e) => return Err(e.into()),
3267 }
3268 }
3269 Cont::Closing { level, then } => {
3270 let floor = match then {
3271 AfterClose::Return { src, n } => src + n,
3272 AfterClose::Nothing => 0,
3273 };
3274 self.close_async(level, then, floor)?;
3275 }
3276 }
3277 Ok(())
3278 }
3279
3280 fn close_async(&mut self, level: usize, then: AfterClose, floor: usize) -> Result<bool, LuaError> {
3284 self.close_upvals(level);
3285 while let Some(v) = self.pop_tbc(level) {
3286 let mm = self.tm(v, Tm::Close);
3287 if !matches!(mm, Value::Func(_)) && self.tm(mm, Tm::Call).is_nil() {
3290 return Err(LuaError::msg(format!("attempt to call a {} value (metamethod 'close')", self.obj_type_name(mm))));
3291 }
3292 let is_lua = matches!(mm, Value::Func(f) if matches!(self.heap.funcs.get(f.idx), Some(Func::Lua { .. })));
3293 if is_lua {
3294 let pos = self.call_top().max(floor);
3295 self.place_call(pos, mm, &[v, Value::Nil])?;
3296 self.precall_event(Some("close"), pos, 2, 0, FrameKind::Cont(Cont::Closing { level, then }))?;
3297 return Ok(false);
3298 }
3299 let saved = self.ntop;
3300 self.ntop = self.ntop.max(floor);
3301 let r = self.call_nested(mm, &[v, Value::Nil]);
3302 self.ntop = saved;
3303 r?;
3304 }
3305 match then {
3306 AfterClose::Nothing => Ok(true),
3307 AfterClose::Return { src, n } => {
3308 self.finish_return(src, n)?;
3309 Ok(false)
3310 }
3311 }
3312 }
3313
3314 fn do_return(&mut self, src: usize, n: usize) -> Result<(), LuaError> {
3316 let Some(base) = self.cur.frames.last().map(|f| f.base) else { return Ok(()) };
3317 if self.cur.open_upvals.last().is_some_and(|(i, _)| *i >= base) {
3318 self.close_upvals(base);
3319 }
3320 if self.cur.tbc.last().is_some_and(|i| *i >= base) {
3321 self.close_async(base, AfterClose::Return { src, n }, src + n)?;
3324 return Ok(());
3325 }
3326 self.finish_return(src, n)
3327 }
3328
3329 fn finish_return(&mut self, src: usize, n: usize) -> Result<(), LuaError> {
3331 let Some(frame) = self.cur.frames.pop() else { return Ok(()) };
3332 self.finish_call(frame.kind, frame.func, src, n, frame.nresults, true)?;
3333 if self.cur.frames.is_empty() && self.cur_ref != self.main_ref && self.cur.resumer.is_some() && self.cur.nny == 0 {
3335 self.finish_coroutine()?;
3336 }
3337 Ok(())
3338 }
3339
3340 pub(crate) fn call_nested(&mut self, f: Value, args: &[Value]) -> Result<Vec<Value>, LuaError> {
3342 let (pos, keep) = self.call_nested_at(f, args)?;
3343 let out = self.cur.stack.get(pos..self.top).map(<[Value]>::to_vec).unwrap_or_default();
3344 if keep {
3346 for v in out.iter().copied().filter(|v| v.is_collectable()) {
3347 self.push_scratch(v);
3348 }
3349 }
3350 Ok(out)
3351 }
3352
3353 pub(crate) fn resume_nested(&mut self) -> Result<Vec<Value>, LuaError> {
3356 let Some(call) = self.pending_call.take() else {
3357 return Err(LuaError::msg("no call is pending"));
3358 };
3359 self.c_depth += 1;
3360 self.cur.nny += 1;
3361 let saved = (self.native_depth, self.ntop);
3362 self.native_depth = 0;
3363 self.ntop = call.ntop;
3364 let step = if self.gc_pending.is_some() { self.gc_step_pausable() } else { Ok(()) };
3366 match &step {
3369 Err(e) if !e.is_pending() && std::mem::take(&mut self.rewound) => {
3370 self.fuel -= 1;
3371 self.due_skip = false;
3372 self.gc_call_before = None;
3373 }
3374 Ok(()) => self.rewound = false,
3375 Err(_) => {}
3376 }
3377 let r = step.and_then(|()| {
3378 if !self.heap.gc_due() {
3381 self.due_skip = false;
3382 }
3383 self.execute(call.bthread, call.bdepth)
3384 });
3385 let ntop = self.ntop;
3386 self.native_depth = saved.0;
3387 self.ntop = saved.1;
3388 self.cur.nny = self.cur.nny.saturating_sub(1);
3389 self.c_depth -= 1;
3390 let (pos, keep) = self.end_nested(r, PendingCall { ntop, ..call })?;
3391 let out = self.cur.stack.get(pos..self.top).map(<[Value]>::to_vec).unwrap_or_default();
3392 if keep {
3393 for v in out.iter().copied().filter(|v| v.is_collectable()) {
3394 self.push_scratch(v);
3395 }
3396 }
3397 Ok(out)
3398 }
3399
3400 pub(crate) fn cancel_nested(&mut self) {
3404 if self.pending_start.take().is_some() {
3405 let (fuel, reserve) = (self.fuel, self.reserve);
3407 self.fuel = i64::MAX;
3408 let _ = self.gc_step();
3409 (self.fuel, self.reserve) = (fuel, reserve);
3410 self.gc_pending = None;
3411 return;
3412 }
3413 let Some(call) = self.pending_call.take() else { return };
3414 if self.gc_pending.is_some() {
3415 let (fuel, reserve) = (self.fuel, self.reserve);
3416 self.fuel = i64::MAX;
3417 let _ = self.gc_step();
3419 (self.fuel, self.reserve) = (fuel, reserve);
3420 self.gc_pending = None;
3421 }
3422 self.due_skip = false;
3423 self.gc_call_before = None;
3424 self.rewound = false;
3425 self.close_upvals(call.pos);
3426 self.cur.tbc.retain(|&s| s < call.pos);
3427 self.cur.frames.truncate(call.bdepth);
3428 }
3429
3430 pub(crate) fn call_nested1(&mut self, f: Value, args: &[Value]) -> Result<Value, LuaError> {
3432 let (pos, keep) = self.call_nested_at(f, args)?;
3433 let v = if self.top > pos { self.st(pos) } else { Value::Nil };
3434 if keep && v.is_collectable() {
3435 self.push_scratch(v);
3436 }
3437 Ok(v)
3438 }
3439
3440 fn call_nested_at(&mut self, f: Value, args: &[Value]) -> Result<(usize, bool), LuaError> {
3443 if self.c_depth >= self.limits.native_depth
3444 || self.stack_base.abs_diff(crate::stack_pos()) > self.limits.stack_bytes
3445 {
3446 let native_on_top =
3451 self.native_stack.last().is_some_and(|&(t, d, ..)| t == self.cur_ref && d == self.cur.frames.len());
3452 return Err(if native_on_top {
3453 LuaError::Plain("C stack overflow".into())
3454 } else {
3455 LuaError::msg("C stack overflow")
3456 });
3457 }
3458 let pos = self.call_top();
3459 self.ensure_stack(pos + args.len() + 1 + EXTRA_STACK)?;
3460 if let Some((slot, rest)) = self.cur.stack.get_mut(pos..pos + 1 + args.len()).and_then(|s| s.split_first_mut()) {
3461 *slot = f;
3462 for (d, a) in rest.iter_mut().zip(args) {
3463 *d = *a;
3464 }
3465 }
3466 let bthread = self.cur_ref;
3467 let bdepth = self.cur.frames.len();
3468 self.c_depth += 1;
3469 self.cur.nny += 1;
3470 let saved = (self.native_depth, self.ntop, self.scratch.len());
3471 self.native_depth = 0;
3472 self.ntop = pos + 1 + args.len();
3473 let called = match f {
3475 Value::Func(fr) if let Some(&Func::Lua { proto, .. }) = self.heap.funcs.get(fr.idx) => {
3476 self.push_frame(fr, proto, pos, args.len(), -1, FrameKind::Normal, false)
3477 }
3478 _ => self.precall(pos, args.len(), -1, FrameKind::Normal, false),
3479 };
3480 let r = match called {
3481 Ok(Called::Done) => Ok(()),
3482 Ok(Called::Lua) => {
3483 if self.fast && self.cur.frames.last().and_then(|f| self.proto(f.proto)).is_some_and(|p| !p.wide()) {
3486 let ctx = crate::fast::Ctx { cur: bthread, stop_depth: bdepth, ..self.fast_ctx() };
3487 crate::fast::run::<WINDOW>(&mut self.heap, &mut self.cur, &mut self.top, &ctx, &mut self.fuel);
3488 }
3489 if self.cur.frames.len() > bdepth { self.execute(bthread, bdepth) } else { Ok(()) }
3490 }
3491 Ok(Called::Switched) => self.execute(bthread, bdepth),
3492 Err(e) => Err(c_level(e)),
3493 };
3494 let ntop = self.ntop;
3495 self.native_depth = saved.0;
3496 self.ntop = saved.1;
3497 self.cur.nny = self.cur.nny.saturating_sub(1);
3498 self.c_depth -= 1;
3499 self.end_nested(r, PendingCall { pos, bthread, bdepth, keep: saved.0 > 0, ntop })
3500 }
3501
3502 fn end_nested(&mut self, r: Result<(), LuaError>, call: PendingCall) -> Result<(usize, bool), LuaError> {
3505 let PendingCall { pos, bdepth, keep, .. } = call;
3506 match r {
3507 Ok(()) => Ok((pos, keep)),
3508 Err(e) => {
3509 if e.is_pending() {
3510 self.pending_call = Some(call);
3511 return Err(e);
3512 }
3513 if e.limit().is_some() {
3514 self.close_upvals(pos);
3515 self.cur.tbc.retain(|&s| s < pos);
3516 self.cur.frames.truncate(bdepth);
3517 return Err(e);
3518 }
3519 let ev = self.normalize(e)?;
3520 let ev = self.close_with_error(pos, ev);
3522 self.cur.frames.truncate(bdepth);
3523 Err(LuaError::Value(ev?))
3524 }
3525 }
3526 }
3527
3528 pub(crate) fn where_(&self, level: usize) -> String {
3532 let mut back: Option<usize> = None;
3536 let mut found = String::new();
3537 self.walk_activations(&self.cur, self.cur_ref, self.err_closing, None, |run| match run {
3538 Run::Lua(i) => {
3539 let b = *back.get_or_insert(level.saturating_sub(1));
3540 if b == 0 {
3541 if let Some(f) = self.cur.frames.get(i) {
3542 found = self.frame_where(f);
3543 }
3544 return true;
3545 }
3546 back = Some(b - 1);
3547 false
3548 }
3549 Run::C { count, .. } => pass_rust(&mut back, level, count).is_some(),
3550 Run::Base => pass_rust(&mut back, level, 1).is_some(),
3551 });
3552 found
3553 }
3554
3555 pub(crate) fn activations(
3562 &self,
3563 ts: &ThreadState,
3564 tref: ThreadRef,
3565 err_closing: Option<(usize, usize)>,
3566 extra: Option<(usize, usize, usize)>,
3567 ) -> Vec<Act> {
3568 let mut runs = Vec::new();
3569 self.walk_activations(ts, tref, err_closing, extra, |run| {
3570 runs.push(run);
3571 false
3572 });
3573 let mut recs = Vec::with_capacity(runs.len());
3574 for run in runs.into_iter().rev() {
3575 match run {
3576 Run::Lua(i) => recs.push(Act::Lua(i)),
3577 Run::Base => recs.push(Act::Base),
3578 Run::C { slot: None, count } => recs.extend(std::iter::repeat_n(Act::C(None), count)),
3579 Run::C { slot: Some(s), count } => recs.extend((0..count).map(|j| Act::C(Some(s + j)))),
3580 }
3581 }
3582 recs
3583 }
3584
3585 pub(crate) fn activation_count(
3587 &self,
3588 ts: &ThreadState,
3589 tref: ThreadRef,
3590 err_closing: Option<(usize, usize)>,
3591 extra: Option<(usize, usize, usize)>,
3592 ) -> usize {
3593 let mut count = 0;
3594 self.walk_activations(ts, tref, err_closing, extra, |run| {
3595 count += match run {
3596 Run::C { count, .. } => count,
3597 Run::Lua(_) | Run::Base => 1,
3598 };
3599 false
3600 });
3601 count
3602 }
3603
3604 fn walk_activations(
3609 &self,
3610 ts: &ThreadState,
3611 tref: ThreadRef,
3612 err_closing: Option<(usize, usize)>,
3613 extra: Option<(usize, usize, usize)>,
3614 mut visit: impl FnMut(Run) -> bool,
3615 ) {
3616 let n = ts.frames.len();
3617 let mut natives: Vec<(usize, usize, usize)> = self
3620 .native_stack
3621 .iter()
3622 .filter(|(t, ..)| *t == tref)
3623 .map(|&(_, d, slot, under)| (d, slot.wrapping_sub(under), under + 1))
3624 .collect();
3625 if let Some((d, slot, under)) = extra
3626 && d <= n
3627 {
3628 let at = natives.iter().position(|&(nd, ..)| nd >= d).unwrap_or(natives.len());
3631 natives.insert(at, (d, slot.wrapping_sub(under), under + 1));
3632 }
3633 let ec_hi = err_closing.map(|(_, hi)| hi);
3639 let mut dead = Dead { ec: err_closing, min_lo: usize::MAX, los: std::collections::BinaryHeap::new() };
3640 let pcalls = |f: &Frame, with_pairs: bool, visit: &mut dyn FnMut(Run) -> bool| match f.kind {
3644 FrameKind::Protected { dest, .. } => {
3645 (with_pairs && under_pairs(f.kind) && visit(Run::C { slot: None, count: 1 }))
3646 || visit(Run::C { slot: Some(dest), count: pcall_levels(f.kind).max(1) })
3647 }
3648 FrameKind::Cont(_) if under_pairs(f.kind) => visit(Run::C { slot: None, count: 1 }),
3649 _ => visit(Run::Base),
3650 };
3651 let mut k = natives.len();
3652 let mut i = n;
3653 loop {
3654 let mut lo_nat = k;
3656 while lo_nat > 0 && natives.get(lo_nat - 1).is_some_and(|&(d, ..)| d >= i) {
3657 lo_nat -= 1;
3658 }
3659 let any = natives.get(lo_nat..k).is_some_and(|s| s.iter().any(|&(d, ..)| d == i));
3660 if let Some(f) = ts.frames.get(i) {
3661 dead.activate(i);
3662 if !dead.gone(i) {
3663 if dead.is_lo(i) {
3664 if pcalls(f, false, &mut visit) {
3667 return;
3668 }
3669 } else {
3670 if visit(Run::Lua(i)) {
3671 return;
3672 }
3673 if !any
3677 && ec_hi != Some(i)
3678 && !f.from_lua
3679 && (!matches!(f.kind, FrameKind::Cont(_)) || under_pairs(f.kind))
3680 && pcalls(f, true, &mut visit)
3681 {
3682 return;
3683 }
3684 }
3685 }
3686 if let FrameKind::Cont(Cont::ErrClosing { frame }) = f.kind
3687 && frame < i
3688 {
3689 dead.add(frame);
3690 }
3691 }
3692 if any {
3696 let keep = i == n || i == 0 || ec_hi == Some(i) || {
3697 dead.activate(i - 1);
3698 !dead.gone(i - 1) && !dead.is_lo(i - 1)
3699 };
3700 for &(d, slot, count) in natives.get(lo_nat..k).unwrap_or_default().iter().rev() {
3701 if keep && d == i && visit(Run::C { slot: Some(slot), count }) {
3702 return;
3703 }
3704 }
3705 }
3706 k = lo_nat;
3707 if i == 0 {
3708 return;
3709 }
3710 i -= 1;
3711 }
3712 }
3713
3714 #[inline]
3716 pub(crate) fn proto(&self, p: u32) -> Option<&Proto> {
3717 self.heap.protos.get(p)
3718 }
3719
3720 fn frame_where(&self, f: &Frame) -> String {
3722 match self.proto(f.proto) {
3723 Some(p) => format!("{}:{}: ", p.source, p.line(f.pc.saturating_sub(1))),
3724 None => String::new(),
3725 }
3726 }
3727
3728 pub(crate) fn charge_error(&mut self) -> Result<(), LuaError> {
3731 let depth = self.cur.frames.len() + self.native_stack.len();
3732 self.charge(ERROR_FUEL + ((depth + crate::debug::take_work()) / 16) as u64)
3733 }
3734
3735 pub(crate) fn normalize(&mut self, e: LuaError) -> Result<Value, LuaError> {
3737 let msg = match e.into_kind() {
3738 ErrorKind::Value(v) => return Ok(v),
3739 ErrorKind::Limit(k) => return Err(LuaError::Limit(k)),
3740 ErrorKind::Pending => return Err(ErrorKind::Pending.into()),
3741 ErrorKind::Msg(m) => format!("{}{m}", self.where_(1)),
3742 ErrorKind::Plain(m) => m,
3743 ErrorKind::Type { op, ty, .. } => format!("{}attempt to {op} a {ty} value", self.where_(1)),
3744 ErrorKind::Call { ty } => format!("{}attempt to call a {ty} value", self.where_(1)),
3745 ErrorKind::IntRepr { .. } => format!("{}number has no integer representation", self.where_(1)),
3746 ErrorKind::Arg(n, m) => return self.arg_error_value(n, &m),
3747 };
3748 self.charge_error()?;
3749 let cut = truncate_utf8(&msg, self.limits.error_len);
3750 let v = self.new_str(cut.as_bytes());
3751 self.heap.mem.headroom = 0;
3754 v.map_err(|e| if e.limit().is_some() { e } else { LuaError::Limit(LimitKind::Memory) })
3755 }
3756
3757 pub(crate) fn arg_error_value(&mut self, n: usize, msg: &str) -> Result<Value, LuaError> {
3759 self.arg_error_bytes(n, msg.as_bytes())
3760 }
3761
3762 pub(crate) fn arg_error_bytes(&mut self, n: usize, msg: &[u8]) -> Result<Value, LuaError> {
3764 let (name, method) = self.called_name();
3765 let head = if method && n == 1 {
3766 format!("calling '{name}' on bad self (")
3767 } else {
3768 format!("bad argument #{} to '{name}' (", if method { n - 1 } else { n })
3769 };
3770 let mut full = self.where_(1).into_bytes();
3771 full.extend_from_slice(head.as_bytes());
3772 full.extend_from_slice(msg);
3773 full.push(b')');
3774 self.charge_error()?;
3775 self.new_str(cut_message(&full, self.limits.error_len))
3776 }
3777
3778 pub(crate) fn msg_bytes(&mut self, parts: &[&[u8]]) -> LuaError {
3783 let mut full = self.where_(1).into_bytes();
3784 for p in parts {
3785 full.extend_from_slice(p);
3786 }
3787 if let Err(e) = self.charge_error() {
3788 return e;
3789 }
3790 match self.new_str(cut_message(&full, self.limits.error_len)) {
3791 Ok(v) => LuaError::Value(v),
3792 Err(e) => e,
3793 }
3794 }
3795
3796 fn called_name(&self) -> (String, bool) {
3799 if self.native_from_lua
3800 && let Some(f) = self.cur.frames.last()
3801 {
3802 let pc = f.pc.saturating_sub(1);
3803 let Some(p) = self.proto(f.proto) else { return (self.native_name.to_owned(), false) };
3804 match p.code.get(pc) {
3805 Some(Instr::Call { a, .. } | Instr::TailCall { a, .. }) => {
3806 if let Some((kind, name)) = crate::debug::obj_name(self, p, pc, *a) {
3807 return (name, kind == "method");
3808 }
3809 }
3810 Some(Instr::TForCall { .. }) => return ("for iterator".into(), false),
3811 _ => {}
3812 }
3813 }
3814 if let Some(event) = self.native_event {
3816 return (event.into(), false);
3817 }
3818 if self.native_name.ends_with("_aux") {
3821 return ("?".into(), false);
3822 }
3823 (self.native_name.to_owned(), false)
3824 }
3825
3826 fn annotate(&self, e: LuaError, pidx: u32, pc: usize, operands: &[crate::debug::Operand]) -> LuaError {
3828 let empty = Proto::default();
3829 let proto = self.proto(pidx).unwrap_or(&empty);
3830 match e.into_kind() {
3831 ErrorKind::Type { op, ty, operand } => {
3832 let info = operands
3833 .get(usize::from(operand))
3834 .map(|o| crate::debug::var_info(self, proto, pc, *o))
3835 .unwrap_or_default();
3836 LuaError::Msg(format!("attempt to {op} a {ty} value{info}"))
3837 }
3838 ErrorKind::Call { ty } => {
3839 let info = operands.first().map(|o| crate::debug::var_info(self, proto, pc, *o)).unwrap_or_default();
3840 LuaError::Msg(format!("attempt to call a {ty} value{info}"))
3841 }
3842 ErrorKind::IntRepr { operand } => {
3843 let info = operands
3844 .get(usize::from(operand))
3845 .map(|o| crate::debug::var_info(self, proto, pc, *o))
3846 .unwrap_or_default();
3847 LuaError::Msg(format!("number{info} has no integer representation"))
3848 }
3849 other => other.into(),
3850 }
3851 }
3852
3853 fn note_traceback(&mut self) {
3855 let mut trace = self.last_trace.take().unwrap_or_default();
3856 trace.clear();
3857 self.trace_sources.clear();
3858 for f in self.cur.frames.iter().rev().take(22) {
3859 let Some(p) = self.heap.protos.get(f.proto) else { continue };
3860 if !self.trace_sources.last().is_some_and(|s| Arc::ptr_eq(s, &p.source)) {
3861 self.trace_sources.push(Arc::clone(&p.source));
3862 }
3863 trace.push((self.trace_sources.len() - 1, p.line(f.pc.saturating_sub(1)), p.line_defined));
3864 }
3865 self.last_trace = Some(trace);
3866 }
3867
3868 pub(crate) fn take_traceback(&mut self) -> String {
3871 let Some(trace) = self.last_trace.take() else { return String::new() };
3872 let mut s = String::from("stack traceback:");
3873 for &(src, line, defined) in &trace {
3874 let Some(source) = self.trace_sources.get(src) else { continue };
3875 let what = if defined == 0 { "in main chunk".to_owned() } else { format!("in function <{source}:{defined}>") };
3876 s.push_str(&format!("\n\t{source}:{line}: {what}"));
3877 }
3878 self.trace_sources.clear();
3879 s
3880 }
3881
3882 fn on_error(&mut self, e: LuaError, bthread: ThreadRef, bdepth: usize) -> Result<(), LuaError> {
3885 if e.is_pending() {
3886 return Err(e);
3887 }
3888 if e.limit().is_some() {
3889 self.abort_to(bthread);
3890 return Err(e);
3891 }
3892 let mut err = match self.normalize(e) {
3893 Ok(v) => v,
3894 Err(e) if e.limit().is_some() => {
3895 self.abort_to(bthread);
3896 return Err(e);
3897 }
3898 Err(other) => return Err(other),
3899 };
3900 let mut first = true;
3901 loop {
3902 let min = if self.cur_ref == bthread { bdepth } else { 0 };
3903 let found = (min..self.cur.frames.len())
3904 .rev()
3905 .find(|&i| matches!(self.cur.frames.get(i).map(|f| f.kind), Some(FrameKind::Protected { .. })));
3906 if std::mem::take(&mut first) && self.handler_raise.thread == Some(self.cur_ref) {
3909 if found.is_some() {
3910 self.handler_raise.raised = None;
3911 self.handler_raise.pos = None;
3912 } else if self.handler_raise.raised.is_none() {
3913 let (level, walked) = self.c_levels();
3917 if let Err(e) = self.charge((walked / RESUMER_FRAMES_PER_FUEL) as u64) {
3918 self.abort_to(bthread);
3919 return Err(e);
3920 }
3921 self.handler_raise.raised = Some(level);
3922 self.handler_raise.pos = self.handler_raise.cross.and_then(|(from, at)| self.cross_where(from, at));
3923 }
3924 }
3925 if let Some(i) = found {
3926 let Some(fr) = self.cur.frames.get(i) else { break };
3927 let dest = match fr.kind {
3928 FrameKind::Protected { dest, .. } => dest,
3929 _ => fr.func,
3930 };
3931 let handler = fr.handler;
3932 if let Some(h) = handler {
3933 err = self.call_handler(h, err).inspect_err(|_| self.abort_to(bthread))?;
3934 }
3935 self.set_st(dest + 1, err);
3943 match self.close_error_async(i) {
3947 Ok(()) => return Ok(()),
3948 Err(e) => {
3949 err = self.rethrown(e, bthread)?;
3950 continue;
3951 }
3952 }
3953 }
3954 if self.cur_ref != bthread && self.cur.resumer.is_some() {
3955 let by_wrap = self
3958 .cur
3959 .resumer
3960 .and_then(|r| self.heap.threads.get(r.idx))
3961 .and_then(|t| t.resume_pending)
3962 .is_some_and(|p| p.wrap);
3963 if by_wrap {
3964 err = match self.close_with_error(0, err) {
3965 Ok(v) => v,
3966 Err(e) => {
3967 self.abort_to(bthread);
3968 return Err(e);
3969 }
3970 };
3971 }
3972 if by_wrap {
3973 self.cur.frames.clear();
3974 } else {
3975 self.cur.died_in = match self.err_native {
3979 Some(((t, d, slot), _, v)) if t == self.cur_ref && self.raw_equal(&v, &err) => {
3980 Some((d, slot, self.st(slot)))
3981 }
3982 _ => None,
3983 };
3984 }
3985 self.cur.status = CoStatus::Dead;
3986 self.cur.error = Some(err);
3987 let wrap = self.switch_back()?;
3988 if wrap.wrap {
3989 if let Value::Str(s) = err
3991 && wrap.from_lua
3992 {
3993 let w = self.cur.frames.last().map_or_else(String::new, |f| self.frame_where(f));
3994 if !w.is_empty() {
3995 self.charge_bytes(self.bytes(s).len())?;
3998 let mut b = w.into_bytes();
3999 b.extend_from_slice(self.bytes(s));
4000 err = self.new_str(&b)?;
4001 }
4002 }
4003 if let FrameKind::Protected { dest, wanted, cont } = wrap.kind {
4004 self.set_st(dest, Value::Bool(false));
4006 self.set_st(dest + 1, err);
4007 let r = self.move_results(dest, dest, 2, wanted).and_then(|()| match cont {
4008 Some(c) => self.apply_cont(c, Value::Bool(false)),
4009 None => Ok(()),
4010 });
4011 match r {
4012 Ok(()) => return Ok(()),
4013 Err(e) => {
4014 err = self.rethrown(e, bthread)?;
4015 continue;
4016 }
4017 }
4018 }
4019 continue;
4020 }
4021 self.set_st(wrap.func, Value::Bool(false));
4022 self.set_st(wrap.func + 1, err);
4023 match self.finish_call(wrap.kind, wrap.func, wrap.func, 2, wrap.nresults, true) {
4024 Ok(()) => return Ok(()),
4025 Err(e) => {
4026 err = self.rethrown(e, bthread)?;
4027 continue;
4028 }
4029 }
4030 }
4031 break;
4032 }
4033 self.note_traceback();
4034 Err(LuaError::Value(err))
4035 }
4036
4037 #[cold]
4041 fn rethrown(&mut self, e: LuaError, bthread: ThreadRef) -> Result<Value, LuaError> {
4042 let r = if e.limit().is_some() { Err(e) } else { self.normalize(e) };
4043 if r.as_ref().is_err_and(|e| e.limit().is_some()) {
4044 self.abort_to(bthread);
4045 return r;
4046 }
4047 r
4048 }
4049
4050 fn abort_to(&mut self, bthread: ThreadRef) {
4052 while self.cur_ref != bthread {
4053 self.close_upvals(0);
4054 self.cur.tbc.clear();
4055 self.cur.frames.clear();
4056 self.cur.status = CoStatus::Dead;
4057 let Some(r) = self.cur.resumer.take() else { break };
4058 self.resume_depth = self.resume_depth.saturating_sub(1);
4059 self.swap_to(r);
4060 self.cur.resume_pending = None;
4061 self.cur.status = CoStatus::Running;
4062 }
4063 }
4064
4065 fn fast_ctx(&self) -> crate::fast::Ctx {
4071 crate::fast::Ctx {
4072 cur: self.cur_ref,
4073 call_depth: self.limits.call_depth,
4074 stop_depth: 0,
4075 index_name: self.tm_names.get(Tm::Index as usize).map_or(Value::Nil, |s| Value::Str(*s)),
4076 eq_name: self.tm_names.get(Tm::Eq as usize).map_or(Value::Nil, |s| Value::Str(*s)),
4077 string_meta: self.string_meta,
4078 string_len: self.limits.string_len,
4079 next_fn: self.names.next_fn,
4080 ipairs_aux: self.names.ipairs_aux,
4081 utf8_iters: self.names.utf8_iters,
4082 math_fast: self.names.math_fast,
4083 math_mask: self.names.math_mask,
4084 table_fast: self.names.table_fast,
4085 table_mask: self.names.table_mask,
4086 }
4087 }
4088
4089 fn swap_to(&mut self, to: ThreadRef) {
4090 let (from, into) = (self.cur_ref.idx as usize, to.idx as usize);
4094 let threads = &mut self.heap.threads;
4095 if from != into && from < threads.slots() && let Some(slot) = threads.at_mut(into) {
4096 std::mem::swap(&mut self.cur, slot);
4097 threads.swap_slots(from, into);
4098 } else {
4099 let incoming = self.heap.threads.get_mut(to.idx).map(std::mem::take).unwrap_or_default();
4100 let outgoing = std::mem::replace(&mut self.cur, incoming);
4101 if let Some(slot) = self.heap.threads.get_mut(self.cur_ref.idx) {
4102 *slot = outgoing;
4103 }
4104 }
4105 self.cur_ref = to;
4106 }
4107
4108 #[cold]
4116 #[inline(never)]
4117 #[allow(clippy::too_many_arguments)]
4118 fn resume_refused(
4119 &mut self,
4120 func: usize,
4121 nres: i32,
4122 co: ThreadRef,
4123 wrap: bool,
4124 from_lua: bool,
4125 kind: FrameKind,
4126 pcall_of_resume: usize,
4127 ) -> Result<Option<Called>, LuaError> {
4128 let (level, walked) = self.c_levels();
4129 self.charge((walked / RESUMER_FRAMES_PER_FUEL) as u64)?;
4131 let from = (level + pcall_of_resume).saturating_sub(2);
4135 let fresh = self.heap.threads.get(co.idx).is_some_and(|t| t.fresh);
4136 let dies = from + 1 == C_HANDLER_LEVELS && fresh;
4137 if from < C_HANDLER_LEVELS && !dies && self.resume_depth < self.limits.native_depth {
4138 return Ok(None);
4139 }
4140 let msg = "C stack overflow";
4141 if dies && self.resume_depth < self.limits.native_depth {
4142 let e = self.new_str(msg.as_bytes())?;
4143 if let Some(t) = self.heap.threads.get_mut(co.idx) {
4144 t.fresh = false;
4145 t.status = CoStatus::Dead;
4146 t.error = if wrap { None } else { Some(e) };
4148 }
4149 }
4150 if wrap {
4151 return Err(if from_lua { LuaError::msg(msg) } else { LuaError::Plain(msg.into()) });
4152 }
4153 let m = self.new_str(msg.as_bytes())?;
4154 self.set_st(func, Value::Bool(false));
4155 self.set_st(func + 1, m);
4156 self.finish_call(kind, func, func, 2, nres, false)?;
4157 Ok(Some(Called::Done))
4158 }
4159
4160 fn do_resume(
4161 &mut self,
4162 func: usize,
4163 nres: i32,
4164 co: ThreadRef,
4165 wrap: bool,
4166 from_lua: bool,
4167 kind: FrameKind,
4168 ) -> Result<Called, LuaError> {
4169 let args = std::mem::take(&mut self.rets);
4170 let status = if co == self.cur_ref {
4171 CoStatus::Running
4172 } else {
4173 self.heap.threads.get(co.idx).map_or(CoStatus::Dead, |t| t.status)
4174 };
4175 if status != CoStatus::Suspended || !self.heap.threads.live(co.idx, co.generation) {
4176 let msg = match status {
4177 CoStatus::Dead => "cannot resume dead coroutine",
4178 _ => "cannot resume non-suspended coroutine",
4179 };
4180 if wrap {
4181 return Err(if from_lua { LuaError::msg(msg) } else { LuaError::Plain(msg.into()) });
4182 }
4183 let m = self.new_str(msg.as_bytes())?;
4184 self.set_st(func, Value::Bool(false));
4185 self.set_st(func + 1, m);
4186 self.finish_call(kind, func, func, 2, nres, false)?;
4187 return Ok(Called::Done);
4188 }
4189 let pcall_of_resume = if from_lua { 0 } else { c_calls(kind) };
4199 let here = pcall_of_resume + self.c_bound_here(func);
4200 if self.c_depth + self.protected_natives + (HANDLER_BASE_LEVELS - 1) + here >= C_HANDLER_LEVELS
4201 || self.resume_depth + 1 > self.limits.native_depth
4202 {
4203 if let Some(done) = self.resume_refused(func, nres, co, wrap, from_lua, kind, pcall_of_resume)? {
4204 return Ok(done);
4205 }
4206 }
4207 if self.heap.threads.get(co.idx).is_some_and(|t| t.fresh) {
4210 self.charge(COROUTINE_COST)?;
4211 }
4212 let inherited = RESUME_LEVELS + here;
4214 self.resume_depth += 1;
4215 self.cur.resume_pending = Some(Pending { func, nresults: nres, wrap, from_lua, kind });
4216 self.cur.status = CoStatus::Normal;
4217 let (prev, depth) = (self.cur_ref, self.cur.frames.len());
4218 self.swap_to(co);
4219 self.cur.status = CoStatus::Running;
4220 self.cur.resumer = Some(prev);
4221 self.cur.c_bound = inherited;
4222 if self.cur.fresh {
4223 self.cur.fresh = false;
4224 self.ensure_stack(args.len() + 1 + EXTRA_STACK)?;
4225 for (i, a) in args.iter().enumerate() {
4226 self.set_st(1 + i, *a);
4227 }
4228 match self.precall(0, args.len(), -1, FrameKind::Normal, false) {
4229 Ok(Called::Done) => self.finish_coroutine()?,
4230 Ok(Called::Lua | Called::Switched) => {}
4231 Err(e) => self.on_error(e, prev, depth)?,
4234 }
4235 } else if let Some(p) = self.cur.yield_pending.take() {
4236 self.cur.unrolled = self.cur.frames.len();
4237 self.ensure_stack(p.func + args.len() + 1)?;
4238 for (i, a) in args.iter().enumerate() {
4239 self.set_st(p.func + i, *a);
4240 }
4241 self.finish_call(p.kind, p.func, p.func, args.len(), p.nresults, true)?;
4242 }
4243 self.give_back_rets(args);
4244 Ok(Called::Switched)
4245 }
4246
4247 fn give_back_rets(&mut self, mut v: Vec<Value>) {
4250 if self.rets.capacity() == 0 && v.capacity() <= crate::stdlib::NATIVE_CHUNK {
4252 v.clear();
4253 self.rets = v;
4254 }
4255 }
4256
4257 fn finish_coroutine(&mut self) -> Result<(), LuaError> {
4259 let vals: Vec<Value> = self.cur.stack.get(0..self.top).map(<[Value]>::to_vec).unwrap_or_default();
4260 self.close_upvals(0);
4261 self.cur.status = CoStatus::Dead;
4262 let me = self.cur_ref;
4263 let r = self.deliver(vals);
4264 self.retire_stack(me);
4266 r
4267 }
4268
4269 fn deliver(&mut self, vals: Vec<Value>) -> Result<(), LuaError> {
4271 let p = self.switch_back()?;
4272 let mut off = 0;
4273 if !p.wrap {
4274 self.ensure_stack(p.func + 1)?;
4275 self.set_st(p.func, Value::Bool(true));
4276 off = 1;
4277 }
4278 let mut hold = crate::stdlib::MemHold::default();
4280 let bytes = vals.capacity().saturating_mul(std::mem::size_of::<Value>());
4281 hold.cover(self, bytes)?;
4282 let r = self.ensure_stack(p.func + off + vals.len() + 1);
4283 hold.give_back(self);
4284 r?;
4285 for (i, v) in vals.iter().enumerate() {
4286 self.set_st(p.func + off + i, *v);
4287 }
4288 let n = vals.len();
4289 self.give_back_rets(vals);
4290 self.finish_call(p.kind, p.func, p.func, n + off, p.nresults, true)
4291 }
4292
4293 pub(crate) fn swap_in_for_close(&mut self, co: ThreadRef) -> (CoStatus, usize) {
4304 let was = std::mem::replace(&mut self.cur.status, CoStatus::Normal);
4305 self.swap_to(co);
4306 self.cur.nny += 1;
4307 let live = crate::heap::parked_live(&self.cur, &self.heap.protos).unwrap_or(self.cur.stack.len());
4308 (was, std::mem::replace(&mut self.ntop, live))
4309 }
4310
4311 pub(crate) fn swap_out_after_close(&mut self, me: ThreadRef, (was, ntop): (CoStatus, usize)) {
4313 self.cur.nny = self.cur.nny.saturating_sub(1);
4314 self.ntop = ntop;
4315 self.swap_to(me);
4316 self.cur.status = was;
4317 }
4318
4319 fn switch_back(&mut self) -> Result<Pending, LuaError> {
4321 self.resume_depth = self.resume_depth.saturating_sub(1);
4322 let Some(r) = self.cur.resumer.take() else {
4323 return Err(LuaError::msg("internal: coroutine without a resumer"));
4324 };
4325 self.swap_to(r);
4326 self.cur.status = CoStatus::Running;
4327 self.cur.resume_pending.take().ok_or_else(|| LuaError::msg("internal: resumer not waiting"))
4328 }
4329
4330 fn do_yield(&mut self, func: usize, nres: i32, kind: FrameKind) -> Result<(), LuaError> {
4331 if self.cur_ref == self.main_ref {
4333 return Err(LuaError::Value(self.new_str(b"attempt to yield from outside a coroutine")?));
4334 }
4335 if self.cur.nny > 0 || self.cur.resumer.is_none() {
4338 return Err(LuaError::Value(self.new_str(b"attempt to yield across a C-call boundary")?));
4339 }
4340 let vals = std::mem::take(&mut self.rets);
4341 self.cur.yield_pending = Some(Pending { func, nresults: nres, wrap: false, from_lua: false, kind });
4342 self.cur.status = CoStatus::Suspended;
4343 self.deliver(vals)
4344 }
4345
4346 pub(crate) fn new_coroutine(&mut self, f: Value) -> Result<ThreadRef, LuaError> {
4361 self.charge(8)?;
4363 let mut stack = match self.spare_stacks.pop() {
4364 Some(s) => {
4365 self.heap.mem.slack_out(s.capacity() * SLOT_BYTES);
4366 s
4367 }
4368 None => Vec::with_capacity(1),
4370 };
4371 stack.clear();
4372 stack.push(f);
4373 let st = ThreadState { stack, fresh: true, ..ThreadState::default() };
4374 self.charge_mem(st.mem_size())?;
4376 let t = self.heap.place_thread(st);
4377 self.hold(Value::Thread(t));
4378 Ok(t)
4379 }
4380
4381 pub(crate) fn retire_stack(&mut self, co: ThreadRef) {
4386 if co == self.cur_ref || co == self.main_ref {
4387 return;
4388 }
4389 if !self.heap.threads.live(co.idx, co.generation) {
4390 return;
4391 }
4392 let Some(t) = self.heap.threads.get_mut(co.idx) else { return };
4393 if t.status != CoStatus::Dead || t.fresh || !t.frames.is_empty() || !t.tbc.is_empty() || !t.open_upvals.is_empty() {
4394 return;
4395 }
4396 let mut stack = std::mem::take(&mut t.stack);
4397 let frames = std::mem::take(&mut t.frames);
4398 let mem = &mut self.heap.mem;
4399 mem.release(frames.capacity() * crate::heap::FRAME_BYTES);
4400 let cap = stack.capacity();
4401 mem.release(cap * SLOT_BYTES);
4402 let held: usize = self.spare_stacks.iter().map(|s| s.capacity() * SLOT_BYTES).sum();
4404 if (1..=SPARE_STACK_SLOTS).contains(&cap)
4405 && self.spare_stacks.len() < SPARE_STACKS
4406 && held + cap * SLOT_BYTES <= mem.cap / 16
4407 {
4408 stack.clear();
4409 mem.slack_in(cap * SLOT_BYTES);
4410 self.spare_stacks.push(stack);
4411 }
4412 }
4413
4414 fn drop_spare_stacks(&mut self) {
4416 for s in self.spare_stacks.drain(..) {
4417 self.heap.mem.slack_out(s.capacity() * SLOT_BYTES);
4418 }
4419 }
4420
4421 pub(crate) fn execute(&mut self, bthread: ThreadRef, bdepth: usize) -> Result<(), LuaError> {
4425 loop {
4426 match self.run(bthread, bdepth) {
4427 Ok(()) => return Ok(()),
4428 Err(e) => self.on_error(e, bthread, bdepth)?,
4429 }
4430 }
4431 }
4432
4433 #[allow(clippy::too_many_lines, reason = "the interpreter's dispatch is one match")]
4441 #[allow(clippy::indexing_slicing, reason = "a u8 register into the 256-slot window cannot be out of bounds")]
4442 fn run(&mut self, bthread: ThreadRef, bdepth: usize) -> Result<(), LuaError> {
4443 use crate::debug::Operand as O;
4444 let mut ctx = self.fast_ctx();
4445 let mut epoch = self.ctx_epoch;
4446 let mut fast_tried: Option<bool> = None;
4451 'reload: loop {
4452 if self.cur_ref == bthread && self.cur.frames.len() <= bdepth {
4453 return Ok(());
4454 }
4455 let Some(frame) = self.cur.frames.last() else { return Ok(()) };
4456 let pidx = frame.proto;
4457 let closure = frame.closure;
4458 let frame_base = frame.base;
4460 let mut base = frame_base;
4461 let mut pc = frame.pc;
4462 let mut fuel = self.fuel;
4463 let wide = self.proto(pidx).is_some_and(Proto::wide);
4464 let width = if wide { WIDE_WINDOW } else { WINDOW };
4465 if self.cur.stack.len() < base + width {
4466 self.ensure_window(base, width)?;
4467 }
4468
4469 macro_rules! save {
4470 () => {{
4471 if let Some(f) = self.cur.frames.last_mut() {
4472 f.pc = pc;
4473 }
4474 self.fuel = fuel;
4475 }};
4476 }
4477 macro_rules! call {
4480 ($e:expr) => {{
4481 save!();
4482 let r = $e;
4483 fuel = self.fuel;
4484 r
4485 }};
4486 }
4487 macro_rules! gc_step_at {
4492 ($before:expr) => {
4493 if let Err(e) = call!(self.gc_due_step()) {
4494 save!();
4495 if $before && e.is_pending() {
4496 if let Some(f) = self.cur.frames.last_mut() {
4497 f.pc = pc - 1 - usize::from(base != frame_base);
4498 }
4499 self.fuel += 1;
4500 self.due_skip = true;
4501 self.rewound = true;
4502 }
4503 return Err(e);
4504 }
4505 };
4506 }
4507 macro_rules! t {
4508 ($e:expr) => {
4509 match $e {
4510 Ok(v) => v,
4511 Err(e) => {
4512 save!();
4513 return Err(e);
4514 }
4515 }
4516 };
4517 }
4518 macro_rules! tpop {
4524 ($e:expr) => {{
4526 save!();
4527 if let Err(e) = $e {
4528 return Err(e);
4529 }
4530 }};
4531 }
4532 macro_rules! ta {
4533 ($e:expr, $ops:expr) => {
4534 match $e {
4535 Ok(v) => v,
4536 Err(e) => {
4537 save!();
4538 let ops = $ops;
4539 return Err(self.annotate(e, pidx, pc - 1, &ops));
4540 }
4541 }
4542 };
4543 }
4544 macro_rules! reload {
4547 () => {
4548 continue 'reload
4549 };
4550 }
4551 macro_rules! reg {
4552 ($i:expr) => {
4553 self.cur.stack.get(base + ($i) as usize).copied().unwrap_or(Value::Nil)
4554 };
4555 }
4556 macro_rules! setr {
4557 ($i:expr, $v:expr) => {{
4558 let v = $v;
4559 if let Some(s) = self.cur.stack.get_mut(base + ($i) as usize) {
4560 *s = v;
4561 }
4562 }};
4563 }
4564 macro_rules! kv {
4565 ($k:expr) => {
4566 self.heap.protos.at(pidx as usize).and_then(|p: &Proto| p.consts.get(($k) as usize).copied()).unwrap_or(Value::Nil)
4567 };
4568 }
4569 macro_rules! rk {
4570 ($x:expr) => {{
4571 let x: Rk = $x;
4572 if x.is_const() { kv!(x.index()) } else { reg!(x.index()) }
4573 }};
4574 }
4575 macro_rules! arith {
4580 ($op:expr, $a:expr, $x:expr, $y:expr, $ops:expr) => {{
4581 let (x, y): (Value, Value) = ($x, $y);
4582 let fast = if $op == ArithOp::Sub && matches!(y, Value::Int(_)) && $ops.len() == 2 && matches!($ops[1], O::Rk(r) if r.is_const()) {
4583 crate::fast::sub_k(x, y)
4584 } else {
4585 crate::fast::arith($op, x, y)
4586 };
4587 match fast {
4588 Some(v) => setr!($a, v),
4589 None => match ta!(call!(self.arith($op, x, y, Cont::Store(base + usize::from($a)))), $ops) {
4590 Some(v) => setr!($a, v),
4591 None => reload!(),
4592 },
4593 }
4594 }};
4595 }
4596 macro_rules! arith_rr {
4598 ($op:ident, $a:expr, $b:expr, $c:expr) => {
4599 arith!(ArithOp::$op, $a, reg!(usize::from($b)), reg!(usize::from($c)), [O::Reg($b), O::Reg($c)])
4600 };
4601 }
4602 macro_rules! arith_rk {
4603 ($op:ident, $a:expr, $b:expr, $k:expr) => {
4604 arith!(ArithOp::$op, $a, reg!(usize::from($b)), kv!($k), [O::Reg($b), O::Rk(Rk::konst($k))])
4605 };
4606 }
4607
4608 if self.ctx_epoch != epoch {
4611 ctx = self.fast_ctx();
4612 epoch = self.ctx_epoch;
4613 }
4614 ctx.cur = self.cur_ref;
4615 ctx.stop_depth = if self.cur_ref == bthread { bdepth } else { 0 };
4616 let mut fast_now = self.fast && fast_tried.take() != Some(wide);
4618 loop {
4619 save!();
4622 let moved = fast_now
4623 && if wide {
4624 crate::fast::run::<WIDE_WINDOW>(&mut self.heap, &mut self.cur, &mut self.top, &ctx, &mut self.fuel)
4625 } else {
4626 crate::fast::run::<WINDOW>(&mut self.heap, &mut self.cur, &mut self.top, &ctx, &mut self.fuel)
4627 };
4628 if moved {
4629 fast_tried = Some(wide);
4630 continue 'reload;
4631 }
4632 self.full_steps += u64::from(self.fast);
4633 fast_now = self.fast;
4634 fuel = self.fuel;
4635 pc = self.cur.frames.last().map_or(pc, |f| f.pc);
4636 fuel = match crate::table::take_probes() {
4639 0 => fuel.saturating_sub(1),
4640 n => fuel.saturating_sub(1 + i64::try_from(n).unwrap_or(i64::MAX)),
4641 };
4642 if fuel < 0 {
4643 self.fuel = fuel;
4645 if let Err(e) = self.refuel() {
4646 save!();
4647 return Err(e);
4648 }
4649 fuel = self.fuel;
4650 }
4651 let Some(ins) = self.heap.protos.at(pidx as usize).and_then(|p| p.code.get(pc)).copied() else {
4652 save!();
4653 return Err(LuaError::msg("internal: ran past the end of the code"));
4654 };
4655 pc += 1;
4656 base = frame_base;
4657 let ins = match ins {
4658 Instr::Window { off } => {
4660 base = frame_base + off as usize;
4661 if self.cur.stack.len() < base + width {
4662 t!(call!(self.ensure_window(base, width)));
4663 }
4664 let Some(next) = self.heap.protos.at(pidx as usize).and_then(|p| p.code.get(pc)).copied() else {
4665 save!();
4666 return Err(LuaError::msg("internal: ran past the end of the code"));
4667 };
4668 pc += 1;
4669 next
4670 }
4671 other => other,
4672 };
4673 match ins {
4674 Instr::Window { .. } => {}
4675 Instr::MoveAbs { a, b, b_hi } => {
4676 let (dst, src) = (frame_base + a as usize, base + (usize::from(b) | usize::from(b_hi) << 16));
4679 if self.cur.stack.len() <= dst.max(src) {
4680 t!(call!(self.ensure_window(dst.max(src), 1)));
4681 }
4682 let v = self.cur.stack.get(src).copied().unwrap_or(Value::Nil);
4683 if let Some(s) = self.cur.stack.get_mut(dst) {
4684 *s = v;
4685 }
4686 }
4687 Instr::SetTop { n } => {
4688 let t = frame_base + n as usize;
4689 t!(call!(self.ensure_stack(t + EXTRA_STACK)));
4690 self.top = t;
4691 }
4692 Instr::PadNil { n } => {
4693 let to = frame_base + n as usize;
4694 let from = self.top.min(to);
4695 t!(call!(self.charge((to - from) as u64 / 8)));
4697 t!(call!(self.ensure_stack(to + EXTRA_STACK)));
4698 if let Some(s) = self.cur.stack.get_mut(from..to) {
4699 s.fill(Value::Nil);
4700 }
4701 }
4702 Instr::Move { a, b } => setr!(usize::from(a), reg!(usize::from(b))),
4703 Instr::LoadK { a, k } => {
4704 let v = kv!(k);
4705 setr!(a, v);
4706 }
4707 Instr::LoadInt { a, i } => setr!(usize::from(a), Value::Int(i64::from(i))),
4708 Instr::LoadBool { a, v } => setr!(usize::from(a), Value::Bool(v)),
4709 Instr::LoadFalseSkip { a } => {
4710 setr!(usize::from(a), Value::Bool(false));
4711 pc += 1;
4712 }
4713 Instr::LoadNil { a, n } => {
4714 t!(call!(self.charge(list_fuel(usize::from(n) + 1))));
4717 for i in 0..=usize::from(n) {
4718 setr!(usize::from(a) + i, Value::Nil);
4719 }
4720 }
4721 Instr::GetUpval { a, u } => {
4722 let v = self.upval_get(closure, u);
4723 setr!(a, v);
4724 }
4725 Instr::GetSelf { a, .. } => setr!(a, Value::Func(closure)),
4726 Instr::SetUpval { a, u } => {
4727 let v = reg!(usize::from(a));
4728 self.upval_set(closure, u, v);
4729 }
4730 Instr::GetTabUp { a, u, k } => {
4731 let t = self.upval_get(closure, u);
4732 let key = kv!(k);
4733 if let Value::Table(tr) = t {
4734 if let Some(v) = self.get_field_cached(tr, key, pidx, pc - 1) {
4735 setr!(a, v);
4736 continue;
4737 }
4738 }
4739 match ta!(call!(self.index(t, key, Cont::Store(base + usize::from(a)))), [O::Upval(u)]) {
4740 Some(v) => setr!(a, v),
4741 None => reload!(),
4742 }
4743 }
4744 Instr::SetTabUp { u, k, v } => {
4745 let t = self.upval_get(closure, u);
4746 let key = kv!(k);
4747 let val = rk!(v);
4748 if let Value::Table(tr) = t
4751 && t!(call!(self.set_field_fast(tr, key, val)))
4752 {
4753 continue;
4754 }
4755 if !ta!(call!(self.set_index(t, key, val)), [O::Upval(u)]) {
4756 reload!();
4757 }
4758 }
4759 Instr::GetTable { a, b, c } => {
4760 let t = reg!(usize::from(b));
4761 let key = reg!(usize::from(c));
4762 if let Value::Table(tr) = t
4763 && let Some(tab) = self.heap.tables.get(tr.idx)
4764 && !matches!(key, Value::Str(r) if self.heap.key_needs_settling(r))
4765 {
4766 let v = self.heap.get_in(tab, key);
4767 if !v.is_nil() || tab.meta.is_none() {
4768 setr!(a, v);
4769 continue;
4770 }
4771 }
4772 match ta!(call!(self.index(t, key, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4773 Some(v) => setr!(a, v),
4774 None => reload!(),
4775 }
4776 }
4777 Instr::GetTableK { a, b, k } => {
4778 let t = reg!(usize::from(b));
4779 let key = kv!(k);
4780 if let Value::Table(tr) = t
4781 && let Some(v) = self.get_field_cached(tr, key, pidx, pc - 1)
4782 {
4783 setr!(a, v);
4784 continue;
4785 }
4786 match ta!(call!(self.index(t, key, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4787 Some(v) => setr!(a, v),
4788 None => reload!(),
4789 }
4790 }
4791 Instr::SelfK { a, b, k } => {
4792 let t = reg!(usize::from(b));
4793 setr!(usize::from(a) + 1, t);
4794 let key = kv!(k);
4795 match ta!(call!(self.index(t, key, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4798 Some(v) => setr!(a, v),
4799 None => reload!(),
4800 }
4801 }
4802 Instr::SetTable { a, b, c } => {
4803 let t = reg!(usize::from(a));
4804 let key = reg!(usize::from(b));
4805 let val = rk!(c);
4806 if let Value::Table(tr) = t
4807 && self.heap.tables.get(tr.idx).is_some_and(|t| t.meta.is_none())
4808 {
4809 t!(call!(self.raw_set(tr, key, val)));
4810 continue;
4811 }
4812 if !ta!(call!(self.set_index(t, key, val)), [O::Reg(a)]) {
4813 reload!();
4814 }
4815 }
4816 Instr::SetTableK { a, k, c } => {
4817 let t = reg!(usize::from(a));
4818 let key = kv!(k);
4819 let val = rk!(c);
4820 if let Value::Table(tr) = t
4821 && t!(call!(self.set_field_fast(tr, key, val)))
4822 {
4823 continue;
4824 }
4825 if !ta!(call!(self.set_index(t, key, val)), [O::Reg(a)]) {
4826 reload!();
4827 }
4828 }
4829 Instr::NewTable { a, arr, hash } => {
4830 if self.heap.gc_due() && !std::mem::take(&mut self.due_skip) {
4831 gc_step_at!(true);
4832 }
4833 let (room, asize, hash) = crate::bytecode::newtable_sizes(arr, hash);
4834 let tr = t!(call!(self.new_table_sized(room, asize, hash)));
4835 setr!(a, Value::Table(tr));
4836 }
4837 Instr::Add { a, b, c } => arith_rr!(Add, a, b, c),
4838 Instr::AddK { a, b, k } => arith_rk!(Add, a, b, k),
4839 Instr::Sub { a, b, c } => arith_rr!(Sub, a, b, c),
4840 Instr::SubK { a, b, k } => arith_rk!(Sub, a, b, k),
4841 Instr::Mul { a, b, c } => arith_rr!(Mul, a, b, c),
4842 Instr::MulK { a, b, k } => arith_rk!(Mul, a, b, k),
4843 Instr::Div { a, b, c } => arith_rr!(Div, a, b, c),
4844 Instr::DivK { a, b, k } => arith_rk!(Div, a, b, k),
4845 Instr::Mod { a, b, c } => arith_rr!(Mod, a, b, c),
4846 Instr::ModK { a, b, k } => arith_rk!(Mod, a, b, k),
4847 Instr::IDiv { a, b, c } => arith_rr!(IDiv, a, b, c),
4848 Instr::IDivK { a, b, k } => arith_rk!(IDiv, a, b, k),
4849 Instr::Arith { op, a, b, c } => {
4850 let x = rk!(b);
4851 let y = rk!(c);
4852 let fast = if op == ArithOp::Sub && c.is_const() { crate::fast::sub_k(x, y) } else { crate::fast::arith(op, x, y) };
4853 match fast {
4854 Some(v) => setr!(a, v),
4855 None => {
4856 match ta!(call!(self.arith(op, x, y, Cont::Store(base + usize::from(a)))), [O::Rk(b), O::Rk(c)]) {
4857 Some(v) => setr!(a, v),
4858 None => reload!(),
4859 }
4860 }
4861 }
4862 }
4863 Instr::Unm { a, b } => {
4864 let x = reg!(usize::from(b));
4865 match x {
4866 Value::Int(i) => setr!(usize::from(a), Value::Int(i.wrapping_neg())),
4867 Value::Num(f) => setr!(usize::from(a), Value::Num(-f)),
4868 _ => match ta!(call!(self.unary(Tm::Unm, x, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4869 Some(v) => setr!(a, v),
4870 None => reload!(),
4871 },
4872 }
4873 }
4874 Instr::BNot { a, b } => {
4875 let x = reg!(usize::from(b));
4876 match x {
4877 Value::Int(i) => setr!(usize::from(a), Value::Int(!i)),
4878 _ => match ta!(call!(self.unary(Tm::BNot, x, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4879 Some(v) => setr!(a, v),
4880 None => reload!(),
4881 },
4882 }
4883 }
4884 Instr::Not { a, b } => setr!(usize::from(a), Value::Bool(!reg!(usize::from(b)).truthy())),
4885 Instr::Len { a, b } => {
4886 let x = reg!(usize::from(b));
4887 match x {
4888 Value::Str(s) => {
4889 let n = self.heap.str_bytes(s).len() as i64;
4890 setr!(a, Value::Int(n));
4891 }
4892 Value::Table(tr) if self.heap.tables.get(tr.idx).is_some_and(|t| t.meta.is_none()) => {
4893 let n = self.raw_len(tr);
4894 setr!(a, Value::Int(n));
4895 }
4896 _ => match ta!(call!(self.len(x, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4897 Some(v) => setr!(a, v),
4898 None => reload!(),
4899 },
4900 }
4901 }
4902 Instr::Concat { a, n } => {
4903 if self.heap.gc_due() && !std::mem::take(&mut self.due_skip) {
4904 gc_step_at!(true);
4905 }
4906 let first = base + usize::from(a);
4907 let done = match call!(self.concat(first, usize::from(n))) {
4908 Ok(d) => d,
4909 Err(e) => {
4910 let e = match e.into_kind() {
4912 ErrorKind::Type { op, ty, operand } => {
4913 let r = a.saturating_add(u16::from(operand));
4914 self.annotate(ErrorKind::Type { op, ty, operand: 0 }.into(), pidx, pc - 1, &[O::Reg(r)])
4915 }
4916 other => other.into(),
4917 };
4918 save!();
4919 return Err(e);
4920 }
4921 };
4922 if !done {
4923 reload!();
4924 }
4925 }
4926 Instr::ToStr { a, b } => {
4927 let x = reg!(usize::from(b));
4928 if matches!(x, Value::Str(_)) {
4929 setr!(usize::from(a), x);
4930 } else {
4931 let s = t!(call!(self.tostring(x)));
4932 setr!(a, s);
4933 }
4934 }
4935 Instr::Jmp { off, close } => {
4936 pc = (pc as i64 + i64::from(off)) as usize;
4937 if close > 0 && !t!(call!(self.close_async(base + usize::from(close) - 1, AfterClose::Nothing, 0))) {
4938 reload!();
4939 }
4940 }
4941 Instr::AddI { a, b, i, sub } => {
4942 let x = reg!(usize::from(b));
4944 match crate::fast::arith(ArithOp::Add, x, Value::Int(i64::from(i))) {
4945 Some(v) => setr!(a, v),
4946 None => {
4947 let (op, y) = if sub { (ArithOp::Sub, -i64::from(i)) } else { (ArithOp::Add, i64::from(i)) };
4948 match ta!(call!(self.arith(op, x, Value::Int(y), Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4949 Some(v) => setr!(a, v),
4950 None => reload!(),
4951 }
4952 }
4953 }
4954 }
4955 Instr::Pow { a, b, c } => arith_rr!(Pow, a, b, c),
4956 Instr::PowK { a, b, k } => arith_rk!(Pow, a, b, k),
4957 Instr::BAnd { a, b, c } => arith_rr!(BAnd, a, b, c),
4958 Instr::BAndK { a, b, k } => arith_rk!(BAnd, a, b, k),
4959 Instr::BOr { a, b, c } => arith_rr!(BOr, a, b, c),
4960 Instr::BOrK { a, b, k } => arith_rk!(BOr, a, b, k),
4961 Instr::BXor { a, b, c } => arith_rr!(BXor, a, b, c),
4962 Instr::BXorK { a, b, k } => arith_rk!(BXor, a, b, k),
4963 Instr::Shl { a, b, c } => arith_rr!(Shl, a, b, c),
4964 Instr::ShlK { a, b, k } => arith_rk!(Shl, a, b, k),
4965 Instr::Shr { a, b, c } => arith_rr!(Shr, a, b, c),
4966 Instr::ShrK { a, b, k } => arith_rk!(Shr, a, b, k),
4967 Instr::EqK { a, k, eq } => {
4968 let (x, y) = (reg!(usize::from(a)), kv!(k));
4969 let res = x.raw_eq(y)
4970 || match (x, y) {
4971 (Value::Str(sa), Value::Str(sb)) => t!(call!(self.str_eq(sa, sb))),
4972 _ => false,
4973 };
4974 if res != eq {
4975 pc += 1;
4976 }
4977 }
4978 Instr::EqI { a, i, eq } => {
4979 if reg!(usize::from(a)).raw_eq(Value::Int(i64::from(i))) != eq {
4980 pc += 1;
4981 }
4982 }
4983 Instr::LtI { a, i, k } | Instr::LeI { a, i, k } | Instr::GtI { a, i, k } | Instr::GeI { a, i, k } => {
4984 let (r, n) = (reg!(usize::from(a)), Value::Int(i64::from(i)));
4986 let (tm, x, y, le) = match ins {
4987 Instr::LtI { .. } => (Tm::Lt, r, n, false),
4988 Instr::LeI { .. } => (Tm::Le, r, n, true),
4989 Instr::GtI { .. } => (Tm::Lt, n, r, false),
4990 _ => (Tm::Le, n, r, true),
4991 };
4992 let res = match crate::fast::less(x, y, le) {
4993 Some(r) => r,
4994 None => match t!(call!(self.order_slow(tm, x, y, Cont::Cond { k }))) {
4995 Some(r) => r,
4996 None => reload!(),
4997 },
4998 };
4999 if res != k {
5000 pc += 1;
5001 }
5002 }
5003 Instr::Eq { b, c, k } => {
5004 let x = rk!(b);
5005 let y = rk!(c);
5006 let res = if x.raw_eq(y) {
5007 true
5008 } else {
5009 match (x, y) {
5010 (Value::Str(sa), Value::Str(sb)) => t!(call!(self.str_eq(sa, sb))),
5011 (Value::Table(_), Value::Table(_)) | (Value::UserData(_), Value::UserData(_)) => {
5012 match t!(call!(self.eq_slow(x, y, Cont::Cond { k }))) {
5013 Some(r) => r,
5014 None => reload!(),
5015 }
5016 }
5017 _ => false,
5018 }
5019 };
5020 if res != k {
5021 pc += 1;
5022 }
5023 }
5024 Instr::Lt { b, c, k } => {
5025 let x = rk!(b);
5026 let y = rk!(c);
5027 let res = match (x, y) {
5028 _ if let Some(r) = crate::fast::less(x, y, false) => r,
5029 (Value::Str(s1), Value::Str(s2)) => {
5030 let n = self.heap.str_bytes(s1).len().min(self.heap.str_bytes(s2).len());
5031 t!(call!(self.charge_bytes(n)));
5032 self.heap.str_bytes(s1) < self.heap.str_bytes(s2)
5033 }
5034 _ => match t!(call!(self.order_slow(Tm::Lt, x, y, Cont::Cond { k }))) {
5035 Some(r) => r,
5036 None => reload!(),
5037 },
5038 };
5039 if res != k {
5040 pc += 1;
5041 }
5042 }
5043 Instr::Le { b, c, k } => {
5044 let x = rk!(b);
5045 let y = rk!(c);
5046 let res = match (x, y) {
5047 _ if let Some(r) = crate::fast::less(x, y, true) => r,
5048 (Value::Str(s1), Value::Str(s2)) => {
5049 let n = self.heap.str_bytes(s1).len().min(self.heap.str_bytes(s2).len());
5050 t!(call!(self.charge_bytes(n)));
5051 self.heap.str_bytes(s1) <= self.heap.str_bytes(s2)
5052 }
5053 _ => match t!(call!(self.order_slow(Tm::Le, x, y, Cont::Cond { k }))) {
5054 Some(r) => r,
5055 None => reload!(),
5056 },
5057 };
5058 if res != k {
5059 pc += 1;
5060 }
5061 }
5062 Instr::Test { a, k } => {
5063 if reg!(usize::from(a)).truthy() != k {
5064 pc += 1;
5065 }
5066 }
5067 Instr::TestSet { a, b, k } => {
5068 let v = reg!(usize::from(b));
5069 if v.truthy() == k {
5070 setr!(usize::from(a), v);
5071 } else {
5072 pc += 1;
5073 }
5074 }
5075 Instr::Call { a, b, c } => {
5076 let func = base + usize::from(a);
5077 let nargs = if b == MULTI { self.top.saturating_sub(func + 1) } else { usize::from(b) };
5078 let nres = if c == MULTI { -1 } else { i32::from(c) };
5079 let called = match reg!(usize::from(a)) {
5082 Value::Func(f) => match self.heap.funcs.get(f.idx) {
5083 Some(Func::Lua { proto, .. }) => {
5084 let proto = *proto;
5085 ta!(call!(self.push_frame(f, proto, func, nargs, nres, FrameKind::Normal, true)), [O::Reg(a)]);
5086 continue 'reload;
5087 }
5088 Some(Func::Native { .. }) if Some(f) == self.names.yield_fn && self.limit_hit.is_none() => {
5089 call!(self.yield_from_lua(func, nargs, nres))
5090 }
5091 Some(Func::Native { f: nf, name, .. })
5097 if Some(f) == self.names.collect_fn && self.limit_hit.is_none() && self.gc_call_before.is_none() && self.basic_step_call(func, nargs) =>
5098 {
5099 let (nf, name) = (*nf, *name);
5100 if let Err(e) = call!(self.collect_step()) {
5101 save!();
5102 if e.is_pending() {
5103 if let Some(fr) = self.cur.frames.last_mut() {
5104 fr.pc = pc - 1 - usize::from(base != frame_base);
5105 }
5106 self.fuel += 1;
5107 self.rewound = true;
5108 } else {
5109 self.gc_call_before = None;
5110 }
5111 return Err(e);
5112 }
5113 call!(self.call_native(func, nargs, nres, FrameKind::Normal, true, name, nf))
5114 }
5115 Some(Func::Native { f: nf, name, in_place, .. }) => {
5116 let (nf, name, op) = (*nf, *name, *in_place);
5117 call!(match if op > 0 { self.call_in_place(op, func, nargs, nres) } else { None } {
5118 Some(r) => r,
5119 None => self.call_native(func, nargs, nres, FrameKind::Normal, true, name, nf),
5120 })
5121 }
5122 _ => call!(self.precall(func, nargs, nres, FrameKind::Normal, true)),
5123 },
5124 _ => call!(self.precall(func, nargs, nres, FrameKind::Normal, true)),
5125 };
5126 match ta!(called, [O::Reg(a)]) {
5127 Called::Done => {
5128 if self.heap.gc_due() {
5129 gc_step_at!(false);
5130 }
5131 }
5132 Called::Lua | Called::Switched => continue 'reload,
5133 }
5134 }
5135 Instr::TailCall { a, b } => {
5136 let func = base + usize::from(a);
5137 let mut nargs = if b == MULTI { self.top.saturating_sub(func + 1) } else { usize::from(b) };
5138 let mut tries = 0;
5141 while !matches!(self.st(func), Value::Func(_)) && tries < MAX_TAG_LOOP {
5142 let fv = self.st(func);
5143 let mm = self.tm(fv, Tm::Call);
5144 if mm.is_nil() {
5145 break;
5146 }
5147 t!(call!(self.charge(1 + nargs as u64 / 8)));
5148 t!(call!(self.ensure_stack(func + nargs + 2 + EXTRA_STACK)));
5149 self.cur.stack.copy_within(func..func + 1 + nargs, func + 1);
5150 self.set_st(func, mm);
5151 nargs += 1;
5152 tries += 1;
5153 }
5154 let is_lua = matches!(self.st(func), Value::Func(f)
5155 if matches!(self.heap.funcs.get(f.idx), Some(Func::Lua { .. })));
5156 if is_lua {
5157 tpop!(self.tail_call(func, nargs));
5158 continue 'reload;
5159 }
5160 match ta!(call!(self.precall(func, nargs, -1, FrameKind::Normal, true)), [O::Reg(a)]) {
5161 Called::Done => {}
5162 Called::Lua | Called::Switched => continue 'reload,
5163 }
5164 }
5165 Instr::Return { .. } | Instr::Return0 | Instr::Return1 { .. } => {
5166 let (a, b) = match ins {
5167 Instr::Return { a, b } => (a, b),
5168 Instr::Return1 { a } => (a, 1),
5169 _ => (0, 0),
5170 };
5171 let src = base + usize::from(a);
5172 let n = if b == MULTI { self.top.saturating_sub(src) } else { usize::from(b) };
5173 if n <= 16
5177 && let Some(f) = self.cur.frames.last()
5178 && (f.from_lua || self.cur.frames.len() > 1)
5179 && matches!(f.kind, FrameKind::Normal)
5180 && !self.cur.open_upvals.last().is_some_and(|(i, _)| *i >= base)
5181 && !self.cur.tbc.last().is_some_and(|i| *i >= base)
5182 {
5183 let (func, wanted) = (f.func, f.nresults);
5184 let want = if wanted < 0 { n } else { wanted as usize };
5185 if want <= 16 && func + want.max(n) < self.cur.stack.len() {
5187 self.cur.stack.copy_within(src..src + n, func);
5188 if let Some(rest) = self.cur.stack.get_mut(func + n..func + want) {
5189 rest.fill(Value::Nil);
5190 }
5191 if wanted < 0 {
5192 self.top = func + n;
5193 }
5194 self.cur.frames.pop();
5195 self.fuel = fuel;
5196 continue 'reload;
5197 }
5198 }
5199 tpop!(self.do_return(src, n));
5200 continue 'reload;
5201 }
5202 Instr::ForPrep { a, off } => {
5203 if t!(call!(self.for_prep(base + usize::from(a)))) {
5204 pc = (pc as i64 + i64::from(off)) as usize;
5205 }
5206 }
5207 Instr::ForLoop { a, off } => {
5208 let ra = usize::from(a);
5209 match (reg!(ra), reg!(ra + 1), reg!(ra + 2)) {
5210 (Value::Int(idx), Value::Int(count), Value::Int(step)) => {
5211 if count as u64 > 0 {
5212 let i = idx.wrapping_add(step);
5213 setr!(ra + 1, Value::Int((count as u64 - 1) as i64));
5214 setr!(ra, Value::Int(i));
5215 setr!(ra + 3, Value::Int(i));
5216 pc = (pc as i64 + i64::from(off)) as usize;
5217 }
5218 }
5219 (Value::Num(idx), Value::Num(limit), Value::Num(step)) => {
5220 let i = idx + step;
5221 if if step > 0.0 { i <= limit } else { limit <= i } {
5222 setr!(ra, Value::Num(i));
5223 setr!(ra + 3, Value::Num(i));
5224 pc = (pc as i64 + i64::from(off)) as usize;
5225 }
5226 }
5227 _ => {}
5228 }
5229 }
5230 Instr::TForPrep { a, off } => {
5231 let slot = base + usize::from(a) + 3;
5232 let v = self.st(slot);
5233 if v.truthy() {
5234 if self.tm(v, Tm::Close).is_nil() {
5235 save!();
5236 return Err(LuaError::msg("variable '(for state)' got a non-closable value"));
5237 }
5238 self.cur.tbc.push(slot);
5239 }
5240 pc = (pc as i64 + i64::from(off)) as usize;
5241 }
5242 Instr::TForCall { a, c } => {
5243 let ra = usize::from(a);
5244 setr!(ra + 4, reg!(ra));
5245 setr!(ra + 5, reg!(ra + 1));
5246 setr!(ra + 6, reg!(ra + 2));
5247 let func = base + ra + 4;
5248 if let Value::Func(f) = reg!(ra + 4)
5249 && let Some(Func::Lua { proto, .. }) = self.heap.funcs.get(f.idx)
5250 {
5251 let proto = *proto;
5252 ta!(call!(self.push_frame(f, proto, func, 2, tfor_wanted(c), FrameKind::Normal, true)), [O::Reg(a)]);
5253 continue 'reload;
5254 }
5255 let r = call!(self.precall(func, 2, tfor_wanted(c), FrameKind::Normal, true)).map_err(|e| match e.into_kind() {
5257 ErrorKind::Call { ty } => LuaError::Msg(format!("attempt to call a {ty} value (for iterator 'for iterator')")),
5258 e => e.into(),
5259 });
5260 match ta!(r, [O::Reg(a)]) {
5261 Called::Done => {}
5262 Called::Lua | Called::Switched => continue 'reload,
5263 }
5264 }
5265 Instr::TForLoop { a, off } => {
5266 let ra = usize::from(a);
5267 let v = reg!(ra + 4);
5268 if !v.is_nil() {
5269 setr!(ra + 2, v);
5270 pc = (pc as i64 + i64::from(off)) as usize;
5271 }
5272 }
5273 Instr::SetList { a, n, off } => {
5274 let ra = base + usize::from(a);
5275 let count = if n == crate::bytecode::SETLIST_MULTI { self.top.saturating_sub(ra + 1) } else { usize::from(n) };
5276 if let Value::Table(tr) = self.st(ra) {
5277 save!();
5278 let part = tr.idx == self.heap.part;
5281 if part {
5282 for j in 0..count {
5283 self.heap.part_writing(tr.idx, Value::Int((off as usize + j + 1) as i64));
5284 }
5285 }
5286 let set = |heap: &mut Heap, stack: &[Value]| {
5289 let vals = stack.get(ra + 1..ra + 1 + count).unwrap_or_default();
5290 match heap.tables.get_mut(tr.idx) {
5291 Some(tab) => tab.set_list(off as usize, vals, &mut heap.mem),
5292 None => Ok(()),
5293 }
5294 };
5295 self.heap.mem.fuel = self.call_fuel();
5297 let mut res = set(&mut self.heap, &self.cur.stack);
5298 if matches!(res, Err(SetError::Memory)) {
5299 t!(call!(self.emergency_gc()));
5300 res = set(&mut self.heap, &self.cur.stack);
5301 }
5302 if part {
5303 for j in 0..count {
5304 let v = self.cur.stack.get(ra + 1 + j).copied().unwrap_or_default();
5305 self.heap.part_written(tr.idx, Value::Int((off as usize + j + 1) as i64), if res.is_ok() { v } else { Value::Nil });
5306 }
5307 }
5308 if let Err(e) = res {
5309 save!();
5310 let k = match e {
5313 SetError::Stopped(k) => {
5314 let heap = &mut self.heap;
5315 let units = heap.tables.get_mut(tr.idx).map_or(0, |tab| tab.take_units(&heap.mem));
5316 let _ = self.charge(units);
5317 k
5318 }
5319 SetError::Fuel => {
5320 (self.fuel, self.reserve) = (-1, 0);
5321 LimitKind::Fuel
5322 }
5323 _ => return Err(self.memory_error(false)),
5324 };
5325 return Err(LuaError::Limit(k));
5326 }
5327 self.heap.barrier_table(tr);
5328 let heap = &mut self.heap;
5329 let resized = heap.tables.get_mut(tr.idx).map_or(0, |tab| tab.take_resized(&heap.mem));
5330 if resized >= 16 {
5331 t!(call!(self.charge(resized as u64 / 16)));
5332 }
5333 }
5334 }
5335 Instr::Closure { a, p } => {
5336 if self.heap.gc_due() && !std::mem::take(&mut self.due_skip) {
5337 gc_step_at!(true);
5338 }
5339 let f = t!(call!(self.make_closure(pidx, closure, frame_base, p as usize)));
5341 setr!(a, f);
5342 }
5343 Instr::VarArg { a, n } => {
5344 let (vstart, vcount) = self.cur.frames.last().map_or((0, 0), |f| (f.vstart, f.vcount));
5345 let ra = base + usize::from(a);
5346 if n == MULTI {
5347 t!(call!(self.charge(vcount as u64 / 8)));
5348 t!(call!(self.ensure_stack(ra + vcount + EXTRA_STACK)));
5349 self.cur.stack.copy_within(vstart..vstart + vcount, ra);
5350 self.top = ra + vcount;
5351 } else {
5352 t!(call!(self.charge(list_fuel(usize::from(n)))));
5354 for i in 0..usize::from(n) {
5355 let v = if i < vcount { self.st(vstart + i) } else { Value::Nil };
5356 self.set_st(ra + i, v);
5357 }
5358 }
5359 }
5360 Instr::Close { a } => {
5361 if !t!(call!(self.close_async(base + usize::from(a), AfterClose::Nothing, 0))) {
5362 reload!();
5363 }
5364 }
5365 Instr::Tbc { a } => {
5366 let v = reg!(usize::from(a));
5367 if v.truthy() {
5368 if self.tm(v, Tm::Close).is_nil() {
5369 save!();
5370 let name = self
5371 .proto(pidx)
5372 .and_then(|p| crate::debug::local_name(p, pc - 1, a))
5373 .unwrap_or_else(|| "?".into());
5374 return Err(LuaError::msg(format!("variable '{name}' got a non-closable value")));
5375 }
5376 self.cur.tbc.push(base + usize::from(a));
5377 }
5378 }
5379 }
5380 }
5381 }
5382 }
5383
5384 #[inline]
5387 fn get_field_cached(&mut self, t: TableRef, key: Value, pidx: u32, pc: usize) -> Option<Value> {
5388 let tab = self.heap.tables.get(t.idx)?;
5389 let hint = self.heap.protos.at(pidx as usize).and_then(|p| p.hints.get(pc)).map_or(0, std::cell::Cell::get);
5390 let (v, slot) = tab.get_hinted(key, hint);
5391 if let Some(slot) = slot
5392 && slot != hint
5393 && let Some(h) = self.heap.protos.at(pidx as usize).and_then(|p| p.hints.get(pc))
5394 {
5395 h.set(slot);
5396 }
5397 if !v.is_nil() || tab.meta.is_none() { Some(v) } else { None }
5398 }
5399
5400
5401
5402 #[inline]
5405 fn set_field_fast(&mut self, t: TableRef, key: Value, val: Value) -> Result<bool, LuaError> {
5406 let Some(tab) = self.heap.tables.get(t.idx) else { return Ok(true) };
5407 if tab.meta.is_some() && self.get_in_settled(t.idx, key)?.is_nil() {
5408 return Ok(false);
5409 }
5410 self.raw_set(t, key, val)?;
5411 Ok(true)
5412 }
5413
5414 fn tail_call(&mut self, func: usize, nargs: usize) -> Result<(), LuaError> {
5415 let Some(frame) = self.cur.frames.last() else { return Ok(()) };
5416 let (fbase, ffunc, nres, kind, from_lua, handler) =
5417 (frame.base, frame.func, frame.nresults, frame.kind, frame.from_lua, frame.handler);
5418 self.close_upvals(fbase);
5419 if self.cur.tbc.last().is_some_and(|&s| s >= fbase) {
5420 self.close_level(fbase)?;
5421 }
5422 if nargs > 16 {
5423 self.charge(nargs as u64 / 8)?;
5424 }
5425 self.cur.stack.copy_within(func..func + 1 + nargs, ffunc);
5426 self.cur.frames.pop();
5427 let unrolled = self.cur.unrolled;
5429 let depth = self.cur.frames.len();
5430 let r = self.precall(ffunc, nargs, nres, kind, from_lua);
5431 if matches!(r, Ok(Called::Lua))
5432 && self.cur.frames.len() == depth + 1
5433 && let Some(f) = self.cur.frames.get_mut(depth)
5434 {
5435 f.tail = true;
5436 }
5437 if self.cur.frames.len() <= unrolled {
5438 self.cur.unrolled = unrolled;
5439 }
5440 if let Some(f) = self.cur.frames.last_mut()
5441 && handler.is_some()
5442 && let (FrameKind::Protected { dest, .. }, FrameKind::Protected { dest: was, .. }) = (f.kind, kind)
5443 && dest == was
5444 {
5445 f.handler = handler;
5446 }
5447 r.map(|_| ())
5448 }
5449
5450 fn make_closure(&mut self, parent: u32, closure: FuncRef, base: usize, p: usize) -> Result<Value, LuaError> {
5451 loop {
5452 match new_closure(&mut self.heap, &mut self.cur.open_upvals, self.cur_ref, parent, closure, base, p) {
5453 Ok((v, extra)) => {
5454 if extra > 0 {
5456 self.charge(extra)?;
5457 }
5458 return Ok(v);
5459 }
5460 Err(None) => return Err(LuaError::msg("internal: no such prototype")),
5461 Err(Some(size)) => {
5463 self.charge_mem(size)?;
5464 self.heap.mem.release(size);
5465 }
5466 }
5467 }
5468 }
5469
5470 fn for_prep(&mut self, ra: usize) -> Result<bool, LuaError> {
5472 let (init, limit, step) = (self.st(ra), self.st(ra + 1), self.st(ra + 2));
5473 if let (Value::Int(i), Value::Int(s)) = (init, step) {
5474 if s == 0 {
5475 return Err(LuaError::msg("'for' step is zero"));
5476 }
5477 let lim = match limit {
5478 Value::Int(l) => l,
5479 other => match self.tonumber_charged(other)? {
5481 Some(Value::Int(l)) => l,
5482 Some(Value::Num(f)) => {
5483 match if s < 0 { number::float_ceil_to_int(f) } else { number::float_floor_to_int(f) } {
5484 Some(l) => l,
5485 None => {
5486 if (f > 0.0) == (s < 0) {
5487 return Ok(true);
5488 }
5489 if f > 0.0 { i64::MAX } else { i64::MIN }
5490 }
5491 }
5492 }
5493 _ => {
5494 return Err(LuaError::msg(format!(
5495 "bad 'for' limit (number expected, got {})",
5496 self.obj_type_name(other)
5497 )));
5498 }
5499 },
5500 };
5501 if if s > 0 { i > lim } else { i < lim } {
5502 return Ok(true);
5503 }
5504 let count = if s > 0 {
5505 (lim as u64).wrapping_sub(i as u64) / (s as u64)
5506 } else {
5507 let s1 = (s.wrapping_add(1)).wrapping_neg() as u64 + 1;
5508 (i as u64).wrapping_sub(lim as u64) / s1
5509 };
5510 self.set_st(ra + 1, Value::Int(count as i64));
5511 self.set_st(ra + 3, Value::Int(i));
5512 return Ok(false);
5513 }
5514 let f = |v: Value, what: &str, s: &mut Self| -> Result<f64, LuaError> {
5515 match s.tonumber_charged(v)?.and_then(Value::as_num) {
5516 Some(f) => Ok(f),
5517 None => Err(LuaError::msg(format!("bad 'for' {what} (number expected, got {})", s.obj_type_name(v)))),
5518 }
5519 };
5520 let l = f(limit, "limit", self)?;
5521 let st = f(step, "step", self)?;
5522 let i = f(init, "initial value", self)?;
5523 if st == 0.0 {
5524 return Err(LuaError::msg("'for' step is zero"));
5525 }
5526 if if st > 0.0 { l < i } else { i < l } {
5527 return Ok(true);
5528 }
5529 self.set_st(ra, Value::Num(i));
5530 self.set_st(ra + 1, Value::Num(l));
5531 self.set_st(ra + 2, Value::Num(st));
5532 self.set_st(ra + 3, Value::Num(i));
5533 Ok(false)
5534 }
5535
5536 #[inline]
5540 fn place_call(&mut self, pos: usize, f: Value, args: &[Value]) -> Result<(), LuaError> {
5541 self.ensure_stack(pos + args.len() + 1 + EXTRA_STACK)?;
5542 self.set_st(pos, f);
5543 for (i, a) in args.iter().enumerate() {
5544 self.set_st(pos + 1 + i, *a);
5545 }
5546 Ok(())
5547 }
5548
5549 #[inline]
5551 fn precall_event(
5552 &mut self,
5553 ev: Option<&'static str>,
5554 pos: usize,
5555 nargs: usize,
5556 nres: i32,
5557 kind: FrameKind,
5558 ) -> Result<Called, LuaError> {
5559 self.pending_event = ev;
5560 let r = self.precall(pos, nargs, nres, kind, false);
5561 self.pending_event = None;
5562 r
5563 }
5564
5565 fn call_meta(&mut self, ev: Tm, f: Value, args: &[Value], cont: Cont) -> Result<Option<Value>, LuaError> {
5569 if !matches!(f, Value::Func(_)) && self.tm(f, Tm::Call).is_nil() {
5570 let name = TM_NAMES.get(ev as usize).map_or("?", |n| n.get(2..).unwrap_or(n));
5571 return Err(LuaError::msg(format!("attempt to call a {} value (metamethod '{name}')", self.obj_type_name(f))));
5572 }
5573 let pos = self.call_top();
5574 self.place_call(pos, f, args)?;
5575 let saved_ntop = self.ntop;
5576 self.ntop = self.ntop.max(pos + 1 + args.len());
5577 let r = self.precall_event(TM_NAMES.get(ev as usize).and_then(|n| n.get(2..)), pos, args.len(), 1, FrameKind::Cont(cont));
5578 self.ntop = saved_ntop;
5579 match r? {
5580 Called::Lua | Called::Switched => Ok(None),
5583 Called::Done => Ok(Some(self.st(pos))),
5584 }
5585 }
5586
5587 fn index_error(&self, t: Value, loop_n: usize) -> LuaError {
5589 let ty = self.obj_type_name(t);
5590 if loop_n == 0 {
5591 ErrorKind::Type { op: "index", ty, operand: 0 }.into()
5592 } else {
5593 LuaError::msg(format!("attempt to index a {ty} value"))
5594 }
5595 }
5596
5597 pub(crate) fn index(&mut self, t: Value, key: Value, cont: Cont) -> Result<Option<Value>, LuaError> {
5599 let mut t = t;
5600 for loop_n in 0..MAX_TAG_LOOP {
5601 let mm = if let Value::Table(tr) = t {
5602 if self.heap.tables.get(tr.idx).is_none() {
5603 return Ok(Some(Value::Nil));
5604 }
5605 let v = self.get_in_settled(tr.idx, key)?;
5606 let Some(tab) = self.heap.tables.get(tr.idx) else { return Ok(Some(Value::Nil)) };
5607 if !v.is_nil() {
5608 return Ok(Some(v));
5609 }
5610 let Some(m) = tab.meta else { return Ok(Some(Value::Nil)) };
5611 let mm = self.tm_in(m, Tm::Index);
5612 if mm.is_nil() {
5613 return Ok(Some(Value::Nil));
5614 }
5615 mm
5616 } else {
5617 let mm = self.tm(t, Tm::Index);
5618 if mm.is_nil() {
5619 return Err(self.index_error(t, loop_n));
5620 }
5621 mm
5622 };
5623 if let Value::Func(_) = mm {
5624 return self.call_meta(Tm::Index, mm, &[t, key], cont);
5625 }
5626 self.charge(link_cost(loop_n) + crate::table::take_probes())?;
5628 t = mm;
5629 }
5630 Err(LuaError::msg("'__index' chain too long; possible loop"))
5631 }
5632
5633 pub(crate) fn set_index(&mut self, t: Value, key: Value, val: Value) -> Result<bool, LuaError> {
5636 let mut t = t;
5637 for loop_n in 0..MAX_TAG_LOOP {
5638 let mm = if let Value::Table(tr) = t {
5639 let Some(tab) = self.heap.tables.get(tr.idx) else { return Ok(true) };
5640 let mm = match tab.meta {
5641 None => Value::Nil,
5642 Some(m) => {
5643 if !self.get_in_settled(tr.idx, key)?.is_nil() {
5644 Value::Nil
5645 } else {
5646 self.tm_in(m, Tm::NewIndex)
5647 }
5648 }
5649 };
5650 if mm.is_nil() {
5651 self.raw_set(tr, key, val)?;
5652 return Ok(true);
5653 }
5654 mm
5655 } else {
5656 let mm = self.tm(t, Tm::NewIndex);
5657 if mm.is_nil() {
5658 return Err(self.index_error(t, loop_n));
5659 }
5660 mm
5661 };
5662 if let Value::Func(_) = mm {
5663 return Ok(self.call_meta(Tm::NewIndex, mm, &[t, key, val], Cont::Discard)?.is_some());
5664 }
5665 self.charge(link_cost(loop_n) + crate::table::take_probes())?;
5667 t = mm;
5668 }
5669 Err(LuaError::msg("'__newindex' chain too long; possible loop"))
5670 }
5671
5672 pub(crate) fn index_nested(&mut self, t: Value, key: Value) -> Result<Value, LuaError> {
5674 self.settle_key(key)?;
5675 let mut t = t;
5676 for link_n in 0..MAX_TAG_LOOP {
5677 let mm = if let Value::Table(tr) = t {
5678 let v = self.raw_get(tr, key);
5679 if !v.is_nil() {
5680 self.hold(v);
5682 return Ok(v);
5683 }
5684 let mm = self.tm(t, Tm::Index);
5685 if mm.is_nil() {
5686 return Ok(Value::Nil);
5687 }
5688 mm
5689 } else {
5690 let mm = self.tm(t, Tm::Index);
5691 if mm.is_nil() {
5692 return Err(LuaError::Plain(format!("attempt to index a {} value", self.obj_type_name(t))));
5693 }
5694 mm
5695 };
5696 if let Value::Func(_) = mm {
5697 return self.call_nested1(mm, &[t, key]);
5698 }
5699 self.charge(link_cost(link_n) + crate::table::take_probes())?;
5701 t = mm;
5702 }
5703 Err(LuaError::Plain("'__index' chain too long; possible loop".into()))
5704 }
5705
5706 pub(crate) fn set_index_nested(&mut self, t: Value, key: Value, val: Value) -> Result<(), LuaError> {
5708 self.settle_key(key)?;
5709 let mut t = t;
5710 for link_n in 0..MAX_TAG_LOOP {
5711 let mm = match t {
5712 Value::Table(tr) => {
5713 let has = !self.raw_get(tr, key).is_nil();
5714 let mm = match self.metatable(t) {
5715 Some(m) if !has => self.tm_in(m, Tm::NewIndex),
5716 _ => Value::Nil,
5717 };
5718 if mm.is_nil() {
5719 return self.raw_set(tr, key, val);
5720 }
5721 mm
5722 }
5723 _ => {
5724 let mm = self.tm(t, Tm::NewIndex);
5725 if mm.is_nil() {
5726 return Err(LuaError::Plain(format!("attempt to index a {} value", self.obj_type_name(t))));
5727 }
5728 mm
5729 }
5730 };
5731 if let Value::Func(_) = mm {
5732 self.call_nested(mm, &[t, key, val])?;
5733 return Ok(());
5734 }
5735 self.charge(link_cost(link_n) + crate::table::take_probes())?;
5737 t = mm;
5738 }
5739 Err(LuaError::Plain("'__newindex' chain too long; possible loop".into()))
5740 }
5741
5742 pub(crate) fn tonumber(&self, v: Value) -> Option<Value> {
5744 match v {
5745 Value::Int(_) | Value::Num(_) => Some(v),
5746 Value::Str(s) => number::str_to_number(self.bytes(s)),
5747 _ => None,
5748 }
5749 }
5750
5751 pub(crate) fn tonumber_charged(&mut self, v: Value) -> Result<Option<Value>, LuaError> {
5755 if let Value::Str(s) = v {
5756 let n = self.bytes(s).len();
5757 if n >= 16 {
5758 self.charge(n as u64 / 16)?;
5759 }
5760 }
5761 Ok(self.tonumber(v))
5762 }
5763
5764 #[inline]
5766 pub(crate) fn charge_bytes(&mut self, n: usize) -> Result<(), LuaError> {
5767 self.charge(crate::heap::bytes_fuel(n))
5768 }
5769
5770 pub(crate) fn tointeger(&self, v: Value) -> Option<i64> {
5772 match v {
5773 Value::Int(i) => Some(i),
5774 Value::Num(f) => number::float_to_int(f),
5775 Value::Str(_) => self.tonumber(v).and_then(Value::as_int),
5776 _ => None,
5777 }
5778 }
5779
5780 pub(crate) fn arith(&mut self, op: ArithOp, x: Value, y: Value, cont: Cont) -> Result<Option<Value>, LuaError> {
5782 if !is_bitwise(op) && self.string_meta.is_some() && (matches!(x, Value::Str(_)) || matches!(y, Value::Str(_))) {
5785 let ev = arith_tm(op);
5786 let mm = self.tm2(x, y, ev);
5787 if mm.is_nil() {
5788 let culprit = if matches!(x, Value::Int(_) | Value::Num(_)) { 1 } else { 0 };
5789 let ty = self.obj_type_name(if culprit == 0 { x } else { y });
5790 return Err(ErrorKind::Type { op: "perform arithmetic on", ty, operand: culprit }.into());
5791 }
5792 if !self.is_string_builtin(mm) {
5793 return self.call_meta(ev, mm, &[x, y], cont);
5794 }
5795 return self.string_arith_now(op, x, y).map(Some);
5796 }
5797 if is_bitwise(op) {
5798 let ints = (int_of(x), int_of(y));
5799 if let (Some(i), Some(j)) = ints {
5800 return Ok(Some(Value::Int(int_arith(op, i, j)?)));
5801 }
5802 } else if let (Some(a), Some(b)) = (self.tonumber_charged(x)?, self.tonumber_charged(y)?) {
5803 let r = arith_values(op, a, b);
5804 if self.string_arith(x) || self.string_arith(y) {
5807 return r.map(Some).map_err(LuaError::plain);
5808 }
5809 return r.map(Some);
5810 }
5811 let mut mm = self.tm(x, arith_tm(op));
5812 if mm.is_nil() && !is_bitwise(op) && self.string_arith(x) {
5813 return self.string_arith_fail(op, x, y).map(Some);
5814 }
5815 if mm.is_nil() {
5816 mm = self.tm(y, arith_tm(op));
5817 if mm.is_nil() && !is_bitwise(op) && self.string_arith(y) {
5818 return self.string_arith_fail(op, x, y).map(Some);
5819 }
5820 }
5821 if !mm.is_nil() {
5822 return self.call_meta(arith_tm(op), mm, &[x, y], cont);
5823 }
5824 if is_bitwise(op) {
5825 if matches!(x, Value::Int(_) | Value::Num(_)) && matches!(y, Value::Int(_) | Value::Num(_)) {
5826 return Err(ErrorKind::IntRepr { operand: if int_of(x).is_none() { 0 } else { 1 } }.into());
5827 }
5828 let culprit = if matches!(x, Value::Int(_) | Value::Num(_)) { 1 } else { 0 };
5829 let ty = self.obj_type_name(if culprit == 0 { x } else { y });
5830 return Err(ErrorKind::Type { op: "perform bitwise operation on", ty, operand: culprit }.into());
5831 }
5832 let culprit = if self.tonumber(x).is_some() { 1 } else { 0 };
5833 let ty = self.obj_type_name(if culprit == 0 { x } else { y });
5834 Err(ErrorKind::Type { op: "perform arithmetic on", ty, operand: culprit }.into())
5835 }
5836
5837 fn string_arith(&self, v: Value) -> bool {
5840 matches!(v, Value::Str(_)) && self.string_meta.is_some()
5841 }
5842
5843 fn is_string_builtin(&self, f: Value) -> bool {
5845 let Value::Func(r) = f else { return false };
5846 matches!(self.heap.funcs.get(r.idx), Some(Func::Native { name, .. }) if name.starts_with("string.__"))
5847 }
5848
5849 pub(crate) fn string_arith_now(&mut self, op: ArithOp, x: Value, y: Value) -> Result<Value, LuaError> {
5851 if let (Some(a), Some(b)) = (self.tonumber_charged(x)?, self.tonumber_charged(y)?) {
5852 return arith_values(op, a, b).map_err(LuaError::plain);
5853 }
5854 self.string_arith_fail(op, x, y)
5855 }
5856
5857 fn string_arith_fail(&mut self, op: ArithOp, x: Value, y: Value) -> Result<Value, LuaError> {
5863 let ev = arith_tm(op);
5864 let mm = if matches!(y, Value::Str(_)) { Value::Nil } else { self.tm(y, ev) };
5865 if mm.is_nil() {
5866 let name = TM_NAMES.get(ev as usize).map_or("?", |n| n.get(2..).unwrap_or(n));
5867 return Err(LuaError::msg(format!("attempt to {name} a '{}' with a '{}'", x.type_name(), y.type_name())));
5868 }
5869 self.call_nested1(mm, &[x, y])
5870 }
5871
5872 fn unary(&mut self, e: Tm, x: Value, cont: Cont) -> Result<Option<Value>, LuaError> {
5873 match e {
5874 Tm::Unm => {
5875 if let Some(n) = self.tonumber_charged(x)? {
5876 return Ok(Some(match n {
5877 Value::Int(i) => Value::Int(i.wrapping_neg()),
5878 Value::Num(f) => Value::Num(-f),
5879 o => o,
5880 }));
5881 }
5882 }
5883 _ => {
5884 if let Some(i) = int_of(x) {
5885 return Ok(Some(Value::Int(!i)));
5886 }
5887 }
5888 }
5889 let mm = self.tm(x, e);
5890 if e == Tm::Unm && self.string_arith(x) && self.is_string_builtin(mm) {
5891 return Err(LuaError::msg("attempt to unm a 'string' with a 'string'"));
5892 }
5893 if !mm.is_nil() {
5894 return self.call_meta(e, mm, &[x, x], cont);
5895 }
5896 if e == Tm::BNot {
5897 if let Value::Num(_) = x {
5898 return Err(ErrorKind::IntRepr { operand: 0 }.into());
5899 }
5900 return Err(ErrorKind::Type { op: "perform bitwise operation on", ty: self.obj_type_name(x), operand: 0 }.into());
5901 }
5902 Err(ErrorKind::Type { op: "perform arithmetic on", ty: self.obj_type_name(x), operand: 0 }.into())
5903 }
5904
5905 pub(crate) fn len(&mut self, x: Value, cont: Cont) -> Result<Option<Value>, LuaError> {
5907 if let Value::Str(s) = x {
5908 return Ok(Some(Value::Int(self.bytes(s).len() as i64)));
5909 }
5910 let mm = self.tm(x, Tm::Len);
5911 if !mm.is_nil() {
5912 return self.call_meta(Tm::Len, mm, &[x, x], cont);
5913 }
5914 if let Value::Table(t) = x {
5915 return Ok(Some(Value::Int(self.raw_len(t))));
5916 }
5917 Err(ErrorKind::Type { op: "get length of", ty: self.obj_type_name(x), operand: 0 }.into())
5918 }
5919
5920 pub(crate) fn len_nested(&mut self, x: Value) -> Result<Value, LuaError> {
5922 if let Value::Str(s) = x {
5923 return Ok(Value::Int(self.bytes(s).len() as i64));
5924 }
5925 let mm = self.tm(x, Tm::Len);
5926 if !mm.is_nil() {
5927 return self.call_nested1(mm, &[x, x]);
5928 }
5929 if let Value::Table(t) = x {
5930 return Ok(Value::Int(self.raw_len(t)));
5931 }
5932 Err(LuaError::Plain(format!("attempt to get length of a {} value", self.obj_type_name(x))))
5933 }
5934
5935 fn eq_slow(&mut self, x: Value, y: Value, cont: Cont) -> Result<Option<bool>, LuaError> {
5936 let mm = self.tm2(x, y, Tm::Eq);
5937 if mm.is_nil() {
5938 return Ok(Some(false));
5939 }
5940 Ok(self.call_meta(Tm::Eq, mm, &[x, y], cont)?.map(Value::truthy))
5941 }
5942
5943 pub(crate) fn str_eq(&mut self, a: StrRef, b: StrRef) -> Result<bool, LuaError> {
5945 if let Some(r) = self.heap.str_eq_quick(a, b) {
5946 return Ok(r);
5947 }
5948 let len = self.bytes(a).len();
5949 self.charge_bytes(len)?;
5950 let mut at = 0usize;
5953 loop {
5954 let end = at.saturating_add(crate::stdlib::COPY_PIECE).min(len);
5955 if self.heap.diff_piece(a.idx, b.idx, at, end).is_some() {
5956 return Ok(false);
5957 }
5958 if end >= len {
5959 return Ok(self.bytes(a).len() == self.bytes(b).len());
5960 }
5961 at = end;
5962 self.check_time()?;
5963 }
5964 }
5965
5966 pub(crate) fn eq_nested(&mut self, x: Value, y: Value) -> Result<bool, LuaError> {
5968 if x.raw_eq(y) {
5969 return Ok(true);
5970 }
5971 match (x, y) {
5972 (Value::Str(a), Value::Str(b)) => self.str_eq(a, b),
5973 (Value::Table(_), Value::Table(_)) | (Value::UserData(_), Value::UserData(_)) => {
5974 let mm = self.tm2(x, y, Tm::Eq);
5975 if mm.is_nil() {
5976 return Ok(false);
5977 }
5978 Ok(self.call_nested1(mm, &[x, y])?.truthy())
5979 }
5980 _ => Ok(false),
5981 }
5982 }
5983
5984 fn order_slow(&mut self, e: Tm, x: Value, y: Value, cont: Cont) -> Result<Option<bool>, LuaError> {
5985 let mm = self.tm2(x, y, e);
5986 if mm.is_nil() && e == Tm::Le && !self.limits.strict_5_4 {
5987 let lt = self.tm2(y, x, Tm::Lt);
5989 if !lt.is_nil() {
5990 let cont = match cont {
5991 Cont::Cond { k } => Cont::Cond { k: !k },
5992 c => c,
5993 };
5994 return Ok(self.call_meta(Tm::Le, lt, &[y, x], cont)?.map(|v| !v.truthy()));
5995 }
5996 }
5997 if mm.is_nil() {
5998 return Err(self.compare_error(x, y));
5999 }
6000 Ok(self.call_meta(e, mm, &[x, y], cont)?.map(Value::truthy))
6001 }
6002
6003 pub(crate) fn compare_error(&self, x: Value, y: Value) -> LuaError {
6004 let (t1, t2) = (self.obj_type_name(x), self.obj_type_name(y));
6005 if t1 == t2 {
6006 LuaError::msg(format!("attempt to compare two {t1} values"))
6007 } else {
6008 LuaError::msg(format!("attempt to compare {t1} with {t2}"))
6009 }
6010 }
6011
6012 pub(crate) fn less_than(&mut self, x: Value, y: Value) -> Result<bool, LuaError> {
6014 Ok(match (x, y) {
6015 (Value::Int(i), Value::Int(j)) => i < j,
6016 (Value::Num(f), Value::Num(g)) => f < g,
6017 (Value::Int(i), Value::Num(g)) => number::int_lt_float(i, g),
6018 (Value::Num(f), Value::Int(j)) => number::float_lt_int(f, j),
6019 (Value::Str(a), Value::Str(b)) => {
6020 let n = self.bytes(a).len().min(self.bytes(b).len());
6021 self.charge_bytes(n)?;
6022 self.bytes(a) < self.bytes(b)
6023 }
6024 _ => {
6025 let mut mm = self.tm(x, Tm::Lt);
6026 if mm.is_nil() {
6027 mm = self.tm(y, Tm::Lt);
6028 }
6029 if mm.is_nil() {
6030 return Err(self.compare_error(x, y).plain());
6031 }
6032 self.call_nested1(mm, &[x, y])?.truthy()
6033 }
6034 })
6035 }
6036
6037 pub(crate) fn concat(&mut self, a: usize, n: usize) -> Result<bool, LuaError> {
6040 let mut n = n;
6041 while n > 1 {
6042 let x = self.st(a + n - 2);
6043 let y = self.st(a + n - 1);
6044 if stringable(x) && stringable(y) {
6045 let mut k = n - 1;
6047 while k > 0 && stringable(self.st(a + k - 1)) {
6048 k -= 1;
6049 }
6050 let mut total = 0usize;
6051 for i in k..n {
6052 total = total.saturating_add(self.str_len_of(self.st(a + i)));
6053 }
6054 if total > self.limits.string_len {
6055 return Err(LuaError::Limit(LimitKind::Memory));
6056 }
6057 let floats = (k..n).filter(|&i| matches!(self.st(a + i), Value::Num(_))).count() as u64;
6058 self.charge((total / 64) as u64 + floats * FLOAT_TEXT_FUEL)?;
6059 let s = if total <= crate::heap::SHORT_LEN {
6063 let mut buf = [0u8; crate::heap::SHORT_LEN];
6064 let mut w: &mut [u8] = &mut buf;
6065 for i in k..n {
6066 self.append_stringable(&mut w, self.st(a + i));
6067 }
6068 let len = crate::heap::SHORT_LEN - w.len();
6069 self.new_str(buf.get(..len).unwrap_or_default())?
6070 } else {
6071 self.charge_mem(crate::heap::str_mem(total))?;
6072 let mut buf = Vec::with_capacity(total);
6073 for i in k..n {
6074 self.append_stringable(&mut buf, self.st(a + i));
6075 }
6076 let v = Value::Str(self.heap.new_long_charged(buf.into_boxed_slice()));
6077 self.hold(v);
6078 v
6079 };
6080 self.set_st(a + k, s);
6081 n = k + 1;
6082 continue;
6083 }
6084 let mm = self.tm2(x, y, Tm::Concat);
6085 if mm.is_nil() {
6086 let culprit = if stringable(x) { n - 1 } else { n - 2 };
6087 let v = if stringable(x) { y } else { x };
6088 return Err(ErrorKind::Type { op: "concatenate", ty: self.obj_type_name(v), operand: culprit as u8 }.into());
6089 }
6090 match self.call_meta(Tm::Concat, mm, &[x, y], Cont::Concat { a, n: n - 1 })? {
6091 Some(v) => {
6092 self.set_st(a + n - 2, v);
6093 n -= 1;
6094 }
6095 None => return Ok(false),
6096 }
6097 }
6098 Ok(true)
6099 }
6100
6101 fn str_len_of(&self, v: Value) -> usize {
6103 stringable_len(&self.heap, v)
6104 }
6105
6106 pub(crate) fn append_stringable(&self, out: &mut impl std::io::Write, v: Value) {
6108 write_stringable(&self.heap, out, v);
6109 }
6110
6111 pub(crate) fn tostring(&mut self, v: Value) -> Result<Value, LuaError> {
6113 let mm = self.tm(v, Tm::ToString);
6114 if !mm.is_nil() {
6115 let r = self.call_nested1(mm, &[v])?;
6116 if !matches!(r, Value::Str(_)) {
6117 if let Value::Int(_) | Value::Num(_) = r {
6118 let mut b = Vec::new();
6119 self.append_stringable(&mut b, r);
6120 return self.new_str(&b);
6121 }
6122 return Err(LuaError::msg("'__tostring' must return a string"));
6123 }
6124 return Ok(r);
6125 }
6126 let text = match v {
6127 Value::Str(_) => return Ok(v),
6128 Value::Nil => "nil".to_owned(),
6129 Value::Bool(b) => return self.new_str(if b { b"true" } else { b"false" }),
6130 Value::Int(_) => {
6131 let mut buf = [0u8; 20];
6132 let mut w: &mut [u8] = &mut buf;
6133 self.append_stringable(&mut w, v);
6134 let n = 20 - w.len();
6135 return self.new_str(buf.get(..n).unwrap_or_default());
6136 }
6137 Value::Num(f) => {
6138 self.charge(FLOAT_TEXT_FUEL)?;
6139 number::fmt_float(f)
6140 }
6141 _ => {
6142 self.charge(4)?;
6145 let kind = self.arg_type_name(v);
6146 format!("{kind}: 0x{:08x}", address_of(v))
6147 }
6148 };
6149 self.new_str(text.as_bytes())
6150 }
6151}
6152
6153pub(crate) fn stringable_len(heap: &Heap, v: Value) -> usize {
6155 match v {
6156 Value::Str(s) => heap.str_bytes(s).len(),
6157 Value::Int(i) => i.unsigned_abs().checked_ilog10().map_or(1, |d| d as usize + 1) + usize::from(i < 0),
6158 Value::Num(f) => number::fmt_float(f).len(),
6159 _ => 0,
6160 }
6161}
6162
6163pub(crate) fn write_stringable(heap: &Heap, out: &mut impl std::io::Write, v: Value) {
6165 let _ = match v {
6166 Value::Str(s) => out.write_all(heap.str_bytes(s)),
6167 Value::Int(i) => write_int(out, i),
6168 Value::Num(f) => out.write_all(number::fmt_float(f).as_bytes()),
6169 _ => Ok(()),
6170 };
6171}
6172
6173#[inline]
6175pub(crate) fn write_int(out: &mut impl std::io::Write, i: i64) -> std::io::Result<()> {
6176 let mut digits = [0u8; 20];
6177 let mut at = digits.len();
6178 let mut n = i.unsigned_abs();
6179 loop {
6180 at -= 1;
6181 if let Some(d) = digits.get_mut(at) {
6182 *d = b'0' + (n % 10) as u8;
6183 }
6184 n /= 10;
6185 if n == 0 {
6186 break;
6187 }
6188 }
6189 if i < 0 {
6190 let _ = out.write_all(b"-");
6191 }
6192 out.write_all(digits.get(at..).unwrap_or_default())
6193}
6194
6195pub(crate) fn address_of(v: Value) -> u64 {
6197 let (kind, idx) = match v {
6198 Value::Table(r) => (1u64, r.idx),
6199 Value::Func(r) => (2, r.idx),
6200 Value::UserData(r) => (3, r.idx),
6201 Value::Thread(r) => (4, r.idx),
6202 Value::Str(r) => (5, r.idx),
6203 _ => (0, 0),
6204 };
6205 0x5500_0000_0000 | (kind << 36) | (u64::from(idx) << 4)
6206}
6207
6208fn stringable(v: Value) -> bool {
6209 matches!(v, Value::Str(_) | Value::Int(_) | Value::Num(_))
6210}
6211
6212fn int_of(v: Value) -> Option<i64> {
6214 match v {
6215 Value::Int(i) => Some(i),
6216 Value::Num(f) => number::float_to_int(f),
6217 _ => None,
6218 }
6219}
6220
6221#[inline]
6222fn float_arith(op: ArithOp, f: f64, g: f64) -> Option<Value> {
6223 Some(Value::Num(match op {
6224 ArithOp::Add => f + g,
6225 ArithOp::Sub => f - g,
6226 ArithOp::Mul => f * g,
6227 ArithOp::Div => f / g,
6228 ArithOp::Pow => {
6229 if g == 2.0 { f * f } else { f.powf(g) }
6230 }
6231 ArithOp::IDiv => (f / g).floor(),
6232 ArithOp::Mod => number::float_mod(f, g),
6233 _ => return None,
6234 }))
6235}
6236
6237fn int_arith(op: ArithOp, i: i64, j: i64) -> Result<i64, LuaError> {
6238 Ok(match op {
6239 ArithOp::Add => i.wrapping_add(j),
6240 ArithOp::Sub => i.wrapping_sub(j),
6241 ArithOp::Mul => i.wrapping_mul(j),
6242 ArithOp::IDiv => {
6243 if j == 0 {
6244 return Err(LuaError::msg("attempt to divide by zero"));
6245 }
6246 number::int_floor_div(i, j)
6247 }
6248 ArithOp::Mod => {
6249 if j == 0 {
6250 return Err(LuaError::msg("attempt to perform 'n%0'"));
6251 }
6252 number::int_mod(i, j)
6253 }
6254 ArithOp::BAnd => i & j,
6255 ArithOp::BOr => i | j,
6256 ArithOp::BXor => i ^ j,
6257 ArithOp::Shl => number::shift_left(i, j),
6258 ArithOp::Shr => number::shift_left(i, j.wrapping_neg()),
6259 _ => 0,
6260 })
6261}
6262
6263pub(crate) fn arith_values(op: ArithOp, a: Value, b: Value) -> Result<Value, LuaError> {
6265 match (a, b) {
6266 (Value::Int(i), Value::Int(j)) if !matches!(op, ArithOp::Div | ArithOp::Pow) => Ok(Value::Int(int_arith(op, i, j)?)),
6267 _ => {
6268 let (f, g) = (a.as_num().unwrap_or(0.0), b.as_num().unwrap_or(0.0));
6269 if is_bitwise(op) {
6270 let (Some(i), Some(j)) = (number::float_to_int(f), number::float_to_int(g)) else {
6271 return Err(LuaError::msg("number has no integer representation"));
6272 };
6273 return Ok(Value::Int(int_arith(op, i, j)?));
6274 }
6275 Ok(float_arith(op, f, g).unwrap_or(Value::Nil))
6276 }
6277 }
6278}
6279
6280pub(crate) fn chunk_id(source: &str) -> String {
6283 let source = source.split('\0').next().unwrap_or("");
6286 if let Some(rest) = source.strip_prefix('=') {
6287 return truncate_utf8(rest, 59).to_owned();
6288 }
6289 if let Some(rest) = source.strip_prefix('@') {
6290 if rest.len() <= 59 {
6291 return rest.to_owned();
6292 }
6293 let tail_start = rest.len() - 56;
6294 let mut s = tail_start;
6295 while !rest.is_char_boundary(s) {
6296 s += 1;
6297 }
6298 return format!("...{}", rest.get(s..).unwrap_or_default());
6299 }
6300 let first = source.split('\n').next().unwrap_or("");
6301 let multi = source.contains('\n');
6302 const MAX: usize = 60 - 15;
6303 if !multi && first.len() < MAX {
6305 return format!("[string \"{first}\"]");
6306 }
6307 let cut = truncate_utf8(first, MAX);
6308 format!("[string \"{cut}...\"]")
6309}
6310
6311pub(crate) fn cut_message(b: &[u8], max: usize) -> &[u8] {
6315 match std::str::from_utf8(b) {
6316 Ok(s) => truncate_utf8(s, max).as_bytes(),
6317 Err(_) => b.get(..max.min(b.len())).unwrap_or_default(),
6318 }
6319}
6320
6321pub(crate) fn truncate_utf8(s: &str, max: usize) -> &str {
6322 if s.len() <= max {
6323 return s;
6324 }
6325 let mut cut = max;
6326 while !s.is_char_boundary(cut) {
6327 cut -= 1;
6328 }
6329 s.get(..cut).unwrap_or_default()
6330}
6331
6332#[inline]
6340pub(crate) fn list_fuel(n: usize) -> u64 {
6341 if n > 16 { n as u64 / 8 } else { 0 }
6342}
6343
6344const OPEN_SHIFT_PER_FUEL: usize = 32;
6346
6347pub(crate) fn new_closure(
6348 heap: &mut Heap,
6349 open: &mut Vec<(usize, u32)>,
6350 cur: ThreadRef,
6351 parent: u32,
6352 closure: FuncRef,
6353 base: usize,
6354 p: usize,
6355) -> Result<(Value, u64), Option<usize>> {
6356 let child = heap.protos.get(parent).and_then(|pp| pp.protos.get(p)).copied().ok_or(None)?;
6357 let mut small = [(false, 0u32); 16];
6360 let big: Vec<(bool, u32)>;
6361 let descs: &[(bool, u32)] = match heap.protos.get(child) {
6362 Some(c) if c.upvals.len() <= small.len() => {
6363 for (s, d) in small.iter_mut().zip(&c.upvals) {
6364 *s = (d.in_stack, d.idx);
6365 }
6366 small.get(..c.upvals.len()).unwrap_or_default()
6367 }
6368 Some(c) => {
6369 big = c.upvals.iter().map(|d| (d.in_stack, d.idx)).collect();
6370 &big
6371 }
6372 None => &[],
6373 };
6374 let fresh = descs
6375 .iter()
6376 .filter(|(in_stack, idx)| *in_stack && open.binary_search_by(|(i, _)| i.cmp(&(base + *idx as usize))).is_err())
6377 .count();
6378 let size = crate::heap::FUNC_BASE + crate::heap::boxed(descs.len() * 8) + fresh * UPVAL_SIZE;
6379 let mut extra = ((descs.len() + 2 * fresh) / 8) as u64;
6384 if !heap.mem.fits(size) {
6385 return Err(Some(size));
6386 }
6387 let _ = heap.mem.charge(size);
6388 let mut ups = Vec::with_capacity(descs.len());
6389 let mut shifted = 0usize;
6391 for &(in_stack, idx) in descs {
6392 if in_stack {
6393 let at = base + idx as usize;
6394 match open.binary_search_by(|(i, _)| i.cmp(&at)) {
6395 Ok(k) => {
6396 let r = open.get(k).map_or(0, |(_, r)| *r);
6397 ups.push(FuncRef { idx: r, generation: heap.upvals.gens.get(r as usize).copied().unwrap_or(0) });
6398 }
6399 Err(k) => {
6400 let r = heap.new_upval_charged(Upval::Open { thread: cur, idx: at });
6401 shifted += open.len() - k;
6402 open.insert(k, (at, r.idx));
6403 ups.push(r);
6404 }
6405 }
6406 } else {
6407 let r = match heap.funcs.get(closure.idx) {
6410 Some(Func::Lua { upvals, .. }) => upvals.get(idx as usize).copied(),
6411 _ => None,
6412 };
6413 ups.push(r.unwrap_or(FuncRef { idx: u32::MAX, generation: 0 }));
6414 }
6415 }
6416 extra += (shifted / OPEN_SHIFT_PER_FUEL) as u64;
6421 let f = heap.new_func_charged(Func::Lua { proto: child, upvals: ups.into_boxed_slice() });
6422 Ok((Value::Func(f), extra))
6423}
6424
6425
6426pub(crate) fn clear_list(v: &mut Vec<Value>) {
6430 if v.capacity() > crate::stdlib::NATIVE_CHUNK {
6431 *v = Vec::new();
6432 } else {
6433 v.clear();
6434 }
6435}