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::<false>(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<const REGISTER: bool>(&mut self, room: usize, asize: usize, hash: usize) -> Result<TableRef, LuaError> {
1337        let t = self.alloc(|h| Heap::new_table_in::<REGISTER>(&mut h.mem, &mut h.tables, &mut h.born, (h.phase, h.sweep, h.table_seed), 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.
1501        h.mark(Value::Table(self.registry));
1502        if let Some(l) = self.names.loaded {
1503            h.mark(Value::Table(l));
1504        }
1505        h.mark(Value::Table(self.globals));
1506        if let Some(m) = self.string_meta {
1507            h.mark(Value::Table(m));
1508        }
1509        for &n in &self.tm_names {
1510            h.mark(Value::Str(n));
1511        }
1512        self.names.mark(h);
1513        h.mark(Value::Thread(self.main_ref));
1514        h.mark(Value::Thread(self.cur_ref));
1515        let walked = h.mark_thread_state(&self.cur);
1516        // Dropped roots forgotten, their charge given back (LR-17, as `prune_roots`).
1517        let before = self.roots.len();
1518        self.roots.retain(|(w, _)| w.strong_count() > 0);
1519        h.mem.release((before - self.roots.len()) * crate::heap::ROOT_BYTES);
1520        for (_, v) in &self.roots {
1521            h.mark(*v);
1522        }
1523        for v in &self.scratch {
1524            h.mark(*v);
1525        }
1526        for v in &self.rets {
1527            h.mark(*v);
1528        }
1529        for v in &self.held {
1530            h.mark(*v);
1531        }
1532        for v in &self.host_rets {
1533            h.mark(*v);
1534        }
1535        if let Some((_, v)) = &self.last_error {
1536            h.mark(*v);
1537        }
1538        walked
1539    }
1540
1541    /// One step of collection, paid for by the allocation since the last.
1542    #[inline]
1543    pub(crate) fn gc_step(&mut self) -> Result<(), LuaError> {
1544        if self.heap.mem.trace.is_none() { self.gc_step_now() } else { self.gc_step_traced() }
1545    }
1546
1547    /// `gc_step` with a trace record of it: its slots, fuel and time (SEC7-G1).
1548    #[cold]
1549    #[inline(never)]
1550    fn gc_step_traced(&mut self) -> Result<(), LuaError> {
1551        use crate::gctrace::TraceOp;
1552        let op = match self.heap.phase {
1553            crate::heap::Phase::Pause => TraceOp::Start,
1554            crate::heap::Phase::Propagate if self.heap.atomic_suspended() => TraceOp::Atomic,
1555            crate::heap::Phase::Propagate => TraceOp::Mark,
1556            crate::heap::Phase::Sweep => TraceOp::Sweep,
1557        };
1558        let (scanned, fuel) = (self.heap.scanned, self.fuel.saturating_add(self.reserve));
1559        let resumed = self.gc_pending.is_some();
1560        let start = self.heap.mem.trace.as_mut().map(|t| {
1561            // (A step resumed after a pause is the same step.)
1562            t.step += u32::from(!resumed);
1563            (t.now(), t.step)
1564        });
1565        let r = self.gc_step_now();
1566        let used = fuel.saturating_sub(self.fuel.max(-1).saturating_add(self.reserve.max(0)));
1567        if let (Some(t), Some((start, step))) = (self.heap.mem.trace.as_mut(), start) {
1568            t.note(op, step, self.heap.scanned.wrapping_sub(scanned) as u64, 0, u64::try_from(used).unwrap_or(0), start);
1569        }
1570        r
1571    }
1572
1573    fn gc_step_now(&mut self) -> Result<(), LuaError> {
1574        // A step paused at the end of the host's poll goes on as it stood (SEC7-G1).
1575        let resumed = self.gc_pending.take();
1576        let (born_step, full, budget) = if let Some(p) = resumed {
1577            p
1578        } else {
1579            let born_step = self.heap.born.take_step();
1580            if self.heap.blocked > 0 {
1581                return Ok(());
1582            }
1583            if self.heap.stopped {
1584                return self.charge_born();
1585            }
1586            if self.heap.mem.stress {
1587                // The test mode's collections are not the script's work: not charged (the
1588                // interrupt still stops one).
1589                let (fuel, reserve) = (self.fuel, self.reserve);
1590                self.fuel = i64::MAX;
1591                let r = self.full_gc();
1592                (self.fuel, self.reserve) = (fuel, reserve);
1593                return r;
1594            }
1595            // A step's budget follows the debt, so one big allocation (an array part
1596            // doubling to 2^21 slots, 32 MiB) made a step of millions of units, done in one
1597            // go past the call's fuel (40 ms). A step does at most what the call's fuel
1598            // still pays for; the rest stays owed (as debt, below) and is done by the steps
1599            // that follow (S6GC-2e).
1600            let full = self.heap.step_budget();
1601            // (Less what the objects made since the last step owe, charged with this step.)
1602            (born_step, full, full.min(self.gc_allow(self.heap.born.pending()).max(1)))
1603        };
1604        // The budget not given to a marking or sweeping step that did not finish its phase.
1605        let mut unspent = 0;
1606        // A suspended atomic phase's work done past the last call's fuel is this step's
1607        // (charged with it, as far as the call's fuel goes, the rest owed again: in the
1608        // step's own trace record, SEC8-F7).
1609        let mut work = if resumed.is_none() && self.heap.atomic_suspended() { std::mem::take(&mut self.atomic_owed) } else { 0 };
1610        match self.heap.phase {
1611            crate::heap::Phase::Pause => {
1612                // Work done and not yet charged when the last cycle ended (a full collection
1613                // stopped for the fuel in its sweep: `charge_or_owe`) is charged, not dropped
1614                // (SEC8-F7): as far as this step's budget goes, the rest owed to the marking
1615                // steps after, as marking's own.
1616                let over = std::mem::take(&mut self.gc_mark_over);
1617                let pay = over.min(budget);
1618                work += pay;
1619                self.gc_mark_over = over - pay;
1620                self.gc_owed_probe.1 += pay as u64;
1621                work += self.clear_dead_stack();
1622                self.heap.start_cycle();
1623                work += self.mark_roots();
1624                work += 64;
1625            }
1626            crate::heap::Phase::Propagate => {
1627                // A suspended atomic phase goes on where it stopped.
1628                let stop = crate::heap::Stop {
1629                    interrupt: &self.interrupt,
1630                    deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
1631                };
1632                let mut stopped = false;
1633                let done = if self.heap.atomic_suspended() {
1634                    true
1635                } else {
1636                    // The objects made since the last step take their part of it, as they
1637                    // did as gray objects (`Born::step`; they are traversed in any case).
1638                    let mark = budget.saturating_sub(born_step);
1639                    let (empty, w, cut, _) = if resumed.is_some() {
1640                        self.heap.propagate_resume(&stop)
1641                    } else {
1642                        self.heap.step_slots = crate::heap::STEP_SLOTS;
1643                        self.heap.propagate(mark.saturating_sub(self.gc_mark_over), &stop)
1644                    };
1645                    if std::mem::take(&mut self.heap.paused) {
1646                        // Paused at the end of the host's poll: nothing charged or settled
1647                        // yet; the resume goes on with it before any script runs, so it ends
1648                        // where it would have, charged as it would have been.
1649                        self.gc_pending = Some((born_step, full, budget));
1650                        return Err(ErrorKind::Pending.into());
1651                    }
1652                    stopped = cut;
1653                    let owed = self.gc_mark_over + w;
1654                    let done = empty && owed <= mark;
1655                    if done {
1656                        self.gc_mark_over = 0;
1657                        work += owed;
1658                    } else {
1659                        self.gc_mark_over = owed.saturating_sub(mark);
1660                        work += mark.min(owed);
1661                        unspent = full - budget;
1662                    }
1663                    done
1664                };
1665                if stopped {
1666                    // A marking step stopped by the interrupt or the deadline: its work is
1667                    // charged and the call stops (marking goes on at the next step).
1668                    self.heap.mem.debt = -STEP_SIZE;
1669                    let work = work + std::mem::take(&mut self.gc_work_carry);
1670                    self.charge_gc(work / WORK_PER_FUEL)?;
1671                    return Err(LuaError::Limit(self.stop_kind()));
1672                }
1673                // SEC7-G1: the atomic phase starts at a step at an instruction, where the call
1674                // can pause in it, not in a Rust function's (`collectgarbage('step')` among
1675                // them): the next step at an instruction starts it (marking has nothing left
1676                // to do meanwhile but what the writes since give it). In every call alike,
1677                // so where it runs follows the program alone.
1678                let defer = done
1679                    && self.native_depth > 0
1680                    && self.gc_atomic_pre.is_none()
1681                    && !self.heap.atomic_suspended()
1682                    && self.atomic_deferred < ATOMIC_DEFERRALS;
1683                if defer {
1684                    self.atomic_deferred += 1;
1685                } else if done {
1686                    self.atomic_deferred = 0;
1687                    let (pre, allow) = match self.gc_atomic_pre.take() {
1688                        // (Paused in it: it goes on with what it had.)
1689                        Some(p) => p,
1690                        None => {
1691                            work += self.clear_dead_stack();
1692                            work += self.mark_roots();
1693                            (work, self.gc_allow(work))
1694                        }
1695                    };
1696                    work = pre;
1697                    let stop = crate::heap::Stop {
1698                        interrupt: &self.interrupt,
1699                        deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
1700                    };
1701                    match self.heap.atomic(&stop, allow) {
1702                        crate::heap::Atomic::Paused => {
1703                            // Paused at the end of the host's poll: nothing charged yet.
1704                            self.gc_atomic_pre = Some((pre, allow));
1705                            self.gc_pending = Some((born_step, full, budget));
1706                            return Err(ErrorKind::Pending.into());
1707                        }
1708                        crate::heap::Atomic::Done(w) => work += w,
1709                        crate::heap::Atomic::Interrupted(w) => {
1710                            self.charge_gc((work + w) / WORK_PER_FUEL)?;
1711                            return Err(LuaError::Limit(LimitKind::Interrupted));
1712                        }
1713                        crate::heap::Atomic::Suspended(w) => return self.atomic_suspended(work + w, LimitKind::Fuel),
1714                        crate::heap::Atomic::TimedOut(w) => return self.atomic_suspended(work + w, LimitKind::Time),
1715                    }
1716                }
1717            }
1718            crate::heap::Phase::Sweep => {
1719                let stop = crate::heap::Stop {
1720                    interrupt: &self.interrupt,
1721                    deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
1722                };
1723                let (done, w, cut) = self.heap.sweep_step(budget, &stop);
1724                work += w;
1725                if cut {
1726                    // Stopped by the interrupt or the deadline: its work is charged and the
1727                    // call stops (the sweep goes on at the next step).
1728                    self.heap.mem.debt = -STEP_SIZE;
1729                    let work = work + std::mem::take(&mut self.gc_work_carry);
1730                    self.charge_gc(work / WORK_PER_FUEL)?;
1731                    return Err(LuaError::Limit(self.stop_kind()));
1732                }
1733                if done {
1734                    self.end_cycle();
1735                } else {
1736                    unspent = full - budget;
1737                }
1738            }
1739        }
1740        if self.heap.phase != crate::heap::Phase::Pause {
1741            // (The inverse of `step_budget`: the bytes the budget not given covers.)
1742            let owed = (unspent as u64).saturating_mul(800) / (self.heap.stepmul.max(1) as u64);
1743            let cap = self.heap.mem.cap;
1744            let room = cap.saturating_sub(self.memory_used());
1745            let runway = cap / 4;
1746            // Even sweeping just the table slab would take more than one host call.
1747            // Begin paying sooner while there is room to run the script between steps.
1748            let tables = &self.heap.tables;
1749            self.heap.born.trace_new_tables = room < runway
1750                && ((tables.slots() - tables.free.len()) / WORK_PER_FUEL) as u64 > self.limits.fuel;
1751            let interval = if self.heap.born.trace_new_tables {
1752                let proportional = ((STEP_SIZE as u128 * room as u128) / runway as u128) as isize;
1753                (proportional * proportional / STEP_SIZE).max(STEP_SIZE / 64)
1754            } else {
1755                STEP_SIZE
1756            };
1757            self.heap.mem.debt = (-interval).saturating_add(isize::try_from(owed).unwrap_or(isize::MAX));
1758        }
1759        // S5C-1: a step stops after the object that passes its budget, so how a cycle's
1760        // work splits into steps follows the order objects are reached, which follows
1761        // where keys sit in hash parts, which follows the seed. Each step's remainder was
1762        // dropped, so fuel differed by a unit or two between seeds; it is carried now.
1763        // (With what the objects made since the last step owe: COV-5, `heap::Born`.)
1764        let work = work + std::mem::take(&mut self.gc_work_carry) + self.heap.born.take_work();
1765        self.gc_work_carry = work % WORK_PER_FUEL;
1766        self.charge_gc(work / WORK_PER_FUEL)
1767    }
1768
1769    /// Charges the collector's `units` of fuel as far as the call's fuel goes; what it cannot
1770    /// pay is owed (`owe_gc`), never dropped (SEC8-F7), and the call stops on its fuel limit.
1771    #[inline]
1772    fn charge_gc(&mut self, units: usize) -> Result<(), LuaError> {
1773        let left = self.call_fuel();
1774        if units > left {
1775            return self.owe_gc(units - left, left);
1776        }
1777        self.charge(units as u64)
1778    }
1779
1780    /// `charge_gc` past the call's fuel: `owed` units of fuel to the collector's next steps or
1781    /// collection (`gc_mark_over`, in work units), the call charged the `left` it had.
1782    #[cold]
1783    fn owe_gc(&mut self, owed: usize, left: usize) -> Result<(), LuaError> {
1784        self.gc_mark_over += owed * WORK_PER_FUEL;
1785        self.gc_owed_probe.0 += (owed * WORK_PER_FUEL) as u64;
1786        self.charge(left as u64)?;
1787        self.fuel = -1;
1788        self.reserve = 0;
1789        Err(LuaError::Limit(LimitKind::Fuel))
1790    }
1791
1792    /// A full collection's `work` (units; `charged` units of fuel of it paid already)
1793    /// charged as far as the call's fuel goes: past it, the call is charged what fuel it had
1794    /// and stops on its fuel limit, and the rest is owed (`gc_mark_over`, charged by the
1795    /// collector's next steps or collection). Dropped, as it was, the work done past the
1796    /// call's fuel (up to a piece of `FULL_GC_CHUNK` and an object) went uncharged, by an
1797    /// amount that followed where the pieces fell in the order objects are reached, so the
1798    /// seed: 5,766,987 units against 5,773,106 for seeds 1 and 7 over 3,300 calls of the G1
1799    /// reproducer at its memory limit (SEC8-F7).
1800    fn charge_or_owe(&mut self, work: usize, charged: &mut usize) -> Result<(), LuaError> {
1801        let pay = work / WORK_PER_FUEL - *charged;
1802        let left = self.call_fuel();
1803        if pay <= left {
1804            self.charge(pay as u64)?;
1805            *charged += pay;
1806            return Ok(());
1807        }
1808        // (The remainder under a unit is owed too: the whole of the work is charged.)
1809        self.gc_mark_over += work % WORK_PER_FUEL;
1810        *charged += left;
1811        self.owe_gc(pay - left, left)
1812    }
1813
1814    /// The collector work the running call may still do: its fuel and reserve, less `done`
1815    /// (work not charged yet), in work units. Unlimited outside a call (a host `load`'s
1816    /// allocations collect unmetered).
1817    fn gc_allow(&self, done: usize) -> usize {
1818        self.call_fuel().saturating_mul(WORK_PER_FUEL).saturating_sub(done + self.gc_work_carry)
1819    }
1820
1821    /// The running call's fuel and reserve: unlimited outside a call.
1822    fn call_fuel(&self) -> usize {
1823        if self.entry == 0 {
1824            return usize::MAX;
1825        }
1826        usize::try_from(self.fuel.max(0).saturating_add(self.reserve.max(0))).unwrap_or(usize::MAX)
1827    }
1828
1829    /// An atomic phase stopped at the call's fuel (S6GC-2e) after `work` units not charged
1830    /// yet: the call is charged what fuel it had and stops on its fuel limit; the rest is
1831    /// owed by the call that resumes it (`resume_atomic`), so how the work splits between
1832    /// calls follows its total, never the order objects were reached in.
1833    /// (Stopped at the deadline instead, `kind` is `Time`: the same, the call stopping on
1834    /// its time limit with the fuel it has left, which `enter` reports: SEC8-F1, zeroed
1835    /// here, it read as the whole budget spent.)
1836    #[cold]
1837    fn atomic_suspended(&mut self, work: usize, kind: LimitKind) -> Result<(), LuaError> {
1838        let work = work + std::mem::take(&mut self.gc_work_carry);
1839        let left = self.call_fuel();
1840        self.atomic_owed = work.saturating_sub(left.saturating_mul(WORK_PER_FUEL));
1841        let _ = self.charge((work - self.atomic_owed) as u64 / WORK_PER_FUEL as u64);
1842        if kind == LimitKind::Fuel {
1843            self.fuel = -1;
1844            self.reserve = 0;
1845        }
1846        Err(LuaError::Limit(kind))
1847    }
1848
1849    /// Why a collector step stopped part-way (`heap::Stop`): the interrupt, else the deadline.
1850    #[cold]
1851    fn stop_kind(&self) -> LimitKind {
1852        if self.interrupt.load(std::sync::atomic::Ordering::Relaxed) { LimitKind::Interrupted } else { LimitKind::Time }
1853    }
1854
1855    /// Finishes a suspended atomic phase before a call from the host runs any script code
1856    /// (a script must not run inside one): charged to this call, which stops on its fuel
1857    /// limit at once if the phase does not fit in it (it is suspended again).
1858    /// Whether the call at `func` with `nargs` arguments is `collectgarbage('step')` or
1859    /// `collectgarbage('step', 0)`: a basic step.
1860    fn basic_step_call(&self, func: usize, nargs: usize) -> bool {
1861        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"));
1862        is_step && (nargs == 1 || (nargs == 2 && matches!(self.st(func + 2), Value::Int(0) | Value::Nil)))
1863    }
1864
1865    /// The step of `collectgarbage('step')` called from Lua code, before the function runs
1866    /// (it answers from `gc_call_before`): what the function's own does, at a step that may
1867    /// pause (`gc_step_pausable`).
1868    fn collect_step(&mut self) -> Result<(), LuaError> {
1869        self.gc_call_before = Some(self.heap.cycle);
1870        let stopped = std::mem::replace(&mut self.heap.stopped, false);
1871        self.heap.mem.debt = self.heap.mem.debt.max(crate::heap::STEP_SIZE);
1872        let r = self.gc_step_pausable();
1873        self.heap.stopped = stopped;
1874        r
1875    }
1876
1877    /// `resume_atomic` at the entry of a call from the host, which may pause at the end of
1878    /// the host's poll (`Heap::poll_allow`): the call then is pending before it started
1879    /// (`pending_start`, SEC7-G1).
1880    pub(crate) fn resume_atomic_pausable(&mut self) -> Result<(), LuaError> {
1881        self.heap.pause_ok = self.heap.poll_allow.is_some() && self.entry == 1;
1882        let r = self.resume_atomic();
1883        self.heap.pause_ok = false;
1884        r
1885    }
1886
1887    pub(crate) fn resume_atomic(&mut self) -> Result<(), LuaError> {
1888        if !self.heap.atomic_suspended() {
1889            return Ok(());
1890        }
1891        // (What it owes is charged by the step: `gc_step_now`.)
1892        let stopped = std::mem::replace(&mut self.heap.stopped, false);
1893        let r = self.gc_step();
1894        self.heap.stopped = stopped;
1895        r
1896    }
1897
1898    /// Clears the running thread's stack above what is live, so stale slots do not keep
1899    /// garbage alive. Only called between instructions, where the live part is the top
1900    /// frame's registers (and a pending variable-length result list), or from a library
1901    /// function, where it is the function's arguments and what it pushed. Returns the
1902    /// collector work: the whole stack, not the slots cleared (S5B-WALK-1). Where the live
1903    /// part ends follows when the atomic step comes, which follows the order objects are
1904    /// reached in, so counting the cleared slots made fuel follow the hash seed (COV-5).
1905    fn clear_dead_stack(&mut self) -> usize {
1906        // In a library function the live stack ends at its arguments and what it pushed (C
1907        // Lua's `L->top` then): its Lua caller's registers above the call are dead, so a
1908        // value only they hold is garbage, as in C Lua (weak tables see it go).
1909        let live = if self.native_depth > 0 {
1910            let mut live = self.ntop;
1911            if let Some(&(i, _)) = self.cur.open_upvals.last() {
1912                live = live.max(i + 1);
1913            }
1914            if let Some(&i) = self.cur.tbc.last() {
1915                live = live.max(i + 1);
1916            }
1917            live
1918        } else {
1919            let frame_top = self.frame_top();
1920            frame_top.max(self.top).max(self.ntop)
1921        };
1922        if self.cur.frames.is_empty() {
1923            return 0;
1924        }
1925        self.cur.stack.get_mut(live..).unwrap_or_default().fill(Value::Nil);
1926        self.cur.stack.len()
1927    }
1928
1929    /// Clears the whole stack when no call is running (back at the host).
1930    pub(crate) fn clear_idle_stack(&mut self) {
1931        if self.cur.frames.is_empty() && self.c_depth == 0 {
1932            // O(1), not a walk over the high-water length: after one deep recursion with
1933            // the collector stopped (so the stack never shrinks), every later call from
1934            // the host paid for clearing millions of slots. The capacity stays charged.
1935            self.cur.stack.clear();
1936            self.top = 0;
1937        }
1938    }
1939
1940    /// Gives back stack the running thread no longer uses (after deep recursion), as C
1941    /// Lua's collector does.
1942    fn shrink_stack(&mut self) {
1943        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())));
1944        let mut live = frame_top.max(self.top).max(self.ntop);
1945        if let Some(&(i, _)) = self.cur.open_upvals.last() {
1946            live = live.max(i + 1);
1947        }
1948        if let Some(&i) = self.cur.tbc.last() {
1949            live = live.max(i + 1);
1950        }
1951        crate::heap::shrink_frames(&mut self.cur.frames, &mut self.heap.mem);
1952        let want = (live * 2).max(64) + EXTRA_STACK;
1953        let cap = self.cur.stack.capacity();
1954        if cap <= want * 2 {
1955            return;
1956        }
1957        let keep = (live + EXTRA_STACK).min(self.cur.stack.len());
1958        self.cur.stack.truncate(keep);
1959        self.cur.stack.shrink_to(want);
1960        let now = self.cur.stack.capacity();
1961        self.heap.mem.release(cap.saturating_sub(now) * 16);
1962        self.top = self.top.min(keep);
1963    }
1964
1965    fn end_cycle(&mut self) {
1966        self.shrink_stack();
1967        self.heap.shrink_parked();
1968        self.heap.trim_scratch();
1969        let est = self.heap.mem.live();
1970        self.heap.estimate = est;
1971        // The next cycle starts when the heap grows by the pause (doubles by default), or
1972        // nears the cap.
1973        let cap = self.heap.mem.cap;
1974        let pause = self.heap.pause;
1975        let mut grow = est.saturating_mul(pause) / 100;
1976        if pause >= 200 {
1977            grow = grow.max(est + 256 * 1024);
1978        }
1979        let threshold = grow.min(cap - cap / 8).max(est + STEP_SIZE as usize);
1980        self.heap.mem.debt = est as isize - threshold as isize;
1981    }
1982
1983    /// A complete collection (finishing the one in progress first).
1984    pub(crate) fn full_gc(&mut self) -> Result<(), LuaError> {
1985        if self.heap.mem.trace.is_none() { self.full_gc_now() } else { self.full_gc_traced() }
1986    }
1987
1988    /// `full_gc` with a trace record of its pass: its slots, fuel and time (SEC8-G3).
1989    #[cold]
1990    #[inline(never)]
1991    fn full_gc_traced(&mut self) -> Result<(), LuaError> {
1992        let (scanned, fuel) = (self.heap.scanned, self.fuel.saturating_add(self.reserve));
1993        let began = match self.heap.phase {
1994            crate::heap::Phase::Pause => crate::gctrace::FULL_BEGAN_PAUSE,
1995            crate::heap::Phase::Propagate => crate::gctrace::FULL_BEGAN_MARK,
1996            crate::heap::Phase::Sweep => crate::gctrace::FULL_BEGAN_SWEEP,
1997        };
1998        let start = self.heap.mem.trace.as_mut().map(|t| {
1999            t.step += 1;
2000            (t.now(), t.step)
2001        });
2002        let r = self.full_gc_now();
2003        let used = fuel.saturating_sub(self.fuel.max(-1).saturating_add(self.reserve.max(0)));
2004        if let (Some(t), Some((start, step))) = (self.heap.mem.trace.as_mut(), start) {
2005            t.note(crate::gctrace::TraceOp::Full, step, self.heap.scanned.wrapping_sub(scanned) as u64, began, u64::try_from(used).unwrap_or(0), start);
2006        }
2007        r
2008    }
2009
2010    fn full_gc_now(&mut self) -> Result<(), LuaError> {
2011        if self.heap.blocked > 0 {
2012            return Ok(());
2013        }
2014        // Marking work steps did past their budgets and did not charge yet (`gc_mark_over`)
2015        // is charged here: dropped, the fuel followed where the steps before had stopped
2016        // in the order objects are reached, so the seed.
2017        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();
2018        let mut charged = 0;
2019        let mut cycles = 0;
2020        // Finish the current cycle, then run a whole new one, charged as it goes so a big
2021        // heap's collection stops at the fuel limit or the host's interrupt (the next
2022        // collection carries on where this one stopped).
2023        loop {
2024            match self.heap.phase {
2025                crate::heap::Phase::Pause => {
2026                    if cycles == 1 {
2027                        break;
2028                    }
2029                    cycles += 1;
2030                    self.heap.start_cycle();
2031                    work += self.mark_roots();
2032                }
2033                crate::heap::Phase::Propagate => {
2034                    let stop = crate::heap::Stop {
2035                        interrupt: &self.interrupt,
2036                        deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
2037                    };
2038                    let done = if self.heap.atomic_suspended() {
2039                        true
2040                    } else {
2041                        self.heap.step_slots = usize::MAX;
2042                        // (A piece no bigger than what the call can still pay: SEC8-F7.)
2043                        let piece = FULL_GC_CHUNK.min(self.gc_allow(work - charged * WORK_PER_FUEL).max(1));
2044                        let (done, w, cut, _) = self.heap.propagate(piece, &stop);
2045                        work += w;
2046                        if cut {
2047                            self.charge_or_owe(work, &mut charged)?;
2048                            return Err(LuaError::Limit(self.stop_kind()));
2049                        }
2050                        done
2051                    };
2052                    if done {
2053                        work += self.mark_roots();
2054                        let allow = self.gc_allow(work - charged * WORK_PER_FUEL);
2055                        let stop = crate::heap::Stop {
2056                            interrupt: &self.interrupt,
2057                            deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
2058                        };
2059                        match self.heap.atomic(&stop, allow) {
2060                            crate::heap::Atomic::Done(w) => work += w,
2061                            // (Never here: a full collection does not pause, `pause_ok` is
2062                            // off in it. Its next pass goes on.)
2063                            crate::heap::Atomic::Paused => {}
2064                            crate::heap::Atomic::Interrupted(w) => {
2065                                self.charge_or_owe(work + w, &mut charged)?;
2066                                return Err(LuaError::Limit(LimitKind::Interrupted));
2067                            }
2068                            crate::heap::Atomic::Suspended(w) => {
2069                                return self.atomic_suspended(work + w - charged * WORK_PER_FUEL, LimitKind::Fuel);
2070                            }
2071                            crate::heap::Atomic::TimedOut(w) => {
2072                                return self.atomic_suspended(work + w - charged * WORK_PER_FUEL, LimitKind::Time);
2073                            }
2074                        }
2075                    }
2076                }
2077                crate::heap::Phase::Sweep => {
2078                    let stop = crate::heap::Stop {
2079                        interrupt: &self.interrupt,
2080                        deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
2081                    };
2082                    let piece = FULL_GC_CHUNK.min(self.gc_allow(work - charged * WORK_PER_FUEL).max(1));
2083                    let (done, w, cut) = self.heap.sweep_step(piece, &stop);
2084                    work += w;
2085                    if cut {
2086                        self.charge_or_owe(work, &mut charged)?;
2087                        return Err(LuaError::Limit(self.stop_kind()));
2088                    }
2089                    if done {
2090                        self.end_cycle();
2091                    }
2092                }
2093            }
2094            self.charge_or_owe(work, &mut charged)?;
2095        }
2096        // A full collection gives the table buffer pool back to the system too, every
2097        // free slot at a slab's end (SEC-M5), and the spare coroutine stacks.
2098        self.heap.mem.drain_pool();
2099        let stop = crate::heap::Stop {
2100            interrupt: &self.interrupt,
2101            deadline: self.deadline.filter(|_| self.entry > 0).zip(self.time_limit.as_ref().map(|(clock, _)| clock)),
2102        };
2103        if self.heap.trim_slabs(&stop) {
2104            return Err(LuaError::Limit(self.stop_kind()));
2105        }
2106        self.drop_spare_stacks();
2107        Ok(())
2108    }
2109
2110    /// A collector step when one is due, else the born work charged (`Heap::gc_due`).
2111    fn gc_due_step(&mut self) -> Result<(), LuaError> {
2112        if self.heap.mem.debt > 0 { self.gc_step_pausable() } else { self.charge_born() }
2113    }
2114
2115    /// A step that may pause at the end of the host's poll (`Heap::poll_allow`): only at
2116    /// an instruction of the call from the host itself, with no Rust function and no
2117    /// coroutine resumed from Lua under it, so the call can be resumed as it stands (a
2118    /// step inside a library function, `collectgarbage` among them, runs to its end).
2119    fn gc_step_pausable(&mut self) -> Result<(), LuaError> {
2120        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;
2121        let r = self.gc_step();
2122        // A step ended past the end of the host's poll pauses the call there too: its work
2123        // all done and charged, nothing of it pending (steps of one object each never
2124        // reached a look inside them, and the script ran its whole fuel in one poll).
2125        let over = r.is_ok() && self.gc_pending.is_none() && self.heap.poll_over();
2126        self.heap.pause_ok = false;
2127        if over {
2128            return Err(ErrorKind::Pending.into());
2129        }
2130        r
2131    }
2132
2133    /// What the objects made since the last step owe (COV-5, `heap::Born`).
2134    fn charge_born(&mut self) -> Result<(), LuaError> {
2135        let work = self.heap.born.take_work() + std::mem::take(&mut self.gc_work_carry);
2136        self.gc_work_carry = work % WORK_PER_FUEL;
2137        self.charge_gc(work / WORK_PER_FUEL)
2138    }
2139
2140    // ---- metatables ----
2141
2142    pub(crate) fn metatable(&self, v: Value) -> Option<TableRef> {
2143        match v {
2144            Value::Table(t) => self.heap.tables.get(t.idx).and_then(|t| t.meta),
2145            Value::UserData(u) => self.heap.uds.get(u.idx).and_then(|u| u.meta),
2146            Value::Str(_) => self.string_meta,
2147            _ => None,
2148        }
2149    }
2150
2151    #[inline]
2152    pub(crate) fn tm_in(&self, mt: TableRef, e: Tm) -> Value {
2153        let Some(t) = self.heap.tables.get(mt.idx) else { return Value::Nil };
2154        let bit = 1u32 << (e as u8);
2155        if t.absent.get() & bit != 0 {
2156            return Value::Nil;
2157        }
2158        let name = self.tm_names.get(e as usize).copied();
2159        let v = name.map_or(Value::Nil, |n| t.get_str(Value::Str(n)));
2160        if v.is_nil() {
2161            t.absent.set(t.absent.get() | bit);
2162        }
2163        v
2164    }
2165
2166    #[inline]
2167    pub(crate) fn tm(&self, v: Value, e: Tm) -> Value {
2168        match self.metatable(v) {
2169            Some(mt) => self.tm_in(mt, e),
2170            None => Value::Nil,
2171        }
2172    }
2173
2174    /// A binary event's metamethod: `x`'s, else `y`'s.
2175    #[inline]
2176    pub(crate) fn tm2(&self, x: Value, y: Value, e: Tm) -> Value {
2177        let mm = self.tm(x, e);
2178        if mm.is_nil() { self.tm(y, e) } else { mm }
2179    }
2180
2181    /// The type name for the machine's messages, as C's `luaT_objtypename`: a table's or a
2182    /// userdata's `__name` (a string), else the plain type name. Other types' metatables
2183    /// (the strings' one) are not looked at.
2184    pub(crate) fn obj_type_name(&self, v: Value) -> String {
2185        if matches!(v, Value::Table(_) | Value::UserData(_)) { self.named_type(v) } else { v.type_name().to_owned() }
2186    }
2187
2188    /// The type name for a library's "expected, got" messages, as C's `luaL_typeerror` (and
2189    /// `luaL_tolstring`) read it with `luaL_getmetafield`: the `__name` (a string) of any
2190    /// value's metatable, the strings' one included (`getmetatable("").__name = "S"` makes
2191    /// `math.floor("x")` say "got S"). Libraries that name a value with `luaL_typename`
2192    /// (`table.concat`, `gsub`'s replacement) use the plain `Value::type_name`.
2193    pub(crate) fn arg_type_name(&self, v: Value) -> String {
2194        self.named_type(v)
2195    }
2196
2197    fn named_type(&self, v: Value) -> String {
2198        if let Some(mt) = self.metatable(v)
2199            && let Value::Str(s) = self.tm_in(mt, Tm::Name)
2200        {
2201            // Bounded: a huge `__name` must not make every message huge.
2202            let b = self.bytes(s);
2203            return String::from_utf8_lossy(b.get(..b.len().min(MAX_NAME)).unwrap_or_default()).into_owned();
2204        }
2205        v.type_name().to_owned()
2206    }
2207
2208    // ---- raw table access ----
2209
2210    #[inline]
2211    pub(crate) fn raw_get(&self, t: TableRef, k: Value) -> Value {
2212        self.heap.tables.get(t.idx).map_or(Value::Nil, |t| self.heap.get_in(t, k))
2213    }
2214
2215    pub(crate) fn raw_set(&mut self, t: TableRef, k: Value, v: Value) -> Result<(), LuaError> {
2216        let settled = self.settle_key(k)?;
2217        // Tables hold interned keys only.
2218        let k = match (k, settled) {
2219            (Value::Str(r), Settled::Absent(best)) => Value::Str(self.heap.canon_absent(r, best)),
2220            (Value::Str(r), _) => Value::Str(self.heap.canon(r)),
2221            _ => k,
2222        };
2223        // The table the collector traverses in chunks: the entry overwritten is marked
2224        // first, the entry written after (S6GC-2e).
2225        let part = t.idx == self.heap.part;
2226        let held = if part { self.heap.part_writing(t.idx, k) } else { k };
2227        self.heap.mem.fuel = self.call_fuel();
2228        self.heap.mem.fuel_watchable = true;
2229        let r = match self.heap.tables.get_mut(t.idx) {
2230            Some(tab) => tab.set(k, v, &mut self.heap.mem),
2231            None => Ok(()),
2232        };
2233        self.heap.mem.fuel_watchable = false;
2234        match r {
2235            Ok(()) => {}
2236            Err(SetError::NilKey) => return Err(LuaError::msg("table index is nil")),
2237            Err(SetError::NanKey) => return Err(LuaError::msg("table index is NaN")),
2238            // A resize stopped between pieces by the interrupt or deadline: the table is as
2239            // it was, and the call stops as at any other look.
2240            Err(SetError::Stopped(k)) => {
2241                if part {
2242                    self.heap.part_written(t.idx, held, Value::Nil);
2243                }
2244                // (What it did is charged: LR-29d, `Table::resumed`.)
2245                let heap = &mut self.heap;
2246                let units = heap.tables.get_mut(t.idx).map_or(0, |tab| tab.take_units(&heap.mem));
2247                let _ = self.charge(units);
2248                return Err(LuaError::Limit(k));
2249            }
2250            Err(SetError::Fuel) => {
2251                if part {
2252                    self.heap.part_written(t.idx, held, Value::Nil);
2253                }
2254                (self.fuel, self.reserve) = (-1, 0);
2255                return Err(LuaError::Limit(LimitKind::Fuel));
2256            }
2257            Err(SetError::Memory) => {
2258                self.emergency_gc()?;
2259                let r = match self.heap.tables.get_mut(t.idx) {
2260                    Some(tab) => tab.set(k, v, &mut self.heap.mem),
2261                    None => Ok(()),
2262                };
2263                if r.is_err() {
2264                    if part {
2265                        self.heap.part_written(t.idx, held, Value::Nil);
2266                    }
2267                    return Err(self.memory_error(false));
2268                }
2269            }
2270        }
2271        if part {
2272            self.heap.part_written(t.idx, held, v);
2273        }
2274        if v.is_collectable() || k.is_collectable() {
2275            self.heap.barrier_table(t);
2276        }
2277        // Resizing is work: charged by the slots it copied.
2278        let heap = &mut self.heap;
2279        let resized = heap.tables.get_mut(t.idx).map_or(0, |tab| tab.take_resized(&heap.mem));
2280        if resized >= 16 {
2281            self.charge(resized as u64 / 16)?;
2282        }
2283        Ok(())
2284    }
2285
2286    pub(crate) fn raw_len(&self, t: TableRef) -> i64 {
2287        self.heap.tables.get(t.idx).map_or(0, |t| t.border())
2288    }
2289
2290    // ---- upvalues ----
2291
2292    #[inline]
2293    fn upval_ref(&self, closure: FuncRef, u: u16) -> Option<u32> {
2294        match self.heap.funcs.get(closure.idx) {
2295            Some(Func::Lua { upvals, .. }) => upvals.get(usize::from(u)).map(|r| r.idx),
2296            _ => None,
2297        }
2298    }
2299
2300    #[inline]
2301    pub(crate) fn upval_get(&self, closure: FuncRef, u: u16) -> Value {
2302        let Some(r) = self.upval_ref(closure, u) else { return Value::Nil };
2303        self.upval_read(r)
2304    }
2305
2306    pub(crate) fn upval_read(&self, r: u32) -> Value {
2307        match self.heap.upvals.get(r) {
2308            Some(Upval::Closed(v)) => *v,
2309            Some(Upval::Open { thread, idx }) => {
2310                if *thread == self.cur_ref {
2311                    self.st(*idx)
2312                } else {
2313                    self.heap.threads.get(thread.idx).and_then(|t| t.stack.get(*idx).copied()).unwrap_or_default()
2314                }
2315            }
2316            None => Value::Nil,
2317        }
2318    }
2319
2320    fn upval_set(&mut self, closure: FuncRef, u: u16, v: Value) {
2321        let Some(r) = self.upval_ref(closure, u) else { return };
2322        match self.heap.upvals.get(r).copied() {
2323            Some(Upval::Closed(_)) => {
2324                if let Some(slot) = self.heap.upvals.get_mut(r) {
2325                    *slot = Upval::Closed(v);
2326                }
2327                if v.is_collectable() {
2328                    self.heap.barrier_upval(r);
2329                }
2330            }
2331            Some(Upval::Open { thread, idx }) => {
2332                if thread == self.cur_ref {
2333                    self.set_st(idx, v);
2334                } else if let Some(t) = self.heap.threads.get_mut(thread.idx)
2335                    && let Some(s) = t.stack.get_mut(idx)
2336                {
2337                    *s = v;
2338                }
2339            }
2340            None => {}
2341        }
2342    }
2343
2344    /// The innermost to-be-closed value at or above `level`, taken off the list.
2345    fn pop_tbc(&mut self, level: usize) -> Option<Value> {
2346        let slot = self.cur.tbc.last().copied().filter(|&slot| slot >= level)?;
2347        self.cur.tbc.pop();
2348        Some(self.st(slot))
2349    }
2350
2351    /// Closes the running thread's upvalues at or above `level`.
2352    pub(crate) fn close_upvals(&mut self, level: usize) {
2353        while let Some(&(idx, r)) = self.cur.open_upvals.last() {
2354            if idx < level {
2355                break;
2356            }
2357            self.cur.open_upvals.pop();
2358            let v = self.st(idx);
2359            if let Some(slot) = self.heap.upvals.get_mut(r) {
2360                *slot = Upval::Closed(v);
2361            }
2362            if v.is_collectable() {
2363                self.heap.barrier_upval(r);
2364            }
2365        }
2366    }
2367
2368    /// Closes upvalues and to-be-closed variables at or above `level` (normal exit).
2369    pub(crate) fn close_level(&mut self, level: usize) -> Result<(), LuaError> {
2370        self.close_upvals(level);
2371        while let Some(v) = self.pop_tbc(level) {
2372            self.call_close(v, Value::Nil)?;
2373        }
2374        Ok(())
2375    }
2376
2377    /// Closes at or above `level` while an error unwinds: each `__close` gets the error,
2378    /// and an error in one replaces it. Returns the error to go on with.
2379    pub(crate) fn close_with_error(&mut self, level: usize, mut err: Value) -> Result<Value, LuaError> {
2380        self.close_upvals(level);
2381        while let Some(v) = self.pop_tbc(level) {
2382            match self.call_close(v, err) {
2383                Ok(()) => {}
2384                Err(e) if e.limit().is_some() => return Err(e),
2385                Err(e) => err = self.normalize(e)?,
2386            }
2387        }
2388        Ok(err)
2389    }
2390
2391    /// Closes the to-be-closed variables of the protected call of frame `i` while an error
2392    /// unwinds to it (the error in its `dest + 1` slot), then makes the call return
2393    /// `false, error`. A Lua `__close` runs as a frame of its own that continues here when
2394    /// it returns (`Cont::ErrClosing`); an error in one replaces the error (`on_error`
2395    /// comes back here). Only limits stop it.
2396    fn close_error_async(&mut self, i: usize) -> Result<(), LuaError> {
2397        let Some(fr) = self.cur.frames.get(i) else { return Ok(()) };
2398        let FrameKind::Protected { dest, wanted, cont } = fr.kind else { return Ok(()) };
2399        let level = fr.func;
2400        let mut err = self.st(dest + 1);
2401        self.close_upvals(level);
2402        while let Some(v) = self.pop_tbc(level) {
2403            let mm = self.tm(v, Tm::Close);
2404            if matches!(mm, Value::Func(f) if matches!(self.heap.funcs.get(f.idx), Some(Func::Lua { .. }))) {
2405                let pos = self.call_top();
2406                let called = self.place_call(pos, mm, &[v, err]).and_then(|()| {
2407                    self.precall_event(Some("close"), pos, 2, 0, FrameKind::Cont(Cont::ErrClosing { frame: i }))
2408                });
2409                match called {
2410                    Ok(_) => return Ok(()),
2411                    Err(e) if e.limit().is_some() => return Err(e),
2412                    Err(e) => {
2413                        err = self.normalize(e)?;
2414                        err = self.close_error_handled(i, err)?;
2415                        self.set_st(dest + 1, err);
2416                        continue;
2417                    }
2418                }
2419            }
2420            let outer = self.err_closing.replace((i, self.cur.frames.len()));
2421            let r = if self.tm(v, Tm::Close).is_nil() {
2422                // C Lua calls the missing method from C: no name for it, no position.
2423                Err(LuaError::Plain("attempt to call a nil value".into()))
2424            } else {
2425                self.call_close(v, err)
2426            };
2427            let r = match r {
2428                Ok(()) => Ok(None),
2429                Err(e) if e.limit().is_some() => Err(e),
2430                Err(e) => self.normalize(e).map(Some),
2431            };
2432            self.err_closing = outer;
2433            if let Some(e) = r? {
2434                err = self.close_error_handled(i, e)?;
2435                self.set_st(dest + 1, err);
2436            }
2437        }
2438        self.cur.frames.truncate(i);
2439        self.set_st(dest, Value::Bool(false));
2440        self.set_st(dest + 1, err);
2441        self.move_results(dest, dest, 2, wanted)?;
2442        if let Some(c) = cont {
2443            self.apply_cont(c, Value::Bool(false))?;
2444        }
2445        Ok(())
2446    }
2447
2448    /// An error a `__close` raised while an error unwinds to the protected call of frame
2449    /// `i`: through that call's message handler, if it has one (S5C-COR-3).
2450    fn close_error_handled(&mut self, i: usize, err: Value) -> Result<Value, LuaError> {
2451        match self.cur.frames.get(i).and_then(|f| f.handler) {
2452            Some(h) => self.call_handler(h, err),
2453            None => Ok(err),
2454        }
2455    }
2456
2457    fn call_close(&mut self, v: Value, err: Value) -> Result<(), LuaError> {
2458        let mm = self.tm(v, Tm::Close);
2459        if mm.is_nil() {
2460            // Checked when declared; gone now: calling it fails, as in C Lua.
2461            return Err(LuaError::msg("attempt to call a nil value (metamethod 'close')"));
2462        }
2463        self.call_nested(mm, &[v, err]).map(|_| ())
2464    }
2465
2466    // ---- calls ----
2467
2468    /// Starts a call of the value at `func` with `nargs` arguments above it.
2469    #[inline]
2470    pub(crate) fn precall(
2471        &mut self,
2472        func: usize,
2473        nargs: usize,
2474        nres: i32,
2475        kind: FrameKind,
2476        from_lua: bool,
2477    ) -> Result<Called, LuaError> {
2478        match self.precall_one(func, nargs, nres, kind, from_lua) {
2479            Ok(Called::Done) if self.nested_pending.is_some() => self.precall_nested(),
2480            r => r,
2481        }
2482    }
2483
2484    /// The callees of nested protected calls (`nested_pending`), one after the other
2485    /// (S5COR-6b). Each is called as a protected call's callee with the kind that completes
2486    /// it and every enclosing one (`Cont::Nest`), and gets the innermost one's handler; a
2487    /// value that cannot be called makes the innermost return `false, error`.
2488    #[cold]
2489    fn precall_nested(&mut self) -> Result<Called, LuaError> {
2490        loop {
2491            let Some(NestedCall { func, nargs, kind, handler }) = self.nested_pending.take() else {
2492                return Err(LuaError::msg("internal: no nested call"));
2493            };
2494            let FrameKind::Protected { dest, cont: Some(nest), .. } = kind else {
2495                return Err(LuaError::msg("internal: nested call without its protected calls"));
2496            };
2497            match self.precall_one(func, nargs, -1, kind, false) {
2498                Ok(Called::Done) if self.nested_pending.is_some() => {}
2499                Ok(Called::Lua) => {
2500                    self.set_handler(dest, handler);
2501                    return Ok(Called::Lua);
2502                }
2503                // (A call that finished at once completed every level: `finish_call`.)
2504                Ok(other) => return Ok(other),
2505                Err(e) if e.limit().is_some() => return Err(e),
2506                Err(e) => {
2507                    self.pcall_failed(e, handler, dest, -1)?;
2508                    // Finished at once: a metamethod's caller (`call_meta`) reads the result.
2509                    self.complete_nest(nest, false)?;
2510                    return Ok(Called::Done);
2511                }
2512            }
2513        }
2514    }
2515
2516    /// The handler of the protected call whose frame was just pushed for `dest` (the
2517    /// callee's own frame: not that of a protected call it made in turn, which
2518    /// `pcall(xpcall, f, h)` puts on top).
2519    fn set_handler(&mut self, dest: usize, handler: Option<Value>) {
2520        if let Some(f) = self.cur.frames.last_mut()
2521            && matches!(f.kind, FrameKind::Protected { dest: d, .. } if d == dest)
2522        {
2523            f.handler = handler;
2524        }
2525    }
2526
2527    /// A protected call whose callee could not be called: `false` and the error (through
2528    /// `handler`) as its results at `dest`.
2529    fn pcall_failed(&mut self, e: LuaError, handler: Option<Value>, dest: usize, wanted: i32) -> Result<(), LuaError> {
2530        let mut ev = self.normalize(c_level(e))?;
2531        if let Some(h) = handler {
2532            ev = self.call_handler(h, ev)?;
2533        }
2534        self.set_st(dest, Value::Bool(false));
2535        self.set_st(dest + 1, ev);
2536        self.move_results(dest, dest, 2, wanted)
2537    }
2538
2539    /// One step of `precall`: may leave a nested protected call's callee to call next.
2540    #[inline]
2541    fn precall_one(
2542        &mut self,
2543        func: usize,
2544        nargs: usize,
2545        nres: i32,
2546        kind: FrameKind,
2547        from_lua: bool,
2548    ) -> Result<Called, LuaError> {
2549        let mut nargs = nargs;
2550        let mut fv = self.st(func);
2551        for _ in 0..MAX_TAG_LOOP {
2552            let Value::Func(f) = fv else {
2553                let mm = self.tm(fv, Tm::Call);
2554                if mm.is_nil() {
2555                    return Err(ErrorKind::Call { ty: self.obj_type_name(fv) }.into());
2556                }
2557                // Each link moves the arguments: charged by their number.
2558                self.charge(1 + nargs as u64 / 8)?;
2559                self.ensure_stack(func + nargs + 2 + EXTRA_STACK)?;
2560                self.cur.stack.copy_within(func..func + 1 + nargs, func + 1);
2561                self.set_st(func, mm);
2562                nargs += 1;
2563                fv = mm;
2564                continue;
2565            };
2566            enum K {
2567                Lua(u32),
2568                Native(NativeFn, &'static str),
2569                Host(crate::heap::HostFn, &'static str),
2570            }
2571            let k = match self.heap.funcs.get(f.idx) {
2572                Some(Func::Lua { proto, .. }) => K::Lua(*proto),
2573                Some(Func::Native { f, name, .. }) => K::Native(*f, name),
2574                Some(Func::Host { f, .. }) => K::Host(Arc::clone(f), "?"),
2575                None => return Err(LuaError::msg("attempt to call a dead function")),
2576            };
2577            return match k {
2578                K::Lua(proto) => self.push_frame(f, proto, func, nargs, nres, kind, from_lua),
2579                K::Native(nf, name) => self.call_native(func, nargs, nres, kind, from_lua, name, |l, a| nf(l, a)),
2580                K::Host(hf, name) => self.call_native(func, nargs, nres, kind, from_lua, name, |l, a| hf(l, a)),
2581            };
2582        }
2583        Err(LuaError::msg("'__call' chain too long; possible loop"))
2584    }
2585
2586    #[allow(clippy::too_many_arguments, reason = "the call protocol's own state")]
2587    fn push_frame(
2588        &mut self,
2589        closure: FuncRef,
2590        proto: u32,
2591        func: usize,
2592        nargs: usize,
2593        nres: i32,
2594        kind: FrameKind,
2595        from_lua: bool,
2596    ) -> Result<Called, LuaError> {
2597        if self.cur.frames.len() >= self.limits.call_depth {
2598            return Err(LuaError::msg("stack overflow"));
2599        }
2600        if !matches!(kind, FrameKind::Normal) && self.cur.frames.len() < self.cur.unrolled {
2601            // Everything from here up was popped since the resume: this frame is new.
2602            self.cur.unrolled = self.cur.frames.len();
2603        }
2604        // Before the window is made: charging may collect, which may shrink the stack to
2605        // the frames it has.
2606        if self.cur.frames.len() == self.cur.frames.capacity() {
2607            self.grow_frames()?;
2608        }
2609        let Some(p) = self.proto(proto) else { return Err(LuaError::msg("internal: no prototype")) };
2610        let np = p.num_params as usize;
2611        let is_vararg = p.is_vararg;
2612        let width = p.window();
2613        let (base, vstart, vcount) = if is_vararg && nargs > np {
2614            // Arguments are moved: work by their number.
2615            if nargs > 16 {
2616                self.charge(nargs as u64 / 8)?;
2617            }
2618            let nb = func + 1 + nargs;
2619            // (Parameters past one window are written here too: `np`.)
2620            self.ensure_window(nb, width.max(np))?;
2621            for i in 0..np {
2622                let v = self.st(func + 1 + i);
2623                self.set_st(nb + i, v);
2624            }
2625            (nb, func + 1 + np, nargs - np)
2626        } else {
2627            self.ensure_window(func + 1, width.max(np))?;
2628            // Missing parameters (SEC-M7: a function may have thousands).
2629            self.charge(list_fuel(np.saturating_sub(nargs)))?;
2630            for i in nargs..np {
2631                self.set_st(func + 1 + i, Value::Nil);
2632            }
2633            (func + 1, func + 1 + np, 0)
2634        };
2635        self.cur.frames.push(Frame {
2636            closure,
2637            proto,
2638            func,
2639            base,
2640            pc: 0,
2641            nresults: nres,
2642            vstart,
2643            vcount,
2644            kind,
2645            from_lua,
2646            tail: false,
2647            handler: None,
2648        });
2649        Ok(Called::Lua)
2650    }
2651
2652    #[allow(clippy::too_many_arguments, reason = "the call protocol's own state")]
2653    #[inline]
2654    fn call_native(
2655        &mut self,
2656        func: usize,
2657        nargs: usize,
2658        nres: i32,
2659        kind: FrameKind,
2660        from_lua: bool,
2661        name: &'static str,
2662        f: impl Fn(&mut Lua, Args) -> Result<Flow, LuaError>,
2663    ) -> Result<Called, LuaError> {
2664        self.ensure_stack(func + 1 + nargs + EXTRA_STACK)?;
2665        self.native_calls = self.native_calls.wrapping_add(1);
2666        self.rets.clear();
2667        let saved = (self.ntop, self.native_from_lua, self.native_name);
2668        let saved_event = std::mem::replace(&mut self.native_event, self.pending_event.take());
2669        self.ntop = func + 1 + nargs;
2670        self.native_from_lua = from_lua;
2671        self.native_name = name;
2672        let mark = self.scratch.len();
2673        let floor = std::mem::replace(&mut self.scratch_floor, mark);
2674        self.native_depth += 1;
2675        // A function `pcall` called directly sits on `pcall`, which has returned already:
2676        // it counts as an activation of its own (for error levels), and so does each
2677        // enclosing protected call it completes (`pcall(pcall, f)`).
2678        let under_pcall = if from_lua { 0 } else { pcall_levels(kind) };
2679        // (The protected calls' own slots are just below, outermost first.)
2680        // Its C levels: those protected calls, and the metamethod call it is (S5COR-6c).
2681        let c_levels = if from_lua { 0 } else { c_calls(kind) };
2682        self.protected_natives += c_levels;
2683        self.native_stack.push((self.cur_ref, self.cur.frames.len(), func, under_pcall));
2684        let owed_before = crate::stdlib::owed();
2685        let held_before = crate::stdlib::held_back();
2686        let r = f(self, Args { func, base: func + 1, n: nargs });
2687        // Buffers the function counted against memory and dropped on the way out (SEC-M1).
2688        let back = crate::stdlib::held_back().saturating_sub(held_before);
2689        if back > 0 {
2690            crate::stdlib::set_held_back(held_before);
2691            self.heap.mem.release(back);
2692        }
2693        // The work the function recorded (`stdlib::owe`, `OutBuf`), paid on every exit:
2694        // an error after building output is not free. Nested calls took their own part.
2695        let done = crate::stdlib::owed().saturating_sub(owed_before);
2696        crate::stdlib::set_owed(owed_before);
2697        let r = match (done, r) {
2698            (0, r) => r,
2699            (n, r) => match self.charge(n) {
2700                Err(e) => Err(e),
2701                Ok(()) => r,
2702            },
2703        };
2704        self.native_depth -= 1;
2705        self.scratch.truncate(mark);
2706        self.scratch_floor = floor;
2707        // A limit hit under this native (a host function that swallowed it) still stops
2708        // the call.
2709        let flow = match (r, self.limit_hit) {
2710            (Ok(fl), None) => fl,
2711            (Ok(_), Some(k)) => {
2712                let e = self.native_failed(LuaError::Limit(k), saved, (under_pcall, c_levels));
2713                self.native_event = saved_event;
2714                return Err(e);
2715            }
2716            (Err(e), _) => {
2717                let e = self.native_failed(e, saved, (under_pcall, c_levels));
2718                self.native_event = saved_event;
2719                return Err(e);
2720            }
2721        };
2722        self.native_stack.pop();
2723        self.protected_natives -= c_levels;
2724        (self.ntop, self.native_from_lua, self.native_name) = saved;
2725        self.native_event = saved_event;
2726        match (flow, kind) {
2727            // The common case: results straight into place.
2728            (Flow::Return, FrameKind::Normal) => {
2729                let n = self.rets.len();
2730                let want = if nres < 0 { n } else { nres as usize };
2731                // The results, or the nils up to what is wanted when more (SEC-M7).
2732                self.charge(list_fuel(n.max(want)))?;
2733                let need = func + n.max(want) + 2;
2734                // One result into a stack long enough already (`place_rets` does no more
2735                // then): stored here, without the call.
2736                match self.rets.first() {
2737                    Some(&v) if n == 1 && need <= self.cur.stack.len() => {
2738                        if let Some(d) = self.cur.stack.get_mut(func) {
2739                            *d = v;
2740                        }
2741                    }
2742                    _ => self.place_rets(func, need)?,
2743                }
2744                if let Some(rest) = self.cur.stack.get_mut(func + n..func + want) {
2745                    rest.fill(Value::Nil);
2746                }
2747                if nres < 0 {
2748                    self.top = func + n;
2749                }
2750                self.rets.clear();
2751                Ok(Called::Done)
2752            }
2753            (flow, kind) => self.native_flow(flow, func, nres, kind, from_lua),
2754        }
2755    }
2756
2757    /// A call from Lua code to a library function marked to run in place
2758    /// (`Func::Native::in_place`, `string::in_place`), made without `call_native`'s set-up:
2759    /// the same results, fuel, memory and stack. None when it cannot: `call_native` makes
2760    /// the call then, from the start (`in_place` leaves nothing done).
2761    #[inline(never)]
2762    fn call_in_place(&mut self, op: u8, func: usize, nargs: usize, nres: i32) -> Option<Result<Called, LuaError>> {
2763        let want = usize::try_from(nres).unwrap_or(0);
2764        // The stack `call_native` makes sure of, room for two results and the nils wanted
2765        // (more than 16 are paid: SEC-M7), and no limit hit pending (it stops the call).
2766        // (Off with the fast loop: the tests' reference path is `call_native`.)
2767        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) {
2768            return None;
2769        }
2770        let mut args = [Value::Nil; 4];
2771        for (i, a) in args.iter_mut().enumerate().take(nargs) {
2772            *a = self.st(func + 1 + i);
2773        }
2774        // (Its fuel is the fuel in hand before the call's step.)
2775        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)?;
2776        self.pending_event = None;
2777        self.fuel -= cost;
2778        for i in 0..n.max(want) {
2779            self.set_st(func + i, r.get(i).copied().unwrap_or(Value::Nil));
2780        }
2781        if nres < 0 {
2782            self.top = func + n;
2783        }
2784        // The interner's walk past the fuel in hand: the next slice, or the stop, where
2785        // `new_str` would take it. (The collector's step after it is the call's.)
2786        if self.fuel < 0
2787            && let Err(e) = self.refuel()
2788        {
2789            return Some(Err(e));
2790        }
2791        Some(Ok(Called::Done))
2792    }
2793
2794    /// `coroutine.yield(...)` called from Lua code: what `call_native` does for it, without
2795    /// the set-up it undoes before a yield is handled (`native_flow`): `yield_` only gathers
2796    /// its arguments and cannot fail, owes no fuel and calls nothing. (With a limit hit
2797    /// pending, `call_native` raises it: the caller takes that path then.)
2798    ///
2799    /// What `call_native` leaves behind for a native called from Lua code that returns
2800    /// `Flow::Yield`, item by item: `ntop`, `native_from_lua`, `native_name`,
2801    /// `native_event`, the scratch floor and `native_depth` are put back; the
2802    /// `native_stack` entry is pushed and popped; `c_calls` and `pcall_levels` are 0 from
2803    /// Lua code, so `protected_natives` does not move; `yield_` owes no fuel. The one
2804    /// lasting effect is `pending_event` taken (cleared): done here too.
2805    fn yield_from_lua(&mut self, func: usize, nargs: usize, nres: i32) -> Result<Called, LuaError> {
2806        self.ensure_stack(func + 1 + nargs + EXTRA_STACK)?;
2807        self.pending_event = None;
2808        self.rets.clear();
2809        for i in 0..nargs {
2810            let v = self.st(func + 1 + i);
2811            self.rets.push(v);
2812        }
2813        self.native_flow(Flow::Yield, func, nres, FrameKind::Normal, true)
2814    }
2815
2816    /// Copies a native's results (`rets`) to the stack from `func`, which is made `need`
2817    /// slots at least. S6-5: many results (`string.byte`, `table.unpack`) are written once,
2818    /// not over a stack first filled with nils, and the host's interrupt and deadline are
2819    /// looked at as they go: 3M of them ran 54 to 74 ms past a 20 ms time limit.
2820    fn place_rets(&mut self, func: usize, need: usize) -> Result<(), LuaError> {
2821        let n = self.rets.len();
2822        if n <= crate::stdlib::NATIVE_CHUNK {
2823            self.ensure_stack(need)?;
2824            if let Some(dst) = self.cur.stack.get_mut(func..func + n) {
2825                // (A loop: results are few, and `copy_from_slice` is a call to memcpy.)
2826                for (d, v) in dst.iter_mut().zip(&self.rets) {
2827                    *d = *v;
2828                }
2829            }
2830            return Ok(());
2831        }
2832        // SEC-M15: the list is counted while the stack grows beside it, and not kept after
2833        // (kept, its capacity stayed outside the account for good: 14 MiB after a
2834        // `string.byte` of 900,000).
2835        // (Not debt: the collector's pace is as before.)
2836        let mut hold = crate::stdlib::MemHold::default();
2837        let rets = std::mem::take(&mut self.rets);
2838        let bytes = rets.capacity().saturating_mul(std::mem::size_of::<Value>());
2839        let r = hold.cover(self, bytes).and_then(|()| self.stack_room(need));
2840        if let Err(e) = r {
2841            hold.give_back(self);
2842            return Err(e);
2843        }
2844        let mut stopped = Ok(());
2845        let mut at = func;
2846        for part in rets.chunks(crate::stdlib::NATIVE_CHUNK) {
2847            let end = at + part.len();
2848            if let Some(dst) = self.cur.stack.get_mut(at..end) {
2849                dst.copy_from_slice(part);
2850            } else {
2851                self.cur.stack.truncate(at);
2852                self.cur.stack.resize(at, Value::Nil);
2853                self.cur.stack.extend_from_slice(part);
2854            }
2855            at = end;
2856            if let Err(e) = self.check_time() {
2857                stopped = Err(e);
2858                break;
2859            }
2860        }
2861        drop(rets);
2862        hold.give_back(self);
2863        // On a stop the stack is left as far as it was written: past the first chunk, so
2864        // past every frame's register window (filling the rest took 5 to 10 ms).
2865        stopped?;
2866        if self.cur.stack.len() < need {
2867            self.cur.stack.resize(need, Value::Nil);
2868        }
2869        Ok(())
2870    }
2871
2872    /// A native's error, given its position and name while the native is still the
2873    /// running function; the call state is put back.
2874    #[cold]
2875    fn native_failed(&mut self, e: LuaError, saved: (usize, bool, &'static str), (under_pcall, c_levels): (usize, usize)) -> LuaError {
2876        // A long result list an error cut short is not kept: past the call it was outside
2877        // the account for good (SEC7-1: 39 MiB after a stopped `table.unpack`).
2878        clear_list(&mut self.rets);
2879        let e = match e.kind() {
2880            ErrorKind::Limit(_) | ErrorKind::Value(_) => e,
2881            _ => match self.normalize(e) {
2882                Ok(v) => LuaError::Value(v),
2883                Err(e) => e,
2884            },
2885        };
2886        // The error's message handler (`xpcall`) runs where it was raised, as in C Lua:
2887        // this native is still a level for `debug.traceback` there (`handler_native`).
2888        if let ErrorKind::Value(v) = *e.kind() {
2889            self.err_native = self.native_stack.last().map(|&(t, d, slot, _)| ((t, d, slot), under_pcall, v));
2890        }
2891        self.native_stack.pop();
2892        self.protected_natives -= c_levels;
2893        (self.ntop, self.native_from_lua, self.native_name) = saved;
2894        e
2895    }
2896
2897    /// What a native asked for besides returning to a plain call: results through a
2898    /// protected or continued frame, a protected call, a yield or a resume.
2899    fn native_flow(&mut self, flow: Flow, func: usize, nres: i32, kind: FrameKind, from_lua: bool) -> Result<Called, LuaError> {
2900        match flow {
2901            Flow::Return => {
2902                let n = self.rets.len();
2903                self.place_rets(func, func + n.max(nres.max(0) as usize) + 2)?;
2904                self.rets.clear();
2905                match kind {
2906                    FrameKind::Cont(_) => self.move_results(func, func, n, nres)?,
2907                    k => self.finish_call(k, func, func, n, nres, false)?,
2908                }
2909                Ok(Called::Done)
2910            }
2911            Flow::PCall { handler, nargs: fnargs } if let Some(nest) = nest_of(kind, func) => {
2912                // S5COR-6 / S5COR-6b: `pcall(pcall, f)` (or `xpcall`, either way round, any
2913                // depth). This protected call's callee gets one frame (or pending call) that
2914                // completes it and every enclosing one (`Cont::Nest`): `f` runs as in a
2915                // plain protected call, so it may yield, and the depth costs no native
2916                // stack. (The enclosing calls' slots are `dest`, `dest + 1`, ..., `func`.)
2917                let pkind = FrameKind::Protected { dest: func, wanted: -1, cont: Some(nest) };
2918                // `precall` calls it (not here: the callee may be a protected call too).
2919                self.nested_pending = Some(NestedCall { func: func + 1, nargs: fnargs, kind: pkind, handler });
2920                Ok(Called::Done)
2921            }
2922            Flow::PCall { handler, nargs: fnargs } if matches!(kind, FrameKind::Protected { .. }) => {
2923                // A protected call whose continuation a `Cont::Nest` cannot carry (none the
2924                // machine makes: `nest_of` packs every metamethod's): run as a nested call
2925                // of its own, which ends with its status and results as a plain return
2926                // that the outer call then wraps. Not yieldable inside.
2927                let me = self.st(func);
2928                let mut args = Vec::with_capacity(fnargs + 2);
2929                args.push(self.st(func + 1));
2930                if let Some(h) = handler {
2931                    args.push(h);
2932                }
2933                args.extend((0..fnargs).map(|i| self.st(func + 2 + i)));
2934                let out = self.call_nested(me, &args)?;
2935                self.rets.clear();
2936                self.rets.extend_from_slice(&out);
2937                self.native_flow(Flow::Return, func, nres, kind, from_lua)
2938            }
2939            Flow::PCall { handler, nargs: fnargs } => {
2940                let cont = match kind {
2941                    FrameKind::Cont(c) => Some(c),
2942                    _ => None,
2943                };
2944                let pkind = FrameKind::Protected { dest: func, wanted: nres, cont };
2945                match self.precall(func + 1, fnargs, -1, pkind, false) {
2946                    Ok(Called::Lua) => {
2947                        self.set_handler(func, handler);
2948                        Ok(Called::Lua)
2949                    }
2950                    Ok(other) => Ok(other),
2951                    Err(e) if e.limit().is_some() => Err(e),
2952                    Err(e) => {
2953                        self.pcall_failed(e, handler, func, nres)?;
2954                        Ok(Called::Done)
2955                    }
2956                }
2957            }
2958            Flow::Yield => {
2959                self.do_yield(func, nres, kind)?;
2960                Ok(Called::Switched)
2961            }
2962            Flow::Resume { co, wrap } => self.do_resume(func, nres, co, wrap, from_lua, kind),
2963            Flow::Call3 { f, arg } => {
2964                // A Lua function into a plain call: a frame in the native's place, which
2965                // sits on it (from Rust) for error levels.
2966                let is_lua = matches!(f, Value::Func(r) if matches!(self.heap.funcs.get(r.idx), Some(Func::Lua { .. })));
2967                if is_lua && matches!(kind, FrameKind::Normal) {
2968                    self.ensure_stack(func + 2 + EXTRA_STACK)?;
2969                    self.set_st(func, f);
2970                    self.set_st(func + 1, arg);
2971                    return self.precall(func, 1, -1, FrameKind::Cont(Cont::Three { wanted: nres }), false);
2972                }
2973                // Under `pcall` (`pcall(pairs, t)`): the same frame, protected, its results cut
2974                // to three when they arrive (so `__pairs` may yield there too).
2975                // S5COR-6c: under nested protected calls (`pcall(pcall, pairs, t)`), or a
2976                // protected call or `pairs` itself used as a metamethod, the same: the
2977                // frame's `Cont::Nest` cuts them to three, then completes the rest.
2978                let three = match kind {
2979                    _ if !is_lua => None,
2980                    FrameKind::Protected { dest, wanted, cont: None } => {
2981                        Some(FrameKind::Protected { dest, wanted, cont: Some(Cont::Three { wanted }) })
2982                    }
2983                    FrameKind::Protected { dest, wanted, cont: Some(Cont::Nest { dest: d, bits, wanted: w, back, n }) } => {
2984                        // (Never `three` already: that kind is a Lua `__pairs` frame's.)
2985                        let nest = Cont::Nest { dest: d, bits: bits.with_three(), wanted: w, back, n };
2986                        Some(FrameKind::Protected { dest, wanted, cont: Some(nest) })
2987                    }
2988                    FrameKind::Protected { dest, wanted, cont: Some(c) } => pack_then(c, dest).and_then(|(then, back, n)| {
2989                        let nest = Cont::Nest { dest, bits: NestBits::new(0, then, true)?, wanted, back, n };
2990                        Some(FrameKind::Protected { dest, wanted: -1, cont: Some(nest) })
2991                    }),
2992                    FrameKind::Cont(c) => pack_then(c, func).and_then(|(then, back, n)| {
2993                        let nest = Cont::Nest { dest: func, bits: NestBits::new(0, then, true)?, wanted: nres, back, n };
2994                        Some(FrameKind::Cont(nest))
2995                    }),
2996                    FrameKind::Normal => None,
2997                };
2998                if let Some(kind) = three {
2999                    self.ensure_stack(func + 2 + EXTRA_STACK)?;
3000                    self.set_st(func, f);
3001                    self.set_st(func + 1, arg);
3002                    return self.precall(func, 1, -1, kind, false);
3003                }
3004                // shortcut: a callable that is not a Lua function runs to completion, not
3005                // yieldable.
3006                let mut out = self.call_nested(f, &[arg])?;
3007                out.resize(3, Value::Nil);
3008                self.rets.clear();
3009                self.rets.extend_from_slice(&out);
3010                self.native_flow(Flow::Return, func, nres, kind, from_lua)
3011            }
3012        }
3013    }
3014
3015    /// C Lua's count of C levels in use here (`nCcalls`), for `call_handler`: nested library
3016    /// callbacks, each protected call (`pcall` is a C function there) and metamethod call on
3017    /// this thread and on the threads that resumed it, and each resume. Walks at most until the count passes
3018    /// C Lua's limit (only on the error path). Also returns the frames walked.
3019    fn c_levels(&self) -> (usize, usize) {
3020        // Frames C Lua calls from C: protected calls, and metamethods, `__close` and
3021        // `__pairs` (continued frames here).
3022        // (Frames a resume after a yield unrolled count no more, as in C Lua.)
3023        let protected = |t: &ThreadState| {
3024            t.frames.iter().skip(t.unrolled).map(|f| c_calls(f.kind)).sum::<usize>()
3025        };
3026        let mut walked = self.cur.frames.len();
3027        let mut level = self.c_depth + self.protected_natives + HANDLER_BASE_LEVELS + protected(&self.cur);
3028        let mut next = self.cur.resumer;
3029        while let Some(r) = next {
3030            if level > 2 * C_HANDLER_LEVELS {
3031                break;
3032            }
3033            let Some(t) = self.heap.threads.get(r.idx) else { break };
3034            // A `pcall` of the resuming function itself (`pcall(coroutine.wrap(f))`) has no
3035            // frame of its own: it is the pending resume's kind.
3036            let pcall_of_resume = t.resume_pending.as_ref().map_or(0, |p| if p.from_lua { 0 } else { c_calls(p.kind) });
3037            level += RESUME_LEVELS + protected(t) + pcall_of_resume;
3038            walked += t.frames.len();
3039            next = t.resumer;
3040        }
3041        (level, walked)
3042    }
3043
3044    /// An upper bound, in constant time, of the C levels this thread's frames and its
3045    /// resumers hold (`c_levels` without the VM-wide terms), for a call at `func`: a frame
3046    /// holds at most three (a protected call, a metamethod, `pairs`) besides the protected
3047    /// calls a nested one completes (`Cont::Nest`), which are as many as the stack slots
3048    /// between its `dest` and `func`; those ranges are disjoint and below `func`. And frames'
3049    /// call slots rise one above the other, so there are at most `func + 1` of them.
3050    #[inline]
3051    fn c_bound_here(&self, func: usize) -> usize {
3052        4 * (func + 1) + self.cur.c_bound
3053    }
3054
3055    /// S6-7: the position C Lua gives the "C stack overflow" raised by the call at level
3056    /// `at` above a handler whose first frame is `from`: the Lua caller of the metamethod
3057    /// frame there. A library function calling back (`sort`'s comparator, `__tostring` from
3058    /// `tostring`) is a level of its own, at the frame its call made (`native_stack`); its
3059    /// call falling on the 200th is raised in it, with no position.
3060    fn cross_where(&self, from: usize, at: usize) -> Option<String> {
3061        let mut held = 0;
3062        for i in from..self.cur.frames.len() {
3063            let f = self.cur.frames.get(i)?;
3064            let natives = self.native_stack.iter().filter(|&&(t, d, ..)| t == self.cur_ref && d == i).count();
3065            if natives > 0 && held + natives >= at {
3066                return None;
3067            }
3068            held += natives + c_calls(f.kind);
3069            if held >= at {
3070                if held != at || !matches!(f.kind, FrameKind::Cont(_)) {
3071                    return None;
3072                }
3073                let caller = self.cur.frames.get(i.checked_sub(1)?)?;
3074                let w = self.frame_where(caller);
3075                return (!w.is_empty()).then_some(w);
3076            }
3077        }
3078        None
3079    }
3080
3081    /// Calls `xpcall`'s handler on an error value (non-yieldable). S5COR-5: as in C Lua, the
3082    /// handler stays in place while it runs, so an error it raises is handled by calling it
3083    /// again with that error (C Lua's `luaG_errormsg` runs inside the raise); its first
3084    /// result becomes the error. Ours gave "error in error handling" at the first one. A
3085    /// handler that keeps failing gets "C stack overflow" from C Lua's 200 C levels on and
3086    /// stops at 220 with "error in error handling" (LUA_ERRERR): the same counts here,
3087    /// from the native levels already in use. A loop, not recursion: the native stack does
3088    /// not grow with the chain.
3089    fn call_handler(&mut self, h: Value, err: Value) -> Result<Value, LuaError> {
3090        // The native that raised this error, if one did (the error value tells a stale
3091        // record from the error being handled).
3092        let raised = match self.err_native.take() {
3093            Some((n, under, v)) if self.raw_equal(&v, &err) => Some((n, under)),
3094            _ => None,
3095        };
3096        let saved = std::mem::replace(&mut self.handler_native, raised);
3097        let watch = std::mem::replace(&mut self.handler_raise, HandlerWatch { thread: Some(self.cur_ref), ..HandlerWatch::default() });
3098        let r = self.call_handler_at(h, err);
3099        self.handler_native = saved;
3100        self.handler_raise = watch;
3101        r
3102    }
3103
3104    fn call_handler_at(&mut self, h: Value, err: Value) -> Result<Value, LuaError> {
3105        const C_LEVELS: usize = C_HANDLER_LEVELS;
3106        const ERRERR_AT: usize = C_LEVELS / 10 * 11;
3107        let mut err = err;
3108        let (level, walked) = self.c_levels();
3109        // (A plain error in the handler is raised one level above this: the handler's.)
3110        let base = level;
3111        // Past C Lua's limit (protected calls nested deeper than its 200 C levels, which C
3112        // Lua refuses and RemedyLua runs: the superset rule), the handler runs as it would at
3113        // C Lua's last level that still runs one: once with the error, then "C stack
3114        // overflow", then "error in error handling". It was never called there.
3115        let mut level = level.min(C_LEVELS - 1);
3116        // S5B-WALK-4: the walk goes through the frames of every coroutine that resumed this
3117        // one, which `charge_error` (this thread's frames) does not see: 150 nested
3118        // coroutines 1,900 frames deep made each `xpcall` error in the innermost walk 285,000
3119        // frames, 440x plain code per unit of fuel. A unit per frame (`RESUMER_FRAMES_PER_FUEL`).
3120        self.charge((walked / RESUMER_FRAMES_PER_FUEL) as u64)?;
3121        loop {
3122            if level + 1 >= ERRERR_AT {
3123                return self.new_str(b"error in error handling");
3124            }
3125            if level == C_LEVELS {
3126                // (Positioned when the call at the 200th was a metamethod's from Lua code.)
3127                let msg = match self.handler_raise.pos.take() {
3128                    Some(w) => format!("{w}C stack overflow"),
3129                    None => "C stack overflow".into(),
3130                };
3131                err = self.new_str(msg.as_bytes())?;
3132            }
3133            self.handler_raise.raised = None;
3134            self.handler_raise.pos = None;
3135            // (The handler's first frame goes where the next frame would.)
3136            self.handler_raise.cross = (level < C_LEVELS).then(|| (self.cur.frames.len(), C_LEVELS - level));
3137            let r = match self.call_nested(h, &[err]) {
3138                Ok(v) => return Ok(v.first().copied().unwrap_or_default()),
3139                Err(e) if e.limit().is_some() => return Err(e),
3140                Err(e) => self.normalize(e),
3141            };
3142            err = r?;
3143            // C Lua calls the handler again where the error was raised: one level above
3144            // the handler's for a plain one, more inside a metamethod, a library callback
3145            // or a `__close` (S6-7: 216 calls against C Lua's 109 for an `__index` error).
3146            let next = level + self.handler_raise.raised.map_or(1, |r| r.saturating_sub(base).max(1));
3147            // A call at C Lua's 200th level, the handler's or one inside it, raises "C stack
3148            // overflow" there instead of running, and the handler is called next at the
3149            // 201st, which is `C_LEVELS` here (as for a plain error): a step past it lands on it.
3150            level = if level < C_LEVELS && next > C_LEVELS { C_LEVELS } else { next };
3151        }
3152    }
3153
3154    /// Copies `n` results from `src` to `dst`, adjusted to `wanted` (-1: all, setting the
3155    /// top).
3156    pub(crate) fn move_results(&mut self, dst: usize, src: usize, n: usize, wanted: i32) -> Result<(), LuaError> {
3157        let want = if wanted < 0 { n } else { wanted as usize };
3158        // The values moved, or the nils written up to what the caller wants when more
3159        // (SEC-M7: a call adjusted to 30,000 results wrote them all for one unit).
3160        let written = n.max(want);
3161        if written > 16 {
3162            self.charge(written as u64 / 8)?;
3163        }
3164        self.ensure_stack(dst + want.max(n) + 1)?;
3165        if dst != src && n > 0 {
3166            self.cur.stack.copy_within(src..src + n, dst);
3167        }
3168        for i in n..want {
3169            self.set_st(dst + i, Value::Nil);
3170        }
3171        if wanted < 0 {
3172            self.top = dst + n;
3173        }
3174        Ok(())
3175    }
3176
3177    /// Places a finished call's results by its kind.
3178    /// `apply_cont`: a `pcall` used as a metamethod passes its status on through its
3179    /// continuation (false when the caller reads the result itself, as `call_meta` does
3180    /// for calls that finish at once).
3181    fn finish_call(
3182        &mut self,
3183        kind: FrameKind,
3184        func: usize,
3185        src: usize,
3186        n: usize,
3187        nres: i32,
3188        apply_cont: bool,
3189    ) -> Result<(), LuaError> {
3190        match kind {
3191            FrameKind::Normal => self.move_results(func, src, n, nres),
3192            FrameKind::Protected { dest, wanted, cont } => {
3193                // `pcall(pairs, t)` with a Lua `__pairs`: its results cut to three.
3194                let n = if matches!(cont, Some(Cont::Three { .. })) || matches!(cont, Some(Cont::Nest { bits, .. }) if bits.three()) {
3195                    self.move_results(dest + 1, src, n.min(3), 3)?;
3196                    3
3197                } else {
3198                    self.move_results(dest + 1, src, n, -1)?;
3199                    n
3200                };
3201                self.set_st(dest, Value::Bool(true));
3202                self.move_results(dest, dest, n + 1, wanted)?;
3203                match cont {
3204                    // Enclosing protected calls are completed however this one finished;
3205                    // the metamethod's continuation only when asked.
3206                    Some(nest @ Cont::Nest { .. }) => self.complete_nest(nest, apply_cont),
3207                    Some(c) if apply_cont => self.apply_cont(c, Value::Bool(true)),
3208                    _ => Ok(()),
3209                }
3210            }
3211            FrameKind::Cont(nest @ Cont::Nest { dest, .. }) => {
3212                // `pairs` used as a metamethod (`levels` 0, `three`).
3213                self.move_results(dest, src, n.min(3), 3)?;
3214                self.move_results(dest, dest, 3, -1)?;
3215                self.complete_nest(nest, apply_cont)
3216            }
3217            FrameKind::Cont(Cont::Three { wanted }) => {
3218                self.move_results(func, src, n.min(3), 3)?;
3219                self.move_results(func, func, 3, wanted)
3220            }
3221            FrameKind::Cont(c) => {
3222                let v = if n > 0 { self.st(src) } else { Value::Nil };
3223                self.apply_cont(c, v)
3224            }
3225        }
3226    }
3227
3228    /// Completes the protected calls a `Cont::Nest` carries, the innermost one's status and
3229    /// results from `dest + levels` up to `top`, then (`apply_then`) gives the metamethod's
3230    /// continuation the outermost one's first result. A caller that reads that result
3231    /// itself (`call_meta`, for a call that finished at once) passes false.
3232    fn complete_nest(&mut self, nest: Cont, apply_then: bool) -> Result<(), LuaError> {
3233        let Cont::Nest { dest, bits, wanted, back, n: then_n } = nest else { return Ok(()) };
3234        let levels = bits.levels() as usize;
3235        let n = self.top.saturating_sub(dest + levels);
3236        for j in 0..levels {
3237            self.set_st(dest + j, Value::Bool(true));
3238        }
3239        self.move_results(dest, dest, n + levels, wanted)?;
3240        match unpack_then(bits.then(), dest, back, then_n) {
3241            Some(c) if apply_then => {
3242                let v = self.st(dest);
3243                self.apply_cont(c, v)
3244            }
3245            _ => Ok(()),
3246        }
3247    }
3248
3249    fn apply_cont(&mut self, c: Cont, v: Value) -> Result<(), LuaError> {
3250        match c {
3251            Cont::Store(slot) => self.set_st(slot, v),
3252            Cont::Discard | Cont::Three { .. } => {}
3253            Cont::ErrClosing { frame } => self.close_error_async(frame)?,
3254            Cont::Nest { .. } => self.complete_nest(c, true)?,
3255            Cont::Cond { k } => {
3256                if v.truthy() != k
3257                    && let Some(f) = self.cur.frames.last_mut()
3258                {
3259                    f.pc += 1;
3260                }
3261            }
3262            Cont::Concat { a, n } => {
3263                self.set_st(a + n - 1, v);
3264                // A type error after a `__concat` returned names its operand, as when the
3265                // instruction itself raises it.
3266                match self.concat(a, n).map_err(LuaError::into_kind) {
3267                    Ok(_) => {}
3268                    Err(ErrorKind::Type { op, ty, operand }) => {
3269                        let Some(&Frame { proto, pc, base, .. }) = self.cur.frames.last() else {
3270                            return Err(ErrorKind::Type { op, ty, operand }.into());
3271                        };
3272                        let r = u16::try_from((a + usize::from(operand)).saturating_sub(base)).unwrap_or(u16::MAX);
3273                        let at = pc.saturating_sub(1);
3274                        return Err(self.annotate(ErrorKind::Type { op, ty, operand: 0 }.into(), proto, at, &[crate::debug::Operand::Reg(r)]));
3275                    }
3276                    Err(e) => return Err(e.into()),
3277                }
3278            }
3279            Cont::Closing { level, then } => {
3280                let floor = match then {
3281                    AfterClose::Return { src, n } => src + n,
3282                    AfterClose::Nothing => 0,
3283                };
3284                self.close_async(level, then, floor)?;
3285            }
3286        }
3287        Ok(())
3288    }
3289
3290    /// Closes upvalues and to-be-closed variables down to `level` on a normal exit. A
3291    /// `__close` written in Lua runs as a frame (so it may yield), continuing here when it
3292    /// returns. True when everything finished at once (and nothing changed the frames).
3293    fn close_async(&mut self, level: usize, then: AfterClose, floor: usize) -> Result<bool, LuaError> {
3294        self.close_upvals(level);
3295        while let Some(v) = self.pop_tbc(level) {
3296            let mm = self.tm(v, Tm::Close);
3297            // Not callable (gone, or never a function): the message names the event, with
3298            // a position, as C Lua's on a normal exit.
3299            if !matches!(mm, Value::Func(_)) && self.tm(mm, Tm::Call).is_nil() {
3300                return Err(LuaError::msg(format!("attempt to call a {} value (metamethod 'close')", self.obj_type_name(mm))));
3301            }
3302            let is_lua = matches!(mm, Value::Func(f) if matches!(self.heap.funcs.get(f.idx), Some(Func::Lua { .. })));
3303            if is_lua {
3304                let pos = self.call_top().max(floor);
3305                self.place_call(pos, mm, &[v, Value::Nil])?;
3306                self.precall_event(Some("close"), pos, 2, 0, FrameKind::Cont(Cont::Closing { level, then }))?;
3307                return Ok(false);
3308            }
3309            let saved = self.ntop;
3310            self.ntop = self.ntop.max(floor);
3311            let r = self.call_nested(mm, &[v, Value::Nil]);
3312            self.ntop = saved;
3313            r?;
3314        }
3315        match then {
3316            AfterClose::Nothing => Ok(true),
3317            AfterClose::Return { src, n } => {
3318                self.finish_return(src, n)?;
3319                Ok(false)
3320            }
3321        }
3322    }
3323
3324    /// Returns from the top frame with `n` values from `src`.
3325    fn do_return(&mut self, src: usize, n: usize) -> Result<(), LuaError> {
3326        let Some(base) = self.cur.frames.last().map(|f| f.base) else { return Ok(()) };
3327        if self.cur.open_upvals.last().is_some_and(|(i, _)| *i >= base) {
3328            self.close_upvals(base);
3329        }
3330        if self.cur.tbc.last().is_some_and(|i| *i >= base) {
3331            // Results stay in place: `__close` calls go above them (they may be an open
3332            // list past the frame's registers); the return finishes after the last one.
3333            self.close_async(base, AfterClose::Return { src, n }, src + n)?;
3334            return Ok(());
3335        }
3336        self.finish_return(src, n)
3337    }
3338
3339    /// The rest of a return, once everything is closed.
3340    fn finish_return(&mut self, src: usize, n: usize) -> Result<(), LuaError> {
3341        let Some(frame) = self.cur.frames.pop() else { return Ok(()) };
3342        self.finish_call(frame.kind, frame.func, src, n, frame.nresults, true)?;
3343        // Not a callback's return to a native body (`nny`: SEC7-V1, `wrap(table.sort)`).
3344        if self.cur.frames.is_empty() && self.cur_ref != self.main_ref && self.cur.resumer.is_some() && self.cur.nny == 0 {
3345            self.finish_coroutine()?;
3346        }
3347        Ok(())
3348    }
3349
3350    /// Calls `f` with `args` from Rust and runs it to completion: the results.
3351    pub(crate) fn call_nested(&mut self, f: Value, args: &[Value]) -> Result<Vec<Value>, LuaError> {
3352        let (pos, keep) = self.call_nested_at(f, args)?;
3353        let out = self.cur.stack.get(pos..self.top).map(<[Value]>::to_vec).unwrap_or_default();
3354        // The results stay reachable from the native's scratch.
3355        if keep {
3356            for v in out.iter().copied().filter(|v| v.is_collectable()) {
3357                self.push_scratch(v);
3358            }
3359        }
3360        Ok(out)
3361    }
3362
3363    /// Goes on with the call from the host that paused at a collector step: the step first,
3364    /// to its end (or the poll's), then the call's frames, as if it had not paused.
3365    pub(crate) fn resume_nested(&mut self) -> Result<Vec<Value>, LuaError> {
3366        let Some(call) = self.pending_call.take() else {
3367            return Err(LuaError::msg("no call is pending"));
3368        };
3369        self.c_depth += 1;
3370        self.cur.nny += 1;
3371        let saved = (self.native_depth, self.ntop);
3372        self.native_depth = 0;
3373        self.ntop = call.ntop;
3374        // (Paused between steps: no step to go on with.)
3375        let step = if self.gc_pending.is_some() { self.gc_step_pausable() } else { Ok(()) };
3376        // Ended by its step (a limit, not a pause): the instruction set to run again does
3377        // not, so its unit is charged again and what it was set to skip goes.
3378        match &step {
3379            Err(e) if !e.is_pending() && std::mem::take(&mut self.rewound) => {
3380                self.fuel -= 1;
3381                self.due_skip = false;
3382                self.gc_call_before = None;
3383            }
3384            Ok(()) => self.rewound = false,
3385            Err(_) => {}
3386        }
3387        let r = step.and_then(|()| {
3388            // The paused instruction runs again without the step it took; with no step due
3389            // now it never looks.
3390            if !self.heap.gc_due() {
3391                self.due_skip = false;
3392            }
3393            self.execute(call.bthread, call.bdepth)
3394        });
3395        let ntop = self.ntop;
3396        self.native_depth = saved.0;
3397        self.ntop = saved.1;
3398        self.cur.nny = self.cur.nny.saturating_sub(1);
3399        self.c_depth -= 1;
3400        let (pos, keep) = self.end_nested(r, PendingCall { ntop, ..call })?;
3401        let out = self.cur.stack.get(pos..self.top).map(<[Value]>::to_vec).unwrap_or_default();
3402        if keep {
3403            for v in out.iter().copied().filter(|v| v.is_collectable()) {
3404                self.push_scratch(v);
3405            }
3406        }
3407        Ok(out)
3408    }
3409
3410    /// Drops the call from the host that paused at a collector step: the step finished
3411    /// first (uncharged: the call is gone), so the heap is as after any step, then the
3412    /// frames dropped as a limit drops them.
3413    pub(crate) fn cancel_nested(&mut self) {
3414        if self.pending_start.take().is_some() {
3415            // Paused before it started: its step finished (uncharged), nothing else to drop.
3416            let (fuel, reserve) = (self.fuel, self.reserve);
3417            self.fuel = i64::MAX;
3418            let _ = self.gc_step();
3419            (self.fuel, self.reserve) = (fuel, reserve);
3420            self.gc_pending = None;
3421            return;
3422        }
3423        let Some(call) = self.pending_call.take() else { return };
3424        if self.gc_pending.is_some() {
3425            let (fuel, reserve) = (self.fuel, self.reserve);
3426            self.fuel = i64::MAX;
3427            // (`pause_ok` is off: it runs to its end.)
3428            let _ = self.gc_step();
3429            (self.fuel, self.reserve) = (fuel, reserve);
3430            self.gc_pending = None;
3431        }
3432        self.due_skip = false;
3433        self.gc_call_before = None;
3434        self.rewound = false;
3435        self.close_upvals(call.pos);
3436        self.cur.tbc.retain(|&s| s < call.pos);
3437        self.cur.frames.truncate(call.bdepth);
3438    }
3439
3440    /// `call_nested` for the first result only (nil when there is none), without a vector.
3441    pub(crate) fn call_nested1(&mut self, f: Value, args: &[Value]) -> Result<Value, LuaError> {
3442        let (pos, keep) = self.call_nested_at(f, args)?;
3443        let v = if self.top > pos { self.st(pos) } else { Value::Nil };
3444        if keep && v.is_collectable() {
3445            self.push_scratch(v);
3446        }
3447        Ok(v)
3448    }
3449
3450    /// Calls `f` from Rust: its results are left at `pos..top`; `keep`: a native is
3451    /// running, whose scratch must keep them reachable.
3452    fn call_nested_at(&mut self, f: Value, args: &[Value]) -> Result<(usize, bool), LuaError> {
3453        if self.c_depth >= self.limits.native_depth
3454            || self.stack_base.abs_diff(crate::stack_pos()) > self.limits.stack_bytes
3455        {
3456            // C Lua's message for its C levels (`luaE_checkcstack`), positioned as there: at
3457            // the running Lua function, none when a library function is running (LIBS-5:
3458            // a `require` cycle said "t:2: stack overflow (too many nested calls from
3459            // library functions)" where C Lua says "C stack overflow").
3460            let native_on_top =
3461                self.native_stack.last().is_some_and(|&(t, d, ..)| t == self.cur_ref && d == self.cur.frames.len());
3462            return Err(if native_on_top {
3463                LuaError::Plain("C stack overflow".into())
3464            } else {
3465                LuaError::msg("C stack overflow")
3466            });
3467        }
3468        let pos = self.call_top();
3469        self.ensure_stack(pos + args.len() + 1 + EXTRA_STACK)?;
3470        if let Some((slot, rest)) = self.cur.stack.get_mut(pos..pos + 1 + args.len()).and_then(|s| s.split_first_mut()) {
3471            *slot = f;
3472            for (d, a) in rest.iter_mut().zip(args) {
3473                *d = *a;
3474            }
3475        }
3476        let bthread = self.cur_ref;
3477        let bdepth = self.cur.frames.len();
3478        self.c_depth += 1;
3479        self.cur.nny += 1;
3480        let saved = (self.native_depth, self.ntop, self.scratch.len());
3481        self.native_depth = 0;
3482        self.ntop = pos + 1 + args.len();
3483        // A Lua function's frame straight away: all `precall` comes to for one.
3484        let called = match f {
3485            Value::Func(fr) if let Some(&Func::Lua { proto, .. }) = self.heap.funcs.get(fr.idx) => {
3486                self.push_frame(fr, proto, pos, args.len(), -1, FrameKind::Normal, false)
3487            }
3488            _ => self.precall(pos, args.len(), -1, FrameKind::Normal, false),
3489        };
3490        let r = match called {
3491            Ok(Called::Done) => Ok(()),
3492            Ok(Called::Lua) => {
3493                // The fast loop first, as `run`'s first step would take it (the frame was just
3494                // pushed with its window): a callback it finishes needs no `run` at all.
3495                if self.fast && self.cur.frames.last().and_then(|f| self.proto(f.proto)).is_some_and(|p| !p.wide()) {
3496                    let ctx = crate::fast::Ctx { cur: bthread, stop_depth: bdepth, ..self.fast_ctx() };
3497                    crate::fast::run::<WINDOW>(&mut self.heap, &mut self.cur, &mut self.top, &ctx, &mut self.fuel);
3498                }
3499                if self.cur.frames.len() > bdepth { self.execute(bthread, bdepth) } else { Ok(()) }
3500            }
3501            Ok(Called::Switched) => self.execute(bthread, bdepth),
3502            Err(e) => Err(c_level(e)),
3503        };
3504        let ntop = self.ntop;
3505        self.native_depth = saved.0;
3506        self.ntop = saved.1;
3507        self.cur.nny = self.cur.nny.saturating_sub(1);
3508        self.c_depth -= 1;
3509        self.end_nested(r, PendingCall { pos, bthread, bdepth, keep: saved.0 > 0, ntop })
3510    }
3511
3512    /// How a call from Rust ended (`call_nested_at`, `resume_nested`); one that paused at a
3513    /// collector step keeps its frames (`pending_call`).
3514    fn end_nested(&mut self, r: Result<(), LuaError>, call: PendingCall) -> Result<(usize, bool), LuaError> {
3515        let PendingCall { pos, bdepth, keep, .. } = call;
3516        match r {
3517            Ok(()) => Ok((pos, keep)),
3518            Err(e) => {
3519                if e.is_pending() {
3520                    self.pending_call = Some(call);
3521                    return Err(e);
3522                }
3523                if e.limit().is_some() {
3524                    self.close_upvals(pos);
3525                    self.cur.tbc.retain(|&s| s < pos);
3526                    self.cur.frames.truncate(bdepth);
3527                    return Err(e);
3528                }
3529                let ev = self.normalize(e)?;
3530                // Close while the erroring frames are still there (their calls go above).
3531                let ev = self.close_with_error(pos, ev);
3532                self.cur.frames.truncate(bdepth);
3533                Err(LuaError::Value(ev?))
3534            }
3535        }
3536    }
3537
3538    // ---- errors ----
3539
3540    /// The source position of the running Lua function: `chunk:line:` or empty.
3541    pub(crate) fn where_(&self, level: usize) -> String {
3542        // How many more activations to pass; set by the topmost one (outside any Rust
3543        // function, level 1 is the running Lua function itself). S6-1: only the activations
3544        // above the level asked for are walked (S6-2: a run of Rust ones in one step).
3545        let mut back: Option<usize> = None;
3546        let mut found = String::new();
3547        self.walk_activations(&self.cur, self.cur_ref, self.err_closing, None, |run| match run {
3548            Run::Lua(i) => {
3549                let b = *back.get_or_insert(level.saturating_sub(1));
3550                if b == 0 {
3551                    if let Some(f) = self.cur.frames.get(i) {
3552                        found = self.frame_where(f);
3553                    }
3554                    return true;
3555                }
3556                back = Some(b - 1);
3557                false
3558            }
3559            Run::C { count, .. } => pass_rust(&mut back, level, count).is_some(),
3560            Run::Base => pass_rust(&mut back, level, 1).is_some(),
3561        });
3562        found
3563    }
3564
3565    /// The activations of thread `ts` (ref `tref`), oldest first, as C Lua's levels are
3566    /// (`debug.traceback` and `debug.getinfo` walk them): its Lua frames, and the Rust
3567    /// functions it is in where they were called. `err_closing` is `Lua::err_closing` for
3568    /// the running thread (None for another). `extra` is a native that is gone from
3569    /// `native_stack` but is still a level (the one that raised the error a message handler
3570    /// handles): its depth, slot, and the protected calls it sat on.
3571    pub(crate) fn activations(
3572        &self,
3573        ts: &ThreadState,
3574        tref: ThreadRef,
3575        err_closing: Option<(usize, usize)>,
3576        extra: Option<(usize, usize, usize)>,
3577    ) -> Vec<Act> {
3578        let mut runs = Vec::new();
3579        self.walk_activations(ts, tref, err_closing, extra, |run| {
3580            runs.push(run);
3581            false
3582        });
3583        let mut recs = Vec::with_capacity(runs.len());
3584        for run in runs.into_iter().rev() {
3585            match run {
3586                Run::Lua(i) => recs.push(Act::Lua(i)),
3587                Run::Base => recs.push(Act::Base),
3588                Run::C { slot: None, count } => recs.extend(std::iter::repeat_n(Act::C(None), count)),
3589                Run::C { slot: Some(s), count } => recs.extend((0..count).map(|j| Act::C(Some(s + j)))),
3590            }
3591        }
3592        recs
3593    }
3594
3595    /// How many activations [`Lua::activations`] lists (walked by runs, without listing them).
3596    pub(crate) fn activation_count(
3597        &self,
3598        ts: &ThreadState,
3599        tref: ThreadRef,
3600        err_closing: Option<(usize, usize)>,
3601        extra: Option<(usize, usize, usize)>,
3602    ) -> usize {
3603        let mut count = 0;
3604        self.walk_activations(ts, tref, err_closing, extra, |run| {
3605            count += match run {
3606                Run::C { count, .. } => count,
3607                Run::Lua(_) | Run::Base => 1,
3608            };
3609            false
3610        });
3611        count
3612    }
3613
3614    /// Walks the activations of thread `ts` (as [`Lua::activations`] lists them) from the
3615    /// newest, in runs, until `visit` says to stop. Each frame, and each run of Rust
3616    /// activations, is one step: an error's position (S6-1) costs only the activations
3617    /// above the level it asks for.
3618    fn walk_activations(
3619        &self,
3620        ts: &ThreadState,
3621        tref: ThreadRef,
3622        err_closing: Option<(usize, usize)>,
3623        extra: Option<(usize, usize, usize)>,
3624        mut visit: impl FnMut(Run) -> bool,
3625    ) {
3626        let n = ts.frames.len();
3627        // The natives in progress on this thread, oldest first: their depth, and their run
3628        // of activations (the protected calls each sat on, then itself) by slot.
3629        let mut natives: Vec<(usize, usize, usize)> = self
3630            .native_stack
3631            .iter()
3632            .filter(|(t, ..)| *t == tref)
3633            .map(|&(_, d, slot, under)| (d, slot.wrapping_sub(under), under + 1))
3634            .collect();
3635        if let Some((d, slot, under)) = extra
3636            && d <= n
3637        {
3638            // Before the natives called later at its depth (the handler, if a native), after
3639            // the protected calls it sat on.
3640            let at = natives.iter().position(|&(nd, ..)| nd >= d).unwrap_or(natives.len());
3641            natives.insert(at, (d, slot.wrapping_sub(under), under + 1));
3642        }
3643        // S5C-COR-1: a `__close` run while an error unwinds to the protected call of frame
3644        // `lo` runs above the frames being unwound (`Cont::ErrClosing` at `hi`, or a native
3645        // or callable `__close` called with `hi` frames: `err_closing`); C Lua runs it once
3646        // they are gone, on `pcall` itself. Those frames, and what they called, are not
3647        // levels.
3648        let ec_hi = err_closing.map(|(_, hi)| hi);
3649        let mut dead = Dead { ec: err_closing, min_lo: usize::MAX, los: std::collections::BinaryHeap::new() };
3650        // The protected calls frame `f` sits on, by slot, outermost first; and `pairs`, newer,
3651        // under a Lua `__pairs` (S5COR-6c: `pcall(pairs, t)` was a level short). Visited
3652        // newest first: true to stop.
3653        let pcalls = |f: &Frame, with_pairs: bool, visit: &mut dyn FnMut(Run) -> bool| match f.kind {
3654            FrameKind::Protected { dest, .. } => {
3655                (with_pairs && under_pairs(f.kind) && visit(Run::C { slot: None, count: 1 }))
3656                    || visit(Run::C { slot: Some(dest), count: pcall_levels(f.kind).max(1) })
3657            }
3658            FrameKind::Cont(_) if under_pairs(f.kind) => visit(Run::C { slot: None, count: 1 }),
3659            _ => visit(Run::Base),
3660        };
3661        let mut k = natives.len();
3662        let mut i = n;
3663        loop {
3664            // The natives called at depth `i` sit just below frame `i`.
3665            let mut lo_nat = k;
3666            while lo_nat > 0 && natives.get(lo_nat - 1).is_some_and(|&(d, ..)| d >= i) {
3667                lo_nat -= 1;
3668            }
3669            let any = natives.get(lo_nat..k).is_some_and(|s| s.iter().any(|&(d, ..)| d == i));
3670            if let Some(f) = ts.frames.get(i) {
3671                dead.activate(i);
3672                if !dead.gone(i) {
3673                    if dead.is_lo(i) {
3674                        // The protected call's callee is gone; `pcall` (a Rust activation)
3675                        // stays.
3676                        if pcalls(f, false, &mut visit) {
3677                            return;
3678                        }
3679                    } else {
3680                        if visit(Run::Lua(i)) {
3681                            return;
3682                        }
3683                        // A frame Rust started (`pcall`, a resume) sits on that Rust function;
3684                        // a metamethod or `__close` the machine called (a continuation, or
3685                        // `err_closing`'s callable `__close`, S6-6) does not.
3686                        if !any
3687                            && ec_hi != Some(i)
3688                            && !f.from_lua
3689                            && (!matches!(f.kind, FrameKind::Cont(_)) || under_pairs(f.kind))
3690                            && pcalls(f, true, &mut visit)
3691                        {
3692                            return;
3693                        }
3694                    }
3695                }
3696                if let FrameKind::Cont(Cont::ErrClosing { frame }) = f.kind
3697                    && frame < i
3698                {
3699                    dead.add(frame);
3700                }
3701            }
3702            // The Rust functions called at this depth, newest first: gone with the frame
3703            // that called them (the native running on top, and a native `__close`, never
3704            // are).
3705            if any {
3706                let keep = i == n || i == 0 || ec_hi == Some(i) || {
3707                    dead.activate(i - 1);
3708                    !dead.gone(i - 1) && !dead.is_lo(i - 1)
3709                };
3710                for &(d, slot, count) in natives.get(lo_nat..k).unwrap_or_default().iter().rev() {
3711                    if keep && d == i && visit(Run::C { slot: Some(slot), count }) {
3712                        return;
3713                    }
3714                }
3715            }
3716            k = lo_nat;
3717            if i == 0 {
3718                return;
3719            }
3720            i -= 1;
3721        }
3722    }
3723
3724    /// The prototype `p`.
3725    #[inline]
3726    pub(crate) fn proto(&self, p: u32) -> Option<&Proto> {
3727        self.heap.protos.get(p)
3728    }
3729
3730    /// `chunk:line: ` of a frame where it stands.
3731    fn frame_where(&self, f: &Frame) -> String {
3732        match self.proto(f.proto) {
3733            Some(p) => format!("{}:{}: ", p.source, p.line(f.pc.saturating_sub(1))),
3734            None => String::new(),
3735        }
3736    }
3737
3738    /// Charges making an error message: the text and its position (a walk over the call
3739    /// stack), and the bytecode read to name variables (`debug::take_work`).
3740    pub(crate) fn charge_error(&mut self) -> Result<(), LuaError> {
3741        let depth = self.cur.frames.len() + self.native_stack.len();
3742        self.charge(ERROR_FUEL + ((depth + crate::debug::take_work()) / 16) as u64)
3743    }
3744
3745    /// Turns an error into the value scripts see.
3746    pub(crate) fn normalize(&mut self, e: LuaError) -> Result<Value, LuaError> {
3747        let msg = match e.into_kind() {
3748            ErrorKind::Value(v) => return Ok(v),
3749            ErrorKind::Limit(k) => return Err(LuaError::Limit(k)),
3750            ErrorKind::Pending => return Err(ErrorKind::Pending.into()),
3751            ErrorKind::Msg(m) => format!("{}{m}", self.where_(1)),
3752            ErrorKind::Plain(m) => m,
3753            ErrorKind::Type { op, ty, .. } => format!("{}attempt to {op} a {ty} value", self.where_(1)),
3754            ErrorKind::Call { ty } => format!("{}attempt to call a {ty} value", self.where_(1)),
3755            ErrorKind::IntRepr { .. } => format!("{}number has no integer representation", self.where_(1)),
3756            ErrorKind::Arg(n, m) => return self.arg_error_value(n, &m),
3757        };
3758        self.charge_error()?;
3759        let cut = truncate_utf8(&msg, self.limits.error_len);
3760        let v = self.new_str(cut.as_bytes());
3761        // (A `memory_error`'s room is for this message only; with no room even for it, the
3762        // memory limit.)
3763        self.heap.mem.headroom = 0;
3764        v.map_err(|e| if e.limit().is_some() { e } else { LuaError::Limit(LimitKind::Memory) })
3765    }
3766
3767    /// `bad argument #n to 'f' (msg)`, with the function named as its call site names it.
3768    pub(crate) fn arg_error_value(&mut self, n: usize, msg: &str) -> Result<Value, LuaError> {
3769        self.arg_error_bytes(n, msg.as_bytes())
3770    }
3771
3772    /// [`Lua::arg_error_value`] for a message that quotes a script's bytes as they are.
3773    pub(crate) fn arg_error_bytes(&mut self, n: usize, msg: &[u8]) -> Result<Value, LuaError> {
3774        let (name, method) = self.called_name();
3775        let head = if method && n == 1 {
3776            format!("calling '{name}' on bad self (")
3777        } else {
3778            format!("bad argument #{} to '{name}' (", if method { n - 1 } else { n })
3779        };
3780        let mut full = self.where_(1).into_bytes();
3781        full.extend_from_slice(head.as_bytes());
3782        full.extend_from_slice(msg);
3783        full.push(b')');
3784        self.charge_error()?;
3785        self.new_str(cut_message(&full, self.limits.error_len))
3786    }
3787
3788    /// An error with a message that quotes a script's bytes as they are, after the running
3789    /// function's position (as `LuaError::Msg` gets it). S5COR-3: messages are Rust strings
3790    /// elsewhere, so a byte that is not UTF-8 (an `é` cut in half in `string.pack`'s format)
3791    /// came out converted, where C Lua shows the byte itself.
3792    pub(crate) fn msg_bytes(&mut self, parts: &[&[u8]]) -> LuaError {
3793        let mut full = self.where_(1).into_bytes();
3794        for p in parts {
3795            full.extend_from_slice(p);
3796        }
3797        if let Err(e) = self.charge_error() {
3798            return e;
3799        }
3800        match self.new_str(cut_message(&full, self.limits.error_len)) {
3801            Ok(v) => LuaError::Value(v),
3802            Err(e) => e,
3803        }
3804    }
3805
3806    /// The running native's name as the calling code names it, and whether it was called
3807    /// as a method.
3808    fn called_name(&self) -> (String, bool) {
3809        if self.native_from_lua
3810            && let Some(f) = self.cur.frames.last()
3811        {
3812            let pc = f.pc.saturating_sub(1);
3813            let Some(p) = self.proto(f.proto) else { return (self.native_name.to_owned(), false) };
3814            match p.code.get(pc) {
3815                Some(Instr::Call { a, .. } | Instr::TailCall { a, .. }) => {
3816                    if let Some((kind, name)) = crate::debug::obj_name(self, p, pc, *a) {
3817                        return (name, kind == "method");
3818                    }
3819                }
3820                Some(Instr::TForCall { .. }) => return ("for iterator".into(), false),
3821                _ => {}
3822            }
3823        }
3824        // Called as a metamethod: C Lua names the event (`funcnamefromcode`).
3825        if let Some(event) = self.native_event {
3826            return (event.into(), false);
3827        }
3828        // A library's internal helper (an iterator `ipairs` or `gmatch` returns) has no
3829        // global name: C Lua's `pushglobalfuncname` finds none and says `?`.
3830        if self.native_name.ends_with("_aux") {
3831            return ("?".into(), false);
3832        }
3833        (self.native_name.to_owned(), false)
3834    }
3835
3836    /// Adds what an operand was to a type error raised by an instruction.
3837    fn annotate(&self, e: LuaError, pidx: u32, pc: usize, operands: &[crate::debug::Operand]) -> LuaError {
3838        let empty = Proto::default();
3839        let proto = self.proto(pidx).unwrap_or(&empty);
3840        match e.into_kind() {
3841            ErrorKind::Type { op, ty, operand } => {
3842                let info = operands
3843                    .get(usize::from(operand))
3844                    .map(|o| crate::debug::var_info(self, proto, pc, *o))
3845                    .unwrap_or_default();
3846                LuaError::Msg(format!("attempt to {op} a {ty} value{info}"))
3847            }
3848            ErrorKind::Call { ty } => {
3849                let info = operands.first().map(|o| crate::debug::var_info(self, proto, pc, *o)).unwrap_or_default();
3850                LuaError::Msg(format!("attempt to call a {ty} value{info}"))
3851            }
3852            ErrorKind::IntRepr { operand } => {
3853                let info = operands
3854                    .get(usize::from(operand))
3855                    .map(|o| crate::debug::var_info(self, proto, pc, *o))
3856                    .unwrap_or_default();
3857                LuaError::Msg(format!("number{info} has no integer representation"))
3858            }
3859            other => other.into(),
3860        }
3861    }
3862
3863    /// Notes the running thread's frames for a traceback ([`Lua::take_traceback`]).
3864    fn note_traceback(&mut self) {
3865        let mut trace = self.last_trace.take().unwrap_or_default();
3866        trace.clear();
3867        self.trace_sources.clear();
3868        for f in self.cur.frames.iter().rev().take(22) {
3869            let Some(p) = self.heap.protos.get(f.proto) else { continue };
3870            if !self.trace_sources.last().is_some_and(|s| Arc::ptr_eq(s, &p.source)) {
3871                self.trace_sources.push(Arc::clone(&p.source));
3872            }
3873            trace.push((self.trace_sources.len() - 1, p.line(f.pc.saturating_sub(1)), p.line_defined));
3874        }
3875        self.last_trace = Some(trace);
3876    }
3877
3878    /// The traceback of the last error that left the machine (then forgotten): empty if
3879    /// none did.
3880    pub(crate) fn take_traceback(&mut self) -> String {
3881        let Some(trace) = self.last_trace.take() else { return String::new() };
3882        let mut s = String::from("stack traceback:");
3883        for &(src, line, defined) in &trace {
3884            let Some(source) = self.trace_sources.get(src) else { continue };
3885            let what = if defined == 0 { "in main chunk".to_owned() } else { format!("in function <{source}:{defined}>") };
3886            s.push_str(&format!("\n\t{source}:{line}: {what}"));
3887        }
3888        self.trace_sources.clear();
3889        s
3890    }
3891
3892    /// Handles an error in the loop with boundary (`bthread`, `bdepth`): unwinds to a
3893    /// `pcall` (Ok: go on running), kills coroutines it escapes from, or returns it.
3894    fn on_error(&mut self, e: LuaError, bthread: ThreadRef, bdepth: usize) -> Result<(), LuaError> {
3895        if e.is_pending() {
3896            return Err(e);
3897        }
3898        if e.limit().is_some() {
3899            self.abort_to(bthread);
3900            return Err(e);
3901        }
3902        let mut err = match self.normalize(e) {
3903            Ok(v) => v,
3904            Err(e) if e.limit().is_some() => {
3905                self.abort_to(bthread);
3906                return Err(e);
3907            }
3908            Err(other) => return Err(other),
3909        };
3910        let mut first = true;
3911        loop {
3912            let min = if self.cur_ref == bthread { bdepth } else { 0 };
3913            let found = (min..self.cur.frames.len())
3914                .rev()
3915                .find(|&i| matches!(self.cur.frames.get(i).map(|f| f.kind), Some(FrameKind::Protected { .. })));
3916            // S6-7: under a message handler, where this error was raised, unless something
3917            // catches it (the first, deepest raise of an error that escapes).
3918            if std::mem::take(&mut first) && self.handler_raise.thread == Some(self.cur_ref) {
3919                if found.is_some() {
3920                    self.handler_raise.raised = None;
3921                    self.handler_raise.pos = None;
3922                } else if self.handler_raise.raised.is_none() {
3923                    // (The walk charged as `call_handler`'s is: once a round, uncharged, a
3924                    // handler failing under a deep resume chain ran at 157x plain code per
3925                    // unit of fuel, S6R-6.)
3926                    let (level, walked) = self.c_levels();
3927                    if let Err(e) = self.charge((walked / RESUMER_FRAMES_PER_FUEL) as u64) {
3928                        self.abort_to(bthread);
3929                        return Err(e);
3930                    }
3931                    self.handler_raise.raised = Some(level);
3932                    self.handler_raise.pos = self.handler_raise.cross.and_then(|(from, at)| self.cross_where(from, at));
3933                }
3934            }
3935            if let Some(i) = found {
3936                let Some(fr) = self.cur.frames.get(i) else { break };
3937                let dest = match fr.kind {
3938                    FrameKind::Protected { dest, .. } => dest,
3939                    _ => fr.func,
3940                };
3941                let handler = fr.handler;
3942                if let Some(h) = handler {
3943                    err = self.call_handler(h, err).inspect_err(|_| self.abort_to(bthread))?;
3944                }
3945                // The handler stays: an error in a `__close` run below goes through it too,
3946                // as in C Lua (`luaD_closeprotected` closes with the handler in place),
3947                // S5C-COR-3. It said the original error only.
3948                // `__close` handlers run while the erroring frames are still there, so their
3949                // calls go above every pending to-be-closed slot; a Lua one runs as a frame
3950                // of its own (it may yield, as in C Lua), and the error waits in the slot
3951                // where it is returned (`dest + 1`, below the frames being closed).
3952                self.set_st(dest + 1, err);
3953                // The protected call's outcome may go to a metamethod's continuation (`pcall`
3954                // as `__concat`), which can raise an error of its own in the frame below: that
3955                // one unwinds again, from there (S5COR-8: it went past every `pcall`).
3956                match self.close_error_async(i) {
3957                    Ok(()) => return Ok(()),
3958                    Err(e) => {
3959                        err = self.rethrown(e, bthread)?;
3960                        continue;
3961                    }
3962                }
3963            }
3964            if self.cur_ref != bthread && self.cur.resumer.is_some() {
3965                // A coroutine that dies does not unwind: its to-be-closed variables wait for
3966                // `coroutine.close`, except under `wrap`, which closes it at once.
3967                let by_wrap = self
3968                    .cur
3969                    .resumer
3970                    .and_then(|r| self.heap.threads.get(r.idx))
3971                    .and_then(|t| t.resume_pending)
3972                    .is_some_and(|p| p.wrap);
3973                if by_wrap {
3974                    err = match self.close_with_error(0, err) {
3975                        Ok(v) => v,
3976                        Err(e) => {
3977                            self.abort_to(bthread);
3978                            return Err(e);
3979                        }
3980                    };
3981                }
3982                if by_wrap {
3983                    self.cur.frames.clear();
3984                } else {
3985                    // LIBS-4: as in C Lua, a coroutine that died by an error keeps its frames
3986                    // (and the function that raised it) for `debug.traceback` and
3987                    // `debug.getinfo`, until `coroutine.close` or the collector frees it.
3988                    self.cur.died_in = match self.err_native {
3989                        Some(((t, d, slot), _, v)) if t == self.cur_ref && self.raw_equal(&v, &err) => {
3990                            Some((d, slot, self.st(slot)))
3991                        }
3992                        _ => None,
3993                    };
3994                }
3995                self.cur.status = CoStatus::Dead;
3996                self.cur.error = Some(err);
3997                let wrap = self.switch_back()?;
3998                if wrap.wrap {
3999                    // `wrap` propagates the error into its caller.
4000                    if let Value::Str(s) = err
4001                        && wrap.from_lua
4002                    {
4003                        let w = self.cur.frames.last().map_or_else(String::new, |f| self.frame_where(f));
4004                        if !w.is_empty() {
4005                            // A copy of the message at each `wrap` it crosses: paid
4006                            // (S6GC-1: a 4 MiB message ran at 300x plain code per unit).
4007                            self.charge_bytes(self.bytes(s).len())?;
4008                            let mut b = w.into_bytes();
4009                            b.extend_from_slice(self.bytes(s));
4010                            err = self.new_str(&b)?;
4011                        }
4012                    }
4013                    if let FrameKind::Protected { dest, wanted, cont } = wrap.kind {
4014                        // The wrap function was called by `pcall`: caught here.
4015                        self.set_st(dest, Value::Bool(false));
4016                        self.set_st(dest + 1, err);
4017                        let r = self.move_results(dest, dest, 2, wanted).and_then(|()| match cont {
4018                            Some(c) => self.apply_cont(c, Value::Bool(false)),
4019                            None => Ok(()),
4020                        });
4021                        match r {
4022                            Ok(()) => return Ok(()),
4023                            Err(e) => {
4024                                err = self.rethrown(e, bthread)?;
4025                                continue;
4026                            }
4027                        }
4028                    }
4029                    continue;
4030                }
4031                self.set_st(wrap.func, Value::Bool(false));
4032                self.set_st(wrap.func + 1, err);
4033                match self.finish_call(wrap.kind, wrap.func, wrap.func, 2, wrap.nresults, true) {
4034                    Ok(()) => return Ok(()),
4035                    Err(e) => {
4036                        err = self.rethrown(e, bthread)?;
4037                        continue;
4038                    }
4039                }
4040            }
4041            break;
4042        }
4043        self.note_traceback();
4044        Err(LuaError::Value(err))
4045    }
4046
4047    /// An error raised while `on_error` completed a protected call (by the continuation its
4048    /// outcome went to): its value, to unwind again; a limit stops everything up to
4049    /// `bthread`.
4050    #[cold]
4051    fn rethrown(&mut self, e: LuaError, bthread: ThreadRef) -> Result<Value, LuaError> {
4052        let r = if e.limit().is_some() { Err(e) } else { self.normalize(e) };
4053        if r.as_ref().is_err_and(|e| e.limit().is_some()) {
4054            self.abort_to(bthread);
4055            return r;
4056        }
4057        r
4058    }
4059
4060    /// After a limit: kills the coroutines between the running one and `bthread`.
4061    fn abort_to(&mut self, bthread: ThreadRef) {
4062        while self.cur_ref != bthread {
4063            self.close_upvals(0);
4064            self.cur.tbc.clear();
4065            self.cur.frames.clear();
4066            self.cur.status = CoStatus::Dead;
4067            let Some(r) = self.cur.resumer.take() else { break };
4068            self.resume_depth = self.resume_depth.saturating_sub(1);
4069            self.swap_to(r);
4070            self.cur.resume_pending = None;
4071            self.cur.status = CoStatus::Running;
4072        }
4073    }
4074
4075    // ---- coroutines ----
4076
4077    /// Makes `to` the running thread, storing the current one in its slot.
4078    /// The fast loop's context (see `ctx_epoch`), for the running thread with no stop
4079    /// depth (`run` sets both per frame).
4080    fn fast_ctx(&self) -> crate::fast::Ctx {
4081        crate::fast::Ctx {
4082            cur: self.cur_ref,
4083            call_depth: self.limits.call_depth,
4084            stop_depth: 0,
4085            index_name: self.tm_names.get(Tm::Index as usize).map_or(Value::Nil, |s| Value::Str(*s)),
4086            eq_name: self.tm_names.get(Tm::Eq as usize).map_or(Value::Nil, |s| Value::Str(*s)),
4087            string_meta: self.string_meta,
4088            string_len: self.limits.string_len,
4089            next_fn: self.names.next_fn,
4090            ipairs_aux: self.names.ipairs_aux,
4091            utf8_iters: self.names.utf8_iters,
4092            math_fast: self.names.math_fast,
4093            math_mask: self.names.math_mask,
4094            table_fast: self.names.table_fast,
4095            table_mask: self.names.table_mask,
4096        }
4097    }
4098
4099    fn swap_to(&mut self, to: ThreadRef) {
4100        // The running thread's slot holds an empty placeholder: `to`'s state comes in,
4101        // the running one goes to its own slot, the placeholder to `to`'s. Boxed, these
4102        // are pointer swaps (moving the states themselves was most of a switch's cost).
4103        let (from, into) = (self.cur_ref.idx as usize, to.idx as usize);
4104        let threads = &mut self.heap.threads;
4105        if from != into && from < threads.slots() && let Some(slot) = threads.at_mut(into) {
4106            std::mem::swap(&mut self.cur, slot);
4107            threads.swap_slots(from, into);
4108        } else {
4109            let incoming = self.heap.threads.get_mut(to.idx).map(std::mem::take).unwrap_or_default();
4110            let outgoing = std::mem::replace(&mut self.cur, incoming);
4111            if let Some(slot) = self.heap.threads.get_mut(self.cur_ref.idx) {
4112                *slot = outgoing;
4113            }
4114        }
4115        self.cur_ref = to;
4116    }
4117
4118    /// Near C Lua's limit (the bound reached it), the exact count: what C Lua does with
4119    /// this resume of `co`, and the outcome when it does not run it (`do_resume`). At 200
4120    /// levels it refuses and the coroutine stays as it was. At 199 the resume goes ahead,
4121    /// taking the 200th, and a coroutine not yet started then fails in the call of its
4122    /// body (`ccall`'s check) before any of it runs: it dies by an unpositioned "C stack
4123    /// overflow", which the resume returns (or `wrap` raises) as from a coroutine that
4124    /// failed. The same outcome here, without switching to it.
4125    #[cold]
4126    #[inline(never)]
4127    #[allow(clippy::too_many_arguments)]
4128    fn resume_refused(
4129        &mut self,
4130        func: usize,
4131        nres: i32,
4132        co: ThreadRef,
4133        wrap: bool,
4134        from_lua: bool,
4135        kind: FrameKind,
4136        pcall_of_resume: usize,
4137    ) -> Result<Option<Called>, LuaError> {
4138        let (level, walked) = self.c_levels();
4139        // (The same walk as `call_handler`'s, charged the same.)
4140        self.charge((walked / RESUMER_FRAMES_PER_FUEL) as u64)?;
4141        // The resumer's count in C Lua (`from`'s `nCcalls`): `c_levels` is the count a
4142        // message handler's call reaches, one past the native running it and one past the
4143        // `lua_resume` that `coroutine.resume` or `wrap` is to C Lua.
4144        let from = (level + pcall_of_resume).saturating_sub(2);
4145        let fresh = self.heap.threads.get(co.idx).is_some_and(|t| t.fresh);
4146        let dies = from + 1 == C_HANDLER_LEVELS && fresh;
4147        if from < C_HANDLER_LEVELS && !dies && self.resume_depth < self.limits.native_depth {
4148            return Ok(None);
4149        }
4150        let msg = "C stack overflow";
4151        if dies && self.resume_depth < self.limits.native_depth {
4152            let e = self.new_str(msg.as_bytes())?;
4153            if let Some(t) = self.heap.threads.get_mut(co.idx) {
4154                t.fresh = false;
4155                t.status = CoStatus::Dead;
4156                // (`wrap` closes a coroutine that failed, as `auxwrap` does: no error kept.)
4157                t.error = if wrap { None } else { Some(e) };
4158            }
4159        }
4160        if wrap {
4161            return Err(if from_lua { LuaError::msg(msg) } else { LuaError::Plain(msg.into()) });
4162        }
4163        let m = self.new_str(msg.as_bytes())?;
4164        self.set_st(func, Value::Bool(false));
4165        self.set_st(func + 1, m);
4166        self.finish_call(kind, func, func, 2, nres, false)?;
4167        Ok(Some(Called::Done))
4168    }
4169
4170    fn do_resume(
4171        &mut self,
4172        func: usize,
4173        nres: i32,
4174        co: ThreadRef,
4175        wrap: bool,
4176        from_lua: bool,
4177        kind: FrameKind,
4178    ) -> Result<Called, LuaError> {
4179        let args = std::mem::take(&mut self.rets);
4180        let status = if co == self.cur_ref {
4181            CoStatus::Running
4182        } else {
4183            self.heap.threads.get(co.idx).map_or(CoStatus::Dead, |t| t.status)
4184        };
4185        if status != CoStatus::Suspended || !self.heap.threads.live(co.idx, co.generation) {
4186            let msg = match status {
4187                CoStatus::Dead => "cannot resume dead coroutine",
4188                _ => "cannot resume non-suspended coroutine",
4189            };
4190            if wrap {
4191                return Err(if from_lua { LuaError::msg(msg) } else { LuaError::Plain(msg.into()) });
4192            }
4193            let m = self.new_str(msg.as_bytes())?;
4194            self.set_st(func, Value::Bool(false));
4195            self.set_st(func + 1, m);
4196            self.finish_call(kind, func, func, 2, nres, false)?;
4197            return Ok(Called::Done);
4198        }
4199        // LR-3: C Lua's `lua_resume` starts the thread's C levels from the resumer's and
4200        // refuses at its limit, before the coroutine runs: "C stack overflow" with no
4201        // position, which `coroutine.resume` returns and `wrap` raises (positioned at its
4202        // caller when that is a Lua function, as `auxwrap`'s `luaL_where(L, 1)`). A `pcall`
4203        // of the resuming function is a C level of its own there. Ours stopped at 200 nested
4204        // resumes whatever else was in use, and put the position on.
4205        // The exact count walks the frames of this thread and its resumers (`c_levels`), so
4206        // a resume first takes an upper bound in constant time and walks only when that
4207        // reaches the limit (charged as `call_handler` charges the walk).
4208        let pcall_of_resume = if from_lua { 0 } else { c_calls(kind) };
4209        let here = pcall_of_resume + self.c_bound_here(func);
4210        if self.c_depth + self.protected_natives + (HANDLER_BASE_LEVELS - 1) + here >= C_HANDLER_LEVELS
4211            || self.resume_depth + 1 > self.limits.native_depth
4212        {
4213            if let Some(done) = self.resume_refused(func, nres, co, wrap, from_lua, kind, pcall_of_resume)? {
4214                return Ok(done);
4215            }
4216        }
4217        // Its first resume maps its register window (LR-8); charged once the resume is
4218        // known to run, so a refused resume leaves the coroutine as it was.
4219        if self.heap.threads.get(co.idx).is_some_and(|t| t.fresh) {
4220            self.charge(COROUTINE_COST)?;
4221        }
4222        // The resumed thread's bound: the resume's level, this thread's and its resumers'.
4223        let inherited = RESUME_LEVELS + here;
4224        self.resume_depth += 1;
4225        self.cur.resume_pending = Some(Pending { func, nresults: nres, wrap, from_lua, kind });
4226        self.cur.status = CoStatus::Normal;
4227        let (prev, depth) = (self.cur_ref, self.cur.frames.len());
4228        self.swap_to(co);
4229        self.cur.status = CoStatus::Running;
4230        self.cur.resumer = Some(prev);
4231        self.cur.c_bound = inherited;
4232        if self.cur.fresh {
4233            self.cur.fresh = false;
4234            self.ensure_stack(args.len() + 1 + EXTRA_STACK)?;
4235            for (i, a) in args.iter().enumerate() {
4236                self.set_st(1 + i, *a);
4237            }
4238            match self.precall(0, args.len(), -1, FrameKind::Normal, false) {
4239                Ok(Called::Done) => self.finish_coroutine()?,
4240                Ok(Called::Lua | Called::Switched) => {}
4241                // A native body's error kills the coroutine here, as the loop would, not in
4242                // the resumer's `pcall` with the coroutine still running (SEC7-V1).
4243                Err(e) => self.on_error(e, prev, depth)?,
4244            }
4245        } else if let Some(p) = self.cur.yield_pending.take() {
4246            self.cur.unrolled = self.cur.frames.len();
4247            self.ensure_stack(p.func + args.len() + 1)?;
4248            for (i, a) in args.iter().enumerate() {
4249                self.set_st(p.func + i, *a);
4250            }
4251            self.finish_call(p.kind, p.func, p.func, args.len(), p.nresults, true)?;
4252        }
4253        self.give_back_rets(args);
4254        Ok(Called::Switched)
4255    }
4256
4257    /// A buffer taken from `rets` goes back (emptied) when `rets` has none, so a switch
4258    /// does not allocate a new one each time.
4259    fn give_back_rets(&mut self, mut v: Vec<Value>) {
4260        // Not a long one: kept, it was outside the account for good (SEC-M15).
4261        if self.rets.capacity() == 0 && v.capacity() <= crate::stdlib::NATIVE_CHUNK {
4262            v.clear();
4263            self.rets = v;
4264        }
4265    }
4266
4267    /// The running coroutine's body returned: its results go to the resumer.
4268    fn finish_coroutine(&mut self) -> Result<(), LuaError> {
4269        let vals: Vec<Value> = self.cur.stack.get(0..self.top).map(<[Value]>::to_vec).unwrap_or_default();
4270        self.close_upvals(0);
4271        self.cur.status = CoStatus::Dead;
4272        let me = self.cur_ref;
4273        let r = self.deliver(vals);
4274        // Its stack is not needed any more: the next coroutine's (LR-8).
4275        self.retire_stack(me);
4276        r
4277    }
4278
4279    /// Switches to the resumer with `vals` as the resume's results.
4280    fn deliver(&mut self, vals: Vec<Value>) -> Result<(), LuaError> {
4281        let p = self.switch_back()?;
4282        let mut off = 0;
4283        if !p.wrap {
4284            self.ensure_stack(p.func + 1)?;
4285            self.set_st(p.func, Value::Bool(true));
4286            off = 1;
4287        }
4288        // The values are counted while the stack grows beside them (SEC-M15).
4289        let mut hold = crate::stdlib::MemHold::default();
4290        let bytes = vals.capacity().saturating_mul(std::mem::size_of::<Value>());
4291        hold.cover(self, bytes)?;
4292        let r = self.ensure_stack(p.func + off + vals.len() + 1);
4293        hold.give_back(self);
4294        r?;
4295        for (i, v) in vals.iter().enumerate() {
4296            self.set_st(p.func + off + i, *v);
4297        }
4298        let n = vals.len();
4299        self.give_back_rets(vals);
4300        self.finish_call(p.kind, p.func, p.func, n + off, p.nresults, true)
4301    }
4302
4303    /// Runs on `co`'s stack for a moment (`coroutine.close`), without letting it yield.
4304    /// The closing thread is `normal` meanwhile, as a resumer is (S6: it said `running`, and
4305    /// closing it from a `__close` there said "cannot close a running coroutine").
4306    /// Returns its status, for [`Lua::swap_out_after_close`].
4307    ///
4308    /// Its handlers are called above what is live on its own stack (`parked_live`), not
4309    /// above the closer's: `ntop` is the closer's while `coroutine.close` runs, and a
4310    /// handler called there (LR-8) grew every closed coroutine's stack to the closer's
4311    /// height, a copy of 240 KiB per `coroutine.close` from a coroutine 15,000 slots deep
4312    /// (15x plain code per unit of fuel).
4313    pub(crate) fn swap_in_for_close(&mut self, co: ThreadRef) -> (CoStatus, usize) {
4314        let was = std::mem::replace(&mut self.cur.status, CoStatus::Normal);
4315        self.swap_to(co);
4316        self.cur.nny += 1;
4317        let live = crate::heap::parked_live(&self.cur, &self.heap.protos).unwrap_or(self.cur.stack.len());
4318        (was, std::mem::replace(&mut self.ntop, live))
4319    }
4320
4321    /// Back from [`Lua::swap_in_for_close`], to `me`, with the status and `ntop` it had.
4322    pub(crate) fn swap_out_after_close(&mut self, me: ThreadRef, (was, ntop): (CoStatus, usize)) {
4323        self.cur.nny = self.cur.nny.saturating_sub(1);
4324        self.ntop = ntop;
4325        self.swap_to(me);
4326        self.cur.status = was;
4327    }
4328
4329    /// Back to the resumer; returns where its resume call wants results.
4330    fn switch_back(&mut self) -> Result<Pending, LuaError> {
4331        self.resume_depth = self.resume_depth.saturating_sub(1);
4332        let Some(r) = self.cur.resumer.take() else {
4333            return Err(LuaError::msg("internal: coroutine without a resumer"));
4334        };
4335        self.swap_to(r);
4336        self.cur.status = CoStatus::Running;
4337        self.cur.resume_pending.take().ok_or_else(|| LuaError::msg("internal: resumer not waiting"))
4338    }
4339
4340    fn do_yield(&mut self, func: usize, nres: i32, kind: FrameKind) -> Result<(), LuaError> {
4341        // Raised from the yield itself, which has no position.
4342        if self.cur_ref == self.main_ref {
4343            return Err(LuaError::Value(self.new_str(b"attempt to yield from outside a coroutine")?));
4344        }
4345        // A coroutine with no resumer runs its `__close` handlers for `coroutine.close`:
4346        // C Lua's message for any coroutine that cannot yield (S5GC-6).
4347        if self.cur.nny > 0 || self.cur.resumer.is_none() {
4348            return Err(LuaError::Value(self.new_str(b"attempt to yield across a C-call boundary")?));
4349        }
4350        let vals = std::mem::take(&mut self.rets);
4351        self.cur.yield_pending = Some(Pending { func, nresults: nres, wrap: false, from_lua: false, kind });
4352        self.cur.status = CoStatus::Suspended;
4353        self.deliver(vals)
4354    }
4355
4356    /// A new coroutine running `f`, on a spare stack when there is one (`retire_stack`).
4357    ///
4358    /// LR-8: a coroutine's first resume grows its stack to a register window (about 4.5
4359    /// KiB), a `__close` handler run by `coroutine.close` to twice that, and a closed or
4360    /// finished coroutine kept it until the collector freed the thread. With the collector
4361    /// stopped (or a long pause) every new coroutine touched about 10 KiB of fresh pages
4362    /// nothing reused: making, resuming and closing one ran at 10x to 20x plain code per
4363    /// unit of fuel on a process's first runs (a coroutine closed from one 15,000 slots
4364    /// deep, more: `swap_in_for_close`). A closed or finished coroutine's stack is given to
4365    /// the next one now: about 860 bytes a coroutine stay fresh (C Lua: 960), and with the
4366    /// collector stopped making and closing one costs what it does with it running. One
4367    /// that is never closed nor finished (a `wrap` left suspended) still maps a window,
4368    /// 9x plain code per unit of fuel with the collector stopped, whose cycles are what
4369    /// paid for it otherwise: the window is charged at its first resume (`COROUTINE_COST`).
4370    pub(crate) fn new_coroutine(&mut self, f: Value) -> Result<ThreadRef, LuaError> {
4371        // A thread made and later swept (`wrap` paid nothing for it).
4372        self.charge(8)?;
4373        let mut stack = match self.spare_stacks.pop() {
4374            Some(s) => {
4375                self.heap.mem.slack_out(s.capacity() * SLOT_BYTES);
4376                s
4377            }
4378            // Its first resume makes the room it needs.
4379            None => Vec::with_capacity(1),
4380        };
4381        stack.clear();
4382        stack.push(f);
4383        let st = ThreadState { stack, fresh: true, ..ThreadState::default() };
4384        // `f` is the caller's argument, so a collection here keeps it.
4385        self.charge_mem(st.mem_size())?;
4386        let t = self.heap.place_thread(st);
4387        self.hold(Value::Thread(t));
4388        Ok(t)
4389    }
4390
4391    /// Takes the stack of `co`, a coroutine that was closed or finished, for a new
4392    /// coroutine to reuse (`new_coroutine`); its frame records go back to the system. Only
4393    /// a dead thread holding nothing on its stack (no frames kept for a traceback, no
4394    /// open upvalues, no pending to-be-closed variables) gives it up.
4395    pub(crate) fn retire_stack(&mut self, co: ThreadRef) {
4396        if co == self.cur_ref || co == self.main_ref {
4397            return;
4398        }
4399        if !self.heap.threads.live(co.idx, co.generation) {
4400            return;
4401        }
4402        let Some(t) = self.heap.threads.get_mut(co.idx) else { return };
4403        if t.status != CoStatus::Dead || t.fresh || !t.frames.is_empty() || !t.tbc.is_empty() || !t.open_upvals.is_empty() {
4404            return;
4405        }
4406        let mut stack = std::mem::take(&mut t.stack);
4407        let frames = std::mem::take(&mut t.frames);
4408        let mem = &mut self.heap.mem;
4409        mem.release(frames.capacity() * crate::heap::FRAME_BYTES);
4410        let cap = stack.capacity();
4411        mem.release(cap * SLOT_BYTES);
4412        // (A kept stack goes back into `used` as slack: resident, counted, not live.)
4413        let held: usize = self.spare_stacks.iter().map(|s| s.capacity() * SLOT_BYTES).sum();
4414        if (1..=SPARE_STACK_SLOTS).contains(&cap)
4415            && self.spare_stacks.len() < SPARE_STACKS
4416            && held + cap * SLOT_BYTES <= mem.cap / 16
4417        {
4418            stack.clear();
4419            mem.slack_in(cap * SLOT_BYTES);
4420            self.spare_stacks.push(stack);
4421        }
4422    }
4423
4424    /// Gives the spare coroutine stacks back to the system.
4425    fn drop_spare_stacks(&mut self) {
4426        for s in self.spare_stacks.drain(..) {
4427            self.heap.mem.slack_out(s.capacity() * SLOT_BYTES);
4428        }
4429    }
4430
4431    // ---- the loop ----
4432
4433    /// Runs until the thread `bthread` is back to `bdepth` frames.
4434    pub(crate) fn execute(&mut self, bthread: ThreadRef, bdepth: usize) -> Result<(), LuaError> {
4435        loop {
4436            match self.run(bthread, bdepth) {
4437                Ok(()) => return Ok(()),
4438                Err(e) => self.on_error(e, bthread, bdepth)?,
4439            }
4440        }
4441    }
4442
4443    /// The execution loop. Lua-to-Lua calls and returns switch frames here, without
4444    /// leaving; it returns when the thread `bthread` is back to `bdepth` frames. Errors
4445    /// leave the failing frame's `pc` (and the fuel) saved.
4446    ///
4447    /// Registers are a 256-slot window of the stack (`ensure_window` keeps it in bounds),
4448    /// indexed by their 8-bit numbers without checks; fuel lives in a local, written back
4449    /// before anything that looks at it.
4450    #[allow(clippy::too_many_lines, reason = "the interpreter's dispatch is one match")]
4451    #[allow(clippy::indexing_slicing, reason = "a u8 register into the 256-slot window cannot be out of bounds")]
4452    fn run(&mut self, bthread: ThreadRef, bdepth: usize) -> Result<(), LuaError> {
4453        use crate::debug::Operand as O;
4454        let mut ctx = self.fast_ctx();
4455        let mut epoch = self.ctx_epoch;
4456        // The width of the fast loop that just switched frames and stopped (in the frame
4457        // `'reload` then picks up). Stopped in a frame of its own width, it stopped at the
4458        // instruction it cannot run, so that one runs in full without entering it again
4459        // for nothing (natives right after a call or return paid two entries).
4460        let mut fast_tried: Option<bool> = None;
4461        'reload: loop {
4462            if self.cur_ref == bthread && self.cur.frames.len() <= bdepth {
4463                return Ok(());
4464            }
4465            let Some(frame) = self.cur.frames.last() else { return Ok(()) };
4466            let pidx = frame.proto;
4467            let closure = frame.closure;
4468            // Register 0; `base` is the same but for an instruction after `Window`.
4469            let frame_base = frame.base;
4470            let mut base = frame_base;
4471            let mut pc = frame.pc;
4472            let mut fuel = self.fuel;
4473            let wide = self.proto(pidx).is_some_and(Proto::wide);
4474            let width = if wide { WIDE_WINDOW } else { WINDOW };
4475            if self.cur.stack.len() < base + width {
4476                self.ensure_window(base, width)?;
4477            }
4478
4479            macro_rules! save {
4480                () => {{
4481                    if let Some(f) = self.cur.frames.last_mut() {
4482                        f.pc = pc;
4483                    }
4484                    self.fuel = fuel;
4485                }};
4486            }
4487            // A call that may charge fuel or switch frames: state saved before, fuel back
4488            // after.
4489            macro_rules! call {
4490                ($e:expr) => {{
4491                    save!();
4492                    let r = $e;
4493                    fuel = self.fuel;
4494                    r
4495                }};
4496            }
4497            // A collector step at an instruction (`gc_due_step`). Paused at the end of the
4498            // host's poll, an instruction that steps before its work (`before`: nothing done
4499            // yet) runs again on resume, without the step (`due_skip`) and with its fetch's
4500            // unit given back; one that steps after its work goes on with the next.
4501            macro_rules! gc_step_at {
4502                ($before:expr) => {
4503                    if let Err(e) = call!(self.gc_due_step()) {
4504                        save!();
4505                        if $before && e.is_pending() {
4506                            if let Some(f) = self.cur.frames.last_mut() {
4507                                f.pc = pc - 1 - usize::from(base != frame_base);
4508                            }
4509                            self.fuel += 1;
4510                            self.due_skip = true;
4511                            self.rewound = true;
4512                        }
4513                        return Err(e);
4514                    }
4515                };
4516            }
4517            macro_rules! t {
4518                ($e:expr) => {
4519                    match $e {
4520                        Ok(v) => v,
4521                        Err(e) => {
4522                            save!();
4523                            return Err(e);
4524                        }
4525                    }
4526                };
4527            }
4528            // `t!(call!(..))` for a call that may pop the running frame (a return, a tail call):
4529            // its state was saved before, and on an error the frame on top may be its caller,
4530            // whose own position must stay (S5COR-11: saving again wrote the returning
4531            // function's position into the caller, so an error a metamethod's continuation
4532            // raised there named the wrong line).
4533            macro_rules! tpop {
4534                // (Both uses reload the frame, and the fuel with it, right after.)
4535                ($e:expr) => {{
4536                    save!();
4537                    if let Err(e) = $e {
4538                        return Err(e);
4539                    }
4540                }};
4541            }
4542            macro_rules! ta {
4543                ($e:expr, $ops:expr) => {
4544                    match $e {
4545                        Ok(v) => v,
4546                        Err(e) => {
4547                            save!();
4548                            let ops = $ops;
4549                            return Err(self.annotate(e, pidx, pc - 1, &ops));
4550                        }
4551                    }
4552                };
4553            }
4554            // After a call that pushed a frame (or switched threads): state was saved by
4555            // `call!` before it.
4556            macro_rules! reload {
4557                () => {
4558                    continue 'reload
4559                };
4560            }
4561            macro_rules! reg {
4562                ($i:expr) => {
4563                    self.cur.stack.get(base + ($i) as usize).copied().unwrap_or(Value::Nil)
4564                };
4565            }
4566            macro_rules! setr {
4567                ($i:expr, $v:expr) => {{
4568                    let v = $v;
4569                    if let Some(s) = self.cur.stack.get_mut(base + ($i) as usize) {
4570                        *s = v;
4571                    }
4572                }};
4573            }
4574            macro_rules! kv {
4575                ($k:expr) => {
4576                    self.heap.protos.at(pidx as usize).and_then(|p: &Proto| p.consts.get(($k) as usize).copied()).unwrap_or(Value::Nil)
4577                };
4578            }
4579            macro_rules! rk {
4580                ($x:expr) => {{
4581                    let x: Rk = $x;
4582                    if x.is_const() { kv!(x.index()) } else { reg!(x.index()) }
4583                }};
4584            }
4585            // Arithmetic with a fast path for numbers and the general path (strings,
4586            // metamethods, errors) otherwise.
4587            // Arithmetic: numbers by the shared rules (`fast::arith`), else the general
4588            // path (strings, metamethods, errors).
4589            macro_rules! arith {
4590                ($op:expr, $a:expr, $x:expr, $y:expr, $ops:expr) => {{
4591                    let (x, y): (Value, Value) = ($x, $y);
4592                    let fast = if $op == ArithOp::Sub && matches!(y, Value::Int(_)) && $ops.len() == 2 && matches!($ops[1], O::Rk(r) if r.is_const()) {
4593                        crate::fast::sub_k(x, y)
4594                    } else {
4595                        crate::fast::arith($op, x, y)
4596                    };
4597                    match fast {
4598                        Some(v) => setr!($a, v),
4599                        None => match ta!(call!(self.arith($op, x, y, Cont::Store(base + usize::from($a)))), $ops) {
4600                            Some(v) => setr!($a, v),
4601                            None => reload!(),
4602                        },
4603                    }
4604                }};
4605            }
4606            // `arith!` on two registers, or on a register and a constant.
4607            macro_rules! arith_rr {
4608                ($op:ident, $a:expr, $b:expr, $c:expr) => {
4609                    arith!(ArithOp::$op, $a, reg!(usize::from($b)), reg!(usize::from($c)), [O::Reg($b), O::Reg($c)])
4610                };
4611            }
4612            macro_rules! arith_rk {
4613                ($op:ident, $a:expr, $b:expr, $k:expr) => {
4614                    arith!(ArithOp::$op, $a, reg!(usize::from($b)), kv!($k), [O::Reg($b), O::Rk(Rk::konst($k))])
4615                };
4616            }
4617
4618            // The fast loop's context: made again only when what it copies changed
4619            // (`ctx_epoch`); the running thread and the stop depth are this frame's.
4620            if self.ctx_epoch != epoch {
4621                ctx = self.fast_ctx();
4622                epoch = self.ctx_epoch;
4623            }
4624            ctx.cur = self.cur_ref;
4625            ctx.stop_depth = if self.cur_ref == bthread { bdepth } else { 0 };
4626            // Whether the next instruction is tried in the fast loop (see `fast_tried`).
4627            let mut fast_now = self.fast && fast_tried.take() != Some(wide);
4628            loop {
4629                // The common cases run in the fast loop; it stops at the first instruction
4630                // it cannot finish, which runs below in full.
4631                save!();
4632                let moved = fast_now
4633                    && if wide {
4634                        crate::fast::run::<WIDE_WINDOW>(&mut self.heap, &mut self.cur, &mut self.top, &ctx, &mut self.fuel)
4635                    } else {
4636                        crate::fast::run::<WINDOW>(&mut self.heap, &mut self.cur, &mut self.top, &ctx, &mut self.fuel)
4637                    };
4638                if moved {
4639                    fast_tried = Some(wide);
4640                    continue 'reload;
4641                }
4642                self.full_steps += u64::from(self.fast);
4643                fast_now = self.fast;
4644                fuel = self.fuel;
4645                pc = self.cur.frames.last().map_or(pc, |f| f.pc);
4646                // One step, plus the probe steps of the instruction before (see
4647                // `table::PROBES`; the fast loop charges them at the same point).
4648                fuel = match crate::table::take_probes() {
4649                    0 => fuel.saturating_sub(1),
4650                    n => fuel.saturating_sub(1 + i64::try_from(n).unwrap_or(i64::MAX)),
4651                };
4652                if fuel < 0 {
4653                    // The next slice of fuel, or the stop (fuel, interrupt, deadline).
4654                    self.fuel = fuel;
4655                    if let Err(e) = self.refuel() {
4656                        save!();
4657                        return Err(e);
4658                    }
4659                    fuel = self.fuel;
4660                }
4661                let Some(ins) = self.heap.protos.at(pidx as usize).and_then(|p| p.code.get(pc)).copied() else {
4662                    save!();
4663                    return Err(LuaError::msg("internal: ran past the end of the code"));
4664                };
4665                pc += 1;
4666                base = frame_base;
4667                let ins = match ins {
4668                    // The next instruction, its registers from `frame_base + off`.
4669                    Instr::Window { off } => {
4670                        base = frame_base + off as usize;
4671                        if self.cur.stack.len() < base + width {
4672                            t!(call!(self.ensure_window(base, width)));
4673                        }
4674                        let Some(next) = self.heap.protos.at(pidx as usize).and_then(|p| p.code.get(pc)).copied() else {
4675                            save!();
4676                            return Err(LuaError::msg("internal: ran past the end of the code"));
4677                        };
4678                        pc += 1;
4679                        next
4680                    }
4681                    other => other,
4682                };
4683                match ins {
4684                    Instr::Window { .. } => {}
4685                    Instr::MoveAbs { a, b, b_hi } => {
4686                        // (The source counts from the window: `base` is `frame_base` unless a
4687                        // `Window` came first.)
4688                        let (dst, src) = (frame_base + a as usize, base + (usize::from(b) | usize::from(b_hi) << 16));
4689                        if self.cur.stack.len() <= dst.max(src) {
4690                            t!(call!(self.ensure_window(dst.max(src), 1)));
4691                        }
4692                        let v = self.cur.stack.get(src).copied().unwrap_or(Value::Nil);
4693                        if let Some(s) = self.cur.stack.get_mut(dst) {
4694                            *s = v;
4695                        }
4696                    }
4697                    Instr::SetTop { n } => {
4698                        let t = frame_base + n as usize;
4699                        t!(call!(self.ensure_stack(t + EXTRA_STACK)));
4700                        self.top = t;
4701                    }
4702                    Instr::PadNil { n } => {
4703                        let to = frame_base + n as usize;
4704                        let from = self.top.min(to);
4705                        // Results adjusted to a count past 16 bits: work by the number filled.
4706                        t!(call!(self.charge((to - from) as u64 / 8)));
4707                        t!(call!(self.ensure_stack(to + EXTRA_STACK)));
4708                        if let Some(s) = self.cur.stack.get_mut(from..to) {
4709                            s.fill(Value::Nil);
4710                        }
4711                    }
4712                    Instr::Move { a, b } => setr!(usize::from(a), reg!(usize::from(b))),
4713                    Instr::LoadK { a, k } => {
4714                        let v = kv!(k);
4715                        setr!(a, v);
4716                    }
4717                    Instr::LoadInt { a, i } => setr!(usize::from(a), Value::Int(i64::from(i))),
4718                    Instr::LoadBool { a, v } => setr!(usize::from(a), Value::Bool(v)),
4719                    Instr::LoadFalseSkip { a } => {
4720                        setr!(usize::from(a), Value::Bool(false));
4721                        pc += 1;
4722                    }
4723                    Instr::LoadNil { a, n } => {
4724                        // SEC-M7: up to 65,536 registers in one instruction (frames past 255
4725                        // registers): paid past 16, as every list of values is.
4726                        t!(call!(self.charge(list_fuel(usize::from(n) + 1))));
4727                        for i in 0..=usize::from(n) {
4728                            setr!(usize::from(a) + i, Value::Nil);
4729                        }
4730                    }
4731                    Instr::GetUpval { a, u } => {
4732                        let v = self.upval_get(closure, u);
4733                        setr!(a, v);
4734                    }
4735                    Instr::GetSelf { a, .. } => setr!(a, Value::Func(closure)),
4736                    Instr::SetUpval { a, u } => {
4737                        let v = reg!(usize::from(a));
4738                        self.upval_set(closure, u, v);
4739                    }
4740                    Instr::GetTabUp { a, u, k } => {
4741                        let t = self.upval_get(closure, u);
4742                        let key = kv!(k);
4743                        if let Value::Table(tr) = t {
4744                            if let Some(v) = self.get_field_cached(tr, key, pidx, pc - 1) {
4745                                setr!(a, v);
4746                                continue;
4747                            }
4748                        }
4749                        match ta!(call!(self.index(t, key, Cont::Store(base + usize::from(a)))), [O::Upval(u)]) {
4750                            Some(v) => setr!(a, v),
4751                            None => reload!(),
4752                        }
4753                    }
4754                    Instr::SetTabUp { u, k, v } => {
4755                        let t = self.upval_get(closure, u);
4756                        let key = kv!(k);
4757                        let val = rk!(v);
4758                        // (Through `call!`, as `SetTableK`: a rehash charges fuel, and the
4759                        // count here must not be written back over it. PERF-SEC-1.)
4760                        if let Value::Table(tr) = t
4761                            && t!(call!(self.set_field_fast(tr, key, val)))
4762                        {
4763                            continue;
4764                        }
4765                        if !ta!(call!(self.set_index(t, key, val)), [O::Upval(u)]) {
4766                            reload!();
4767                        }
4768                    }
4769                    Instr::GetTable { a, b, c } => {
4770                        let t = reg!(usize::from(b));
4771                        let key = reg!(usize::from(c));
4772                        if let Value::Table(tr) = t
4773                            && let Some(tab) = self.heap.tables.get(tr.idx)
4774                            && !matches!(key, Value::Str(r) if self.heap.key_needs_settling(r))
4775                        {
4776                            let v = self.heap.get_in(tab, key);
4777                            if !v.is_nil() || tab.meta.is_none() {
4778                                setr!(a, v);
4779                                continue;
4780                            }
4781                        }
4782                        match ta!(call!(self.index(t, key, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4783                            Some(v) => setr!(a, v),
4784                            None => reload!(),
4785                        }
4786                    }
4787                    Instr::GetTableK { a, b, k } => {
4788                        let t = reg!(usize::from(b));
4789                        let key = kv!(k);
4790                        if let Value::Table(tr) = t
4791                            && let Some(v) = self.get_field_cached(tr, key, pidx, pc - 1)
4792                        {
4793                            setr!(a, v);
4794                            continue;
4795                        }
4796                        match ta!(call!(self.index(t, key, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4797                            Some(v) => setr!(a, v),
4798                            None => reload!(),
4799                        }
4800                    }
4801                    Instr::SelfK { a, b, k } => {
4802                        let t = reg!(usize::from(b));
4803                        setr!(usize::from(a) + 1, t);
4804                        let key = kv!(k);
4805                        // (The fast loop finds methods; here, the general lookup, which
4806                        // charges each `__index` link as the fast loop does.)
4807                        match ta!(call!(self.index(t, key, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4808                            Some(v) => setr!(a, v),
4809                            None => reload!(),
4810                        }
4811                    }
4812                    Instr::SetTable { a, b, c } => {
4813                        let t = reg!(usize::from(a));
4814                        let key = reg!(usize::from(b));
4815                        let val = rk!(c);
4816                        if let Value::Table(tr) = t
4817                            && self.heap.tables.get(tr.idx).is_some_and(|t| t.meta.is_none())
4818                        {
4819                            t!(call!(self.raw_set(tr, key, val)));
4820                            continue;
4821                        }
4822                        if !ta!(call!(self.set_index(t, key, val)), [O::Reg(a)]) {
4823                            reload!();
4824                        }
4825                    }
4826                    Instr::SetTableK { a, k, c } => {
4827                        let t = reg!(usize::from(a));
4828                        let key = kv!(k);
4829                        let val = rk!(c);
4830                        if let Value::Table(tr) = t
4831                            && t!(call!(self.set_field_fast(tr, key, val)))
4832                        {
4833                            continue;
4834                        }
4835                        if !ta!(call!(self.set_index(t, key, val)), [O::Reg(a)]) {
4836                            reload!();
4837                        }
4838                    }
4839                    Instr::NewTable { a, arr, hash } => {
4840                        if self.heap.gc_due() && !std::mem::take(&mut self.due_skip) {
4841                            gc_step_at!(true);
4842                        }
4843                        let (room, asize, hash) = crate::bytecode::newtable_sizes(arr, hash);
4844                        let tr = t!(call!(self.new_table_sized::<true>(room, asize, hash)));
4845                        setr!(a, Value::Table(tr));
4846                    }
4847                    Instr::Add { a, b, c } => arith_rr!(Add, a, b, c),
4848                    Instr::AddK { a, b, k } => arith_rk!(Add, a, b, k),
4849                    Instr::Sub { a, b, c } => arith_rr!(Sub, a, b, c),
4850                    Instr::SubK { a, b, k } => arith_rk!(Sub, a, b, k),
4851                    Instr::Mul { a, b, c } => arith_rr!(Mul, a, b, c),
4852                    Instr::MulK { a, b, k } => arith_rk!(Mul, a, b, k),
4853                    Instr::Div { a, b, c } => arith_rr!(Div, a, b, c),
4854                    Instr::DivK { a, b, k } => arith_rk!(Div, a, b, k),
4855                    Instr::Mod { a, b, c } => arith_rr!(Mod, a, b, c),
4856                    Instr::ModK { a, b, k } => arith_rk!(Mod, a, b, k),
4857                    Instr::IDiv { a, b, c } => arith_rr!(IDiv, a, b, c),
4858                    Instr::IDivK { a, b, k } => arith_rk!(IDiv, a, b, k),
4859                    Instr::Arith { op, a, b, c } => {
4860                        let x = rk!(b);
4861                        let y = rk!(c);
4862                        let fast = if op == ArithOp::Sub && c.is_const() { crate::fast::sub_k(x, y) } else { crate::fast::arith(op, x, y) };
4863                        match fast {
4864                            Some(v) => setr!(a, v),
4865                            None => {
4866                                match ta!(call!(self.arith(op, x, y, Cont::Store(base + usize::from(a)))), [O::Rk(b), O::Rk(c)]) {
4867                                    Some(v) => setr!(a, v),
4868                                    None => reload!(),
4869                                }
4870                            }
4871                        }
4872                    }
4873                    Instr::Unm { a, b } => {
4874                        let x = reg!(usize::from(b));
4875                        match x {
4876                            Value::Int(i) => setr!(usize::from(a), Value::Int(i.wrapping_neg())),
4877                            Value::Num(f) => setr!(usize::from(a), Value::Num(-f)),
4878                            _ => match ta!(call!(self.unary(Tm::Unm, x, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4879                                Some(v) => setr!(a, v),
4880                                None => reload!(),
4881                            },
4882                        }
4883                    }
4884                    Instr::BNot { a, b } => {
4885                        let x = reg!(usize::from(b));
4886                        match x {
4887                            Value::Int(i) => setr!(usize::from(a), Value::Int(!i)),
4888                            _ => match ta!(call!(self.unary(Tm::BNot, x, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4889                                Some(v) => setr!(a, v),
4890                                None => reload!(),
4891                            },
4892                        }
4893                    }
4894                    Instr::Not { a, b } => setr!(usize::from(a), Value::Bool(!reg!(usize::from(b)).truthy())),
4895                    Instr::Len { a, b } => {
4896                        let x = reg!(usize::from(b));
4897                        match x {
4898                            Value::Str(s) => {
4899                                let n = self.heap.str_bytes(s).len() as i64;
4900                                setr!(a, Value::Int(n));
4901                            }
4902                            Value::Table(tr) if self.heap.tables.get(tr.idx).is_some_and(|t| t.meta.is_none()) => {
4903                                let n = self.raw_len(tr);
4904                                setr!(a, Value::Int(n));
4905                            }
4906                            _ => match ta!(call!(self.len(x, Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4907                                Some(v) => setr!(a, v),
4908                                None => reload!(),
4909                            },
4910                        }
4911                    }
4912                    Instr::Concat { a, n } => {
4913                        if self.heap.gc_due() && !std::mem::take(&mut self.due_skip) {
4914                            gc_step_at!(true);
4915                        }
4916                        let first = base + usize::from(a);
4917                        let done = match call!(self.concat(first, usize::from(n))) {
4918                            Ok(d) => d,
4919                            Err(e) => {
4920                                // Which operand failed: concat reports it relative to `a`.
4921                                let e = match e.into_kind() {
4922                                    ErrorKind::Type { op, ty, operand } => {
4923                                        let r = a.saturating_add(u16::from(operand));
4924                                        self.annotate(ErrorKind::Type { op, ty, operand: 0 }.into(), pidx, pc - 1, &[O::Reg(r)])
4925                                    }
4926                                    other => other.into(),
4927                                };
4928                                save!();
4929                                return Err(e);
4930                            }
4931                        };
4932                        if !done {
4933                            reload!();
4934                        }
4935                    }
4936                    Instr::ToStr { a, b } => {
4937                        let x = reg!(usize::from(b));
4938                        if matches!(x, Value::Str(_)) {
4939                            setr!(usize::from(a), x);
4940                        } else {
4941                            let s = t!(call!(self.tostring(x)));
4942                            setr!(a, s);
4943                        }
4944                    }
4945                    Instr::Jmp { off, close } => {
4946                        pc = (pc as i64 + i64::from(off)) as usize;
4947                        if close > 0 && !t!(call!(self.close_async(base + usize::from(close) - 1, AfterClose::Nothing, 0))) {
4948                            reload!();
4949                        }
4950                    }
4951                    Instr::AddI { a, b, i, sub } => {
4952                        // As `x + i` (or `x - -i`, whose metamethod and message see `-`).
4953                        let x = reg!(usize::from(b));
4954                        match crate::fast::arith(ArithOp::Add, x, Value::Int(i64::from(i))) {
4955                            Some(v) => setr!(a, v),
4956                            None => {
4957                                let (op, y) = if sub { (ArithOp::Sub, -i64::from(i)) } else { (ArithOp::Add, i64::from(i)) };
4958                                match ta!(call!(self.arith(op, x, Value::Int(y), Cont::Store(base + usize::from(a)))), [O::Reg(b)]) {
4959                                    Some(v) => setr!(a, v),
4960                                    None => reload!(),
4961                                }
4962                            }
4963                        }
4964                    }
4965                    Instr::Pow { a, b, c } => arith_rr!(Pow, a, b, c),
4966                    Instr::PowK { a, b, k } => arith_rk!(Pow, a, b, k),
4967                    Instr::BAnd { a, b, c } => arith_rr!(BAnd, a, b, c),
4968                    Instr::BAndK { a, b, k } => arith_rk!(BAnd, a, b, k),
4969                    Instr::BOr { a, b, c } => arith_rr!(BOr, a, b, c),
4970                    Instr::BOrK { a, b, k } => arith_rk!(BOr, a, b, k),
4971                    Instr::BXor { a, b, c } => arith_rr!(BXor, a, b, c),
4972                    Instr::BXorK { a, b, k } => arith_rk!(BXor, a, b, k),
4973                    Instr::Shl { a, b, c } => arith_rr!(Shl, a, b, c),
4974                    Instr::ShlK { a, b, k } => arith_rk!(Shl, a, b, k),
4975                    Instr::Shr { a, b, c } => arith_rr!(Shr, a, b, c),
4976                    Instr::ShrK { a, b, k } => arith_rk!(Shr, a, b, k),
4977                    Instr::EqK { a, k, eq } => {
4978                        let (x, y) = (reg!(usize::from(a)), kv!(k));
4979                        let res = x.raw_eq(y)
4980                            || match (x, y) {
4981                                (Value::Str(sa), Value::Str(sb)) => t!(call!(self.str_eq(sa, sb))),
4982                                _ => false,
4983                            };
4984                        if res != eq {
4985                            pc += 1;
4986                        }
4987                    }
4988                    Instr::EqI { a, i, eq } => {
4989                        if reg!(usize::from(a)).raw_eq(Value::Int(i64::from(i))) != eq {
4990                            pc += 1;
4991                        }
4992                    }
4993                    Instr::LtI { a, i, k } | Instr::LeI { a, i, k } | Instr::GtI { a, i, k } | Instr::GeI { a, i, k } => {
4994                        // Written with the immediate on the right (`<`, `<=`) or on the left.
4995                        let (r, n) = (reg!(usize::from(a)), Value::Int(i64::from(i)));
4996                        let (tm, x, y, le) = match ins {
4997                            Instr::LtI { .. } => (Tm::Lt, r, n, false),
4998                            Instr::LeI { .. } => (Tm::Le, r, n, true),
4999                            Instr::GtI { .. } => (Tm::Lt, n, r, false),
5000                            _ => (Tm::Le, n, r, true),
5001                        };
5002                        let res = match crate::fast::less(x, y, le) {
5003                            Some(r) => r,
5004                            None => match t!(call!(self.order_slow(tm, x, y, Cont::Cond { k }))) {
5005                                Some(r) => r,
5006                                None => reload!(),
5007                            },
5008                        };
5009                        if res != k {
5010                            pc += 1;
5011                        }
5012                    }
5013                    Instr::Eq { b, c, k } => {
5014                        let x = rk!(b);
5015                        let y = rk!(c);
5016                        let res = if x.raw_eq(y) {
5017                            true
5018                        } else {
5019                            match (x, y) {
5020                                (Value::Str(sa), Value::Str(sb)) => t!(call!(self.str_eq(sa, sb))),
5021                                (Value::Table(_), Value::Table(_)) | (Value::UserData(_), Value::UserData(_)) => {
5022                                    match t!(call!(self.eq_slow(x, y, Cont::Cond { k }))) {
5023                                        Some(r) => r,
5024                                        None => reload!(),
5025                                    }
5026                                }
5027                                _ => false,
5028                            }
5029                        };
5030                        if res != k {
5031                            pc += 1;
5032                        }
5033                    }
5034                    Instr::Lt { b, c, k } => {
5035                        let x = rk!(b);
5036                        let y = rk!(c);
5037                        let res = match (x, y) {
5038                            _ if let Some(r) = crate::fast::less(x, y, false) => r,
5039                            (Value::Str(s1), Value::Str(s2)) => {
5040                                let n = self.heap.str_bytes(s1).len().min(self.heap.str_bytes(s2).len());
5041                                t!(call!(self.charge_bytes(n)));
5042                                self.heap.str_bytes(s1) < self.heap.str_bytes(s2)
5043                            }
5044                            _ => match t!(call!(self.order_slow(Tm::Lt, x, y, Cont::Cond { k }))) {
5045                                Some(r) => r,
5046                                None => reload!(),
5047                            },
5048                        };
5049                        if res != k {
5050                            pc += 1;
5051                        }
5052                    }
5053                    Instr::Le { b, c, k } => {
5054                        let x = rk!(b);
5055                        let y = rk!(c);
5056                        let res = match (x, y) {
5057                            _ if let Some(r) = crate::fast::less(x, y, true) => r,
5058                            (Value::Str(s1), Value::Str(s2)) => {
5059                                let n = self.heap.str_bytes(s1).len().min(self.heap.str_bytes(s2).len());
5060                                t!(call!(self.charge_bytes(n)));
5061                                self.heap.str_bytes(s1) <= self.heap.str_bytes(s2)
5062                            }
5063                            _ => match t!(call!(self.order_slow(Tm::Le, x, y, Cont::Cond { k }))) {
5064                                Some(r) => r,
5065                                None => reload!(),
5066                            },
5067                        };
5068                        if res != k {
5069                            pc += 1;
5070                        }
5071                    }
5072                    Instr::Test { a, k } => {
5073                        if reg!(usize::from(a)).truthy() != k {
5074                            pc += 1;
5075                        }
5076                    }
5077                    Instr::TestSet { a, b, k } => {
5078                        let v = reg!(usize::from(b));
5079                        if v.truthy() == k {
5080                            setr!(usize::from(a), v);
5081                        } else {
5082                            pc += 1;
5083                        }
5084                    }
5085                    Instr::Call { a, b, c } => {
5086                        let func = base + usize::from(a);
5087                        let nargs = if b == MULTI { self.top.saturating_sub(func + 1) } else { usize::from(b) };
5088                        let nres = if c == MULTI { -1 } else { i32::from(c) };
5089                        // A Lua function: a new frame, run here. A library function: called
5090                        // straight away.
5091                        let called = match reg!(usize::from(a)) {
5092                            Value::Func(f) => match self.heap.funcs.get(f.idx) {
5093                                Some(Func::Lua { proto, .. }) => {
5094                                    let proto = *proto;
5095                                    ta!(call!(self.push_frame(f, proto, func, nargs, nres, FrameKind::Normal, true)), [O::Reg(a)]);
5096                                    continue 'reload;
5097                                }
5098                                Some(Func::Native { .. }) if Some(f) == self.names.yield_fn && self.limit_hit.is_none() => {
5099                                    call!(self.yield_from_lua(func, nargs, nres))
5100                                }
5101                                // `collectgarbage('step')`: its step first, here, where the
5102                                // call can pause at the end of the host's poll (in the
5103                                // function it could not); paused, the call runs again on
5104                                // resume, its step done, as an instruction that steps before
5105                                // its work does (`gc_step_at!`).
5106                                Some(Func::Native { f: nf, name, .. })
5107                                    if Some(f) == self.names.collect_fn && self.limit_hit.is_none() && self.gc_call_before.is_none() && self.basic_step_call(func, nargs) =>
5108                                {
5109                                    let (nf, name) = (*nf, *name);
5110                                    if let Err(e) = call!(self.collect_step()) {
5111                                        save!();
5112                                        if e.is_pending() {
5113                                            if let Some(fr) = self.cur.frames.last_mut() {
5114                                                fr.pc = pc - 1 - usize::from(base != frame_base);
5115                                            }
5116                                            self.fuel += 1;
5117                                            self.rewound = true;
5118                                        } else {
5119                                            self.gc_call_before = None;
5120                                        }
5121                                        return Err(e);
5122                                    }
5123                                    call!(self.call_native(func, nargs, nres, FrameKind::Normal, true, name, nf))
5124                                }
5125                                Some(Func::Native { f: nf, name, in_place, .. }) => {
5126                                    let (nf, name, op) = (*nf, *name, *in_place);
5127                                    call!(match if op > 0 { self.call_in_place(op, func, nargs, nres) } else { None } {
5128                                        Some(r) => r,
5129                                        None => self.call_native(func, nargs, nres, FrameKind::Normal, true, name, nf),
5130                                    })
5131                                }
5132                                _ => call!(self.precall(func, nargs, nres, FrameKind::Normal, true)),
5133                            },
5134                            _ => call!(self.precall(func, nargs, nres, FrameKind::Normal, true)),
5135                        };
5136                        match ta!(called, [O::Reg(a)]) {
5137                            Called::Done => {
5138                                if self.heap.gc_due() {
5139                                    gc_step_at!(false);
5140                                }
5141                            }
5142                            Called::Lua | Called::Switched => continue 'reload,
5143                        }
5144                    }
5145                    Instr::TailCall { a, b } => {
5146                        let func = base + usize::from(a);
5147                        let mut nargs = if b == MULTI { self.top.saturating_sub(func + 1) } else { usize::from(b) };
5148                        // A callable object: its `__call` handler goes first, and the call stays
5149                        // a tail call when the handler is a Lua function.
5150                        let mut tries = 0;
5151                        while !matches!(self.st(func), Value::Func(_)) && tries < MAX_TAG_LOOP {
5152                            let fv = self.st(func);
5153                            let mm = self.tm(fv, Tm::Call);
5154                            if mm.is_nil() {
5155                                break;
5156                            }
5157                            t!(call!(self.charge(1 + nargs as u64 / 8)));
5158                            t!(call!(self.ensure_stack(func + nargs + 2 + EXTRA_STACK)));
5159                            self.cur.stack.copy_within(func..func + 1 + nargs, func + 1);
5160                            self.set_st(func, mm);
5161                            nargs += 1;
5162                            tries += 1;
5163                        }
5164                        let is_lua = matches!(self.st(func), Value::Func(f)
5165                            if matches!(self.heap.funcs.get(f.idx), Some(Func::Lua { .. })));
5166                        if is_lua {
5167                            tpop!(self.tail_call(func, nargs));
5168                            continue 'reload;
5169                        }
5170                        match ta!(call!(self.precall(func, nargs, -1, FrameKind::Normal, true)), [O::Reg(a)]) {
5171                            Called::Done => {}
5172                            Called::Lua | Called::Switched => continue 'reload,
5173                        }
5174                    }
5175                    Instr::Return { .. } | Instr::Return0 | Instr::Return1 { .. } => {
5176                        let (a, b) = match ins {
5177                            Instr::Return { a, b } => (a, b),
5178                            Instr::Return1 { a } => (a, 1),
5179                            _ => (0, 0),
5180                        };
5181                        let src = base + usize::from(a);
5182                        let n = if b == MULTI { self.top.saturating_sub(src) } else { usize::from(b) };
5183                        // The common case: nothing to close, few results, back to a Lua caller or
5184                        // to Rust above another frame (a callback: `finish_return` does no more
5185                        // then; under the last frame a coroutine finishes).
5186                        if n <= 16
5187                            && let Some(f) = self.cur.frames.last()
5188                            && (f.from_lua || self.cur.frames.len() > 1)
5189                            && matches!(f.kind, FrameKind::Normal)
5190                            && !self.cur.open_upvals.last().is_some_and(|(i, _)| *i >= base)
5191                            && !self.cur.tbc.last().is_some_and(|i| *i >= base)
5192                        {
5193                            let (func, wanted) = (f.func, f.nresults);
5194                            let want = if wanted < 0 { n } else { wanted as usize };
5195                            // (More than 16 wanted is paid: `move_results`, SEC-M7.)
5196                            if want <= 16 && func + want.max(n) < self.cur.stack.len() {
5197                                self.cur.stack.copy_within(src..src + n, func);
5198                                if let Some(rest) = self.cur.stack.get_mut(func + n..func + want) {
5199                                    rest.fill(Value::Nil);
5200                                }
5201                                if wanted < 0 {
5202                                    self.top = func + n;
5203                                }
5204                                self.cur.frames.pop();
5205                                self.fuel = fuel;
5206                                continue 'reload;
5207                            }
5208                        }
5209                        tpop!(self.do_return(src, n));
5210                        continue 'reload;
5211                    }
5212                    Instr::ForPrep { a, off } => {
5213                        if t!(call!(self.for_prep(base + usize::from(a)))) {
5214                            pc = (pc as i64 + i64::from(off)) as usize;
5215                        }
5216                    }
5217                    Instr::ForLoop { a, off } => {
5218                        let ra = usize::from(a);
5219                        match (reg!(ra), reg!(ra + 1), reg!(ra + 2)) {
5220                            (Value::Int(idx), Value::Int(count), Value::Int(step)) => {
5221                                if count as u64 > 0 {
5222                                    let i = idx.wrapping_add(step);
5223                                    setr!(ra + 1, Value::Int((count as u64 - 1) as i64));
5224                                    setr!(ra, Value::Int(i));
5225                                    setr!(ra + 3, Value::Int(i));
5226                                    pc = (pc as i64 + i64::from(off)) as usize;
5227                                }
5228                            }
5229                            (Value::Num(idx), Value::Num(limit), Value::Num(step)) => {
5230                                let i = idx + step;
5231                                if if step > 0.0 { i <= limit } else { limit <= i } {
5232                                    setr!(ra, Value::Num(i));
5233                                    setr!(ra + 3, Value::Num(i));
5234                                    pc = (pc as i64 + i64::from(off)) as usize;
5235                                }
5236                            }
5237                            _ => {}
5238                        }
5239                    }
5240                    Instr::TForPrep { a, off } => {
5241                        let slot = base + usize::from(a) + 3;
5242                        let v = self.st(slot);
5243                        if v.truthy() {
5244                            if self.tm(v, Tm::Close).is_nil() {
5245                                save!();
5246                                return Err(LuaError::msg("variable '(for state)' got a non-closable value"));
5247                            }
5248                            self.cur.tbc.push(slot);
5249                        }
5250                        pc = (pc as i64 + i64::from(off)) as usize;
5251                    }
5252                    Instr::TForCall { a, c } => {
5253                        let ra = usize::from(a);
5254                        setr!(ra + 4, reg!(ra));
5255                        setr!(ra + 5, reg!(ra + 1));
5256                        setr!(ra + 6, reg!(ra + 2));
5257                        let func = base + ra + 4;
5258                        if let Value::Func(f) = reg!(ra + 4)
5259                            && let Some(Func::Lua { proto, .. }) = self.heap.funcs.get(f.idx)
5260                        {
5261                            let proto = *proto;
5262                            ta!(call!(self.push_frame(f, proto, func, 2, tfor_wanted(c), FrameKind::Normal, true)), [O::Reg(a)]);
5263                            continue 'reload;
5264                        }
5265                        // C Lua names the callee of this call "for iterator" whatever it is.
5266                        let r = call!(self.precall(func, 2, tfor_wanted(c), FrameKind::Normal, true)).map_err(|e| match e.into_kind() {
5267                            ErrorKind::Call { ty } => LuaError::Msg(format!("attempt to call a {ty} value (for iterator 'for iterator')")),
5268                            e => e.into(),
5269                        });
5270                        match ta!(r, [O::Reg(a)]) {
5271                            Called::Done => {}
5272                            Called::Lua | Called::Switched => continue 'reload,
5273                        }
5274                    }
5275                    Instr::TForLoop { a, off } => {
5276                        let ra = usize::from(a);
5277                        let v = reg!(ra + 4);
5278                        if !v.is_nil() {
5279                            setr!(ra + 2, v);
5280                            pc = (pc as i64 + i64::from(off)) as usize;
5281                        }
5282                    }
5283                    Instr::SetList { a, n, off } => {
5284                        let ra = base + usize::from(a);
5285                        let count = if n == crate::bytecode::SETLIST_MULTI { self.top.saturating_sub(ra + 1) } else { usize::from(n) };
5286                        if let Value::Table(tr) = self.st(ra) {
5287                            save!();
5288                            // The table the collector traverses in chunks (S6GC-2e): the
5289                            // entries overwritten are marked first, those written after.
5290                            let part = tr.idx == self.heap.part;
5291                            if part {
5292                                for j in 0..count {
5293                                    self.heap.part_writing(tr.idx, Value::Int((off as usize + j + 1) as i64));
5294                                }
5295                            }
5296                            // The values straight from the stack (a copy would be an allocation
5297                            // per constructor).
5298                            let set = |heap: &mut Heap, stack: &[Value]| {
5299                                let vals = stack.get(ra + 1..ra + 1 + count).unwrap_or_default();
5300                                match heap.tables.get_mut(tr.idx) {
5301                                    Some(tab) => tab.set_list(off as usize, vals, &mut heap.mem),
5302                                    None => Ok(()),
5303                                }
5304                            };
5305                            // (The fuel the list's growth may take, refused past it: LR-29d.)
5306                            self.heap.mem.fuel = self.call_fuel();
5307                            let mut res = set(&mut self.heap, &self.cur.stack);
5308                            if matches!(res, Err(SetError::Memory)) {
5309                                t!(call!(self.emergency_gc()));
5310                                res = set(&mut self.heap, &self.cur.stack);
5311                            }
5312                            if part {
5313                                for j in 0..count {
5314                                    let v = self.cur.stack.get(ra + 1 + j).copied().unwrap_or_default();
5315                                    self.heap.part_written(tr.idx, Value::Int((off as usize + j + 1) as i64), if res.is_ok() { v } else { Value::Nil });
5316                                }
5317                            }
5318                            if let Err(e) = res {
5319                                save!();
5320                                // (A resize stopped by the interrupt or deadline, or refused
5321                                // for the fuel left: that limit.)
5322                                let k = match e {
5323                                    SetError::Stopped(k) => {
5324                                        let heap = &mut self.heap;
5325                                        let units = heap.tables.get_mut(tr.idx).map_or(0, |tab| tab.take_units(&heap.mem));
5326                                        let _ = self.charge(units);
5327                                        k
5328                                    }
5329                                    SetError::Fuel => {
5330                                        (self.fuel, self.reserve) = (-1, 0);
5331                                        LimitKind::Fuel
5332                                    }
5333                                    _ => return Err(self.memory_error(false)),
5334                                };
5335                                return Err(LuaError::Limit(k));
5336                            }
5337                            self.heap.barrier_table(tr);
5338                            let heap = &mut self.heap;
5339                            let resized = heap.tables.get_mut(tr.idx).map_or(0, |tab| tab.take_resized(&heap.mem));
5340                            if resized >= 16 {
5341                                t!(call!(self.charge(resized as u64 / 16)));
5342                            }
5343                        }
5344                    }
5345                    Instr::Closure { a, p } => {
5346                        if self.heap.gc_due() && !std::mem::take(&mut self.due_skip) {
5347                            gc_step_at!(true);
5348                        }
5349                        // Upvalues from registers count from the frame's base.
5350                        let f = t!(call!(self.make_closure(pidx, closure, frame_base, p as usize)));
5351                        setr!(a, f);
5352                    }
5353                    Instr::VarArg { a, n } => {
5354                        let (vstart, vcount) = self.cur.frames.last().map_or((0, 0), |f| (f.vstart, f.vcount));
5355                        let ra = base + usize::from(a);
5356                        if n == MULTI {
5357                            t!(call!(self.charge(vcount as u64 / 8)));
5358                            t!(call!(self.ensure_stack(ra + vcount + EXTRA_STACK)));
5359                            self.cur.stack.copy_within(vstart..vstart + vcount, ra);
5360                            self.top = ra + vcount;
5361                        } else {
5362                            // SEC-M7: a fixed count up to 65,535, paid past 16 as the open one.
5363                            t!(call!(self.charge(list_fuel(usize::from(n)))));
5364                            for i in 0..usize::from(n) {
5365                                let v = if i < vcount { self.st(vstart + i) } else { Value::Nil };
5366                                self.set_st(ra + i, v);
5367                            }
5368                        }
5369                    }
5370                    Instr::Close { a } => {
5371                        if !t!(call!(self.close_async(base + usize::from(a), AfterClose::Nothing, 0))) {
5372                            reload!();
5373                        }
5374                    }
5375                    Instr::Tbc { a } => {
5376                        let v = reg!(usize::from(a));
5377                        if v.truthy() {
5378                            if self.tm(v, Tm::Close).is_nil() {
5379                                save!();
5380                                let name = self
5381                                    .proto(pidx)
5382                                    .and_then(|p| crate::debug::local_name(p, pc - 1, a))
5383                                    .unwrap_or_else(|| "?".into());
5384                                return Err(LuaError::msg(format!("variable '{name}' got a non-closable value")));
5385                            }
5386                            self.cur.tbc.push(base + usize::from(a));
5387                        }
5388                    }
5389                }
5390            }
5391        }
5392    }
5393
5394    /// `t[key]` for a constant string key through the instruction's slot hint, when the
5395    /// table has it (or has no metatable to ask): None means "take the general path".
5396    #[inline]
5397    fn get_field_cached(&mut self, t: TableRef, key: Value, pidx: u32, pc: usize) -> Option<Value> {
5398        let tab = self.heap.tables.get(t.idx)?;
5399        let hint = self.heap.protos.at(pidx as usize).and_then(|p| p.hints.get(pc)).map_or(0, std::cell::Cell::get);
5400        let (v, slot) = tab.get_hinted(key, hint);
5401        if let Some(slot) = slot
5402            && slot != hint
5403            && let Some(h) = self.heap.protos.at(pidx as usize).and_then(|p| p.hints.get(pc))
5404        {
5405            h.set(slot);
5406        }
5407        if !v.is_nil() || tab.meta.is_none() { Some(v) } else { None }
5408    }
5409
5410
5411
5412    /// `t[key] = val` in place when the key exists and nothing intercepts (no metatable, or
5413    /// the field is there already): true when done.
5414    #[inline]
5415    fn set_field_fast(&mut self, t: TableRef, key: Value, val: Value) -> Result<bool, LuaError> {
5416        let Some(tab) = self.heap.tables.get(t.idx) else { return Ok(true) };
5417        if tab.meta.is_some() && self.get_in_settled(t.idx, key)?.is_nil() {
5418            return Ok(false);
5419        }
5420        self.raw_set(t, key, val)?;
5421        Ok(true)
5422    }
5423
5424    fn tail_call(&mut self, func: usize, nargs: usize) -> Result<(), LuaError> {
5425        let Some(frame) = self.cur.frames.last() else { return Ok(()) };
5426        let (fbase, ffunc, nres, kind, from_lua, handler) =
5427            (frame.base, frame.func, frame.nresults, frame.kind, frame.from_lua, frame.handler);
5428        self.close_upvals(fbase);
5429        if self.cur.tbc.last().is_some_and(|&s| s >= fbase) {
5430            self.close_level(fbase)?;
5431        }
5432        if nargs > 16 {
5433            self.charge(nargs as u64 / 8)?;
5434        }
5435        self.cur.stack.copy_within(func..func + 1 + nargs, ffunc);
5436        self.cur.frames.pop();
5437        // The new frame takes the old one's place, unrolled or not (`ThreadState::unrolled`).
5438        let unrolled = self.cur.unrolled;
5439        let depth = self.cur.frames.len();
5440        let r = self.precall(ffunc, nargs, nres, kind, from_lua);
5441        if matches!(r, Ok(Called::Lua))
5442            && self.cur.frames.len() == depth + 1
5443            && let Some(f) = self.cur.frames.get_mut(depth)
5444        {
5445            f.tail = true;
5446        }
5447        if self.cur.frames.len() <= unrolled {
5448            self.cur.unrolled = unrolled;
5449        }
5450        if let Some(f) = self.cur.frames.last_mut()
5451            && handler.is_some()
5452            && let (FrameKind::Protected { dest, .. }, FrameKind::Protected { dest: was, .. }) = (f.kind, kind)
5453            && dest == was
5454        {
5455            f.handler = handler;
5456        }
5457        r.map(|_| ())
5458    }
5459
5460    fn make_closure(&mut self, parent: u32, closure: FuncRef, base: usize, p: usize) -> Result<Value, LuaError> {
5461        loop {
5462            match new_closure(&mut self.heap, &mut self.cur.open_upvals, self.cur_ref, parent, closure, base, p) {
5463                Ok((v, extra)) => {
5464                    // Its upvalues (S5B-WALK-5; `charge` does not collect).
5465                    if extra > 0 {
5466                        self.charge(extra)?;
5467                    }
5468                    return Ok(v);
5469                }
5470                Err(None) => return Err(LuaError::msg("internal: no such prototype")),
5471                // Not enough memory: collect (or stop at the limit), then make it.
5472                Err(Some(size)) => {
5473                    self.charge_mem(size)?;
5474                    self.heap.mem.release(size);
5475                }
5476            }
5477        }
5478    }
5479
5480    /// Numeric `for` preparation: false to run the loop, true to skip it.
5481    fn for_prep(&mut self, ra: usize) -> Result<bool, LuaError> {
5482        let (init, limit, step) = (self.st(ra), self.st(ra + 1), self.st(ra + 2));
5483        if let (Value::Int(i), Value::Int(s)) = (init, step) {
5484            if s == 0 {
5485                return Err(LuaError::msg("'for' step is zero"));
5486            }
5487            let lim = match limit {
5488                Value::Int(l) => l,
5489                // Exactly, through the integer first (a numeric string included).
5490                other => match self.tonumber_charged(other)? {
5491                    Some(Value::Int(l)) => l,
5492                    Some(Value::Num(f)) => {
5493                        match if s < 0 { number::float_ceil_to_int(f) } else { number::float_floor_to_int(f) } {
5494                            Some(l) => l,
5495                            None => {
5496                                if (f > 0.0) == (s < 0) {
5497                                    return Ok(true);
5498                                }
5499                                if f > 0.0 { i64::MAX } else { i64::MIN }
5500                            }
5501                        }
5502                    }
5503                    _ => {
5504                        return Err(LuaError::msg(format!(
5505                            "bad 'for' limit (number expected, got {})",
5506                            self.obj_type_name(other)
5507                        )));
5508                    }
5509                },
5510            };
5511            if if s > 0 { i > lim } else { i < lim } {
5512                return Ok(true);
5513            }
5514            let count = if s > 0 {
5515                (lim as u64).wrapping_sub(i as u64) / (s as u64)
5516            } else {
5517                let s1 = (s.wrapping_add(1)).wrapping_neg() as u64 + 1;
5518                (i as u64).wrapping_sub(lim as u64) / s1
5519            };
5520            self.set_st(ra + 1, Value::Int(count as i64));
5521            self.set_st(ra + 3, Value::Int(i));
5522            return Ok(false);
5523        }
5524        let f = |v: Value, what: &str, s: &mut Self| -> Result<f64, LuaError> {
5525            match s.tonumber_charged(v)?.and_then(Value::as_num) {
5526                Some(f) => Ok(f),
5527                None => Err(LuaError::msg(format!("bad 'for' {what} (number expected, got {})", s.obj_type_name(v)))),
5528            }
5529        };
5530        let l = f(limit, "limit", self)?;
5531        let st = f(step, "step", self)?;
5532        let i = f(init, "initial value", self)?;
5533        if st == 0.0 {
5534            return Err(LuaError::msg("'for' step is zero"));
5535        }
5536        if if st > 0.0 { l < i } else { i < l } {
5537            return Ok(true);
5538        }
5539        self.set_st(ra, Value::Num(i));
5540        self.set_st(ra + 1, Value::Num(l));
5541        self.set_st(ra + 2, Value::Num(st));
5542        self.set_st(ra + 3, Value::Num(i));
5543        Ok(false)
5544    }
5545
5546    // ---- metamethod paths ----
5547
5548    /// Puts `f` and `args` at slot `pos`, to be called there.
5549    #[inline]
5550    fn place_call(&mut self, pos: usize, f: Value, args: &[Value]) -> Result<(), LuaError> {
5551        self.ensure_stack(pos + args.len() + 1 + EXTRA_STACK)?;
5552        self.set_st(pos, f);
5553        for (i, a) in args.iter().enumerate() {
5554            self.set_st(pos + 1 + i, *a);
5555        }
5556        Ok(())
5557    }
5558
5559    /// `precall` of a metamethod for event `ev` (named in the callee's messages).
5560    #[inline]
5561    fn precall_event(
5562        &mut self,
5563        ev: Option<&'static str>,
5564        pos: usize,
5565        nargs: usize,
5566        nres: i32,
5567        kind: FrameKind,
5568    ) -> Result<Called, LuaError> {
5569        self.pending_event = ev;
5570        let r = self.precall(pos, nargs, nres, kind, false);
5571        self.pending_event = None;
5572        r
5573    }
5574
5575    /// Calls metamethod `f` with `args` for an instruction: Some(result) when done now
5576    /// (a Rust function), None when a Lua frame was pushed (its result goes by `cont`).
5577    /// `ev` names the metamethod when `f` cannot be called (C's `funcnamefromcode`).
5578    fn call_meta(&mut self, ev: Tm, f: Value, args: &[Value], cont: Cont) -> Result<Option<Value>, LuaError> {
5579        if !matches!(f, Value::Func(_)) && self.tm(f, Tm::Call).is_nil() {
5580            let name = TM_NAMES.get(ev as usize).map_or("?", |n| n.get(2..).unwrap_or(n));
5581            return Err(LuaError::msg(format!("attempt to call a {} value (metamethod '{name}')", self.obj_type_name(f))));
5582        }
5583        let pos = self.call_top();
5584        self.place_call(pos, f, args)?;
5585        let saved_ntop = self.ntop;
5586        self.ntop = self.ntop.max(pos + 1 + args.len());
5587        let r = self.precall_event(TM_NAMES.get(ev as usize).and_then(|n| n.get(2..)), pos, args.len(), 1, FrameKind::Cont(cont));
5588        self.ntop = saved_ntop;
5589        match r? {
5590            // A Lua frame (or `pcall` of one) delivers its result through `cont`; so does a
5591            // resumed or yielding coroutine (`wrap`, `coroutine.yield` as a metamethod).
5592            Called::Lua | Called::Switched => Ok(None),
5593            Called::Done => Ok(Some(self.st(pos))),
5594        }
5595    }
5596
5597    /// Indexing `t`, which is not a table and has no metamethod, at link `loop_n` of a chain.
5598    fn index_error(&self, t: Value, loop_n: usize) -> LuaError {
5599        let ty = self.obj_type_name(t);
5600        if loop_n == 0 {
5601            ErrorKind::Type { op: "index", ty, operand: 0 }.into()
5602        } else {
5603            LuaError::msg(format!("attempt to index a {ty} value"))
5604        }
5605    }
5606
5607    /// `t[k]` with metamethods.
5608    pub(crate) fn index(&mut self, t: Value, key: Value, cont: Cont) -> Result<Option<Value>, LuaError> {
5609        let mut t = t;
5610        for loop_n in 0..MAX_TAG_LOOP {
5611            let mm = if let Value::Table(tr) = t {
5612                if self.heap.tables.get(tr.idx).is_none() {
5613                    return Ok(Some(Value::Nil));
5614                }
5615                let v = self.get_in_settled(tr.idx, key)?;
5616                let Some(tab) = self.heap.tables.get(tr.idx) else { return Ok(Some(Value::Nil)) };
5617                if !v.is_nil() {
5618                    return Ok(Some(v));
5619                }
5620                let Some(m) = tab.meta else { return Ok(Some(Value::Nil)) };
5621                let mm = self.tm_in(m, Tm::Index);
5622                if mm.is_nil() {
5623                    return Ok(Some(Value::Nil));
5624                }
5625                mm
5626            } else {
5627                let mm = self.tm(t, Tm::Index);
5628                if mm.is_nil() {
5629                    return Err(self.index_error(t, loop_n));
5630                }
5631                mm
5632            };
5633            if let Value::Func(_) = mm {
5634                return self.call_meta(Tm::Index, mm, &[t, key], cont);
5635            }
5636            // Each link of a chain is a step, and so is its lookup's probing (S5GC-1).
5637            self.charge(link_cost(loop_n) + crate::table::take_probes())?;
5638            t = mm;
5639        }
5640        Err(LuaError::msg("'__index' chain too long; possible loop"))
5641    }
5642
5643    /// `t[k] = v` with metamethods: true when done now, false when a Lua `__newindex`
5644    /// frame was pushed.
5645    pub(crate) fn set_index(&mut self, t: Value, key: Value, val: Value) -> Result<bool, LuaError> {
5646        let mut t = t;
5647        for loop_n in 0..MAX_TAG_LOOP {
5648            let mm = if let Value::Table(tr) = t {
5649                let Some(tab) = self.heap.tables.get(tr.idx) else { return Ok(true) };
5650                let mm = match tab.meta {
5651                    None => Value::Nil,
5652                    Some(m) => {
5653                        if !self.get_in_settled(tr.idx, key)?.is_nil() {
5654                            Value::Nil
5655                        } else {
5656                            self.tm_in(m, Tm::NewIndex)
5657                        }
5658                    }
5659                };
5660                if mm.is_nil() {
5661                    self.raw_set(tr, key, val)?;
5662                    return Ok(true);
5663                }
5664                mm
5665            } else {
5666                let mm = self.tm(t, Tm::NewIndex);
5667                if mm.is_nil() {
5668                    return Err(self.index_error(t, loop_n));
5669                }
5670                mm
5671            };
5672            if let Value::Func(_) = mm {
5673                return Ok(self.call_meta(Tm::NewIndex, mm, &[t, key, val], Cont::Discard)?.is_some());
5674            }
5675            // Each link of a chain is a step, and so is its lookup's probing (S5GC-1).
5676            self.charge(link_cost(loop_n) + crate::table::take_probes())?;
5677            t = mm;
5678        }
5679        Err(LuaError::msg("'__newindex' chain too long; possible loop"))
5680    }
5681
5682    /// `t[k]` from Rust (nested calls for metamethods).
5683    pub(crate) fn index_nested(&mut self, t: Value, key: Value) -> Result<Value, LuaError> {
5684        self.settle_key(key)?;
5685        let mut t = t;
5686        for link_n in 0..MAX_TAG_LOOP {
5687            let mm = if let Value::Table(tr) = t {
5688                let v = self.raw_get(tr, key);
5689                if !v.is_nil() {
5690                    // The native reading it may hold it across allocations.
5691                    self.hold(v);
5692                    return Ok(v);
5693                }
5694                let mm = self.tm(t, Tm::Index);
5695                if mm.is_nil() {
5696                    return Ok(Value::Nil);
5697                }
5698                mm
5699            } else {
5700                let mm = self.tm(t, Tm::Index);
5701                if mm.is_nil() {
5702                    return Err(LuaError::Plain(format!("attempt to index a {} value", self.obj_type_name(t))));
5703                }
5704                mm
5705            };
5706            if let Value::Func(_) = mm {
5707                return self.call_nested1(mm, &[t, key]);
5708            }
5709            // Each link of a chain is a step, and so is its lookup's probing (S5GC-1).
5710            self.charge(link_cost(link_n) + crate::table::take_probes())?;
5711            t = mm;
5712        }
5713        Err(LuaError::Plain("'__index' chain too long; possible loop".into()))
5714    }
5715
5716    /// `t[k] = v` from Rust.
5717    pub(crate) fn set_index_nested(&mut self, t: Value, key: Value, val: Value) -> Result<(), LuaError> {
5718        self.settle_key(key)?;
5719        let mut t = t;
5720        for link_n in 0..MAX_TAG_LOOP {
5721            let mm = match t {
5722                Value::Table(tr) => {
5723                    let has = !self.raw_get(tr, key).is_nil();
5724                    let mm = match self.metatable(t) {
5725                        Some(m) if !has => self.tm_in(m, Tm::NewIndex),
5726                        _ => Value::Nil,
5727                    };
5728                    if mm.is_nil() {
5729                        return self.raw_set(tr, key, val);
5730                    }
5731                    mm
5732                }
5733                _ => {
5734                    let mm = self.tm(t, Tm::NewIndex);
5735                    if mm.is_nil() {
5736                        return Err(LuaError::Plain(format!("attempt to index a {} value", self.obj_type_name(t))));
5737                    }
5738                    mm
5739                }
5740            };
5741            if let Value::Func(_) = mm {
5742                self.call_nested(mm, &[t, key, val])?;
5743                return Ok(());
5744            }
5745            // Each link of a chain is a step, and so is its lookup's probing (S5GC-1).
5746            self.charge(link_cost(link_n) + crate::table::take_probes())?;
5747            t = mm;
5748        }
5749        Err(LuaError::Plain("'__newindex' chain too long; possible loop".into()))
5750    }
5751
5752    /// A number from a value, converting strings (Lua's arithmetic coercion).
5753    pub(crate) fn tonumber(&self, v: Value) -> Option<Value> {
5754        match v {
5755            Value::Int(_) | Value::Num(_) => Some(v),
5756            Value::Str(s) => number::str_to_number(self.bytes(s)),
5757            _ => None,
5758        }
5759    }
5760
5761    /// `tonumber`, charging fuel for the length of a string it parses: a unit per 16 bytes,
5762    /// what the slowest numerals cost (a long fraction or digit run takes the float
5763    /// parser's big-number path; at a unit per 64 bytes they ran 4 to 5x plain code: LR-22).
5764    pub(crate) fn tonumber_charged(&mut self, v: Value) -> Result<Option<Value>, LuaError> {
5765        if let Value::Str(s) = v {
5766            let n = self.bytes(s).len();
5767            if n >= 16 {
5768                self.charge(n as u64 / 16)?;
5769            }
5770        }
5771        Ok(self.tonumber(v))
5772    }
5773
5774    /// Fuel for comparing or copying `n` bytes.
5775    #[inline]
5776    pub(crate) fn charge_bytes(&mut self, n: usize) -> Result<(), LuaError> {
5777        self.charge(crate::heap::bytes_fuel(n))
5778    }
5779
5780    /// An integer from a value (exact floats and numeric strings convert).
5781    pub(crate) fn tointeger(&self, v: Value) -> Option<i64> {
5782        match v {
5783            Value::Int(i) => Some(i),
5784            Value::Num(f) => number::float_to_int(f),
5785            Value::Str(_) => self.tonumber(v).and_then(Value::as_int),
5786            _ => None,
5787        }
5788    }
5789
5790    /// Arithmetic with coercion and metamethods.
5791    pub(crate) fn arith(&mut self, op: ArithOp, x: Value, y: Value, cont: Cont) -> Result<Option<Value>, LuaError> {
5792        // A string operand: whatever the string metatable says (its own `__add` … is done
5793        // here directly; a script's replacement is called).
5794        if !is_bitwise(op) && self.string_meta.is_some() && (matches!(x, Value::Str(_)) || matches!(y, Value::Str(_))) {
5795            let ev = arith_tm(op);
5796            let mm = self.tm2(x, y, ev);
5797            if mm.is_nil() {
5798                let culprit = if matches!(x, Value::Int(_) | Value::Num(_)) { 1 } else { 0 };
5799                let ty = self.obj_type_name(if culprit == 0 { x } else { y });
5800                return Err(ErrorKind::Type { op: "perform arithmetic on", ty, operand: culprit }.into());
5801            }
5802            if !self.is_string_builtin(mm) {
5803                return self.call_meta(ev, mm, &[x, y], cont);
5804            }
5805            return self.string_arith_now(op, x, y).map(Some);
5806        }
5807        if is_bitwise(op) {
5808            let ints = (int_of(x), int_of(y));
5809            if let (Some(i), Some(j)) = ints {
5810                return Ok(Some(Value::Int(int_arith(op, i, j)?)));
5811            }
5812        } else if let (Some(a), Some(b)) = (self.tonumber_charged(x)?, self.tonumber_charged(y)?) {
5813            let r = arith_values(op, a, b);
5814            // With a string operand the work happens in the string library's metamethod,
5815            // whose errors carry no position.
5816            if self.string_arith(x) || self.string_arith(y) {
5817                return r.map(Some).map_err(LuaError::plain);
5818            }
5819            return r.map(Some);
5820        }
5821        let mut mm = self.tm(x, arith_tm(op));
5822        if mm.is_nil() && !is_bitwise(op) && self.string_arith(x) {
5823            return self.string_arith_fail(op, x, y).map(Some);
5824        }
5825        if mm.is_nil() {
5826            mm = self.tm(y, arith_tm(op));
5827            if mm.is_nil() && !is_bitwise(op) && self.string_arith(y) {
5828                return self.string_arith_fail(op, x, y).map(Some);
5829            }
5830        }
5831        if !mm.is_nil() {
5832            return self.call_meta(arith_tm(op), mm, &[x, y], cont);
5833        }
5834        if is_bitwise(op) {
5835            if matches!(x, Value::Int(_) | Value::Num(_)) && matches!(y, Value::Int(_) | Value::Num(_)) {
5836                return Err(ErrorKind::IntRepr { operand: if int_of(x).is_none() { 0 } else { 1 } }.into());
5837            }
5838            let culprit = if matches!(x, Value::Int(_) | Value::Num(_)) { 1 } else { 0 };
5839            let ty = self.obj_type_name(if culprit == 0 { x } else { y });
5840            return Err(ErrorKind::Type { op: "perform bitwise operation on", ty, operand: culprit }.into());
5841        }
5842        let culprit = if self.tonumber(x).is_some() { 1 } else { 0 };
5843        let ty = self.obj_type_name(if culprit == 0 { x } else { y });
5844        Err(ErrorKind::Type { op: "perform arithmetic on", ty, operand: culprit }.into())
5845    }
5846
5847    /// Whether `v` is a string whose arithmetic goes through the string library's
5848    /// metamethods (as in Lua 5.4, when the string library is open).
5849    fn string_arith(&self, v: Value) -> bool {
5850        matches!(v, Value::Str(_)) && self.string_meta.is_some()
5851    }
5852
5853    /// Whether `f` is one of the string library's own arithmetic metamethods.
5854    fn is_string_builtin(&self, f: Value) -> bool {
5855        let Value::Func(r) = f else { return false };
5856        matches!(self.heap.funcs.get(r.idx), Some(Func::Native { name, .. }) if name.starts_with("string.__"))
5857    }
5858
5859    /// The string library's arithmetic, called directly (`getmetatable("").__add(a, b)`).
5860    pub(crate) fn string_arith_now(&mut self, op: ArithOp, x: Value, y: Value) -> Result<Value, LuaError> {
5861        if let (Some(a), Some(b)) = (self.tonumber_charged(x)?, self.tonumber_charged(y)?) {
5862            return arith_values(op, a, b).map_err(LuaError::plain);
5863        }
5864        self.string_arith_fail(op, x, y)
5865    }
5866
5867    /// The string library's arithmetic metamethod when coercion failed (`trymt`): the
5868    /// second operand's own metamethod, or "attempt to add a 'string' with a 'table'".
5869    /// C Lua calls that metamethod from the string library (`lua_call`): it is not
5870    /// yieldable, error levels count the library function, and a value that is not
5871    /// callable is reported without a position.
5872    fn string_arith_fail(&mut self, op: ArithOp, x: Value, y: Value) -> Result<Value, LuaError> {
5873        let ev = arith_tm(op);
5874        let mm = if matches!(y, Value::Str(_)) { Value::Nil } else { self.tm(y, ev) };
5875        if mm.is_nil() {
5876            let name = TM_NAMES.get(ev as usize).map_or("?", |n| n.get(2..).unwrap_or(n));
5877            return Err(LuaError::msg(format!("attempt to {name} a '{}' with a '{}'", x.type_name(), y.type_name())));
5878        }
5879        self.call_nested1(mm, &[x, y])
5880    }
5881
5882    fn unary(&mut self, e: Tm, x: Value, cont: Cont) -> Result<Option<Value>, LuaError> {
5883        match e {
5884            Tm::Unm => {
5885                if let Some(n) = self.tonumber_charged(x)? {
5886                    return Ok(Some(match n {
5887                        Value::Int(i) => Value::Int(i.wrapping_neg()),
5888                        Value::Num(f) => Value::Num(-f),
5889                        o => o,
5890                    }));
5891                }
5892            }
5893            _ => {
5894                if let Some(i) = int_of(x) {
5895                    return Ok(Some(Value::Int(!i)));
5896                }
5897            }
5898        }
5899        let mm = self.tm(x, e);
5900        if e == Tm::Unm && self.string_arith(x) && self.is_string_builtin(mm) {
5901            return Err(LuaError::msg("attempt to unm a 'string' with a 'string'"));
5902        }
5903        if !mm.is_nil() {
5904            return self.call_meta(e, mm, &[x, x], cont);
5905        }
5906        if e == Tm::BNot {
5907            if let Value::Num(_) = x {
5908                return Err(ErrorKind::IntRepr { operand: 0 }.into());
5909            }
5910            return Err(ErrorKind::Type { op: "perform bitwise operation on", ty: self.obj_type_name(x), operand: 0 }.into());
5911        }
5912        Err(ErrorKind::Type { op: "perform arithmetic on", ty: self.obj_type_name(x), operand: 0 }.into())
5913    }
5914
5915    /// `#x` with `__len`.
5916    pub(crate) fn len(&mut self, x: Value, cont: Cont) -> Result<Option<Value>, LuaError> {
5917        if let Value::Str(s) = x {
5918            return Ok(Some(Value::Int(self.bytes(s).len() as i64)));
5919        }
5920        let mm = self.tm(x, Tm::Len);
5921        if !mm.is_nil() {
5922            return self.call_meta(Tm::Len, mm, &[x, x], cont);
5923        }
5924        if let Value::Table(t) = x {
5925            return Ok(Some(Value::Int(self.raw_len(t))));
5926        }
5927        Err(ErrorKind::Type { op: "get length of", ty: self.obj_type_name(x), operand: 0 }.into())
5928    }
5929
5930    /// `#x` from Rust.
5931    pub(crate) fn len_nested(&mut self, x: Value) -> Result<Value, LuaError> {
5932        if let Value::Str(s) = x {
5933            return Ok(Value::Int(self.bytes(s).len() as i64));
5934        }
5935        let mm = self.tm(x, Tm::Len);
5936        if !mm.is_nil() {
5937            return self.call_nested1(mm, &[x, x]);
5938        }
5939        if let Value::Table(t) = x {
5940            return Ok(Value::Int(self.raw_len(t)));
5941        }
5942        Err(LuaError::Plain(format!("attempt to get length of a {} value", self.obj_type_name(x))))
5943    }
5944
5945    fn eq_slow(&mut self, x: Value, y: Value, cont: Cont) -> Result<Option<bool>, LuaError> {
5946        let mm = self.tm2(x, y, Tm::Eq);
5947        if mm.is_nil() {
5948            return Ok(Some(false));
5949        }
5950        Ok(self.call_meta(Tm::Eq, mm, &[x, y], cont)?.map(Value::truthy))
5951    }
5952
5953    /// Whether two strings are equal (comparing long strings' bytes is charged).
5954    pub(crate) fn str_eq(&mut self, a: StrRef, b: StrRef) -> Result<bool, LuaError> {
5955        if let Some(r) = self.heap.str_eq_quick(a, b) {
5956            return Ok(r);
5957        }
5958        let len = self.bytes(a).len();
5959        self.charge_bytes(len)?;
5960        // A long pair a piece at a time, each a look at the deadline (S6T-EQ: two 16 MiB
5961        // strings were compared in one go, 1.5 ms).
5962        let mut at = 0usize;
5963        loop {
5964            let end = at.saturating_add(crate::stdlib::COPY_PIECE).min(len);
5965            if self.heap.diff_piece(a.idx, b.idx, at, end).is_some() {
5966                return Ok(false);
5967            }
5968            if end >= len {
5969                return Ok(self.bytes(a).len() == self.bytes(b).len());
5970            }
5971            at = end;
5972            self.check_time()?;
5973        }
5974    }
5975
5976    /// `x == y` from Rust.
5977    pub(crate) fn eq_nested(&mut self, x: Value, y: Value) -> Result<bool, LuaError> {
5978        if x.raw_eq(y) {
5979            return Ok(true);
5980        }
5981        match (x, y) {
5982            (Value::Str(a), Value::Str(b)) => self.str_eq(a, b),
5983            (Value::Table(_), Value::Table(_)) | (Value::UserData(_), Value::UserData(_)) => {
5984                let mm = self.tm2(x, y, Tm::Eq);
5985                if mm.is_nil() {
5986                    return Ok(false);
5987                }
5988                Ok(self.call_nested1(mm, &[x, y])?.truthy())
5989            }
5990            _ => Ok(false),
5991        }
5992    }
5993
5994    fn order_slow(&mut self, e: Tm, x: Value, y: Value, cont: Cont) -> Result<Option<bool>, LuaError> {
5995        let mm = self.tm2(x, y, e);
5996        if mm.is_nil() && e == Tm::Le && !self.limits.strict_5_4 {
5997            // `LUA_COMPAT_LT_LE` (stock 5.4 builds): `a <= b` as `not (b < a)`.
5998            let lt = self.tm2(y, x, Tm::Lt);
5999            if !lt.is_nil() {
6000                let cont = match cont {
6001                    Cont::Cond { k } => Cont::Cond { k: !k },
6002                    c => c,
6003                };
6004                return Ok(self.call_meta(Tm::Le, lt, &[y, x], cont)?.map(|v| !v.truthy()));
6005            }
6006        }
6007        if mm.is_nil() {
6008            return Err(self.compare_error(x, y));
6009        }
6010        Ok(self.call_meta(e, mm, &[x, y], cont)?.map(Value::truthy))
6011    }
6012
6013    pub(crate) fn compare_error(&self, x: Value, y: Value) -> LuaError {
6014        let (t1, t2) = (self.obj_type_name(x), self.obj_type_name(y));
6015        if t1 == t2 {
6016            LuaError::msg(format!("attempt to compare two {t1} values"))
6017        } else {
6018            LuaError::msg(format!("attempt to compare {t1} with {t2}"))
6019        }
6020    }
6021
6022    /// `x < y` from Rust.
6023    pub(crate) fn less_than(&mut self, x: Value, y: Value) -> Result<bool, LuaError> {
6024        Ok(match (x, y) {
6025            (Value::Int(i), Value::Int(j)) => i < j,
6026            (Value::Num(f), Value::Num(g)) => f < g,
6027            (Value::Int(i), Value::Num(g)) => number::int_lt_float(i, g),
6028            (Value::Num(f), Value::Int(j)) => number::float_lt_int(f, j),
6029            (Value::Str(a), Value::Str(b)) => {
6030                let n = self.bytes(a).len().min(self.bytes(b).len());
6031                self.charge_bytes(n)?;
6032                self.bytes(a) < self.bytes(b)
6033            }
6034            _ => {
6035                let mut mm = self.tm(x, Tm::Lt);
6036                if mm.is_nil() {
6037                    mm = self.tm(y, Tm::Lt);
6038                }
6039                if mm.is_nil() {
6040                    return Err(self.compare_error(x, y).plain());
6041                }
6042                self.call_nested1(mm, &[x, y])?.truthy()
6043            }
6044        })
6045    }
6046
6047    /// Concatenates `n` values from slot `a` into slot `a`: true when done, false when a
6048    /// Lua `__concat` frame was pushed.
6049    pub(crate) fn concat(&mut self, a: usize, n: usize) -> Result<bool, LuaError> {
6050        let mut n = n;
6051        while n > 1 {
6052            let x = self.st(a + n - 2);
6053            let y = self.st(a + n - 1);
6054            if stringable(x) && stringable(y) {
6055                // The longest run of strings and numbers ending at the top, joined at once.
6056                let mut k = n - 1;
6057                while k > 0 && stringable(self.st(a + k - 1)) {
6058                    k -= 1;
6059                }
6060                let mut total = 0usize;
6061                for i in k..n {
6062                    total = total.saturating_add(self.str_len_of(self.st(a + i)));
6063                }
6064                if total > self.limits.string_len {
6065                    return Err(LuaError::Limit(LimitKind::Memory));
6066                }
6067                let floats = (k..n).filter(|&i| matches!(self.st(a + i), Value::Num(_))).count() as u64;
6068                self.charge((total / 64) as u64 + floats * FLOAT_TEXT_FUEL)?;
6069                // One buffer of the exact size, one copy of each part: a short result is
6070                // built on the stack and interned; a long one is charged first, then its
6071                // buffer becomes the string.
6072                let s = if total <= crate::heap::SHORT_LEN {
6073                    let mut buf = [0u8; crate::heap::SHORT_LEN];
6074                    let mut w: &mut [u8] = &mut buf;
6075                    for i in k..n {
6076                        self.append_stringable(&mut w, self.st(a + i));
6077                    }
6078                    let len = crate::heap::SHORT_LEN - w.len();
6079                    self.new_str(buf.get(..len).unwrap_or_default())?
6080                } else {
6081                    self.charge_mem(crate::heap::str_mem(total))?;
6082                    let mut buf = Vec::with_capacity(total);
6083                    for i in k..n {
6084                        self.append_stringable(&mut buf, self.st(a + i));
6085                    }
6086                    let v = Value::Str(self.heap.new_long_charged(buf.into_boxed_slice()));
6087                    self.hold(v);
6088                    v
6089                };
6090                self.set_st(a + k, s);
6091                n = k + 1;
6092                continue;
6093            }
6094            let mm = self.tm2(x, y, Tm::Concat);
6095            if mm.is_nil() {
6096                let culprit = if stringable(x) { n - 1 } else { n - 2 };
6097                let v = if stringable(x) { y } else { x };
6098                return Err(ErrorKind::Type { op: "concatenate", ty: self.obj_type_name(v), operand: culprit as u8 }.into());
6099            }
6100            match self.call_meta(Tm::Concat, mm, &[x, y], Cont::Concat { a, n: n - 1 })? {
6101                Some(v) => {
6102                    self.set_st(a + n - 2, v);
6103                    n -= 1;
6104                }
6105                None => return Ok(false),
6106            }
6107        }
6108        Ok(true)
6109    }
6110
6111    /// The exact length of a string or number as `..` writes it.
6112    fn str_len_of(&self, v: Value) -> usize {
6113        stringable_len(&self.heap, v)
6114    }
6115
6116    /// Writes a string or number as `..` does (into a buffer sized by `str_len_of`).
6117    pub(crate) fn append_stringable(&self, out: &mut impl std::io::Write, v: Value) {
6118        write_stringable(&self.heap, out, v);
6119    }
6120
6121    /// `tostring(v)`.
6122    pub(crate) fn tostring(&mut self, v: Value) -> Result<Value, LuaError> {
6123        let mm = self.tm(v, Tm::ToString);
6124        if !mm.is_nil() {
6125            let r = self.call_nested1(mm, &[v])?;
6126            if !matches!(r, Value::Str(_)) {
6127                if let Value::Int(_) | Value::Num(_) = r {
6128                    let mut b = Vec::new();
6129                    self.append_stringable(&mut b, r);
6130                    return self.new_str(&b);
6131                }
6132                return Err(LuaError::msg("'__tostring' must return a string"));
6133            }
6134            return Ok(r);
6135        }
6136        let text = match v {
6137            Value::Str(_) => return Ok(v),
6138            Value::Nil => "nil".to_owned(),
6139            Value::Bool(b) => return self.new_str(if b { b"true" } else { b"false" }),
6140            Value::Int(_) => {
6141                let mut buf = [0u8; 20];
6142                let mut w: &mut [u8] = &mut buf;
6143                self.append_stringable(&mut w, v);
6144                let n = 20 - w.len();
6145                return self.new_str(buf.get(..n).unwrap_or_default());
6146            }
6147            Value::Num(f) => {
6148                self.charge(FLOAT_TEXT_FUEL)?;
6149                number::fmt_float(f)
6150            }
6151            _ => {
6152                // The name (maybe `__name`, read as `luaL_tolstring` reads it) and the
6153                // address, formatted.
6154                self.charge(4)?;
6155                let kind = self.arg_type_name(v);
6156                format!("{kind}: 0x{:08x}", address_of(v))
6157            }
6158        };
6159        self.new_str(text.as_bytes())
6160    }
6161}
6162
6163/// The exact length of a string or number as `..` writes it.
6164pub(crate) fn stringable_len(heap: &Heap, v: Value) -> usize {
6165    match v {
6166        Value::Str(s) => heap.str_bytes(s).len(),
6167        Value::Int(i) => i.unsigned_abs().checked_ilog10().map_or(1, |d| d as usize + 1) + usize::from(i < 0),
6168        Value::Num(f) => number::fmt_float(f).len(),
6169        _ => 0,
6170    }
6171}
6172
6173/// Writes a string or number as `..` does (into a buffer sized by `stringable_len`).
6174pub(crate) fn write_stringable(heap: &Heap, out: &mut impl std::io::Write, v: Value) {
6175    let _ = match v {
6176        Value::Str(s) => out.write_all(heap.str_bytes(s)),
6177        Value::Int(i) => write_int(out, i),
6178        Value::Num(f) => out.write_all(number::fmt_float(f).as_bytes()),
6179        _ => Ok(()),
6180    };
6181}
6182
6183/// An integer's decimal text into `out`.
6184#[inline]
6185pub(crate) fn write_int(out: &mut impl std::io::Write, i: i64) -> std::io::Result<()> {
6186    let mut digits = [0u8; 20];
6187    let mut at = digits.len();
6188    let mut n = i.unsigned_abs();
6189    loop {
6190        at -= 1;
6191        if let Some(d) = digits.get_mut(at) {
6192            *d = b'0' + (n % 10) as u8;
6193        }
6194        n /= 10;
6195        if n == 0 {
6196            break;
6197        }
6198    }
6199    if i < 0 {
6200        let _ = out.write_all(b"-");
6201    }
6202    out.write_all(digits.get(at..).unwrap_or_default())
6203}
6204
6205/// A stable pseudo-address for `tostring` of objects.
6206pub(crate) fn address_of(v: Value) -> u64 {
6207    let (kind, idx) = match v {
6208        Value::Table(r) => (1u64, r.idx),
6209        Value::Func(r) => (2, r.idx),
6210        Value::UserData(r) => (3, r.idx),
6211        Value::Thread(r) => (4, r.idx),
6212        Value::Str(r) => (5, r.idx),
6213        _ => (0, 0),
6214    };
6215    0x5500_0000_0000 | (kind << 36) | (u64::from(idx) << 4)
6216}
6217
6218fn stringable(v: Value) -> bool {
6219    matches!(v, Value::Str(_) | Value::Int(_) | Value::Num(_))
6220}
6221
6222/// An integer from a number for bitwise operations (strings do not convert, as in 5.4).
6223fn int_of(v: Value) -> Option<i64> {
6224    match v {
6225        Value::Int(i) => Some(i),
6226        Value::Num(f) => number::float_to_int(f),
6227        _ => None,
6228    }
6229}
6230
6231#[inline]
6232fn float_arith(op: ArithOp, f: f64, g: f64) -> Option<Value> {
6233    Some(Value::Num(match op {
6234        ArithOp::Add => f + g,
6235        ArithOp::Sub => f - g,
6236        ArithOp::Mul => f * g,
6237        ArithOp::Div => f / g,
6238        ArithOp::Pow => {
6239            if g == 2.0 { f * f } else { f.powf(g) }
6240        }
6241        ArithOp::IDiv => (f / g).floor(),
6242        ArithOp::Mod => number::float_mod(f, g),
6243        _ => return None,
6244    }))
6245}
6246
6247fn int_arith(op: ArithOp, i: i64, j: i64) -> Result<i64, LuaError> {
6248    Ok(match op {
6249        ArithOp::Add => i.wrapping_add(j),
6250        ArithOp::Sub => i.wrapping_sub(j),
6251        ArithOp::Mul => i.wrapping_mul(j),
6252        ArithOp::IDiv => {
6253            if j == 0 {
6254                return Err(LuaError::msg("attempt to divide by zero"));
6255            }
6256            number::int_floor_div(i, j)
6257        }
6258        ArithOp::Mod => {
6259            if j == 0 {
6260                return Err(LuaError::msg("attempt to perform 'n%0'"));
6261            }
6262            number::int_mod(i, j)
6263        }
6264        ArithOp::BAnd => i & j,
6265        ArithOp::BOr => i | j,
6266        ArithOp::BXor => i ^ j,
6267        ArithOp::Shl => number::shift_left(i, j),
6268        ArithOp::Shr => number::shift_left(i, j.wrapping_neg()),
6269        _ => 0,
6270    })
6271}
6272
6273/// Arithmetic on two numbers.
6274pub(crate) fn arith_values(op: ArithOp, a: Value, b: Value) -> Result<Value, LuaError> {
6275    match (a, b) {
6276        (Value::Int(i), Value::Int(j)) if !matches!(op, ArithOp::Div | ArithOp::Pow) => Ok(Value::Int(int_arith(op, i, j)?)),
6277        _ => {
6278            let (f, g) = (a.as_num().unwrap_or(0.0), b.as_num().unwrap_or(0.0));
6279            if is_bitwise(op) {
6280                let (Some(i), Some(j)) = (number::float_to_int(f), number::float_to_int(g)) else {
6281                    return Err(LuaError::msg("number has no integer representation"));
6282                };
6283                return Ok(Value::Int(int_arith(op, i, j)?));
6284            }
6285            Ok(float_arith(op, f, g).unwrap_or(Value::Nil))
6286        }
6287    }
6288}
6289
6290/// How a chunk name prints in messages: `=name` as is, `@file` as the file, source text as
6291/// `[string "first line..."]`.
6292pub(crate) fn chunk_id(source: &str) -> String {
6293    // C Lua's chunk name is a C string: it ends at the first zero byte (`load("\0")` is
6294    // `[string ""]`), S5C-COR-2.
6295    let source = source.split('\0').next().unwrap_or("");
6296    if let Some(rest) = source.strip_prefix('=') {
6297        return truncate_utf8(rest, 59).to_owned();
6298    }
6299    if let Some(rest) = source.strip_prefix('@') {
6300        if rest.len() <= 59 {
6301            return rest.to_owned();
6302        }
6303        let tail_start = rest.len() - 56;
6304        let mut s = tail_start;
6305        while !rest.is_char_boundary(s) {
6306            s += 1;
6307        }
6308        return format!("...{}", rest.get(s..).unwrap_or_default());
6309    }
6310    let first = source.split('\n').next().unwrap_or("");
6311    let multi = source.contains('\n');
6312    const MAX: usize = 60 - 15;
6313    // C's `luaO_chunkid` keeps the text whole only below the limit; at it, "..." is added.
6314    if !multi && first.len() < MAX {
6315        return format!("[string \"{first}\"]");
6316    }
6317    let cut = truncate_utf8(first, MAX);
6318    format!("[string \"{cut}...\"]")
6319}
6320
6321/// `s` cut to at most `max` bytes on a character boundary.
6322/// `b` cut to at most `max` bytes: at a character boundary when it is UTF-8 (as
6323/// [`truncate_utf8`]), else at `max`.
6324pub(crate) fn cut_message(b: &[u8], max: usize) -> &[u8] {
6325    match std::str::from_utf8(b) {
6326        Ok(s) => truncate_utf8(s, max).as_bytes(),
6327        Err(_) => b.get(..max.min(b.len())).unwrap_or_default(),
6328    }
6329}
6330
6331pub(crate) fn truncate_utf8(s: &str, max: usize) -> &str {
6332    if s.len() <= max {
6333        return s;
6334    }
6335    let mut cut = max;
6336    while !s.is_char_boundary(cut) {
6337        cut -= 1;
6338    }
6339    s.get(..cut).unwrap_or_default()
6340}
6341
6342/// Makes closure `p` of prototype `parent` (running as `closure` with registers from
6343/// `base` of the thread `cur`, whose open upvalues are `open`): the one place both
6344/// interpreter paths make closures. Its memory (the function and any upvalues it opens)
6345/// is charged first; Err(Some(bytes)) when that does not fit (nothing is changed),
6346/// Err(None) for a missing prototype.
6347/// Fuel for writing a list of `n` values in one step (registers, results, arguments): free
6348/// up to 16, then a unit per 8, as the call protocol charges argument and result lists.
6349#[inline]
6350pub(crate) fn list_fuel(n: usize) -> u64 {
6351    if n > 16 { n as u64 / 8 } else { 0 }
6352}
6353
6354/// Open upvalues moved (16 bytes each) per unit of fuel when a new one is put below them.
6355const OPEN_SHIFT_PER_FUEL: usize = 32;
6356
6357pub(crate) fn new_closure(
6358    heap: &mut Heap,
6359    open: &mut Vec<(usize, u32)>,
6360    cur: ThreadRef,
6361    parent: u32,
6362    closure: FuncRef,
6363    base: usize,
6364    p: usize,
6365) -> Result<(Value, u64), Option<usize>> {
6366    let child = heap.protos.get(parent).and_then(|pp| pp.protos.get(p)).copied().ok_or(None)?;
6367    // The upvalue descriptions, copied out (making upvalues below needs the heap mutably):
6368    // into a buffer on the stack for the common few, without an allocation.
6369    let mut small = [(false, 0u32); 16];
6370    let big: Vec<(bool, u32)>;
6371    let descs: &[(bool, u32)] = match heap.protos.get(child) {
6372        Some(c) if c.upvals.len() <= small.len() => {
6373            for (s, d) in small.iter_mut().zip(&c.upvals) {
6374                *s = (d.in_stack, d.idx);
6375            }
6376            small.get(..c.upvals.len()).unwrap_or_default()
6377        }
6378        Some(c) => {
6379            big = c.upvals.iter().map(|d| (d.in_stack, d.idx)).collect();
6380            &big
6381        }
6382        None => &[],
6383    };
6384    let fresh = descs
6385        .iter()
6386        .filter(|(in_stack, idx)| *in_stack && open.binary_search_by(|(i, _)| i.cmp(&(base + *idx as usize))).is_err())
6387        .count();
6388    let size = crate::heap::FUNC_BASE + crate::heap::boxed(descs.len() * 8) + fresh * UPVAL_SIZE;
6389    // S5B-WALK-5: a closure's upvalues (up to 255, each found among the open ones or made)
6390    // were one unit with the instruction: building a 250-upvalue closure over and over ran
6391    // at 4x plain code per unit. A unit per 8 upvalues, and 2 more per 8 made, charged by
6392    // both paths from this count, so fuel stays the same either way.
6393    let mut extra = ((descs.len() + 2 * fresh) / 8) as u64;
6394    if !heap.mem.fits(size) {
6395        return Err(Some(size));
6396    }
6397    let _ = heap.mem.charge(size);
6398    let mut ups = Vec::with_capacity(descs.len());
6399    // Open upvalues moved up to make room for new ones (SEC-M6).
6400    let mut shifted = 0usize;
6401    for &(in_stack, idx) in descs {
6402        if in_stack {
6403            let at = base + idx as usize;
6404            match open.binary_search_by(|(i, _)| i.cmp(&at)) {
6405                Ok(k) => {
6406                    let r = open.get(k).map_or(0, |(_, r)| *r);
6407                    ups.push(FuncRef { idx: r, generation: heap.upvals.gens.get(r as usize).copied().unwrap_or(0) });
6408                }
6409                Err(k) => {
6410                    let r = heap.new_upval_charged(Upval::Open { thread: cur, idx: at });
6411                    shifted += open.len() - k;
6412                    open.insert(k, (at, r.idx));
6413                    ups.push(r);
6414                }
6415            }
6416        } else {
6417            // The enclosing closure's own upvalue (read in place: making upvalues does not
6418            // touch the function slab).
6419            let r = match heap.funcs.get(closure.idx) {
6420                Some(Func::Lua { upvals, .. }) => upvals.get(idx as usize).copied(),
6421                _ => None,
6422            };
6423            ups.push(r.unwrap_or(FuncRef { idx: u32::MAX, generation: 0 }));
6424        }
6425    }
6426    // SEC-M6: an upvalue made below others already open moves them all up (the list is kept
6427    // sorted by slot): a frame of 8,000 locals captured from the last down ran at 22x plain
6428    // code per unit of fuel, more with more locals. Paid by the entries moved (slots, not
6429    // the seed, decide them, so fuel stays the same on both paths and under any seed).
6430    extra += (shifted / OPEN_SHIFT_PER_FUEL) as u64;
6431    let f = heap.new_func_charged(Func::Lua { proto: child, upvals: ups.into_boxed_slice() });
6432    Ok((Value::Func(f), extra))
6433}
6434
6435
6436/// Empties a result list, giving back its room when it is long (`NATIVE_CHUNK` values or
6437/// more): only lists being placed are counted (SEC-M15), so a long one kept was outside
6438/// the account (SEC7-1).
6439pub(crate) fn clear_list(v: &mut Vec<Value>) {
6440    if v.capacity() > crate::stdlib::NATIVE_CHUNK {
6441        *v = Vec::new();
6442    } else {
6443        v.clear();
6444    }
6445}