Skip to main content

lua_vm/
vm.rs

1//! Lua virtual machine — port of `lvm.c`.
2//!
3//! This module implements:
4//! - Number coercion helpers (tonumber_, flttointeger, tointegerns, tointeger)
5//! - Numeric `for`-loop preparation and stepping (forlimit, forprep, floatforloop)
6//! - Table get/set with metamethod chaining (finishget, finishset)
7//! - String comparison respecting embedded NULs (l_strcmp)
8//! - Relational operators: lessthan, lessequal, equalobj (with metamethods)
9//! - String concatenation (concat)
10//! - Object length operator (objlen)
11//! - Integer arithmetic: idiv, mod, modf, shiftl
12//! - Closure creation (pushclosure)
13//! - Yield-resume bridge (finishOp)
14//! - Main interpreter loop (execute) — the Lua bytecode dispatch engine.
15//!
16//! # Control flow note
17//! The C source uses `goto startfunc` / `goto returning` / `goto ret` across
18//! labelled points in `luaV_execute`. These are modelled with Rust's labelled
19//! loops (`'startfunc`, `'returning`, `'dispatch`) and `continue`/`break`
20//! on those labels.
21
22#[allow(unused_imports)]
23use crate::prelude::*;
24use crate::state::LuaState;
25use lua_types::opcode::Instruction;
26use lua_types::tagmethod::TagMethod;
27use lua_types::{CallInfoIdx, GcRef, LuaError, LuaString, LuaValue, StackIdx};
28
29/// TODO(multiversion, Step 0 deferred): this `OpCode` is a DUPLICATE of the
30/// canonical one in `lua-code/src/opcodes.rs:87`. The Step-0 plan wanted them
31/// consolidated to one owner (`lua-code`) with `lua-vm` depending on it, but
32/// that creates a DEPENDENCY CYCLE: `lua-code/Cargo.toml` already depends on
33/// `lua-vm`, so `lua-vm` cannot depend back on `lua-code`. Consolidating
34/// therefore requires moving the canonical `OpCode`/`OP_MODES`/`Instruction`
35/// definitions DOWN into `lua-types` (which `lua-types/src/opcode.rs` already
36/// reserves) and pointing both `lua-vm` and `lua-code` at it — plus reconciling
37/// variant-name skew between the two copies (`lua-vm` uses `BXOrK`/`BXOr`,
38/// `lua-code` uses `BXorK`/`BXor`; `lua-vm` also has `LoadKx`/`GetUpval`
39/// aliases) and the `InstructionExt` decode trait that lives here. That is a
40/// larger refactor than the Step-0 scaffold; deferred to keep 5.4 green.
41/// Duplicate sites: `lua-vm/src/vm.rs:45` (this enum) vs
42/// `lua-code/src/opcodes.rs:87` (canonical).
43///
44/// Original note: Stubbed locally with all 5.4 opcodes so call sites in
45/// vm.rs/debug.rs resolve; the real numeric values and per-opcode mode flags
46/// live in `lua-types/src/opcode.rs` once translated.
47///
48/// `#[repr(u8)]` with explicit discriminants matching C-Lua's `lopcodes.h`
49/// numbering (0=OP_MOVE, 1=OP_LOADI, ..., 82=OP_EXTRAARG). The ordered, dense
50/// 0..=82 layout lets LLVM compile `opcode()` to a bounds-checked cast on the
51/// low 7 bits of the instruction word and fuse it with the dispatch `match`
52/// downstream. Discriminant order intentionally matches the integer keys in
53/// `InstructionExt::opcode`, not the prior compile-order grouping.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
55#[allow(non_camel_case_types)]
56#[repr(u8)]
57pub enum OpCode {
58    Move = 0,
59    LoadI = 1,
60    LoadF = 2,
61    LoadK = 3,
62    LoadKX = 4,
63    LoadFalse = 5,
64    LFalseSkip = 6,
65    LoadTrue = 7,
66    LoadNil = 8,
67    GetUpVal = 9,
68    SetUpVal = 10,
69    GetTabUp = 11,
70    GetTable = 12,
71    GetI = 13,
72    GetField = 14,
73    SetTabUp = 15,
74    SetTable = 16,
75    SetI = 17,
76    SetField = 18,
77    NewTable = 19,
78    Self_ = 20,
79    AddI = 21,
80    AddK = 22,
81    SubK = 23,
82    MulK = 24,
83    ModK = 25,
84    PowK = 26,
85    DivK = 27,
86    IDivK = 28,
87    BAndK = 29,
88    BOrK = 30,
89    BXOrK = 31,
90    ShrI = 32,
91    ShlI = 33,
92    Add = 34,
93    Sub = 35,
94    Mul = 36,
95    Mod = 37,
96    Pow = 38,
97    Div = 39,
98    IDiv = 40,
99    BAnd = 41,
100    BOr = 42,
101    BXOr = 43,
102    Shl = 44,
103    Shr = 45,
104    MmBin = 46,
105    MmBinI = 47,
106    MmBinK = 48,
107    Unm = 49,
108    BNot = 50,
109    Not = 51,
110    Len = 52,
111    Concat = 53,
112    Close = 54,
113    Tbc = 55,
114    Jmp = 56,
115    Eq = 57,
116    Lt = 58,
117    Le = 59,
118    EqK = 60,
119    EqI = 61,
120    LtI = 62,
121    LeI = 63,
122    GtI = 64,
123    GeI = 65,
124    Test = 66,
125    TestSet = 67,
126    Call = 68,
127    TailCall = 69,
128    Return = 70,
129    Return0 = 71,
130    Return1 = 72,
131    ForLoop = 73,
132    ForPrep = 74,
133    TForPrep = 75,
134    TForCall = 76,
135    TForLoop = 77,
136    SetList = 78,
137    Closure = 79,
138    VarArg = 80,
139    VarArgPrep = 81,
140    ExtraArg = 82,
141    /// Lua 5.5 `global name = expr` guard. Reads register A (the current value
142    /// of the global), and if it is non-nil raises `global '<name>' already
143    /// defined`. Bx encodes the name: 0 means "?", otherwise Bx-1 is the index
144    /// into the constant table of the name string. Mirrors upstream
145    /// `OP_ERRNNIL` (`ldebug.c:luaG_errnnil`). 5.5-only; no other version emits
146    /// it. Appended after `ExtraArg` so existing opcode indices are unchanged.
147    ErrNNil = 83,
148    /// Lua 5.5 named-varargs (`function f(...t)`) support. Packs all extra
149    /// varargs of the current frame into a fresh table stored in register A,
150    /// with `table.pack` semantics: a 1-based sequence of all extra args plus
151    /// an integer `.n` field counting them (including nil holes). Emitted once
152    /// at function entry (right after `VarArgPrep`) when a vararg name is bound.
153    /// 5.5-only; no other version's parser emits it. Appended after `ErrNNil`
154    /// so existing opcode indices are unchanged.
155    VarArgPack = 84,
156    /// Lua 5.5 virtual named-vararg indexed read. Reads key register C from the
157    /// named vararg parameter in register B without materializing its table.
158    GetVArg = 85,
159}
160
161/// Number of distinct opcodes (matches C-Lua's `NUM_OPCODES`). Held for
162/// downstream debug/dump callers that count opcodes by name; the dispatch
163/// hot path in `InstructionExt::opcode` does its own per-arm match.
164#[allow(dead_code)]
165const NUM_OPCODES: u8 = 86;
166
167impl OpCode {
168    /// Legacy alias retained because the prior duplicate enum variant
169    /// `LoadKx` (case-typo of `LoadKX`) is still referenced from
170    /// `crates/lua-vm/src/debug.rs`. Both names denote the same C
171    /// `OP_LOADKX` opcode. Kept as an associated `const` so existing call
172    /// sites compile unchanged while the enum remains a clean 0..=82 dense
173    /// discriminant set required by `#[repr(u8)]`.
174    #[allow(non_upper_case_globals)]
175    pub const LoadKx: OpCode = OpCode::LoadKX;
176
177    /// Legacy alias for `GetUpVal` retained for the same reason as `LoadKx`.
178    #[allow(non_upper_case_globals)]
179    pub const GetUpval: OpCode = OpCode::GetUpVal;
180
181    /// Decode a raw opcode field value to an `OpCode`, or `None` if out of
182    /// range (`v >= 83`). This is the canonical decoder; `lua-code` re-exports
183    /// `OpCode` and uses this rather than carrying its own duplicate enum.
184    pub fn from_u32(v: u32) -> Option<Self> {
185        match v {
186            0 => Some(Self::Move),
187            1 => Some(Self::LoadI),
188            2 => Some(Self::LoadF),
189            3 => Some(Self::LoadK),
190            4 => Some(Self::LoadKX),
191            5 => Some(Self::LoadFalse),
192            6 => Some(Self::LFalseSkip),
193            7 => Some(Self::LoadTrue),
194            8 => Some(Self::LoadNil),
195            9 => Some(Self::GetUpVal),
196            10 => Some(Self::SetUpVal),
197            11 => Some(Self::GetTabUp),
198            12 => Some(Self::GetTable),
199            13 => Some(Self::GetI),
200            14 => Some(Self::GetField),
201            15 => Some(Self::SetTabUp),
202            16 => Some(Self::SetTable),
203            17 => Some(Self::SetI),
204            18 => Some(Self::SetField),
205            19 => Some(Self::NewTable),
206            20 => Some(Self::Self_),
207            21 => Some(Self::AddI),
208            22 => Some(Self::AddK),
209            23 => Some(Self::SubK),
210            24 => Some(Self::MulK),
211            25 => Some(Self::ModK),
212            26 => Some(Self::PowK),
213            27 => Some(Self::DivK),
214            28 => Some(Self::IDivK),
215            29 => Some(Self::BAndK),
216            30 => Some(Self::BOrK),
217            31 => Some(Self::BXOrK),
218            32 => Some(Self::ShrI),
219            33 => Some(Self::ShlI),
220            34 => Some(Self::Add),
221            35 => Some(Self::Sub),
222            36 => Some(Self::Mul),
223            37 => Some(Self::Mod),
224            38 => Some(Self::Pow),
225            39 => Some(Self::Div),
226            40 => Some(Self::IDiv),
227            41 => Some(Self::BAnd),
228            42 => Some(Self::BOr),
229            43 => Some(Self::BXOr),
230            44 => Some(Self::Shl),
231            45 => Some(Self::Shr),
232            46 => Some(Self::MmBin),
233            47 => Some(Self::MmBinI),
234            48 => Some(Self::MmBinK),
235            49 => Some(Self::Unm),
236            50 => Some(Self::BNot),
237            51 => Some(Self::Not),
238            52 => Some(Self::Len),
239            53 => Some(Self::Concat),
240            54 => Some(Self::Close),
241            55 => Some(Self::Tbc),
242            56 => Some(Self::Jmp),
243            57 => Some(Self::Eq),
244            58 => Some(Self::Lt),
245            59 => Some(Self::Le),
246            60 => Some(Self::EqK),
247            61 => Some(Self::EqI),
248            62 => Some(Self::LtI),
249            63 => Some(Self::LeI),
250            64 => Some(Self::GtI),
251            65 => Some(Self::GeI),
252            66 => Some(Self::Test),
253            67 => Some(Self::TestSet),
254            68 => Some(Self::Call),
255            69 => Some(Self::TailCall),
256            70 => Some(Self::Return),
257            71 => Some(Self::Return0),
258            72 => Some(Self::Return1),
259            73 => Some(Self::ForLoop),
260            74 => Some(Self::ForPrep),
261            75 => Some(Self::TForPrep),
262            76 => Some(Self::TForCall),
263            77 => Some(Self::TForLoop),
264            78 => Some(Self::SetList),
265            79 => Some(Self::Closure),
266            80 => Some(Self::VarArg),
267            81 => Some(Self::VarArgPrep),
268            82 => Some(Self::ExtraArg),
269            83 => Some(Self::ErrNNil),
270            84 => Some(Self::VarArgPack),
271            85 => Some(Self::GetVArg),
272            _ => None,
273        }
274    }
275}
276
277/// Instruction accessor extension trait. Per-mode decode helpers, with
278/// bodies derived from `lopcodes.h` macro shapes.
279pub trait InstructionExt {
280    fn opcode(&self) -> OpCode;
281    fn arg_a(&self) -> i32;
282    fn arg_b(&self) -> i32;
283    fn arg_c(&self) -> i32;
284    fn arg_k(&self) -> i32;
285    fn arg_ax(&self) -> i32;
286    fn arg_bx(&self) -> i32;
287    fn arg_s_b(&self) -> i32;
288    fn arg_s_c(&self) -> i32;
289    fn arg_s_j(&self) -> i32;
290    fn arg_s_bx(&self) -> i32;
291    fn test_k(&self) -> bool;
292    fn test_a_mode(&self) -> bool;
293    fn is_mm_mode(&self) -> bool;
294    fn is_vararg_prep(&self) -> bool;
295    fn is_in_top(&self) -> bool;
296}
297
298impl InstructionExt for Instruction {
299    ///
300    /// The 83-arm match looks expensive, but because `OpCode` is
301    /// `#[repr(u8)]` with explicit discriminants 0..=82 matching each match
302    /// arm's integer key exactly, LLVM compiles this to a single bounds
303    /// check + identity cast — no jump table, no memory indirection. The
304    /// previous array-lookup form forced an extra `OPCODE_TABLE` byte load
305    /// per dispatch tick that LLVM could not see through.
306    #[inline(always)]
307    fn opcode(&self) -> OpCode {
308        match (self.raw() & 0x7F) as u8 {
309            0 => OpCode::Move,
310            1 => OpCode::LoadI,
311            2 => OpCode::LoadF,
312            3 => OpCode::LoadK,
313            4 => OpCode::LoadKX,
314            5 => OpCode::LoadFalse,
315            6 => OpCode::LFalseSkip,
316            7 => OpCode::LoadTrue,
317            8 => OpCode::LoadNil,
318            9 => OpCode::GetUpVal,
319            10 => OpCode::SetUpVal,
320            11 => OpCode::GetTabUp,
321            12 => OpCode::GetTable,
322            13 => OpCode::GetI,
323            14 => OpCode::GetField,
324            15 => OpCode::SetTabUp,
325            16 => OpCode::SetTable,
326            17 => OpCode::SetI,
327            18 => OpCode::SetField,
328            19 => OpCode::NewTable,
329            20 => OpCode::Self_,
330            21 => OpCode::AddI,
331            22 => OpCode::AddK,
332            23 => OpCode::SubK,
333            24 => OpCode::MulK,
334            25 => OpCode::ModK,
335            26 => OpCode::PowK,
336            27 => OpCode::DivK,
337            28 => OpCode::IDivK,
338            29 => OpCode::BAndK,
339            30 => OpCode::BOrK,
340            31 => OpCode::BXOrK,
341            32 => OpCode::ShrI,
342            33 => OpCode::ShlI,
343            34 => OpCode::Add,
344            35 => OpCode::Sub,
345            36 => OpCode::Mul,
346            37 => OpCode::Mod,
347            38 => OpCode::Pow,
348            39 => OpCode::Div,
349            40 => OpCode::IDiv,
350            41 => OpCode::BAnd,
351            42 => OpCode::BOr,
352            43 => OpCode::BXOr,
353            44 => OpCode::Shl,
354            45 => OpCode::Shr,
355            46 => OpCode::MmBin,
356            47 => OpCode::MmBinI,
357            48 => OpCode::MmBinK,
358            49 => OpCode::Unm,
359            50 => OpCode::BNot,
360            51 => OpCode::Not,
361            52 => OpCode::Len,
362            53 => OpCode::Concat,
363            54 => OpCode::Close,
364            55 => OpCode::Tbc,
365            56 => OpCode::Jmp,
366            57 => OpCode::Eq,
367            58 => OpCode::Lt,
368            59 => OpCode::Le,
369            60 => OpCode::EqK,
370            61 => OpCode::EqI,
371            62 => OpCode::LtI,
372            63 => OpCode::LeI,
373            64 => OpCode::GtI,
374            65 => OpCode::GeI,
375            66 => OpCode::Test,
376            67 => OpCode::TestSet,
377            68 => OpCode::Call,
378            69 => OpCode::TailCall,
379            70 => OpCode::Return,
380            71 => OpCode::Return0,
381            72 => OpCode::Return1,
382            73 => OpCode::ForLoop,
383            74 => OpCode::ForPrep,
384            75 => OpCode::TForPrep,
385            76 => OpCode::TForCall,
386            77 => OpCode::TForLoop,
387            78 => OpCode::SetList,
388            79 => OpCode::Closure,
389            80 => OpCode::VarArg,
390            81 => OpCode::VarArgPrep,
391            82 => OpCode::ExtraArg,
392            83 => OpCode::ErrNNil,
393            84 => OpCode::VarArgPack,
394            85 => OpCode::GetVArg,
395            _ => OpCode::ExtraArg,
396        }
397    }
398    #[inline]
399    fn arg_a(&self) -> i32 {
400        ((self.raw() >> 7) & 0xFF) as i32
401    }
402    #[inline]
403    fn arg_b(&self) -> i32 {
404        ((self.raw() >> 16) & 0xFF) as i32
405    }
406    #[inline]
407    fn arg_c(&self) -> i32 {
408        ((self.raw() >> 24) & 0xFF) as i32
409    }
410    #[inline]
411    fn arg_k(&self) -> i32 {
412        ((self.raw() >> 15) & 0x1) as i32
413    }
414    #[inline]
415    fn arg_ax(&self) -> i32 {
416        (self.raw() >> 7) as i32
417    }
418    #[inline]
419    fn arg_bx(&self) -> i32 {
420        (self.raw() >> 15) as i32
421    }
422    #[inline]
423    fn arg_s_b(&self) -> i32 {
424        self.arg_b() - 0x7F
425    }
426    #[inline]
427    fn arg_s_c(&self) -> i32 {
428        self.arg_c() - 0x7F
429    }
430    #[inline]
431    fn arg_s_j(&self) -> i32 {
432        self.arg_ax() - 0xFFFFFF
433    }
434    #[inline]
435    fn arg_s_bx(&self) -> i32 {
436        self.arg_bx() - 0xFFFF
437    }
438    #[inline]
439    fn test_k(&self) -> bool {
440        (self.raw() & (1 << 15)) != 0
441    }
442    #[inline]
443    fn test_a_mode(&self) -> bool {
444        (op_mode_byte(self.opcode()) & (1 << 3)) != 0
445    }
446    #[inline]
447    fn is_mm_mode(&self) -> bool {
448        (op_mode_byte(self.opcode()) & (1 << 7)) != 0
449    }
450    #[inline]
451    fn is_vararg_prep(&self) -> bool {
452        matches!(self.opcode(), OpCode::VarArgPrep)
453    }
454    #[inline]
455    fn is_in_top(&self) -> bool {
456        (op_mode_byte(self.opcode()) & (1 << 5)) != 0 && self.arg_b() == 0
457    }
458}
459
460///
461/// Layout (from lopcodes.h `opmode` macro):
462///   bit 7: MM (metamethod call)
463///   bit 6: OT (instruction sets `L->top` for next when C == 0)
464///   bit 5: IT (instruction reads `L->top` from prev when B == 0)
465///   bit 4: T  (test; next instruction must be a jump)
466///   bit 3: A  (instruction writes register A)
467///   bits 0-2: op format mode (iABC, iABx, iAsBx, iAx, isJ)
468///
469/// lua-types does not yet expose the canonical `OP_MODES` table; this
470/// is a local stand-in keyed off the vm.rs `OpCode` copy so the four mode
471/// predicates above can answer correctly until the real table lands (see
472/// the `OpCode` duplication note above the `OpCode` definition).
473const OP_MODE_BYTES: [u8; NUM_OPCODES as usize] = [
474    0x08, // Move
475    0x0a, // LoadI
476    0x0a, // LoadF
477    0x09, // LoadK
478    0x09, // LoadKX
479    0x08, // LoadFalse
480    0x08, // LFalseSkip
481    0x08, // LoadTrue
482    0x08, // LoadNil
483    0x08, // GetUpVal
484    0x00, // SetUpVal
485    0x08, // GetTabUp
486    0x08, // GetTable
487    0x08, // GetI
488    0x08, // GetField
489    0x00, // SetTabUp
490    0x00, // SetTable
491    0x00, // SetI
492    0x00, // SetField
493    0x08, // NewTable
494    0x08, // Self_
495    0x08, // AddI
496    0x08, // AddK
497    0x08, // SubK
498    0x08, // MulK
499    0x08, // ModK
500    0x08, // PowK
501    0x08, // DivK
502    0x08, // IDivK
503    0x08, // BAndK
504    0x08, // BOrK
505    0x08, // BXOrK
506    0x08, // ShrI
507    0x08, // ShlI
508    0x08, // Add
509    0x08, // Sub
510    0x08, // Mul
511    0x08, // Mod
512    0x08, // Pow
513    0x08, // Div
514    0x08, // IDiv
515    0x08, // BAnd
516    0x08, // BOr
517    0x08, // BXOr
518    0x08, // Shl
519    0x08, // Shr
520    0x80, // MmBin
521    0x80, // MmBinI
522    0x80, // MmBinK
523    0x08, // Unm
524    0x08, // BNot
525    0x08, // Not
526    0x08, // Len
527    0x08, // Concat
528    0x00, // Close
529    0x00, // Tbc
530    0x04, // Jmp
531    0x10, // Eq
532    0x10, // Lt
533    0x10, // Le
534    0x10, // EqK
535    0x10, // EqI
536    0x10, // LtI
537    0x10, // LeI
538    0x10, // GtI
539    0x10, // GeI
540    0x10, // Test
541    0x18, // TestSet
542    0x68, // Call
543    0x68, // TailCall
544    0x20, // Return
545    0x00, // Return0
546    0x00, // Return1
547    0x09, // ForLoop
548    0x09, // ForPrep
549    0x01, // TForPrep
550    0x00, // TForCall
551    0x09, // TForLoop
552    0x20, // SetList
553    0x09, // Closure
554    0x48, // VarArg
555    0x28, // VarArgPrep
556    0x03, // ExtraArg
557    0x01, // ErrNNil (iABx, no A-write, no test)
558    0x08, // VarArgPack (iABC, sets register A)
559    0x08, // GetVArg (iABC, sets register A)
560];
561
562#[inline(always)]
563fn op_mode_byte(op: OpCode) -> u8 {
564    OP_MODE_BYTES[op as usize]
565}
566
567// ─── Constants ───────────────────────────────────────────────────────────────
568
569/// Limit for tag-method chains to avoid infinite loops.
570const MAX_TAG_LOOP: i32 = 2000;
571
572const NBITS: u32 = 64;
573
574// ─── F2Imod — float-to-integer rounding mode ────────────────────────────────
575
576/// Rounding mode for float→integer coercions.
577#[derive(Debug, Clone, Copy, PartialEq, Eq)]
578pub(crate) enum F2Imod {
579    /// Accept only exact integral values (no rounding).
580    Eq,
581    /// Round toward negative infinity.
582    Floor,
583    /// Round toward positive infinity.
584    Ceil,
585}
586
587// ─── Integer-overflow-safe helpers ──────────────────────────────────────────
588
589#[inline]
590fn intop_add(a: i64, b: i64) -> i64 {
591    (a as u64).wrapping_add(b as u64) as i64
592}
593
594#[inline]
595fn intop_sub(a: i64, b: i64) -> i64 {
596    (a as u64).wrapping_sub(b as u64) as i64
597}
598
599#[inline]
600fn intop_mul(a: i64, b: i64) -> i64 {
601    (a as u64).wrapping_mul(b as u64) as i64
602}
603
604/// Shifts via unsigned intermediate to get logical (not arithmetic) semantics.
605#[inline]
606fn intop_shr(x: i64, n: u32) -> i64 {
607    // PERF(port): logical right shift via unsigned; matches C unsigned semantics
608    (x as u64 >> n) as i64
609}
610
611#[inline]
612fn intop_shl(x: i64, n: u32) -> i64 {
613    (x as u64).wrapping_shl(n) as i64
614}
615
616#[inline]
617fn intop_band(a: i64, b: i64) -> i64 {
618    ((a as u64) & (b as u64)) as i64
619}
620#[inline]
621fn intop_bor(a: i64, b: i64) -> i64 {
622    ((a as u64) | (b as u64)) as i64
623}
624#[inline]
625fn intop_bxor(a: i64, b: i64) -> i64 {
626    ((a as u64) ^ (b as u64)) as i64
627}
628
629// ─── l_intfitsf ─────────────────────────────────────────────────────────────
630
631/// f64 has 53 bits of mantissa (including implicit leading 1).
632/// All i64 values with |i| <= 2^53 are exactly representable.
633#[inline]
634fn int_fits_float(i: i64) -> bool {
635    const MAXINTFITSF: u64 = 1u64 << f64::MANTISSA_DIGITS;
636    (MAXINTFITSF.wrapping_add(i as u64)) <= 2 * MAXINTFITSF
637}
638
639// ─── Private helper: string-to-number coercion ──────────────────────────────
640
641/// Attempt to convert a string value to a number in-place.
642/// Returns `Some(LuaValue)` with the numeric result, or `None` if the
643/// value is not a string or cannot be parsed as a numeral.
644fn str_to_number(obj: &LuaValue) -> Option<LuaValue> {
645    // cvt2num(o) = matches!(o, LuaValue::Str(_))
646    let s = match obj {
647        LuaValue::Str(ts) => ts.as_bytes().to_vec(),
648        _ => return None,
649    };
650    // Trim whitespace as Lua allows spaces around numerals in coercions.
651    let trimmed = trim_whitespace(&s);
652    if trimmed.is_empty() {
653        return None;
654    }
655    let mut result = LuaValue::Nil;
656    if crate::object::str2num(trimmed, &mut result) != 0 {
657        return Some(result);
658    }
659    None
660}
661
662fn trim_whitespace(s: &[u8]) -> &[u8] {
663    let start = s
664        .iter()
665        .position(|&b| !b.is_ascii_whitespace())
666        .unwrap_or(s.len());
667    let end = s
668        .iter()
669        .rposition(|&b| !b.is_ascii_whitespace())
670        .map(|i| i + 1)
671        .unwrap_or(0);
672    if start <= end {
673        &s[start..end]
674    } else {
675        &s[0..0]
676    }
677}
678
679// ─── Number coercion (public API matching lvm.h exports) ────────────────────
680
681/// Convert `obj` to f64, with string coercion.  Returns `Some(f64)` on
682/// success.  The fast path (already float) is handled by the caller's
683/// `tonumber` macro (inlined at call sites).
684pub(crate) fn tonumber_(obj: &LuaValue) -> Option<f64> {
685    if let LuaValue::Int(i) = obj {
686        return Some(*i as f64);
687    }
688    if let Some(v) = str_to_number(obj) {
689        return match v {
690            LuaValue::Float(f) => Some(f),
691            LuaValue::Int(i) => Some(i as f64),
692            _ => None,
693        };
694    }
695    None
696}
697
698/// Full numeric coercion including the float fast-path that `tonumber_` omits.
699fn tonumber(obj: &LuaValue) -> Option<f64> {
700    if let LuaValue::Float(f) = obj {
701        return Some(*f);
702    }
703    tonumber_(obj)
704}
705
706/// Convert float `n` to an integer according to `mode`.
707/// Returns `Some(i64)` on success.
708pub(crate) fn flt_to_integer(n: f64, mode: F2Imod) -> Option<i64> {
709    let f = n.floor();
710    if n != f {
711        match mode {
712            F2Imod::Eq => return None,
713            F2Imod::Ceil => {
714                // f = floor(n) + 1 = ceil(n) since n is not integral
715                let f = f + 1.0;
716                // lua_numbertointeger checks i64::MIN <= f <= i64::MAX
717                if f >= i64::MIN as f64 && f < (i64::MAX as f64 + 1.0) {
718                    return Some(f as i64);
719                }
720                return None;
721            }
722            F2Imod::Floor => { /* f is already floor(n) */ }
723        }
724    }
725    if f >= i64::MIN as f64 && f < (i64::MAX as f64 + 1.0) {
726        Some(f as i64)
727    } else {
728        None
729    }
730}
731
732/// Convert a value to integer without string coercion.
733pub(crate) fn to_integer_ns(obj: &LuaValue, mode: F2Imod) -> Option<i64> {
734    if let LuaValue::Float(f) = obj {
735        return flt_to_integer(*f, mode);
736    }
737    if let LuaValue::Int(i) = obj {
738        return Some(*i);
739    }
740    None
741}
742
743/// Convert a value to integer, with string coercion.
744pub(crate) fn to_integer(obj: &LuaValue, mode: F2Imod) -> Option<i64> {
745    let coerced;
746    let obj = if let Some(v) = str_to_number(obj) {
747        coerced = v;
748        &coerced
749    } else {
750        obj
751    };
752    to_integer_ns(obj, mode)
753}
754
755// ─── for-loop helpers ────────────────────────────────────────────────────────
756
757/// lua_Integer *p, lua_Integer step)`
758/// Compute the integer loop limit.  Returns `Ok(true)` to skip the loop,
759/// `Ok(false)` with `*p` set to the limit, or `Err` if the limit is not a
760/// number at all.
761fn forlimit(
762    state: &mut LuaState,
763    init: i64,
764    lim: &LuaValue,
765    step: i64,
766) -> Result<(bool, i64), LuaError> {
767    let round = if step < 0 {
768        F2Imod::Ceil
769    } else {
770        F2Imod::Floor
771    };
772    if let Some(p) = to_integer(lim, round) {
773        let skip = if step > 0 { init > p } else { init < p };
774        return Ok((skip, p));
775    }
776    let flim = match tonumber(lim) {
777        Some(f) => f,
778        None => return Err(crate::debug::for_error(state, lim, b"limit")),
779    };
780    if 0.0_f64 < flim {
781        // positive → too large
782        if step < 0 {
783            return Ok((true, 0));
784        }
785        Ok((false, i64::MAX))
786    } else {
787        // negative → less than min integer
788        if step > 0 {
789            return Ok((true, 0));
790        }
791        Ok((false, i64::MIN))
792    }
793}
794
795/// Prepare a numeric `for` loop (OP_FORPREP).
796/// Stack layout at `ra`:
797///   ra+0: init, ra+1: limit, ra+2: step, ra+3: control variable (written here)
798/// Returns `Ok(true)` to skip the loop body entirely.
799pub(crate) fn forprep(state: &mut LuaState, ra: StackIdx) -> Result<bool, LuaError> {
800    let pinit = state.get_at(ra);
801    let plimit = state.get_at(ra + 1);
802    let pstep = state.get_at(ra + 2);
803
804    if let (LuaValue::Int(init), LuaValue::Int(step)) = (&pinit, &pstep) {
805        let init = *init;
806        let step = *step;
807        if step == 0 {
808            return Err(LuaError::runtime(format_args!("'for' step is zero")));
809        }
810        state.set_at(ra + 3, LuaValue::Int(init));
811
812        let (skip, limit) = forlimit(state, init, &plimit, step)?;
813        if skip {
814            return Ok(true);
815        }
816        let count: u64 = if step > 0 {
817            let c = (limit as u64).wrapping_sub(init as u64);
818            if step != 1 {
819                c / (step as u64)
820            } else {
821                c
822            }
823        } else {
824            let c = (init as u64).wrapping_sub(limit as u64);
825            c / (((-(step + 1)) as u64).wrapping_add(1))
826        };
827        state.set_at(ra + 1, LuaValue::Int(count as i64));
828        Ok(false)
829    } else {
830        let limit_f = match tonumber(&plimit) {
831            Some(f) => f,
832            None => return Err(crate::debug::for_error(state, &plimit, b"limit")),
833        };
834        let step_f = match tonumber(&pstep) {
835            Some(f) => f,
836            None => return Err(crate::debug::for_error(state, &pstep, b"step")),
837        };
838        let init_f = match tonumber(&pinit) {
839            Some(f) => f,
840            None => return Err(crate::debug::for_error(state, &pinit, b"initial value")),
841        };
842        if step_f == 0.0 {
843            return Err(LuaError::runtime(format_args!("'for' step is zero")));
844        }
845        let skip = if step_f > 0.0 {
846            limit_f < init_f
847        } else {
848            init_f < limit_f
849        };
850        if skip {
851            return Ok(true);
852        }
853        //    setfltvalue(s2v(ra), init); setfltvalue(s2v(ra+3), init);
854        state.set_at(ra + 1, LuaValue::Float(limit_f));
855        state.set_at(ra + 2, LuaValue::Float(step_f));
856        state.set_at(ra, LuaValue::Float(init_f));
857        state.set_at(ra + 3, LuaValue::Float(init_f));
858        Ok(false)
859    }
860}
861
862/// `forlimit` for the legacy (<=5.3) numeric `for`. Mirrors 5.3.6 `forlimit`:
863/// returns `Some((clamped_limit, stopnow))` when `obj` is a number — clamping an
864/// out-of-integer-range float limit to `i64::MAX`/`MIN` and flagging `stopnow`
865/// when that means the loop must not run — or `None` when `obj` is not a number
866/// (the caller then falls through to the float path / error).
867fn forlimit_legacy(obj: &LuaValue, step: i64) -> Option<(i64, bool)> {
868    let round = if step < 0 {
869        F2Imod::Ceil
870    } else {
871        F2Imod::Floor
872    };
873    if let Some(p) = to_integer(obj, round) {
874        return Some((p, false));
875    }
876    let n = tonumber(obj)?;
877    if 0.0 < n {
878        Some((i64::MAX, step < 0))
879    } else {
880        Some((i64::MIN, step >= 0))
881    }
882}
883
884/// Prepare a legacy (<=5.3) numeric `for` (OP_FORPREP). Mirrors 5.3.6
885/// `OP_FORPREP`: subtract the step from the initial value and let the caller
886/// always jump forward to OP_FORLOOP (which performs the first test). This is
887/// what makes iteration 1 enter the body via a backward jump — the source of
888/// the extra per-iteration line-hook event on <=5.3 (issue #92). Note there is
889/// deliberately **no** "'for' step is zero" check (that was added in 5.4): on
890/// 5.3 a zero step simply fails FORLOOP's test and the loop runs zero times.
891pub(crate) fn forprep_legacy(state: &mut LuaState, ra: StackIdx) -> Result<(), LuaError> {
892    let init = state.get_at(ra);
893    let plimit = state.get_at(ra + 1);
894    let pstep = state.get_at(ra + 2);
895
896    // 5.1/5.2 `OP_FORPREP` coerce in source order init → limit → step, so the
897    // *initial value* is the first reported when several operands are
898    // non-numeric (`for i='a','b'` blames the initial value, not the limit).
899    // 5.3 reordered the checks to limit → step → init (it clamps the limit
900    // first via `forlimit`), which the shared path below already mirrors.
901    if matches!(
902        state.global().lua_version,
903        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
904    ) && !matches!(init, LuaValue::Int(_))
905        && tonumber(&init).is_none()
906    {
907        return Err(crate::debug::for_error(state, &init, b"initial value"));
908    }
909
910    if let (LuaValue::Int(initv), LuaValue::Int(stepv)) = (&init, &pstep) {
911        let (initv, stepv) = (*initv, *stepv);
912        if let Some((ilimit, stopnow)) = forlimit_legacy(&plimit, stepv) {
913            let base = if stopnow { 0 } else { initv };
914            state.set_at(ra + 1, LuaValue::Int(ilimit));
915            state.set_at(ra, LuaValue::Int(intop_sub(base, stepv)));
916            return Ok(());
917        }
918        // limit is not a number: fall through so the float path raises
919        // "'for' limit must be a number" in upstream source order.
920    }
921
922    let nlimit = match tonumber(&plimit) {
923        Some(f) => f,
924        None => return Err(crate::debug::for_error(state, &plimit, b"limit")),
925    };
926    let nstep = match tonumber(&pstep) {
927        Some(f) => f,
928        None => return Err(crate::debug::for_error(state, &pstep, b"step")),
929    };
930    let ninit = match tonumber(&init) {
931        Some(f) => f,
932        None => return Err(crate::debug::for_error(state, &init, b"initial value")),
933    };
934    state.set_at(ra + 1, LuaValue::Float(nlimit));
935    state.set_at(ra + 2, LuaValue::Float(nstep));
936    state.set_at(ra, LuaValue::Float(ninit - nstep));
937    Ok(())
938}
939
940/// One iteration of a legacy (<=5.3) numeric `for` (OP_FORLOOP). Adds the step
941/// to the index and tests against the already-clamped limit; returns `true`
942/// when the loop continues (the caller jumps back to the body). Mirrors 5.3.6
943/// `OP_FORLOOP` — compare-based, no precomputed count.
944fn forloop_legacy(state: &mut LuaState, ra: StackIdx) -> bool {
945    if let LuaValue::Int(step) = state.get_at(ra + 2) {
946        let idx = intop_add(
947            match state.get_at(ra) {
948                LuaValue::Int(x) => x,
949                _ => 0,
950            },
951            step,
952        );
953        let limit = match state.get_at(ra + 1) {
954            LuaValue::Int(l) => l,
955            _ => 0,
956        };
957        let cont = if step > 0 { idx <= limit } else { limit <= idx };
958        if cont {
959            state.set_at(ra, LuaValue::Int(idx));
960            state.set_at(ra + 3, LuaValue::Int(idx));
961        }
962        cont
963    } else {
964        let step = match state.get_at(ra + 2) {
965            LuaValue::Float(f) => f,
966            _ => return false,
967        };
968        let idx = match state.get_at(ra) {
969            LuaValue::Float(f) => f,
970            _ => return false,
971        } + step;
972        let limit = match state.get_at(ra + 1) {
973            LuaValue::Float(f) => f,
974            _ => return false,
975        };
976        let cont = if step > 0.0 {
977            idx <= limit
978        } else {
979            limit <= idx
980        };
981        if cont {
982            state.set_at(ra, LuaValue::Float(idx));
983            state.set_at(ra + 3, LuaValue::Float(idx));
984        }
985        cont
986    }
987}
988
989/// Increments the float loop index and returns `true` if the loop continues.
990fn float_for_loop(state: &mut LuaState, ra: StackIdx) -> bool {
991    //    idx  = fltvalue(s2v(ra));
992    let step = match state.get_at(ra + 2) {
993        LuaValue::Float(f) => f,
994        _ => return false,
995    };
996    let limit = match state.get_at(ra + 1) {
997        LuaValue::Float(f) => f,
998        _ => return false,
999    };
1000    let idx = match state.get_at(ra) {
1001        LuaValue::Float(f) => f,
1002        _ => return false,
1003    };
1004    let idx = idx + step;
1005    if if step > 0.0 {
1006        idx <= limit
1007    } else {
1008        limit <= idx
1009    } {
1010        state.set_at(ra, LuaValue::Float(idx));
1011        state.set_at(ra + 3, LuaValue::Float(idx));
1012        true
1013    } else {
1014        false
1015    }
1016}
1017
1018// ─── Table get/set with metamethod chains ────────────────────────────────────
1019
1020/// StkId val, const TValue *slot)`
1021/// Finish a table-get with metamethod lookup.  `slot_was_none = true` means
1022/// `t` is not a table and we should look for `__index` on `t` itself.
1023pub(crate) fn finish_get(
1024    state: &mut LuaState,
1025    t_val: LuaValue,
1026    key: LuaValue,
1027    result_idx: StackIdx,
1028    slot_empty: bool,
1029    t_idx: Option<StackIdx>,
1030    var_hint: Option<(&[u8], &[u8])>,
1031) -> Result<(), LuaError> {
1032    let mut t = t_val;
1033    let mut t_idx = t_idx;
1034    for _loop in 0..MAX_TAG_LOOP {
1035        let tm: LuaValue;
1036        if slot_empty && !matches!(t, LuaValue::Table(_)) {
1037            tm = state.get_tm_by_obj(&t, TagMethod::Index);
1038            if matches!(tm, LuaValue::Nil) {
1039                return Err(match (t_idx, var_hint) {
1040                    (Some(idx), _) => crate::debug::type_error(state, &t, idx, b"index"),
1041                    (None, Some((kind, name))) => {
1042                        crate::debug::type_error_with_hint(state, &t, b"index", kind, name)
1043                    }
1044                    (None, None) => LuaError::type_error(&t, "index"),
1045                });
1046            }
1047        } else {
1048            let mt = state.table_metatable(&t);
1049            tm = state.fast_tm_table(mt.as_ref(), TagMethod::Index);
1050            if matches!(tm, LuaValue::Nil) {
1051                state.set_at(result_idx, LuaValue::Nil);
1052                return Ok(());
1053            }
1054        }
1055        if matches!(tm, LuaValue::Function(_)) {
1056            state.call_tm_res(tm, &t, &key, result_idx)?;
1057            return Ok(());
1058        }
1059        t = tm.clone();
1060        t_idx = None;
1061        if let Some(v) = state.fast_get(&t, &key)? {
1062            state.set_at(result_idx, v);
1063            return Ok(());
1064        }
1065        // else: loop — tail-call luaV_finishget
1066    }
1067    Err(LuaError::runtime(format_args!(
1068        "'__index' chain too long; possible loop"
1069    )))
1070}
1071
1072/// TValue *val, const TValue *slot)`
1073/// Finish a table-set with `__newindex` metamethod lookup.
1074///
1075/// `var_hint` carries a `(kind, name)` pair (e.g. `(b"upvalue", b"a")`) used
1076/// only when `t_idx` is None and the target is non-indexable — typically
1077/// when the LHS is an upvalue (OP_SETTABUP). Pointer-identifying var_info
1078/// won't recover the upvalue's name in that case, so the caller passes it
1079/// in directly.
1080pub(crate) fn finish_set(
1081    state: &mut LuaState,
1082    t_val: LuaValue,
1083    key: LuaValue,
1084    val: LuaValue,
1085    _slot_present: bool,
1086    t_idx: Option<StackIdx>,
1087    var_hint: Option<(&[u8], &[u8])>,
1088) -> Result<(), LuaError> {
1089    let mut t = t_val;
1090    let mut t_idx = t_idx;
1091    for _loop in 0..MAX_TAG_LOOP {
1092        let tm: LuaValue;
1093        if matches!(t, LuaValue::Table(_)) {
1094            let mt = state.table_metatable(&t);
1095            tm = state.fast_tm_table(mt.as_ref(), TagMethod::NewIndex);
1096            if matches!(tm, LuaValue::Nil) {
1097                state.table_raw_set(&t, key, val.clone())?;
1098                state.gc_value_barrier_back(&t, &val);
1099                return Ok(());
1100            }
1101        } else {
1102            tm = state.get_tm_by_obj(&t, TagMethod::NewIndex);
1103            if matches!(tm, LuaValue::Nil) {
1104                return Err(match (t_idx, var_hint) {
1105                    (Some(idx), _) => crate::debug::type_error(state, &t, idx, b"index"),
1106                    (None, Some((kind, name))) => {
1107                        crate::debug::type_error_with_hint(state, &t, b"index", kind, name)
1108                    }
1109                    (None, None) => LuaError::type_error(&t, "index"),
1110                });
1111            }
1112        }
1113        if matches!(tm, LuaValue::Function(_)) {
1114            state.call_tm(tm, &t, &key, &val)?;
1115            return Ok(());
1116        }
1117        t = tm.clone();
1118        t_idx = None;
1119        if state.fast_get(&t, &key)?.is_some() {
1120            state.table_raw_set(&t, key.clone(), val.clone())?;
1121            state.gc_value_barrier_back(&t, &val);
1122            return Ok(());
1123        }
1124    }
1125    Err(LuaError::runtime(format_args!(
1126        "'__newindex' chain too long; possible loop"
1127    )))
1128}
1129
1130// ─── String comparison ───────────────────────────────────────────────────────
1131
1132/// Lexicographic string comparison that handles embedded NULs by segmenting.
1133/// Returns negative / zero / positive like `strcmp`.
1134///
1135/// C uses `strcoll` for locale-aware comparison within each NUL-free
1136/// segment. There is no locale support here, so `slice::cmp` is used instead
1137/// (byte-by-byte lexicographic order, equivalent to `memcmp`). This means
1138/// locale-specific ordering (e.g. accented characters) differs from the C
1139/// reference.
1140fn str_cmp(s1: &[u8], s2: &[u8]) -> std::cmp::Ordering {
1141    let mut s1 = s1;
1142    let mut s2 = s2;
1143    loop {
1144        // Find the first NUL in each slice to delimit a segment.
1145        let z1 = s1.iter().position(|&b| b == 0).unwrap_or(s1.len());
1146        let z2 = s2.iter().position(|&b| b == 0).unwrap_or(s2.len());
1147        // Compare segment up to first NUL using byte order (not strcoll).
1148        let seg_cmp = s1[..z1].cmp(&s2[..z2]);
1149        if seg_cmp != std::cmp::Ordering::Equal {
1150            return seg_cmp;
1151        }
1152        // Both segments compare equal up to the NUL position.
1153        if z2 == s2.len() {
1154            // s2 is finished
1155            if z1 == s1.len() {
1156                return std::cmp::Ordering::Equal;
1157            }
1158            return std::cmp::Ordering::Greater; // s1 has more
1159        }
1160        if z1 == s1.len() {
1161            return std::cmp::Ordering::Less; // s1 finished, s2 has more
1162        }
1163        // Both have NULs; advance past them.
1164        s1 = &s1[z1 + 1..];
1165        s2 = &s2[z2 + 1..];
1166    }
1167}
1168
1169// ─── Comparison helpers (int vs float mixed comparisons) ────────────────────
1170
1171#[inline]
1172fn lt_int_float(i: i64, f: f64) -> bool {
1173    if int_fits_float(i) {
1174        (i as f64) < f
1175    } else {
1176        match flt_to_integer(f, F2Imod::Ceil) {
1177            Some(fi) => i < fi,
1178            None => f > 0.0, // f is out of integer range; positive means i < f
1179        }
1180    }
1181}
1182
1183#[inline]
1184fn le_int_float(i: i64, f: f64) -> bool {
1185    if int_fits_float(i) {
1186        (i as f64) <= f
1187    } else {
1188        match flt_to_integer(f, F2Imod::Floor) {
1189            Some(fi) => i <= fi,
1190            None => f > 0.0,
1191        }
1192    }
1193}
1194
1195#[inline]
1196fn lt_float_int(f: f64, i: i64) -> bool {
1197    if int_fits_float(i) {
1198        f < (i as f64)
1199    } else {
1200        match flt_to_integer(f, F2Imod::Floor) {
1201            Some(fi) => fi < i,
1202            None => f < 0.0,
1203        }
1204    }
1205}
1206
1207#[inline]
1208fn le_float_int(f: f64, i: i64) -> bool {
1209    if int_fits_float(i) {
1210        f <= (i as f64)
1211    } else {
1212        match flt_to_integer(f, F2Imod::Ceil) {
1213            Some(fi) => fi <= i,
1214            None => f < 0.0,
1215        }
1216    }
1217}
1218
1219#[inline]
1220fn lt_num(l: &LuaValue, r: &LuaValue) -> bool {
1221    debug_assert!(matches!(l, LuaValue::Int(_) | LuaValue::Float(_)));
1222    debug_assert!(matches!(r, LuaValue::Int(_) | LuaValue::Float(_)));
1223    match (l, r) {
1224        (LuaValue::Int(li), LuaValue::Int(ri)) => li < ri,
1225        (LuaValue::Int(li), LuaValue::Float(rf)) => lt_int_float(*li, *rf),
1226        (LuaValue::Float(lf), LuaValue::Float(rf)) => lf < rf,
1227        (LuaValue::Float(lf), LuaValue::Int(ri)) => lt_float_int(*lf, *ri),
1228        _ => false,
1229    }
1230}
1231
1232#[inline]
1233fn le_num(l: &LuaValue, r: &LuaValue) -> bool {
1234    debug_assert!(matches!(l, LuaValue::Int(_) | LuaValue::Float(_)));
1235    debug_assert!(matches!(r, LuaValue::Int(_) | LuaValue::Float(_)));
1236    match (l, r) {
1237        (LuaValue::Int(li), LuaValue::Int(ri)) => li <= ri,
1238        (LuaValue::Int(li), LuaValue::Float(rf)) => le_int_float(*li, *rf),
1239        (LuaValue::Float(lf), LuaValue::Float(rf)) => lf <= rf,
1240        (LuaValue::Float(lf), LuaValue::Int(ri)) => le_float_int(*lf, *ri),
1241        _ => false,
1242    }
1243}
1244
1245/// `l < r` for non-numbers (strings or metamethod).
1246fn less_than_others(state: &mut LuaState, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
1247    debug_assert!(
1248        !(matches!(l, LuaValue::Int(_) | LuaValue::Float(_))
1249            && matches!(r, LuaValue::Int(_) | LuaValue::Float(_)))
1250    );
1251    match (l, r) {
1252        (LuaValue::Str(ts1), LuaValue::Str(ts2)) => {
1253            Ok(str_cmp(ts1.as_bytes(), ts2.as_bytes()) == std::cmp::Ordering::Less)
1254        }
1255        _ => state.call_order_tm(l, r, TagMethod::Lt),
1256    }
1257}
1258
1259pub(crate) fn less_than(
1260    state: &mut LuaState,
1261    l: &LuaValue,
1262    r: &LuaValue,
1263) -> Result<bool, LuaError> {
1264    if matches!(l, LuaValue::Int(_) | LuaValue::Float(_))
1265        && matches!(r, LuaValue::Int(_) | LuaValue::Float(_))
1266    {
1267        Ok(lt_num(l, r))
1268    } else {
1269        less_than_others(state, l, r)
1270    }
1271}
1272
1273fn less_equal_others(state: &mut LuaState, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
1274    match (l, r) {
1275        (LuaValue::Str(ts1), LuaValue::Str(ts2)) => {
1276            Ok(str_cmp(ts1.as_bytes(), ts2.as_bytes()) != std::cmp::Ordering::Greater)
1277        }
1278        _ => state.call_order_tm(l, r, TagMethod::Le),
1279    }
1280}
1281
1282pub(crate) fn less_equal(
1283    state: &mut LuaState,
1284    l: &LuaValue,
1285    r: &LuaValue,
1286) -> Result<bool, LuaError> {
1287    if matches!(l, LuaValue::Int(_) | LuaValue::Float(_))
1288        && matches!(r, LuaValue::Int(_) | LuaValue::Float(_))
1289    {
1290        Ok(le_num(l, r))
1291    } else {
1292        less_equal_others(state, l, r)
1293    }
1294}
1295
1296// ─── Equality ────────────────────────────────────────────────────────────────
1297
1298/// `luaO_rawequalObj`: primitive equality with no metamethod dispatch.
1299///
1300/// Calling `equal_obj` with a `None` state suppresses every metamethod, so the
1301/// result is the raw tag+value/pointer comparison and can never raise. Used by
1302/// the 5.1 same-reference comparison rule to test whether two handler functions
1303/// are the identical reference.
1304pub(crate) fn raw_equal_values(t1: &LuaValue, t2: &LuaValue) -> bool {
1305    matches!(equal_obj(None, t1, t2), Ok(true))
1306}
1307
1308/// Select the `__eq` metamethod for two table/userdata operands.
1309///
1310/// 5.2+ consult the left operand's handler, then the right's (left-then-right).
1311/// 5.1 honours `__eq` only when both operands resolve to the SAME handler
1312/// reference (`get_equalTM`), returning `Nil` (i.e. "not equal") otherwise. The
1313/// caller has already established that the operands are the same kind and not
1314/// the identical object.
1315fn equal_tm(state: &mut LuaState, t1: &LuaValue, t2: &LuaValue) -> LuaValue {
1316    let eq = crate::tagmethods::TagMethod::Eq;
1317    if state.global().lua_version == lua_types::LuaVersion::V51 {
1318        return crate::tagmethods::get_comp_tm_51(state, t1, t2, eq);
1319    }
1320    let tm1 = crate::tagmethods::get_tm_by_obj(state, t1, eq);
1321    if tm1.is_nil() {
1322        crate::tagmethods::get_tm_by_obj(state, t2, eq)
1323    } else {
1324        tm1
1325    }
1326}
1327
1328/// Main equality test.  `raw = true` means no metamethods (L == NULL in C).
1329pub(crate) fn equal_obj(
1330    state: Option<&mut LuaState>,
1331    t1: &LuaValue,
1332    t2: &LuaValue,
1333) -> Result<bool, LuaError> {
1334    // In Rust, same variant = same tag.  If variant differs, check the number
1335    // special case (Int and Float can be equal).
1336    let same_variant = std::mem::discriminant(t1) == std::mem::discriminant(t2);
1337    if !same_variant {
1338        let t1_is_num = matches!(t1, LuaValue::Int(_) | LuaValue::Float(_));
1339        let t2_is_num = matches!(t2, LuaValue::Int(_) | LuaValue::Float(_));
1340        if !(t1_is_num && t2_is_num) {
1341            return Ok(false);
1342        }
1343        // luaV_tointegerns(t1, &i1, F2Ieq) && luaV_tointegerns(t2, &i2, F2Ieq) && i1==i2
1344        let i1 = to_integer_ns(t1, F2Imod::Eq);
1345        let i2 = to_integer_ns(t2, F2Imod::Eq);
1346        return Ok(i1.is_some() && i2.is_some() && i1 == i2);
1347    }
1348
1349    match (t1, t2) {
1350        (LuaValue::Nil, LuaValue::Nil) => Ok(true),
1351        (LuaValue::Bool(b1), LuaValue::Bool(b2)) => Ok(b1 == b2),
1352        (LuaValue::Int(i1), LuaValue::Int(i2)) => Ok(i1 == i2),
1353        (LuaValue::Float(f1), LuaValue::Float(f2)) => Ok(f1 == f2),
1354        (LuaValue::LightUserData(p1), LuaValue::LightUserData(p2)) => Ok(p1 == p2),
1355        (LuaValue::Function(f1), LuaValue::Function(f2)) => {
1356            use lua_types::closure::LuaClosure;
1357            let same = match (f1, f2) {
1358                (LuaClosure::Lua(a), LuaClosure::Lua(b)) => GcRef::ptr_eq(a, b),
1359                (LuaClosure::C(a), LuaClosure::C(b)) => GcRef::ptr_eq(a, b),
1360                (LuaClosure::LightC(a), LuaClosure::LightC(b)) => a == b,
1361                _ => false,
1362            };
1363            Ok(same)
1364        }
1365        (LuaValue::Str(s1), LuaValue::Str(s2)) => {
1366            //    luaS_eqlngstr for long strings (content eq).
1367            // In Rust, LuaString PartialEq handles both.
1368            Ok(s1 == s2)
1369        }
1370        (LuaValue::UserData(u1), LuaValue::UserData(u2)) => {
1371            //    else if (L == NULL) return 0;
1372            //    tm = fasttm(L, uvalue(t1)->metatable, TM_EQ);
1373            if std::ptr::eq(u1.as_ptr(), u2.as_ptr()) {
1374                return Ok(true);
1375            }
1376            let Some(state) = state else {
1377                return Ok(false);
1378            };
1379            let tm = equal_tm(state, t1, t2);
1380            if matches!(tm, LuaValue::Nil) {
1381                return Ok(false);
1382            }
1383            let result = state.call_tm_res_bool(tm, t1, t2)?;
1384            Ok(result)
1385        }
1386        (LuaValue::Table(h1), LuaValue::Table(h2)) => {
1387            if std::ptr::eq(h1.as_ptr(), h2.as_ptr()) {
1388                return Ok(true);
1389            }
1390            let Some(state) = state else {
1391                return Ok(false);
1392            };
1393            let tm = equal_tm(state, t1, t2);
1394            if matches!(tm, LuaValue::Nil) {
1395                return Ok(false);
1396            }
1397            let result = state.call_tm_res_bool(tm, t1, t2)?;
1398            Ok(result)
1399        }
1400        (LuaValue::Thread(a), LuaValue::Thread(b)) => Ok(GcRef::ptr_eq(a, b)),
1401        _ => Ok(std::ptr::eq(t1 as *const _, t2 as *const _)),
1402    }
1403}
1404
1405// ─── Concatenation ───────────────────────────────────────────────────────────
1406
1407/// Copy `n` strings from `top-n .. top-1` into `buff`.
1408fn copy_to_buf(state: &LuaState, top: StackIdx, n: u32, buf: &mut Vec<u8>) {
1409    buf.clear();
1410    let mut remaining = n;
1411    loop {
1412        let idx = top - remaining as i32;
1413        let v = state.get_at(idx);
1414        if let LuaValue::Str(ts) = v {
1415            buf.extend_from_slice(ts.as_bytes());
1416        }
1417        if remaining <= 1 {
1418            break;
1419        }
1420        remaining -= 1;
1421    }
1422}
1423
1424/// Concatenate `total` values on the top of the stack, leaving one result.
1425pub(crate) fn concat(state: &mut LuaState, total: i32) -> Result<(), LuaError> {
1426    if total == 1 {
1427        return Ok(());
1428    }
1429    if total == 2 {
1430        let top = state.top_idx();
1431        let v_tm1 = state.get_at(top - 1);
1432        let v_tm2 = state.get_at(top - 2);
1433        if concat_pair_fast(state, top, v_tm2, v_tm1)? {
1434            return Ok(());
1435        }
1436    }
1437    let mut total = total;
1438    loop {
1439        let top = state.top_idx();
1440        let v_tm1 = state.get_at(top - 1); // top-1
1441        let v_tm2 = state.get_at(top - 2); // top-2
1442
1443        //    luaT_tryconcatTM(L);
1444        let top2_coercible = matches!(v_tm2, LuaValue::Str(_))
1445            || matches!(v_tm2, LuaValue::Int(_) | LuaValue::Float(_));
1446        // tostring converts numbers to strings; we check top-1 too
1447        let top1_stringlike = matches!(v_tm1, LuaValue::Str(_))
1448            || matches!(v_tm1, LuaValue::Int(_) | LuaValue::Float(_));
1449        if !top2_coercible || !top1_stringlike {
1450            state.try_concat_tm(&v_tm1, &v_tm2)?;
1451            // at the bottom of the do-while runs for this branch too.
1452            // The metamethod writes its single result to top-2, leaving
1453            // top-1 stale; popping that stale slot is what makes the next
1454            // iteration see the just-computed result at the new top-1.
1455            total -= 1;
1456            let top = state.top_idx();
1457            state.set_top(top - 1);
1458            if total <= 1 {
1459                break;
1460            }
1461            continue;
1462        }
1463
1464        let is_empty =
1465            |v: &LuaValue| -> bool { matches!(v, LuaValue::Str(s) if s.as_bytes().is_empty()) };
1466
1467        let n: u32;
1468        if is_empty(&v_tm1) {
1469            state.coerce_to_string(top - 2)?;
1470            n = 2;
1471        } else if is_empty(&v_tm2) {
1472            // so top-1 is guaranteed to be a string here. We replicate that
1473            // conversion before the copy so numbers don't leak through.
1474            state.coerce_to_string(top - 1)?;
1475            let v = state.get_at(top - 1);
1476            state.set_at(top - 2, v);
1477            n = 2;
1478        } else {
1479            // Ensure top-1 is a string (coerce if number)
1480            state.coerce_to_string(top - 1)?;
1481            let s1 = match state.get_at(top - 1) {
1482                LuaValue::Str(ts) => ts.as_bytes().len(),
1483                _ => 0,
1484            };
1485            let mut total_len = s1;
1486            let mut count: u32 = 1;
1487            let top = state.top_idx();
1488            loop {
1489                if count as i32 >= total {
1490                    break;
1491                }
1492                let idx = top - (count as i32 + 1);
1493                let v = state.get_at(idx);
1494                if !matches!(v, LuaValue::Str(_) | LuaValue::Int(_) | LuaValue::Float(_)) {
1495                    break;
1496                }
1497                state.coerce_to_string(idx)?;
1498                let l = match state.get_at(idx) {
1499                    LuaValue::Str(ts) => ts.as_bytes().len(),
1500                    _ => 0,
1501                };
1502                if l >= usize::MAX - total_len {
1503                    // pop strings to avoid wasting stack
1504                    state.set_top(top - total as i32);
1505                    return Err(LuaError::runtime(format_args!("string length overflow")));
1506                }
1507                total_len += l;
1508                count += 1;
1509            }
1510            n = count;
1511
1512            // Build concatenated result
1513            if let Some(err) = state.sandbox_reserve(total_len) {
1514                return Err(err);
1515            }
1516            let mut buf: Vec<u8> = Vec::with_capacity(total_len);
1517            let top = state.top_idx();
1518            copy_to_buf(state, top, n, &mut buf);
1519            let ts = state.intern_or_create_str(&buf)?;
1520            state.set_at(top - n as i32, LuaValue::Str(ts));
1521        }
1522        total -= n as i32 - 1;
1523        let top = state.top_idx();
1524        state.set_top(top - ((n - 1) as i32));
1525
1526        if total <= 1 {
1527            break;
1528        }
1529    }
1530    Ok(())
1531}
1532
1533enum ConcatPiece {
1534    Str(GcRef<LuaString>),
1535    Num(Vec<u8>),
1536}
1537
1538impl ConcatPiece {
1539    #[inline]
1540    fn len(&self) -> usize {
1541        match self {
1542            ConcatPiece::Str(s) => s.as_bytes().len(),
1543            ConcatPiece::Num(bytes) => bytes.len(),
1544        }
1545    }
1546
1547    #[inline]
1548    fn append_to(&self, out: &mut Vec<u8>) {
1549        match self {
1550            ConcatPiece::Str(s) => out.extend_from_slice(s.as_bytes()),
1551            ConcatPiece::Num(bytes) => out.extend_from_slice(bytes),
1552        }
1553    }
1554}
1555
1556#[inline]
1557fn concat_piece(v: LuaValue, version: lua_types::LuaVersion) -> Option<ConcatPiece> {
1558    match v {
1559        LuaValue::Str(s) => Some(ConcatPiece::Str(s)),
1560        LuaValue::Int(_) | LuaValue::Float(_) => Some(ConcatPiece::Num(
1561            crate::object::number_to_str_buf(&v, version),
1562        )),
1563        _ => None,
1564    }
1565}
1566
1567#[inline]
1568fn concat_pair_fast(
1569    state: &mut LuaState,
1570    top: StackIdx,
1571    left: LuaValue,
1572    right: LuaValue,
1573) -> Result<bool, LuaError> {
1574    let version = state.global().lua_version;
1575    let Some(left) = concat_piece(left, version) else {
1576        return Ok(false);
1577    };
1578    let Some(right) = concat_piece(right, version) else {
1579        return Ok(false);
1580    };
1581    let total_len = left
1582        .len()
1583        .checked_add(right.len())
1584        .ok_or_else(|| LuaError::runtime(format_args!("string length overflow")))?;
1585    if let Some(err) = state.sandbox_reserve(total_len) {
1586        return Err(err);
1587    }
1588    let mut buf = Vec::with_capacity(total_len);
1589    left.append_to(&mut buf);
1590    right.append_to(&mut buf);
1591    let ts = state.intern_or_create_str(&buf)?;
1592    state.set_at(top - 2, LuaValue::Str(ts));
1593    state.set_top(top - 1);
1594    Ok(true)
1595}
1596
1597// ─── Object length ───────────────────────────────────────────────────────────
1598
1599/// Main implementation of the `#` operator.
1600pub(crate) fn obj_len(
1601    state: &mut LuaState,
1602    ra: StackIdx,
1603    rb: LuaValue,
1604    rb_idx: StackIdx,
1605) -> Result<(), LuaError> {
1606    match &rb {
1607        LuaValue::Table(_) => {
1608            //    if (tm) break; else setivalue(s2v(ra), luaH_getn(h));
1609            // Lua 5.1 `#t` never consults a table `__len` metamethod (only
1610            // userdata can intercept `#` there); `__len` on tables was added in
1611            // 5.2. Under V51 we therefore always take the primitive length.
1612            let consult_len_tm = !matches!(state.global().lua_version, lua_types::LuaVersion::V51);
1613            let tm = if consult_len_tm {
1614                let mt = state.table_metatable(&rb);
1615                state.fast_tm_table(mt.as_ref(), TagMethod::Len)
1616            } else {
1617                LuaValue::Nil
1618            };
1619            if matches!(tm, LuaValue::Nil) {
1620                let n = state.table_length(&rb)?;
1621                state.set_at(ra, LuaValue::Int(n as i64));
1622                return Ok(());
1623            }
1624            // Fall through to call metamethod
1625            state.call_tm_res(tm, &rb, &rb, ra)?;
1626        }
1627        LuaValue::Str(ts) => {
1628            //    case LUA_VLNGSTR: setivalue(s2v(ra), tsvalue(rb)->u.lnglen);
1629            // Unified in Rust — just get length
1630            let n = ts.len();
1631            state.set_at(ra, LuaValue::Int(n as i64));
1632        }
1633        other => {
1634            //    if (notm(tm)) luaG_typeerror(L, rb, "get length of");
1635            let tm = state.get_tm_by_obj(other, TagMethod::Len);
1636            if matches!(tm, LuaValue::Nil) {
1637                return Err(crate::debug::type_error(
1638                    state,
1639                    other,
1640                    rb_idx,
1641                    b"get length of",
1642                ));
1643            }
1644            state.call_tm_res(tm, &rb, &rb, ra)?;
1645        }
1646    }
1647    Ok(())
1648}
1649
1650// ─── Integer arithmetic ──────────────────────────────────────────────────────
1651
1652/// Integer floor-division.
1653pub(crate) fn idiv(m: i64, n: i64) -> Result<i64, LuaError> {
1654    if (n as u64).wrapping_add(1) <= 1 {
1655        if n == 0 {
1656            return Err(LuaError::runtime(format_args!("attempt to divide by zero")));
1657        }
1658        return Ok(intop_sub(0, m));
1659    }
1660    let q = m / n;
1661    // Correct toward floor (C division truncates toward zero)
1662    if (m ^ n) < 0 && m % n != 0 {
1663        Ok(q - 1)
1664    } else {
1665        Ok(q)
1666    }
1667}
1668
1669/// Integer modulus (Lua semantics: same sign as divisor).
1670pub(crate) fn imod(m: i64, n: i64) -> Result<i64, LuaError> {
1671    if (n as u64).wrapping_add(1) <= 1 {
1672        if n == 0 {
1673            return Err(LuaError::runtime(format_args!("attempt to perform 'n%0'")));
1674        }
1675        return Ok(0);
1676    }
1677    let r = m % n;
1678    if r != 0 && (r ^ n) < 0 {
1679        Ok(r + n)
1680    } else {
1681        Ok(r)
1682    }
1683}
1684
1685/// Float modulus (Lua semantics).
1686pub(crate) fn fmodf(m: f64, n: f64) -> f64 {
1687    let r = m % n;
1688    let opposite_signs = if r > 0.0 { n < 0.0 } else { r < 0.0 && n > 0.0 };
1689    if opposite_signs {
1690        r + n
1691    } else {
1692        r
1693    }
1694}
1695
1696/// Phase-B helper: map a u8 raw value to a `TagMethod`. Mirrors C's
1697/// `cast(TMS, x)` direct cast; out-of-range returns `TagMethod::Index`.
1698pub(crate) fn tagmethod_from_index(i: usize) -> TagMethod {
1699    use TagMethod::*;
1700    match i {
1701        0 => Index,
1702        1 => NewIndex,
1703        2 => Gc,
1704        3 => Mode,
1705        4 => Len,
1706        5 => Eq,
1707        6 => Add,
1708        7 => Sub,
1709        8 => Mul,
1710        9 => Mod,
1711        10 => Pow,
1712        11 => Div,
1713        12 => Idiv,
1714        13 => Band,
1715        14 => Bor,
1716        15 => Bxor,
1717        16 => Shl,
1718        17 => Shr,
1719        18 => Unm,
1720        19 => Bnot,
1721        20 => Lt,
1722        21 => Le,
1723        22 => Concat,
1724        23 => Call,
1725        24 => Close,
1726        _ => Index,
1727    }
1728}
1729
1730/// Integer floor-mod: Lua's `%` operator on integers. Result has the same sign
1731/// as the divisor. Raises on `n == 0`.
1732pub(crate) fn int_floor_mod(_state: &mut LuaState, a: i64, b: i64) -> Result<i64, LuaError> {
1733    imod(a, b)
1734}
1735
1736/// Integer floor-div: Lua's `//` operator on integers. Truncates toward
1737/// negative infinity. Raises on `n == 0`.
1738pub(crate) fn int_floor_div(_state: &mut LuaState, a: i64, b: i64) -> Result<i64, LuaError> {
1739    idiv(a, b)
1740}
1741
1742/// Float floor-mod: Lua's `%` operator on floats. Result has the same sign as
1743/// the divisor.  NaN / division-by-zero behavior mirrors C `fmod`.
1744pub(crate) fn float_floor_mod(_state: &mut LuaState, a: f64, b: f64) -> Result<f64, LuaError> {
1745    Ok(fmodf(a, b))
1746}
1747
1748/// Left shift; right shift is shift-left by negated count.
1749pub(crate) fn shiftl(x: i64, y: i64) -> i64 {
1750    if y < 0 {
1751        if y <= -(NBITS as i64) {
1752            0
1753        } else {
1754            intop_shr(x, (-y) as u32)
1755        }
1756    } else {
1757        if y >= NBITS as i64 {
1758            0
1759        } else {
1760            intop_shl(x, y as u32)
1761        }
1762    }
1763}
1764
1765// ─── Closure creation ────────────────────────────────────────────────────────
1766
1767/// Create a new Lua closure from prototype `p`, initialise its upvalues,
1768/// and push it onto the stack at `ra`.
1769///
1770/// Forwards to the `LuaState` method of the same name, which has access to
1771/// the enclosing closure's upvals and the child proto from the current frame.
1772fn push_closure(
1773    state: &mut LuaState,
1774    proto_idx: usize, // index into current closure's proto.p[]
1775    ci: CallInfoIdx,
1776    base: StackIdx,
1777    ra: StackIdx,
1778) -> Result<(), LuaError> {
1779    state.push_closure(proto_idx, ci, base, ra)
1780}
1781
1782// ─── Yield recovery ──────────────────────────────────────────────────────────
1783
1784/// Resume the opcode that was interrupted by a yield.
1785/// Called when a coroutine is resumed after yielding mid-instruction.
1786pub(crate) fn finish_op(state: &mut LuaState) -> Result<(), LuaError> {
1787    //    StkId base = ci->func.p + 1;
1788    //    Instruction inst = *(ci->u.l.savedpc - 1);
1789    //    OpCode op = GET_OPCODE(inst);
1790    let ci = state.current_ci_idx();
1791    let base = state.ci_base(ci);
1792    let inst = state.ci_prev_instruction(ci);
1793    let op = inst.opcode();
1794
1795    match op {
1796        //    setobjs2s(L, base + GETARG_A(*(ci->u.l.savedpc - 2)), --L->top.p);
1797        OpCode::MmBin | OpCode::MmBinI | OpCode::MmBinK => {
1798            let prev_inst = state.ci_prev2_instruction(ci);
1799            let a = prev_inst.arg_a();
1800            state.dec_top();
1801            let top = state.top_idx();
1802            let v = state.get_at(top);
1803            state.set_at(base + a, v);
1804        }
1805        //    setobjs2s(L, base + GETARG_A(inst), --L->top.p);
1806        OpCode::Unm
1807        | OpCode::BNot
1808        | OpCode::Len
1809        | OpCode::GetTabUp
1810        | OpCode::GetTable
1811        | OpCode::GetI
1812        | OpCode::GetField
1813        | OpCode::Self_ => {
1814            let a = inst.arg_a();
1815            state.dec_top();
1816            let top = state.top_idx();
1817            let v = state.get_at(top);
1818            state.set_at(base + a, v);
1819        }
1820        //    case OP_GTI: case OP_GEI: case OP_EQ:
1821        //    int res = !l_isfalse(s2v(L->top.p - 1)); L->top.p--;
1822        //    if (res != GETARG_k(inst)) ci->u.l.savedpc++;
1823        OpCode::Lt
1824        | OpCode::Le
1825        | OpCode::LtI
1826        | OpCode::LeI
1827        | OpCode::GtI
1828        | OpCode::GeI
1829        | OpCode::Eq => {
1830            let top_minus1 = state.top_idx() - 1;
1831            let v = state.get_at(top_minus1);
1832            let mut res = !matches!(v, LuaValue::Nil | LuaValue::Bool(false));
1833            state.dec_top();
1834            // LUA_COMPAT_LT_LE: if this `__le` was derived from a `__lt` that
1835            // yielded (5.1–5.4), the result `b < a` must be negated back to
1836            // `a <= b`. The mark was set in `tagmethods::call_order_tm`.
1837            // C (lvm.c luaV_finishOp): `if (callstatus & CIST_LEQ) { ^= ; res = !res; }`
1838            if (state.get_ci(ci).callstatus & crate::state::CIST_LEQ) != 0 {
1839                state.get_ci_mut(ci).callstatus &= !crate::state::CIST_LEQ;
1840                res = !res;
1841            }
1842            if (res as i32) != inst.arg_k() {
1843                state.ci_skip_next_instruction(ci);
1844            }
1845        }
1846        //    StkId top = L->top.p - 1;
1847        //    int a = GETARG_A(inst);
1848        //    int total = cast_int(top - 1 - (base + a));
1849        //    setobjs2s(L, top - 2, top);  L->top.p = top - 1;
1850        //    luaV_concat(L, total);
1851        OpCode::Concat => {
1852            let top = state.top_idx() - 1; // top when luaT_tryconcatTM was called
1853            let a = inst.arg_a();
1854            let total_concat = (top - 1 - (base + a)) as i32;
1855            let v = state.get_at(top);
1856            state.set_at(top - 2, v);
1857            state.set_top(top - 1);
1858            concat(state, total_concat)?;
1859        }
1860        OpCode::Close => {
1861            state.ci_step_pc_back(ci);
1862        }
1863        //    StkId ra = base + GETARG_A(inst);
1864        //    L->top.p = ra + ci->u2.nres;
1865        //    ci->u.l.savedpc--;
1866        OpCode::Return => {
1867            let a = inst.arg_a();
1868            let ra = base + a;
1869            let nres = state.ci_nres(ci);
1870            state.set_top(ra + nres);
1871            state.ci_step_pc_back(ci);
1872        }
1873        other => {
1874            debug_assert!(
1875                matches!(
1876                    other,
1877                    OpCode::TForCall
1878                        | OpCode::Call
1879                        | OpCode::TailCall
1880                        | OpCode::SetTabUp
1881                        | OpCode::SetTable
1882                        | OpCode::SetI
1883                        | OpCode::SetField
1884                ),
1885                "unexpected opcode in finish_op: {:?}",
1886                other
1887            );
1888        }
1889    }
1890    Ok(())
1891}
1892
1893// ─── Main interpreter loop ───────────────────────────────────────────────────
1894
1895/// Main Lua bytecode interpreter loop.
1896///
1897/// # Control flow modelling
1898/// The C function uses goto labels: `startfunc`, `returning`, `ret`,
1899/// `l_tforcall`, `l_tforloop`.  These are modelled as follows:
1900/// - `'startfunc: loop { ... }` — outer loop; `continue 'startfunc` = goto startfunc
1901/// - `'returning: loop { ... }` — inner loop; `continue 'returning` = goto returning
1902/// - `break 'dispatch` from the inner dispatch loop → runs `ret:` logic
1903/// - `l_tforcall` / `l_tforloop` — inlined at TFORPREP / TFORCALL handlers
1904pub(crate) fn execute(state: &mut LuaState, mut ci: CallInfoIdx) -> Result<(), LuaError> {
1905    let mut trap: bool;
1906    // The numeric-`for` opcodes use legacy (<=5.3) semantics on 5.1/5.2/5.3:
1907    // FORPREP jumps forward to FORLOOP (so iteration 1 enters the body via a
1908    // backward jump, firing one line-hook event per iteration), and FORLOOP is
1909    // compare-based rather than 5.4's precomputed-count form (issue #92). The
1910    // version is fixed for the VM's lifetime, so resolve it once here; the
1911    // 5.4/5.5 path is unchanged and pays nothing.
1912    let legacy_for = matches!(
1913        state.global().lua_version,
1914        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
1915    );
1916    let tfor_55 = state.global().lua_version == lua_types::LuaVersion::V55;
1917
1918    // Corresponds to C's `startfunc:` label — the entry point that (re)sets `trap`.
1919    'startfunc: loop {
1920        trap = state.hook_mask() != 0;
1921
1922        // Corresponds to C's `returning:` label — the re-entry after a Lua
1923        // call returns, without resetting trap.
1924        'returning: loop {
1925            let ci_slot = ci.as_usize();
1926            let func_idx = state.call_info[ci_slot].func;
1927            let cl = match state.stack[func_idx.0 as usize].val {
1928                LuaValue::Function(lua_types::closure::LuaClosure::Lua(c)) => c,
1929                _ => {
1930                    return Err(LuaError::runtime(format_args!(
1931                        "internal: execute called on non-Lua frame"
1932                    )));
1933                }
1934            };
1935            let code = &cl.proto.code;
1936            let constants = &cl.proto.k;
1937            // pc is an index into proto.code (u32)
1938            let mut pc: u32 = state.call_info[ci_slot].saved_pc();
1939
1940            if trap {
1941                trap = state.trace_call(ci)?;
1942            }
1943            let mut base: StackIdx = state.call_info[ci.as_usize()].func + 1;
1944
1945            // ── Main dispatch loop ──────────────────────────────────────────
1946            'dispatch: loop {
1947                if trap {
1948                    trap = state.trace_exec(ci, pc)?;
1949                    base = state.ci_base(ci); // updatebase
1950                }
1951                let i: Instruction = code[pc as usize];
1952                pc += 1;
1953                let op = i.opcode();
1954                #[cfg(feature = "opcode-profile")]
1955                crate::opcode_profile::record(op);
1956
1957                debug_assert!(base == state.ci_base(ci));
1958
1959                // In normal C-Lua builds, `lua_assert` compiles away; keep the
1960                // stack-top invalidation only for debug parity so release
1961                // dispatch avoids an opcode-mode lookup and a `top` write.
1962                #[cfg(debug_assertions)]
1963                {
1964                    let op_mode = op_mode_byte(op);
1965                    if (op_mode & (1 << 5)) == 0 || i.arg_b() != 0 {
1966                        state.set_top(base);
1967                    }
1968                }
1969
1970                match op {
1971                    // ── OP_MOVE ──────────────────────────────────────────────
1972                    OpCode::Move => {
1973                        let ra = base + i.arg_a();
1974                        let rb = base + i.arg_b();
1975                        let v = state.stack[rb.0 as usize].val;
1976                        state.stack[ra.0 as usize].val = v;
1977                    }
1978                    // ── OP_LOADI ─────────────────────────────────────────────
1979                    OpCode::LoadI => {
1980                        let ra = base + i.arg_a();
1981                        let b = i.arg_s_bx() as i64;
1982                        state.stack[ra.0 as usize].val = LuaValue::Int(b);
1983                    }
1984                    // ── OP_LOADF ─────────────────────────────────────────────
1985                    OpCode::LoadF => {
1986                        let ra = base + i.arg_a();
1987                        let b = i.arg_s_bx() as f64;
1988                        state.stack[ra.0 as usize].val = LuaValue::Float(b);
1989                    }
1990                    // ── OP_LOADK ─────────────────────────────────────────────
1991                    OpCode::LoadK => {
1992                        let ra = base + i.arg_a();
1993                        let k_idx = i.arg_bx() as usize;
1994                        state.stack[ra.0 as usize].val = constants[k_idx];
1995                    }
1996                    // ── OP_LOADKX ────────────────────────────────────────────
1997                    OpCode::LoadKX => {
1998                        let ra = base + i.arg_a();
1999                        let extra = code[pc as usize];
2000                        pc += 1;
2001                        let k_idx = extra.arg_ax() as usize;
2002                        state.stack[ra.0 as usize].val = constants[k_idx];
2003                    }
2004                    // ── OP_LOADFALSE ─────────────────────────────────────────
2005                    OpCode::LoadFalse => {
2006                        let ra = base + i.arg_a();
2007                        state.stack[ra.0 as usize].val = LuaValue::Bool(false);
2008                    }
2009                    // ── OP_LFALSESKIP ────────────────────────────────────────
2010                    OpCode::LFalseSkip => {
2011                        let ra = base + i.arg_a();
2012                        state.stack[ra.0 as usize].val = LuaValue::Bool(false);
2013                        pc += 1;
2014                    }
2015                    // ── OP_LOADTRUE ──────────────────────────────────────────
2016                    OpCode::LoadTrue => {
2017                        let ra = base + i.arg_a();
2018                        state.stack[ra.0 as usize].val = LuaValue::Bool(true);
2019                    }
2020                    // ── OP_LOADNIL ───────────────────────────────────────────
2021                    OpCode::LoadNil => {
2022                        let ra = base + i.arg_a();
2023                        let b = i.arg_b();
2024                        for k in 0..=b {
2025                            state.stack[(ra + k).0 as usize].val = LuaValue::Nil;
2026                        }
2027                    }
2028                    // ── OP_GETUPVAL ──────────────────────────────────────────
2029                    OpCode::GetUpVal => {
2030                        let ra = base + i.arg_a();
2031                        let b = i.arg_b() as usize;
2032                        let uv = cl.upval(b);
2033                        let v = match uv.try_open_payload() {
2034                            Some((thread_id, idx))
2035                                if thread_id == state.cached_thread_id =>
2036                            {
2037                                state.stack[idx.0 as usize].val
2038                            }
2039                            Some(_) => state.upvalue_get(&cl, b),
2040                            None => uv.closed_value(),
2041                        };
2042                        state.stack[ra.0 as usize].val = v;
2043                    }
2044                    // ── OP_SETUPVAL ──────────────────────────────────────────
2045                    //    setobj(L, uv->v.p, s2v(ra)); luaC_barrier(L, uv, s2v(ra));
2046                    OpCode::SetUpVal => {
2047                        let ra = base + i.arg_a();
2048                        let b = i.arg_b() as usize;
2049                        let v = state.stack[ra.0 as usize].val;
2050                        let uv = cl.upval(b);
2051                        match uv.try_open_payload() {
2052                            Some((thread_id, idx))
2053                                if thread_id == state.cached_thread_id =>
2054                            {
2055                                state.stack[idx.0 as usize].val = v;
2056                                if v.is_collectable() {
2057                                    state.gc_barrier_upval(&uv, &v);
2058                                }
2059                            }
2060                            None => {
2061                                uv.set_closed_value(v);
2062                                if v.is_collectable() {
2063                                    state.gc_barrier_upval(&uv, &v);
2064                                }
2065                            }
2066                            _ => {
2067                                state.upvalue_set(&cl, b, v)?;
2068                            }
2069                        }
2070                    }
2071                    // ── OP_GETTABUP ──────────────────────────────────────────
2072                    //    if (luaV_fastget(..., luaH_getshortstr)) setobj2s(L, ra, slot)
2073                    //    else Protect(luaV_finishget(...))
2074                    OpCode::GetTabUp => {
2075                        let ra = base + i.arg_a();
2076                        let b = i.arg_b() as usize;
2077                        let k_idx = i.arg_c() as usize;
2078                        let upval = state.upvalue_get(&cl, b);
2079                        let key = constants[k_idx];
2080                        match state.fast_get_short_str(&upval, &key)? {
2081                            Some(v) => state.set_at(ra, v),
2082                            None => {
2083                                state.set_ci_savedpc(ci, pc);
2084                                state.set_top(state.ci_top(ci));
2085                                let upval_name: Vec<u8> =
2086                                    cl.0.proto
2087                                        .upvalues
2088                                        .get(b)
2089                                        .and_then(|uv| uv.name.as_ref())
2090                                        .map(|s| s.as_bytes().to_vec())
2091                                        .unwrap_or_else(|| b"?".to_vec());
2092                                let hint: Option<(&[u8], &[u8])> = Some((b"upvalue", &upval_name));
2093                                finish_get(state, upval, key, ra, true, None, hint)?;
2094                                trap = state.ci_trap(ci);
2095                            }
2096                        }
2097                    }
2098                    // ── OP_GETTABLE ──────────────────────────────────────────
2099                    //    if (integer key) fastgeti else fastget
2100                    OpCode::GetTable => {
2101                        let ra = base + i.arg_a();
2102                        let rb_idx = base + i.arg_b();
2103                        let rb_v = state.get_at(rb_idx);
2104                        let rc_v = state.get_at(base + i.arg_c());
2105                        let fast_result = if let LuaValue::Int(n) = &rc_v {
2106                            state.fast_get_int(&rb_v, *n)?
2107                        } else {
2108                            state.fast_get(&rb_v, &rc_v)?
2109                        };
2110                        match fast_result {
2111                            Some(v) => state.set_at(ra, v),
2112                            None => {
2113                                state.set_ci_savedpc(ci, pc);
2114                                state.set_top(state.ci_top(ci));
2115                                finish_get(state, rb_v, rc_v, ra, true, Some(rb_idx), None)?;
2116                                trap = state.ci_trap(ci);
2117                            }
2118                        }
2119                    }
2120                    // ── OP_GETI ──────────────────────────────────────────────
2121                    //    if (luaV_fastgeti(L, rb, c, slot)) setobj2s(L, ra, slot)
2122                    //    else { TValue key; setivalue(&key, c); Protect(finishget) }
2123                    OpCode::GetI => {
2124                        let ra = base + i.arg_a();
2125                        let rb_idx = base + i.arg_b();
2126                        let rb_v = state.get_at(rb_idx);
2127                        let c = i.arg_c() as i64;
2128                        match state.fast_get_int(&rb_v, c)? {
2129                            Some(v) => state.set_at(ra, v),
2130                            None => {
2131                                let key = LuaValue::Int(c);
2132                                state.set_ci_savedpc(ci, pc);
2133                                state.set_top(state.ci_top(ci));
2134                                finish_get(state, rb_v, key, ra, true, Some(rb_idx), None)?;
2135                                trap = state.ci_trap(ci);
2136                            }
2137                        }
2138                    }
2139                    // ── OP_GETFIELD ──────────────────────────────────────────
2140                    OpCode::GetField => {
2141                        let ra = base + i.arg_a();
2142                        let rb_idx = base + i.arg_b();
2143                        let rb_v = state.get_at(rb_idx);
2144                        let k_idx = i.arg_c() as usize;
2145                        let key = constants[k_idx];
2146                        match state.fast_get_short_str(&rb_v, &key)? {
2147                            Some(v) => state.set_at(ra, v),
2148                            None => {
2149                                state.set_ci_savedpc(ci, pc);
2150                                state.set_top(state.ci_top(ci));
2151                                finish_get(state, rb_v, key, ra, true, Some(rb_idx), None)?;
2152                                trap = state.ci_trap(ci);
2153                            }
2154                        }
2155                    }
2156                    // ── OP_SETTABUP ──────────────────────────────────────────
2157                    OpCode::SetTabUp => {
2158                        let a = i.arg_a() as usize;
2159                        let b_idx = i.arg_b() as usize; // key is KB(i)
2160                        let rc_v = if i.test_k() {
2161                            constants[i.arg_c() as usize]
2162                        } else {
2163                            state.get_at(base + i.arg_c())
2164                        };
2165                        let upval = state.upvalue_get(&cl, a);
2166                        let key = constants[b_idx];
2167                        if let LuaValue::Table(tbl) = upval {
2168                            if !tbl.has_metatable() {
2169                                if rc_v.is_collectable() {
2170                                    state.gc_table_barrier_back(&tbl, &rc_v);
2171                                }
2172                                if let LuaValue::Str(s) = key {
2173                                    tbl.raw_set_short_str(state, s, rc_v)?;
2174                                } else {
2175                                    tbl.raw_set(state, key, rc_v)?;
2176                                }
2177                                continue 'dispatch;
2178                            }
2179                        }
2180                        match state.fast_get_short_str(&upval, &key)? {
2181                            Some(_slot) => {
2182                                state.gc_value_barrier_back(&upval, &rc_v);
2183                                if let LuaValue::Table(tbl) = upval {
2184                                    if let LuaValue::Str(s) = key {
2185                                        tbl.raw_set_short_str(state, s, rc_v)?;
2186                                    } else {
2187                                        tbl.raw_set(state, key, rc_v)?;
2188                                    }
2189                                } else {
2190                                    state.table_raw_set(&upval, key, rc_v)?;
2191                                }
2192                            }
2193                            None => {
2194                                state.set_ci_savedpc(ci, pc);
2195                                state.set_top(state.ci_top(ci));
2196                                let upval_name: Vec<u8> = cl
2197                                    .proto
2198                                    .upvalues
2199                                    .get(a)
2200                                    .and_then(|uv| uv.name.as_ref())
2201                                    .map(|s| s.as_bytes().to_vec())
2202                                    .unwrap_or_else(|| b"?".to_vec());
2203                                let hint: Option<(&[u8], &[u8])> = Some((b"upvalue", &upval_name));
2204                                finish_set(state, upval, key, rc_v, false, None, hint)?;
2205                                trap = state.ci_trap(ci);
2206                            }
2207                        }
2208                    }
2209                    // ── OP_SETTABLE ───────────────────────────────────────────
2210                    OpCode::SetTable => {
2211                        let ra_idx = base + i.arg_a();
2212                        let ra_v = state.get_at(ra_idx);
2213                        let rb_v = state.get_at(base + i.arg_b());
2214                        let rc_v = if i.test_k() {
2215                            constants[i.arg_c() as usize]
2216                        } else {
2217                            state.get_at(base + i.arg_c())
2218                        };
2219                        if let LuaValue::Table(tbl) = ra_v {
2220                            if !tbl.has_metatable() {
2221                                if rc_v.is_collectable() {
2222                                    state.gc_table_barrier_back(&tbl, &rc_v);
2223                                }
2224                                match rb_v {
2225                                    LuaValue::Int(n) => tbl.raw_set_int(state, n, rc_v)?,
2226                                    LuaValue::Str(s) if s.is_short() => {
2227                                        tbl.raw_set_short_str(state, s, rc_v)?
2228                                    }
2229                                    _ => tbl.raw_set(state, rb_v, rc_v)?,
2230                                }
2231                            } else {
2232                                let fast = if let LuaValue::Int(n) = &rb_v {
2233                                    state.fast_get_int(&ra_v, *n)?
2234                                } else {
2235                                    state.fast_get(&ra_v, &rb_v)?
2236                                };
2237                                if fast.is_some() {
2238                                    state.gc_value_barrier_back(&ra_v, &rc_v);
2239                                    match rb_v {
2240                                        LuaValue::Int(n) => tbl.raw_set_int(state, n, rc_v)?,
2241                                        LuaValue::Str(s) if s.is_short() => {
2242                                            tbl.raw_set_short_str(state, s, rc_v)?
2243                                        }
2244                                        _ => tbl.raw_set(state, rb_v, rc_v)?,
2245                                    }
2246                                } else {
2247                                    state.set_ci_savedpc(ci, pc);
2248                                    state.set_top(state.ci_top(ci));
2249                                    finish_set(state, ra_v, rb_v, rc_v, false, Some(ra_idx), None)?;
2250                                    trap = state.ci_trap(ci);
2251                                }
2252                            }
2253                        } else {
2254                            state.set_ci_savedpc(ci, pc);
2255                            state.set_top(state.ci_top(ci));
2256                            finish_set(state, ra_v, rb_v, rc_v, false, Some(ra_idx), None)?;
2257                            trap = state.ci_trap(ci);
2258                        }
2259                    }
2260                    // ── OP_SETI ───────────────────────────────────────────────
2261                    OpCode::SetI => {
2262                        let ra_idx = base + i.arg_a();
2263                        let ra_v = state.get_at(ra_idx);
2264                        let c = i.arg_b() as i64;
2265                        let rc_v = if i.test_k() {
2266                            constants[i.arg_c() as usize]
2267                        } else {
2268                            state.get_at(base + i.arg_c())
2269                        };
2270                        if let LuaValue::Table(tbl) = ra_v {
2271                            if !tbl.has_metatable() {
2272                                if rc_v.is_collectable() {
2273                                    state.gc_table_barrier_back(&tbl, &rc_v);
2274                                }
2275                                tbl.raw_set_int(state, c, rc_v)?;
2276                            } else {
2277                                let fast = state.fast_get_int(&ra_v, c)?;
2278                                if fast.is_some() {
2279                                    state.gc_value_barrier_back(&ra_v, &rc_v);
2280                                    tbl.raw_set_int(state, c, rc_v)?;
2281                                } else {
2282                                    state.set_ci_savedpc(ci, pc);
2283                                    state.set_top(state.ci_top(ci));
2284                                    finish_set(
2285                                        state,
2286                                        ra_v,
2287                                        LuaValue::Int(c),
2288                                        rc_v,
2289                                        false,
2290                                        Some(ra_idx),
2291                                        None,
2292                                    )?;
2293                                    trap = state.ci_trap(ci);
2294                                }
2295                            }
2296                        } else {
2297                            state.set_ci_savedpc(ci, pc);
2298                            state.set_top(state.ci_top(ci));
2299                            finish_set(
2300                                state,
2301                                ra_v,
2302                                LuaValue::Int(c),
2303                                rc_v,
2304                                false,
2305                                Some(ra_idx),
2306                                None,
2307                            )?;
2308                            trap = state.ci_trap(ci);
2309                        }
2310                    }
2311                    // ── OP_SETFIELD ───────────────────────────────────────────
2312                    OpCode::SetField => {
2313                        let ra_idx = base + i.arg_a();
2314                        let ra_v = state.get_at(ra_idx);
2315                        let b_idx = i.arg_b() as usize;
2316                        let key = constants[b_idx];
2317                        let rc_v = if i.test_k() {
2318                            constants[i.arg_c() as usize]
2319                        } else {
2320                            state.get_at(base + i.arg_c())
2321                        };
2322                        if let LuaValue::Table(tbl) = ra_v {
2323                            if !tbl.has_metatable() {
2324                                if rc_v.is_collectable() {
2325                                    state.gc_table_barrier_back(&tbl, &rc_v);
2326                                }
2327                                if let LuaValue::Str(s) = key {
2328                                    tbl.raw_set_short_str(state, s, rc_v)?;
2329                                } else {
2330                                    tbl.raw_set(state, key, rc_v)?;
2331                                }
2332                            } else {
2333                                match state.fast_get_short_str(&ra_v, &key)? {
2334                                    Some(_) => {
2335                                        state.gc_value_barrier_back(&ra_v, &rc_v);
2336                                        if let LuaValue::Str(s) = key {
2337                                            tbl.raw_set_short_str(state, s, rc_v)?;
2338                                        } else {
2339                                            tbl.raw_set(state, key, rc_v)?;
2340                                        }
2341                                    }
2342                                    None => {
2343                                        state.set_ci_savedpc(ci, pc);
2344                                        state.set_top(state.ci_top(ci));
2345                                        finish_set(
2346                                            state,
2347                                            ra_v,
2348                                            key,
2349                                            rc_v,
2350                                            false,
2351                                            Some(ra_idx),
2352                                            None,
2353                                        )?;
2354                                        trap = state.ci_trap(ci);
2355                                    }
2356                                }
2357                            }
2358                        } else {
2359                            state.set_ci_savedpc(ci, pc);
2360                            state.set_top(state.ci_top(ci));
2361                            finish_set(state, ra_v, key, rc_v, false, Some(ra_idx), None)?;
2362                            trap = state.ci_trap(ci);
2363                        }
2364                    }
2365                    // ── OP_NEWTABLE ───────────────────────────────────────────
2366                    //    if (TESTARG_k(i)) c += GETARG_Ax(*pc) * (MAXARG_C + 1); pc++;
2367                    OpCode::NewTable => {
2368                        let ra = base + i.arg_a();
2369                        let mut b = i.arg_b();
2370                        let mut c = i.arg_c();
2371                        if b > 0 {
2372                            b = 1 << (b - 1);
2373                        }
2374                        if i.test_k() {
2375                            let extra = code[pc as usize];
2376                            pc += 1;
2377                            const MAXARG_C: i32 = (1 << 8) - 1;
2378                            c += extra.arg_ax() * (MAXARG_C + 1);
2379                        } else {
2380                            pc += 1; // skip extra argument even if zero
2381                        }
2382                        state.set_top(ra + 1);
2383                        let t = if b != 0 || c != 0 {
2384                            state.new_table_with_sizes(c as u32, b as u32)?
2385                        } else {
2386                            state.new_table()
2387                        };
2388                        state.set_at(ra, LuaValue::Table(t.clone()));
2389                        state.set_ci_savedpc(ci, pc);
2390                        state.set_top(ra + 1);
2391                        state.gc_cond_step();
2392                        if state.hookmask != 0 {
2393                            trap = state.ci_trap(ci);
2394                        }
2395                    }
2396                    // ── OP_SELF ───────────────────────────────────────────────
2397                    OpCode::Self_ => {
2398                        let ra = base + i.arg_a();
2399                        let rb_idx = base + i.arg_b();
2400                        let rb_v = state.get_at(rb_idx);
2401                        let k_idx = i.arg_c() as usize; // RKC key (always a string)
2402                        let key = if i.test_k() {
2403                            constants[k_idx]
2404                        } else {
2405                            state.get_at(base + i.arg_c())
2406                        };
2407                        state.set_at(ra + 1, rb_v.clone());
2408                        match state.fast_get_short_str(&rb_v, &key)? {
2409                            Some(v) => state.set_at(ra, v),
2410                            None => {
2411                                state.set_ci_savedpc(ci, pc);
2412                                state.set_top(state.ci_top(ci));
2413                                finish_get(state, rb_v, key, ra, true, Some(rb_idx), None)?;
2414                                trap = state.ci_trap(ci);
2415                            }
2416                        }
2417                    }
2418                    // ── Arithmetic immediates ──────────────────────────────────
2419                    OpCode::AddI => {
2420                        let ra = base + i.arg_a();
2421                        let rb = base + i.arg_b();
2422                        let imm = i.arg_s_c() as i64;
2423                        let rb_v = state.stack[rb.0 as usize].val;
2424                        match rb_v {
2425                            LuaValue::Int(iv1) => {
2426                                pc += 1;
2427                                state.stack[ra.0 as usize].val = LuaValue::Int(intop_add(iv1, imm));
2428                            }
2429                            LuaValue::Float(nb) => {
2430                                pc += 1;
2431                                state.stack[ra.0 as usize].val = LuaValue::Float(nb + imm as f64);
2432                            }
2433                            _ => {}
2434                        }
2435                    }
2436                    // ── Arithmetic with K constant operand ─────────────────────
2437                    OpCode::AddK => {
2438                        let ra = base + i.arg_a();
2439                        let rb = base + i.arg_b();
2440                        let kidx = i.arg_c() as usize;
2441                        if let (Some(i1), Some(i2)) =
2442                            (state.get_int_at(rb), state.proto_const_int(&cl, kidx))
2443                        {
2444                            pc += 1;
2445                            state.set_at(ra, LuaValue::Int(intop_add(i1, i2)));
2446                        } else if let (Some(n1), Some(n2)) =
2447                            (state.get_num_at(rb), state.proto_const_num(&cl, kidx))
2448                        {
2449                            pc += 1;
2450                            state.set_at(ra, LuaValue::Float(n1 + n2));
2451                        }
2452                    }
2453                    OpCode::SubK => {
2454                        let ra = base + i.arg_a();
2455                        let rb = base + i.arg_b();
2456                        let kidx = i.arg_c() as usize;
2457                        if let (Some(i1), Some(i2)) =
2458                            (state.get_int_at(rb), state.proto_const_int(&cl, kidx))
2459                        {
2460                            pc += 1;
2461                            state.set_at(ra, LuaValue::Int(intop_sub(i1, i2)));
2462                        } else if let (Some(n1), Some(n2)) =
2463                            (state.get_num_at(rb), state.proto_const_num(&cl, kidx))
2464                        {
2465                            pc += 1;
2466                            state.set_at(ra, LuaValue::Float(n1 - n2));
2467                        }
2468                    }
2469                    OpCode::MulK => {
2470                        let ra = base + i.arg_a();
2471                        let rb = base + i.arg_b();
2472                        let kidx = i.arg_c() as usize;
2473                        if let (Some(i1), Some(i2)) =
2474                            (state.get_int_at(rb), state.proto_const_int(&cl, kidx))
2475                        {
2476                            pc += 1;
2477                            state.set_at(ra, LuaValue::Int(intop_mul(i1, i2)));
2478                        } else if let (Some(n1), Some(n2)) =
2479                            (state.get_num_at(rb), state.proto_const_num(&cl, kidx))
2480                        {
2481                            pc += 1;
2482                            state.set_at(ra, LuaValue::Float(n1 * n2));
2483                        }
2484                    }
2485                    OpCode::ModK => {
2486                        let ra = base + i.arg_a();
2487                        let v1 = state.get_at(base + i.arg_b());
2488                        let v2 = constants[i.arg_c() as usize];
2489                        state.set_ci_savedpc(ci, pc); // savestate for div-by-zero
2490                        state.set_top(state.ci_top(ci));
2491                        arith_op_checked(state, ra, &v1, &v2, &mut pc, |a, b| imod(a, b), fmodf)?;
2492                    }
2493                    OpCode::PowK => {
2494                        let ra = base + i.arg_a();
2495                        let rb = base + i.arg_b();
2496                        let kidx = i.arg_c() as usize;
2497                        if let (Some(n1), Some(n2)) =
2498                            (state.get_num_at(rb), state.proto_const_num(&cl, kidx))
2499                        {
2500                            pc += 1;
2501                            let r = if n2 == 2.0 { n1 * n1 } else { n1.powf(n2) };
2502                            state.set_at(ra, LuaValue::Float(r));
2503                        }
2504                    }
2505                    OpCode::DivK => {
2506                        let ra = base + i.arg_a();
2507                        let rb = base + i.arg_b();
2508                        let kidx = i.arg_c() as usize;
2509                        if let (Some(n1), Some(n2)) =
2510                            (state.get_num_at(rb), state.proto_const_num(&cl, kidx))
2511                        {
2512                            pc += 1;
2513                            state.set_at(ra, LuaValue::Float(n1 / n2));
2514                        }
2515                    }
2516                    OpCode::IDivK => {
2517                        let ra = base + i.arg_a();
2518                        let v1 = state.get_at(base + i.arg_b());
2519                        let v2 = constants[i.arg_c() as usize];
2520                        state.set_ci_savedpc(ci, pc);
2521                        state.set_top(state.ci_top(ci));
2522                        arith_op_checked(
2523                            state,
2524                            ra,
2525                            &v1,
2526                            &v2,
2527                            &mut pc,
2528                            |a, b| idiv(a, b),
2529                            |a, b| (a / b).floor(),
2530                        )?;
2531                    }
2532                    OpCode::BAndK => {
2533                        let ra = base + i.arg_a();
2534                        let v1 = state.get_at(base + i.arg_b());
2535                        let v2 = constants[i.arg_c() as usize];
2536                        bitwise_op_k(state, ra, &v1, &v2, &mut pc, intop_band);
2537                    }
2538                    OpCode::BOrK => {
2539                        let ra = base + i.arg_a();
2540                        let v1 = state.get_at(base + i.arg_b());
2541                        let v2 = constants[i.arg_c() as usize];
2542                        bitwise_op_k(state, ra, &v1, &v2, &mut pc, intop_bor);
2543                    }
2544                    OpCode::BXOrK => {
2545                        let ra = base + i.arg_a();
2546                        let v1 = state.get_at(base + i.arg_b());
2547                        let v2 = constants[i.arg_c() as usize];
2548                        bitwise_op_k(state, ra, &v1, &v2, &mut pc, intop_bxor);
2549                    }
2550                    OpCode::ShrI => {
2551                        let ra = base + i.arg_a();
2552                        let v = state.get_at(base + i.arg_b());
2553                        let ic = i.arg_s_c() as i64;
2554                        if let Some(ib) = to_integer_ns(&v, F2Imod::Eq) {
2555                            pc += 1;
2556                            state.set_at(ra, LuaValue::Int(shiftl(ib, -ic)));
2557                        }
2558                    }
2559                    OpCode::ShlI => {
2560                        let ra = base + i.arg_a();
2561                        let v = state.get_at(base + i.arg_b());
2562                        let ic = i.arg_s_c() as i64;
2563                        if let Some(ib) = to_integer_ns(&v, F2Imod::Eq) {
2564                            pc += 1;
2565                            state.set_at(ra, LuaValue::Int(shiftl(ic, ib)));
2566                        }
2567                    }
2568                    // ── Arithmetic with register operands ──────────────────────
2569                    OpCode::Add => {
2570                        let ra = base + i.arg_a();
2571                        let rb = base + i.arg_b();
2572                        let rc = base + i.arg_c();
2573                        let ra_u = ra.0 as usize;
2574                        let rb_v = state.stack[rb.0 as usize].val;
2575                        let rc_v = state.stack[rc.0 as usize].val;
2576                        if let (LuaValue::Int(i1), LuaValue::Int(i2)) = (rb_v, rc_v) {
2577                            pc += 1;
2578                            state.stack[ra_u].val = LuaValue::Int(intop_add(i1, i2));
2579                        } else if let (Some(n1), Some(n2)) =
2580                            (number_value(rb_v), number_value(rc_v))
2581                        {
2582                            pc += 1;
2583                            state.stack[ra_u].val = LuaValue::Float(n1 + n2);
2584                        }
2585                    }
2586                    OpCode::Sub => {
2587                        let ra = base + i.arg_a();
2588                        let rb = base + i.arg_b();
2589                        let rc = base + i.arg_c();
2590                        let ra_u = ra.0 as usize;
2591                        let rb_v = state.stack[rb.0 as usize].val;
2592                        let rc_v = state.stack[rc.0 as usize].val;
2593                        if let (LuaValue::Int(i1), LuaValue::Int(i2)) = (rb_v, rc_v) {
2594                            pc += 1;
2595                            state.stack[ra_u].val = LuaValue::Int(intop_sub(i1, i2));
2596                        } else if let (Some(n1), Some(n2)) =
2597                            (number_value(rb_v), number_value(rc_v))
2598                        {
2599                            pc += 1;
2600                            state.stack[ra_u].val = LuaValue::Float(n1 - n2);
2601                        }
2602                    }
2603                    OpCode::Mul => {
2604                        let ra = base + i.arg_a();
2605                        let rb = base + i.arg_b();
2606                        let rc = base + i.arg_c();
2607                        if let Some((i1, i2)) = state.get_int_pair_at(rb, rc) {
2608                            pc += 1;
2609                            state.set_at(ra, LuaValue::Int(intop_mul(i1, i2)));
2610                        } else if let Some((n1, n2)) = state.get_num_pair_at(rb, rc) {
2611                            pc += 1;
2612                            state.set_at(ra, LuaValue::Float(n1 * n2));
2613                        }
2614                    }
2615                    OpCode::Mod => {
2616                        let ra = base + i.arg_a();
2617                        let v1 = state.get_at(base + i.arg_b());
2618                        let v2 = state.get_at(base + i.arg_c());
2619                        state.set_ci_savedpc(ci, pc);
2620                        state.set_top(state.ci_top(ci));
2621                        arith_op_checked(state, ra, &v1, &v2, &mut pc, |a, b| imod(a, b), fmodf)?;
2622                    }
2623                    OpCode::Pow => {
2624                        let ra = base + i.arg_a();
2625                        let rb = base + i.arg_b();
2626                        let rc = base + i.arg_c();
2627                        if let Some((n1, n2)) = state.get_num_pair_at(rb, rc) {
2628                            pc += 1;
2629                            let r = if n2 == 2.0 { n1 * n1 } else { n1.powf(n2) };
2630                            state.set_at(ra, LuaValue::Float(r));
2631                        }
2632                    }
2633                    OpCode::Div => {
2634                        let ra = base + i.arg_a();
2635                        let rb = base + i.arg_b();
2636                        let rc = base + i.arg_c();
2637                        if let Some((n1, n2)) = state.get_num_pair_at(rb, rc) {
2638                            pc += 1;
2639                            state.set_at(ra, LuaValue::Float(n1 / n2));
2640                        }
2641                    }
2642                    OpCode::IDiv => {
2643                        let ra = base + i.arg_a();
2644                        let v1 = state.get_at(base + i.arg_b());
2645                        let v2 = state.get_at(base + i.arg_c());
2646                        state.set_ci_savedpc(ci, pc);
2647                        state.set_top(state.ci_top(ci));
2648                        arith_op_checked(
2649                            state,
2650                            ra,
2651                            &v1,
2652                            &v2,
2653                            &mut pc,
2654                            |a, b| idiv(a, b),
2655                            |a, b| (a / b).floor(),
2656                        )?;
2657                    }
2658                    // ── Bitwise with register operands ─────────────────────────
2659                    // if (tointegerns(v1, &i1) && tointegerns(v2, &i2)) { pc++; setivalue... }
2660                    OpCode::BAnd => {
2661                        let ra = base + i.arg_a();
2662                        let v1 = state.get_at(base + i.arg_b());
2663                        let v2 = state.get_at(base + i.arg_c());
2664                        bitwise_op_rr(state, ra, &v1, &v2, &mut pc, intop_band);
2665                    }
2666                    OpCode::BOr => {
2667                        let ra = base + i.arg_a();
2668                        let v1 = state.get_at(base + i.arg_b());
2669                        let v2 = state.get_at(base + i.arg_c());
2670                        bitwise_op_rr(state, ra, &v1, &v2, &mut pc, intop_bor);
2671                    }
2672                    OpCode::BXOr => {
2673                        let ra = base + i.arg_a();
2674                        let v1 = state.get_at(base + i.arg_b());
2675                        let v2 = state.get_at(base + i.arg_c());
2676                        bitwise_op_rr(state, ra, &v1, &v2, &mut pc, intop_bxor);
2677                    }
2678                    OpCode::Shr => {
2679                        let ra = base + i.arg_a();
2680                        let v1 = state.get_at(base + i.arg_b());
2681                        let v2 = state.get_at(base + i.arg_c());
2682                        bitwise_shift_rr(state, ra, &v1, &v2, &mut pc, true);
2683                    }
2684                    OpCode::Shl => {
2685                        let ra = base + i.arg_a();
2686                        let v1 = state.get_at(base + i.arg_b());
2687                        let v2 = state.get_at(base + i.arg_c());
2688                        bitwise_shift_rr(state, ra, &v1, &v2, &mut pc, false);
2689                    }
2690                    // ── OP_MMBIN ─────────────────────────────────────────────
2691                    // Instruction pi = *(pc - 2); TMS tm = (TMS)GETARG_C(i);
2692                    // StkId result = RA(pi);
2693                    // Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm));
2694                    OpCode::MmBin => {
2695                        let ra_idx = base + i.arg_a();
2696                        let rb_idx = base + i.arg_b();
2697                        let ra_v = state.get_at(ra_idx);
2698                        let rb_v = state.get_at(rb_idx);
2699                        let tm = tagmethod_from_index(i.arg_c() as usize);
2700                        let prev_inst = code[(pc - 2) as usize];
2701                        let result_idx = base + prev_inst.arg_a();
2702                        state.set_ci_savedpc(ci, pc);
2703                        state.set_top(state.ci_top(ci));
2704                        state.try_bin_tm(
2705                            &ra_v,
2706                            Some(ra_idx),
2707                            &rb_v,
2708                            Some(rb_idx),
2709                            result_idx,
2710                            tm,
2711                        )?;
2712                        trap = state.ci_trap(ci);
2713                    }
2714                    OpCode::MmBinI => {
2715                        let ra_idx = base + i.arg_a();
2716                        let ra_v = state.get_at(ra_idx);
2717                        let imm = i.arg_s_b() as i64;
2718                        let tm = tagmethod_from_index(i.arg_c() as usize);
2719                        let flip = i.arg_k() != 0;
2720                        let prev_inst = code[(pc - 2) as usize];
2721                        let result_idx = base + prev_inst.arg_a();
2722                        state.set_ci_savedpc(ci, pc);
2723                        state.set_top(state.ci_top(ci));
2724                        state.try_bin_i_tm(&ra_v, Some(ra_idx), imm, flip, result_idx, tm)?;
2725                        trap = state.ci_trap(ci);
2726                    }
2727                    OpCode::MmBinK => {
2728                        let ra_idx = base + i.arg_a();
2729                        let ra_v = state.get_at(ra_idx);
2730                        let imm = constants[i.arg_b() as usize];
2731                        let tm = tagmethod_from_index(i.arg_c() as usize);
2732                        let flip = i.arg_k() != 0;
2733                        let prev_inst = code[(pc - 2) as usize];
2734                        let result_idx = base + prev_inst.arg_a();
2735                        state.set_ci_savedpc(ci, pc);
2736                        state.set_top(state.ci_top(ci));
2737                        state.try_bin_assoc_tm(
2738                            &ra_v,
2739                            Some(ra_idx),
2740                            &imm,
2741                            None,
2742                            flip,
2743                            result_idx,
2744                            tm,
2745                        )?;
2746                        trap = state.ci_trap(ci);
2747                    }
2748                    // ── OP_UNM ───────────────────────────────────────────────
2749                    //    else if (tonumberns(rb, nb)) setfltvalue(s2v(ra), -nb)
2750                    //    else Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM))
2751                    OpCode::Unm => {
2752                        let ra = base + i.arg_a();
2753                        let rb_idx = base + i.arg_b();
2754                        let rb_v = state.get_at(rb_idx);
2755                        match &rb_v {
2756                            LuaValue::Int(ib) => {
2757                                state.set_at(ra, LuaValue::Int(intop_sub(0, *ib)));
2758                            }
2759                            LuaValue::Float(nb) => {
2760                                state.set_at(ra, LuaValue::Float(-nb));
2761                            }
2762                            _ => {
2763                                state.set_ci_savedpc(ci, pc);
2764                                state.set_top(state.ci_top(ci));
2765                                state.try_bin_tm(
2766                                    &rb_v,
2767                                    Some(rb_idx),
2768                                    &rb_v,
2769                                    Some(rb_idx),
2770                                    ra,
2771                                    TagMethod::Unm,
2772                                )?;
2773                                trap = state.ci_trap(ci);
2774                            }
2775                        }
2776                    }
2777                    // ── OP_BNOT ──────────────────────────────────────────────
2778                    OpCode::BNot => {
2779                        let ra = base + i.arg_a();
2780                        let rb_idx = base + i.arg_b();
2781                        let rb_v = state.get_at(rb_idx);
2782                        if let Some(ib) = to_integer_ns(&rb_v, F2Imod::Eq) {
2783                            state.set_at(ra, LuaValue::Int(!ib));
2784                        } else {
2785                            state.set_ci_savedpc(ci, pc);
2786                            state.set_top(state.ci_top(ci));
2787                            state.try_bin_tm(
2788                                &rb_v,
2789                                Some(rb_idx),
2790                                &rb_v,
2791                                Some(rb_idx),
2792                                ra,
2793                                TagMethod::Bnot,
2794                            )?;
2795                            trap = state.ci_trap(ci);
2796                        }
2797                    }
2798                    // ── OP_NOT ───────────────────────────────────────────────
2799                    OpCode::Not => {
2800                        let ra = base + i.arg_a();
2801                        let rb_v = state.get_at(base + i.arg_b());
2802                        let falsy = matches!(rb_v, LuaValue::Nil | LuaValue::Bool(false));
2803                        state.set_at(ra, LuaValue::Bool(falsy));
2804                    }
2805                    // ── OP_LEN ───────────────────────────────────────────────
2806                    OpCode::Len => {
2807                        let ra = base + i.arg_a();
2808                        let rb_idx = base + i.arg_b();
2809                        let rb_v = state.get_at(rb_idx);
2810                        state.set_ci_savedpc(ci, pc);
2811                        state.set_top(state.ci_top(ci));
2812                        obj_len(state, ra, rb_v, rb_idx)?;
2813                        trap = state.ci_trap(ci);
2814                    }
2815                    // ── OP_CONCAT ─────────────────────────────────────────────
2816                    OpCode::Concat => {
2817                        let ra = base + i.arg_a();
2818                        let n = i.arg_b() as i32;
2819                        state.set_top(ra + n as i32);
2820                        state.set_ci_savedpc(ci, pc); // ProtectNT: save pc only
2821                        concat(state, n)?;
2822                        let top = state.top_idx();
2823                        state.set_ci_savedpc(ci, pc);
2824                        state.set_top(top);
2825                        state.gc_cond_step();
2826                        trap = state.ci_trap(ci);
2827                    }
2828                    // ── OP_CLOSE ──────────────────────────────────────────────
2829                    OpCode::Close => {
2830                        let ra = base + i.arg_a();
2831                        state.set_ci_savedpc(ci, pc);
2832                        state.set_top(state.ci_top(ci));
2833                        crate::func::close(
2834                            state,
2835                            ra,
2836                            lua_types::status::LuaStatus::Ok as i32,
2837                            true,
2838                        )?;
2839                        trap = state.ci_trap(ci);
2840                    }
2841                    // ── OP_TBC ────────────────────────────────────────────────
2842                    OpCode::Tbc => {
2843                        let ra = base + i.arg_a();
2844                        state.set_ci_savedpc(ci, pc);
2845                        state.set_top(state.ci_top(ci));
2846                        state.new_tbc_upval(ra)?;
2847                    }
2848                    // ── OP_JMP ────────────────────────────────────────────────
2849                    OpCode::Jmp => {
2850                        pc = (pc as i64 + i.arg_s_j() as i64) as u32;
2851                        trap = state.ci_trap(ci);
2852                    }
2853                    // ── OP_EQ ─────────────────────────────────────────────────
2854                    OpCode::Eq => {
2855                        let ra_v = state.get_at(base + i.arg_a());
2856                        let rb_v = state.get_at(base + i.arg_b());
2857                        state.set_ci_savedpc(ci, pc);
2858                        state.set_top(state.ci_top(ci));
2859                        let cond = equal_obj(Some(state), &ra_v, &rb_v)? as u32;
2860                        trap = state.ci_trap(ci);
2861                        if (cond as i32) != i.arg_k() {
2862                            pc += 1;
2863                        } else {
2864                            let next = code[pc as usize];
2865                            pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
2866                            trap = state.ci_trap(ci);
2867                        }
2868                    }
2869                    // ── OP_LT ─────────────────────────────────────────────────
2870                    OpCode::Lt => {
2871                        let ra_v = state.get_at(base + i.arg_a());
2872                        let rb_v = state.get_at(base + i.arg_b());
2873                        let cond = if let (LuaValue::Int(ia), LuaValue::Int(ib)) = (&ra_v, &rb_v) {
2874                            *ia < *ib
2875                        } else if matches!(
2876                            (&ra_v, &rb_v),
2877                            (
2878                                LuaValue::Int(_) | LuaValue::Float(_),
2879                                LuaValue::Int(_) | LuaValue::Float(_)
2880                            )
2881                        ) {
2882                            lt_num(&ra_v, &rb_v)
2883                        } else {
2884                            state.set_ci_savedpc(ci, pc);
2885                            state.set_top(state.ci_top(ci));
2886                            let r = less_than_others(state, &ra_v, &rb_v)?;
2887                            trap = state.ci_trap(ci);
2888                            r
2889                        };
2890                        if (cond as i32) != i.arg_k() {
2891                            pc += 1;
2892                        } else {
2893                            let next = code[pc as usize];
2894                            pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
2895                            trap = state.ci_trap(ci);
2896                        }
2897                    }
2898                    // ── OP_LE ─────────────────────────────────────────────────
2899                    OpCode::Le => {
2900                        let ra_v = state.get_at(base + i.arg_a());
2901                        let rb_v = state.get_at(base + i.arg_b());
2902                        let cond = if let (LuaValue::Int(ia), LuaValue::Int(ib)) = (&ra_v, &rb_v) {
2903                            *ia <= *ib
2904                        } else if matches!(
2905                            (&ra_v, &rb_v),
2906                            (
2907                                LuaValue::Int(_) | LuaValue::Float(_),
2908                                LuaValue::Int(_) | LuaValue::Float(_)
2909                            )
2910                        ) {
2911                            le_num(&ra_v, &rb_v)
2912                        } else {
2913                            state.set_ci_savedpc(ci, pc);
2914                            state.set_top(state.ci_top(ci));
2915                            let r = less_equal_others(state, &ra_v, &rb_v)?;
2916                            trap = state.ci_trap(ci);
2917                            r
2918                        };
2919                        if (cond as i32) != i.arg_k() {
2920                            pc += 1;
2921                        } else {
2922                            let next = code[pc as usize];
2923                            pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
2924                            trap = state.ci_trap(ci);
2925                        }
2926                    }
2927                    // ── OP_EQK ────────────────────────────────────────────────
2928                    OpCode::EqK => {
2929                        let ra_v = state.get_at(base + i.arg_a());
2930                        let rb_v = constants[i.arg_b() as usize];
2931                        let cond = equal_obj(None, &ra_v, &rb_v)? as u32;
2932                        if (cond as i32) != i.arg_k() {
2933                            pc += 1;
2934                        } else {
2935                            let next = code[pc as usize];
2936                            pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
2937                            trap = state.ci_trap(ci);
2938                        }
2939                    }
2940                    // ── OP_EQI ────────────────────────────────────────────────
2941                    //    if (ttisinteger) cond = ivalue == im
2942                    //    elif (ttisfloat) cond = numeq(fltvalue, cast_num(im))
2943                    //    else cond = 0
2944                    OpCode::EqI => {
2945                        let ra_v = state.get_at(base + i.arg_a());
2946                        let im = i.arg_s_b() as i64;
2947                        let cond: bool = match &ra_v {
2948                            LuaValue::Int(iv) => *iv == im,
2949                            LuaValue::Float(fv) => *fv == im as f64,
2950                            _ => false,
2951                        };
2952                        if (cond as i32) != i.arg_k() {
2953                            pc += 1;
2954                        } else {
2955                            let next = code[pc as usize];
2956                            pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
2957                            trap = state.ci_trap(ci);
2958                        }
2959                    }
2960                    // ── OP_LTI / OP_LEI / OP_GTI / OP_GEI ───────────────────
2961                    //              inv=0/0/1/1, tm=TM_LT/TM_LE/TM_LT/TM_LE)
2962                    OpCode::LtI => {
2963                        let ra = base + i.arg_a();
2964                        let im = i.arg_s_b() as i64;
2965                        let fast_cond = match &state.stack[ra.0 as usize].val {
2966                            LuaValue::Int(ia) => Some(*ia < im),
2967                            LuaValue::Float(fa) => Some(*fa < im as f64),
2968                            _ => None,
2969                        };
2970                        let cond = match fast_cond {
2971                            Some(cond) => cond,
2972                            None => order_imm_slow(
2973                                state,
2974                                ra,
2975                                pc,
2976                                &mut trap,
2977                                ci,
2978                                i,
2979                                im,
2980                                false,
2981                                TagMethod::Lt,
2982                            )?,
2983                        };
2984                        finish_order_imm_jump(state, code, &mut pc, &mut trap, ci, i, cond);
2985                    }
2986                    OpCode::LeI => {
2987                        let ra = base + i.arg_a();
2988                        let im = i.arg_s_b() as i64;
2989                        let fast_cond = match &state.stack[ra.0 as usize].val {
2990                            LuaValue::Int(ia) => Some(*ia <= im),
2991                            LuaValue::Float(fa) => Some(*fa <= im as f64),
2992                            _ => None,
2993                        };
2994                        let cond = match fast_cond {
2995                            Some(cond) => cond,
2996                            None => order_imm_slow(
2997                                state,
2998                                ra,
2999                                pc,
3000                                &mut trap,
3001                                ci,
3002                                i,
3003                                im,
3004                                false,
3005                                TagMethod::Le,
3006                            )?,
3007                        };
3008                        finish_order_imm_jump(state, code, &mut pc, &mut trap, ci, i, cond);
3009                    }
3010                    OpCode::GtI => {
3011                        let ra = base + i.arg_a();
3012                        let im = i.arg_s_b() as i64;
3013                        let fast_cond = match &state.stack[ra.0 as usize].val {
3014                            LuaValue::Int(ia) => Some(*ia > im),
3015                            LuaValue::Float(fa) => Some(*fa > im as f64),
3016                            _ => None,
3017                        };
3018                        let cond = match fast_cond {
3019                            Some(cond) => cond,
3020                            None => order_imm_slow(
3021                                state,
3022                                ra,
3023                                pc,
3024                                &mut trap,
3025                                ci,
3026                                i,
3027                                im,
3028                                true,
3029                                TagMethod::Lt,
3030                            )?,
3031                        };
3032                        finish_order_imm_jump(state, code, &mut pc, &mut trap, ci, i, cond);
3033                    }
3034                    OpCode::GeI => {
3035                        let ra = base + i.arg_a();
3036                        let im = i.arg_s_b() as i64;
3037                        let fast_cond = match &state.stack[ra.0 as usize].val {
3038                            LuaValue::Int(ia) => Some(*ia >= im),
3039                            LuaValue::Float(fa) => Some(*fa >= im as f64),
3040                            _ => None,
3041                        };
3042                        let cond = match fast_cond {
3043                            Some(cond) => cond,
3044                            None => order_imm_slow(
3045                                state,
3046                                ra,
3047                                pc,
3048                                &mut trap,
3049                                ci,
3050                                i,
3051                                im,
3052                                true,
3053                                TagMethod::Le,
3054                            )?,
3055                        };
3056                        finish_order_imm_jump(state, code, &mut pc, &mut trap, ci, i, cond);
3057                    }
3058                    // ── OP_TEST ────────────────────────────────────────────────
3059                    OpCode::Test => {
3060                        let ra_v = state.get_at(base + i.arg_a());
3061                        let cond = !matches!(ra_v, LuaValue::Nil | LuaValue::Bool(false));
3062                        if (cond as i32) != i.arg_k() {
3063                            pc += 1;
3064                        } else {
3065                            let next = code[pc as usize];
3066                            pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
3067                            trap = state.ci_trap(ci);
3068                        }
3069                    }
3070                    // ── OP_TESTSET ─────────────────────────────────────────────
3071                    //    else { setobj2s(L, ra, rb); donextjump(ci); }
3072                    OpCode::TestSet => {
3073                        let ra = base + i.arg_a();
3074                        let rb_v = state.get_at(base + i.arg_b());
3075                        let falsy = matches!(rb_v, LuaValue::Nil | LuaValue::Bool(false));
3076                        if (falsy as i32) == i.arg_k() {
3077                            pc += 1;
3078                        } else {
3079                            state.set_at(ra, rb_v);
3080                            let next = code[pc as usize];
3081                            pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
3082                            trap = state.ci_trap(ci);
3083                        }
3084                    }
3085                    // ── OP_CALL ────────────────────────────────────────────────
3086                    //      updatetrap(ci);
3087                    //    else { ci = newci; goto startfunc; }
3088                    OpCode::Call => {
3089                        let ra = base + i.arg_a();
3090                        let b = i.arg_b();
3091                        let nresults = i.arg_c() as i32 - 1;
3092                        if b != 0 {
3093                            state.set_top(ra + b);
3094                        }
3095                        state.set_ci_savedpc(ci, pc); // savepc
3096                        let had_hook = state.hookmask != 0;
3097                        match state.precall(ra, nresults)? {
3098                            None => {
3099                                // C functions such as debug.sethook can change
3100                                // hook state during the call, so refresh the VM
3101                                // trap when hooks were or became relevant.
3102                                if had_hook || state.hookmask != 0 {
3103                                    trap = state.ci_trap(ci); // updatetrap
3104                                }
3105                            }
3106                            Some(new_ci) => {
3107                                // Lua function — goto startfunc
3108                                ci = new_ci;
3109                                continue 'startfunc;
3110                            }
3111                        }
3112                    }
3113                    // ── OP_TAILCALL ────────────────────────────────────────────
3114                    //      goto startfunc;
3115                    //    else { ci->func.p -= delta; luaD_poscall(L, ci, n);
3116                    //            updatetrap; goto ret; }
3117                    OpCode::TailCall => {
3118                        let ra = base + i.arg_a();
3119                        let b = i.arg_b();
3120                        let nparams1 = i.arg_c();
3121                        let delta = if nparams1 != 0 {
3122                            state.ci_nextraargs(ci) + nparams1 as i32
3123                        } else {
3124                            0
3125                        };
3126                        let top_b: i32 = if b != 0 {
3127                            state.set_top(ra + b);
3128                            b
3129                        } else {
3130                            state.top_idx() - ra
3131                        };
3132                        state.set_ci_savedpc(ci, pc);
3133                        if i.test_k() {
3134                            state.close_upvals_from_base(ci)?;
3135                        }
3136                        let n = state.pretailcall(ci, ra, top_b, delta)?;
3137                        if n < 0 {
3138                            // Lua function — goto startfunc
3139                            state.note_lua_tailcall(ci);
3140                            continue 'startfunc;
3141                        } else {
3142                            // C function — ci->func.p -= delta; luaD_poscall; goto ret
3143                            state.ci_adjust_func(ci, delta);
3144                            state.poscall(ci, n as u32)?;
3145                            if state.hookmask != 0 {
3146                                trap = state.ci_trap(ci);
3147                            }
3148                            break 'dispatch; // goto ret
3149                        }
3150                    }
3151                    // ── OP_RETURN ──────────────────────────────────────────────
3152                    //    savepc; if TESTARG_k: close upvals;
3153                    //    if nparams1: ci->func -= nextraargs+nparams1;
3154                    //    L->top.p = ra+n; luaD_poscall; goto ret
3155                    OpCode::Return => {
3156                        let ra = base + i.arg_a();
3157                        let n_raw = i.arg_b() as i32 - 1;
3158                        let nparams1 = i.arg_c();
3159                        let n: u32 = if n_raw < 0 {
3160                            (state.top_idx() - ra) as u32
3161                        } else {
3162                            n_raw as u32
3163                        };
3164                        state.set_ci_savedpc(ci, pc);
3165                        if i.test_k() {
3166                            state.ci_nres_set(ci, n as i32);
3167                            let ci_top = state.ci_top(ci);
3168                            if state.top_idx().0 < ci_top.0 {
3169                                state.set_top(ci_top);
3170                            }
3171                            crate::func::close(state, base, crate::func::CLOSE_K_TOP, true)?;
3172                            if state.hookmask != 0 {
3173                                trap = state.ci_trap(ci);
3174                            }
3175                            base = state.ci_base(ci); // updatestack
3176                        }
3177                        if nparams1 != 0 {
3178                            let nextraargs = state.ci_nextraargs(ci) as u32;
3179                            state.ci_adjust_func(ci, nextraargs as i32 + nparams1 as i32);
3180                        }
3181                        state.set_top(ra + n as i32);
3182                        state.poscall(ci, n)?;
3183                        if state.hookmask != 0 {
3184                            trap = state.ci_trap(ci);
3185                        }
3186                        break 'dispatch; // goto ret
3187                    }
3188                    // ── OP_RETURN0 ─────────────────────────────────────────────
3189                    //    else { L->ci = ci->previous; L->top = base-1;
3190                    //           for (nres = ci->nresults; nres > 0; nres--)
3191                    //             setnilvalue(L->top++) }
3192                    //    goto ret;
3193                    OpCode::Return0 => {
3194                        if state.hookmask == 0 {
3195                            let ci_slot = ci.as_usize();
3196                            let nres = state.call_info[ci_slot].nresults as i32;
3197                            state.ci = state.call_info[ci_slot]
3198                                .previous
3199                                .expect("RETURN0: returning frame has no previous CallInfo");
3200                            state.top = base - 1;
3201                            for _ in 0..nres.max(0) {
3202                                state.push(LuaValue::Nil);
3203                            }
3204                        } else {
3205                            return0_hook(state, ci, base, i, pc, &mut trap)?;
3206                        }
3207                        break 'dispatch; // goto ret
3208                    }
3209                    // ── OP_RETURN1 ─────────────────────────────────────────────
3210                    //    else { nres = ci->nresults; ci = ci->previous; ...handle results... }
3211                    //    goto ret;
3212                    OpCode::Return1 => {
3213                        if state.hookmask == 0 {
3214                            let ci_slot = ci.as_usize();
3215                            let nres = state.call_info[ci_slot].nresults as i32;
3216                            state.ci = state.call_info[ci_slot]
3217                                .previous
3218                                .expect("RETURN1: returning frame has no previous CallInfo");
3219                            if nres == 0 {
3220                                state.top = base - 1;
3221                            } else {
3222                                let ra = base + i.arg_a();
3223                                state.stack[(base - 1).0 as usize].val =
3224                                    state.stack[ra.0 as usize].val; // at least this result
3225                                state.top = base;
3226                                for _ in 1..nres.max(0) {
3227                                    state.push(LuaValue::Nil);
3228                                }
3229                            }
3230                        } else {
3231                            return1_hook(state, ci, base, i, pc, &mut trap)?;
3232                        }
3233                        break 'dispatch; // goto ret
3234                    }
3235                    // ── OP_FORLOOP ─────────────────────────────────────────────
3236                    //    else if (floatforloop(ra)) pc -= GETARG_Bx(i)
3237                    //    updatetrap(ci);
3238                    OpCode::ForLoop => {
3239                        let ra = base + i.arg_a();
3240                        if legacy_for {
3241                            if forloop_legacy(state, ra) {
3242                                pc = (pc as i64 - i.arg_bx() as i64) as u32;
3243                            }
3244                            if state.hookmask != 0 {
3245                                trap = state.ci_trap(ci);
3246                            }
3247                        } else {
3248                            let ra_u = ra.0 as usize;
3249                            let window: &mut [crate::state::StackValue; 4] = (&mut state.stack
3250                                [ra_u..ra_u + 4])
3251                                .try_into()
3252                                .expect("FORLOOP register window");
3253                            if let LuaValue::Int(step) = window[2].val {
3254                                let count = match window[1].val {
3255                                    LuaValue::Int(c) => c as u64,
3256                                    _ => 0,
3257                                };
3258                                if count > 0 {
3259                                    let idx = match window[0].val {
3260                                        LuaValue::Int(x) => x,
3261                                        _ => 0,
3262                                    };
3263                                    window[1].val = LuaValue::Int((count - 1) as i64);
3264                                    let new_idx = intop_add(idx, step);
3265                                    window[0].val = LuaValue::Int(new_idx);
3266                                    window[3].val = LuaValue::Int(new_idx);
3267                                    pc = (pc as i64 - i.arg_bx() as i64) as u32;
3268                                }
3269                            } else if float_for_loop(state, ra) {
3270                                pc = (pc as i64 - i.arg_bx() as i64) as u32;
3271                            }
3272                            if state.hookmask != 0 {
3273                                trap = state.ci_trap(ci);
3274                            }
3275                        }
3276                    }
3277                    // ── OP_FORPREP ─────────────────────────────────────────────
3278                    OpCode::ForPrep => {
3279                        let ra = base + i.arg_a();
3280                        state.set_ci_savedpc(ci, pc);
3281                        state.set_top(state.ci_top(ci));
3282                        if legacy_for {
3283                            // 5.3: prep subtracts the step and ALWAYS jumps forward
3284                            // to FORLOOP (which runs the first test).
3285                            forprep_legacy(state, ra)?;
3286                            pc = (pc as i64 + i.arg_bx() as i64) as u32;
3287                        } else if forprep(state, ra)? {
3288                            pc = (pc as i64 + i.arg_bx() as i64 + 1) as u32;
3289                        }
3290                    }
3291                    // ── OP_TFORPREP ────────────────────────────────────────────
3292                    //    pc += GETARG_Bx(i); i = *pc++; assert(OP_TFORCALL && ra==RA(i));
3293                    //    goto l_tforcall;
3294                    OpCode::TForPrep => {
3295                        let ra = base + i.arg_a();
3296                        state.set_ci_savedpc(ci, pc);
3297                        state.set_top(state.ci_top(ci));
3298                        if tfor_55 {
3299                            let closing = state.get_at(ra + 3);
3300                            let control = state.get_at(ra + 2);
3301                            state.set_at(ra + 2, closing);
3302                            state.set_at(ra + 3, control);
3303                            state.new_tbc_upval(ra + 2)?;
3304                        } else {
3305                            state.new_tbc_upval(ra + 3)?;
3306                        }
3307                        pc = (pc as i64 + i.arg_bx() as i64) as u32;
3308                        let tfc_i = code[pc as usize];
3309                        pc += 1;
3310                        debug_assert!(tfc_i.opcode() == OpCode::TForCall);
3311                        // inline l_tforcall:
3312                        let tfc_ra = base + tfc_i.arg_a();
3313                        if tfor_55 {
3314                            let src = tfc_ra.0 as usize;
3315                            let func = state.stack[src].val.clone();
3316                            let state_val = state.stack[src + 1].val.clone();
3317                            let control = state.stack[src + 3].val.clone();
3318                            state.stack[src + 3].val = func;
3319                            state.stack[src + 4].val = state_val;
3320                            state.stack[src + 5].val = control;
3321                            state.set_top(tfc_ra + 6);
3322                            state.set_ci_savedpc(ci, pc);
3323                            if !state.call_known_c_at(tfc_ra + 3, tfc_i.arg_c() as i32)? {
3324                                state.call_at(tfc_ra + 3, tfc_i.arg_c() as i32)?;
3325                            }
3326                        } else {
3327                            let src = tfc_ra.0 as usize;
3328                            let dst = src + 4;
3329                            for k in 0..3usize {
3330                                state.stack[dst + k].val = state.stack[src + k].val.clone();
3331                            }
3332                            state.set_top(tfc_ra + 4 + 3);
3333                            state.set_ci_savedpc(ci, pc);
3334                            if !state.call_known_c_at(tfc_ra + 4, tfc_i.arg_c() as i32)? {
3335                                state.call_at(tfc_ra + 4, tfc_i.arg_c() as i32)?;
3336                            }
3337                        }
3338                        trap = state.ci_trap(ci);
3339                        base = state.ci_base(ci); // updatestack
3340                        let tfl_i = code[pc as usize];
3341                        pc += 1;
3342                        debug_assert!(tfl_i.opcode() == OpCode::TForLoop);
3343                        let tfl_ra = base + tfl_i.arg_a();
3344                        // inline l_tforloop:
3345                        if tfor_55 {
3346                            if !matches!(state.get_at(tfl_ra + 3), LuaValue::Nil) {
3347                                pc = (pc as i64 - tfl_i.arg_bx() as i64) as u32;
3348                            }
3349                        } else if !matches!(state.get_at(tfl_ra + 4), LuaValue::Nil) {
3350                            let v = state.get_at(tfl_ra + 4);
3351                            state.set_at(tfl_ra + 2, v);
3352                            pc = (pc as i64 - tfl_i.arg_bx() as i64) as u32;
3353                        }
3354                    }
3355                    // ── OP_TFORCALL ────────────────────────────────────────────
3356                    OpCode::TForCall => {
3357                        let ra = base + i.arg_a();
3358                        if tfor_55 {
3359                            let src = ra.0 as usize;
3360                            let func = state.stack[src].val.clone();
3361                            let state_val = state.stack[src + 1].val.clone();
3362                            let control = state.stack[src + 3].val.clone();
3363                            state.stack[src + 3].val = func;
3364                            state.stack[src + 4].val = state_val;
3365                            state.stack[src + 5].val = control;
3366                            state.set_top(ra + 6);
3367                            state.set_ci_savedpc(ci, pc);
3368                            if !state.call_known_c_at(ra + 3, i.arg_c() as i32)? {
3369                                state.call_at(ra + 3, i.arg_c() as i32)?;
3370                            }
3371                        } else {
3372                            let src = ra.0 as usize;
3373                            let dst = src + 4;
3374                            for k in 0..3usize {
3375                                state.stack[dst + k].val = state.stack[src + k].val.clone();
3376                            }
3377                            state.set_top(ra + 4 + 3);
3378                            state.set_ci_savedpc(ci, pc);
3379                            if !state.call_known_c_at(ra + 4, i.arg_c() as i32)? {
3380                                state.call_at(ra + 4, i.arg_c() as i32)?;
3381                            }
3382                        }
3383                        trap = state.ci_trap(ci);
3384                        base = state.ci_base(ci); // updatestack
3385                        let tfl_i = code[pc as usize];
3386                        pc += 1;
3387                        debug_assert!(tfl_i.opcode() == OpCode::TForLoop);
3388                        let tfl_ra = base + tfl_i.arg_a();
3389                        if tfor_55 {
3390                            if !matches!(state.get_at(tfl_ra + 3), LuaValue::Nil) {
3391                                pc = (pc as i64 - tfl_i.arg_bx() as i64) as u32;
3392                            }
3393                        } else if !matches!(state.get_at(tfl_ra + 4), LuaValue::Nil) {
3394                            let v = state.get_at(tfl_ra + 4);
3395                            state.set_at(tfl_ra + 2, v);
3396                            pc = (pc as i64 - tfl_i.arg_bx() as i64) as u32;
3397                        }
3398                    }
3399                    // ── OP_TFORLOOP ────────────────────────────────────────────
3400                    OpCode::TForLoop => {
3401                        let ra = base + i.arg_a();
3402                        if tfor_55 {
3403                            if !matches!(state.get_at(ra + 3), LuaValue::Nil) {
3404                                pc = (pc as i64 - i.arg_bx() as i64) as u32;
3405                            }
3406                        } else if !matches!(state.get_at(ra + 4), LuaValue::Nil) {
3407                            let v = state.get_at(ra + 4);
3408                            state.set_at(ra + 2, v);
3409                            pc = (pc as i64 - i.arg_bx() as i64) as u32;
3410                        }
3411                    }
3412                    // ── OP_SETLIST ─────────────────────────────────────────────
3413                    //    if TESTARG_k: last += Ax * (MAXARG_C+1); pc++;
3414                    //    for (; n > 0; n--) h->array[last-1] = val; luaC_barrierback
3415                    OpCode::SetList => {
3416                        let ra = base + i.arg_a();
3417                        let n_raw = i.arg_b();
3418                        let mut last = i.arg_c();
3419                        let t_val = state.get_at(ra);
3420                        let n: i32 = if n_raw == 0 {
3421                            state.top_idx() - ra - 1
3422                        } else {
3423                            state.set_top(state.ci_top(ci));
3424                            n_raw
3425                        };
3426                        last += n;
3427                        if i.test_k() {
3428                            let extra = code[pc as usize];
3429                            pc += 1;
3430                            const MAXARG_C: i32 = (1 << 8) - 1;
3431                            last += extra.arg_ax() * (MAXARG_C + 1);
3432                        }
3433                        state.table_ensure_array(&t_val, last as usize)?;
3434                        for k in (1..=n).rev() {
3435                            let val = state.get_at(ra + k as i32);
3436                            state.table_array_set(&t_val, (last - 1) as usize, val.clone())?;
3437                            last -= 1;
3438                            state.gc_value_barrier_back(&t_val, &val);
3439                        }
3440                    }
3441                    // ── OP_CLOSURE ─────────────────────────────────────────────
3442                    //    halfProtect(pushclosure(L, p, cl->upvals, base, ra));
3443                    //    checkGC(L, ra+1);
3444                    OpCode::Closure => {
3445                        let ra = base + i.arg_a();
3446                        let proto_idx = i.arg_bx() as usize;
3447                        state.set_ci_savedpc(ci, pc);
3448                        state.set_top(state.ci_top(ci));
3449                        push_closure(state, proto_idx, ci, base, ra)?;
3450                        // checkGC
3451                        state.set_ci_savedpc(ci, pc);
3452                        state.set_top(ra + 1);
3453                        state.gc_cond_step();
3454                        trap = state.ci_trap(ci);
3455                    }
3456                    // ── OP_VARARG ──────────────────────────────────────────────
3457                    OpCode::VarArg => {
3458                        let ra = base + i.arg_a();
3459                        let n = i.arg_c() as i32 - 1;
3460                        state.set_ci_savedpc(ci, pc);
3461                        state.set_top(state.ci_top(ci));
3462                        state.get_varargs(ci, ra, n)?;
3463                        trap = state.ci_trap(ci);
3464                    }
3465                    // ── OP_VARARGPREP ──────────────────────────────────────────
3466                    //    if (trap) luaD_hookcall(L, ci); L->oldpc = 1;
3467                    //    updatebase(ci);
3468                    OpCode::VarArgPrep => {
3469                        let nparams = i.arg_a();
3470                        state.set_ci_savedpc(ci, pc);
3471                        state.adjust_varargs(ci, nparams, &cl)?;
3472                        trap = state.ci_trap(ci);
3473                        if trap {
3474                            state.hook_call(ci)?;
3475                            state.set_oldpc(1);
3476                        }
3477                        base = state.ci_base(ci);
3478                    }
3479                    // ── OP_GETVARG (Lua 5.5 virtual named-vararg read) ────────
3480                    OpCode::GetVArg => {
3481                        let ra = base + i.arg_a();
3482                        let vararg_reg = base + i.arg_b();
3483                        let key = state.get_at(base + i.arg_c()).clone();
3484                        let val = if let LuaValue::Table(t) = state.get_at(vararg_reg) {
3485                            t.get(&key)
3486                        } else {
3487                            let nextra = state.ci_nextraargs(ci);
3488                            match key {
3489                                LuaValue::Int(n) if n >= 1 && n <= nextra as i64 => {
3490                                    let ci_func = state.ci_base(ci) - 1;
3491                                    state.get_at(ci_func - nextra + n as i32 - 1)
3492                                }
3493                                LuaValue::Float(f)
3494                                    if f.is_finite()
3495                                        && f.fract() == 0.0
3496                                        && f >= 1.0
3497                                        && f <= nextra as f64 =>
3498                                {
3499                                    let ci_func = state.ci_base(ci) - 1;
3500                                    state.get_at(ci_func - nextra + f as i32 - 1)
3501                                }
3502                                LuaValue::Str(s) if s.as_bytes() == b"n" => {
3503                                    LuaValue::Int(nextra as i64)
3504                                }
3505                                _ => LuaValue::Nil,
3506                            }
3507                        };
3508                        state.set_at(ra, val);
3509                    }
3510                    // ── OP_EXTRAARG ────────────────────────────────────────────
3511                    OpCode::ExtraArg => {
3512                        debug_assert!(false, "OP_EXTRAARG executed directly");
3513                    }
3514                    // ── OP_ERRNNIL (Lua 5.5 global-already-defined guard) ──────
3515                    //    luaG_errnnil: if the global's current value is non-nil,
3516                    //    raise `global '<name>' already defined`. Bx == 0 → "?",
3517                    //    else Bx-1 indexes the constant table for the name.
3518                    OpCode::ErrNNil => {
3519                        let ra = base + i.arg_a();
3520                        if !matches!(state.get_at(ra), LuaValue::Nil) {
3521                            let bx = i.arg_bx();
3522                            let name: Vec<u8> = if bx == 0 {
3523                                b"?".to_vec()
3524                            } else {
3525                                match constants[(bx - 1) as usize] {
3526                                    LuaValue::Str(s) => s.as_bytes().to_vec(),
3527                                    _ => b"?".to_vec(),
3528                                }
3529                            };
3530                            let mut msg = Vec::with_capacity(name.len() + 24);
3531                            msg.extend_from_slice(b"global '");
3532                            msg.extend_from_slice(&name);
3533                            msg.extend_from_slice(b"' already defined");
3534                            state.set_ci_savedpc(ci, pc);
3535                            return Err(crate::debug::prefixed_runtime_pub(state, msg));
3536                        }
3537                    }
3538                    // ── OP_VARARGPACK (Lua 5.5 named varargs) ──────────────────
3539                    //    Pack the current frame's extra varargs into a fresh
3540                    //    table stored in register A. Mirrors `table.pack(...)`:
3541                    //    a 1-based sequence of all extra args plus an integer
3542                    //    `.n` field counting them (nil holes included). The
3543                    //    extra args were moved by VARARGPREP to the slots just
3544                    //    below `ci->func`, i.e. `ci_func - nextra .. ci_func-1`.
3545                    OpCode::VarArgPack => {
3546                        if !cl.proto.vararg_table_needed && !i.test_k() {
3547                            state.set_ci_savedpc(ci, pc);
3548                            continue;
3549                        }
3550                        let ra = base + i.arg_a();
3551                        let nextra = state.ci_nextraargs(ci);
3552                        let ci_func: StackIdx = state.ci_base(ci) - 1;
3553                        let t = if nextra > 0 {
3554                            state.new_table_with_sizes(nextra as u32, 1)?
3555                        } else {
3556                            state.new_table()
3557                        };
3558                        for k in 0..nextra {
3559                            let src: StackIdx = ci_func - nextra as i32 + k as i32;
3560                            let val = state.get_at(src);
3561                            t.raw_set_int(state, (k + 1) as i64, val)?;
3562                        }
3563                        let n_key = state.intern_str(b"n")?;
3564                        t.raw_set(state, LuaValue::Str(n_key), LuaValue::Int(nextra as i64))?;
3565                        state.set_at(ra, LuaValue::Table(t));
3566                        state.set_ci_savedpc(ci, pc);
3567                        state.set_top(ra + 1);
3568                        state.gc_cond_step();
3569                        if state.hookmask != 0 {
3570                            trap = state.ci_trap(ci);
3571                        }
3572                    }
3573                } // end match opcode
3574            } // end 'dispatch loop
3575
3576            // ── ret: label ──────────────────────────────────────────────────
3577            if state.ci_is_fresh(ci) {
3578                return Ok(());
3579            } else {
3580                ci = state
3581                    .ci_previous(ci)
3582                    .expect("ci_previous: not fresh frame must have previous");
3583                continue 'returning;
3584            }
3585        } // end 'returning loop
3586    } // end 'startfunc loop
3587}
3588
3589// ─── Local opcode dispatch helpers ───────────────────────────────────────────
3590
3591#[inline(always)]
3592fn number_value(v: LuaValue) -> Option<f64> {
3593    match v {
3594        LuaValue::Float(f) => Some(f),
3595        LuaValue::Int(i) => Some(i as f64),
3596        _ => None,
3597    }
3598}
3599
3600/// Increments `pc` on success (the `pc++` in the C macros).
3601#[allow(dead_code)]
3602#[inline]
3603fn arith_op_aux_rr(
3604    state: &mut LuaState,
3605    ra: StackIdx,
3606    v1: &LuaValue,
3607    v2: &LuaValue,
3608    pc: &mut u32,
3609    iop: fn(i64, i64) -> i64,
3610    fop: fn(f64, f64) -> f64,
3611) {
3612    if let (LuaValue::Int(i1), LuaValue::Int(i2)) = (v1, v2) {
3613        *pc += 1;
3614        state.set_at(ra, LuaValue::Int(iop(*i1, *i2)));
3615    } else {
3616        arith_float_aux(state, ra, v1, v2, pc, fop);
3617    }
3618}
3619
3620#[allow(dead_code)]
3621#[inline]
3622fn arith_float_aux(
3623    state: &mut LuaState,
3624    ra: StackIdx,
3625    v1: &LuaValue,
3626    v2: &LuaValue,
3627    pc: &mut u32,
3628    fop: fn(f64, f64) -> f64,
3629) {
3630    let n1 = match v1 {
3631        LuaValue::Float(f) => Some(*f),
3632        LuaValue::Int(i) => Some(*i as f64),
3633        _ => None,
3634    };
3635    let n2 = match v2 {
3636        LuaValue::Float(f) => Some(*f),
3637        LuaValue::Int(i) => Some(*i as f64),
3638        _ => None,
3639    };
3640    if let (Some(n1), Some(n2)) = (n1, n2) {
3641        *pc += 1;
3642        state.set_at(ra, LuaValue::Float(fop(n1, n2)));
3643    }
3644}
3645
3646#[allow(dead_code)]
3647#[inline]
3648fn arith_op_checked(
3649    state: &mut LuaState,
3650    ra: StackIdx,
3651    v1: &LuaValue,
3652    v2: &LuaValue,
3653    pc: &mut u32,
3654    iop: fn(i64, i64) -> Result<i64, LuaError>,
3655    fop: fn(f64, f64) -> f64,
3656) -> Result<(), LuaError> {
3657    if let (LuaValue::Int(i1), LuaValue::Int(i2)) = (v1, v2) {
3658        *pc += 1;
3659        let result = iop(*i1, *i2).map_err(|e| match e {
3660            LuaError::Runtime(LuaValue::Str(s)) => {
3661                crate::debug::prefixed_runtime_pub(state, s.as_bytes().to_vec())
3662            }
3663            LuaError::RuntimeMsg(b) => crate::debug::prefixed_runtime_pub(state, b.into_vec()),
3664            other => other,
3665        })?;
3666        state.set_at(ra, LuaValue::Int(result));
3667    } else {
3668        arith_float_aux(state, ra, v1, v2, pc, fop);
3669    }
3670    Ok(())
3671}
3672
3673#[allow(dead_code)]
3674#[inline]
3675fn bitwise_op_k(
3676    state: &mut LuaState,
3677    ra: StackIdx,
3678    v1: &LuaValue,
3679    v2: &LuaValue, // must be integer (K constant)
3680    pc: &mut u32,
3681    op: fn(i64, i64) -> i64,
3682) {
3683    let i2 = match v2 {
3684        LuaValue::Int(i) => *i,
3685        _ => return,
3686    };
3687    if let Some(i1) = to_integer_ns(v1, F2Imod::Eq) {
3688        *pc += 1;
3689        state.set_at(ra, LuaValue::Int(op(i1, i2)));
3690    }
3691}
3692
3693#[allow(dead_code)]
3694#[inline]
3695fn bitwise_op_rr(
3696    state: &mut LuaState,
3697    ra: StackIdx,
3698    v1: &LuaValue,
3699    v2: &LuaValue,
3700    pc: &mut u32,
3701    op: fn(i64, i64) -> i64,
3702) {
3703    if let (Some(i1), Some(i2)) = (to_integer_ns(v1, F2Imod::Eq), to_integer_ns(v2, F2Imod::Eq)) {
3704        *pc += 1;
3705        state.set_at(ra, LuaValue::Int(op(i1, i2)));
3706    }
3707}
3708
3709/// `right = true` negates `y` for right-shift semantics.
3710#[allow(dead_code)]
3711#[inline]
3712fn bitwise_shift_rr(
3713    state: &mut LuaState,
3714    ra: StackIdx,
3715    v1: &LuaValue,
3716    v2: &LuaValue,
3717    pc: &mut u32,
3718    right: bool,
3719) {
3720    if let (Some(i1), Some(i2)) = (to_integer_ns(v1, F2Imod::Eq), to_integer_ns(v2, F2Imod::Eq)) {
3721        let y = if right { intop_sub(0, i2) } else { i2 };
3722        *pc += 1;
3723        state.set_at(ra, LuaValue::Int(shiftl(i1, y)));
3724    }
3725}
3726
3727/// Cold half of C's `op_orderI` macro: only reached when the operand is not a
3728/// plain integer/float and a metamethod lookup may be needed.
3729#[cold]
3730#[inline(never)]
3731#[allow(clippy::too_many_arguments)]
3732fn order_imm_slow(
3733    state: &mut LuaState,
3734    ra: StackIdx,
3735    pc: u32,
3736    trap: &mut bool,
3737    ci: CallInfoIdx,
3738    i: Instruction,
3739    im: i64,
3740    inv: bool,
3741    tm: TagMethod,
3742) -> Result<bool, LuaError> {
3743    let ra_v = state.get_at(ra);
3744    let isf = i.arg_c() != 0;
3745    state.set_ci_savedpc(ci, pc);
3746    state.set_top(state.ci_top(ci));
3747    let r = state.call_order_i_tm(&ra_v, im, inv, isf, tm)?;
3748    *trap = state.ci_trap(ci);
3749    Ok(r)
3750}
3751
3752#[inline(always)]
3753fn finish_order_imm_jump(
3754    state: &mut LuaState,
3755    code: &[Instruction],
3756    pc: &mut u32,
3757    trap: &mut bool,
3758    ci: CallInfoIdx,
3759    i: Instruction,
3760    cond: bool,
3761) {
3762    if (cond as i32) != i.arg_k() {
3763        *pc += 1;
3764    } else {
3765        let next = code[*pc as usize];
3766        *pc = (*pc as i64 + next.arg_s_j() as i64 + 1) as u32;
3767        if state.hookmask != 0 {
3768            *trap = state.ci_trap(ci);
3769        }
3770    }
3771}
3772
3773#[cold]
3774#[inline(never)]
3775fn return0_hook(
3776    state: &mut LuaState,
3777    ci: CallInfoIdx,
3778    base: StackIdx,
3779    i: Instruction,
3780    pc: u32,
3781    trap: &mut bool,
3782) -> Result<(), LuaError> {
3783    let ra = base + i.arg_a();
3784    state.set_top(ra);
3785    state.set_ci_savedpc(ci, pc);
3786    state.poscall(ci, 0)?;
3787    *trap = true;
3788    Ok(())
3789}
3790
3791#[cold]
3792#[inline(never)]
3793fn return1_hook(
3794    state: &mut LuaState,
3795    ci: CallInfoIdx,
3796    base: StackIdx,
3797    i: Instruction,
3798    pc: u32,
3799    trap: &mut bool,
3800) -> Result<(), LuaError> {
3801    let ra = base + i.arg_a();
3802    state.set_top(ra + 1);
3803    state.set_ci_savedpc(ci, pc);
3804    state.poscall(ci, 1)?;
3805    *trap = true;
3806    Ok(())
3807}