Skip to main content

remedy_lua/
vm.rs

1//! The virtual machine: the execution loop, calls, metamethods, errors, coroutines and the
2//! collector's driver.
3//!
4//! Lua-to-Lua calls, `pcall`, metamethods written in Lua and coroutine switches all happen
5//! inside one loop without growing the Rust stack, so scripts can recurse deeply, yield
6//! from inside `pcall` and metamethods, and the fuel counter sees every step. Rust
7//! re-enters the loop only for library functions that call back into Lua (`table.sort`'s
8//! comparator, `string.gsub`'s replacement function, `__tostring`, `__close`), and that
9//! nesting has its own limit.
10
11use 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
20/// A library function written in Rust.
21pub(crate) type NativeFn = fn(&mut Lua, Args) -> Result<Flow, LuaError>;
22
23/// Where a native call's arguments are: `n` values from stack slot `base`.
24#[derive(Clone, Copy, Debug)]
25pub struct Args {
26    pub(crate) func: usize,
27    pub(crate) base: usize,
28    pub(crate) n: usize,
29}
30
31/// What a native function asks the machine to do when it returns.
32pub(crate) enum Flow {
33    /// Return the values in `rets`.
34    Return,
35    /// `pcall`/`xpcall`: call the first argument with the rest, protected.
36    PCall { handler: Option<Value>, nargs: usize },
37    /// `coroutine.yield` with the values in `rets`.
38    Yield,
39    /// `coroutine.resume` (or a `wrap` function) of `co` with the values in `rets`.
40    Resume { co: ThreadRef, wrap: bool },
41    /// Call `f(arg)` in the native's place, its results cut to three (`pairs` calling
42    /// `__pairs`: C Lua's `lua_callk`, so it may yield).
43    Call3 { f: Value, arg: Value },
44}
45
46/// What went wrong while running (see `LuaError`).
47#[derive(Debug)]
48pub(crate) enum ErrorKind {
49    /// A raised value (message strings already carry their position).
50    Value(Value),
51    /// A message that gets the position of the running Lua function.
52    Msg(String),
53    /// A message raised by the machine while a Rust function runs: no position (as C
54    /// Lua's errors raised inside C functions).
55    Plain(String),
56    /// `attempt to {op} a {ty} value`, with what the operand was (see `annotate`).
57    Type { op: &'static str, ty: String, operand: u8 },
58    /// `attempt to call a {ty} value`.
59    Call { ty: String },
60    /// `bad argument #{n} to '{name}' ({msg})`.
61    Arg(usize, String),
62    /// `number{info} has no integer representation`.
63    IntRepr { operand: u8 },
64    /// A limit: not catchable.
65    Limit(LimitKind),
66    /// Not an error: the call paused at a collector step at the end of the host's poll,
67    /// its frames kept (`Lua::pending_call`, SEC7-G1). Nothing catches it.
68    Pending,
69}
70
71/// What `Lua::settle_key` found for a key.
72#[derive(Clone, Copy, Debug)]
73pub(crate) enum Settled {
74    /// Nothing to do (not a long string, or its interned copy known).
75    Plain,
76    /// Its interned copy (now known).
77    Found,
78    /// No interned string equals it: the one it could have equaled and the first byte
79    /// where they differ (None: there was none).
80    Absent(Option<(u32, usize)>),
81}
82
83/// An error while running: one word, so results carrying it come back in registers (at
84/// 48 bytes, each call site's result took a stack slot of its own: `Lua::run`'s frame was
85/// 6 KiB, which bounded nested host calls to 59 levels in `Limits::stack_bytes`).
86#[derive(Debug)]
87pub(crate) struct LuaError(Box<ErrorKind>);
88
89const _: () = assert!(std::mem::size_of::<Result<Value, LuaError>>() == 16);
90
91/// A call from the host paused at a collector step: where its results go, the thread and
92/// depth it returns at, whether a native's scratch keeps them, and its native top.
93#[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    /// As raised from Rust: a message without a position (`Msg` becomes `Plain`).
136    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    /// The limit it is, if it is one (not catchable).
143    /// The call paused (`ErrorKind::Pending`).
144    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/// Metamethod events.
157#[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
244/// An error raised at C level (by a protected call, or a call from Rust, itself): a call
245/// error then carries no position.
246fn 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/// The results a generic `for`'s iterator call wants: `c`, or all of them (MULTI, for more
254/// than a 16-bit count: `PadNil` adjusts them).
255#[inline]
256fn tfor_wanted(c: u16) -> i32 {
257    if c == MULTI { -1 } else { i32::from(c) }
258}
259
260/// What happens with a metamethod's result when the Lua function computing it returns.
261#[derive(Clone, Copy, Debug)]
262pub(crate) enum Cont {
263    /// Store it in a stack slot.
264    Store(usize),
265    /// Ignore it.
266    Discard,
267    /// A comparison: skip the caller's next instruction unless truthy(result) == k.
268    Cond { k: bool },
269    /// Concatenation in progress over `n` values from slot `a`.
270    Concat { a: usize, n: usize },
271    /// Closing to-be-closed variables down to `level` on a normal exit; then `then`.
272    Closing { level: usize, then: AfterClose },
273    /// `__pairs` called by `pairs` (`Flow::Call3`): its results in the frame's place, cut
274    /// to three, then adjusted to `wanted`.
275    Three { wanted: i32 },
276    /// A `__close` run while an error unwinds to the protected call of frame `frame`
277    /// returned: the next one, then the protected call's `false, error`.
278    ErrClosing { frame: usize },
279    /// The innermost of `levels + 1` nested protected calls (`pcall(pcall, f)`: each one's
280    /// callee is the next; S5COR-6b) finished, its status and results from slot
281    /// `dest + levels` up to `top` (its `wanted` is always -1): each enclosing one puts its
282    /// `true` in the slot below (their slots are `dest..dest + levels`, one above the
283    /// other), and the outermost's results go to `dest`, adjusted to `wanted`. One frame
284    /// (or pending call) carries them all, so a yield inside works, as in C Lua, and the
285    /// depth costs no native stack.
286    ///
287    /// Two things may wrap it (S5COR-6c): `three`, the innermost callee is a Lua `__pairs`
288    /// that `pairs` called (`pcall(pcall, pairs, t)`), whose results are cut to three
289    /// first; and `then`, the outermost call is a metamethod (`pcall` as `__add`, say, or
290    /// `pairs` as `__index`, with `levels` 0 and no protected call of its own when the
291    /// frame is a `FrameKind::Cont`), whose continuation then gets the outermost's first
292    /// result: `then` with `back` and `n` is that continuation, packed (`pack_then`), and
293    /// `levels`, `then` and `three` share a word (`NestBits`), so a frame keeps its size.
294    Nest { dest: usize, bits: NestBits, wanted: i32, back: u32, n: u32 },
295}
296
297/// A metamethod's continuation after a `Cont::Nest`, packed with its `back` and `n`.
298#[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/// A `Cont::Nest`'s `levels` (below 2^27), `then` and `three`, in one word: bit 0 is
309/// `three`, bits 1-3 `then`, the rest `levels`.
310#[derive(Clone, Copy, Debug, PartialEq, Eq)]
311pub(crate) struct NestBits(u32);
312
313impl NestBits {
314    /// None past 2^27 - 1 levels (2^27 protected calls one above the other need 2 GiB of
315    /// stack); the call then runs nested, once per 2^27 levels.
316    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
346/// `c`, the continuation of a metamethod called at `dest`, as a `Cont::Nest`'s `then`,
347/// `back` (its slot, `dest - back`: a register of the frame below) and `n`. None for a
348/// continuation that is not a metamethod's, or one too far below to pack (which a frame's
349/// registers never are).
350fn 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
361/// The continuation `pack_then` packed.
362fn 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    /// Whether the machine called a metamethod for an instruction with this continuation
376    /// (for `debug.getinfo`'s "metamethod" names).
377    pub(crate) fn is_metamethod(self) -> bool {
378        matches!(self, Cont::Store(_) | Cont::Discard | Cont::Cond { .. } | Cont::Concat { .. } | Cont::Closing { .. })
379    }
380}
381
382/// What a normal-exit close goes on with.
383#[derive(Clone, Copy, Debug)]
384pub(crate) enum AfterClose {
385    /// Nothing (a block's end or a jump out of it).
386    Nothing,
387    /// The frame returns `n` results from `src`.
388    Return { src: usize, n: usize },
389}
390
391// `Cont::Nest` fits in the continuation as it was: a frame stays 136 bytes (64-bit).
392const _: () = assert!(std::mem::size_of::<Cont>() <= 32 && std::mem::size_of::<FrameKind>() <= 48);
393// The tail-call flag fits in the frame's padding, and the record is 128 bytes: a frame
394// is found by a shift (at 136 it took a shift and an add, on every frame switch).
395const _: () = assert!(std::mem::size_of::<Frame>() <= 128);
396
397/// The continuation that completes the protected call of kind `kind` whose callee, at
398/// `func`, is a protected call too, and every protected call enclosing it (S5COR-6b), and
399/// then the metamethod's continuation the outermost one's status goes to (S5COR-6c). None
400/// when its slots are not one above the other (which the call protocol never does) or its
401/// continuation is not one a `Cont::Nest` carries.
402fn 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/// The protected calls a call of kind `kind` sits on: one for a protected call, one more
419/// for each enclosing one it completes (`Cont::Nest`).
420#[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/// A Lua `__pairs` that `pairs` called: its frame sits on `pairs`, a Rust activation (for
430/// error levels) and a C level (`lua_callk` in C Lua).
431#[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/// The C levels (`nCcalls` in C Lua) a frame or native call of kind `kind` that Rust
441/// started adds: each protected call (`pcall` calls from C), the metamethod call (C Lua's
442/// `luaT_callTMres`), and `pairs`'s call of `__pairs` (S5COR-6c: `pcall(pairs, t)` and
443/// `pcall` as a metamethod each counted one level short).
444#[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
456/// The frames an error's position skips, for [`Lua::where_`] walking down from the top:
457/// those strictly between a protected call `lo` an error unwinds to and the `__close` it
458/// runs above them, at `hi`. An interval counts once the walk is below its `hi`.
459struct Dead {
460    /// `err_closing`'s interval, until the walk is below its `hi`.
461    ec: Option<(usize, usize)>,
462    /// The least `lo` of the intervals counting: the frames above it are gone.
463    min_lo: usize,
464    /// The `lo`s counting, at or below the walk (the greatest on top).
465    los: std::collections::BinaryHeap<usize>,
466}
467
468impl Dead {
469    /// An interval whose `hi` the walk passed.
470    fn add(&mut self, lo: usize) {
471        self.min_lo = self.min_lo.min(lo);
472        self.los.push(lo);
473    }
474
475    /// The walk is at frame `t`: `err_closing`'s interval counts if its `hi` is above.
476    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    /// Frame `t` is a protected call being unwound to (`t` never grows between calls).
490    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
498/// Passes `k` Rust activations (no position) in [`Lua::where_`]'s walk: the position
499/// (empty) when the level asked for is one of them.
500fn 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    /// Called by `pcall`: results go to `dest` after `true`; a `pcall` used as a
516    /// metamethod passes its status on through `cont`.
517    Protected { dest: usize, wanted: i32, cont: Option<Cont> },
518    Cont(Cont),
519}
520
521/// A Lua function's activation.
522pub(crate) struct Frame {
523    pub closure: FuncRef,
524    /// The prototype (in the heap). (The end of its registers is not kept: it is always
525    /// `base + frame_size`, see `Lua::frame_top`.)
526    pub proto: u32,
527    /// Stack slot of the function: results go here.
528    pub func: usize,
529    /// Register 0.
530    pub base: usize,
531    pub pc: usize,
532    pub nresults: i32,
533    pub vstart: usize,
534    pub vcount: usize,
535    pub kind: FrameKind,
536    /// Called from a Lua function (not from Rust).
537    pub from_lua: bool,
538    /// Entered by a tail call (`debug.getinfo`'s `istailcall`; it has no call-site name).
539    pub tail: bool,
540    /// `xpcall`'s message handler.
541    pub handler: Option<Value>,
542}
543
544/// One activation of a thread (`Lua::activations`).
545#[derive(Clone, Copy, Debug, PartialEq, Eq)]
546pub(crate) enum Act {
547    /// A Lua frame (its index).
548    Lua(usize),
549    /// A Rust function: the stack slot that holds it, when known.
550    C(Option<usize>),
551    /// Where Rust started the thread's frames (a call from the host, a coroutine's body):
552    /// a level for error positions, no activation in a traceback.
553    Base,
554}
555
556/// A run of activations, walked newest first (`Lua::walk_activations`).
557#[derive(Clone, Copy, Debug)]
558enum Run {
559    /// A Lua frame (its index).
560    Lua(usize),
561    /// `count` Rust functions, in slots `slot..slot + count` (oldest first), when known.
562    C { slot: Option<usize>, count: usize },
563    /// Where Rust started the thread's frames ([`Act::Base`]).
564    Base,
565}
566
567pub(crate) enum Called {
568    /// A Lua frame was pushed: run it.
569    Lua,
570    /// A native function finished; results are in place.
571    Done,
572    /// The running thread changed.
573    Switched,
574}
575
576/// A protected call's callee to call next (`Lua::nested_pending`): its slot, its arguments,
577/// the kind that completes every enclosing protected call, and the innermost one's
578/// message handler.
579#[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
587/// A frame's register window: registers are 8-bit numbers.
588pub(crate) use crate::bytecode::{WIDE_WINDOW, WINDOW};
589/// Room above a frame's registers for metamethod calls and native arguments.
590pub(crate) const EXTRA_STACK: usize = 24;
591
592/// Spare coroutine stacks kept (`Lua::spare_stacks`), and the largest kept, in slots.
593const SPARE_STACKS: usize = 8;
594const SPARE_STACK_SLOTS: usize = 2048;
595/// Bytes a stack slot holds.
596const SLOT_BYTES: usize = crate::table::SLOT_SIZE;
597/// Fuel a coroutine's first resume costs for the memory it maps (LR-8): its record and its
598/// register window, a unit per 128 bytes (37). Fixed, so the same whether a spare stack is
599/// reused or not, with the fast loop or not, under any hash seed.
600pub(crate) const COROUTINE_COST: u64 =
601    ((crate::heap::THREAD_BASE + (256 + EXTRA_STACK + 1) * SLOT_BYTES) / 128) as u64;
602/// Most `__index`/`__newindex` links followed, and `__call` links.
603const MAX_TAG_LOOP: usize = 2000;
604/// Longest `__name` used in messages and `tostring`.
605const MAX_NAME: usize = 256;
606/// The fuel handed out at a time: how many steps may pass between looks at the host's
607/// interrupt and deadline (a fraction of a millisecond of work).
608/// Fuel for each link of an `__index` or `__newindex` chain (and the probing of its lookup
609/// besides, S5GC-1). A link reads the metatable, finds its `__index` and looks the key up
610/// in another table: about two instructions' work, and the loads of different tables, not
611/// in the caches for a long chain. At 1, keys aimed at the worst layout (a known hash
612/// seed; S5B-OPEN-2's residual) in 1,999 tables of 2^9 slots on one chain ran at 8.3x
613/// plain code per unit of fuel with the fast loop and 6.5x without, against 4.2x and 3.4x
614/// for the same tables looked up directly. The count is the program's, never the seed's.
615pub(crate) const LINK_COST: u64 = 2;
616
617/// Links of one access charged `LINK_COST`; each past them costs `DEEP_LINK_COST`. A class
618/// hierarchy is a few links deep; the amplifier of S5B-OPEN-2's residual is a long chain
619/// through tables not in the caches, a cache miss or more per link: at 2 units a link the
620/// worst layout still ran at 5.3x plain code per unit of fuel here (fast loop; 4.0x
621/// without) and up to 9x on slower memory.
622pub(crate) const SHALLOW_LINKS: usize = 4;
623pub(crate) const DEEP_LINK_COST: u64 = 8;
624
625/// The fuel for link `n` (from 0) of one `__index` or `__newindex` chain walk.
626#[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
633/// Fuel for making an error message (its position and text; calibrated with
634/// `examples/fuelcal.rs`), on top of what naming its variables reads.
635const ERROR_FUEL: u64 = 24;
636
637/// Collector work units per fuel unit.
638pub(crate) const WORK_PER_FUEL: usize = 4;
639
640/// Steps in Rust functions in a row that leave the atomic phase for a step at an
641/// instruction (`Lua::atomic_deferred`).
642const ATOMIC_DEFERRALS: u32 = 16;
643/// Collector work a full collection does between charges (and looks at the interrupt).
644const FULL_GC_CHUNK: usize = 1 << 14;
645
646/// Fuel for writing a float as text (`%.14g` and friends cost about as much as eight
647/// instructions; calibrated: `examples/fuelcal.rs`).
648pub(crate) const FLOAT_TEXT_FUEL: u64 = 8;
649
650/// What runs scripts: a RemedyLua state with its globals, heap and limits. One thread
651/// uses it at a time; it may move between threads (`Send`).
652pub 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    /// End of the last variable-count result list.
658    pub(crate) top: usize,
659    /// While a native runs: the first free stack slot above its arguments.
660    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    /// Bumped whenever something the fast loop's context copies changes (the limits, the
667    /// string metatable, the library functions it runs in place): `run` makes its
668    /// context again then, and only then.
669    pub(crate) ctx_epoch: u64,
670    /// The pattern matcher's state, kept between `find`, `match` and `gmatch` calls (made
671    /// afresh it was 700 bytes to set up per call; see `MatchState::reuse`).
672    pub(crate) match_state: Option<Box<crate::stdlib::pattern::MatchState>>,
673    /// Stacks of coroutines that were closed or finished, for new coroutines to reuse
674    /// (`retire_stack`, LR-8). Bounded (`SPARE_STACKS`, `SPARE_STACK_SLOTS`, a sixteenth of
675    /// the memory limit), counted in `Mem::used` as slack while kept (`Mem::slack_in`),
676    /// emptied by full collections.
677    pub(crate) spare_stacks: Vec<Vec<Value>>,
678    pub(crate) fuel: i64,
679    /// Fuel left when a limit stopped the call from the host (`fuel` itself is then spent,
680    /// so nothing runs on): what `fuel_left` reports for it.
681    pub(crate) stopped_left: Option<u64>,
682    pub(crate) limits: Limits,
683    /// Execution loops entered from Rust and not yet left.
684    pub(crate) c_depth: usize,
685    pub(crate) native_depth: u32,
686    /// Calls through `call_native` (a test probe: `Lua::native_calls`).
687    pub(crate) native_calls: u64,
688    pub(crate) native_from_lua: bool,
689    /// The metamethod event the running native was called for (`call_meta`), which names
690    /// it in argument errors as C Lua names it (`bad argument #1 to 'index'`).
691    pub(crate) native_event: Option<&'static str>,
692    /// The event `call_meta` is about to call a metamethod for, taken by `call_native`.
693    pub(crate) pending_event: Option<&'static str>,
694    /// The native running now (for error messages).
695    pub(crate) native_name: &'static str,
696    /// Where the native stack was when the host called in (see `Limits::stack_bytes`).
697    pub(crate) stack_base: usize,
698    /// Coroutines resumed and not yet back (each resumed from inside another).
699    pub(crate) resume_depth: usize,
700    /// Natives running directly under `pcall` (`pcall(string.gsub, ...)`), which have no
701    /// frame of their own: C levels for `call_handler` (S5COR-5).
702    pub(crate) protected_natives: usize,
703    /// Collector work done but not yet a whole unit of fuel (`gc_step`): carried to the
704    /// next step, so the fuel charged is the work done over `WORK_PER_FUEL`, however a
705    /// cycle's work splits into steps (S5C-1).
706    pub(crate) gc_work_carry: usize,
707    /// Marking work done but not yet charged (a step stops after the object that passes
708    /// its budget): each unfinished marking step charges exactly its budget and keeps the
709    /// rest here, and marking counts as finished only once what is left fits in a step, so
710    /// how marking splits into steps follows the total work alone, never the order objects
711    /// are reached in (which follows the hash seed: S6GC-2 made that visible).
712    pub(crate) gc_mark_over: usize,
713    /// Atomic-phase work done past a call's fuel, owed by the call that resumes it.
714    pub(crate) atomic_owed: usize,
715    /// Test probe (SEC8-F7): collector work units owed past a call's fuel (`owe_gc`) since
716    /// the state was made, and those of them a cycle's start charged (a carry left when the
717    /// last cycle ended).
718    pub(crate) gc_owed_probe: (u64, u64),
719    /// A marking step paused at the end of the host's poll (SEC7-G1): what it started
720    /// with (the objects made since the last step's part, its budget whole, its budget),
721    /// so `gc_step` goes on with it, inside its loop (`Heap::propagate_resume`), and ends
722    /// it as it would have ended.
723    pub(crate) gc_pending: Option<(usize, usize, usize)>,
724    /// The call from the host paused with it, its frames kept.
725    pub(crate) pending_call: Option<PendingCall>,
726    /// The paused instruction runs again on resume, without the step it took.
727    pub(crate) due_skip: bool,
728    /// A step paused inside its atomic phase: the work the step had done before it, and
729    /// the allowance it gave it, so it ends as it would have (SEC7-G1).
730    pub(crate) gc_atomic_pre: Option<(usize, usize)>,
731    /// The atomic phase not started in a step inside a Rust function, times in a row: it
732    /// starts at a step at an instruction, where the call can pause (SEC7-G1), or after
733    /// `ATOMIC_DEFERRALS` such steps (a script whose allocations all come from Rust
734    /// functions still ends its cycles).
735    pub(crate) atomic_deferred: u32,
736    /// A call from the host paused before it started (resuming a suspended atomic phase
737    /// at its entry, `resume_atomic`): the function and its arguments.
738    pub(crate) pending_start: Option<(Value, Vec<Value>)>,
739    /// `collectgarbage('step')` called from Lua code: its step ran at the call (the cycle
740    /// before it), for the function to answer from (`collect_step`, SEC7-G1).
741    pub(crate) gc_call_before: Option<u32>,
742    /// The paused instruction was set to run again, its fetch's unit given back: when the
743    /// step it paused in ends the call instead (a limit), the unit is taken back, as the
744    /// instruction does not run again (SEC7-G1).
745    pub(crate) rewound: bool,
746    /// While a native `__close` runs as an error unwinds to the protected call of this
747    /// frame, called with this many frames: the frames between are gone for error levels,
748    /// as in C Lua (S5C-COR-3); a callable `__close`'s own frame above them is not (S6-6).
749    pub(crate) err_closing: Option<(usize, usize)>,
750    /// A protected call whose callee is a protected call in turn (`pcall(pcall, f)`)
751    /// leaves that callee's own callee here and returns `Called::Done`: `precall` goes on
752    /// with it, in a loop, so the depth costs no native stack (S5COR-6b).
753    pub(crate) nested_pending: Option<NestedCall>,
754    /// Natives in progress: their thread, how many Lua frames it had when they were
755    /// called (for error positions by level), each one's stack slot (for
756    /// `debug.traceback` and `debug.getinfo`), and the protected calls it sits on, which
757    /// are activations too, in the slots just below (a native called by `pcall`; S6-2: a
758    /// run of 100,000 nested ones took an entry each, at each level).
759    pub(crate) native_stack: Vec<(ThreadRef, usize, usize, usize)>,
760    /// The native whose error was raised last (its `native_stack` record) and that error.
761    /// (With the protected calls it sat on, as `call_native` counts them.)
762    pub(crate) err_native: Option<((ThreadRef, usize, usize), usize, Value)>,
763    /// While a message handler runs: the native that raised the error it handles, and
764    /// the protected calls it sat on.
765    pub(crate) handler_native: Option<((ThreadRef, usize, usize), usize)>,
766    /// S6-7: while a message handler runs (`call_handler`), its thread, and C Lua's C
767    /// levels where the error escaping it was raised (`on_error` sees the raise with the
768    /// frames still there). C Lua calls the handler again at that point (`luaG_errormsg`),
769    /// so an error raised inside a metamethod or a library callback costs it more levels.
770    pub(crate) handler_raise: HandlerWatch,
771    pub(crate) roots: Vec<(Weak<()>, Value)>,
772    /// The fast loop is on (a test switch turns it off to check it against `run` alone).
773    pub(crate) fast: bool,
774    /// Instructions the full path ran while the fast loop was on (see `Lua::full_steps`).
775    pub(crate) full_steps: u64,
776    /// Length of `roots` after it was last pruned of dropped handles.
777    pub(crate) roots_pruned_at: usize,
778    /// Objects natives made and still hold, kept alive until they return.
779    pub(crate) scratch: Vec<Value>,
780    /// Values the host made or got outside a call (`create_*`, `from_data`, `get`, a call's
781    /// results), kept alive until the next call from the host returns.
782    pub(crate) held: Vec<Value>,
783    /// Where the running native's own part of `scratch` starts. Only that part is compacted
784    /// (`push_scratch`), so positions below it (a caller's, `sort`'s root slots) stay put.
785    pub(crate) scratch_floor: usize,
786    /// The length of `scratch` at which its running part is next compacted.
787    pub(crate) scratch_compact_at: usize,
788    /// The length of `held` at which it is next compacted.
789    pub(crate) held_compact_at: usize,
790    /// The results of the last `Lua::call` made inside each running host function (the
791    /// innermost one's from `host_rets_base`), kept until that function's next call
792    /// (S5API-3: `rets` is the natives' return channel, cleared by any native call).
793    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    /// `print` output not taken yet (when no sink is set).
798    pub(crate) output: Vec<u8>,
799    /// Bytes `print` and `warn` wrote in the current call from the host.
800    pub(crate) output_used: usize,
801    /// Bytes of `output`'s buffer charged to the memory account (until `take_output`).
802    pub(crate) output_charged: usize,
803    /// Whether `warn` writes: off until a script sends "@on", as in `luaL_newstate`.
804    pub(crate) warn_on: bool,
805    /// The collector mode a script last asked for (only the incremental collector exists).
806    pub(crate) gc_generational: bool,
807    /// The last error object that left the state, with its text (see `from_host_error`).
808    pub(crate) last_error: Option<(String, Value)>,
809    /// A limit that stopped a call: later steps of the same call from the host fail with
810    /// it too, even when a host function swallowed the error.
811    pub(crate) limit_hit: Option<LimitKind>,
812    /// Fuel not yet given to `fuel`: the budget is handed out a slice at a time, and between
813    /// slices the interrupt and the deadline are checked (see `refuel`).
814    pub(crate) reserve: i64,
815    /// The host's interrupt: set from any thread, it stops the running call.
816    pub(crate) interrupt: std::sync::Arc<std::sync::atomic::AtomicBool>,
817    /// A clock and how long one call from the host may run by it.
818    pub(crate) time_limit: Option<(crate::Clock, std::time::Duration)>,
819    /// When the running call must stop, by `time_limit`'s clock.
820    pub(crate) deadline: Option<std::time::Duration>,
821    /// The host's own data, by type.
822    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    /// Host calls in progress (fuel resets only at the outermost).
825    pub(crate) entry: u32,
826    /// A panic (a host function's, or a bug) unwound through a call: the machine may be
827    /// mid-instruction, so every later call is refused.
828    pub(crate) poisoned: bool,
829    /// What compiles left to free a piece at a time, each with the bytes it is charged.
830    pub(crate) deferred: crate::diag::Deferred,
831    /// Traceback of the last error that left the machine, if one did: its frames, top
832    /// first (at most 22), as an index in `trace_sources`, the line, and the line the
833    /// function starts on. S6GC-H1: noted at each error, made into text only for the host
834    /// ([`Lua::take_traceback`]), as most errors are caught.
835    pub(crate) last_trace: Option<Vec<(usize, u32, u32)>>,
836    /// The chunks `last_trace` names.
837    pub(crate) trace_sources: Vec<Arc<str>>,
838    /// The clocks of `os.time`/`os.date` (time since the Unix epoch) and `os.clock` (time
839    /// the program has run); `None` reads as 0 (see `Lua::set_os_clocks`).
840    pub(crate) os_clocks: (Option<crate::Clock>, Option<crate::Clock>),
841    /// Seconds east of UTC for `os.date` local time.
842    pub(crate) utc_offset: i64,
843    /// Interned strings the libraries use often.
844    pub(crate) names: crate::stdlib::Names,
845    /// Modules the host registered for `require` (`Lua::add_module`), by name.
846    pub(crate) modules: std::collections::HashMap<Vec<u8>, crate::ModuleSource>,
847    /// What `os.getenv` reads (`Libs::ENV`, `Lua::set_env`): the host's map, never the
848    /// process environment. Not counted against the memory limit (the host's copy).
849    pub(crate) env: std::collections::HashMap<Vec<u8>, std::sync::Arc<[u8]>>,
850    /// The longest name `env` has held: a longer one is looked up without being hashed.
851    pub(crate) env_name_max: usize,
852    /// `io`'s standard streams (stdin, stdout, stderr) as the host set them (`Libs::IO`);
853    /// None while an operation holds one, or before the host set one (the default).
854    pub(crate) io_std: [Option<crate::stdlib::io::FileState>; 3],
855    /// What `io.open` asks for files (`Lua::set_file_opener`).
856    pub(crate) io_opener: Option<crate::IoOpener>,
857    /// The file handles' metatable (`FILE*`, in the registry too).
858    pub(crate) io_meta: Option<TableRef>,
859    /// The host's module loader for `require` (`Lua::set_module_loader`).
860    pub(crate) module_loader: Option<crate::ModuleLoader>,
861}
862
863pub(crate) type Vm = Lua;
864
865/// What `on_error` notes for `call_handler` (S6-7).
866#[derive(Default, Clone)]
867pub(crate) struct HandlerWatch {
868    /// The thread the handler runs on (errors raised on others do not count).
869    thread: Option<ThreadRef>,
870    /// C Lua's C levels where the error escaping the handler was raised.
871    raised: Option<usize>,
872    /// For a round that may pass C Lua's 200th level: the handler's first frame and the
873    /// levels above the handler's call where the 200th falls.
874    cross: Option<(usize, usize)>,
875    /// The position of the Lua function whose metamethod call fell on the 200th level
876    /// (C Lua's "C stack overflow" there is raised at it).
877    pos: Option<String>,
878}
879
880/// Frames of the resume chain walked (`c_levels`) per unit of fuel. It was 16, as
881/// `charge_error` charges frames, while a global write left the fast loop; with global
882/// writes in it, plain code that writes globals (the cost tests' control) runs 2.8x as
883/// fast per unit, and 80 coroutines 1,900 frames deep under `xpcall` errors ran at 16x
884/// it (S5B-WALK-4's bound is 12x). At 5: PERF-RECAL. At 1:
885/// plain code kept getting faster in the fast loop (at 3 the test read up to 9.6x alone and
886/// 13.4x under the suite's load), most of it from a resume's walk (`resume_refused`), which
887/// still charged a unit per 16 frames; both walks are charged from this one rate.
888const RESUMER_FRAMES_PER_FUEL: usize = 1;
889
890/// C levels C Lua has in use where `xpcall`'s handler first runs from the top of a chunk,
891/// beyond ours (`call_handler`).
892const HANDLER_BASE_LEVELS: usize = 2;
893/// C Lua's limit of C levels (`LUAI_MAXCCALLS`).
894const C_HANDLER_LEVELS: usize = 200;
895/// C levels a resume adds in C Lua (`lua_resume` and the resuming library function).
896const RESUME_LEVELS: usize = 1;
897
898/// The least length `push_scratch` and `push_held` let a list grow to before compacting it.
899const COMPACT_MIN: usize = 1024;
900
901/// Drops repeated objects and plain values from `v[from..]`, keeping the first copy of each
902/// object, so every value that stays only moves down (marks into `v` above `from` still keep
903/// what was below them): how many are left from `from`.
904pub(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/// A cheap hasher for `compact_values`' keys (an object's kind, slot and generation, which
923/// a script does not choose): a splitmix64 finish over the words written. SipHash made the
924/// compaction cost about a hundred instructions per value kept.
925#[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        // One seed for everything random in the state (fixed by the host, or fresh).
965        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        // The machine's own objects are made with room to spare.
969        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        // Not `mix_seed(base, 3)`: that is invertible, and `math.random(0)` returns the
979        // generator's state word, so one call gave back `base` and with it the string and
980        // table hash seeds (S5GC-4).
981        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        // S5API-7: seeded as `math.randomseed` seeds it (C Lua's `setseed`, 16 values
1071        // discarded). The state set by hand before made the second value the same for
1072        // every seed.
1073        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    // ---- stack ----
1081
1082    #[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    /// Makes the running thread's stack at least `n` slots.
1095    #[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    /// `ensure_stack` when the stack is too short (out of line: the check is inlined).
1104    #[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    /// Makes the running thread's stack able to hold `n` slots (charged), without
1112    /// lengthening it.
1113    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    /// Room for more call frames, charged (S5GC-7: frame records were not, and at about
1127    /// 100 bytes against some 36 bytes of stack a level, coroutines parked deep in
1128    /// recursion held 285 MB under a 64 MB limit). The fast loop leaves growing to here.
1129    #[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    /// Makes the stack hold a full register window (256 slots) from `base`: registers are
1142    /// then indexed by their 8-bit number without checks. (The slack past the top is not
1143    /// counted against `stack_slots`.)
1144    #[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    /// The end of the running frame's registers (0 without one).
1164    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    /// Where a call made now (a metamethod, a native's callback) puts its function.
1169    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    // ---- memory ----
1175
1176    /// The error for memory the budget cannot give (after a full collection). Where C Lua
1177    /// would already have stopped with its own catchable error, that error: past its 200 C
1178    /// levels (metamethods, protected calls and resumes nested: "C stack overflow"), past its
1179    /// 1,000,000 stack slots, or, growing this thread's own stack (`own`), with that stack
1180    /// filling the budget (call depth is bounded by memory here: "stack overflow"); C Lua
1181    /// has no budget, so anything else failing then is the uncatchable memory
1182    /// limit. Nothing was allocated, so the cap holds; the unwinding frees the frames and
1183    /// the collector gives their room back. The error's message gets a little room past the
1184    /// cap (`on_error` takes it back): the budget is full, and C Lua's allocator would not be.
1185    #[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    /// Accounts for `n` bytes, collecting first when that passes the cap.
1199    pub(crate) fn charge_mem(&mut self, n: usize) -> Result<(), LuaError> {
1200        self.charge_room(n, false)
1201    }
1202
1203    /// `charge_mem` for this thread's own stack or frames (`memory_error`).
1204    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    /// The last resort when memory is full outside any call: the values held for the host
1227    /// (`held`) go too, and are collected. Whether there was anything to release.
1228    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    /// Runs `f` (an allocation), collecting and retrying once when memory is full.
1238    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    /// Records `name` (a string) as the chunk name of compiled chunk `f` and every
1253    /// function nested in it (`debug.getinfo`'s `source`). A walk over the prototypes, which
1254    /// the compile already paid for, in a loop (no native recursion).
1255    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        // A prototype marked already would not mark it again.
1266        if name.is_collectable() && self.heap.phase == crate::heap::Phase::Propagate {
1267            self.heap.mark(name);
1268        }
1269    }
1270
1271    /// Forgets the roots whose handles were dropped, giving back their charge (LR-17).
1272    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    /// Keeps a value a native made alive until the native returns.
1279    #[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    /// Keeps `v` in the running native's scratch. S5API-1: a native that calls back many
1287    /// times (`gsub` with a function, `sort`'s comparator, `load`'s reader, a host function
1288    /// calling `get` in a loop) kept every result and capture, mostly the same few objects,
1289    /// one uncharged slot each: native memory many times the memory limit, bounded only by
1290    /// fuel. Each time the running part doubles, repeats and plain values are dropped from
1291    /// it, so it stays within twice the number of distinct objects it keeps (themselves
1292    /// charged).
1293    #[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    /// Keeps `v` for the host until its next call (S5API-2: compacted as `push_scratch`
1304    /// does, so a host that reads the same values over and over between calls does not grow
1305    /// it without bound).
1306    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    /// A string (interned when short).
1315    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            // A library function that makes many strings pays for their interner walks as
1324            // it goes (S5GC-3), not once it returns.
1325            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    /// A table with room for `room` array slots, sized as Lua sizes it (`lua_createtable`
1335    /// or a constructor): `asize` array slots, `hash` fields (so `#` agrees).
1336    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    /// Bytes in a string value.
1356    #[inline]
1357    pub(crate) fn bytes(&self, s: StrRef) -> &[u8] {
1358        self.heap.str_bytes(s)
1359    }
1360
1361    // ---- fuel ----
1362
1363    /// Charges the probe steps of the table work done since the last instruction (see
1364    /// `table::PROBES`), for natives that look up many keys in one call.
1365    pub(crate) fn charge_probes(&mut self) -> Result<(), LuaError> {
1366        self.charge(crate::table::take_probes())
1367    }
1368
1369    /// Charges `n` steps of fuel. Library functions charge as they work, so the interrupt is
1370    /// looked at here too: a long `gsub` or `sort` stops as soon as the host asks.
1371    #[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    /// Stops the call for the host's interrupt or its deadline, without charging fuel: for
1381    /// natives that do much work per unit charged, between chunks of it (S6-5: the deadline
1382    /// was read only when a slice of fuel ran out, so one big charge read it once).
1383    #[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    /// Settles a long string key before a lookup walks the interner with it: its hash and the
1397    /// comparison with an interned string of that hash are done a piece at a time
1398    /// (`stdlib::COPY_PIECE`) between looks at the host's interrupt and deadline. (S6T-KEY: the
1399    /// first lookup of a 16 MiB key hashed it in one go, 6.4 ms past a 1 ms time limit;
1400    /// a lookup of an equal copy also compared all its bytes.) No fuel: the hash and the
1401    /// comparison were free before and are the same work, done earlier.
1402    ///
1403    /// The comparison is with the one interned string the key can equal (`Heap::key_best`,
1404    /// S6T-EQ), and what it found is used by the lookup or interning that follows, which
1405    /// so compares nothing again: a lookup compares at most one key's worth of bytes.
1406    #[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            // SEC-M11: the bytes compared are paid for. A miss records nothing, so a key that
1432            // differs from an interned one of its hash and length only at its end (made with
1433            // a seed the script knows) compared its whole length at every lookup, free: 4 MiB
1434            // for 4 units. A miss happens only between strings of one whole hash, so fuel
1435            // stays the same under any seed for a program not aimed at one.
1436            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    /// `heap.get_in` on table `t`, with a long key settled (`settle_key`) when the plain
1447    /// lookup misses: the same lookups otherwise, so the same probes and fuel.
1448    #[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            // No interned copy: in no table.
1457            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    /// The fuel in hand ran out (or the host may have interrupted): stops the call for the
1464    /// host's interrupt, its deadline or the end of the budget, or hands out the next slice
1465    /// of fuel. The budget stays exact: a call stops at the step where fuel and reserve
1466    /// together run out, whatever the slice.
1467    #[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    // ---- collector ----
1493
1494    /// Marks the roots: the work, the running thread's slots walked (S5B-WALK-1).
1495    fn mark_roots(&mut self) -> usize {
1496        let h = &mut self.heap;
1497        // The registry and its loaded-modules table first, so the globals are traversed
1498        // before them (the gray list is a stack): the libraries in the loaded table are
1499        // reached through the globals, as they were before that table existed, and the
1500        // modules only the loaded table holds right after the globals. (LIBS-1: traversed
1501        // before the globals, the loaded table reached the libraries in its own hash order,
1502        // a cycle's split into steps followed that order, and so fuel followed the seed far
1503        // more often. It still can in rare shapes, as it could before this table existed:
1504        // LIBS-8.)
1505        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        // Dropped roots forgotten, their charge given back (LR-17, as `prune_roots`).
1521        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    /// One step of collection, paid for by the allocation since the last.
1546    #[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    /// `gc_step` with a trace record of it: its slots, fuel and time (SEC7-G1).
1552    #[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            // (A step resumed after a pause is the same step.)
1566            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        // A step paused at the end of the host's poll goes on as it stood (SEC7-G1).
1579        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                // The test mode's collections are not the script's work: not charged (the
1592                // interrupt still stops one).
1593                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            // A step's budget follows the debt, so one big allocation (an array part
1600            // doubling to 2^21 slots, 32 MiB) made a step of millions of units, done in one
1601            // go past the call's fuel (40 ms). A step does at most what the call's fuel
1602            // still pays for; the rest stays owed (as debt, below) and is done by the steps
1603            // that follow (S6GC-2e).
1604            let full = self.heap.step_budget();
1605            // (Less what the objects made since the last step owe, charged with this step.)
1606            (born_step, full, full.min(self.gc_allow(self.heap.born.pending()).max(1)))
1607        };
1608        // The budget not given to a marking or sweeping step that did not finish its phase.
1609        let mut unspent = 0;
1610        // A suspended atomic phase's work done past the last call's fuel is this step's
1611        // (charged with it, as far as the call's fuel goes, the rest owed again: in the
1612        // step's own trace record, SEC8-F7).
1613        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                // Work done and not yet charged when the last cycle ended (a full collection
1617                // stopped for the fuel in its sweep: `charge_or_owe`) is charged, not dropped
1618                // (SEC8-F7): as far as this step's budget goes, the rest owed to the marking
1619                // steps after, as marking's own.
1620                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                // A suspended atomic phase goes on where it stopped.
1632                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                    // The objects made since the last step take their part of it, as they
1641                    // did as gray objects (`Born::step`; they are traversed in any case).
1642                    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                        // Paused at the end of the host's poll: nothing charged or settled
1651                        // yet; the resume goes on with it before any script runs, so it ends
1652                        // where it would have, charged as it would have been.
1653                        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                    // A marking step stopped by the interrupt or the deadline: its work is
1671                    // charged and the call stops (marking goes on at the next step).
1672                    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                // SEC7-G1: the atomic phase starts at a step at an instruction, where the call
1678                // can pause in it, not in a Rust function's (`collectgarbage('step')` among
1679                // them): the next step at an instruction starts it (marking has nothing left
1680                // to do meanwhile but what the writes since give it). In every call alike,
1681                // so where it runs follows the program alone.
1682                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                        // (Paused in it: it goes on with what it had.)
1693                        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                            // Paused at the end of the host's poll: nothing charged yet.
1708                            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                    // Stopped by the interrupt or the deadline: its work is charged and the
1731                    // call stops (the sweep goes on at the next step).
1732                    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            // (The inverse of `step_budget`: the bytes the budget not given covers.)
1746            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        // S5C-1: a step stops after the object that passes its budget, so how a cycle's
1750        // work splits into steps follows the order objects are reached, which follows
1751        // where keys sit in hash parts, which follows the seed. Each step's remainder was
1752        // dropped, so fuel differed by a unit or two between seeds; it is carried now.
1753        // (With what the objects made since the last step owe: COV-5, `heap::Born`.)
1754        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    /// Charges the collector's `units` of fuel as far as the call's fuel goes; what it cannot
1760    /// pay is owed (`owe_gc`), never dropped (SEC8-F7), and the call stops on its fuel limit.
1761    #[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    /// `charge_gc` past the call's fuel: `owed` units of fuel to the collector's next steps or
1771    /// collection (`gc_mark_over`, in work units), the call charged the `left` it had.
1772    #[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    /// A full collection's `work` (units; `charged` units of fuel of it paid already)
1783    /// charged as far as the call's fuel goes: past it, the call is charged what fuel it had
1784    /// and stops on its fuel limit, and the rest is owed (`gc_mark_over`, charged by the
1785    /// collector's next steps or collection). Dropped, as it was, the work done past the
1786    /// call's fuel (up to a piece of `FULL_GC_CHUNK` and an object) went uncharged, by an
1787    /// amount that followed where the pieces fell in the order objects are reached, so the
1788    /// seed: 5,766,987 units against 5,773,106 for seeds 1 and 7 over 3,300 calls of the G1
1789    /// reproducer at its memory limit (SEC8-F7).
1790    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        // (The remainder under a unit is owed too: the whole of the work is charged.)
1799        self.gc_mark_over += work % WORK_PER_FUEL;
1800        *charged += left;
1801        self.owe_gc(pay - left, left)
1802    }
1803
1804    /// The collector work the running call may still do: its fuel and reserve, less `done`
1805    /// (work not charged yet), in work units. Unlimited outside a call (a host `load`'s
1806    /// allocations collect unmetered).
1807    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    /// The running call's fuel and reserve: unlimited outside a call.
1812    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    /// An atomic phase stopped at the call's fuel (S6GC-2e) after `work` units not charged
1820    /// yet: the call is charged what fuel it had and stops on its fuel limit; the rest is
1821    /// owed by the call that resumes it (`resume_atomic`), so how the work splits between
1822    /// calls follows its total, never the order objects were reached in.
1823    /// (Stopped at the deadline instead, `kind` is `Time`: the same, the call stopping on
1824    /// its time limit with the fuel it has left, which `enter` reports: SEC8-F1, zeroed
1825    /// here, it read as the whole budget spent.)
1826    #[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    /// Why a collector step stopped part-way (`heap::Stop`): the interrupt, else the deadline.
1840    #[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    /// Finishes a suspended atomic phase before a call from the host runs any script code
1846    /// (a script must not run inside one): charged to this call, which stops on its fuel
1847    /// limit at once if the phase does not fit in it (it is suspended again).
1848    /// Whether the call at `func` with `nargs` arguments is `collectgarbage('step')` or
1849    /// `collectgarbage('step', 0)`: a basic step.
1850    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    /// The step of `collectgarbage('step')` called from Lua code, before the function runs
1856    /// (it answers from `gc_call_before`): what the function's own does, at a step that may
1857    /// pause (`gc_step_pausable`).
1858    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    /// `resume_atomic` at the entry of a call from the host, which may pause at the end of
1868    /// the host's poll (`Heap::poll_allow`): the call then is pending before it started
1869    /// (`pending_start`, SEC7-G1).
1870    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        // (What it owes is charged by the step: `gc_step_now`.)
1882        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    /// Clears the running thread's stack above what is live, so stale slots do not keep
1889    /// garbage alive. Only called between instructions, where the live part is the top
1890    /// frame's registers (and a pending variable-length result list), or from a library
1891    /// function, where it is the function's arguments and what it pushed. Returns the
1892    /// collector work: the whole stack, not the slots cleared (S5B-WALK-1). Where the live
1893    /// part ends follows when the atomic step comes, which follows the order objects are
1894    /// reached in, so counting the cleared slots made fuel follow the hash seed (COV-5).
1895    fn clear_dead_stack(&mut self) -> usize {
1896        // In a library function the live stack ends at its arguments and what it pushed (C
1897        // Lua's `L->top` then): its Lua caller's registers above the call are dead, so a
1898        // value only they hold is garbage, as in C Lua (weak tables see it go).
1899        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    /// Clears the whole stack when no call is running (back at the host).
1920    pub(crate) fn clear_idle_stack(&mut self) {
1921        if self.cur.frames.is_empty() && self.c_depth == 0 {
1922            // O(1), not a walk over the high-water length: after one deep recursion with
1923            // the collector stopped (so the stack never shrinks), every later call from
1924            // the host paid for clearing millions of slots. The capacity stays charged.
1925            self.cur.stack.clear();
1926            self.top = 0;
1927        }
1928    }
1929
1930    /// Gives back stack the running thread no longer uses (after deep recursion), as C
1931    /// Lua's collector does.
1932    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        // The next cycle starts when the heap grows by the pause (doubles by default), or
1962        // nears the cap.
1963        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    /// A complete collection (finishing the one in progress first).
1974    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    /// `full_gc` with a trace record of its pass: its slots, fuel and time (SEC8-G3).
1979    #[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        // Marking work steps did past their budgets and did not charge yet (`gc_mark_over`)
2005        // is charged here: dropped, the fuel followed where the steps before had stopped
2006        // in the order objects are reached, so the seed.
2007        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        // Finish the current cycle, then run a whole new one, charged as it goes so a big
2011        // heap's collection stops at the fuel limit or the host's interrupt (the next
2012        // collection carries on where this one stopped).
2013        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                        // (A piece no bigger than what the call can still pay: SEC8-F7.)
2033                        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                            // (Never here: a full collection does not pause, `pause_ok` is
2052                            // off in it. Its next pass goes on.)
2053                            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        // A full collection gives the table buffer pool back to the system too, every
2087        // free slot at a slab's end (SEC-M5), and the spare coroutine stacks.
2088        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    /// A collector step when one is due, else the born work charged (`Heap::gc_due`).
2101    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    /// A step that may pause at the end of the host's poll (`Heap::poll_allow`): only at
2106    /// an instruction of the call from the host itself, with no Rust function and no
2107    /// coroutine resumed from Lua under it, so the call can be resumed as it stands (a
2108    /// step inside a library function, `collectgarbage` among them, runs to its end).
2109    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        // A step ended past the end of the host's poll pauses the call there too: its work
2113        // all done and charged, nothing of it pending (steps of one object each never
2114        // reached a look inside them, and the script ran its whole fuel in one poll).
2115        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    /// What the objects made since the last step owe (COV-5, `heap::Born`).
2124    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    // ---- metatables ----
2131
2132    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    /// A binary event's metamethod: `x`'s, else `y`'s.
2165    #[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    /// The type name for the machine's messages, as C's `luaT_objtypename`: a table's or a
2172    /// userdata's `__name` (a string), else the plain type name. Other types' metatables
2173    /// (the strings' one) are not looked at.
2174    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    /// The type name for a library's "expected, got" messages, as C's `luaL_typeerror` (and
2179    /// `luaL_tolstring`) read it with `luaL_getmetafield`: the `__name` (a string) of any
2180    /// value's metatable, the strings' one included (`getmetatable("").__name = "S"` makes
2181    /// `math.floor("x")` say "got S"). Libraries that name a value with `luaL_typename`
2182    /// (`table.concat`, `gsub`'s replacement) use the plain `Value::type_name`.
2183    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            // Bounded: a huge `__name` must not make every message huge.
2192            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    // ---- raw table access ----
2199
2200    #[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        // Tables hold interned keys only.
2208        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        // The table the collector traverses in chunks: the entry overwritten is marked
2214        // first, the entry written after (S6GC-2e).
2215        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            // A resize stopped between pieces by the interrupt or deadline: the table is as
2229            // it was, and the call stops as at any other look.
2230            Err(SetError::Stopped(k)) => {
2231                if part {
2232                    self.heap.part_written(t.idx, held, Value::Nil);
2233                }
2234                // (What it did is charged: LR-29d, `Table::resumed`.)
2235                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        // Resizing is work: charged by the slots it copied.
2268        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    // ---- upvalues ----
2281
2282    #[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    /// The innermost to-be-closed value at or above `level`, taken off the list.
2335    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    /// Closes the running thread's upvalues at or above `level`.
2342    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    /// Closes upvalues and to-be-closed variables at or above `level` (normal exit).
2359    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    /// Closes at or above `level` while an error unwinds: each `__close` gets the error,
2368    /// and an error in one replaces it. Returns the error to go on with.
2369    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    /// Closes the to-be-closed variables of the protected call of frame `i` while an error
2382    /// unwinds to it (the error in its `dest + 1` slot), then makes the call return
2383    /// `false, error`. A Lua `__close` runs as a frame of its own that continues here when
2384    /// it returns (`Cont::ErrClosing`); an error in one replaces the error (`on_error`
2385    /// comes back here). Only limits stop it.
2386    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                // C Lua calls the missing method from C: no name for it, no position.
2413                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    /// An error a `__close` raised while an error unwinds to the protected call of frame
2439    /// `i`: through that call's message handler, if it has one (S5C-COR-3).
2440    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            // Checked when declared; gone now: calling it fails, as in C Lua.
2451            return Err(LuaError::msg("attempt to call a nil value (metamethod 'close')"));
2452        }
2453        self.call_nested(mm, &[v, err]).map(|_| ())
2454    }
2455
2456    // ---- calls ----
2457
2458    /// Starts a call of the value at `func` with `nargs` arguments above it.
2459    #[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    /// The callees of nested protected calls (`nested_pending`), one after the other
2475    /// (S5COR-6b). Each is called as a protected call's callee with the kind that completes
2476    /// it and every enclosing one (`Cont::Nest`), and gets the innermost one's handler; a
2477    /// value that cannot be called makes the innermost return `false, error`.
2478    #[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                // (A call that finished at once completed every level: `finish_call`.)
2494                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                    // Finished at once: a metamethod's caller (`call_meta`) reads the result.
2499                    self.complete_nest(nest, false)?;
2500                    return Ok(Called::Done);
2501                }
2502            }
2503        }
2504    }
2505
2506    /// The handler of the protected call whose frame was just pushed for `dest` (the
2507    /// callee's own frame: not that of a protected call it made in turn, which
2508    /// `pcall(xpcall, f, h)` puts on top).
2509    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    /// A protected call whose callee could not be called: `false` and the error (through
2518    /// `handler`) as its results at `dest`.
2519    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    /// One step of `precall`: may leave a nested protected call's callee to call next.
2530    #[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                // Each link moves the arguments: charged by their number.
2548                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            // Everything from here up was popped since the resume: this frame is new.
2592            self.cur.unrolled = self.cur.frames.len();
2593        }
2594        // Before the window is made: charging may collect, which may shrink the stack to
2595        // the frames it has.
2596        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            // Arguments are moved: work by their number.
2605            if nargs > 16 {
2606                self.charge(nargs as u64 / 8)?;
2607            }
2608            let nb = func + 1 + nargs;
2609            // (Parameters past one window are written here too: `np`.)
2610            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            // Missing parameters (SEC-M7: a function may have thousands).
2619            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        // A function `pcall` called directly sits on `pcall`, which has returned already:
2666        // it counts as an activation of its own (for error levels), and so does each
2667        // enclosing protected call it completes (`pcall(pcall, f)`).
2668        let under_pcall = if from_lua { 0 } else { pcall_levels(kind) };
2669        // (The protected calls' own slots are just below, outermost first.)
2670        // Its C levels: those protected calls, and the metamethod call it is (S5COR-6c).
2671        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        // Buffers the function counted against memory and dropped on the way out (SEC-M1).
2678        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        // The work the function recorded (`stdlib::owe`, `OutBuf`), paid on every exit:
2684        // an error after building output is not free. Nested calls took their own part.
2685        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        // A limit hit under this native (a host function that swallowed it) still stops
2698        // the call.
2699        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            // The common case: results straight into place.
2718            (Flow::Return, FrameKind::Normal) => {
2719                let n = self.rets.len();
2720                let want = if nres < 0 { n } else { nres as usize };
2721                // The results, or the nils up to what is wanted when more (SEC-M7).
2722                self.charge(list_fuel(n.max(want)))?;
2723                let need = func + n.max(want) + 2;
2724                // One result into a stack long enough already (`place_rets` does no more
2725                // then): stored here, without the call.
2726                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    /// A call from Lua code to a library function marked to run in place
2748    /// (`Func::Native::in_place`, `string::in_place`), made without `call_native`'s set-up:
2749    /// the same results, fuel, memory and stack. None when it cannot: `call_native` makes
2750    /// the call then, from the start (`in_place` leaves nothing done).
2751    #[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        // The stack `call_native` makes sure of, room for two results and the nils wanted
2755        // (more than 16 are paid: SEC-M7), and no limit hit pending (it stops the call).
2756        // (Off with the fast loop: the tests' reference path is `call_native`.)
2757        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        // (Its fuel is the fuel in hand before the call's step.)
2765        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        // The interner's walk past the fuel in hand: the next slice, or the stop, where
2775        // `new_str` would take it. (The collector's step after it is the call's.)
2776        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    /// `coroutine.yield(...)` called from Lua code: what `call_native` does for it, without
2785    /// the set-up it undoes before a yield is handled (`native_flow`): `yield_` only gathers
2786    /// its arguments and cannot fail, owes no fuel and calls nothing. (With a limit hit
2787    /// pending, `call_native` raises it: the caller takes that path then.)
2788    ///
2789    /// What `call_native` leaves behind for a native called from Lua code that returns
2790    /// `Flow::Yield`, item by item: `ntop`, `native_from_lua`, `native_name`,
2791    /// `native_event`, the scratch floor and `native_depth` are put back; the
2792    /// `native_stack` entry is pushed and popped; `c_calls` and `pcall_levels` are 0 from
2793    /// Lua code, so `protected_natives` does not move; `yield_` owes no fuel. The one
2794    /// lasting effect is `pending_event` taken (cleared): done here too.
2795    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    /// Copies a native's results (`rets`) to the stack from `func`, which is made `need`
2807    /// slots at least. S6-5: many results (`string.byte`, `table.unpack`) are written once,
2808    /// not over a stack first filled with nils, and the host's interrupt and deadline are
2809    /// looked at as they go: 3M of them ran 54 to 74 ms past a 20 ms time limit.
2810    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                // (A loop: results are few, and `copy_from_slice` is a call to memcpy.)
2816                for (d, v) in dst.iter_mut().zip(&self.rets) {
2817                    *d = *v;
2818                }
2819            }
2820            return Ok(());
2821        }
2822        // SEC-M15: the list is counted while the stack grows beside it, and not kept after
2823        // (kept, its capacity stayed outside the account for good: 14 MiB after a
2824        // `string.byte` of 900,000).
2825        // (Not debt: the collector's pace is as before.)
2826        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        // On a stop the stack is left as far as it was written: past the first chunk, so
2854        // past every frame's register window (filling the rest took 5 to 10 ms).
2855        stopped?;
2856        if self.cur.stack.len() < need {
2857            self.cur.stack.resize(need, Value::Nil);
2858        }
2859        Ok(())
2860    }
2861
2862    /// A native's error, given its position and name while the native is still the
2863    /// running function; the call state is put back.
2864    #[cold]
2865    fn native_failed(&mut self, e: LuaError, saved: (usize, bool, &'static str), (under_pcall, c_levels): (usize, usize)) -> LuaError {
2866        // A long result list an error cut short is not kept: past the call it was outside
2867        // the account for good (SEC7-1: 39 MiB after a stopped `table.unpack`).
2868        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        // The error's message handler (`xpcall`) runs where it was raised, as in C Lua:
2877        // this native is still a level for `debug.traceback` there (`handler_native`).
2878        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    /// What a native asked for besides returning to a plain call: results through a
2888    /// protected or continued frame, a protected call, a yield or a resume.
2889    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                // S5COR-6 / S5COR-6b: `pcall(pcall, f)` (or `xpcall`, either way round, any
2903                // depth). This protected call's callee gets one frame (or pending call) that
2904                // completes it and every enclosing one (`Cont::Nest`): `f` runs as in a
2905                // plain protected call, so it may yield, and the depth costs no native
2906                // stack. (The enclosing calls' slots are `dest`, `dest + 1`, ..., `func`.)
2907                let pkind = FrameKind::Protected { dest: func, wanted: -1, cont: Some(nest) };
2908                // `precall` calls it (not here: the callee may be a protected call too).
2909                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                // A protected call whose continuation a `Cont::Nest` cannot carry (none the
2914                // machine makes: `nest_of` packs every metamethod's): run as a nested call
2915                // of its own, which ends with its status and results as a plain return
2916                // that the outer call then wraps. Not yieldable inside.
2917                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                // A Lua function into a plain call: a frame in the native's place, which
2955                // sits on it (from Rust) for error levels.
2956                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                // Under `pcall` (`pcall(pairs, t)`): the same frame, protected, its results cut
2964                // to three when they arrive (so `__pairs` may yield there too).
2965                // S5COR-6c: under nested protected calls (`pcall(pcall, pairs, t)`), or a
2966                // protected call or `pairs` itself used as a metamethod, the same: the
2967                // frame's `Cont::Nest` cuts them to three, then completes the rest.
2968                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                        // (Never `three` already: that kind is a Lua `__pairs` frame's.)
2975                        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                // shortcut: a callable that is not a Lua function runs to completion, not
2995                // yieldable.
2996                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    /// C Lua's count of C levels in use here (`nCcalls`), for `call_handler`: nested library
3006    /// callbacks, each protected call (`pcall` is a C function there) and metamethod call on
3007    /// this thread and on the threads that resumed it, and each resume. Walks at most until the count passes
3008    /// C Lua's limit (only on the error path). Also returns the frames walked.
3009    fn c_levels(&self) -> (usize, usize) {
3010        // Frames C Lua calls from C: protected calls, and metamethods, `__close` and
3011        // `__pairs` (continued frames here).
3012        // (Frames a resume after a yield unrolled count no more, as in C Lua.)
3013        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            // A `pcall` of the resuming function itself (`pcall(coroutine.wrap(f))`) has no
3025            // frame of its own: it is the pending resume's kind.
3026            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    /// An upper bound, in constant time, of the C levels this thread's frames and its
3035    /// resumers hold (`c_levels` without the VM-wide terms), for a call at `func`: a frame
3036    /// holds at most three (a protected call, a metamethod, `pairs`) besides the protected
3037    /// calls a nested one completes (`Cont::Nest`), which are as many as the stack slots
3038    /// between its `dest` and `func`; those ranges are disjoint and below `func`. And frames'
3039    /// call slots rise one above the other, so there are at most `func + 1` of them.
3040    #[inline]
3041    fn c_bound_here(&self, func: usize) -> usize {
3042        4 * (func + 1) + self.cur.c_bound
3043    }
3044
3045    /// S6-7: the position C Lua gives the "C stack overflow" raised by the call at level
3046    /// `at` above a handler whose first frame is `from`: the Lua caller of the metamethod
3047    /// frame there. A library function calling back (`sort`'s comparator, `__tostring` from
3048    /// `tostring`) is a level of its own, at the frame its call made (`native_stack`); its
3049    /// call falling on the 200th is raised in it, with no position.
3050    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    /// Calls `xpcall`'s handler on an error value (non-yieldable). S5COR-5: as in C Lua, the
3072    /// handler stays in place while it runs, so an error it raises is handled by calling it
3073    /// again with that error (C Lua's `luaG_errormsg` runs inside the raise); its first
3074    /// result becomes the error. Ours gave "error in error handling" at the first one. A
3075    /// handler that keeps failing gets "C stack overflow" from C Lua's 200 C levels on and
3076    /// stops at 220 with "error in error handling" (LUA_ERRERR): the same counts here,
3077    /// from the native levels already in use. A loop, not recursion: the native stack does
3078    /// not grow with the chain.
3079    fn call_handler(&mut self, h: Value, err: Value) -> Result<Value, LuaError> {
3080        // The native that raised this error, if one did (the error value tells a stale
3081        // record from the error being handled).
3082        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        // (A plain error in the handler is raised one level above this: the handler's.)
3100        let base = level;
3101        // Past C Lua's limit (protected calls nested deeper than its 200 C levels, which C
3102        // Lua refuses and RemedyLua runs: the superset rule), the handler runs as it would at
3103        // C Lua's last level that still runs one: once with the error, then "C stack
3104        // overflow", then "error in error handling". It was never called there.
3105        let mut level = level.min(C_LEVELS - 1);
3106        // S5B-WALK-4: the walk goes through the frames of every coroutine that resumed this
3107        // one, which `charge_error` (this thread's frames) does not see: 150 nested
3108        // coroutines 1,900 frames deep made each `xpcall` error in the innermost walk 285,000
3109        // frames, 440x plain code per unit of fuel. A unit per frame (`RESUMER_FRAMES_PER_FUEL`).
3110        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                // (Positioned when the call at the 200th was a metamethod's from Lua code.)
3117                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            // (The handler's first frame goes where the next frame would.)
3126            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            // C Lua calls the handler again where the error was raised: one level above
3134            // the handler's for a plain one, more inside a metamethod, a library callback
3135            // or a `__close` (S6-7: 216 calls against C Lua's 109 for an `__index` error).
3136            let next = level + self.handler_raise.raised.map_or(1, |r| r.saturating_sub(base).max(1));
3137            // A call at C Lua's 200th level, the handler's or one inside it, raises "C stack
3138            // overflow" there instead of running, and the handler is called next at the
3139            // 201st, which is `C_LEVELS` here (as for a plain error): a step past it lands on it.
3140            level = if level < C_LEVELS && next > C_LEVELS { C_LEVELS } else { next };
3141        }
3142    }
3143
3144    /// Copies `n` results from `src` to `dst`, adjusted to `wanted` (-1: all, setting the
3145    /// top).
3146    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        // The values moved, or the nils written up to what the caller wants when more
3149        // (SEC-M7: a call adjusted to 30,000 results wrote them all for one unit).
3150        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    /// Places a finished call's results by its kind.
3168    /// `apply_cont`: a `pcall` used as a metamethod passes its status on through its
3169    /// continuation (false when the caller reads the result itself, as `call_meta` does
3170    /// for calls that finish at once).
3171    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                // `pcall(pairs, t)` with a Lua `__pairs`: its results cut to three.
3184                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                    // Enclosing protected calls are completed however this one finished;
3195                    // the metamethod's continuation only when asked.
3196                    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                // `pairs` used as a metamethod (`levels` 0, `three`).
3203                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    /// Completes the protected calls a `Cont::Nest` carries, the innermost one's status and
3219    /// results from `dest + levels` up to `top`, then (`apply_then`) gives the metamethod's
3220    /// continuation the outermost one's first result. A caller that reads that result
3221    /// itself (`call_meta`, for a call that finished at once) passes false.
3222    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                // A type error after a `__concat` returned names its operand, as when the
3255                // instruction itself raises it.
3256                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    /// Closes upvalues and to-be-closed variables down to `level` on a normal exit. A
3281    /// `__close` written in Lua runs as a frame (so it may yield), continuing here when it
3282    /// returns. True when everything finished at once (and nothing changed the frames).
3283    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            // Not callable (gone, or never a function): the message names the event, with
3288            // a position, as C Lua's on a normal exit.
3289            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    /// Returns from the top frame with `n` values from `src`.
3315    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            // Results stay in place: `__close` calls go above them (they may be an open
3322            // list past the frame's registers); the return finishes after the last one.
3323            self.close_async(base, AfterClose::Return { src, n }, src + n)?;
3324            return Ok(());
3325        }
3326        self.finish_return(src, n)
3327    }
3328
3329    /// The rest of a return, once everything is closed.
3330    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        // Not a callback's return to a native body (`nny`: SEC7-V1, `wrap(table.sort)`).
3334        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    /// Calls `f` with `args` from Rust and runs it to completion: the results.
3341    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        // The results stay reachable from the native's scratch.
3345        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    /// Goes on with the call from the host that paused at a collector step: the step first,
3354    /// to its end (or the poll's), then the call's frames, as if it had not paused.
3355    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        // (Paused between steps: no step to go on with.)
3365        let step = if self.gc_pending.is_some() { self.gc_step_pausable() } else { Ok(()) };
3366        // Ended by its step (a limit, not a pause): the instruction set to run again does
3367        // not, so its unit is charged again and what it was set to skip goes.
3368        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            // The paused instruction runs again without the step it took; with no step due
3379            // now it never looks.
3380            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    /// Drops the call from the host that paused at a collector step: the step finished
3401    /// first (uncharged: the call is gone), so the heap is as after any step, then the
3402    /// frames dropped as a limit drops them.
3403    pub(crate) fn cancel_nested(&mut self) {
3404        if self.pending_start.take().is_some() {
3405            // Paused before it started: its step finished (uncharged), nothing else to drop.
3406            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            // (`pause_ok` is off: it runs to its end.)
3418            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    /// `call_nested` for the first result only (nil when there is none), without a vector.
3431    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    /// Calls `f` from Rust: its results are left at `pos..top`; `keep`: a native is
3441    /// running, whose scratch must keep them reachable.
3442    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            // C Lua's message for its C levels (`luaE_checkcstack`), positioned as there: at
3447            // the running Lua function, none when a library function is running (LIBS-5:
3448            // a `require` cycle said "t:2: stack overflow (too many nested calls from
3449            // library functions)" where C Lua says "C stack overflow").
3450            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        // A Lua function's frame straight away: all `precall` comes to for one.
3474        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                // The fast loop first, as `run`'s first step would take it (the frame was just
3484                // pushed with its window): a callback it finishes needs no `run` at all.
3485                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    /// How a call from Rust ended (`call_nested_at`, `resume_nested`); one that paused at a
3503    /// collector step keeps its frames (`pending_call`).
3504    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                // Close while the erroring frames are still there (their calls go above).
3521                let ev = self.close_with_error(pos, ev);
3522                self.cur.frames.truncate(bdepth);
3523                Err(LuaError::Value(ev?))
3524            }
3525        }
3526    }
3527
3528    // ---- errors ----
3529
3530    /// The source position of the running Lua function: `chunk:line:` or empty.
3531    pub(crate) fn where_(&self, level: usize) -> String {
3532        // How many more activations to pass; set by the topmost one (outside any Rust
3533        // function, level 1 is the running Lua function itself). S6-1: only the activations
3534        // above the level asked for are walked (S6-2: a run of Rust ones in one step).
3535        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    /// The activations of thread `ts` (ref `tref`), oldest first, as C Lua's levels are
3556    /// (`debug.traceback` and `debug.getinfo` walk them): its Lua frames, and the Rust
3557    /// functions it is in where they were called. `err_closing` is `Lua::err_closing` for
3558    /// the running thread (None for another). `extra` is a native that is gone from
3559    /// `native_stack` but is still a level (the one that raised the error a message handler
3560    /// handles): its depth, slot, and the protected calls it sat on.
3561    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    /// How many activations [`Lua::activations`] lists (walked by runs, without listing them).
3586    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    /// Walks the activations of thread `ts` (as [`Lua::activations`] lists them) from the
3605    /// newest, in runs, until `visit` says to stop. Each frame, and each run of Rust
3606    /// activations, is one step: an error's position (S6-1) costs only the activations
3607    /// above the level it asks for.
3608    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        // The natives in progress on this thread, oldest first: their depth, and their run
3618        // of activations (the protected calls each sat on, then itself) by slot.
3619        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            // Before the natives called later at its depth (the handler, if a native), after
3629            // the protected calls it sat on.
3630            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        // S5C-COR-1: a `__close` run while an error unwinds to the protected call of frame
3634        // `lo` runs above the frames being unwound (`Cont::ErrClosing` at `hi`, or a native
3635        // or callable `__close` called with `hi` frames: `err_closing`); C Lua runs it once
3636        // they are gone, on `pcall` itself. Those frames, and what they called, are not
3637        // levels.
3638        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        // The protected calls frame `f` sits on, by slot, outermost first; and `pairs`, newer,
3641        // under a Lua `__pairs` (S5COR-6c: `pcall(pairs, t)` was a level short). Visited
3642        // newest first: true to stop.
3643        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            // The natives called at depth `i` sit just below frame `i`.
3655            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                        // The protected call's callee is gone; `pcall` (a Rust activation)
3665                        // stays.
3666                        if pcalls(f, false, &mut visit) {
3667                            return;
3668                        }
3669                    } else {
3670                        if visit(Run::Lua(i)) {
3671                            return;
3672                        }
3673                        // A frame Rust started (`pcall`, a resume) sits on that Rust function;
3674                        // a metamethod or `__close` the machine called (a continuation, or
3675                        // `err_closing`'s callable `__close`, S6-6) does not.
3676                        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            // The Rust functions called at this depth, newest first: gone with the frame
3693            // that called them (the native running on top, and a native `__close`, never
3694            // are).
3695            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    /// The prototype `p`.
3715    #[inline]
3716    pub(crate) fn proto(&self, p: u32) -> Option<&Proto> {
3717        self.heap.protos.get(p)
3718    }
3719
3720    /// `chunk:line: ` of a frame where it stands.
3721    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    /// Charges making an error message: the text and its position (a walk over the call
3729    /// stack), and the bytecode read to name variables (`debug::take_work`).
3730    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    /// Turns an error into the value scripts see.
3736    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        // (A `memory_error`'s room is for this message only; with no room even for it, the
3752        // memory limit.)
3753        self.heap.mem.headroom = 0;
3754        v.map_err(|e| if e.limit().is_some() { e } else { LuaError::Limit(LimitKind::Memory) })
3755    }
3756
3757    /// `bad argument #n to 'f' (msg)`, with the function named as its call site names it.
3758    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    /// [`Lua::arg_error_value`] for a message that quotes a script's bytes as they are.
3763    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    /// An error with a message that quotes a script's bytes as they are, after the running
3779    /// function's position (as `LuaError::Msg` gets it). S5COR-3: messages are Rust strings
3780    /// elsewhere, so a byte that is not UTF-8 (an `é` cut in half in `string.pack`'s format)
3781    /// came out converted, where C Lua shows the byte itself.
3782    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    /// The running native's name as the calling code names it, and whether it was called
3797    /// as a method.
3798    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        // Called as a metamethod: C Lua names the event (`funcnamefromcode`).
3815        if let Some(event) = self.native_event {
3816            return (event.into(), false);
3817        }
3818        // A library's internal helper (an iterator `ipairs` or `gmatch` returns) has no
3819        // global name: C Lua's `pushglobalfuncname` finds none and says `?`.
3820        if self.native_name.ends_with("_aux") {
3821            return ("?".into(), false);
3822        }
3823        (self.native_name.to_owned(), false)
3824    }
3825
3826    /// Adds what an operand was to a type error raised by an instruction.
3827    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    /// Notes the running thread's frames for a traceback ([`Lua::take_traceback`]).
3854    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    /// The traceback of the last error that left the machine (then forgotten): empty if
3869    /// none did.
3870    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    /// Handles an error in the loop with boundary (`bthread`, `bdepth`): unwinds to a
3883    /// `pcall` (Ok: go on running), kills coroutines it escapes from, or returns it.
3884    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            // S6-7: under a message handler, where this error was raised, unless something
3907            // catches it (the first, deepest raise of an error that escapes).
3908            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                    // (The walk charged as `call_handler`'s is: once a round, uncharged, a
3914                    // handler failing under a deep resume chain ran at 157x plain code per
3915                    // unit of fuel, S6R-6.)
3916                    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                // The handler stays: an error in a `__close` run below goes through it too,
3936                // as in C Lua (`luaD_closeprotected` closes with the handler in place),
3937                // S5C-COR-3. It said the original error only.
3938                // `__close` handlers run while the erroring frames are still there, so their
3939                // calls go above every pending to-be-closed slot; a Lua one runs as a frame
3940                // of its own (it may yield, as in C Lua), and the error waits in the slot
3941                // where it is returned (`dest + 1`, below the frames being closed).
3942                self.set_st(dest + 1, err);
3943                // The protected call's outcome may go to a metamethod's continuation (`pcall`
3944                // as `__concat`), which can raise an error of its own in the frame below: that
3945                // one unwinds again, from there (S5COR-8: it went past every `pcall`).
3946                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                // A coroutine that dies does not unwind: its to-be-closed variables wait for
3956                // `coroutine.close`, except under `wrap`, which closes it at once.
3957                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                    // LIBS-4: as in C Lua, a coroutine that died by an error keeps its frames
3976                    // (and the function that raised it) for `debug.traceback` and
3977                    // `debug.getinfo`, until `coroutine.close` or the collector frees it.
3978                    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                    // `wrap` propagates the error into its caller.
3990                    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                            // A copy of the message at each `wrap` it crosses: paid
3996                            // (S6GC-1: a 4 MiB message ran at 300x plain code per unit).
3997                            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                        // The wrap function was called by `pcall`: caught here.
4005                        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    /// An error raised while `on_error` completed a protected call (by the continuation its
4038    /// outcome went to): its value, to unwind again; a limit stops everything up to
4039    /// `bthread`.
4040    #[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    /// After a limit: kills the coroutines between the running one and `bthread`.
4051    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    // ---- coroutines ----
4066
4067    /// Makes `to` the running thread, storing the current one in its slot.
4068    /// The fast loop's context (see `ctx_epoch`), for the running thread with no stop
4069    /// depth (`run` sets both per frame).
4070    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        // The running thread's slot holds an empty placeholder: `to`'s state comes in,
4091        // the running one goes to its own slot, the placeholder to `to`'s. Boxed, these
4092        // are pointer swaps (moving the states themselves was most of a switch's cost).
4093        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    /// Near C Lua's limit (the bound reached it), the exact count: what C Lua does with
4109    /// this resume of `co`, and the outcome when it does not run it (`do_resume`). At 200
4110    /// levels it refuses and the coroutine stays as it was. At 199 the resume goes ahead,
4111    /// taking the 200th, and a coroutine not yet started then fails in the call of its
4112    /// body (`ccall`'s check) before any of it runs: it dies by an unpositioned "C stack
4113    /// overflow", which the resume returns (or `wrap` raises) as from a coroutine that
4114    /// failed. The same outcome here, without switching to it.
4115    #[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        // (The same walk as `call_handler`'s, charged the same.)
4130        self.charge((walked / RESUMER_FRAMES_PER_FUEL) as u64)?;
4131        // The resumer's count in C Lua (`from`'s `nCcalls`): `c_levels` is the count a
4132        // message handler's call reaches, one past the native running it and one past the
4133        // `lua_resume` that `coroutine.resume` or `wrap` is to C Lua.
4134        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                // (`wrap` closes a coroutine that failed, as `auxwrap` does: no error kept.)
4147                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        // LR-3: C Lua's `lua_resume` starts the thread's C levels from the resumer's and
4190        // refuses at its limit, before the coroutine runs: "C stack overflow" with no
4191        // position, which `coroutine.resume` returns and `wrap` raises (positioned at its
4192        // caller when that is a Lua function, as `auxwrap`'s `luaL_where(L, 1)`). A `pcall`
4193        // of the resuming function is a C level of its own there. Ours stopped at 200 nested
4194        // resumes whatever else was in use, and put the position on.
4195        // The exact count walks the frames of this thread and its resumers (`c_levels`), so
4196        // a resume first takes an upper bound in constant time and walks only when that
4197        // reaches the limit (charged as `call_handler` charges the walk).
4198        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        // Its first resume maps its register window (LR-8); charged once the resume is
4208        // known to run, so a refused resume leaves the coroutine as it was.
4209        if self.heap.threads.get(co.idx).is_some_and(|t| t.fresh) {
4210            self.charge(COROUTINE_COST)?;
4211        }
4212        // The resumed thread's bound: the resume's level, this thread's and its resumers'.
4213        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                // A native body's error kills the coroutine here, as the loop would, not in
4232                // the resumer's `pcall` with the coroutine still running (SEC7-V1).
4233                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    /// A buffer taken from `rets` goes back (emptied) when `rets` has none, so a switch
4248    /// does not allocate a new one each time.
4249    fn give_back_rets(&mut self, mut v: Vec<Value>) {
4250        // Not a long one: kept, it was outside the account for good (SEC-M15).
4251        if self.rets.capacity() == 0 && v.capacity() <= crate::stdlib::NATIVE_CHUNK {
4252            v.clear();
4253            self.rets = v;
4254        }
4255    }
4256
4257    /// The running coroutine's body returned: its results go to the resumer.
4258    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        // Its stack is not needed any more: the next coroutine's (LR-8).
4265        self.retire_stack(me);
4266        r
4267    }
4268
4269    /// Switches to the resumer with `vals` as the resume's results.
4270    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        // The values are counted while the stack grows beside them (SEC-M15).
4279        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    /// Runs on `co`'s stack for a moment (`coroutine.close`), without letting it yield.
4294    /// The closing thread is `normal` meanwhile, as a resumer is (S6: it said `running`, and
4295    /// closing it from a `__close` there said "cannot close a running coroutine").
4296    /// Returns its status, for [`Lua::swap_out_after_close`].
4297    ///
4298    /// Its handlers are called above what is live on its own stack (`parked_live`), not
4299    /// above the closer's: `ntop` is the closer's while `coroutine.close` runs, and a
4300    /// handler called there (LR-8) grew every closed coroutine's stack to the closer's
4301    /// height, a copy of 240 KiB per `coroutine.close` from a coroutine 15,000 slots deep
4302    /// (15x plain code per unit of fuel).
4303    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    /// Back from [`Lua::swap_in_for_close`], to `me`, with the status and `ntop` it had.
4312    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    /// Back to the resumer; returns where its resume call wants results.
4320    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        // Raised from the yield itself, which has no position.
4332        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        // A coroutine with no resumer runs its `__close` handlers for `coroutine.close`:
4336        // C Lua's message for any coroutine that cannot yield (S5GC-6).
4337        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    /// A new coroutine running `f`, on a spare stack when there is one (`retire_stack`).
4347    ///
4348    /// LR-8: a coroutine's first resume grows its stack to a register window (about 4.5
4349    /// KiB), a `__close` handler run by `coroutine.close` to twice that, and a closed or
4350    /// finished coroutine kept it until the collector freed the thread. With the collector
4351    /// stopped (or a long pause) every new coroutine touched about 10 KiB of fresh pages
4352    /// nothing reused: making, resuming and closing one ran at 10x to 20x plain code per
4353    /// unit of fuel on a process's first runs (a coroutine closed from one 15,000 slots
4354    /// deep, more: `swap_in_for_close`). A closed or finished coroutine's stack is given to
4355    /// the next one now: about 860 bytes a coroutine stay fresh (C Lua: 960), and with the
4356    /// collector stopped making and closing one costs what it does with it running. One
4357    /// that is never closed nor finished (a `wrap` left suspended) still maps a window,
4358    /// 9x plain code per unit of fuel with the collector stopped, whose cycles are what
4359    /// paid for it otherwise: the window is charged at its first resume (`COROUTINE_COST`).
4360    pub(crate) fn new_coroutine(&mut self, f: Value) -> Result<ThreadRef, LuaError> {
4361        // A thread made and later swept (`wrap` paid nothing for it).
4362        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            // Its first resume makes the room it needs.
4369            None => Vec::with_capacity(1),
4370        };
4371        stack.clear();
4372        stack.push(f);
4373        let st = ThreadState { stack, fresh: true, ..ThreadState::default() };
4374        // `f` is the caller's argument, so a collection here keeps it.
4375        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    /// Takes the stack of `co`, a coroutine that was closed or finished, for a new
4382    /// coroutine to reuse (`new_coroutine`); its frame records go back to the system. Only
4383    /// a dead thread holding nothing on its stack (no frames kept for a traceback, no
4384    /// open upvalues, no pending to-be-closed variables) gives it up.
4385    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        // (A kept stack goes back into `used` as slack: resident, counted, not live.)
4403        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    /// Gives the spare coroutine stacks back to the system.
4415    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    // ---- the loop ----
4422
4423    /// Runs until the thread `bthread` is back to `bdepth` frames.
4424    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    /// The execution loop. Lua-to-Lua calls and returns switch frames here, without
4434    /// leaving; it returns when the thread `bthread` is back to `bdepth` frames. Errors
4435    /// leave the failing frame's `pc` (and the fuel) saved.
4436    ///
4437    /// Registers are a 256-slot window of the stack (`ensure_window` keeps it in bounds),
4438    /// indexed by their 8-bit numbers without checks; fuel lives in a local, written back
4439    /// before anything that looks at it.
4440    #[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        // The width of the fast loop that just switched frames and stopped (in the frame
4447        // `'reload` then picks up). Stopped in a frame of its own width, it stopped at the
4448        // instruction it cannot run, so that one runs in full without entering it again
4449        // for nothing (natives right after a call or return paid two entries).
4450        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            // Register 0; `base` is the same but for an instruction after `Window`.
4459            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            // A call that may charge fuel or switch frames: state saved before, fuel back
4478            // after.
4479            macro_rules! call {
4480                ($e:expr) => {{
4481                    save!();
4482                    let r = $e;
4483                    fuel = self.fuel;
4484                    r
4485                }};
4486            }
4487            // A collector step at an instruction (`gc_due_step`). Paused at the end of the
4488            // host's poll, an instruction that steps before its work (`before`: nothing done
4489            // yet) runs again on resume, without the step (`due_skip`) and with its fetch's
4490            // unit given back; one that steps after its work goes on with the next.
4491            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            // `t!(call!(..))` for a call that may pop the running frame (a return, a tail call):
4519            // its state was saved before, and on an error the frame on top may be its caller,
4520            // whose own position must stay (S5COR-11: saving again wrote the returning
4521            // function's position into the caller, so an error a metamethod's continuation
4522            // raised there named the wrong line).
4523            macro_rules! tpop {
4524                // (Both uses reload the frame, and the fuel with it, right after.)
4525                ($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            // After a call that pushed a frame (or switched threads): state was saved by
4545            // `call!` before it.
4546            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            // Arithmetic with a fast path for numbers and the general path (strings,
4576            // metamethods, errors) otherwise.
4577            // Arithmetic: numbers by the shared rules (`fast::arith`), else the general
4578            // path (strings, metamethods, errors).
4579            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            // `arith!` on two registers, or on a register and a constant.
4597            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            // The fast loop's context: made again only when what it copies changed
4609            // (`ctx_epoch`); the running thread and the stop depth are this frame's.
4610            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            // Whether the next instruction is tried in the fast loop (see `fast_tried`).
4617            let mut fast_now = self.fast && fast_tried.take() != Some(wide);
4618            loop {
4619                // The common cases run in the fast loop; it stops at the first instruction
4620                // it cannot finish, which runs below in full.
4621                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                // One step, plus the probe steps of the instruction before (see
4637                // `table::PROBES`; the fast loop charges them at the same point).
4638                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                    // The next slice of fuel, or the stop (fuel, interrupt, deadline).
4644                    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                    // The next instruction, its registers from `frame_base + off`.
4659                    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                        // (The source counts from the window: `base` is `frame_base` unless a
4677                        // `Window` came first.)
4678                        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                        // Results adjusted to a count past 16 bits: work by the number filled.
4696                        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                        // SEC-M7: up to 65,536 registers in one instruction (frames past 255
4715                        // registers): paid past 16, as every list of values is.
4716                        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                        // (Through `call!`, as `SetTableK`: a rehash charges fuel, and the
4749                        // count here must not be written back over it. PERF-SEC-1.)
4750                        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                        // (The fast loop finds methods; here, the general lookup, which
4796                        // charges each `__index` link as the fast loop does.)
4797                        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                                // Which operand failed: concat reports it relative to `a`.
4911                                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                        // As `x + i` (or `x - -i`, whose metamethod and message see `-`).
4943                        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                        // Written with the immediate on the right (`<`, `<=`) or on the left.
4985                        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                        // A Lua function: a new frame, run here. A library function: called
5080                        // straight away.
5081                        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                                // `collectgarbage('step')`: its step first, here, where the
5092                                // call can pause at the end of the host's poll (in the
5093                                // function it could not); paused, the call runs again on
5094                                // resume, its step done, as an instruction that steps before
5095                                // its work does (`gc_step_at!`).
5096                                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                        // A callable object: its `__call` handler goes first, and the call stays
5139                        // a tail call when the handler is a Lua function.
5140                        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                        // The common case: nothing to close, few results, back to a Lua caller or
5174                        // to Rust above another frame (a callback: `finish_return` does no more
5175                        // then; under the last frame a coroutine finishes).
5176                        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                            // (More than 16 wanted is paid: `move_results`, SEC-M7.)
5186                            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                        // C Lua names the callee of this call "for iterator" whatever it is.
5256                        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                            // The table the collector traverses in chunks (S6GC-2e): the
5279                            // entries overwritten are marked first, those written after.
5280                            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                            // The values straight from the stack (a copy would be an allocation
5287                            // per constructor).
5288                            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                            // (The fuel the list's growth may take, refused past it: LR-29d.)
5296                            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                                // (A resize stopped by the interrupt or deadline, or refused
5311                                // for the fuel left: that limit.)
5312                                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                        // Upvalues from registers count from the frame's base.
5340                        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                            // SEC-M7: a fixed count up to 65,535, paid past 16 as the open one.
5353                            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    /// `t[key]` for a constant string key through the instruction's slot hint, when the
5385    /// table has it (or has no metatable to ask): None means "take the general path".
5386    #[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    /// `t[key] = val` in place when the key exists and nothing intercepts (no metatable, or
5403    /// the field is there already): true when done.
5404    #[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        // The new frame takes the old one's place, unrolled or not (`ThreadState::unrolled`).
5428        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                    // Its upvalues (S5B-WALK-5; `charge` does not collect).
5455                    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                // Not enough memory: collect (or stop at the limit), then make it.
5462                Err(Some(size)) => {
5463                    self.charge_mem(size)?;
5464                    self.heap.mem.release(size);
5465                }
5466            }
5467        }
5468    }
5469
5470    /// Numeric `for` preparation: false to run the loop, true to skip it.
5471    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                // Exactly, through the integer first (a numeric string included).
5480                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    // ---- metamethod paths ----
5537
5538    /// Puts `f` and `args` at slot `pos`, to be called there.
5539    #[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    /// `precall` of a metamethod for event `ev` (named in the callee's messages).
5550    #[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    /// Calls metamethod `f` with `args` for an instruction: Some(result) when done now
5566    /// (a Rust function), None when a Lua frame was pushed (its result goes by `cont`).
5567    /// `ev` names the metamethod when `f` cannot be called (C's `funcnamefromcode`).
5568    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            // A Lua frame (or `pcall` of one) delivers its result through `cont`; so does a
5581            // resumed or yielding coroutine (`wrap`, `coroutine.yield` as a metamethod).
5582            Called::Lua | Called::Switched => Ok(None),
5583            Called::Done => Ok(Some(self.st(pos))),
5584        }
5585    }
5586
5587    /// Indexing `t`, which is not a table and has no metamethod, at link `loop_n` of a chain.
5588    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    /// `t[k]` with metamethods.
5598    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            // Each link of a chain is a step, and so is its lookup's probing (S5GC-1).
5627            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    /// `t[k] = v` with metamethods: true when done now, false when a Lua `__newindex`
5634    /// frame was pushed.
5635    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            // Each link of a chain is a step, and so is its lookup's probing (S5GC-1).
5666            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    /// `t[k]` from Rust (nested calls for metamethods).
5673    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                    // The native reading it may hold it across allocations.
5681                    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            // Each link of a chain is a step, and so is its lookup's probing (S5GC-1).
5700            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    /// `t[k] = v` from Rust.
5707    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            // Each link of a chain is a step, and so is its lookup's probing (S5GC-1).
5736            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    /// A number from a value, converting strings (Lua's arithmetic coercion).
5743    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    /// `tonumber`, charging fuel for the length of a string it parses: a unit per 16 bytes,
5752    /// what the slowest numerals cost (a long fraction or digit run takes the float
5753    /// parser's big-number path; at a unit per 64 bytes they ran 4 to 5x plain code: LR-22).
5754    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    /// Fuel for comparing or copying `n` bytes.
5765    #[inline]
5766    pub(crate) fn charge_bytes(&mut self, n: usize) -> Result<(), LuaError> {
5767        self.charge(crate::heap::bytes_fuel(n))
5768    }
5769
5770    /// An integer from a value (exact floats and numeric strings convert).
5771    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    /// Arithmetic with coercion and metamethods.
5781    pub(crate) fn arith(&mut self, op: ArithOp, x: Value, y: Value, cont: Cont) -> Result<Option<Value>, LuaError> {
5782        // A string operand: whatever the string metatable says (its own `__add` … is done
5783        // here directly; a script's replacement is called).
5784        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            // With a string operand the work happens in the string library's metamethod,
5805            // whose errors carry no position.
5806            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    /// Whether `v` is a string whose arithmetic goes through the string library's
5838    /// metamethods (as in Lua 5.4, when the string library is open).
5839    fn string_arith(&self, v: Value) -> bool {
5840        matches!(v, Value::Str(_)) && self.string_meta.is_some()
5841    }
5842
5843    /// Whether `f` is one of the string library's own arithmetic metamethods.
5844    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    /// The string library's arithmetic, called directly (`getmetatable("").__add(a, b)`).
5850    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    /// The string library's arithmetic metamethod when coercion failed (`trymt`): the
5858    /// second operand's own metamethod, or "attempt to add a 'string' with a 'table'".
5859    /// C Lua calls that metamethod from the string library (`lua_call`): it is not
5860    /// yieldable, error levels count the library function, and a value that is not
5861    /// callable is reported without a position.
5862    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    /// `#x` with `__len`.
5906    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    /// `#x` from Rust.
5921    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    /// Whether two strings are equal (comparing long strings' bytes is charged).
5944    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        // A long pair a piece at a time, each a look at the deadline (S6T-EQ: two 16 MiB
5951        // strings were compared in one go, 1.5 ms).
5952        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    /// `x == y` from Rust.
5967    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            // `LUA_COMPAT_LT_LE` (stock 5.4 builds): `a <= b` as `not (b < a)`.
5988            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    /// `x < y` from Rust.
6013    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    /// Concatenates `n` values from slot `a` into slot `a`: true when done, false when a
6038    /// Lua `__concat` frame was pushed.
6039    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                // The longest run of strings and numbers ending at the top, joined at once.
6046                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                // One buffer of the exact size, one copy of each part: a short result is
6060                // built on the stack and interned; a long one is charged first, then its
6061                // buffer becomes the string.
6062                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    /// The exact length of a string or number as `..` writes it.
6102    fn str_len_of(&self, v: Value) -> usize {
6103        stringable_len(&self.heap, v)
6104    }
6105
6106    /// Writes a string or number as `..` does (into a buffer sized by `str_len_of`).
6107    pub(crate) fn append_stringable(&self, out: &mut impl std::io::Write, v: Value) {
6108        write_stringable(&self.heap, out, v);
6109    }
6110
6111    /// `tostring(v)`.
6112    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                // The name (maybe `__name`, read as `luaL_tolstring` reads it) and the
6143                // address, formatted.
6144                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
6153/// The exact length of a string or number as `..` writes it.
6154pub(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
6163/// Writes a string or number as `..` does (into a buffer sized by `stringable_len`).
6164pub(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/// An integer's decimal text into `out`.
6174#[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
6195/// A stable pseudo-address for `tostring` of objects.
6196pub(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
6212/// An integer from a number for bitwise operations (strings do not convert, as in 5.4).
6213fn 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
6263/// Arithmetic on two numbers.
6264pub(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
6280/// How a chunk name prints in messages: `=name` as is, `@file` as the file, source text as
6281/// `[string "first line..."]`.
6282pub(crate) fn chunk_id(source: &str) -> String {
6283    // C Lua's chunk name is a C string: it ends at the first zero byte (`load("\0")` is
6284    // `[string ""]`), S5C-COR-2.
6285    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    // C's `luaO_chunkid` keeps the text whole only below the limit; at it, "..." is added.
6304    if !multi && first.len() < MAX {
6305        return format!("[string \"{first}\"]");
6306    }
6307    let cut = truncate_utf8(first, MAX);
6308    format!("[string \"{cut}...\"]")
6309}
6310
6311/// `s` cut to at most `max` bytes on a character boundary.
6312/// `b` cut to at most `max` bytes: at a character boundary when it is UTF-8 (as
6313/// [`truncate_utf8`]), else at `max`.
6314pub(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/// Makes closure `p` of prototype `parent` (running as `closure` with registers from
6333/// `base` of the thread `cur`, whose open upvalues are `open`): the one place both
6334/// interpreter paths make closures. Its memory (the function and any upvalues it opens)
6335/// is charged first; Err(Some(bytes)) when that does not fit (nothing is changed),
6336/// Err(None) for a missing prototype.
6337/// Fuel for writing a list of `n` values in one step (registers, results, arguments): free
6338/// up to 16, then a unit per 8, as the call protocol charges argument and result lists.
6339#[inline]
6340pub(crate) fn list_fuel(n: usize) -> u64 {
6341    if n > 16 { n as u64 / 8 } else { 0 }
6342}
6343
6344/// Open upvalues moved (16 bytes each) per unit of fuel when a new one is put below them.
6345const 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    // The upvalue descriptions, copied out (making upvalues below needs the heap mutably):
6358    // into a buffer on the stack for the common few, without an allocation.
6359    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    // S5B-WALK-5: a closure's upvalues (up to 255, each found among the open ones or made)
6380    // were one unit with the instruction: building a 250-upvalue closure over and over ran
6381    // at 4x plain code per unit. A unit per 8 upvalues, and 2 more per 8 made, charged by
6382    // both paths from this count, so fuel stays the same either way.
6383    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    // Open upvalues moved up to make room for new ones (SEC-M6).
6390    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            // The enclosing closure's own upvalue (read in place: making upvalues does not
6408            // touch the function slab).
6409            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    // SEC-M6: an upvalue made below others already open moves them all up (the list is kept
6417    // sorted by slot): a frame of 8,000 locals captured from the last down ran at 22x plain
6418    // code per unit of fuel, more with more locals. Paid by the entries moved (slots, not
6419    // the seed, decide them, so fuel stays the same on both paths and under any seed).
6420    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
6426/// Empties a result list, giving back its room when it is long (`NATIVE_CHUNK` values or
6427/// more): only lists being placed are counted (SEC-M15), so a long one kept was outside
6428/// the account (SEC7-1).
6429pub(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}