Skip to main content

lua_parse/
lib.rs

1//! Lua parser — translates the token stream produced by the lexer into
2//! bytecode prototypes (`LuaProto`).
3//!
4//! This crate is the recursive-descent parser with single-pass bytecode codegen
5//! folded in: the front end pairs with `lua-lex` for tokens and `lua-code` for
6//! opcode tables. It is verified by the bytecode-parity structural oracle plus
7//! the behavioral suite (see `GRADUATED.md`); it is no longer a line-by-line
8//! mirror of any C source, so do not reach for `lparser.c`/`lcode.c` to reason
9//! about it.
10//!
11//! # Ownership shapes
12//! * `BlockCnt` and `LhsAssign` are `Option<Box<...>>` chains; [`enter_block`]
13//!   pushes, [`leave_block`] pops. `FuncState.prev` is likewise
14//!   `Option<Box<FuncState>>`.
15//! * `FuncState.f` is `Box<LuaProto>` during compilation (owned, mutably
16//!   accessible); it is consumed into the GC when the function closes.
17
18use lua_types::{AbsLineInfo, GcRef, LocalVar, LuaError, LuaProto, LuaString, LuaValue, UpvalDesc};
19
20// ── Token kind constants ────────────────────────────────────────────────────
21
22/// Token kinds cross the lexer boundary as plain `i32` (`TK_*`), matching the
23/// `i32` that `lua_lex` emits and the error formatters read. These constants
24/// are the parser's view of that boundary; they are deliberately not an enum so
25/// the lexer/parser interface stays a single integer contract.
26pub type TokenKind = i32;
27pub const TK_AND: TokenKind = 257;
28pub const TK_BREAK: TokenKind = 258;
29pub const TK_DO: TokenKind = 259;
30pub const TK_ELSE: TokenKind = 260;
31pub const TK_ELSEIF: TokenKind = 261;
32pub const TK_END: TokenKind = 262;
33pub const TK_FALSE: TokenKind = 263;
34pub const TK_FOR: TokenKind = 264;
35pub const TK_FUNCTION: TokenKind = 265;
36pub const TK_GOTO: TokenKind = 266;
37pub const TK_IF: TokenKind = 267;
38pub const TK_IN: TokenKind = 268;
39pub const TK_LOCAL: TokenKind = 269;
40pub const TK_NIL: TokenKind = 270;
41pub const TK_NOT: TokenKind = 271;
42pub const TK_OR: TokenKind = 272;
43pub const TK_REPEAT: TokenKind = 273;
44pub const TK_RETURN: TokenKind = 274;
45pub const TK_THEN: TokenKind = 275;
46pub const TK_TRUE: TokenKind = 276;
47pub const TK_UNTIL: TokenKind = 277;
48pub const TK_WHILE: TokenKind = 278;
49pub const TK_IDIV: TokenKind = 279;
50pub const TK_CONCAT: TokenKind = 280;
51pub const TK_DOTS: TokenKind = 281;
52pub const TK_EQ: TokenKind = 282;
53pub const TK_GE: TokenKind = 283;
54pub const TK_LE: TokenKind = 284;
55pub const TK_NE: TokenKind = 285;
56pub const TK_SHL: TokenKind = 286;
57pub const TK_SHR: TokenKind = 287;
58pub const TK_DBCOLON: TokenKind = 288;
59pub const TK_EOS: TokenKind = 289;
60pub const TK_FLT: TokenKind = 290;
61pub const TK_INT: TokenKind = 291;
62pub const TK_NAME: TokenKind = 292;
63pub const TK_STRING: TokenKind = 293;
64
65// ── Parser constants ────────────────────────────────────────────────────────
66
67const MAX_VARS: i32 = 200;
68
69const NO_JUMP: i32 = -1;
70
71const UNARY_PRIORITY: i32 = 12;
72
73const LUA_MULTRET: i32 = -1;
74
75const MAX_UPVAL: u8 = 255;
76
77/// Lua 5.1's per-function upvalue ceiling (`LUAI_MAXUPVALUES` in 5.1's
78/// `luaconf.h`). Later versions raised this to [`MAX_UPVAL`] = 255; 5.1 caps it
79/// at 60. Enforced only on the [`lua_types::LuaVersion::V51`] path.
80const MAX_UPVAL_V51: i32 = 60;
81
82/// Largest value the 18-bit `Bx` instruction field can hold; the ceiling on a
83/// constant-table index reachable without an `EXTRAARG` prefix.
84const MAXARG_BX: i32 = (1 << 17) - 1;
85
86const LFIELDS_PER_FLUSH: i32 = 50;
87
88// ── Variable kind constants ─────────────────────────────────────────────────
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91#[repr(u8)]
92pub enum VarKind {
93    Reg = 0,
94    Const = 1,
95    ToBeClosed = 2,
96    CompileTimeConst = 3,
97    VarArg = 4,
98}
99
100impl VarKind {
101    pub fn from_u8(v: u8) -> Self {
102        match v {
103            0 => VarKind::Reg,
104            1 => VarKind::Const,
105            2 => VarKind::ToBeClosed,
106            3 => VarKind::CompileTimeConst,
107            4 => VarKind::VarArg,
108            _ => VarKind::Reg,
109        }
110    }
111    pub fn as_u8(self) -> u8 {
112        self as u8
113    }
114}
115
116// ── ExprKind ────────────────────────────────────────────────────────────────
117
118/// The descriptor kind of a parsed expression: where its value currently lives
119/// and how to materialize it. Drives every `discharge`/`exp2*` decision in
120/// codegen. The associated data each kind carries lives in [`ExprPayload`].
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum ExprKind {
123    /// Empty expression (an empty list slot).
124    Void,
125    /// Constant `nil`.
126    Nil,
127    /// Constant `true`.
128    True,
129    /// Constant `false`.
130    False,
131    /// Constant already in the function's constant table; carries its index.
132    K,
133    /// Float literal.
134    KFlt,
135    /// Integer literal.
136    KInt,
137    /// String literal (interned).
138    KStr,
139    /// Value sitting in a fixed register that must not be relocated.
140    NonReloc,
141    /// Local variable; carries its register and stack-frame variable indices.
142    Local,
143    /// Upvalue; carries its upvalue index.
144    UpVal,
145    /// Compile-time constant; carries its absolute active-variable index.
146    Const,
147    /// Table indexed by a register key; carries table register and key index.
148    Indexed,
149    /// Upvalue indexed by a constant key.
150    IndexUp,
151    /// Table indexed by an integer key.
152    IndexI,
153    /// Table indexed by a short-string key.
154    IndexStr,
155    /// Named vararg parameter; carries its register and variable indices.
156    VarArgVar,
157    /// Indexed named vararg parameter.
158    VarArgIndex,
159    /// Test/comparison whose value is realized by a jump; carries the jump pc.
160    Jmp,
161    /// Result that may land in any register; carries the instruction pc.
162    Reloc,
163    /// Function call; carries the call instruction's pc.
164    Call,
165    /// Vararg expansion; carries the instruction pc.
166    VarArg,
167}
168
169impl ExprKind {
170    #[inline]
171    pub fn has_mult_ret(self) -> bool {
172        matches!(self, ExprKind::Call | ExprKind::VarArg)
173    }
174
175    #[inline]
176    pub fn is_var(self) -> bool {
177        matches!(
178            self,
179            ExprKind::Local
180                | ExprKind::UpVal
181                | ExprKind::Const
182                | ExprKind::Indexed
183                | ExprKind::IndexUp
184                | ExprKind::IndexI
185                | ExprKind::IndexStr
186                | ExprKind::VarArgVar
187                | ExprKind::VarArgIndex
188        )
189    }
190
191    #[inline]
192    pub fn is_indexed(self) -> bool {
193        matches!(
194            self,
195            ExprKind::Indexed
196                | ExprKind::IndexUp
197                | ExprKind::IndexI
198                | ExprKind::IndexStr
199                | ExprKind::VarArgIndex
200        )
201    }
202}
203
204// ── ExprPayload ─────────────────────────────────────────────────────────────
205
206/// The payload of an [`ExprDesc`], discriminated by its sibling [`ExprKind`]
207/// (`ExprDesc::k`). Only the field(s) named for the active kind are meaningful;
208/// the rest are unused for that kind.
209///
210/// This is intentionally a flat struct rather than a tagged `enum` carrying
211/// per-variant data. Folding it into one is a deliberate **recorded
212/// honest-negative** (see the Sprint-1 recipe ledger): the kind and the payload
213/// are set in separate statements throughout codegen (e.g. `init_exp` writes a
214/// dummy `info` for every kind, then the caller overwrites the real field), and
215/// several helpers take the kind and the payload as separate arguments — shapes
216/// an enum's "the variant *is* the data" model cannot express without an invalid
217/// intermediate. The behavioral invariant (which field each kind uses) is held
218/// by the bytecode-parity oracle, not by the type system here.
219#[derive(Debug, Clone, Default)]
220pub struct ExprPayload {
221    pub ival: i64,
222    pub nval: f64,
223    pub strval: Option<GcRef<LuaString>>,
224    pub info: i32,
225    pub ind_idx: i16,
226    pub ind_t: u8,
227    pub var_ridx: u8,
228    pub var_vidx: u16,
229    /// The materialized value of a [`ExprKind::Const`] (`VCONST`) expression: a
230    /// snapshot of the resolved `<const>` compile-time constant's stored value,
231    /// copied out of the owning function's `VarDesc::const_val` by [`searchvar`]
232    /// at resolution time. `Some` only for `ExprKind::Const`; `None` for every
233    /// other kind.
234    ///
235    /// This snapshot exists so that constant discharge (`cg_exp2const`'s
236    /// const-of-const arm and `cg_discharge_vars`'s `Const` arm) can read the
237    /// value from the `ExprDesc` alone. Those run in `FuncState`-only codegen
238    /// contexts that hold no reference to `LexState`/`DynData`, so they cannot
239    /// re-read `dyd.actvar[info].const_val` the way C's `const2val` does; the
240    /// absolute index in `u.info` is still kept for [`check_readonly`].
241    pub const_snapshot: Option<LuaValue>,
242    /// Lua 5.5: when this expression resolves a global that was declared
243    /// `global x <const>`, the declared name is recorded here so that an
244    /// assignment to it is rejected by [`check_readonly`]. `None` for every
245    /// other expression (and on all pre-5.5 versions).
246    pub global_const_name: Option<GcRef<LuaString>>,
247}
248
249// ── ExprDesc ────────────────────────────────────────────────────────────────
250
251/// Field `t`/`f` are patch-lists for short-circuit boolean evaluation.
252#[derive(Debug, Clone)]
253pub struct ExprDesc {
254    pub k: ExprKind,
255    pub u: ExprPayload,
256    pub t: i32,
257    pub f: i32,
258}
259
260impl Default for ExprDesc {
261    fn default() -> Self {
262        ExprDesc {
263            k: ExprKind::Void,
264            u: ExprPayload::default(),
265            t: NO_JUMP,
266            f: NO_JUMP,
267        }
268    }
269}
270
271// ── VarDesc ─────────────────────────────────────────────────────────────────
272
273/// A compile-time variable descriptor. `const_val` is only meaningful when
274/// `kind == VarKind::CompileTimeConst`; for every other kind it is unused. Kept
275/// as a flat struct for the same reason as [`ExprPayload`] (see that type's
276/// note and the Sprint-1 honest-negative).
277#[derive(Debug, Clone)]
278pub struct VarDesc {
279    pub kind: VarKind,
280    pub ridx: u8,
281    pub pidx: i16,
282    pub name: Option<GcRef<LuaString>>,
283    pub const_val: LuaValue,
284}
285
286impl Default for VarDesc {
287    fn default() -> Self {
288        VarDesc {
289            kind: VarKind::Reg,
290            ridx: 0,
291            pidx: 0,
292            name: None,
293            const_val: LuaValue::Nil,
294        }
295    }
296}
297
298// ── LabelDesc ───────────────────────────────────────────────────────────────
299
300#[derive(Debug, Clone)]
301pub struct LabelDesc {
302    pub name: Option<GcRef<LuaString>>,
303    pub pc: i32,
304    pub line: i32,
305    pub nactvar: u8,
306    pub close: bool,
307}
308
309#[derive(Debug, Clone)]
310pub struct ScopeBarrier {
311    pub level: u8,
312    pub name: GcRef<LuaString>,
313}
314
315// ── DynData ─────────────────────────────────────────────────────────────────
316
317/// C stored C-style dynamic arrays (arr/n/size); Rust uses Vec.
318#[derive(Debug, Default)]
319pub struct DynData {
320    pub actvar: Vec<VarDesc>,
321    pub gt: Vec<LabelDesc>,
322    pub label: Vec<LabelDesc>,
323}
324
325// ── BlockCnt ────────────────────────────────────────────────────────────────
326
327/// In C: stack-allocated, chained via raw `*previous` pointer.
328/// In Rust: heap-allocated in an `Option<Box<BlockCnt>>` chain on FuncState.
329#[derive(Debug)]
330pub struct BlockCnt {
331    pub previous: Option<Box<BlockCnt>>,
332    pub firstlabel: i32,
333    pub firstgoto: i32,
334    pub nactvar: u8,
335    pub scope_level: u8,
336    pub upval: bool,
337    pub isloop: bool,
338    pub insidetbc: bool,
339    /// Lua 5.5: the `global`-declaration scope state (LexState `global_strict`
340    /// and the length of `declared_globals`) saved on block entry and restored
341    /// on exit, so a `global` declaration is scoped to its enclosing block —
342    /// e.g. `do global x end` does not leak strict mode past the block.
343    pub saved_global_strict: bool,
344    pub saved_declared_globals: usize,
345    /// Lua 5.5: the `global *` wildcard flag saved on block entry and restored
346    /// on exit, so a `global *` is scoped to its enclosing block.
347    pub saved_global_wildcard: bool,
348    pub saved_global_wildcard_const: bool,
349    pub saved_scope_barriers: usize,
350}
351
352// ── FuncState ───────────────────────────────────────────────────────────────
353
354/// Per-function compilation state. One per function being compiled; nested
355/// functions chain through `prev` (innermost first), heap-allocated as an
356/// `Option<Box<FuncState>>` owned by [`LexState`].
357#[derive(Debug)]
358pub struct FuncState {
359    /// The prototype under construction, owned outright (rather than behind the
360    /// GC's `RefCell`) for the duration of compilation; [`close_func`] hands it
361    /// to the GC or the parent function at close time.
362    pub f: Box<LuaProto>,
363    pub prev: Option<Box<FuncState>>,
364    pub bl: Option<Box<BlockCnt>>,
365    pub pc: i32,
366    pub lasttarget: i32,
367    pub previousline: i32,
368    pub nk: i32,
369    pub np: i32,
370    pub nabslineinfo: i32,
371    pub firstlocal: i32,
372    pub firstlabel: i32,
373    pub ndebugvars: i16,
374    pub nactvar: u8,
375    /// The number of active-variable registers actually occupied on the VM
376    /// stack — C's `luaY_nvarstack(fs)` / `reglevel(fs, fs->nactvar)`. Equal to
377    /// `nactvar` while every active variable is a real register-backed local,
378    /// but strictly less once a `<const>` compile-time constant (`RDKCTC`) is in
379    /// scope, since such a variable is counted by `nactvar` yet consumes no
380    /// register. This is the watermark every register-bound codegen helper
381    /// (`cg_free_reg`, `cg_exp_to_any_reg`, `cg_free_reg_if_temp`) must compare
382    /// against instead of `nactvar`; it is maintained by `adjust_local_vars`
383    /// and `remove_vars` (the only sites that grow/shrink the active set) so it
384    /// is readable from `FuncState`-only contexts that cannot reach `LexState`'s
385    /// `dyd.actvar` to recompute `reglevel`.
386    pub nactvar_reg: u8,
387    pub first_scope_barrier: usize,
388    pub nups: u8,
389    pub freereg: u8,
390    pub iwthabs: u8,
391    pub needclose: bool,
392    /// Current `ls.lastline`, mirrored on every `sync_from_lex`. [`emit_inst`]
393    /// attributes each instruction's line to the just-consumed token via this
394    /// field, instead of whatever `line` the caller threaded down. The threaded
395    /// `line` parameter survives only for explicit line-fixup overrides.
396    pub last_token_line: i32,
397}
398
399// ── ConsControl ─────────────────────────────────────────────────────────────
400
401/// Table-constructor accumulator. `t` is a *copy* of the table-expression
402/// descriptor rather than a reference into the caller; a routine that mutates
403/// it must write the result back into the caller's descriptor itself.
404#[derive(Debug)]
405pub struct ConsControl {
406    pub v: ExprDesc,
407    pub t: ExprDesc,
408    pub nh: i32,
409    pub na: i32,
410    pub tostore: i32,
411}
412
413// ── LhsAssign ───────────────────────────────────────────────────────────────
414
415/// One link in a multiple-assignment target list, chained innermost-first
416/// through `prev` as an `Option<Box<...>>`.
417#[derive(Debug)]
418pub struct LhsAssign {
419    pub prev: Option<Box<LhsAssign>>,
420    pub v: ExprDesc,
421}
422
423// ── Unary / binary operator enums ───────────────────────────────────────────
424
425/// Unary operators recognized by the expression parser. `NoUnOpr` is the
426/// "this token is not a unary operator" sentinel returned by [`getunopr`].
427#[derive(Debug, Clone, Copy, PartialEq, Eq)]
428pub enum UnOpr {
429    Minus,
430    BNot,
431    Not,
432    Len,
433    NoUnOpr,
434}
435
436/// Binary operators recognized by the expression parser, in the discriminant
437/// order that indexes [`PRIORITY`]. `NoBinOpr` is the "not a binary operator"
438/// sentinel returned by [`getbinopr`].
439#[derive(Debug, Clone, Copy, PartialEq, Eq)]
440pub enum BinOpr {
441    Add,
442    Sub,
443    Mul,
444    Mod,
445    Pow,
446    Div,
447    IDiv,
448    BAnd,
449    BOr,
450    BXor,
451    Shl,
452    Shr,
453    Concat,
454    Eq,
455    Lt,
456    Le,
457    Ne,
458    Gt,
459    Ge,
460    And,
461    Or,
462    NoBinOpr,
463}
464
465/// Indexed by BinOpr discriminant (0 = Add, ... 20 = Or).
466const PRIORITY: [(u8, u8); 21] = [
467    (10, 10),
468    (10, 10), // Add, Sub
469    (11, 11),
470    (11, 11), // Mul, Mod
471    (14, 13), // Pow (right-associative)
472    (11, 11),
473    (11, 11), // Div, IDiv
474    (6, 6),
475    (4, 4),
476    (5, 5), // BAnd, BOr, BXor
477    (7, 7),
478    (7, 7), // Shl, Shr
479    (9, 8), // Concat (right-associative)
480    (3, 3),
481    (3, 3),
482    (3, 3), // Eq, Lt, Le
483    (3, 3),
484    (3, 3),
485    (3, 3), // Ne, Gt, Ge
486    (2, 2),
487    (1, 1), // And, Or
488];
489
490/// Re-export of the canonical opcode enum so downstream crates that consume
491/// emitted prototypes can name opcodes without depending on `lua-code` directly.
492pub use lua_code::opcodes::OpCode;
493
494// ── LexState ─────────────────────────────────────────────────────────────────
495
496/// Semantic info attached to a token.
497#[derive(Debug, Clone, Default)]
498pub struct TokenValue {
499    pub r: f64,
500    pub i: i64,
501    pub ts: Option<GcRef<LuaString>>,
502}
503
504#[derive(Debug, Clone, Default)]
505pub struct LexToken {
506    pub token: TokenKind,
507    pub seminfo: TokenValue,
508}
509
510/// The parser's working state: the current and lookahead tokens, the active
511/// [`FuncState`] chain, dynamic name/label/goto data, and the parser-side flags
512/// for Lua 5.5 `global` scoping. It embeds the lexer's own state in [`Self::lex`]
513/// and drives it through [`lex_next`] / [`lex_lookahead`]; the two layers stay
514/// separate so the lexer remains usable on its own.
515pub struct LexState {
516    pub current: i32,
517    pub linenumber: i32,
518    pub lastline: i32,
519    pub t: LexToken,
520    pub lookahead: LexToken,
521    pub fs: Option<Box<FuncState>>,
522    pub dyd: DynData,
523    pub source: Option<GcRef<LuaString>>,
524    pub envn: Option<GcRef<LuaString>>,
525    /// Underlying lexer state that owns the ZIO stream and lex buffer.
526    /// The parser drives the lexer by calling `lex_next` / `lex_lookahead`,
527    /// which forward to `lua_lex::next` / `lua_lex::lookahead` on this inner
528    /// state and then mirror the resulting token into `self.t` / `self.lookahead`.
529    pub lex: lua_lex::LexState,
530    /// Parser recursion depth, bounded by the [`enter_level`] / [`leave_level`]
531    /// guard against runaway nesting (the "C stack overflow" error).
532    pub recursion_depth: u32,
533    /// Lua 5.5 global-declaration mode (manual §2.2). A chunk begins with an
534    /// implicit `global *` (`false` here): every free name is a global, as in
535    /// 5.4. The first explicit `global name, …` declaration flips this to
536    /// `true` ("strict"), after which a free name must appear in
537    /// [`Self::declared_globals`] or it is a compile-time error. `global *`
538    /// flips it back to `false`. Only ever set on the 5.5 path (the lexer emits
539    /// `TK_GLOBAL` only there), so pre-5.5 versions are unaffected.
540    pub global_strict: bool,
541    /// Lua 5.5: whether a `global *` (the wildcard declaration) is in effect for
542    /// the current scope. When `true`, every free name is a global regardless of
543    /// [`Self::global_strict`] — the wildcard suppresses the "not declared"
544    /// error. Upstream represents `*` as a `new_varkind(ls, NULL, ...)` entry
545    /// that coexists with named `global` declarations; a later `global name`
546    /// does NOT void an active `*`. Block-scoped (saved/restored like
547    /// [`Self::declared_globals`]).
548    pub global_wildcard: bool,
549    /// Whether the active explicit `global *` wildcard was declared `<const>`.
550    /// Named global declarations still win for their own names; this applies
551    /// only to otherwise free globals resolved through the wildcard.
552    pub global_wildcard_const: bool,
553    /// Names declared via `global`, each paired with whether it was declared
554    /// `<const>` (read-only). Consulted by name resolution under
555    /// [`Self::global_strict`].
556    pub declared_globals: Vec<(GcRef<LuaString>, bool)>,
557    /// Lua 5.5 `global` declarations participate in goto scope checks like
558    /// locals, but they do not occupy VM registers. Keep that bookkeeping
559    /// separate from `FuncState::nactvar` so codegen remains register-stable.
560    pub scope_barriers: Vec<ScopeBarrier>,
561}
562
563const PARSER_MAX_C_CALLS: u32 = 200;
564
565/// Guards parser recursion depth, mirroring C's `enterlevel` / `nCcalls`.
566///
567/// Lua 5.1's `enterlevel` (lparser.c) raised the *lexer* error
568/// `chunk has too many syntax levels` (a source-located message with no
569/// `near '<token>'` suffix, the `luaX_lexerror(ls, msg, 0)` path) when the
570/// recursion counter passed `LUAI_MAXCCALLS`. Lua 5.2 and 5.3 replaced that
571/// with the syntax error `too many C levels (limit is 200) in <where>` (with a
572/// source location and `near '<token>'` suffix, the `checklimit`/`errorlimit`
573/// path of those versions' `lparser.c`). Lua 5.4 replaced *that* with a bare
574/// runtime `C stack overflow` with no location, which is what 5.4/5.5 keep.
575fn enter_level(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
576    ls.recursion_depth += 1;
577    if ls.recursion_depth < PARSER_MAX_C_CALLS {
578        return Ok(());
579    }
580    match state.global().lua_version {
581        lua_types::LuaVersion::V51 => Err(lua_lex::sem_error(
582            &mut ls.lex,
583            b"chunk has too many syntax levels",
584        )),
585        lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53 => {
586            let fs = ls.fs.as_ref().unwrap();
587            let where_clause: Vec<u8> = if fs.f.linedefined == 0 {
588                b"main function".to_vec()
589            } else {
590                format!("function at line {}", fs.f.linedefined).into_bytes()
591            };
592            let mut msg: Vec<u8> = Vec::new();
593            msg.extend_from_slice(b"too many C levels (limit is ");
594            msg.extend_from_slice(PARSER_MAX_C_CALLS.to_string().as_bytes());
595            msg.extend_from_slice(b") in ");
596            msg.extend_from_slice(&where_clause);
597            Err(lua_lex::syntax_error(&mut ls.lex, &msg))
598        }
599        _ => Err(LuaError::syntax(format_args!("C stack overflow"))),
600    }
601}
602
603fn leave_level(ls: &mut LexState) {
604    ls.recursion_depth = ls.recursion_depth.saturating_sub(1);
605}
606
607/// Advance the lexer one token and mirror the resulting state into the
608/// parser's outer [`LexState`] fields.
609fn lex_next(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
610    lua_lex::next(state, &mut ls.lex)?;
611    sync_from_lex(ls);
612    Ok(())
613}
614
615/// Populate the lookahead token and mirror lexer state into the parser's outer
616/// [`LexState`].
617fn lex_lookahead(ls: &mut LexState, state: &mut LuaState) -> Result<TokenKind, LuaError> {
618    let kind = lua_lex::lookahead(state, &mut ls.lex)?;
619    sync_from_lex(ls);
620    Ok(kind)
621}
622
623/// Copy lexer-side current/line/token/lookahead values back into the parser's
624/// outer LexState. Used after every `lua_lex::next` / `lua_lex::lookahead`.
625fn sync_from_lex(ls: &mut LexState) {
626    ls.current = ls.lex.current;
627    ls.linenumber = ls.lex.linenumber;
628    ls.lastline = ls.lex.lastline;
629    ls.t = LexToken {
630        token: ls.lex.t.kind,
631        seminfo: local_token_value(&ls.lex.t.value),
632    };
633    ls.lookahead = LexToken {
634        token: ls.lex.lookahead.kind,
635        seminfo: local_token_value(&ls.lex.lookahead.value),
636    };
637    // Mirror lastline into the active FuncState so emit_inst can read it
638    // without needing access to LexState. This matches lua-c's
639    // `savelineinfo(fs, f, fs->ls->lastline)` semantics.
640    if let Some(fs) = ls.fs.as_mut() {
641        fs.last_token_line = ls.lastline;
642    }
643}
644
645/// Re-export of the VM state type the parser threads through codegen.
646pub use lua_vm::state::LuaState;
647
648// ── Inline codegen (single-pass bytecode emission) ──────────────────────────
649//
650// The bytecode generator is folded into this crate (the standalone `lua-code`
651// crate is only the opcode tables / `Instruction` encoding). The `cg_*`
652// functions below emit instructions, allocate and free registers, build the
653// constant table, compute jump offsets, fold constants, and attribute line
654// info — single-pass, as each expression and statement is parsed.
655//
656// This emission/register/jump/line-info/constant-fold core is deliberately
657// kept structurally faithful to its original shape (the hot-loop exception in
658// the idiomatization roadmap): its instruction ordering, register LIFO
659// discipline, and constant-insertion order are the load-bearing details the
660// bytecode-parity oracle pins. Idiomatize *around* it, not *through* it.
661
662fn emit_inst(fs: &mut FuncState, line: i32, inst: lua_code::opcodes::Instruction) -> i32 {
663    const MAX_IWTH_ABS: i32 = 128;
664    const LIM_LINE_DIFF: i32 = 0x80;
665    const ABS_LINE_INFO: i8 = -0x80i8;
666    let pc = fs.pc as usize;
667    if fs.f.code.len() <= pc {
668        fs.f.code
669            .resize(pc + 1, lua_types::opcode::Instruction::default());
670    }
671    fs.f.code[pc] = lua_types::opcode::Instruction::new(inst.0);
672    if fs.f.lineinfo.len() <= pc {
673        fs.f.lineinfo.resize(pc + 1, 0i8);
674    }
675    let linedif_raw = line - fs.previousline;
676    let need_abs = linedif_raw.abs() >= LIM_LINE_DIFF || {
677        let over = fs.iwthabs as i32 >= MAX_IWTH_ABS;
678        if !over {
679            fs.iwthabs += 1;
680        }
681        over
682    };
683    if need_abs {
684        fs.f.abslineinfo.push(AbsLineInfo {
685            pc: pc as i32,
686            line,
687        });
688        fs.nabslineinfo += 1;
689        fs.f.lineinfo[pc] = ABS_LINE_INFO;
690        fs.iwthabs = 1;
691    } else {
692        fs.f.lineinfo[pc] = linedif_raw as i8;
693    }
694    fs.previousline = line;
695    let result = fs.pc;
696    fs.pc += 1;
697    result
698}
699
700fn add_k_value(fs: &mut FuncState, v: LuaValue) -> i32 {
701    let idx = fs.nk;
702    if (fs.f.k.len() as i32) <= idx {
703        fs.f.k.resize((idx + 1) as usize, LuaValue::Nil);
704    }
705    fs.f.k[idx as usize] = v;
706    fs.nk += 1;
707    idx
708}
709
710fn add_k_string(fs: &mut FuncState, s: GcRef<LuaString>) -> i32 {
711    for (i, k) in fs.f.k.iter().take(fs.nk as usize).enumerate() {
712        if let LuaValue::Str(existing) = k {
713            if GcRef::ptr_eq(existing, &s) {
714                return i as i32;
715            }
716        }
717    }
718    add_k_value(fs, LuaValue::Str(s))
719}
720
721fn bump_maxstack(fs: &mut FuncState, n: u8) {
722    if fs.f.maxstacksize < n {
723        fs.f.maxstacksize = n;
724    }
725}
726
727fn reserve_reg(fs: &mut FuncState) -> Result<u8, LuaError> {
728    if fs.freereg == u8::MAX {
729        return Err(LuaError::syntax(format_args!(
730            "function or expression needs too many registers"
731        )));
732    }
733    let r = fs.freereg;
734    fs.freereg += 1;
735    bump_maxstack(fs, fs.freereg);
736    Ok(r)
737}
738
739fn reserve_regs(fs: &mut FuncState, n: i32) -> Result<(), LuaError> {
740    let newstack = fs.freereg as i32 + n;
741    if newstack >= 255 {
742        return Err(LuaError::syntax(format_args!(
743            "function or expression needs too many registers"
744        )));
745    }
746    fs.freereg = newstack as u8;
747    bump_maxstack(fs, fs.freereg);
748    Ok(())
749}
750
751/// Free `reg` if it sits above the active-local register watermark.
752///
753/// Mirrors C's `freereg` from `lcode.c`: registers below `luaY_nvarstack(fs)`
754/// belong to register-backed declared locals and must not be popped;
755/// temporaries above that watermark are freed by decrementing `fs.freereg`.
756/// The watermark is [`FuncState::nactvar_reg`], not `nactvar`, so a `<const>`
757/// compile-time constant (which `nactvar` counts but occupies no register)
758/// does not make a temporary look like a local.
759fn cg_free_reg(fs: &mut FuncState, reg: i32) {
760    if reg >= fs.nactvar_reg as i32 {
761        debug_assert_eq!(reg, fs.freereg as i32 - 1);
762        fs.freereg = fs.freereg.saturating_sub(1);
763    }
764}
765
766/// Free the temporary register held by `e` if any.
767///
768/// Mirrors C's `freeexp` from `lcode.c`: only `VNONRELOC` carries a concrete
769/// register that may need releasing.
770fn cg_free_exp(fs: &mut FuncState, e: &ExprDesc) {
771    if e.k == ExprKind::NonReloc {
772        cg_free_reg(fs, e.u.info);
773    }
774}
775
776/// Free temporary registers held by `e1` and `e2`, releasing the higher
777/// register first so the LIFO invariant on `fs.freereg` holds.
778///
779/// Mirrors C's `freeexps` from `lcode.c`.
780fn cg_free_exps(fs: &mut FuncState, e1: &ExprDesc, e2: &ExprDesc) {
781    let r1 = if e1.k == ExprKind::NonReloc {
782        e1.u.info
783    } else {
784        -1
785    };
786    let r2 = if e2.k == ExprKind::NonReloc {
787        e2.u.info
788    } else {
789        -1
790    };
791    if r1 > r2 {
792        cg_free_reg(fs, r1);
793        cg_free_reg(fs, r2);
794    } else {
795        cg_free_reg(fs, r2);
796        cg_free_reg(fs, r1);
797    }
798}
799
800/// Constant-folding `luaK_posfix` for arithmetic binary operators where both
801/// operands are already numeric literals (`KInt` / `KFlt`). Mirrors the
802/// `constfolding` branch in C's `luaK_posfix`: when both operands are
803/// numerals, the result is computed at compile time and stored back into
804/// `e1`. Non-foldable arithmetic follows Lua 5.4's immediate/K preference
805/// (`OP_ADDI`, `OP_ADDK`, `OP_MULK`, ...) before falling back to the
806/// two-register emit path (`OP_ADD` ... `OP_SHR`) plus an `OP_MMBIN`
807/// metamethod-dispatch instruction. `Concat` is delegated to
808/// `cg_emit_concat`; comparisons to `cg_emit_order` / `cg_emit_eq`;
809/// `And` / `Or` short-circuit jumps to `cg_concat`.
810/// Floor modulo with C-Lua semantics (`luaV_mod`, lvm.c): result takes the
811/// divisor's sign; `n == -1` short-circuits to 0 to avoid `i64::MIN % -1`
812/// overflow, matching C's castS2U special case.
813fn fold_int_mod(m: i64, n: i64) -> i64 {
814    if n == -1 {
815        return 0;
816    }
817    let r = m % n;
818    if r != 0 && (r ^ n) < 0 {
819        r + n
820    } else {
821        r
822    }
823}
824
825/// Floor division with C-Lua semantics (`luaV_idiv`, lvm.c): rounds toward
826/// negative infinity; `n == -1` short-circuits to wrapping negation to
827/// avoid `i64::MIN / -1` overflow, matching C's castS2U special case.
828fn fold_int_idiv(m: i64, n: i64) -> i64 {
829    if n == -1 {
830        return m.wrapping_neg();
831    }
832    let q = m / n;
833    if (m ^ n) < 0 && m % n != 0 {
834        q - 1
835    } else {
836        q
837    }
838}
839
840/// Left shift with C-Lua semantics (`luaV_shiftl`, lvm.c): negative counts
841/// shift right LOGICALLY (unsigned), counts at or beyond the integer width
842/// produce 0.
843fn fold_int_shiftl(x: i64, y: i64) -> i64 {
844    if y < 0 {
845        if y <= -64 {
846            0
847        } else {
848            ((x as u64) >> (-y as u32)) as i64
849        }
850    } else if y >= 64 {
851        0
852    } else {
853        ((x as u64) << (y as u32)) as i64
854    }
855}
856
857fn cg_posfix_fold(
858    fs: &mut FuncState,
859    op: BinOpr,
860    e1: &mut ExprDesc,
861    e2: &mut ExprDesc,
862    line: i32,
863) -> Result<(), LuaError> {
864    // Lua C records line info at emit time from `ls->lastline`. By the time
865    // postfix code runs, the RHS has already been parsed, so discharging RHS
866    // indexed expressions must use the current token line, not the saved
867    // operator line. The operator line is still used below for the binop/MMBIN
868    // instructions themselves.
869    let rhs_line = fs.last_token_line;
870    cg_discharge_vars(fs, rhs_line, e2)?;
871
872    let promote = |k: ExprKind, u: &ExprPayload| -> Option<f64> {
873        match k {
874            ExprKind::KInt => Some(u.ival as f64),
875            ExprKind::KFlt => Some(u.nval),
876            _ => None,
877        }
878    };
879
880    let foldable = e1.t == NO_JUMP && e1.f == NO_JUMP && e2.t == NO_JUMP && e2.f == NO_JUMP;
881
882    if foldable {
883        if let (ExprKind::KInt, ExprKind::KInt) = (e1.k, e2.k) {
884            let a = e1.u.ival;
885            let b = e2.u.ival;
886            let r: Option<i64> = match op {
887                BinOpr::Add => Some(a.wrapping_add(b)),
888                BinOpr::Sub => Some(a.wrapping_sub(b)),
889                BinOpr::Mul => Some(a.wrapping_mul(b)),
890                BinOpr::Mod if b != 0 => Some(fold_int_mod(a, b)),
891                BinOpr::IDiv if b != 0 => Some(fold_int_idiv(a, b)),
892                BinOpr::BAnd => Some(a & b),
893                BinOpr::BOr => Some(a | b),
894                BinOpr::BXor => Some(a ^ b),
895                BinOpr::Shl => Some(fold_int_shiftl(a, b)),
896                BinOpr::Shr => Some(fold_int_shiftl(a, b.wrapping_neg())),
897                _ => None,
898            };
899            if let Some(v) = r {
900                e1.k = ExprKind::KInt;
901                e1.u.ival = v;
902                return Ok(());
903            }
904        }
905        if let (Some(a), Some(b)) = (promote(e1.k, &e1.u), promote(e2.k, &e2.u)) {
906            let r: Option<f64> = match op {
907                BinOpr::Add => Some(a + b),
908                BinOpr::Sub => Some(a - b),
909                BinOpr::Mul => Some(a * b),
910                BinOpr::Div => Some(a / b),
911                BinOpr::Pow => Some(a.powf(b)),
912                _ => None,
913            };
914            if let Some(v) = r {
915                if !v.is_nan() && v != 0.0 {
916                    e1.k = ExprKind::KFlt;
917                    e1.u.nval = v;
918                    return Ok(());
919                }
920            }
921        }
922    }
923
924    if matches!(op, BinOpr::Lt | BinOpr::Le) {
925        return cg_emit_order(fs, op, e1, e2, line);
926    }
927
928    if matches!(op, BinOpr::Gt | BinOpr::Ge) {
929        let swap_op = if matches!(op, BinOpr::Gt) {
930            BinOpr::Lt
931        } else {
932            BinOpr::Le
933        };
934        std::mem::swap(e1, e2);
935        return cg_emit_order(fs, swap_op, e1, e2, line);
936    }
937
938    if matches!(op, BinOpr::Eq | BinOpr::Ne) {
939        return cg_emit_eq(fs, op, e1, e2, line);
940    }
941
942    if matches!(op, BinOpr::And) {
943        debug_assert_eq!(e1.t, NO_JUMP);
944        cg_concat(fs, &mut e2.f, e1.f)?;
945        *e1 = e2.clone();
946        return Ok(());
947    }
948
949    if matches!(op, BinOpr::Or) {
950        debug_assert_eq!(e1.f, NO_JUMP);
951        cg_concat(fs, &mut e2.t, e1.t)?;
952        *e1 = e2.clone();
953        return Ok(());
954    }
955
956    if matches!(op, BinOpr::Concat) {
957        return cg_emit_concat(fs, e1, e2, line);
958    }
959
960    match op {
961        BinOpr::Add | BinOpr::Mul => cg_code_commutative(fs, op, e1, e2, line),
962        BinOpr::Sub => {
963            if cg_finish_bin_exp_neg(
964                fs,
965                e1,
966                e2,
967                lua_code::opcodes::OpCode::AddI,
968                line,
969                lua_types::tagmethod::TagMethod::Sub,
970            )? {
971                Ok(())
972            } else {
973                cg_code_arith(fs, op, e1, e2, false, line)
974            }
975        }
976        BinOpr::Mod | BinOpr::Pow | BinOpr::Div | BinOpr::IDiv => {
977            cg_code_arith(fs, op, e1, e2, false, line)
978        }
979        BinOpr::BAnd | BinOpr::BOr | BinOpr::BXor => cg_code_bitwise(fs, op, e1, e2, line),
980        BinOpr::Shl => cg_code_shift_left(fs, e1, e2, line),
981        BinOpr::Shr => cg_code_shift_right(fs, e1, e2, line),
982        BinOpr::Concat
983        | BinOpr::Eq
984        | BinOpr::Lt
985        | BinOpr::Le
986        | BinOpr::Ne
987        | BinOpr::Gt
988        | BinOpr::Ge
989        | BinOpr::And
990        | BinOpr::Or
991        | BinOpr::NoBinOpr => {
992            unreachable!(
993                "cg_posfix_fold reached opcode match with non-arith op {:?}",
994                op
995            )
996        }
997    }
998}
999
1000fn cg_binop_reg_opcode(op: BinOpr) -> lua_code::opcodes::OpCode {
1001    match op {
1002        BinOpr::Add => lua_code::opcodes::OpCode::Add,
1003        BinOpr::Sub => lua_code::opcodes::OpCode::Sub,
1004        BinOpr::Mul => lua_code::opcodes::OpCode::Mul,
1005        BinOpr::Mod => lua_code::opcodes::OpCode::Mod,
1006        BinOpr::Pow => lua_code::opcodes::OpCode::Pow,
1007        BinOpr::Div => lua_code::opcodes::OpCode::Div,
1008        BinOpr::IDiv => lua_code::opcodes::OpCode::IDiv,
1009        BinOpr::BAnd => lua_code::opcodes::OpCode::BAnd,
1010        BinOpr::BOr => lua_code::opcodes::OpCode::BOr,
1011        BinOpr::BXor => lua_code::opcodes::OpCode::BXOr,
1012        BinOpr::Shl => lua_code::opcodes::OpCode::Shl,
1013        BinOpr::Shr => lua_code::opcodes::OpCode::Shr,
1014        _ => unreachable!("non-value binary operator {:?}", op),
1015    }
1016}
1017
1018fn cg_binop_k_opcode(op: BinOpr) -> lua_code::opcodes::OpCode {
1019    match op {
1020        BinOpr::Add => lua_code::opcodes::OpCode::AddK,
1021        BinOpr::Sub => lua_code::opcodes::OpCode::SubK,
1022        BinOpr::Mul => lua_code::opcodes::OpCode::MulK,
1023        BinOpr::Mod => lua_code::opcodes::OpCode::ModK,
1024        BinOpr::Pow => lua_code::opcodes::OpCode::PowK,
1025        BinOpr::Div => lua_code::opcodes::OpCode::DivK,
1026        BinOpr::IDiv => lua_code::opcodes::OpCode::IDivK,
1027        BinOpr::BAnd => lua_code::opcodes::OpCode::BAndK,
1028        BinOpr::BOr => lua_code::opcodes::OpCode::BOrK,
1029        BinOpr::BXor => lua_code::opcodes::OpCode::BXOrK,
1030        _ => unreachable!("operator has no K opcode {:?}", op),
1031    }
1032}
1033
1034fn cg_binop_event(op: BinOpr) -> lua_types::tagmethod::TagMethod {
1035    match op {
1036        BinOpr::Add => lua_types::tagmethod::TagMethod::Add,
1037        BinOpr::Sub => lua_types::tagmethod::TagMethod::Sub,
1038        BinOpr::Mul => lua_types::tagmethod::TagMethod::Mul,
1039        BinOpr::Mod => lua_types::tagmethod::TagMethod::Mod,
1040        BinOpr::Pow => lua_types::tagmethod::TagMethod::Pow,
1041        BinOpr::Div => lua_types::tagmethod::TagMethod::Div,
1042        BinOpr::IDiv => lua_types::tagmethod::TagMethod::Idiv,
1043        BinOpr::BAnd => lua_types::tagmethod::TagMethod::Band,
1044        BinOpr::BOr => lua_types::tagmethod::TagMethod::Bor,
1045        BinOpr::BXor => lua_types::tagmethod::TagMethod::Bxor,
1046        BinOpr::Shl => lua_types::tagmethod::TagMethod::Shl,
1047        BinOpr::Shr => lua_types::tagmethod::TagMethod::Shr,
1048        _ => unreachable!("operator has no arithmetic metamethod {:?}", op),
1049    }
1050}
1051
1052fn cg_is_numeral(e: &ExprDesc) -> bool {
1053    e.t == NO_JUMP && e.f == NO_JUMP && matches!(e.k, ExprKind::KInt | ExprKind::KFlt)
1054}
1055
1056fn cg_is_integer(e: &ExprDesc) -> bool {
1057    e.t == NO_JUMP && e.f == NO_JUMP && e.k == ExprKind::KInt
1058}
1059
1060/// Mirrors C's `hasjumps(e)` from `lcode.c`: `e->t != e->f`. An expression
1061/// whose value is realized by a pending short-circuit jump list cannot be a
1062/// compile-time constant. Note this is the exact `t != f` form (both may be
1063/// `NO_JUMP`, in which case there are no jumps), NOT `t == NO_JUMP && f ==
1064/// NO_JUMP` — the two agree only because a genuine jump list makes exactly one
1065/// side non-`NO_JUMP`.
1066fn cg_has_jumps(e: &ExprDesc) -> bool {
1067    e.t != e.f
1068}
1069
1070/// Mirrors C's `luaK_exp2const` (`lcode.c`): if `e` is a compile-time constant,
1071/// return its value; otherwise `None`. Used by `localstat` to decide whether a
1072/// `local x <const> = <expr>` initializer folds into an `RDKCTC` constant.
1073///
1074/// Unlike C, this takes no `FuncState`: the const-of-const case reads the
1075/// snapshot already carried on the resolved [`ExprKind::Const`] expression
1076/// (§4.0.A) rather than `dyd.actvar`.
1077fn cg_exp2const(e: &ExprDesc) -> Option<LuaValue> {
1078    if cg_has_jumps(e) {
1079        return None;
1080    }
1081    match e.k {
1082        ExprKind::False => Some(LuaValue::Bool(false)),
1083        ExprKind::True => Some(LuaValue::Bool(true)),
1084        ExprKind::Nil => Some(LuaValue::Nil),
1085        ExprKind::KStr => e.u.strval.clone().map(LuaValue::Str),
1086        ExprKind::KInt => Some(LuaValue::Int(e.u.ival)),
1087        ExprKind::KFlt => Some(LuaValue::Float(e.u.nval)),
1088        ExprKind::Const => e.u.const_snapshot.clone(),
1089        _ => None,
1090    }
1091}
1092
1093fn cg_find_k_value(fs: &FuncState, v: &LuaValue) -> Option<i32> {
1094    fs.f.k
1095        .iter()
1096        .take(fs.nk as usize)
1097        .position(|existing| existing == v)
1098        .map(|idx| idx as i32)
1099}
1100
1101fn cg_k_value_index_limited(fs: &mut FuncState, value: LuaValue, maxarg: u32) -> Option<i32> {
1102    let idx = if let Some(idx) = cg_find_k_value(fs, &value) {
1103        idx
1104    } else {
1105        if fs.nk as u32 > maxarg {
1106            return None;
1107        }
1108        add_k_value(fs, value)
1109    };
1110    if idx as u32 > maxarg {
1111        None
1112    } else {
1113        Some(idx)
1114    }
1115}
1116
1117fn cg_k_string_index_limited(fs: &mut FuncState, s: GcRef<LuaString>, maxarg: u32) -> Option<i32> {
1118    for (i, k) in fs.f.k.iter().take(fs.nk as usize).enumerate() {
1119        if let LuaValue::Str(existing) = k {
1120            if GcRef::ptr_eq(existing, &s) {
1121                let idx = i as i32;
1122                return (idx as u32 <= maxarg).then_some(idx);
1123            }
1124        }
1125    }
1126    if fs.nk as u32 > maxarg {
1127        return None;
1128    }
1129    let idx = add_k_string(fs, s);
1130    (idx as u32 <= maxarg).then_some(idx)
1131}
1132
1133fn cg_exp_to_k(fs: &mut FuncState, e: &mut ExprDesc) -> bool {
1134    if !cg_is_numeral(e) {
1135        return false;
1136    }
1137    let value = match e.k {
1138        ExprKind::KInt => LuaValue::Int(e.u.ival),
1139        ExprKind::KFlt => LuaValue::Float(e.u.nval),
1140        _ => return false,
1141    };
1142    let Some(idx) = cg_k_value_index_limited(fs, value, lua_code::opcodes::MAXARG_C) else {
1143        return false;
1144    };
1145    e.k = ExprKind::K;
1146    e.u.info = idx;
1147    true
1148}
1149
1150fn cg_exp_to_int_k(fs: &mut FuncState, e: &mut ExprDesc) -> bool {
1151    if !cg_is_integer(e) {
1152        return false;
1153    }
1154    let Some(idx) =
1155        cg_k_value_index_limited(fs, LuaValue::Int(e.u.ival), lua_code::opcodes::MAXARG_C)
1156    else {
1157        return false;
1158    };
1159    e.k = ExprKind::K;
1160    e.u.info = idx;
1161    true
1162}
1163
1164fn cg_exp_to_const_k(fs: &mut FuncState, e: &mut ExprDesc, maxarg: u32) -> bool {
1165    if e.t != NO_JUMP || e.f != NO_JUMP {
1166        return false;
1167    }
1168    let idx = match e.k {
1169        ExprKind::Nil => cg_k_value_index_limited(fs, LuaValue::Nil, maxarg),
1170        ExprKind::False => cg_k_value_index_limited(fs, LuaValue::Bool(false), maxarg),
1171        ExprKind::True => cg_k_value_index_limited(fs, LuaValue::Bool(true), maxarg),
1172        ExprKind::KInt => cg_k_value_index_limited(fs, LuaValue::Int(e.u.ival), maxarg),
1173        ExprKind::KFlt => cg_k_value_index_limited(fs, LuaValue::Float(e.u.nval), maxarg),
1174        ExprKind::KStr => {
1175            let Some(s) = e.u.strval.clone() else {
1176                return false;
1177            };
1178            cg_k_string_index_limited(fs, s, maxarg)
1179        }
1180        ExprKind::K => {
1181            if e.u.info >= 0 && (e.u.info as u32) <= maxarg {
1182                Some(e.u.info)
1183            } else {
1184                None
1185            }
1186        }
1187        _ => None,
1188    };
1189    let Some(idx) = idx else {
1190        return false;
1191    };
1192    e.k = ExprKind::K;
1193    e.u.info = idx;
1194    true
1195}
1196
1197fn cg_finish_bin_exp_val(
1198    fs: &mut FuncState,
1199    e1: &mut ExprDesc,
1200    e2: &mut ExprDesc,
1201    opcode: lua_code::opcodes::OpCode,
1202    v2: u32,
1203    flip: bool,
1204    line: i32,
1205    mm_opcode: lua_code::opcodes::OpCode,
1206    event: lua_types::tagmethod::TagMethod,
1207) -> Result<(), LuaError> {
1208    let v1 = cg_exp_to_any_reg(fs, line, e1)?;
1209    let inst = lua_code::opcodes::Instruction::abck(opcode, 0, v1 as u32, v2, 0);
1210    let pc = emit_inst(fs, line, inst);
1211    cg_free_exps(fs, e1, e2);
1212    e1.u.info = pc;
1213    e1.k = ExprKind::Reloc;
1214
1215    let mm_inst =
1216        lua_code::opcodes::Instruction::abck(mm_opcode, v1 as u32, v2, event as u32, flip as u32);
1217    emit_inst(fs, line, mm_inst);
1218    Ok(())
1219}
1220
1221fn cg_code_bin_exp_val(
1222    fs: &mut FuncState,
1223    op: BinOpr,
1224    e1: &mut ExprDesc,
1225    e2: &mut ExprDesc,
1226    line: i32,
1227) -> Result<(), LuaError> {
1228    let opcode = cg_binop_reg_opcode(op);
1229    let v2 = cg_exp_to_any_reg(fs, line, e2)? as u32;
1230    cg_finish_bin_exp_val(
1231        fs,
1232        e1,
1233        e2,
1234        opcode,
1235        v2,
1236        false,
1237        line,
1238        lua_code::opcodes::OpCode::MmBin,
1239        cg_binop_event(op),
1240    )
1241}
1242
1243fn cg_code_bin_i(
1244    fs: &mut FuncState,
1245    opcode: lua_code::opcodes::OpCode,
1246    e1: &mut ExprDesc,
1247    e2: &mut ExprDesc,
1248    flip: bool,
1249    line: i32,
1250    event: lua_types::tagmethod::TagMethod,
1251) -> Result<(), LuaError> {
1252    let Some(v2) = cg_sc_int(e2) else {
1253        unreachable!("cg_code_bin_i called with non-small-integer operand");
1254    };
1255    cg_finish_bin_exp_val(
1256        fs,
1257        e1,
1258        e2,
1259        opcode,
1260        v2 as u32,
1261        flip,
1262        line,
1263        lua_code::opcodes::OpCode::MmBinI,
1264        event,
1265    )
1266}
1267
1268fn cg_code_bin_k(
1269    fs: &mut FuncState,
1270    op: BinOpr,
1271    e1: &mut ExprDesc,
1272    e2: &mut ExprDesc,
1273    flip: bool,
1274    line: i32,
1275) -> Result<(), LuaError> {
1276    let v2 = e2.u.info as u32;
1277    cg_finish_bin_exp_val(
1278        fs,
1279        e1,
1280        e2,
1281        cg_binop_k_opcode(op),
1282        v2,
1283        flip,
1284        line,
1285        lua_code::opcodes::OpCode::MmBinK,
1286        cg_binop_event(op),
1287    )
1288}
1289
1290fn cg_code_bin_no_k(
1291    fs: &mut FuncState,
1292    op: BinOpr,
1293    e1: &mut ExprDesc,
1294    e2: &mut ExprDesc,
1295    flip: bool,
1296    line: i32,
1297) -> Result<(), LuaError> {
1298    if flip {
1299        std::mem::swap(e1, e2);
1300    }
1301    cg_code_bin_exp_val(fs, op, e1, e2, line)
1302}
1303
1304fn cg_code_arith(
1305    fs: &mut FuncState,
1306    op: BinOpr,
1307    e1: &mut ExprDesc,
1308    e2: &mut ExprDesc,
1309    flip: bool,
1310    line: i32,
1311) -> Result<(), LuaError> {
1312    if cg_is_numeral(e2) && cg_exp_to_k(fs, e2) {
1313        cg_code_bin_k(fs, op, e1, e2, flip, line)
1314    } else {
1315        cg_code_bin_no_k(fs, op, e1, e2, flip, line)
1316    }
1317}
1318
1319fn cg_code_commutative(
1320    fs: &mut FuncState,
1321    op: BinOpr,
1322    e1: &mut ExprDesc,
1323    e2: &mut ExprDesc,
1324    line: i32,
1325) -> Result<(), LuaError> {
1326    let mut flip = false;
1327    if cg_is_numeral(e1) {
1328        std::mem::swap(e1, e2);
1329        flip = true;
1330    }
1331    if op == BinOpr::Add && cg_sc_int(e2).is_some() {
1332        cg_code_bin_i(
1333            fs,
1334            lua_code::opcodes::OpCode::AddI,
1335            e1,
1336            e2,
1337            flip,
1338            line,
1339            lua_types::tagmethod::TagMethod::Add,
1340        )
1341    } else {
1342        cg_code_arith(fs, op, e1, e2, flip, line)
1343    }
1344}
1345
1346fn cg_code_bitwise(
1347    fs: &mut FuncState,
1348    op: BinOpr,
1349    e1: &mut ExprDesc,
1350    e2: &mut ExprDesc,
1351    line: i32,
1352) -> Result<(), LuaError> {
1353    let mut flip = false;
1354    if cg_is_integer(e1) {
1355        std::mem::swap(e1, e2);
1356        flip = true;
1357    }
1358    if cg_is_integer(e2) && cg_exp_to_int_k(fs, e2) {
1359        cg_code_bin_k(fs, op, e1, e2, flip, line)
1360    } else {
1361        cg_code_bin_no_k(fs, op, e1, e2, flip, line)
1362    }
1363}
1364
1365fn cg_code_shift_left(
1366    fs: &mut FuncState,
1367    e1: &mut ExprDesc,
1368    e2: &mut ExprDesc,
1369    line: i32,
1370) -> Result<(), LuaError> {
1371    if cg_sc_int(e1).is_some() {
1372        std::mem::swap(e1, e2);
1373        cg_code_bin_i(
1374            fs,
1375            lua_code::opcodes::OpCode::ShlI,
1376            e1,
1377            e2,
1378            true,
1379            line,
1380            lua_types::tagmethod::TagMethod::Shl,
1381        )
1382    } else if cg_finish_bin_exp_neg(
1383        fs,
1384        e1,
1385        e2,
1386        lua_code::opcodes::OpCode::ShrI,
1387        line,
1388        lua_types::tagmethod::TagMethod::Shl,
1389    )? {
1390        Ok(())
1391    } else {
1392        cg_code_bin_exp_val(fs, BinOpr::Shl, e1, e2, line)
1393    }
1394}
1395
1396fn cg_code_shift_right(
1397    fs: &mut FuncState,
1398    e1: &mut ExprDesc,
1399    e2: &mut ExprDesc,
1400    line: i32,
1401) -> Result<(), LuaError> {
1402    if cg_sc_int(e2).is_some() {
1403        cg_code_bin_i(
1404            fs,
1405            lua_code::opcodes::OpCode::ShrI,
1406            e1,
1407            e2,
1408            false,
1409            line,
1410            lua_types::tagmethod::TagMethod::Shr,
1411        )
1412    } else {
1413        cg_code_bin_exp_val(fs, BinOpr::Shr, e1, e2, line)
1414    }
1415}
1416
1417fn cg_finish_bin_exp_neg(
1418    fs: &mut FuncState,
1419    e1: &mut ExprDesc,
1420    e2: &mut ExprDesc,
1421    opcode: lua_code::opcodes::OpCode,
1422    line: i32,
1423    event: lua_types::tagmethod::TagMethod,
1424) -> Result<bool, LuaError> {
1425    if e2.k != ExprKind::KInt || e2.t != NO_JUMP || e2.f != NO_JUMP {
1426        return Ok(false);
1427    }
1428    let i2 = e2.u.ival;
1429    let Some(neg_i2) = i2.checked_neg() else {
1430        return Ok(false);
1431    };
1432    let biased = (i2 as i128) + (lua_code::opcodes::OFFSET_S_C as i128);
1433    let neg_biased = (neg_i2 as i128) + (lua_code::opcodes::OFFSET_S_C as i128);
1434    if !(0..=lua_code::opcodes::MAXARG_C as i128).contains(&biased)
1435        || !(0..=lua_code::opcodes::MAXARG_C as i128).contains(&neg_biased)
1436    {
1437        return Ok(false);
1438    }
1439
1440    let v1 = cg_exp_to_any_reg(fs, line, e1)?;
1441    let inst = lua_code::opcodes::Instruction::abck(opcode, 0, v1 as u32, neg_biased as u32, 0);
1442    let pc = emit_inst(fs, line, inst);
1443    cg_free_exps(fs, e1, e2);
1444    e1.u.info = pc;
1445    e1.k = ExprKind::Reloc;
1446
1447    let mm_inst = lua_code::opcodes::Instruction::abck(
1448        lua_code::opcodes::OpCode::MmBinI,
1449        v1 as u32,
1450        biased as u32,
1451        event as u32,
1452        0,
1453    );
1454    emit_inst(fs, line, mm_inst);
1455    Ok(true)
1456}
1457
1458/// Mirrors C's `codeorder` from `lcode.c` for relational binops (`<`, `<=`,
1459/// `>`, `>=`). Emits a comparison opcode (with `k = 1`) followed by an
1460/// `OP_JMP` with offset `NO_JUMP`; the resulting `VJMP` expression carries
1461/// the jump's pc in `e1.u.info` so the surrounding control-flow logic can
1462/// patch it. When one operand is a small-integer literal that fits the
1463/// signed-C field, the immediate forms (`OP_LTI` / `OP_GTI`) are used;
1464/// otherwise both operands are discharged to registers and the register
1465/// form (`OP_LT`) is emitted.
1466fn cg_emit_order(
1467    fs: &mut FuncState,
1468    op: BinOpr,
1469    e1: &mut ExprDesc,
1470    e2: &mut ExprDesc,
1471    line: i32,
1472) -> Result<(), LuaError> {
1473    debug_assert!(matches!(op, BinOpr::Lt | BinOpr::Le));
1474    let is_le = matches!(op, BinOpr::Le);
1475    let (op_imm_e2, op_imm_e1, op_reg) = if is_le {
1476        (
1477            lua_code::opcodes::OpCode::LeI,
1478            lua_code::opcodes::OpCode::GeI,
1479            lua_code::opcodes::OpCode::Le,
1480        )
1481    } else {
1482        (
1483            lua_code::opcodes::OpCode::LtI,
1484            lua_code::opcodes::OpCode::GtI,
1485            lua_code::opcodes::OpCode::Lt,
1486        )
1487    };
1488    let (r1, r2, cmp_op, isfloat) = if let Some((im, isf)) = cg_sc_number(e2) {
1489        let r1 = cg_exp_to_any_reg(fs, line, e1)?;
1490        (r1, im, op_imm_e2, isf)
1491    } else if let Some((im, isf)) = cg_sc_number(e1) {
1492        let r1 = cg_exp_to_any_reg(fs, line, e2)?;
1493        (r1, im, op_imm_e1, isf)
1494    } else {
1495        let r2 = cg_exp_to_any_reg(fs, line, e2)?;
1496        let r1 = cg_exp_to_any_reg(fs, line, e1)?;
1497        (r1, r2, op_reg, false)
1498    };
1499    cg_free_exps(fs, e1, e2);
1500    let cmp =
1501        lua_code::opcodes::Instruction::abck(cmp_op, r1 as u32, r2 as u32, isfloat as u32, 1);
1502    emit_inst(fs, line, cmp);
1503    let jmp_arg = (NO_JUMP + lua_code::opcodes::OFFSET_S_J) as u32;
1504    let jmp = lua_code::opcodes::Instruction::sj(lua_code::opcodes::OpCode::Jmp, jmp_arg, 0);
1505    let jmp_pc = emit_inst(fs, line, jmp);
1506    e1.u.info = jmp_pc;
1507    e1.k = ExprKind::Jmp;
1508    Ok(())
1509}
1510
1511/// Mirrors C's `codeeq` from `lcode.c` for the equality binops (`==`, `~=`).
1512/// Emits an `OP_EQI`, `OP_EQK`, or `OP_EQ` comparison followed by an `OP_JMP`
1513/// whose pc is stored in `e1.u.info`; `e1.k` becomes `VJMP`. The `k` bit
1514/// selects between `==` (k=1) and `~=` (k=0).
1515fn cg_emit_eq(
1516    fs: &mut FuncState,
1517    op: BinOpr,
1518    e1: &mut ExprDesc,
1519    e2: &mut ExprDesc,
1520    line: i32,
1521) -> Result<(), LuaError> {
1522    debug_assert!(matches!(op, BinOpr::Eq | BinOpr::Ne));
1523    if e1.k != ExprKind::NonReloc {
1524        std::mem::swap(e1, e2);
1525    }
1526    let r1 = cg_exp_to_any_reg(fs, line, e1)?;
1527    let (r2, cmp_op, isfloat) = if let Some((im, isf)) = cg_sc_number(e2) {
1528        (im, lua_code::opcodes::OpCode::EqI, isf)
1529    } else if cg_exp_to_const_k(fs, e2, lua_code::opcodes::MAXARG_B) {
1530        (e2.u.info as u8, lua_code::opcodes::OpCode::EqK, false)
1531    } else {
1532        let r = cg_exp_to_any_reg(fs, line, e2)?;
1533        (r, lua_code::opcodes::OpCode::Eq, false)
1534    };
1535    cg_free_exps(fs, e1, e2);
1536    let k_bit = if matches!(op, BinOpr::Eq) { 1 } else { 0 };
1537    let cmp =
1538        lua_code::opcodes::Instruction::abck(cmp_op, r1 as u32, r2 as u32, isfloat as u32, k_bit);
1539    emit_inst(fs, line, cmp);
1540    let jmp_pc = cg_jump(fs, line);
1541    e1.u.info = jmp_pc;
1542    e1.k = ExprKind::Jmp;
1543    Ok(())
1544}
1545
1546/// Mirrors C's `previousinstruction` from `lcode.c`: returns the index of the
1547/// last emitted instruction, but only when `pc` is past `lasttarget` (i.e. the
1548/// previous instruction is reachable without crossing a jump label). Used by
1549/// peephole merges such as the `OP_CONCAT` chain fold.
1550fn previous_instruction_idx(fs: &FuncState) -> Option<usize> {
1551    if fs.pc > fs.lasttarget {
1552        Some((fs.pc - 1) as usize)
1553    } else {
1554        None
1555    }
1556}
1557
1558/// Mirrors C's `codeconcat` from `lcode.c`. The left operand `e1` has
1559/// already been placed on the stack by `cg_infix`'s `OPR_CONCAT` arm
1560/// (`luaK_exp2nextreg`); here we only push `e2` onto the next register and
1561/// emit (or fold into) the `OP_CONCAT`. When the previous instruction is
1562/// itself an `OP_CONCAT` whose `A` register is exactly `e1.u.info + 1`,
1563/// the chain is merged by widening that instruction's `B` field;
1564/// otherwise a fresh `OP_CONCAT A=e1.u.info, B=2` is emitted. In both
1565/// branches the temporary register holding `e2` is freed.
1566fn cg_emit_concat(
1567    fs: &mut FuncState,
1568    e1: &mut ExprDesc,
1569    e2: &mut ExprDesc,
1570    line: i32,
1571) -> Result<(), LuaError> {
1572    cg_exp_to_next_reg(fs, line, e2)?;
1573
1574    if let Some(prev_idx) = previous_instruction_idx(fs) {
1575        let prev = lua_code::opcodes::Instruction(fs.f.code[prev_idx].0);
1576        if prev.opcode() == Some(lua_code::opcodes::OpCode::Concat) {
1577            let n = prev.arg_b();
1578            debug_assert_eq!(e1.u.info + 1, prev.arg_a() as i32);
1579            cg_free_exp(fs, e2);
1580            let mut updated = prev;
1581            updated.set_arg_a(e1.u.info as u32);
1582            updated.set_arg_b(n + 1);
1583            fs.f.code[prev_idx] = lua_types::opcode::Instruction::new(updated.0);
1584            return Ok(());
1585        }
1586    }
1587
1588    let inst = lua_code::opcodes::Instruction::abck(
1589        lua_code::opcodes::OpCode::Concat,
1590        e1.u.info as u32,
1591        2,
1592        0,
1593        0,
1594    );
1595    emit_inst(fs, line, inst);
1596    cg_free_exp(fs, e2);
1597    Ok(())
1598}
1599
1600/// Mirrors the `constfolding` call in C's `luaK_prefix` (`lcode.c`) for
1601/// unary minus and bitwise-not on jump-free numeric literals: folds in
1602/// place and returns `true` when the operation applies. Integer negation
1603/// wraps (`intop(-, 0, v)`); float negation refuses NaN and zero results so
1604/// `-0.0` keeps its sign as a runtime `OP_UNM`; bitwise-not requires an
1605/// operand that converts exactly to an integer (`F2Ieq`), matching
1606/// `luaO_rawarith`'s `validop`. A `false` return leaves `e` untouched and
1607/// the caller emits the register-form opcode, exactly like C falling
1608/// through to `codeunexpval`.
1609fn cg_fold_unary(op: UnOpr, e: &mut ExprDesc) -> bool {
1610    if e.t != NO_JUMP || e.f != NO_JUMP {
1611        return false;
1612    }
1613    match (op, e.k) {
1614        (UnOpr::Minus, ExprKind::KInt) => {
1615            e.u.ival = e.u.ival.wrapping_neg();
1616            true
1617        }
1618        (UnOpr::Minus, ExprKind::KFlt) => {
1619            let n = -e.u.nval;
1620            if n.is_nan() || n == 0.0 {
1621                false
1622            } else {
1623                e.u.nval = n;
1624                true
1625            }
1626        }
1627        (UnOpr::BNot, ExprKind::KInt) => {
1628            e.u.ival = !e.u.ival;
1629            true
1630        }
1631        (UnOpr::BNot, ExprKind::KFlt) => match flt_to_int_exact(e.u.nval) {
1632            Some(iv) => {
1633                e.k = ExprKind::KInt;
1634                e.u.ival = !iv;
1635                true
1636            }
1637            None => false,
1638        },
1639        _ => false,
1640    }
1641}
1642
1643/// Mirrors C's `luaK_prefix` from `lcode.c`. Discharges `e`, then for
1644/// `Minus` / `BNot` tries compile-time constant folding (`cg_fold_unary`);
1645/// when that does not apply (and always for `Len`), emits the unary opcode
1646/// via the `codeunexpval` shape (place operand in a register, emit
1647/// `OP_UNM` / `OP_BNOT` / `OP_LEN` with `A` left as 0 so the result is
1648/// relocatable). `Not` is routed through `cg_codenot`, which performs
1649/// literal folding, JMP-condition flipping, or emits `OP_NOT` for register
1650/// operands.
1651fn cg_prefix(fs: &mut FuncState, op: UnOpr, e: &mut ExprDesc, line: i32) -> Result<(), LuaError> {
1652    cg_discharge_vars(fs, line, e)?;
1653    if matches!(op, UnOpr::Minus | UnOpr::BNot) && cg_fold_unary(op, e) {
1654        return Ok(());
1655    }
1656    let opcode = match op {
1657        UnOpr::Minus => lua_code::opcodes::OpCode::Unm,
1658        UnOpr::BNot => lua_code::opcodes::OpCode::BNot,
1659        UnOpr::Len => lua_code::opcodes::OpCode::Len,
1660        UnOpr::Not => return cg_codenot(fs, line, e),
1661        UnOpr::NoUnOpr => return Ok(()),
1662    };
1663    let r = cg_exp_to_any_reg(fs, line, e)?;
1664    cg_free_exp(fs, e);
1665    let inst = lua_code::opcodes::Instruction::abck(opcode, 0, r as u32, 0, 0);
1666    let pc = emit_inst(fs, line, inst);
1667    e.u.info = pc;
1668    e.k = ExprKind::Reloc;
1669    Ok(())
1670}
1671
1672/// Return the pc of the test instruction that controls the jump at `pc`,
1673/// or `pc` itself if the jump is unconditional.
1674///
1675/// Mirrors C's `getjumpcontrol` from `lcode.c`: when `pc >= 1` and the
1676/// preceding opcode has the T-mode bit set (i.e. it's a test that is always
1677/// paired with a following `OP_JMP`), the control lives at `pc - 1`.
1678fn cg_get_jump_control(fs: &FuncState, pc: i32) -> i32 {
1679    if pc >= 1 {
1680        let prev = cg_inst_at(fs, pc - 1);
1681        if let Some(op) = prev.opcode() {
1682            if lua_code::opcodes::test_t_mode(op) {
1683                return pc - 1;
1684            }
1685        }
1686    }
1687    pc
1688}
1689
1690/// Patch the destination register of a `TESTSET` that controls the jump at
1691/// `node`. If the control isn't a `TESTSET`, returns `false`. With `reg ==
1692/// NO_REG` (or when `reg` already equals B), the instruction is rewritten to
1693/// a plain `OP_TEST` (preserving the original `k` bit) — the test no longer
1694/// produces a value.
1695///
1696/// Mirrors C's `patchtestreg` from `lcode.c`.
1697fn cg_patch_test_reg(fs: &mut FuncState, node: i32, reg: u32) -> bool {
1698    let ctrl_pc = cg_get_jump_control(fs, node);
1699    let mut inst = cg_inst_at(fs, ctrl_pc);
1700    if inst.opcode() != Some(lua_code::opcodes::OpCode::TestSet) {
1701        return false;
1702    }
1703    let b = inst.arg_b();
1704    let k = inst.arg_k();
1705    if reg != lua_code::opcodes::NO_REG && reg != b {
1706        inst.set_arg_a(reg);
1707        cg_set_inst_at(fs, ctrl_pc, inst);
1708    } else {
1709        let test =
1710            lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::Test, b, 0, 0, k);
1711        cg_set_inst_at(fs, ctrl_pc, test);
1712    }
1713    true
1714}
1715
1716/// Walk the jump-list rooted at `list` and strip every `TESTSET` of its
1717/// destination register, leaving plain `OP_TEST`s behind. Used after
1718/// `not <expr>` swaps `e.t` / `e.f`: any pending value-producing tests in
1719/// the new lists would write the unnegated value, which is wrong.
1720///
1721/// Mirrors C's `removevalues` from `lcode.c`.
1722fn cg_remove_values(fs: &mut FuncState, list: i32) {
1723    let mut walk = JumpList::new(list);
1724    while let Some(pc) = walk.next(fs) {
1725        cg_patch_test_reg(fs, pc, lua_code::opcodes::NO_REG);
1726    }
1727}
1728
1729/// Mirrors C's `codenot` from `lcode.c`. Handles constant folding for `not`
1730/// (nil/false → true; any other constant → false), flips the condition bit
1731/// of a jump-result expression, or emits `OP_NOT` for in-register operands.
1732/// After negation, `e.t` and `e.f` are swapped (the old true-exit list now
1733/// fires when the negated value is false, and vice versa) and any
1734/// value-producing tests in the new lists are downgraded to plain tests via
1735/// `cg_remove_values`.
1736fn cg_codenot(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1737    match e.k {
1738        ExprKind::Nil | ExprKind::False => {
1739            e.k = ExprKind::True;
1740        }
1741        ExprKind::K | ExprKind::KFlt | ExprKind::KInt | ExprKind::KStr | ExprKind::True => {
1742            e.k = ExprKind::False;
1743        }
1744        ExprKind::Jmp => {
1745            cg_negate_condition(fs, e);
1746        }
1747        ExprKind::Reloc | ExprKind::NonReloc => {
1748            let reg = cg_exp_to_any_reg(fs, line, e)?;
1749            cg_free_exp(fs, e);
1750            let inst = lua_code::opcodes::Instruction::abck(
1751                lua_code::opcodes::OpCode::Not,
1752                0,
1753                reg as u32,
1754                0,
1755                0,
1756            );
1757            let pc = emit_inst(fs, line, inst);
1758            e.u.info = pc;
1759            e.k = ExprKind::Reloc;
1760        }
1761        _ => debug_assert!(false, "cg_codenot: unexpected ExprKind {:?}", e.k),
1762    }
1763    std::mem::swap(&mut e.f, &mut e.t);
1764    cg_remove_values(fs, e.f);
1765    cg_remove_values(fs, e.t);
1766    Ok(())
1767}
1768
1769/// Emit OP_JMP with NO_JUMP offset; return its pc.
1770///
1771/// Mirrors C's `luaK_jump`.
1772fn cg_jump(fs: &mut FuncState, line: i32) -> i32 {
1773    let jmp_arg = (NO_JUMP + lua_code::opcodes::OFFSET_S_J) as u32;
1774    let jmp = lua_code::opcodes::Instruction::sj(lua_code::opcodes::OpCode::Jmp, jmp_arg, 0);
1775    emit_inst(fs, line, jmp)
1776}
1777
1778/// Read an instruction word from `fs.f.code` wrapped in the methodful
1779/// `lua_code::opcodes::Instruction` so accessor helpers are available.
1780fn cg_inst_at(fs: &FuncState, pc: i32) -> lua_code::opcodes::Instruction {
1781    lua_code::opcodes::Instruction(fs.f.code[pc as usize].0)
1782}
1783
1784/// Store an instruction word into `fs.f.code` from a methodful
1785/// `lua_code::opcodes::Instruction`.
1786fn cg_set_inst_at(fs: &mut FuncState, pc: i32, inst: lua_code::opcodes::Instruction) {
1787    fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(inst.0);
1788}
1789
1790/// Return the absolute pc that the jump at `pc` targets, or `NO_JUMP` if the
1791/// jump's offset field is still the sentinel.
1792fn cg_get_jump(fs: &FuncState, pc: i32) -> i32 {
1793    let offset = cg_inst_at(fs, pc).arg_s_j();
1794    if offset == NO_JUMP {
1795        NO_JUMP
1796    } else {
1797        (pc + 1) + offset
1798    }
1799}
1800
1801/// A cursor over a singly-linked jump list — the chain of pending `OP_JMP`s
1802/// threaded through their own offset fields, terminated by `NO_JUMP`.
1803///
1804/// This is a *lending* cursor rather than a plain [`Iterator`]: every visit
1805/// body mutates the same [`FuncState`] (patching the visited jump's controller
1806/// or offset), so the chain cannot be borrowed across steps. Instead the
1807/// `FuncState` is handed back in on each [`JumpList::next`] call.
1808///
1809/// Crucially, `next` computes the *following* node **before** returning the
1810/// current one, so a body may rewrite the current node's instruction without
1811/// breaking the walk — this preserves the order the hand-written loops relied
1812/// on (read-next-then-mutate). Yielding the same pc sequence as the manual
1813/// `while pc != NO_JUMP { ...; pc = cg_get_jump(fs, pc) }` is the behavioral
1814/// invariant; the jump offsets that ultimately get patched must not move.
1815struct JumpList {
1816    cur: i32,
1817}
1818
1819impl JumpList {
1820    /// Begin walking the list rooted at `list` (which may be `NO_JUMP`).
1821    fn new(list: i32) -> Self {
1822        JumpList { cur: list }
1823    }
1824
1825    /// Yield the current jump pc and advance to its successor, or `None` at the
1826    /// end of the chain. The successor is read *before* this returns, so the
1827    /// caller may rewrite the yielded node without disturbing the walk.
1828    fn next(&mut self, fs: &FuncState) -> Option<i32> {
1829        if self.cur == NO_JUMP {
1830            return None;
1831        }
1832        let pc = self.cur;
1833        self.cur = cg_get_jump(fs, pc);
1834        Some(pc)
1835    }
1836}
1837
1838/// Patch the jump at `pc` to land at absolute `dest`.
1839///
1840/// Mirrors C's `fixjump` from `lcode.c`.
1841fn cg_fix_jump(fs: &mut FuncState, pc: i32, dest: i32) -> Result<(), LuaError> {
1842    debug_assert!(dest != NO_JUMP);
1843    let offset = dest - (pc + 1);
1844    let max = lua_code::opcodes::MAXARG_S_J as i32 - lua_code::opcodes::OFFSET_S_J;
1845    let min = -lua_code::opcodes::OFFSET_S_J;
1846    if offset < min || offset > max {
1847        return Err(LuaError::syntax(format_args!("control structure too long")));
1848    }
1849    let mut inst = cg_inst_at(fs, pc);
1850    inst.set_arg_s_j(offset);
1851    cg_set_inst_at(fs, pc, inst);
1852    Ok(())
1853}
1854
1855/// Record `fs.pc` as a jump label and return it.
1856///
1857/// Mirrors C's `luaK_getlabel` from `lcode.c`.
1858fn cg_get_label(fs: &mut FuncState) -> i32 {
1859    fs.lasttarget = fs.pc;
1860    fs.pc
1861}
1862
1863/// Concatenate jump-list `l2` onto the tail of `*l1`.
1864///
1865/// Mirrors C's `luaK_concat` from `lcode.c`.
1866fn cg_concat(fs: &mut FuncState, l1: &mut i32, l2: i32) -> Result<(), LuaError> {
1867    if l2 == NO_JUMP {
1868        return Ok(());
1869    }
1870    if *l1 == NO_JUMP {
1871        *l1 = l2;
1872        return Ok(());
1873    }
1874    let mut walk = JumpList::new(*l1);
1875    let mut tail = *l1;
1876    while let Some(pc) = walk.next(fs) {
1877        tail = pc;
1878    }
1879    cg_fix_jump(fs, tail, l2)
1880}
1881
1882/// Patch every jump in the singly-linked list rooted at `list` to land at
1883/// absolute pc `target`.
1884///
1885/// Mirrors C's `luaK_patchlist`, which delegates to `patchlistaux(fs, list,
1886/// target, NO_REG, target)`: every `TESTSET` controller in the list gets
1887/// rewritten to a plain `OP_TEST` (the value-producing destination register
1888/// is no longer wanted at a fall-through target), and every jump is fixed to
1889/// `target`.
1890fn cg_patch_list(fs: &mut FuncState, list: i32, target: i32) -> Result<(), LuaError> {
1891    cg_patch_list_aux(fs, list, target, lua_code::opcodes::NO_REG, target)
1892}
1893
1894/// Patch every jump in `list` to land at the current `fs.pc`.
1895///
1896/// Mirrors C's `luaK_patchtohere` from `lcode.c`.
1897fn cg_patch_to_here(fs: &mut FuncState, list: i32) -> Result<(), LuaError> {
1898    let target = cg_get_label(fs);
1899    cg_patch_list(fs, list, target)
1900}
1901
1902/// Flip the `k` (condition) bit of the test instruction that immediately
1903/// precedes `e`'s JMP. After this, the jump fires on the opposite truth
1904/// value of the original comparison.
1905///
1906/// Mirrors C's `negatecondition` from `lcode.c`.
1907fn cg_negate_condition(fs: &mut FuncState, e: &ExprDesc) {
1908    let pc = e.u.info - 1;
1909    let mut inst = cg_inst_at(fs, pc);
1910    let k = inst.arg_k();
1911    inst.set_arg_k(k ^ 1);
1912    cg_set_inst_at(fs, pc, inst);
1913}
1914
1915/// Arrange for control to fall through when `e` is true and to jump (via the
1916/// patch list rooted at `e.f`) when `e` is false. After this call `e.t` has
1917/// been patched to the current pc and `e.f` holds the false-exit list.
1918///
1919/// Mirrors C's `luaK_goiftrue` from `lcode.c`. `VJMP` (comparison results)
1920/// negate the condition so the jump fires on false; literal-true forms emit
1921/// no jump; any other kind is forced into a register and tested with
1922/// `OP_TESTSET` via `cg_jump_on_cond`.
1923fn cg_go_if_true(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1924    cg_discharge_vars(fs, line, e)?;
1925    let pc: i32 = match e.k {
1926        ExprKind::Jmp => {
1927            cg_negate_condition(fs, e);
1928            e.u.info
1929        }
1930        ExprKind::K | ExprKind::KFlt | ExprKind::KInt | ExprKind::KStr | ExprKind::True => NO_JUMP,
1931        _ => cg_jump_on_cond(fs, line, e, 0)?,
1932    };
1933    cg_concat(fs, &mut e.f, pc)?;
1934    cg_patch_to_here(fs, e.t)?;
1935    e.t = NO_JUMP;
1936    Ok(())
1937}
1938
1939/// Mirror of `cg_go_if_true` for false short-circuit (`or` operator and
1940/// `while not <cond>` shaped control flow). Falls through when `e` is false
1941/// and jumps when true. After this call `e.f` has been patched to the
1942/// current pc and `e.t` holds the true-exit list.
1943///
1944/// Mirrors C's `luaK_goiffalse` from `lcode.c`.
1945fn cg_go_if_false(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1946    cg_discharge_vars(fs, line, e)?;
1947    let pc: i32 = match e.k {
1948        ExprKind::Jmp => e.u.info,
1949        ExprKind::Nil | ExprKind::False => NO_JUMP,
1950        _ => cg_jump_on_cond(fs, line, e, 1)?,
1951    };
1952    cg_concat(fs, &mut e.t, pc)?;
1953    cg_patch_to_here(fs, e.f)?;
1954    e.f = NO_JUMP;
1955    Ok(())
1956}
1957
1958/// Emit a conditional test (`OP_TESTSET` in general; bare `OP_TEST` when a
1959/// trailing `OP_NOT` is peephole-folded) followed by an `OP_JMP`, so control
1960/// transfers to the jump's patch list when `e`'s truth value equals `cond`.
1961/// Returns the pc of the emitted jump so the caller can append it to the
1962/// appropriate exit list. Mirrors C's `jumponcond` from `lcode.c`,
1963/// including both subtleties: the `OP_NOT` removal for `VRELOC` operands,
1964/// and discharging via `discharge2anyreg` (NOT `exp2anyreg`) so pending
1965/// jump lists survive for the caller to patch.
1966///
1967/// Mirrors C's `removelastinstruction` / `removelastlineinfo` from
1968/// `lcode.c`: drops the last emitted instruction and undoes its line-info
1969/// bookkeeping. A relative line entry rolls `previousline` / `iwthabs`
1970/// back; an absolute entry is popped and the next emit is forced absolute
1971/// by saturating `iwthabs` (C sets `MAXIWTHABS + 1`).
1972fn remove_last_instruction(fs: &mut FuncState) {
1973    const ABS_LINE_INFO: i8 = -0x80i8;
1974    let pc = (fs.pc - 1) as usize;
1975    if fs.f.lineinfo[pc] != ABS_LINE_INFO {
1976        fs.previousline -= fs.f.lineinfo[pc] as i32;
1977        fs.iwthabs -= 1;
1978    } else {
1979        debug_assert_eq!(
1980            fs.f.abslineinfo[fs.nabslineinfo as usize - 1].pc,
1981            pc as i32
1982        );
1983        fs.f.abslineinfo.pop();
1984        fs.nabslineinfo -= 1;
1985        fs.iwthabs = 129;
1986    }
1987    fs.pc -= 1;
1988}
1989
1990fn cg_jump_on_cond(
1991    fs: &mut FuncState,
1992    line: i32,
1993    e: &mut ExprDesc,
1994    cond: u8,
1995) -> Result<i32, LuaError> {
1996    if e.k == ExprKind::Reloc {
1997        let ie = lua_code::opcodes::Instruction(fs.f.code[e.u.info as usize].0);
1998        if ie.opcode() == Some(lua_code::opcodes::OpCode::Not) {
1999            remove_last_instruction(fs);
2000            let test = lua_code::opcodes::Instruction::abck(
2001                lua_code::opcodes::OpCode::Test,
2002                ie.arg_b(),
2003                0,
2004                0,
2005                (cond == 0) as u32,
2006            );
2007            emit_inst(fs, line, test);
2008            return Ok(cg_jump(fs, line));
2009        }
2010    }
2011    cg_discharge_to_any_reg(fs, line, e)?;
2012    cg_free_exp(fs, e);
2013    let reg = e.u.info;
2014    let test = lua_code::opcodes::Instruction::abck(
2015        lua_code::opcodes::OpCode::TestSet,
2016        lua_code::opcodes::NO_REG,
2017        reg as u32,
2018        0,
2019        cond as u32,
2020    );
2021    emit_inst(fs, line, test);
2022    Ok(cg_jump(fs, line))
2023}
2024
2025/// Mirrors C's `discharge2anyreg` from `lcode.c`: if `e` is not already
2026/// sitting in a register, reserve one and discharge into it. Unlike
2027/// `cg_exp_to_any_reg` (`luaK_exp2anyreg`), this does NOT resolve pending
2028/// `e.t` / `e.f` jump lists — `jumponcond` relies on that, because the
2029/// lists must stay live for the caller's `goiftrue` / `goiffalse` to patch
2030/// (that is how an `and`-chain's `TESTSET` gets demoted to `TEST` at the
2031/// following `or`).
2032fn cg_discharge_to_any_reg(
2033    fs: &mut FuncState,
2034    line: i32,
2035    e: &mut ExprDesc,
2036) -> Result<(), LuaError> {
2037    if e.k != ExprKind::NonReloc {
2038        let reg = reserve_reg(fs)?;
2039        cg_discharge_to_reg(fs, line, e, reg)?;
2040    }
2041    Ok(())
2042}
2043
2044/// First half of `luaK_posfix`: pre-process the left operand `v` of a binary
2045/// operator before the right operand is parsed. Mirrors C's `luaK_infix`
2046/// from `lcode.c`. The codegen reconciliation has not yet routed parser
2047/// calls through `lua_code::infix`, so this lives in the parser file
2048/// alongside the other `cg_*` helpers.
2049///
2050/// For `And`/`Or` the operand is converted into a short-circuit form (jump
2051/// list closed via `cg_go_if_true` / `cg_go_if_false`). For `Concat` it is
2052/// pushed onto the next register. Other arithmetic, bitwise, and comparison
2053/// operators rely on `cg_posfix_fold` to discharge their operands after the
2054/// right-hand side is known, so `cg_infix` only calls `cg_discharge_vars`
2055/// for them.
2056fn cg_infix(fs: &mut FuncState, op: BinOpr, v: &mut ExprDesc, line: i32) -> Result<(), LuaError> {
2057    // Mirrors C's `luaK_infix`, which calls `luaK_dischargevars` before the
2058    // operator switch. This turns a resolved `<const>` left operand into its
2059    // literal (`ExprKind::Const` -> KInt/KFlt/...) so the numeral tests below
2060    // can keep it foldable; without it a folded const left operand falls
2061    // through to `cg_exp_to_any_reg` and stops folding (codex HIGH-3). For
2062    // every already-discharged or non-const operand this is a no-op and the
2063    // emitted bytecode is unchanged.
2064    cg_discharge_vars(fs, line, v)?;
2065    match op {
2066        BinOpr::And => cg_go_if_true(fs, line, v),
2067        BinOpr::Or => cg_go_if_false(fs, line, v),
2068        BinOpr::Concat => cg_exp_to_next_reg(fs, line, v),
2069        BinOpr::Add
2070        | BinOpr::Sub
2071        | BinOpr::Mul
2072        | BinOpr::Div
2073        | BinOpr::IDiv
2074        | BinOpr::Mod
2075        | BinOpr::Pow
2076        | BinOpr::BAnd
2077        | BinOpr::BOr
2078        | BinOpr::BXor
2079        | BinOpr::Shl
2080        | BinOpr::Shr
2081        | BinOpr::Eq
2082        | BinOpr::Ne
2083        | BinOpr::Lt
2084        | BinOpr::Le
2085        | BinOpr::Gt
2086        | BinOpr::Ge => {
2087            if matches!(v.k, ExprKind::KInt | ExprKind::KFlt) && v.t == NO_JUMP && v.f == NO_JUMP {
2088                cg_discharge_vars(fs, line, v)
2089            } else {
2090                cg_exp_to_any_reg(fs, line, v).map(|_| ())
2091            }
2092        }
2093        _ => cg_discharge_vars(fs, line, v),
2094    }
2095}
2096
2097/// Mirrors C's `isSCint` from `lcode.c` (a restriction of `isSCnumber` to
2098/// the integer case): returns `Some(int2sC(ival))` if `e` is a `VKINT`
2099/// literal whose value fits the signed-C 8-bit operand field, else `None`.
2100/// The returned byte is already pre-encoded with the `OFFSET_sC` bias so
2101/// the caller can drop it straight into an `sC` argument slot.
2102fn cg_sc_int(e: &ExprDesc) -> Option<u8> {
2103    if !matches!(e.k, ExprKind::KInt) {
2104        return None;
2105    }
2106    if e.t != NO_JUMP || e.f != NO_JUMP {
2107        return None;
2108    }
2109    let biased = (e.u.ival as u64).wrapping_add(lua_code::opcodes::OFFSET_S_C as u64);
2110    if biased <= lua_code::opcodes::MAXARG_C as u64 {
2111        Some(biased as u8)
2112    } else {
2113        None
2114    }
2115}
2116
2117/// Exact float-to-integer conversion: C's `luaV_flttointns` with `F2Ieq`
2118/// (`lvm.c`). Succeeds only when `n` has no fractional part and the value is
2119/// representable as an `i64`; the range test mirrors `lua_numbertointeger`.
2120fn flt_to_int_exact(n: f64) -> Option<i64> {
2121    if n.floor() == n && n >= (i64::MIN as f64) && n < -(i64::MIN as f64) {
2122        Some(n as i64)
2123    } else {
2124        None
2125    }
2126}
2127
2128/// Mirrors C's `isSCnumber` from `lcode.c`: like [`cg_sc_int`] but also
2129/// accepts a float literal whose value converts exactly to an integer
2130/// (`F2Ieq`), reporting which case matched so the caller can encode the
2131/// `isfloat` flag in the comparison instruction's C slot. The VM's
2132/// metamethod fallback (`order_imm_slow` -> `call_order_i_tm`) reads that
2133/// flag to rebuild the constant with its original type, so `x < 2.0` calls
2134/// `__lt` with a float even though the immediate is stored as an integer.
2135fn cg_sc_number(e: &ExprDesc) -> Option<(u8, bool)> {
2136    let (i, isfloat) = match e.k {
2137        ExprKind::KInt => (e.u.ival, false),
2138        ExprKind::KFlt => (flt_to_int_exact(e.u.nval)?, true),
2139        _ => return None,
2140    };
2141    if e.t != NO_JUMP || e.f != NO_JUMP {
2142        return None;
2143    }
2144    let biased = (i as u64).wrapping_add(lua_code::opcodes::OFFSET_S_C as u64);
2145    if biased <= lua_code::opcodes::MAXARG_C as u64 {
2146        Some((biased as u8, isfloat))
2147    } else {
2148        None
2149    }
2150}
2151
2152fn mark_vararg_table_needed(fs: &mut FuncState) {
2153    fs.f.vararg_table_needed = true;
2154    for inst in fs.f.code.iter_mut() {
2155        let mut op = lua_code::opcodes::Instruction(inst.raw());
2156        if op.opcode() == Some(lua_code::opcodes::OpCode::VarArgPack) {
2157            op.set_arg_k(1);
2158            *inst = lua_types::opcode::Instruction::new(op.0);
2159            break;
2160        }
2161    }
2162}
2163
2164/// Lua 5.1 only: when the body uses `...` directly, stock 5.1 clears
2165/// `VARARG_NEEDSARG` (lparser.c's `fs->f->is_vararg &= ~VARARG_NEEDSARG`) so the
2166/// implicit `arg` table is never filled — but `arg` stays a declared local that
2167/// reads as nil (it shadows any global `arg`). We model this by rewriting the
2168/// entry `VARARGPACK` that would build `arg` into a `LOADNIL` of the same
2169/// register, so the local is initialized to nil at function entry instead of
2170/// holding whatever value previously occupied that stack slot.
2171fn clear_arg_table_needed(fs: &mut FuncState) {
2172    for inst in fs.f.code.iter_mut() {
2173        let op = lua_code::opcodes::Instruction(inst.raw());
2174        if op.opcode() == Some(lua_code::opcodes::OpCode::VarArgPack) {
2175            let arg_reg = op.arg_a();
2176            let load_nil = lua_code::opcodes::Instruction::abck(
2177                lua_code::opcodes::OpCode::LoadNil,
2178                arg_reg,
2179                0,
2180                0,
2181                0,
2182            );
2183            *inst = lua_types::opcode::Instruction::new(load_nil.0);
2184            break;
2185        }
2186    }
2187}
2188
2189/// Minimal `luaK_exp2anyreg`: ensure `e` ends up in *some* register. If `e`
2190/// is already `VNONRELOC` and its register is at or above the register
2191/// watermark ([`FuncState::nactvar_reg`], = `luaY_nvarstack`), keep it there;
2192/// otherwise discharge to the next free register.
2193fn cg_exp_to_any_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<u8, LuaError> {
2194    cg_discharge_vars(fs, line, e)?;
2195    if e.k == ExprKind::NonReloc {
2196        if e.t == NO_JUMP && e.f == NO_JUMP {
2197            return Ok(e.u.info as u8);
2198        }
2199        if e.u.info >= fs.nactvar_reg as i32 {
2200            cg_exp_to_reg(fs, line, e, e.u.info as u8)?;
2201            return Ok(e.u.info as u8);
2202        }
2203    }
2204    cg_exp_to_next_reg(fs, line, e)?;
2205    Ok(e.u.info as u8)
2206}
2207
2208/// Minimal `luaK_dischargevars` covering the cases the parser bootstrap can
2209/// produce: `VLOCAL`, `VUpVal`, `VIndexUp`, `VKStr`. Other variants are left
2210/// untouched. Returns Ok(()) on success.
2211fn cg_discharge_vars(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
2212    match e.k {
2213        ExprKind::Const => {
2214            // Mirrors C's `const2exp(const2val(fs, e), e)`: turn a resolved
2215            // `<const>` compile-time constant back into its literal expression
2216            // so the existing literal-lowering paths emit LOADI/LOADK/LOADFALSE/
2217            // LOADTRUE/LOADNIL exactly as for a bare literal. The value comes
2218            // from the snapshot (§4.0.A), never `dyd.actvar`.
2219            let v = e
2220                .u
2221                .const_snapshot
2222                .clone()
2223                .expect("ExprKind::Const must carry a const_snapshot");
2224            match v {
2225                LuaValue::Int(i) => {
2226                    e.k = ExprKind::KInt;
2227                    e.u.ival = i;
2228                }
2229                LuaValue::Float(f) => {
2230                    e.k = ExprKind::KFlt;
2231                    e.u.nval = f;
2232                }
2233                LuaValue::Bool(false) => e.k = ExprKind::False,
2234                LuaValue::Bool(true) => e.k = ExprKind::True,
2235                LuaValue::Nil => e.k = ExprKind::Nil,
2236                LuaValue::Str(s) => {
2237                    e.k = ExprKind::KStr;
2238                    e.u.strval = Some(s);
2239                }
2240                other => {
2241                    unreachable!("a <const> compile-time constant cannot be {other:?}")
2242                }
2243            }
2244        }
2245        ExprKind::VarArgVar => {
2246            mark_vararg_table_needed(fs);
2247            e.u.info = e.u.var_ridx as i32;
2248            e.k = ExprKind::NonReloc;
2249        }
2250        ExprKind::Local => {
2251            e.u.info = e.u.var_ridx as i32;
2252            e.k = ExprKind::NonReloc;
2253        }
2254        ExprKind::UpVal => {
2255            let inst = lua_code::opcodes::Instruction::abck(
2256                lua_code::opcodes::OpCode::GetUpVal,
2257                0,
2258                e.u.info as u32,
2259                0,
2260                0,
2261            );
2262            let pc = emit_inst(fs, line, inst);
2263            e.u.info = pc;
2264            e.k = ExprKind::Reloc;
2265        }
2266        ExprKind::IndexUp => {
2267            let inst = lua_code::opcodes::Instruction::abck(
2268                lua_code::opcodes::OpCode::GetTabUp,
2269                0,
2270                e.u.ind_t as u32,
2271                e.u.ind_idx as u32,
2272                0,
2273            );
2274            let pc = emit_inst(fs, line, inst);
2275            e.u.info = pc;
2276            e.k = ExprKind::Reloc;
2277        }
2278        ExprKind::IndexI => {
2279            cg_free_reg_if_temp(fs, e.u.ind_t as i32);
2280            let inst = lua_code::opcodes::Instruction::abck(
2281                lua_code::opcodes::OpCode::GetI,
2282                0,
2283                e.u.ind_t as u32,
2284                e.u.ind_idx as u32,
2285                0,
2286            );
2287            let pc = emit_inst(fs, line, inst);
2288            e.u.info = pc;
2289            e.k = ExprKind::Reloc;
2290        }
2291        ExprKind::IndexStr => {
2292            cg_free_reg_if_temp(fs, e.u.ind_t as i32);
2293            let inst = lua_code::opcodes::Instruction::abck(
2294                lua_code::opcodes::OpCode::GetField,
2295                0,
2296                e.u.ind_t as u32,
2297                e.u.ind_idx as u32,
2298                0,
2299            );
2300            let pc = emit_inst(fs, line, inst);
2301            e.u.info = pc;
2302            e.k = ExprKind::Reloc;
2303        }
2304        ExprKind::Indexed => {
2305            let t_reg = e.u.ind_t as i32;
2306            let idx_reg = e.u.ind_idx as i32;
2307            if idx_reg > t_reg {
2308                cg_free_reg_if_temp(fs, idx_reg);
2309                cg_free_reg_if_temp(fs, t_reg);
2310            } else {
2311                cg_free_reg_if_temp(fs, t_reg);
2312                cg_free_reg_if_temp(fs, idx_reg);
2313            }
2314            let inst = lua_code::opcodes::Instruction::abck(
2315                lua_code::opcodes::OpCode::GetTable,
2316                0,
2317                e.u.ind_t as u32,
2318                e.u.ind_idx as u32,
2319                0,
2320            );
2321            let pc = emit_inst(fs, line, inst);
2322            e.u.info = pc;
2323            e.k = ExprKind::Reloc;
2324        }
2325        ExprKind::VarArgIndex => {
2326            let t_reg = e.u.ind_t as i32;
2327            let idx_reg = e.u.ind_idx as i32;
2328            if idx_reg > t_reg {
2329                cg_free_reg_if_temp(fs, idx_reg);
2330                cg_free_reg_if_temp(fs, t_reg);
2331            } else {
2332                cg_free_reg_if_temp(fs, t_reg);
2333                cg_free_reg_if_temp(fs, idx_reg);
2334            }
2335            let inst = lua_code::opcodes::Instruction::abck(
2336                lua_code::opcodes::OpCode::GetVArg,
2337                0,
2338                e.u.ind_t as u32,
2339                e.u.ind_idx as u32,
2340                0,
2341            );
2342            let pc = emit_inst(fs, line, inst);
2343            e.u.info = pc;
2344            e.k = ExprKind::Reloc;
2345        }
2346        ExprKind::VarArg | ExprKind::Call => {
2347            cg_set_one_ret(fs, e);
2348        }
2349        _ => {}
2350    }
2351    Ok(())
2352}
2353
2354/// Fixes up `e` (a `Call` or `VarArg` expression) to yield exactly one
2355/// result. For a Call this leaves the already-emitted instruction alone (it
2356/// was emitted with `ARG_C = 2`, i.e. exactly one result) and reclassifies
2357/// `e` as `NonReloc` pointing at the result register (the Call's `ARG_A`).
2358/// For a VarArg this patches `ARG_C = 2` and leaves `e` as `Reloc` so the
2359/// caller can place the single result into a destination register.
2360fn cg_set_one_ret(fs: &mut FuncState, e: &mut ExprDesc) {
2361    if e.k == ExprKind::Call {
2362        let pc_idx = e.u.info as usize;
2363        let lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
2364        debug_assert_eq!(lc.arg_c(), 2);
2365        e.u.info = lc.arg_a() as i32;
2366        e.k = ExprKind::NonReloc;
2367    } else if e.k == ExprKind::VarArg {
2368        let pc_idx = e.u.info as usize;
2369        let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
2370        lc.set_arg_c(2);
2371        fs.f.code[pc_idx] = lua_types::opcode::Instruction::new(lc.0);
2372        e.k = ExprKind::Reloc;
2373    }
2374}
2375
2376/// Stores the value in `ex` into the variable described by `var`. Handles
2377/// VLocal (move into register), VUpVal (OP_SETUPVAL), VIndexUp
2378/// (OP_SETTABUP), VIndexI/IndexStr/Indexed (OP_SETI/SETFIELD/SETTABLE).
2379fn cg_storevar(
2380    fs: &mut FuncState,
2381    line: i32,
2382    var: &ExprDesc,
2383    ex: &mut ExprDesc,
2384) -> Result<(), LuaError> {
2385    match var.k {
2386        ExprKind::Local => {
2387            cg_free_exp(fs, ex);
2388            cg_exp_to_reg(fs, line, ex, var.u.var_ridx as u8)?;
2389            return Ok(());
2390        }
2391        ExprKind::UpVal => {
2392            let e_reg = cg_exp_to_any_reg(fs, line, ex)?;
2393            let inst = lua_code::opcodes::Instruction::abck(
2394                lua_code::opcodes::OpCode::SetUpVal,
2395                e_reg as u32,
2396                var.u.info as u32,
2397                0,
2398                0,
2399            );
2400            emit_inst(fs, line, inst);
2401        }
2402        ExprKind::IndexUp => {
2403            cg_store_abrk(
2404                fs,
2405                line,
2406                lua_code::opcodes::OpCode::SetTabUp,
2407                var.u.ind_t as u32,
2408                var.u.ind_idx as u32,
2409                ex,
2410            )?;
2411        }
2412        ExprKind::IndexI => {
2413            cg_store_abrk(
2414                fs,
2415                line,
2416                lua_code::opcodes::OpCode::SetI,
2417                var.u.ind_t as u32,
2418                var.u.ind_idx as u32,
2419                ex,
2420            )?;
2421        }
2422        ExprKind::IndexStr => {
2423            cg_store_abrk(
2424                fs,
2425                line,
2426                lua_code::opcodes::OpCode::SetField,
2427                var.u.ind_t as u32,
2428                var.u.ind_idx as u32,
2429                ex,
2430            )?;
2431        }
2432        ExprKind::Indexed => {
2433            cg_store_abrk(
2434                fs,
2435                line,
2436                lua_code::opcodes::OpCode::SetTable,
2437                var.u.ind_t as u32,
2438                var.u.ind_idx as u32,
2439                ex,
2440            )?;
2441        }
2442        ExprKind::VarArgIndex => {
2443            mark_vararg_table_needed(fs);
2444            cg_store_abrk(
2445                fs,
2446                line,
2447                lua_code::opcodes::OpCode::SetTable,
2448                var.u.ind_t as u32,
2449                var.u.ind_idx as u32,
2450                ex,
2451            )?;
2452        }
2453        _ => {
2454            return Err(LuaError::syntax(format_args!(
2455                "internal: cg_storevar: invalid var kind {:?}",
2456                var.k
2457            )));
2458        }
2459    }
2460    cg_free_exp(fs, ex);
2461    Ok(())
2462}
2463
2464/// Helper for cg_storevar: emit an ABRK-form store. Mirrors C's `codeABRK`
2465/// for the SetTabUp/SetI/SetField/SetTable family. When `ex` is a constant
2466/// the K bit is set; otherwise the value is forced into a register.
2467fn cg_store_abrk(
2468    fs: &mut FuncState,
2469    line: i32,
2470    op: lua_code::opcodes::OpCode,
2471    a: u32,
2472    b: u32,
2473    ex: &mut ExprDesc,
2474) -> Result<(), LuaError> {
2475    if cg_exp_to_const_k(fs, ex, lua_code::opcodes::MAXARG_C) {
2476        let inst = lua_code::opcodes::Instruction::abck(op, a, b, ex.u.info as u32, 1);
2477        emit_inst(fs, line, inst);
2478        return Ok(());
2479    }
2480    let c_reg = cg_exp_to_any_reg(fs, line, ex)?;
2481    let inst = lua_code::opcodes::Instruction::abck(op, a, b, c_reg as u32, 0);
2482    emit_inst(fs, line, inst);
2483    Ok(())
2484}
2485
2486/// Mirrors C's `discharge2reg` from `lcode.c`: places the value described by
2487/// `e` into `reg`. For `Jmp` this is a no-op (the caller — `cg_exp_to_reg` —
2488/// is responsible for stitching the jump into `e.t` and emitting the
2489/// LoadTrue / LFalseSkip pair if a concrete value is needed).
2490fn cg_discharge_to_reg(
2491    fs: &mut FuncState,
2492    line: i32,
2493    e: &mut ExprDesc,
2494    reg: u8,
2495) -> Result<(), LuaError> {
2496    cg_discharge_vars(fs, line, e)?;
2497    match e.k {
2498        ExprKind::Jmp => {
2499            return Ok(());
2500        }
2501        ExprKind::NonReloc => {
2502            if e.u.info as u8 != reg {
2503                let inst = lua_code::opcodes::Instruction::abck(
2504                    lua_code::opcodes::OpCode::Move,
2505                    reg as u32,
2506                    e.u.info as u32,
2507                    0,
2508                    0,
2509                );
2510                emit_inst(fs, line, inst);
2511            }
2512        }
2513        ExprKind::Reloc => {
2514            let pc = e.u.info as usize;
2515            let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc].0);
2516            lc.set_arg_a(reg as u32);
2517            fs.f.code[pc] = lua_types::opcode::Instruction::new(lc.0);
2518        }
2519        ExprKind::Nil => {
2520            let inst = lua_code::opcodes::Instruction::abck(
2521                lua_code::opcodes::OpCode::LoadNil,
2522                reg as u32,
2523                0,
2524                0,
2525                0,
2526            );
2527            emit_inst(fs, line, inst);
2528        }
2529        ExprKind::True => {
2530            let inst = lua_code::opcodes::Instruction::abck(
2531                lua_code::opcodes::OpCode::LoadTrue,
2532                reg as u32,
2533                0,
2534                0,
2535                0,
2536            );
2537            emit_inst(fs, line, inst);
2538        }
2539        ExprKind::False => {
2540            let inst = lua_code::opcodes::Instruction::abck(
2541                lua_code::opcodes::OpCode::LoadFalse,
2542                reg as u32,
2543                0,
2544                0,
2545                0,
2546            );
2547            emit_inst(fs, line, inst);
2548        }
2549        ExprKind::KInt => {
2550            let i = e.u.ival;
2551            let max = lua_code::opcodes::MAXARG_BX as i64 - lua_code::opcodes::OFFSET_S_BX as i64;
2552            let min = -(lua_code::opcodes::OFFSET_S_BX as i64);
2553            if i >= min && i <= max {
2554                let bx = (i as i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
2555                let inst = lua_code::opcodes::Instruction::abx(
2556                    lua_code::opcodes::OpCode::LoadI,
2557                    reg as u32,
2558                    bx,
2559                );
2560                emit_inst(fs, line, inst);
2561            } else {
2562                let k_idx = add_k_value(fs, LuaValue::Int(i));
2563                let inst = lua_code::opcodes::Instruction::abx(
2564                    lua_code::opcodes::OpCode::LoadK,
2565                    reg as u32,
2566                    k_idx as u32,
2567                );
2568                emit_inst(fs, line, inst);
2569            }
2570        }
2571        ExprKind::KFlt => {
2572            let f = e.u.nval;
2573            let max = lua_code::opcodes::MAXARG_BX as i64 - lua_code::opcodes::OFFSET_S_BX as i64;
2574            let min = -(lua_code::opcodes::OFFSET_S_BX as i64);
2575            let fi_opt: Option<i64> = if f.fract() == 0.0 && f.abs() < i64::MAX as f64 {
2576                Some(f as i64)
2577            } else {
2578                None
2579            };
2580            if let Some(fi) = fi_opt.filter(|fi| *fi >= min && *fi <= max) {
2581                let bx = (fi as i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
2582                let inst = lua_code::opcodes::Instruction::abx(
2583                    lua_code::opcodes::OpCode::LoadF,
2584                    reg as u32,
2585                    bx,
2586                );
2587                emit_inst(fs, line, inst);
2588            } else {
2589                let k_idx = add_k_value(fs, LuaValue::Float(f));
2590                let inst = lua_code::opcodes::Instruction::abx(
2591                    lua_code::opcodes::OpCode::LoadK,
2592                    reg as u32,
2593                    k_idx as u32,
2594                );
2595                emit_inst(fs, line, inst);
2596            }
2597        }
2598        ExprKind::KStr => {
2599            let s =
2600                e.u.strval.clone().ok_or_else(|| {
2601                    LuaError::syntax(format_args!("internal: VKStr with no strval"))
2602                })?;
2603            let k_idx = add_k_string(fs, s);
2604            let inst = lua_code::opcodes::Instruction::abx(
2605                lua_code::opcodes::OpCode::LoadK,
2606                reg as u32,
2607                k_idx as u32,
2608            );
2609            emit_inst(fs, line, inst);
2610        }
2611        ExprKind::K => {
2612            let inst = lua_code::opcodes::Instruction::abx(
2613                lua_code::opcodes::OpCode::LoadK,
2614                reg as u32,
2615                e.u.info as u32,
2616            );
2617            emit_inst(fs, line, inst);
2618        }
2619        _ => {
2620            return Err(LuaError::syntax(format_args!(
2621                "internal: cg_discharge_to_reg cannot discharge {:?}",
2622                e.k
2623            )));
2624        }
2625    }
2626    e.u.info = reg as i32;
2627    e.k = ExprKind::NonReloc;
2628    Ok(())
2629}
2630
2631/// Mirrors C's `need_value` from `lcode.c`: walks the jump-list `list` and
2632/// returns true if any controlling instruction is *not* an `OP_TESTSET`,
2633/// meaning a concrete LoadTrue / LFalseSkip pair must be emitted to provide
2634/// the value at the fallthrough.
2635fn cg_need_value(fs: &FuncState, list: i32) -> bool {
2636    let mut walk = JumpList::new(list);
2637    while let Some(pc) = walk.next(fs) {
2638        let ctrl_pc = cg_get_jump_control(fs, pc);
2639        let ctrl = cg_inst_at(fs, ctrl_pc);
2640        if ctrl.opcode() != Some(lua_code::opcodes::OpCode::TestSet) {
2641            return true;
2642        }
2643    }
2644    false
2645}
2646
2647/// Mirrors C's `code_loadbool` from `lcode.c`: records `fs.pc` as a jump
2648/// label, then emits the requested LoadTrue / LoadFalse / LFalseSkip
2649/// instruction and returns its pc.
2650fn cg_code_loadbool(fs: &mut FuncState, line: i32, reg: i32, op: lua_code::opcodes::OpCode) -> i32 {
2651    cg_get_label(fs);
2652    let inst = lua_code::opcodes::Instruction::abck(op, reg as u32, 0, 0, 0);
2653    emit_inst(fs, line, inst)
2654}
2655
2656/// Mirrors C's `patchlistaux` from `lcode.c`: walks the jump-list `list`,
2657/// rewriting `TESTSET` controllers to write `reg` (and routing them to
2658/// `vtarget`) and leaving plain tests to fall through to `dtarget`.
2659fn cg_patch_list_aux(
2660    fs: &mut FuncState,
2661    list: i32,
2662    vtarget: i32,
2663    reg: u32,
2664    dtarget: i32,
2665) -> Result<(), LuaError> {
2666    let mut walk = JumpList::new(list);
2667    while let Some(pc) = walk.next(fs) {
2668        if cg_patch_test_reg(fs, pc, reg) {
2669            cg_fix_jump(fs, pc, vtarget)?;
2670        } else {
2671            cg_fix_jump(fs, pc, dtarget)?;
2672        }
2673    }
2674    Ok(())
2675}
2676
2677/// Discharge `e` into the specific register `reg`. Mirrors C's `exp2reg`
2678/// from `lcode.c`: delegates to `cg_discharge_to_reg`, then folds the jump
2679/// at `e.u.info` into `e.t` (when `e` is itself a test) and patches any
2680/// pending `e.t` / `e.f` jump-lists. When the lists actually need a value
2681/// (i.e. any controller isn't a `TESTSET`), emits the LFalseSkip / LoadTrue
2682/// pair around which the jumps land.
2683fn cg_exp_to_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc, reg: u8) -> Result<(), LuaError> {
2684    cg_discharge_to_reg(fs, line, e, reg)?;
2685    if e.k == ExprKind::Jmp {
2686        let info = e.u.info;
2687        cg_concat(fs, &mut e.t, info)?;
2688    }
2689    if e.t != e.f {
2690        let mut p_f = NO_JUMP;
2691        let mut p_t = NO_JUMP;
2692        if cg_need_value(fs, e.t) || cg_need_value(fs, e.f) {
2693            let fj = if e.k == ExprKind::Jmp {
2694                NO_JUMP
2695            } else {
2696                cg_jump(fs, line)
2697            };
2698            p_f = cg_code_loadbool(fs, line, reg as i32, lua_code::opcodes::OpCode::LFalseSkip);
2699            p_t = cg_code_loadbool(fs, line, reg as i32, lua_code::opcodes::OpCode::LoadTrue);
2700            cg_patch_to_here(fs, fj)?;
2701        }
2702        let final_pc = cg_get_label(fs);
2703        cg_patch_list_aux(fs, e.f, final_pc, reg as u32, p_f)?;
2704        cg_patch_list_aux(fs, e.t, final_pc, reg as u32, p_t)?;
2705    }
2706    e.f = NO_JUMP;
2707    e.t = NO_JUMP;
2708    e.u.info = reg as i32;
2709    e.k = ExprKind::NonReloc;
2710    Ok(())
2711}
2712
2713/// Like `cg_free_reg`, but only acts when the index actually belongs to a
2714/// temporary register (one at or above the register watermark
2715/// [`FuncState::nactvar_reg`]). Used by indexed-get dischargers, which may
2716/// operate on either a temp result or a local.
2717fn cg_free_reg_if_temp(fs: &mut FuncState, reg: i32) {
2718    if reg >= fs.nactvar_reg as i32 {
2719        debug_assert!(reg < fs.freereg as i32);
2720        if reg == fs.freereg as i32 - 1 {
2721            fs.freereg -= 1;
2722        }
2723    }
2724}
2725
2726/// Mirrors C's `luaK_exp2nextreg` from `lcode.c`: discharge variable forms,
2727/// free any temp held by `e`, reserve the next register, then call
2728/// `cg_exp_to_reg` to place the value (handling `Jmp` and pending
2729/// `e.t` / `e.f` jump-lists through the shared `exp2reg` path).
2730/// Emit the Lua 5.5 `global name = expr` already-defined guard for one global.
2731///
2732/// Mirrors upstream `checkglobal`/`luaK_codecheckglobal` (`lcode.c`): read the
2733/// global's current value into a temporary register and emit `OP_ERRNNIL`,
2734/// which raises `global '<name>' already defined` at runtime if that value is
2735/// non-nil. `target` is the `_ENV[name]` lvalue; it is cloned so the caller's
2736/// copy is left intact for the subsequent store. The temporary is freed
2737/// immediately so the store's `freereg - 1` source slot is undisturbed.
2738///
2739/// Bx encodes the name like upstream: `0` means the name index is unavailable
2740/// (renders as `?`), otherwise `Bx - 1` is the constant-table index of the
2741/// name string. The error reports `line`, the initializer's line number.
2742fn cg_check_global(
2743    fs: &mut FuncState,
2744    line: i32,
2745    target: &ExprDesc,
2746    name: GcRef<LuaString>,
2747) -> Result<(), LuaError> {
2748    let k = add_k_string(fs, name);
2749    let bx = if (k as u32) >= lua_code::opcodes::MAXARG_BX {
2750        0
2751    } else {
2752        (k + 1) as u32
2753    };
2754    let mut probe = target.clone();
2755    cg_exp_to_next_reg(fs, line, &mut probe)?;
2756    let reg = probe.u.info;
2757    let inst =
2758        lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::ErrNNil, reg as u32, bx);
2759    emit_inst(fs, line, inst);
2760    cg_free_reg(fs, reg);
2761    Ok(())
2762}
2763
2764fn cg_exp_to_next_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
2765    cg_discharge_vars(fs, line, e)?;
2766    cg_free_exp(fs, e);
2767    let reg = reserve_reg(fs)?;
2768    cg_exp_to_reg(fs, line, e, reg)
2769}
2770
2771/// Patches the Call or VarArg instruction in `e` so that it produces
2772/// `nresults` values (or LUA_MULTRET when `nresults == -1`).
2773fn cg_set_returns(fs: &mut FuncState, e: &mut ExprDesc, nresults: i32) {
2774    let pc_idx = e.u.info as usize;
2775    let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
2776    if e.k == ExprKind::Call {
2777        lc.set_arg_c((nresults + 1) as u32);
2778    } else {
2779        debug_assert_eq!(e.k, ExprKind::VarArg);
2780        lc.set_arg_c((nresults + 1) as u32);
2781        lc.set_arg_a(fs.freereg as u32);
2782        // Upstream `luaK_setreturns` reserves the slot via `luaK_reserveregs`,
2783        // which also grows `maxstacksize`. A bare `freereg += 1` left the high
2784        // watermark stale and tripped the `maxstacksize >= freereg` invariant
2785        // whenever the VARARG sat above register 0 (e.g. a 5.5 named-vararg
2786        // local occupying a lower slot).
2787        fs.freereg += 1;
2788        bump_maxstack(fs, fs.freereg);
2789    }
2790    fs.f.code[pc_idx] = lua_types::opcode::Instruction::new(lc.0);
2791}
2792
2793/// `OP_JMP` instructions to the final landing pc. Capped at 100 hops to
2794/// avoid infinite loops on malformed code.
2795fn cg_final_target(fs: &FuncState, mut i: i32) -> i32 {
2796    for _ in 0..100 {
2797        let inst = cg_inst_at(fs, i);
2798        if inst.opcode() != Some(lua_code::opcodes::OpCode::Jmp) {
2799            break;
2800        }
2801        i += inst.arg_s_j() + 1;
2802    }
2803    i
2804}
2805
2806///
2807/// Patches `OP_RETURN`/`OP_RETURN0`/`OP_RETURN1`/`OP_TAILCALL` to record the
2808/// vararg signature (so the VM can roll back `ci->func` on return) and the
2809/// `needclose` flag (so it closes pending upvalues). Also resolves chained
2810/// `OP_JMP` jumps to their final target.
2811fn cg_finish(fs: &mut FuncState) {
2812    use lua_code::opcodes::OpCode;
2813    let needclose = fs.needclose;
2814    let is_vararg = fs.f.is_vararg;
2815    let numparams = fs.f.numparams as u32;
2816    let pc_end = fs.pc;
2817    for i in 0..pc_end {
2818        let mut inst = cg_inst_at(fs, i);
2819        match inst.opcode() {
2820            Some(OpCode::Return0) | Some(OpCode::Return1) => {
2821                if !(needclose || is_vararg) {
2822                    continue;
2823                }
2824                inst.set_opcode(OpCode::Return);
2825                if needclose {
2826                    inst.set_arg_k(1);
2827                }
2828                if is_vararg {
2829                    inst.set_arg_c(numparams + 1);
2830                }
2831                cg_set_inst_at(fs, i, inst);
2832            }
2833            Some(OpCode::Return) | Some(OpCode::TailCall) => {
2834                if needclose {
2835                    inst.set_arg_k(1);
2836                }
2837                if is_vararg {
2838                    inst.set_arg_c(numparams + 1);
2839                }
2840                cg_set_inst_at(fs, i, inst);
2841            }
2842            Some(OpCode::Jmp) => {
2843                let target = cg_final_target(fs, i);
2844                let _ = cg_fix_jump(fs, i, target);
2845            }
2846            _ => {}
2847        }
2848    }
2849}
2850
2851/// Emits a return instruction, choosing the most specific opcode available
2852/// based on `nret`. `first` is the first result register; `nret` is the
2853/// number of values to return (`LUA_MULTRET` for "all values on top").
2854fn cg_emit_return(
2855    fs: &mut FuncState,
2856    line: i32,
2857    first: i32,
2858    nret: i32,
2859    version: lua_types::LuaVersion,
2860) -> Result<(), LuaError> {
2861    let op = match nret {
2862        0 => lua_code::opcodes::OpCode::Return0,
2863        1 => lua_code::opcodes::OpCode::Return1,
2864        _ => lua_code::opcodes::OpCode::Return,
2865    };
2866    if matches!(version, lua_types::LuaVersion::V55) {
2867        check_limit(fs, nret + 1, lua_code::opcodes::MAXARG_B as i32, "returns")?;
2868    }
2869    let inst = lua_code::opcodes::Instruction::abck(op, first as u32, (nret + 1) as u32, 0, 0);
2870    emit_inst(fs, line, inst);
2871    Ok(())
2872}
2873
2874// ── Free functions ──────────────────────────────────────────────────────────
2875
2876// (Both defined later in this file; Rust has no forward declarations.)
2877
2878// ── §1 Error helpers ────────────────────────────────────────────────────────
2879
2880/// Constructs a syntax error for a missing expected token.
2881/// In Rust, `l_noret` becomes returning `LuaError`; callers use
2882/// `return Err(error_expected(...))`.
2883fn error_expected(ls: &mut LexState, token: TokenKind) -> LuaError {
2884    let tok_str = lua_lex::token2str(&ls.lex, token);
2885    let mut msg: Vec<u8> = Vec::with_capacity(tok_str.len() + 10);
2886    msg.extend_from_slice(&tok_str);
2887    msg.extend_from_slice(b" expected");
2888    lua_lex::syntax_error(&mut ls.lex, &msg)
2889}
2890
2891/// Constructs a compile-time limit-exceeded syntax error.
2892fn error_limit(fs: &FuncState, limit: i32, what: &str) -> LuaError {
2893    let line = fs.f.linedefined;
2894    if line == 0 {
2895        LuaError::syntax(format_args!(
2896            "too many {} (limit is {}) in main function",
2897            what, limit
2898        ))
2899    } else {
2900        LuaError::syntax(format_args!(
2901            "too many {} (limit is {}) in function at line {}",
2902            what, limit, line
2903        ))
2904    }
2905}
2906
2907fn check_limit(fs: &FuncState, v: i32, l: i32, what: &str) -> Result<(), LuaError> {
2908    if v > l {
2909        return Err(error_limit(fs, l, what));
2910    }
2911    Ok(())
2912}
2913
2914/// Constructs Lua 5.1's `errorlimit` message, which predates the modern
2915/// `"too many %s (limit is %d) ..."` wording produced by [`error_limit`].
2916///
2917/// Lua 5.1's `lparser.c errorlimit` emits `"function at line %d has more than
2918/// %d %s"` (or `"main function has more than %d %s"` when `linedefined == 0`),
2919/// reporting the *limit* rather than the attempted count. The limit value also
2920/// differs from later versions for upvalues: 5.1 caps a function at
2921/// `LUAI_MAXUPVALUES = 60`, whereas 5.2+ allow `MAXUPVAL = 255`. Used only on
2922/// the [`lua_types::LuaVersion::V51`] path so 5.2–5.5 stay byte-identical.
2923fn error_limit_v51(fs: &FuncState, limit: i32, what: &str) -> LuaError {
2924    let line = fs.f.linedefined;
2925    if line == 0 {
2926        LuaError::syntax(format_args!("main function has more than {} {}", limit, what))
2927    } else {
2928        LuaError::syntax(format_args!(
2929            "function at line {} has more than {} {}",
2930            line, limit, what
2931        ))
2932    }
2933}
2934
2935// ── §2 Basic parse utilities ─────────────────────────────────────────────────
2936
2937/// If the current token matches `c`, consume it and return true.
2938fn test_next(ls: &mut LexState, state: &mut LuaState, c: TokenKind) -> Result<bool, LuaError> {
2939    if ls.t.token == c {
2940        lex_next(ls, state)?;
2941        Ok(true)
2942    } else {
2943        Ok(false)
2944    }
2945}
2946
2947fn check(ls: &mut LexState, c: TokenKind) -> Result<(), LuaError> {
2948    if ls.t.token != c {
2949        return Err(error_expected(ls, c));
2950    }
2951    Ok(())
2952}
2953
2954fn check_next(ls: &mut LexState, state: &mut LuaState, c: TokenKind) -> Result<(), LuaError> {
2955    check(ls, c)?;
2956    lex_next(ls, state)?;
2957    Ok(())
2958}
2959
2960/// Expects TK_NAME, returns the name string, advances.
2961fn str_check_name(ls: &mut LexState, state: &mut LuaState) -> Result<GcRef<LuaString>, LuaError> {
2962    check(ls, TK_NAME)?;
2963    let ts =
2964        ls.t.seminfo
2965            .ts
2966            .clone()
2967            .ok_or_else(|| LuaError::syntax(format_args!("name expected")))?;
2968    lex_next(ls, state)?;
2969    Ok(ts)
2970}
2971
2972fn init_exp(e: &mut ExprDesc, k: ExprKind, i: i32) {
2973    e.f = NO_JUMP;
2974    e.t = NO_JUMP;
2975    e.k = k;
2976    e.u.info = i;
2977}
2978
2979fn codestring(e: &mut ExprDesc, s: GcRef<LuaString>) {
2980    e.f = NO_JUMP;
2981    e.t = NO_JUMP;
2982    e.k = ExprKind::KStr;
2983    e.u.strval = Some(s);
2984}
2985
2986fn codename(ls: &mut LexState, state: &mut LuaState, e: &mut ExprDesc) -> Result<(), LuaError> {
2987    let name = str_check_name(ls, state)?;
2988    codestring(e, name);
2989    Ok(())
2990}
2991
2992// ── §3 Variable handling ─────────────────────────────────────────────────────
2993
2994/// Registers a local variable in the proto's debug-info locvars array.
2995/// Returns the index in locvars (= fs->ndebugvars before increment).
2996fn register_local_var(
2997    _ls: &mut LexState,
2998    _state: &mut LuaState,
2999    fs: &mut FuncState,
3000    varname: GcRef<LuaString>,
3001) -> Result<i32, LuaError> {
3002    // In Rust, Vec grows automatically; just push a placeholder if needed.
3003    let idx = fs.ndebugvars as usize;
3004    while fs.f.locvars.len() <= idx {
3005        fs.f.locvars.push(LocalVar {
3006            varname: varname.clone(), // placeholder; overwritten below
3007            startpc: 0,
3008            endpc: 0,
3009        });
3010    }
3011    fs.f.locvars[idx].varname = varname;
3012    fs.f.locvars[idx].startpc = fs.pc;
3013    let result = fs.ndebugvars as i32;
3014    fs.ndebugvars += 1;
3015    Ok(result)
3016}
3017
3018/// Creates a new local variable entry in dyd.actvar.
3019/// Returns the variable's index relative to fs->firstlocal.
3020fn new_local_var(
3021    ls: &mut LexState,
3022    _state: &mut LuaState,
3023    name: GcRef<LuaString>,
3024) -> Result<i32, LuaError> {
3025    let fs = ls.fs.as_ref().unwrap();
3026    let n = ls.dyd.actvar.len() as i32;
3027    let first_local = fs.firstlocal;
3028    check_limit(fs, n + 1 - first_local, MAX_VARS, "local variables")?;
3029
3030    let mut var = VarDesc::default();
3031    var.kind = VarKind::Reg;
3032    var.name = Some(name);
3033    ls.dyd.actvar.push(var);
3034    let result = ls.dyd.actvar.len() as i32 - 1 - first_local;
3035    Ok(result)
3036}
3037
3038/// Returns a reference to the VarDesc at index `fs->firstlocal + vidx`.
3039fn get_local_var_desc<'a>(ls: &'a LexState, fs: &FuncState, vidx: i32) -> &'a VarDesc {
3040    &ls.dyd.actvar[(fs.firstlocal + vidx) as usize]
3041}
3042
3043fn get_local_var_desc_mut(ls: &mut LexState, first_local: i32, vidx: i32) -> &mut VarDesc {
3044    &mut ls.dyd.actvar[(first_local + vidx) as usize]
3045}
3046
3047/// Converts a compiler-index level to its register number.
3048fn reg_level(ls: &LexState, fs: &FuncState, nvar: i32) -> i32 {
3049    let mut nvar = nvar;
3050    while nvar > 0 {
3051        nvar -= 1;
3052        let vd = get_local_var_desc(ls, fs, nvar);
3053        if vd.kind != VarKind::CompileTimeConst {
3054            return vd.ridx as i32 + 1;
3055        }
3056    }
3057    0
3058}
3059
3060/// Returns the number of variables currently occupying registers.
3061/// LUAI_FUNC visibility.
3062pub fn nvarstack(ls: &LexState, fs: &FuncState) -> i32 {
3063    reg_level(ls, fs, fs.nactvar as i32)
3064}
3065
3066fn init_var(ls: &LexState, fs: &FuncState, e: &mut ExprDesc, vidx: i32) {
3067    e.f = NO_JUMP;
3068    e.t = NO_JUMP;
3069    e.k = ExprKind::Local;
3070    e.u.var_vidx = vidx as u16;
3071    e.u.var_ridx = get_local_var_desc(ls, fs, vidx).ridx;
3072}
3073
3074/// Raises an error if expression `e` describes a read-only variable.
3075fn check_readonly(ls: &mut LexState, state: &mut LuaState, e: &ExprDesc) -> Result<(), LuaError> {
3076    // Lua 5.5: assignment to a `global x <const>` declared global is rejected
3077    // at compile time, tagged on the resolved expression by `singlevar`.
3078    if let Some(name) = e.u.global_const_name.as_ref() {
3079        let msg = format!(
3080            "attempt to assign to const variable '{}'",
3081            String::from_utf8_lossy(name.as_bytes())
3082        );
3083        // Semantic error (C's luaK_semerror): no "near <token>" suffix.
3084        return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
3085    }
3086    let varname: Option<GcRef<LuaString>> = {
3087        let fs = ls.fs.as_ref().unwrap();
3088        match e.k {
3089            ExprKind::Const => ls.dyd.actvar[e.u.info as usize].name.clone(),
3090            ExprKind::Local | ExprKind::VarArgVar => {
3091                let vd = get_local_var_desc(ls, fs, e.u.var_vidx as i32);
3092                if vd.kind != VarKind::Reg {
3093                    vd.name.clone()
3094                } else {
3095                    None
3096                }
3097            }
3098            ExprKind::UpVal => {
3099                let up = &fs.f.upvalues[e.u.info as usize];
3100                if VarKind::from_u8(up.kind) != VarKind::Reg {
3101                    up.name.clone()
3102                } else {
3103                    None
3104                }
3105            }
3106            _ => None,
3107        }
3108    };
3109    if let Some(vname) = varname {
3110        // C's luaK_semerror: a semantic error carries no "near <token>" suffix
3111        // (it zeroes ls->t.token before luaX_syntaxerror). Use lex_error with
3112        // token 0 to match the reference exactly for every version. constructs.lua's
3113        // checkload(":1: attempt to assign...") still matches (prefix).
3114        let _ = state;
3115        let msg = format!(
3116            "attempt to assign to const variable '{}'",
3117            String::from_utf8_lossy(vname.as_bytes())
3118        );
3119        return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
3120    }
3121    Ok(())
3122}
3123
3124/// Starts the scope for the last `nvars` created variables.
3125fn adjust_local_vars(ls: &mut LexState, state: &mut LuaState, nvars: i32) -> Result<(), LuaError> {
3126    // Extract needed data to avoid borrow conflict with ls.fs and ls.dyd
3127    let first_local = ls.fs.as_ref().unwrap().firstlocal;
3128    let nactvar_start = ls.fs.as_ref().unwrap().nactvar as i32;
3129    let mut reglevel_val = {
3130        let fs = ls.fs.as_ref().unwrap();
3131        reg_level(ls, fs, fs.nactvar as i32)
3132    };
3133
3134    for i in 0..nvars {
3135        let vidx = nactvar_start + i;
3136        ls.fs.as_mut().unwrap().nactvar += 1;
3137        let var_name = ls.dyd.actvar[(first_local + vidx) as usize].name.clone();
3138        ls.dyd.actvar[(first_local + vidx) as usize].ridx = reglevel_val as u8;
3139        reglevel_val += 1;
3140        if let Some(vn) = var_name {
3141            let mut fs_box = ls.fs.take().unwrap();
3142            let pidx_result = register_local_var(ls, state, &mut fs_box, vn);
3143            ls.fs = Some(fs_box);
3144            let pidx = pidx_result?;
3145            ls.dyd.actvar[(first_local + vidx) as usize].pidx = pidx as i16;
3146        } else {
3147            // No variable name: not expected in valid source.
3148        }
3149    }
3150    // Every variable adjusted here is register-backed (a `<const>` CTC is
3151    // folded before this runs and excluded from the count), so the register
3152    // watermark advances to the level reached after placing them. This mirrors
3153    // `reg_level(ls, fs, fs.nactvar)` without re-walking `dyd.actvar`.
3154    ls.fs.as_mut().unwrap().nactvar_reg = reglevel_val as u8;
3155    Ok(())
3156}
3157
3158/// Closes scope for all variables above `tolevel`, updating their endpc.
3159fn remove_vars(ls: &mut LexState, fs: &mut FuncState, tolevel: i32) {
3160    //
3161    // C just decrements a length counter; the underlying array memory is
3162    // untouched and the subsequent loop reads from it freely. A Rust
3163    // `truncate` would actually free the entries, leaving the loop reading
3164    // out-of-range and silently writing every iteration's endpc to
3165    // `locvars[0]` (via the `unwrap_or(0)` fallback below). Defer the
3166    // truncate until after the loop walks each soon-to-be-removed entry.
3167    let delta = fs.nactvar as i32 - tolevel;
3168    while fs.nactvar as i32 > tolevel {
3169        fs.nactvar -= 1;
3170        let nactvar = fs.nactvar as i32;
3171        let vd_kind = {
3172            let first_local = fs.firstlocal;
3173            ls.dyd
3174                .actvar
3175                .get((first_local + nactvar) as usize)
3176                .map(|v| v.kind)
3177                .unwrap_or(VarKind::Reg)
3178        };
3179        if vd_kind != VarKind::CompileTimeConst {
3180            let vd_pidx = {
3181                let first_local = fs.firstlocal;
3182                ls.dyd
3183                    .actvar
3184                    .get((first_local + nactvar) as usize)
3185                    .map(|v| v.pidx)
3186                    .unwrap_or(0)
3187            };
3188            if let Some(lv) = fs.f.locvars.get_mut(vd_pidx as usize) {
3189                lv.endpc = fs.pc;
3190            }
3191        }
3192    }
3193    if delta > 0 {
3194        let new_len = ls.dyd.actvar.len().saturating_sub(delta as usize);
3195        ls.dyd.actvar.truncate(new_len);
3196    }
3197    // The active set shrank; recompute the register watermark from the
3198    // surviving descriptors (which are still present below `tolevel`). This
3199    // keeps `nactvar_reg == reg_level(ls, fs, fs.nactvar)` after any CTC that
3200    // was in scope is dropped.
3201    fs.nactvar_reg = reg_level(ls, fs, fs.nactvar as i32) as u8;
3202}
3203
3204// ── §4 Upvalue handling ──────────────────────────────────────────────────────
3205
3206/// Returns the index of an upvalue named `name`, or -1 if not found.
3207fn search_upvalue(fs: &FuncState, name: &GcRef<LuaString>) -> i32 {
3208    for (i, up) in fs.f.upvalues.iter().enumerate() {
3209        if up.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
3210            return i as i32;
3211        }
3212    }
3213    -1
3214}
3215
3216/// Grows upvalues array and returns index of the new slot.
3217///
3218/// `version` selects the upvalue ceiling and the limit-error wording: Lua 5.1
3219/// caps a function at [`MAX_UPVAL_V51`] = 60 and reports it via
3220/// [`error_limit_v51`] (`"function at line %d has more than 60 upvalues"`),
3221/// while 5.2–5.5 keep [`MAX_UPVAL`] = 255 and the modern [`error_limit`]
3222/// wording.
3223fn alloc_upvalue(
3224    fs: &mut FuncState,
3225    version: lua_types::LuaVersion,
3226) -> Result<usize, LuaError> {
3227    if version == lua_types::LuaVersion::V51 {
3228        if fs.nups as i32 + 1 > MAX_UPVAL_V51 {
3229            return Err(error_limit_v51(fs, MAX_UPVAL_V51, "upvalues"));
3230        }
3231    } else if fs.nups as i32 + 1 > MAX_UPVAL as i32 {
3232        return Err(error_limit(fs, MAX_UPVAL as i32, "upvalues"));
3233    }
3234    let idx = fs.nups as usize;
3235    while fs.f.upvalues.len() <= idx {
3236        fs.f.upvalues.push(UpvalDesc {
3237            name: None,
3238            instack: false,
3239            idx: 0,
3240            kind: 0,
3241        });
3242    }
3243    fs.nups += 1;
3244    Ok(idx)
3245}
3246
3247/// Adds a new upvalue descriptor and returns its index.
3248fn new_upvalue(
3249    ls: &LexState,
3250    fs: &mut FuncState,
3251    name: GcRef<LuaString>,
3252    v: &ExprDesc,
3253) -> Result<i32, LuaError> {
3254    let idx = alloc_upvalue(fs, ls.lex.version)?;
3255    let kind: u8 = if v.k == ExprKind::Local {
3256        let prev = fs
3257            .prev
3258            .as_deref()
3259            .expect("upvalue capture requires enclosing FuncState");
3260        get_local_var_desc(ls, prev, v.u.var_vidx as i32)
3261            .kind
3262            .as_u8()
3263    } else {
3264        let prev = fs
3265            .prev
3266            .as_deref()
3267            .expect("upvalue chain requires enclosing FuncState");
3268        prev.f.upvalues[v.u.info as usize].kind
3269    };
3270    let up = &mut fs.f.upvalues[idx];
3271    if v.k == ExprKind::Local {
3272        up.instack = true;
3273        up.idx = v.u.var_ridx;
3274    } else {
3275        up.instack = false;
3276        up.idx = v.u.info as u8;
3277    }
3278    up.kind = kind;
3279    up.name = Some(name);
3280    Ok(fs.nups as i32 - 1)
3281}
3282
3283/// Searches the active local variables of `fs` for one named `n`, scanning
3284/// from the most-recently-declared backwards so that the innermost shadowing
3285/// declaration wins. On a hit it initializes `var` (its [`ExprKind`] is readable
3286/// from `var.k`) and returns the WITHIN-FUNCTION local index `i` of the found
3287/// declaration; on a miss it returns `-1`.
3288///
3289/// The returned index (rather than the kind) is what the caller needs: it feeds
3290/// [`scope_level_of_local_in`] so the 5.5 per-frame resolver can compare the
3291/// found local/const/vararg's declaration scope level against a matching
3292/// `global` barrier's level (`singlevaraux`). All hit kinds are `>= 0`, so the
3293/// caller's `>= 0` "found?" gate is unchanged.
3294fn searchvar(ls: &LexState, fs: &FuncState, n: &GcRef<LuaString>, var: &mut ExprDesc) -> i32 {
3295    for i in (0..fs.nactvar as i32).rev() {
3296        let vd = get_local_var_desc(ls, fs, i);
3297        if vd.name.as_ref().is_some_and(|nm| GcRef::ptr_eq(nm, n)) {
3298            if vd.kind == VarKind::CompileTimeConst {
3299                init_exp(var, ExprKind::Const, fs.firstlocal + i);
3300                // `u.info` keeps the ABSOLUTE actvar index (check_readonly reads
3301                // it). The value snapshot lets discharge fold the constant from
3302                // the ExprDesc alone (§4.0.A); `var_vidx` is the within-function
3303                // local index so the 5.5 global-shadowing barrier can compute
3304                // this constant's scope level (§4.4).
3305                var.u.const_snapshot = Some(vd.const_val.clone());
3306                var.u.var_vidx = i as u16;
3307            } else {
3308                init_var(ls, fs, var, i);
3309                var.u.const_snapshot = None;
3310                if vd.kind == VarKind::VarArg {
3311                    var.k = ExprKind::VarArgVar;
3312                }
3313            }
3314            return i;
3315        }
3316    }
3317    -1
3318}
3319
3320/// Marks the block where the variable at `level` was defined as having an upvalue.
3321fn markupval(fs: &mut FuncState, level: i32) {
3322    let mut current = fs.bl.as_deref_mut();
3323    while let Some(b) = current {
3324        if (b.nactvar as i32) <= level {
3325            b.upval = true;
3326            break;
3327        }
3328        current = b.previous.as_deref_mut();
3329    }
3330    fs.needclose = true;
3331}
3332
3333fn marktobeclosed(fs: &mut FuncState) {
3334    if let Some(bl) = fs.bl.as_mut() {
3335        bl.upval = true;
3336        bl.insidetbc = true;
3337    }
3338    fs.needclose = true;
3339}
3340
3341// ── §5 Variable resolution ───────────────────────────────────────────────────
3342
3343/// Recursively finds variable `n` in `fs` and its enclosing functions.
3344/// If not found at any level, sets var->k = VVOID (global).
3345///
3346/// Lua 5.5's `global x` barrier decision is made HERE, at each recursion frame,
3347/// BEFORE any capture side effect (`markupval` / `mark_vararg_table_needed` /
3348/// `search_upvalue` / `new_upvalue`) — exactly where reference 5.5's
3349/// `searchvar`/`singlevaraux` make it (`lparser.c`). A post-hoc check in
3350/// `singlevar` cannot work: `new_upvalue` has already incremented `fs.nups` and
3351/// `close_func` preserves the slot, so a later `var.k = Void` would leave a
3352/// phantom upvalue the reference never creates (issue #304 §2).
3353///
3354/// `upper` is the EXCLUSIVE upper bound of this frame's barrier slice in
3355/// `ls.scope_barriers`. Each frame's slice is `[fs.first_scope_barrier .. upper]`;
3356/// recursion into the enclosing function passes `upper = fs.first_scope_barrier`,
3357/// so every outer frame sees only its own barriers (§3). On ≤5.4
3358/// `ls.scope_barriers` is empty, the slice is empty, no `global` barrier ever
3359/// matches, and the local always wins — byte-identical to the pre-5.5 path.
3360fn singlevaraux(
3361    ls: &LexState,
3362    fs: Option<&mut FuncState>,
3363    n: &GcRef<LuaString>,
3364    var: &mut ExprDesc,
3365    base: bool,
3366    upper: usize,
3367) -> Result<(), LuaError> {
3368    match fs {
3369        None => {
3370            init_exp(var, ExprKind::Void, 0);
3371        }
3372        Some(fs) => {
3373            let lower = fs.first_scope_barrier;
3374            let hi = upper.min(ls.scope_barriers.len());
3375            let lo = lower.min(hi);
3376            let slice = &ls.scope_barriers[lo..hi];
3377            let global_level = latest_matching_global_barrier_in_slice(slice, n);
3378            let found_idx = searchvar(ls, fs, n, var);
3379            let local_wins = if found_idx >= 0 {
3380                let local_level = scope_level_of_local_in(fs, slice, found_idx);
3381                match global_level {
3382                    Some(g) => local_level > g,
3383                    None => true,
3384                }
3385            } else {
3386                false
3387            };
3388            if local_wins {
3389                if !base {
3390                    if var.k == ExprKind::VarArgVar {
3391                        mark_vararg_table_needed(fs);
3392                        var.k = ExprKind::Local;
3393                    }
3394                    if var.k == ExprKind::Local {
3395                        markupval(fs, var.u.var_vidx as i32);
3396                    }
3397                }
3398            } else if global_level.is_some() {
3399                init_exp(var, ExprKind::Void, 0);
3400            } else {
3401                let idx = search_upvalue(fs, n);
3402                let final_idx = if idx < 0 {
3403                    singlevaraux(ls, fs.prev.as_deref_mut(), n, var, false, lower)?;
3404                    if var.k == ExprKind::Local
3405                        || var.k == ExprKind::VarArgVar
3406                        || var.k == ExprKind::UpVal
3407                    {
3408                        if var.k == ExprKind::VarArgVar {
3409                            var.k = ExprKind::Local;
3410                        }
3411                        new_upvalue(ls, fs, n.clone(), var)?
3412                    } else {
3413                        return Ok(());
3414                    }
3415                } else {
3416                    idx
3417                };
3418                init_exp(var, ExprKind::UpVal, final_idx);
3419            }
3420        }
3421    }
3422    Ok(())
3423}
3424
3425/// Finds the variable named by the next TK_NAME token.
3426fn singlevar(ls: &mut LexState, state: &mut LuaState, var: &mut ExprDesc) -> Result<(), LuaError> {
3427    let name_line = ls.linenumber;
3428    let varname = str_check_name(ls, state)?;
3429    let upper = ls.scope_barriers.len();
3430    let mut fs_box = ls.fs.take();
3431    let recurse_result = singlevaraux(ls, fs_box.as_deref_mut(), &varname, var, true, upper);
3432    ls.fs = fs_box;
3433    recurse_result?;
3434    if var.k == ExprKind::Void {
3435        // Lua 5.5: once a scope is in strict mode (an explicit `global`
3436        // declaration was seen), a free name must be a declared global —
3437        // otherwise it is a compile-time error (manual §2.2). `global_strict`
3438        // is only ever set on the 5.5 path, so pre-5.5 resolution is unchanged.
3439        let mut declared_const: Option<bool> = None;
3440        for (n, c) in ls.declared_globals.iter().rev() {
3441            if GcRef::ptr_eq(n, &varname) {
3442                declared_const = Some(*c);
3443                break;
3444            }
3445        }
3446        let is_const_global = match declared_const {
3447            Some(c) => c,
3448            None if ls.global_wildcard => ls.global_wildcard_const,
3449            None if ls.global_strict => {
3450                let msg = format!(
3451                    "variable '{}' not declared",
3452                    String::from_utf8_lossy(varname.as_bytes())
3453                );
3454                // Semantic error (C's luaK_semerror): no "near <token>" suffix.
3455                let saved_line = ls.lex.linenumber;
3456                ls.lex.linenumber = name_line;
3457                let err = lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0);
3458                ls.lex.linenumber = saved_line;
3459                return Err(err);
3460            }
3461            None => false,
3462        };
3463        let envn = ls
3464            .envn
3465            .clone()
3466            .expect("envn must be set when resolving globals");
3467        let mut env_var = ExprDesc::default();
3468        let upper = ls.scope_barriers.len();
3469        let mut fs_box = ls.fs.take();
3470        let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut env_var, true, upper);
3471        ls.fs = fs_box;
3472        r?;
3473        // Reference `buildglobal`: if `_ENV` itself resolves to a shadowing
3474        // global (`env_var.k == Void`), there is no environment to index —
3475        // raise the semantic error rather than pass `Void` to codegen (§5).
3476        if env_var.k == ExprKind::Void {
3477            let msg = format!(
3478                "{} is global when accessing variable '{}'",
3479                lua_lex::LUA_ENV.escape_ascii(),
3480                String::from_utf8_lossy(varname.as_bytes())
3481            );
3482            return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
3483        }
3484        let line = ls.lastline;
3485        let fs = ls.fs.as_mut().unwrap();
3486        cg_exp_to_any_reg_up(fs, line, &mut env_var)?;
3487        let mut key = ExprDesc::default();
3488        let const_name = if is_const_global {
3489            Some(varname.clone())
3490        } else {
3491            None
3492        };
3493        codestring(&mut key, varname);
3494        cg_indexed(fs, line, &mut env_var, &mut key)?;
3495        *var = env_var;
3496        var.u.global_const_name = const_name;
3497    }
3498    Ok(())
3499}
3500
3501fn adjust_assign(
3502    ls: &mut LexState,
3503    _state: &mut LuaState,
3504    nvars: i32,
3505    nexps: i32,
3506    e: &mut ExprDesc,
3507) -> Result<(), LuaError> {
3508    let needed = nvars - nexps;
3509    let line = ls.lastline;
3510    let fs = ls.fs.as_mut().unwrap();
3511    if e.k.has_mult_ret() {
3512        let extra = if needed + 1 < 0 { 0 } else { needed + 1 };
3513        cg_set_returns(fs, e, extra);
3514    } else {
3515        if e.k != ExprKind::Void {
3516            cg_exp_to_next_reg(fs, line, e)?;
3517        }
3518        if needed > 0 {
3519            let from = fs.freereg as i32;
3520            cg_emit_nil(fs, line, from, needed);
3521        }
3522    }
3523    if needed > 0 {
3524        for _ in 0..needed {
3525            reserve_reg(fs)?;
3526        }
3527    } else {
3528        fs.freereg = (fs.freereg as i32 + needed) as u8;
3529    }
3530    Ok(())
3531}
3532
3533/// Emits `OP_NEWTABLE` followed by the required `OP_EXTRAARG` slot. The two
3534/// instructions are written as placeholders; `cg_settablesize` later patches
3535/// them with the final array/hash sizes. Returns the pc of `OP_NEWTABLE`.
3536fn cg_emit_newtable(fs: &mut FuncState, line: i32) -> i32 {
3537    let newtable =
3538        lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::NewTable, 0, 0, 0, 0);
3539    let pc = emit_inst(fs, line, newtable);
3540    let extra = lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, 0);
3541    emit_inst(fs, line, extra);
3542    pc
3543}
3544
3545/// Patches a previously-emitted `OP_NEWTABLE`/`OP_EXTRAARG` pair with the
3546/// final array size (`asize`) and hash size (`hsize`). Mirrors
3547/// `luaK_settablesize` from `lcode.c`.
3548fn cg_settablesize(fs: &mut FuncState, pc: i32, ra: i32, asize: i32, hsize: i32) {
3549    let rb = if hsize != 0 {
3550        (hsize as u32).next_power_of_two().trailing_zeros() as i32 + 1
3551    } else {
3552        0
3553    };
3554    let maxc = lua_code::opcodes::MAXARG_C as i32 + 1;
3555    let extra = asize / maxc;
3556    let rc = asize % maxc;
3557    let k = if extra > 0 { 1u32 } else { 0u32 };
3558    let newtable = lua_code::opcodes::Instruction::abck(
3559        lua_code::opcodes::OpCode::NewTable,
3560        ra as u32,
3561        rb as u32,
3562        rc as u32,
3563        k,
3564    );
3565    fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(newtable.0);
3566    let extra_inst =
3567        lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, extra as u32);
3568    fs.f.code[pc as usize + 1] = lua_types::opcode::Instruction::new(extra_inst.0);
3569}
3570
3571/// Emits `OP_SETLIST` for `tostore` elements starting at `base+1`, with
3572/// `nelems` already-stored elements preceding them. `tostore == -1` means
3573/// `LUA_MULTRET` (encoded as 0 in the B field). Also resets `fs.freereg`
3574/// to `base + 1`, mirroring `luaK_setlist`.
3575fn cg_setlist(fs: &mut FuncState, line: i32, base: i32, nelems: i32, tostore: i32) {
3576    let maxc = lua_code::opcodes::MAXARG_C as i32;
3577    let tostore_arg = if tostore == LUA_MULTRET { 0 } else { tostore };
3578    if nelems <= maxc {
3579        let inst = lua_code::opcodes::Instruction::abck(
3580            lua_code::opcodes::OpCode::SetList,
3581            base as u32,
3582            tostore_arg as u32,
3583            nelems as u32,
3584            0,
3585        );
3586        emit_inst(fs, line, inst);
3587    } else {
3588        let extra = nelems / (maxc + 1);
3589        let nelems_lo = nelems % (maxc + 1);
3590        let inst = lua_code::opcodes::Instruction::abck(
3591            lua_code::opcodes::OpCode::SetList,
3592            base as u32,
3593            tostore_arg as u32,
3594            nelems_lo as u32,
3595            1,
3596        );
3597        emit_inst(fs, line, inst);
3598        let extra_inst =
3599            lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, extra as u32);
3600        emit_inst(fs, line, extra_inst);
3601    }
3602    fs.freereg = (base + 1) as u8;
3603}
3604
3605/// Converts a table-and-key expression pair into the appropriate `VINDEX*`
3606/// variant. Mirrors `luaK_indexed` from `lcode.c`. Assumes `t` is already a
3607/// value-producing form (`VLOCAL`, `VNONRELOC`, or `VUPVAL`) and that any
3608/// short-string key has already been promoted to a `VKSTR` constant index.
3609fn cg_indexed(
3610    fs: &mut FuncState,
3611    line: i32,
3612    t: &mut ExprDesc,
3613    k: &mut ExprDesc,
3614) -> Result<(), LuaError> {
3615    t.u.global_const_name = None;
3616    if k.k == ExprKind::KStr {
3617        let s =
3618            k.u.strval
3619                .clone()
3620                .ok_or_else(|| LuaError::syntax(format_args!("internal: VKStr with no strval")))?;
3621        let k_idx = add_k_string(fs, s);
3622        k.u.info = k_idx;
3623        k.k = ExprKind::K;
3624    }
3625    let k_is_kstr =
3626        k.k == ExprKind::K && k.u.info >= 0 && (k.u.info as u32) <= lua_code::opcodes::MAXARG_B;
3627    if t.k == ExprKind::VarArgVar {
3628        cg_exp_to_any_reg(fs, line, k)?;
3629        t.u.ind_t = t.u.var_ridx;
3630        t.u.ind_idx = k.u.info as i16;
3631        t.k = ExprKind::VarArgIndex;
3632        return Ok(());
3633    }
3634    if t.k == ExprKind::UpVal && !k_is_kstr {
3635        cg_exp_to_any_reg(fs, line, t)?;
3636    }
3637    if t.k == ExprKind::UpVal {
3638        let temp = t.u.info as u8;
3639        t.u.ind_t = temp;
3640        t.u.ind_idx = k.u.info as i16;
3641        t.k = ExprKind::IndexUp;
3642        return Ok(());
3643    }
3644    let t_reg = match t.k {
3645        ExprKind::Local => t.u.var_ridx,
3646        ExprKind::NonReloc => t.u.info as u8,
3647        _ => {
3648            return Err(LuaError::syntax(format_args!(
3649                "internal: cg_indexed on non-register table kind {:?}",
3650                t.k
3651            )))
3652        }
3653    };
3654    t.u.ind_t = t_reg;
3655    if k.k == ExprKind::K && k_is_kstr {
3656        t.u.ind_idx = k.u.info as i16;
3657        t.k = ExprKind::IndexStr;
3658    } else if k.k == ExprKind::KInt && cg_fits_int_key(k.u.ival) {
3659        t.u.ind_idx = k.u.ival as i16;
3660        t.k = ExprKind::IndexI;
3661    } else {
3662        cg_exp_to_any_reg(fs, line, k)?;
3663        t.u.ind_idx = k.u.info as i16;
3664        t.k = ExprKind::Indexed;
3665    }
3666    Ok(())
3667}
3668
3669fn cg_fits_int_key(i: i64) -> bool {
3670    i >= 0 && (i as u32) <= lua_code::opcodes::MAXARG_C
3671}
3672
3673/// Emits OP_SELF, converting `e:key(...)` into the equivalent of `(e.key)(e, ...)`.
3674/// Leaves `e` as VNONRELOC pointing at the function register (base); the self
3675/// register is `base + 1`. `key` must be a string expression (VKStr).
3676fn cg_self(
3677    fs: &mut FuncState,
3678    line: i32,
3679    e: &mut ExprDesc,
3680    key: &mut ExprDesc,
3681    keep_self_opcode_for_register_key: bool,
3682) -> Result<(), LuaError> {
3683    cg_exp_to_any_reg(fs, line, e)?;
3684    let ereg = e.u.info;
3685    cg_free_exp(fs, e);
3686    let base = fs.freereg as i32;
3687    e.u.info = base;
3688    e.k = ExprKind::NonReloc;
3689    reserve_regs(fs, 2)?;
3690    let key_str = key.u.strval.clone().ok_or_else(|| {
3691        LuaError::syntax(format_args!(
3692            "internal: cg_self expected VKStr key, got {:?}",
3693            key.k
3694        ))
3695    })?;
3696    let k_idx = add_k_string(fs, key_str);
3697    if (k_idx as u32) <= lua_code::opcodes::MAXINDEXRK {
3698        let inst = lua_code::opcodes::Instruction::abck(
3699            lua_code::opcodes::OpCode::Self_,
3700            base as u32,
3701            ereg as u32,
3702            k_idx as u32,
3703            1,
3704        );
3705        emit_inst(fs, line, inst);
3706    } else if keep_self_opcode_for_register_key {
3707        key.k = ExprKind::K;
3708        key.u.info = k_idx;
3709        cg_exp_to_any_reg(fs, line, key)?;
3710        let inst = lua_code::opcodes::Instruction::abck(
3711            lua_code::opcodes::OpCode::Self_,
3712            base as u32,
3713            ereg as u32,
3714            key.u.info as u32,
3715            0,
3716        );
3717        emit_inst(fs, line, inst);
3718    } else {
3719        key.k = ExprKind::K;
3720        key.u.info = k_idx;
3721        cg_exp_to_any_reg(fs, line, key)?;
3722        let move_inst = lua_code::opcodes::Instruction::abck(
3723            lua_code::opcodes::OpCode::Move,
3724            (base + 1) as u32,
3725            ereg as u32,
3726            0,
3727            0,
3728        );
3729        emit_inst(fs, line, move_inst);
3730        let get_inst = lua_code::opcodes::Instruction::abck(
3731            lua_code::opcodes::OpCode::GetTable,
3732            base as u32,
3733            ereg as u32,
3734            key.u.info as u32,
3735            0,
3736        );
3737        emit_inst(fs, line, get_inst);
3738    }
3739    cg_free_exp(fs, key);
3740    Ok(())
3741}
3742
3743/// Minimal `luaK_exp2anyregup`: if `e` is an upvalue or constant, leave it as
3744/// is; otherwise discharge it into some register.
3745fn cg_exp_to_any_reg_up(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
3746    if matches!(e.k, ExprKind::UpVal | ExprKind::K | ExprKind::VarArgVar) {
3747        return Ok(());
3748    }
3749    cg_exp_to_any_reg(fs, line, e)?;
3750    Ok(())
3751}
3752
3753/// Minimal `luaK_nil`: emits a LoadNil instruction filling `n` consecutive
3754/// registers starting at `from` with `nil`. Does not perform the C
3755/// optimization that merges with a preceding LoadNil.
3756fn cg_emit_nil(fs: &mut FuncState, line: i32, from: i32, n: i32) {
3757    let inst = lua_code::opcodes::Instruction::abck(
3758        lua_code::opcodes::OpCode::LoadNil,
3759        from as u32,
3760        (n - 1) as u32,
3761        0,
3762        0,
3763    );
3764    emit_inst(fs, line, inst);
3765}
3766
3767// ── §6 Label / goto management ───────────────────────────────────────────────
3768
3769fn current_scope_level(ls: &LexState) -> u8 {
3770    let (local_count, first_barrier) = ls.fs.as_ref().map_or((0usize, 0usize), |fs| {
3771        (fs.nactvar as usize, fs.first_scope_barrier)
3772    });
3773    let barrier_count = ls.scope_barriers.len().saturating_sub(first_barrier);
3774    let level = local_count + barrier_count;
3775    level.min(u8::MAX as usize) as u8
3776}
3777
3778fn local_level_for_scope_level(ls: &LexState, scope_level: u8) -> i32 {
3779    let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3780    let barriers_before = ls.scope_barriers[first_barrier..]
3781        .iter()
3782        .filter(|b| b.level < scope_level)
3783        .count();
3784    let locals = scope_level as i32 - barriers_before as i32;
3785    let max_locals = ls.fs.as_ref().map_or(0i32, |fs| fs.nactvar as i32);
3786    locals.clamp(0, max_locals)
3787}
3788
3789fn add_scope_barrier(ls: &mut LexState, name: GcRef<LuaString>) {
3790    let level = current_scope_level(ls);
3791    ls.scope_barriers.push(ScopeBarrier { level, name });
3792}
3793
3794/// The level of the latest (declaration-order last) `global <name>` barrier in
3795/// a frame's barrier `slice`, or `None` if the frame declares no matching
3796/// `global`. Barriers are pushed in declaration order, so `rev().find` yields the
3797/// most recent one; its level is compared strictly (`>`) against a found local's
3798/// scope level so a later declaration — global or local — wins, exactly like
3799/// reference 5.5's newest-first `searchvar` scan over `actvar` (`lparser.c:414`).
3800fn latest_matching_global_barrier_in_slice(
3801    slice: &[ScopeBarrier],
3802    name: &GcRef<LuaString>,
3803) -> Option<u8> {
3804    slice
3805        .iter()
3806        .rev()
3807        .find(|b| GcRef::ptr_eq(&b.name, name))
3808        .map(|b| b.level)
3809}
3810
3811/// The scope level (declaration ordinal) of the `local_index`-th register/CTC
3812/// local in `fs`, given `fs`'s active global-barrier `slice`. Used during the
3813/// per-frame resolution walk in [`singlevaraux`] to place a found local on the
3814/// same level axis as the `global` barriers so the two can be ordered. Barriers
3815/// occupy their own levels; locals fill the gaps, so the level of the k-th local
3816/// is the (k+1)-th non-barrier level.
3817fn scope_level_of_local_in(fs: &FuncState, slice: &[ScopeBarrier], local_index: i32) -> u8 {
3818    let scope_level_max = fs.nactvar as usize + slice.len();
3819    let target = local_index.max(0) as usize;
3820    let mut locals_seen = 0usize;
3821    for level in 0..=scope_level_max {
3822        let lvl = level.min(u8::MAX as usize) as u8;
3823        if slice.iter().any(|b| b.level == lvl) {
3824            continue;
3825        }
3826        if locals_seen == target {
3827            return lvl;
3828        }
3829        locals_seen += 1;
3830    }
3831    local_index.max(0).min(u8::MAX as i32) as u8
3832}
3833
3834fn scope_name_at(ls: &LexState, level: u8, label_nactvar: u8) -> Vec<u8> {
3835    let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3836    for scope_level in level..label_nactvar {
3837        if let Some(barrier) = ls.scope_barriers[first_barrier..]
3838            .iter()
3839            .find(|b| b.level == scope_level)
3840        {
3841            return barrier.name.as_bytes().to_vec();
3842        }
3843
3844        let barriers_before = ls.scope_barriers[first_barrier..]
3845            .iter()
3846            .filter(|b| b.level < scope_level)
3847            .count();
3848        let vidx = scope_level as i32 - barriers_before as i32;
3849        if vidx < 0 {
3850            continue;
3851        }
3852        if let Some(name) = ls.fs.as_ref().and_then(|fs| {
3853            if (fs.firstlocal + vidx) >= 0
3854                && ((fs.firstlocal + vidx) as usize) < ls.dyd.actvar.len()
3855            {
3856                let vd = get_local_var_desc(ls, fs, vidx);
3857                vd.name.as_ref().map(|n| n.as_bytes().to_vec())
3858            } else {
3859                None
3860            }
3861        }) {
3862            return name;
3863        }
3864    }
3865
3866    b"*".to_vec()
3867}
3868
3869fn jumpscopeerror(
3870    ls: &LexState,
3871    version: lua_types::LuaVersion,
3872    gt_idx: usize,
3873    label_nactvar: u8,
3874) -> LuaError {
3875    let gt = &ls.dyd.gt[gt_idx];
3876    let line = gt.line;
3877    let gt_name_bytes: &[u8] = gt.name.as_ref().map(|n| n.as_bytes()).unwrap_or(b"");
3878    let gt_name = String::from_utf8_lossy(gt_name_bytes);
3879    let varname_bytes = scope_name_at(ls, gt.nactvar, label_nactvar);
3880    let varname = String::from_utf8_lossy(&varname_bytes);
3881    if version == lua_types::LuaVersion::V55 {
3882        LuaError::syntax(format_args!(
3883            "<goto {}> at line {} jumps into the scope of '{}'",
3884            gt_name, line, varname
3885        ))
3886    } else {
3887        LuaError::syntax(format_args!(
3888            "<goto {}> at line {} jumps into the scope of local '{}'",
3889            gt_name, line, varname
3890        ))
3891    }
3892}
3893
3894/// Resolves goto at index `g` to `label`, removing it from pending list.
3895fn solvegoto(
3896    ls: &mut LexState,
3897    state: &mut LuaState,
3898    g: usize,
3899    label_pc: i32,
3900    label_nactvar: u8,
3901) -> Result<(), LuaError> {
3902    if ls.dyd.gt[g].nactvar < label_nactvar {
3903        let version = state.global().lua_version;
3904        return Err(jumpscopeerror(ls, version, g, label_nactvar));
3905    }
3906    let gt_pc = ls.dyd.gt[g].pc;
3907    cg_patch_list(ls.fs.as_mut().unwrap(), gt_pc, label_pc)?;
3908    ls.dyd.gt.remove(g);
3909    Ok(())
3910}
3911
3912/// Searches for an active label with the given name, starting the scan at the
3913/// label-list index `first`.
3914///
3915/// The scan-start encodes the version-specific scope of goto resolution. In Lua
3916/// 5.2/5.3, upstream `gotostat` resolves a goto against labels of the **current
3917/// block only** (`fs->bl->firstlabel`); a goto that matches no current-block
3918/// label stays pending and is resolved later when its label is declared (or is
3919/// moved out to the enclosing block on block exit). In 5.4/5.5 `findlabel` was
3920/// changed to scan the whole function (`fs->firstlabel`).
3921fn findlabel_from(ls: &LexState, name: &GcRef<LuaString>, first: usize) -> Option<usize> {
3922    for i in first..ls.dyd.label.len() {
3923        let lb = &ls.dyd.label[i];
3924        if lb.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
3925            return Some(i);
3926        }
3927    }
3928    None
3929}
3930
3931/// Resolves a goto against labels visible per the active version's rules.
3932///
3933/// 5.2/5.3 scan only the current block; 5.4/5.5 scan the whole function.
3934fn findlabel_for_goto(ls: &LexState, state: &LuaState, name: &GcRef<LuaString>) -> Option<usize> {
3935    let block_scoped = matches!(
3936        state.global().lua_version,
3937        lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3938    );
3939    let first = if block_scoped {
3940        ls.fs
3941            .as_ref()
3942            .unwrap()
3943            .bl
3944            .as_ref()
3945            .map_or(0, |b| b.firstlabel) as usize
3946    } else {
3947        ls.fs.as_ref().unwrap().firstlabel as usize
3948    };
3949    findlabel_from(ls, name, first)
3950}
3951
3952/// Adds a new label/goto entry; returns its index.
3953fn new_label_entry(
3954    ls: &mut LexState,
3955    _state: &mut LuaState,
3956    is_goto: bool,
3957    name: GcRef<LuaString>,
3958    line: i32,
3959    pc: i32,
3960) -> Result<usize, LuaError> {
3961    let nactvar = current_scope_level(ls);
3962    let entry = LabelDesc {
3963        name: Some(name),
3964        pc,
3965        line,
3966        nactvar,
3967        close: false,
3968    };
3969    let list = if is_goto {
3970        &mut ls.dyd.gt
3971    } else {
3972        &mut ls.dyd.label
3973    };
3974    let n = list.len();
3975    list.push(entry);
3976    Ok(n)
3977}
3978
3979fn new_goto_entry(
3980    ls: &mut LexState,
3981    state: &mut LuaState,
3982    name: GcRef<LuaString>,
3983    line: i32,
3984    pc: i32,
3985) -> Result<usize, LuaError> {
3986    new_label_entry(ls, state, true, name, line, pc)
3987}
3988
3989/// Resolves all pending gotos that match label `lb`.
3990/// Returns true if any goto needed close.
3991fn solvegotos(ls: &mut LexState, state: &mut LuaState, lb_idx: usize) -> Result<bool, LuaError> {
3992    let lb_name = ls.dyd.label[lb_idx].name.clone();
3993    let lb_pc = ls.dyd.label[lb_idx].pc;
3994    let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
3995    let first_goto = ls
3996        .fs
3997        .as_ref()
3998        .unwrap()
3999        .bl
4000        .as_ref()
4001        .map_or(0, |b| b.firstgoto) as usize;
4002
4003    let mut i = first_goto;
4004    let mut needs_close = false;
4005    while i < ls.dyd.gt.len() {
4006        let gt_name = ls.dyd.gt[i].name.clone();
4007        let names_match = lb_name
4008            .as_ref()
4009            .and_then(|ln| gt_name.as_ref().map(|gn| GcRef::ptr_eq(ln, gn)))
4010            .unwrap_or(false);
4011        if names_match {
4012            needs_close |= ls.dyd.gt[i].close;
4013            // solvegoto removes element i, so don't increment i
4014            solvegoto(ls, state, i, lb_pc, lb_nactvar)?;
4015        } else {
4016            i += 1;
4017        }
4018    }
4019    Ok(needs_close)
4020}
4021
4022/// Creates a new label; resolves pending gotos. Returns true if CLOSE emitted.
4023fn createlabel(
4024    ls: &mut LexState,
4025    state: &mut LuaState,
4026    name: GcRef<LuaString>,
4027    line: i32,
4028    last: bool,
4029) -> Result<bool, LuaError> {
4030    let label_pc = cg_get_label(ls.fs.as_mut().unwrap());
4031    let l = new_label_entry(ls, state, false, name, line, label_pc)?;
4032    if last {
4033        let bl_scope_level = ls
4034            .fs
4035            .as_ref()
4036            .unwrap()
4037            .bl
4038            .as_ref()
4039            .map_or(0, |b| b.scope_level);
4040        ls.dyd.label[l].nactvar = bl_scope_level;
4041    }
4042    let needs_close = solvegotos(ls, state, l)?;
4043    if needs_close {
4044        let nstack = nvarstack(ls, ls.fs.as_ref().unwrap()) as u32;
4045        let inst =
4046            lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::Close, nstack, 0, 0, 0);
4047        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4048        return Ok(true);
4049    }
4050    Ok(false)
4051}
4052
4053/// Adjusts pending gotos to outer block level when leaving a block.
4054///
4055/// For 5.4/5.5 this only re-levels the pending gotos to the enclosing block
4056/// (backward gotos were already resolved eagerly in `gotostat`, whose
4057/// `findlabel` scans the whole function). For 5.2/5.3, `gotostat` resolves a
4058/// goto only against the current block, so a backward goto to an enclosing
4059/// block's label is still pending here; upstream 5.3 `movegotosout` re-runs
4060/// the (now current-block-scoped) `findlabel` to close such gotos. This must be
4061/// called *after* the leaving block has been popped, so the current block is
4062/// the enclosing one.
4063fn movegotosout(
4064    ls: &mut LexState,
4065    state: &mut LuaState,
4066    bl_firstgoto: usize,
4067    bl_scope_level: u8,
4068    bl_upval: bool,
4069) -> Result<(), LuaError> {
4070    let reresolve = matches!(
4071        state.global().lua_version,
4072        lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
4073    );
4074    let mut i = bl_firstgoto;
4075    while i < ls.dyd.gt.len() {
4076        if reresolve {
4077            if ls.dyd.gt[i].nactvar > bl_scope_level {
4078                if bl_upval {
4079                    ls.dyd.gt[i].close = true;
4080                }
4081                ls.dyd.gt[i].nactvar = bl_scope_level;
4082            }
4083        } else {
4084            if bl_upval {
4085                ls.dyd.gt[i].close = true;
4086            }
4087            ls.dyd.gt[i].nactvar = bl_scope_level;
4088        }
4089        if reresolve {
4090            let gt_name = ls.dyd.gt[i].name.clone();
4091            let lb_idx = gt_name
4092                .as_ref()
4093                .and_then(|n| findlabel_for_goto(ls, state, n));
4094            if let Some(lb_idx) = lb_idx {
4095                let lb_pc = ls.dyd.label[lb_idx].pc;
4096                let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
4097                let trigger1 = ls.dyd.gt[i].close;
4098                let close_level = goto_close_level(ls, lb_nactvar, bl_scope_level, trigger1);
4099                if let Some(level) = close_level {
4100                    resolve_goto_with_close(ls, state, i, lb_pc, lb_nactvar, level)?;
4101                } else {
4102                    solvegoto(ls, state, i, lb_pc, lb_nactvar)?;
4103                }
4104                continue;
4105            }
4106        }
4107        i += 1;
4108    }
4109    Ok(())
4110}
4111
4112/// Computes the scope level at which a backward goto resolving to an
4113/// enclosing-block label (`label_nactvar`) must close upvalues, or `None` if no
4114/// close is needed.
4115///
4116/// This mirrors the two `luaK_patchclose` callsites upstream 5.3 reaches while
4117/// resolving a pending goto in `movegotosout`:
4118///
4119///   1. `movegotosout` itself: if the exited block captured upvalues and the
4120///      goto leaves that block's scope, close at the exited block's level
4121///      (`bl_scope_level`). This is exactly when the goto entry's `close` flag
4122///      was set just before re-leveling, passed in as `trigger1`.
4123///   2. `findlabel`: if the goto also leaves the target label's scope
4124///      (`bl_scope_level > label_nactvar`, since the goto's level was already
4125///      re-leveled to `bl_scope_level`) and the enclosing block either captured
4126///      upvalues or holds at least one label, close at the *label's* level
4127///      (`label_nactvar`).
4128///
4129/// Upstream applies these with `SETARG_A` so the later (smaller, more inclusive)
4130/// level wins; this returns that minimum. Trigger 2 dominates whenever it fires
4131/// because `label_nactvar <= bl_scope_level` for an enclosing label, so closing
4132/// at the label's level also covers locals declared after the label in the
4133/// label's own block (e.g. `goto.lua`'s `local b` redeclared just after `::l1::`).
4134fn goto_close_level(
4135    ls: &LexState,
4136    label_nactvar: u8,
4137    bl_scope_level: u8,
4138    trigger1: bool,
4139) -> Option<u8> {
4140    let enclosing = ls.fs.as_ref().unwrap().bl.as_ref();
4141    let enclosing_upval = enclosing.map_or(false, |b| b.upval);
4142    let enclosing_has_label =
4143        enclosing.map_or(false, |b| ls.dyd.label.len() as i32 > b.firstlabel);
4144    let trigger2 = bl_scope_level > label_nactvar && (enclosing_upval || enclosing_has_label);
4145    match (trigger1, trigger2) {
4146        (_, true) => Some(label_nactvar),
4147        (true, false) => Some(bl_scope_level),
4148        (false, false) => None,
4149    }
4150}
4151
4152/// Resolves a pending backward goto (index `g`) to an enclosing-block label at
4153/// `label_pc`, closing the upvalues of the locals the goto exits at scope level
4154/// `close_scope_level` (from [`goto_close_level`]).
4155///
4156/// In block-scoped goto (5.2/5.3) a backward goto whose target label lives in an
4157/// enclosing block is resolved here, in `movegotosout`, after the inner block
4158/// has been popped. Upstream lua-c patches the goto's own `OP_JMP` to carry a
4159/// close (`luaK_patchclose`, the JMP's `A` field). This port's bytecode is the
4160/// 5.4 format, whose `OP_JMP` carries no close field — closes are explicit
4161/// `OP_CLOSE` instructions. So instead of patching the JMP in place, this emits a
4162/// `CLOSE; JMP→label` trampoline at the current pc and redirects the goto's
4163/// original JMP to land on the `CLOSE`. The upvalues of the exited locals are
4164/// therefore closed on every backward iteration, giving each iteration a fresh
4165/// upvalue cell (the behavior `goto.lua`'s upvalue-closing tests assert under
4166/// 5.2/5.3).
4167fn resolve_goto_with_close(
4168    ls: &mut LexState,
4169    state: &mut LuaState,
4170    g: usize,
4171    label_pc: i32,
4172    label_nactvar: u8,
4173    close_scope_level: u8,
4174) -> Result<(), LuaError> {
4175    if ls.dyd.gt[g].nactvar < label_nactvar {
4176        let version = state.global().lua_version;
4177        return Err(jumpscopeerror(ls, version, g, label_nactvar));
4178    }
4179    let line = ls.dyd.gt[g].line;
4180    let gt_pc = ls.dyd.gt[g].pc;
4181    let close_local_level = local_level_for_scope_level(ls, close_scope_level);
4182    let close_level = reg_level(ls, ls.fs.as_ref().unwrap(), close_local_level) as u32;
4183    let close_pc = {
4184        let inst = lua_code::opcodes::Instruction::abck(
4185            lua_code::opcodes::OpCode::Close,
4186            close_level,
4187            0,
4188            0,
4189            0,
4190        );
4191        emit_inst(ls.fs.as_mut().unwrap(), line, inst)
4192    };
4193    let jmp_pc = cg_jump(ls.fs.as_mut().unwrap(), line);
4194    cg_patch_list(ls.fs.as_mut().unwrap(), jmp_pc, label_pc)?;
4195    cg_patch_list(ls.fs.as_mut().unwrap(), gt_pc, close_pc)?;
4196    ls.dyd.gt.remove(g);
4197    Ok(())
4198}
4199
4200/// Pushes a new block scope onto fs->bl.
4201fn enter_block(ls: &mut LexState, isloop: bool) {
4202    let firstlabel = ls.dyd.label.len() as i32;
4203    let firstgoto = ls.dyd.gt.len() as i32;
4204    let saved_global_strict = ls.global_strict;
4205    let saved_declared_globals = ls.declared_globals.len();
4206    let saved_global_wildcard = ls.global_wildcard;
4207    let saved_global_wildcard_const = ls.global_wildcard_const;
4208    let saved_scope_barriers = ls.scope_barriers.len();
4209    let scope_level = current_scope_level(ls);
4210    let insidetbc = ls
4211        .fs
4212        .as_ref()
4213        .and_then(|f| f.bl.as_ref())
4214        .map_or(false, |b| b.insidetbc);
4215    let fs = ls.fs.as_mut().unwrap();
4216    let nactvar = fs.nactvar;
4217    let new_bl = Box::new(BlockCnt {
4218        previous: fs.bl.take(),
4219        firstlabel,
4220        firstgoto,
4221        nactvar,
4222        scope_level,
4223        upval: false,
4224        isloop,
4225        insidetbc,
4226        saved_global_strict,
4227        saved_declared_globals,
4228        saved_global_wildcard,
4229        saved_global_wildcard_const,
4230        saved_scope_barriers,
4231    });
4232    fs.bl = Some(new_bl);
4233}
4234
4235fn undef_goto(ls: &mut LexState, version: lua_types::LuaVersion, gt_idx: usize) -> LuaError {
4236    let (line, name_bytes): (i32, Vec<u8>) = {
4237        let gt = &ls.dyd.gt[gt_idx];
4238        (
4239            gt.line,
4240            gt.name
4241                .as_ref()
4242                .map(|n| n.as_bytes().to_vec())
4243                .unwrap_or_default(),
4244        )
4245    };
4246    let msg = if name_bytes == b"break" {
4247        // 5.2/5.3 word the deferred break-outside-loop error differently from
4248        // 5.4. (5.1/5.5 raise eagerly in `breakstat` and never reach here.)
4249        if matches!(
4250            version,
4251            lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
4252        ) {
4253            format!("<break> at line {} not inside a loop", line)
4254        } else {
4255            format!("break outside loop at line {}", line)
4256        }
4257    } else {
4258        let name_str = String::from_utf8_lossy(&name_bytes);
4259        format!(
4260            "no visible label '{}' for <goto> at line {}",
4261            name_str, line
4262        )
4263    };
4264    lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0)
4265}
4266
4267/// Pops the innermost block scope, emitting CLOSE if needed.
4268fn leave_block(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4269    // Snapshot block fields without popping; createlabel below relies on
4270    // fs->bl still pointing at this (loop) block so solvegotos can read
4271    // fs->bl->firstgoto.
4272    let (bl_nactvar, bl_scope_level, bl_isloop, bl_upval, bl_firstgoto, bl_firstlabel) = {
4273        let bl = ls
4274            .fs
4275            .as_ref()
4276            .unwrap()
4277            .bl
4278            .as_ref()
4279            .expect("leave_block: no current block");
4280        (
4281            bl.nactvar,
4282            bl.scope_level,
4283            bl.isloop,
4284            bl.upval,
4285            bl.firstgoto,
4286            bl.firstlabel,
4287        )
4288    };
4289
4290    // Lua 5.5: restore the `global`-declaration scope to what it was on block
4291    // entry, so an explicit `global` decl (and the strict mode it triggers) is
4292    // confined to its enclosing block.
4293    {
4294        let (sgs, sdg, sgw, sgwc, ssb) = {
4295            let bl = ls.fs.as_ref().unwrap().bl.as_ref().unwrap();
4296            (
4297                bl.saved_global_strict,
4298                bl.saved_declared_globals,
4299                bl.saved_global_wildcard,
4300                bl.saved_global_wildcard_const,
4301                bl.saved_scope_barriers,
4302            )
4303        };
4304        ls.global_strict = sgs;
4305        ls.declared_globals.truncate(sdg);
4306        ls.global_wildcard = sgw;
4307        ls.global_wildcard_const = sgwc;
4308        ls.scope_barriers.truncate(ssb);
4309    }
4310
4311    let stklevel = reg_level(ls, ls.fs.as_ref().unwrap(), bl_nactvar as i32);
4312    let mut fs_box = ls.fs.take().unwrap();
4313    remove_vars(ls, &mut fs_box, bl_nactvar as i32);
4314    debug_assert!(bl_nactvar == fs_box.nactvar);
4315    ls.fs = Some(fs_box);
4316
4317    let hasclose = if bl_isloop {
4318        let break_str = state.intern_str(b"break")?;
4319        createlabel(ls, state, break_str, 0, false)?
4320    } else {
4321        false
4322    };
4323
4324    // Now pop the block off fs.bl, restoring its previous link.
4325    let mut bl_box = ls.fs.as_mut().unwrap().bl.take().unwrap();
4326    let previous = bl_box.previous.take();
4327    ls.fs.as_mut().unwrap().bl = previous;
4328
4329    let has_prev_block = ls.fs.as_ref().unwrap().bl.is_some();
4330    if !hasclose && has_prev_block && bl_upval {
4331        // Use `lastline` so the OP_CLOSE attributes to the block's terminating
4332        // token (END/UNTIL) rather than whatever the parser has peeked to next.
4333        // Mirrors lua-c's `savelineinfo(fs, f, fs->ls->lastline)`.
4334        let line = ls.lastline;
4335        let inst = lua_code::opcodes::Instruction::abck(
4336            lua_code::opcodes::OpCode::Close,
4337            stklevel as u32,
4338            0,
4339            0,
4340            0,
4341        );
4342        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4343    }
4344    ls.fs.as_mut().unwrap().freereg = stklevel as u8;
4345
4346    ls.dyd.label.truncate(bl_firstlabel as usize);
4347
4348    if has_prev_block {
4349        movegotosout(ls, state, bl_firstgoto as usize, bl_scope_level, bl_upval)?;
4350    } else {
4351        if (bl_firstgoto as usize) < ls.dyd.gt.len() {
4352            let version = state.global().lua_version;
4353            return Err(undef_goto(ls, version, bl_firstgoto as usize));
4354        }
4355    }
4356    Ok(())
4357}
4358
4359// ── §7 Proto management ──────────────────────────────────────────────────────
4360
4361/// Adds a new prototype slot to the current function's proto list.
4362/// Returns a mutable reference to the new prototype.
4363fn add_prototype(ls: &mut LexState, _state: &mut LuaState) -> Result<Box<LuaProto>, LuaError> {
4364    let np = ls.fs.as_ref().unwrap().np as usize;
4365    let new_proto = Box::new(LuaProto::placeholder());
4366    while ls.fs.as_ref().unwrap().f.p.len() <= np {
4367        ls.fs
4368            .as_mut()
4369            .unwrap()
4370            .f
4371            .p
4372            .push(GcRef::new(LuaProto::placeholder()));
4373    }
4374    ls.fs.as_mut().unwrap().np += 1;
4375    Ok(new_proto)
4376}
4377
4378/// Emits OP_CLOSURE in the parent function and fixes up v.
4379fn codeclosure(ls: &mut LexState, _state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4380    let line = ls.lastline;
4381    let mut child = ls.fs.take().expect("codeclosure: no current FuncState");
4382    let result = (|| -> Result<(), LuaError> {
4383        let parent = child
4384            .prev
4385            .as_mut()
4386            .expect("codeclosure: child FuncState has no parent (called outside body()?)");
4387        let bx = (parent.np - 1) as u32;
4388        let inst = lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::Closure, 0, bx);
4389        let pc = emit_inst(parent, line, inst);
4390        init_exp(v, ExprKind::Reloc, pc);
4391        cg_exp_to_next_reg(parent, line, v)
4392    })();
4393    ls.fs = Some(child);
4394    result
4395}
4396
4397/// Installs `new_fs` as the current FuncState, pushing old one as `prev`.
4398fn open_func(
4399    ls: &mut LexState,
4400    _state: &mut LuaState,
4401    mut new_fs: FuncState,
4402) -> Result<(), LuaError> {
4403    new_fs.prev = ls.fs.take();
4404
4405    let f = &mut new_fs.f;
4406    new_fs.pc = 0;
4407    new_fs.previousline = f.linedefined;
4408    new_fs.iwthabs = 0;
4409    new_fs.lasttarget = 0;
4410    new_fs.freereg = 0;
4411    new_fs.nk = 0;
4412    new_fs.nabslineinfo = 0;
4413    new_fs.np = 0;
4414    new_fs.nups = 0;
4415    new_fs.ndebugvars = 0;
4416    new_fs.nactvar = 0;
4417    new_fs.nactvar_reg = 0;
4418    new_fs.needclose = false;
4419
4420    new_fs.firstlocal = ls.dyd.actvar.len() as i32;
4421    new_fs.firstlabel = ls.dyd.label.len() as i32;
4422    new_fs.bl = None;
4423
4424    new_fs.f.source = ls.source.clone();
4425    new_fs.f.maxstacksize = 2;
4426
4427    ls.fs = Some(Box::new(new_fs));
4428
4429    enter_block(ls, false);
4430    Ok(())
4431}
4432
4433/// Finalizes and pops the current FuncState.
4434/// Returns the completed LuaProto.
4435fn close_func(ls: &mut LexState, state: &mut LuaState) -> Result<Box<LuaProto>, LuaError> {
4436    {
4437        let first = {
4438            let fs = ls.fs.as_ref().unwrap();
4439            nvarstack(ls, fs)
4440        };
4441        let line = ls.lastline;
4442        let fs = ls.fs.as_mut().unwrap();
4443        let inst = lua_code::opcodes::Instruction::abck(
4444            lua_code::opcodes::OpCode::Return0,
4445            first as u32,
4446            1,
4447            0,
4448            0,
4449        );
4450        emit_inst(fs, line, inst);
4451    }
4452    leave_block(ls, state)?;
4453    debug_assert!(ls.fs.as_ref().unwrap().bl.is_none());
4454
4455    //                     and needclose, and resolve JMP chains to final target.
4456    cg_finish(ls.fs.as_mut().unwrap());
4457
4458    {
4459        let fs = ls.fs.as_mut().unwrap();
4460        let pc = fs.pc as usize;
4461        let nabslineinfo = fs.nabslineinfo as usize;
4462        let nk = fs.nk as usize;
4463        let np = fs.np as usize;
4464        let ndebugvars = fs.ndebugvars as usize;
4465        let nups = fs.nups as usize;
4466        fs.f.code.truncate(pc);
4467        fs.f.lineinfo.truncate(pc);
4468        fs.f.abslineinfo.truncate(nabslineinfo);
4469        fs.f.k.truncate(nk);
4470        fs.f.p.truncate(np);
4471        fs.f.locvars.truncate(ndebugvars);
4472        fs.f.upvalues.truncate(nups);
4473    }
4474
4475    let mut fs_box = ls.fs.take().unwrap();
4476    ls.fs = fs_box.prev.take();
4477
4478    Ok(fs_box.f)
4479}
4480
4481// ── §8 Grammar rules — block / statement lists ───────────────────────────────
4482
4483/// Returns true if the current token can end a block.
4484fn block_follow(ls: &LexState, withuntil: bool) -> bool {
4485    match ls.t.token {
4486        TK_ELSE | TK_ELSEIF | TK_END | TK_EOS => true,
4487        TK_UNTIL => withuntil,
4488        _ => false,
4489    }
4490}
4491
4492fn statlist(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4493    let v51 = state.global().lua_version == lua_types::LuaVersion::V51;
4494    while !block_follow(ls, true) {
4495        if ls.t.token == TK_RETURN {
4496            statement(ls, state)?;
4497            return Ok(());
4498        }
4499        statement(ls, state)?;
4500        if v51 {
4501            test_next(ls, state, b';' as TokenKind)?;
4502        }
4503    }
4504    Ok(())
4505}
4506
4507/// Handles '.' NAME or ':' NAME field selection.
4508fn fieldsel(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4509    let line = ls.lastline;
4510    cg_exp_to_any_reg_up(ls.fs.as_mut().unwrap(), line, v)?;
4511    lex_next(ls, state)?; // skip '.' or ':'
4512    let mut key = ExprDesc::default();
4513    codename(ls, state, &mut key)?;
4514    cg_indexed(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
4515    Ok(())
4516}
4517
4518/// Handles '[' expr ']' indexing.
4519/// Corresponds to `luaK_exp2val` (`lcode.c`): if the expression carries a pending jump
4520/// list (a relational/boolean result), force it into a real register so its
4521/// boolean materialization is emitted before any later instruction; otherwise
4522/// just discharge its variable form. Used by `yindex` so an upvalue indexed by
4523/// a comparison key (`_ENV[1<2]`) lowers correctly.
4524///
4525/// `materialize_jmp` ports the version-specific guard. Lua 5.5's `luaK_exp2val`
4526/// reads `if (e->k == VJMP || hasjumps(e))`; Lua 5.3 and 5.4 read only
4527/// `if (hasjumps(e))`. Because our shared codegen lowers an upvalue index to a
4528/// register-based GETTABUP for every version (unlike 5.3's RK-based form), the
4529/// `VJMP` clause must also be applied for 5.3 to reproduce its `nil` result.
4530/// Lua 5.4 deliberately omits the clause — its reference genuinely raises
4531/// "attempt to index a number value" for `_ENV[1<2]`, an upstream behavior 5.5
4532/// later fixed — so `materialize_jmp` is false on 5.4.
4533fn exp_to_val(
4534    fs: &mut FuncState,
4535    line: i32,
4536    e: &mut ExprDesc,
4537    materialize_jmp: bool,
4538) -> Result<(), LuaError> {
4539    if (materialize_jmp && e.k == ExprKind::Jmp) || e.t != e.f {
4540        cg_exp_to_any_reg(fs, line, e)?;
4541    } else {
4542        cg_discharge_vars(fs, line, e)?;
4543    }
4544    Ok(())
4545}
4546
4547fn yindex(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4548    lex_next(ls, state)?;
4549    expr(ls, state, v)?;
4550    let line = ls.linenumber;
4551    let materialize_jmp = state.global().lua_version != lua_types::LuaVersion::V54;
4552    exp_to_val(ls.fs.as_mut().unwrap(), line, v, materialize_jmp)?;
4553    check_next(ls, state, b']' as TokenKind)?;
4554    Ok(())
4555}
4556
4557// ── §9 Constructor rules ─────────────────────────────────────────────────────
4558
4559fn recfield(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
4560    let reg = ls.fs.as_ref().unwrap().freereg as i32;
4561    let mut key = ExprDesc::default();
4562    let mut val = ExprDesc::default();
4563    if ls.t.token == TK_NAME {
4564        let fs = ls.fs.as_ref().unwrap();
4565        check_limit(fs, cc.nh, i32::MAX, "items in a constructor")?;
4566        codename(ls, state, &mut key)?;
4567    } else {
4568        yindex(ls, state, &mut key)?;
4569    }
4570    cc.nh += 1;
4571    check_next(ls, state, b'=' as TokenKind)?;
4572    let mut tab = cc.t.clone();
4573    let line = ls.lastline;
4574    cg_indexed(ls.fs.as_mut().unwrap(), line, &mut tab, &mut key)?;
4575    expr(ls, state, &mut val)?;
4576    cg_storevar(ls.fs.as_mut().unwrap(), line, &tab, &mut val)?;
4577    ls.fs.as_mut().unwrap().freereg = reg as u8;
4578    Ok(())
4579}
4580
4581fn closelistfield(
4582    ls: &mut LexState,
4583    state: &mut LuaState,
4584    cc: &mut ConsControl,
4585) -> Result<(), LuaError> {
4586    let _ = state;
4587    if cc.v.k == ExprKind::Void {
4588        return Ok(());
4589    }
4590    let line = ls.lastline;
4591    cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut cc.v)?;
4592    cc.v.k = ExprKind::Void;
4593    if cc.tostore == LFIELDS_PER_FLUSH {
4594        let t_info = cc.t.u.info;
4595        cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, cc.tostore);
4596        cc.na += cc.tostore;
4597        cc.tostore = 0;
4598    }
4599    Ok(())
4600}
4601
4602fn lastlistfield(
4603    ls: &mut LexState,
4604    state: &mut LuaState,
4605    cc: &mut ConsControl,
4606) -> Result<(), LuaError> {
4607    let _ = state;
4608    if cc.tostore == 0 {
4609        return Ok(());
4610    }
4611    let t_info = cc.t.u.info;
4612    let line = ls.lastline;
4613    if cc.v.k.has_mult_ret() {
4614        cg_set_returns(ls.fs.as_mut().unwrap(), &mut cc.v, LUA_MULTRET);
4615        cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, LUA_MULTRET);
4616        cc.na -= 1;
4617    } else {
4618        if cc.v.k != ExprKind::Void {
4619            cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut cc.v)?;
4620        }
4621        cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, cc.tostore);
4622    }
4623    cc.na += cc.tostore;
4624    Ok(())
4625}
4626
4627fn listfield(
4628    ls: &mut LexState,
4629    state: &mut LuaState,
4630    cc: &mut ConsControl,
4631) -> Result<(), LuaError> {
4632    expr(ls, state, &mut cc.v)?;
4633    cc.tostore += 1;
4634    Ok(())
4635}
4636
4637fn field(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
4638    match ls.t.token {
4639        TK_NAME => {
4640            let next_is_eq = lex_lookahead(ls, state)? == b'=' as TokenKind;
4641            if !next_is_eq {
4642                listfield(ls, state, cc)?;
4643            } else {
4644                recfield(ls, state, cc)?;
4645            }
4646        }
4647        c if c == b'[' as TokenKind => {
4648            recfield(ls, state, cc)?;
4649        }
4650        _ => {
4651            listfield(ls, state, cc)?;
4652        }
4653    }
4654    Ok(())
4655}
4656
4657fn constructor(ls: &mut LexState, state: &mut LuaState, t: &mut ExprDesc) -> Result<(), LuaError> {
4658    let line = ls.lastline;
4659    let pc = cg_emit_newtable(ls.fs.as_mut().unwrap(), line);
4660
4661    let freereg = ls.fs.as_ref().unwrap().freereg as i32;
4662    init_exp(t, ExprKind::NonReloc, freereg);
4663    reserve_regs(ls.fs.as_mut().unwrap(), 1)?;
4664
4665    let mut cc = ConsControl {
4666        v: ExprDesc::default(),
4667        t: t.clone(),
4668        nh: 0,
4669        na: 0,
4670        tostore: 0,
4671    };
4672
4673    check_next(ls, state, b'{' as TokenKind)?;
4674    loop {
4675        debug_assert!(cc.v.k == ExprKind::Void || cc.tostore > 0);
4676        if ls.t.token == b'}' as TokenKind {
4677            break;
4678        }
4679        closelistfield(ls, state, &mut cc)?;
4680        field(ls, state, &mut cc)?;
4681        if !test_next(ls, state, b',' as TokenKind)? && !test_next(ls, state, b';' as TokenKind)? {
4682            break;
4683        }
4684    }
4685    check_match(ls, state, b'}' as TokenKind, b'{' as TokenKind, line)?;
4686    lastlistfield(ls, state, &mut cc)?;
4687
4688    let t_info = t.u.info;
4689    cg_settablesize(ls.fs.as_mut().unwrap(), pc, t_info, cc.na, cc.nh);
4690    Ok(())
4691}
4692
4693// ── §10 Parameter list and function body ─────────────────────────────────────
4694
4695fn setvararg(fs: &mut FuncState, _state: &mut LuaState, nparams: i32) -> Result<(), LuaError> {
4696    fs.f.is_vararg = true;
4697    let inst = lua_code::opcodes::Instruction::abck(
4698        lua_code::opcodes::OpCode::VarArgPrep,
4699        nparams as u32,
4700        0,
4701        0,
4702        0,
4703    );
4704    let line = fs.previousline;
4705    emit_inst(fs, line, inst);
4706    Ok(())
4707}
4708
4709fn parlist(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4710    let mut nparams: i32 = 0;
4711    let mut isvararg = false;
4712    // Lua 5.5 adds a vararg-parameter local after the fixed parameters. In the
4713    // named form (`function f(...t)`) it is the packed table `t`; in the plain
4714    // form (`function f(...)`) it is a hidden "(vararg table)" debug local.
4715    // Pre-5.5 versions do not reserve that local, and a name after `...` stays
4716    // a parse error because the loop breaks as soon as it sees `...`.
4717    let is_v55 = state.global().lua_version == lua_types::LuaVersion::V55;
4718    // Lua 5.1 (`LUA_COMPAT_VARARG`) gives every vararg function an implicit local
4719    // named `arg`, a `table.pack`-style table of the extra arguments (`arg.n` is
4720    // the count). It is declared as an ordinary local right after the fixed
4721    // parameters, mirroring `parlist`'s `new_localvarliteral(ls, "arg", ...)`
4722    // plus `VARARG_HASARG | VARARG_NEEDSARG`. 5.2 removed it, so this is V51-only.
4723    let is_v51 = state.global().lua_version == lua_types::LuaVersion::V51;
4724    let mut has_vararg_local = false;
4725    let mut has_vararg_name = false;
4726    let mut has_arg_local = false;
4727    let mut vararg_name_vidx: Option<i32> = None;
4728    if ls.t.token != b')' as TokenKind {
4729        loop {
4730            match ls.t.token {
4731                TK_NAME => {
4732                    let name = str_check_name(ls, state)?;
4733                    new_local_var(ls, state, name)?;
4734                    nparams += 1;
4735                }
4736                TK_DOTS => {
4737                    lex_next(ls, state)?;
4738                    isvararg = true;
4739                    // 5.5 named varargs: a NAME after `...` is the vararg-table
4740                    // parameter. Push it as a local here (mirroring upstream's
4741                    // `new_varkind(..., RDKVAVAR)`); it is activated by the
4742                    // separate `adjust_local_vars(1)` below, and materialized at
4743                    // function entry by VARARGPACK.
4744                    if is_v55 && ls.t.token == TK_NAME {
4745                        let name = str_check_name(ls, state)?;
4746                        vararg_name_vidx = Some(new_local_var(ls, state, name)?);
4747                        has_vararg_local = true;
4748                        has_vararg_name = true;
4749                    } else if is_v55 {
4750                        let name = state.intern_str(b"(vararg table)")?;
4751                        new_local_var(ls, state, name)?;
4752                        has_vararg_local = true;
4753                    } else if is_v51 {
4754                        let name = state.intern_str(b"arg")?;
4755                        new_local_var(ls, state, name)?;
4756                        has_vararg_local = true;
4757                        has_arg_local = true;
4758                    }
4759                }
4760                _ => {
4761                    return Err(LuaError::syntax(format_args!("<name> or '...' expected")));
4762                }
4763            }
4764            if isvararg || !test_next(ls, state, b',' as TokenKind)? {
4765                break;
4766            }
4767        }
4768    }
4769    adjust_local_vars(ls, state, nparams)?;
4770    let numparams = ls.fs.as_ref().unwrap().nactvar;
4771    ls.fs.as_mut().unwrap().f.numparams = numparams;
4772    if isvararg {
4773        setvararg(ls.fs.as_mut().unwrap(), state, numparams as i32)?;
4774    }
4775    if has_vararg_local {
4776        adjust_local_vars(ls, state, 1)?;
4777        if let Some(vidx) = vararg_name_vidx {
4778            let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
4779            get_local_var_desc_mut(ls, firstlocal, vidx).kind = VarKind::VarArg;
4780        }
4781        if has_arg_local {
4782            let fs = ls.fs.as_mut().unwrap();
4783            let arg_locvar = (fs.ndebugvars - 1) as usize;
4784            fs.f.locvars[arg_locvar].startpc = 0;
4785        }
4786    }
4787    // Reserve registers for parameters (plus the vararg-table parameter, if
4788    // present), in one call as upstream does (`luaK_reserveregs(fs, nactvar)`).
4789    let nactvar = ls.fs.as_ref().unwrap().nactvar as i32;
4790    reserve_regs(ls.fs.as_mut().unwrap(), nactvar)?;
4791    // Materialize the named-vararg table into its register: VARARGPACK packs
4792    // all extra args (table.pack semantics) into a fresh table at the vararg
4793    // local's slot, which is the topmost active local.
4794    if has_vararg_name {
4795        let reg = nvarstack(ls, ls.fs.as_ref().unwrap()) - 1;
4796        let inst = lua_code::opcodes::Instruction::abck(
4797            lua_code::opcodes::OpCode::VarArgPack,
4798            reg as u32,
4799            0,
4800            0,
4801            0,
4802        );
4803        let line = ls.fs.as_ref().unwrap().previousline;
4804        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4805        // Record the vararg-table register so `OP_VARARG` unpacks live from this
4806        // table (shared storage), making `t` mutations visible through `...`.
4807        ls.fs.as_mut().unwrap().f.vararg_table_reg = Some(reg as u8);
4808    }
4809    // Materialize the Lua 5.1 implicit `arg` table the same way, but with the K
4810    // bit set so VARARGPACK builds the table unconditionally at entry (it is the
4811    // default; `simpleexp`'s `...` arm calls `clear_arg_table_needed`, which
4812    // rewrites this entry VARARGPACK into a LOADNIL when the body actually uses
4813    // `...`, matching C's `is_vararg &= ~VARARG_NEEDSARG` — `arg` stays a
4814    // declared local but reads nil). Unlike the 5.5 named form, `arg` is an
4815    // ordinary local with no `vararg_table_reg` aliasing, so `...` keeps reading
4816    // the raw extra args independently of `arg`.
4817    if has_arg_local {
4818        let reg = nvarstack(ls, ls.fs.as_ref().unwrap()) - 1;
4819        let inst = lua_code::opcodes::Instruction::abck(
4820            lua_code::opcodes::OpCode::VarArgPack,
4821            reg as u32,
4822            0,
4823            0,
4824            1,
4825        );
4826        let line = ls.fs.as_ref().unwrap().previousline;
4827        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4828    }
4829    Ok(())
4830}
4831
4832fn check_match(
4833    ls: &mut LexState,
4834    state: &mut LuaState,
4835    what: TokenKind,
4836    who: TokenKind,
4837    where_line: i32,
4838) -> Result<(), LuaError> {
4839    if !test_next(ls, state, what)? {
4840        if where_line == ls.linenumber {
4841            return Err(error_expected(ls, what));
4842        } else {
4843            let what_str = lua_lex::token2str(&ls.lex, what);
4844            let who_str = lua_lex::token2str(&ls.lex, who);
4845            let mut msg: Vec<u8> = Vec::new();
4846            msg.extend_from_slice(&what_str);
4847            msg.extend_from_slice(b" expected (to close ");
4848            msg.extend_from_slice(&who_str);
4849            use std::io::Write as _;
4850            let _ = write!(msg, " at line {})", where_line);
4851            return Err(lua_lex::syntax_error(&mut ls.lex, &msg));
4852        }
4853    }
4854    Ok(())
4855}
4856
4857fn body(
4858    ls: &mut LexState,
4859    state: &mut LuaState,
4860    e: &mut ExprDesc,
4861    ismethod: bool,
4862    line: i32,
4863) -> Result<(), LuaError> {
4864    let new_proto = add_prototype(ls, state)?;
4865    let mut new_fs = FuncState {
4866        f: new_proto,
4867        prev: None,
4868        bl: None,
4869        pc: 0,
4870        lasttarget: 0,
4871        previousline: line,
4872        nk: 0,
4873        np: 0,
4874        nabslineinfo: 0,
4875        firstlocal: 0,
4876        firstlabel: 0,
4877        ndebugvars: 0,
4878        nactvar: 0,
4879        nactvar_reg: 0,
4880        first_scope_barrier: ls.scope_barriers.len(),
4881        nups: 0,
4882        freereg: 0,
4883        iwthabs: 0,
4884        needclose: false,
4885        last_token_line: ls.lastline,
4886    };
4887    new_fs.f.linedefined = line;
4888    open_func(ls, state, new_fs)?;
4889
4890    check_next(ls, state, b'(' as TokenKind)?;
4891    if ismethod {
4892        let self_str = state.intern_str(b"self")?;
4893        new_local_var(ls, state, self_str)?;
4894        adjust_local_vars(ls, state, 1)?;
4895    }
4896    parlist(ls, state)?;
4897    check_next(ls, state, b')' as TokenKind)?;
4898    statlist(ls, state)?;
4899    ls.fs.as_mut().unwrap().f.lastlinedefined = ls.linenumber;
4900    check_match(ls, state, TK_END, TK_FUNCTION, line)?;
4901    codeclosure(ls, state, e)?;
4902    let inner_proto = close_func(ls, state)?;
4903    let parent = ls
4904        .fs
4905        .as_mut()
4906        .expect("body: close_func left no parent FuncState");
4907    let slot = (parent.np - 1) as usize;
4908    if parent.f.p.len() <= slot {
4909        parent
4910            .f
4911            .p
4912            .resize_with(slot + 1, || GcRef::new(LuaProto::placeholder()));
4913    }
4914    let inner_ref = GcRef::new(*inner_proto);
4915    inner_ref.account_buffer(inner_ref.buffer_bytes() as isize);
4916    parent.f.p[slot] = inner_ref;
4917    Ok(())
4918}
4919
4920// ── §11 Expression list and function arguments ────────────────────────────────
4921
4922fn explist(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<i32, LuaError> {
4923    let mut n = 1;
4924    expr(ls, state, v)?;
4925    while test_next(ls, state, b',' as TokenKind)? {
4926        let line = ls.lastline;
4927        cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, v)?;
4928        expr(ls, state, v)?;
4929        n += 1;
4930    }
4931    Ok(n)
4932}
4933
4934/// Parses a function call's argument list and emits the CALL.
4935///
4936/// `suffixed_line` is the line captured at the start of the enclosing
4937/// [`suffixedexp`] (the callee's first line). Lua 5.2 and 5.3 attribute the
4938/// CALL instruction to that line via `luaK_fixline`, so a runtime call-error on
4939/// `a\n(\n23)` reports the callee's line (1), not the open-paren line (2). Lua
4940/// 5.4/5.5 dropped that fixup and attribute the CALL to the open-paren line, so
4941/// those versions keep using `ls.linenumber` at funcargs entry and their
4942/// bytecode line info is unchanged.
4943fn funcargs(
4944    ls: &mut LexState,
4945    state: &mut LuaState,
4946    f: &mut ExprDesc,
4947    suffixed_line: i32,
4948) -> Result<(), LuaError> {
4949    let mut args = ExprDesc::default();
4950    // BEFORE consuming, so the OP_CALL/etc emissions attribute to the call site.
4951    // errors.lua tests `a\n(\n23)` expects error at line of `(`, not line of `a`.
4952    let line = ls.linenumber;
4953    match ls.t.token {
4954        c if c == b'(' as TokenKind => {
4955            if state.global().lua_version == lua_types::LuaVersion::V51
4956                && ls.linenumber != ls.lastline
4957            {
4958                return Err(lua_lex::syntax_error(
4959                    &mut ls.lex,
4960                    b"ambiguous syntax (function call x new statement)",
4961                ));
4962            }
4963            lex_next(ls, state)?; // skip '('
4964            if ls.t.token == b')' as TokenKind {
4965                args.k = ExprKind::Void;
4966            } else {
4967                explist(ls, state, &mut args)?;
4968                if args.k.has_mult_ret() {
4969                    // Call/VarArg to produce LUA_MULTRET so all of its return
4970                    // values become arguments to the enclosing call.
4971                    cg_set_returns(ls.fs.as_mut().unwrap(), &mut args, LUA_MULTRET);
4972                }
4973            }
4974            check_match(ls, state, b')' as TokenKind, b'(' as TokenKind, line)?;
4975        }
4976        c if c == b'{' as TokenKind => {
4977            constructor(ls, state, &mut args)?;
4978        }
4979        TK_STRING => {
4980            let s =
4981                ls.t.seminfo
4982                    .ts
4983                    .clone()
4984                    .ok_or_else(|| LuaError::syntax(format_args!("string expected")))?;
4985            codestring(&mut args, s);
4986            lex_next(ls, state)?;
4987        }
4988        _ => {
4989            return Err(LuaError::syntax(format_args!(
4990                "function arguments expected"
4991            )));
4992        }
4993    }
4994    debug_assert!(f.k == ExprKind::NonReloc);
4995    let base = f.u.info;
4996    let nparams: i32 = if args.k.has_mult_ret() {
4997        // luaK_setmultret's patching for VVarArg / VCall args is not
4998        // replicated here; only single non-multret args are fully
4999        // supported by this codegen path.
5000        LUA_MULTRET
5001    } else {
5002        if args.k != ExprKind::Void {
5003            cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut args)?;
5004        }
5005        ls.fs.as_ref().unwrap().freereg as i32 - (base + 1)
5006    };
5007    let call_inst = lua_code::opcodes::Instruction::abck(
5008        lua_code::opcodes::OpCode::Call,
5009        base as u32,
5010        (nparams + 1) as u32,
5011        2,
5012        0,
5013    );
5014    let call_line = if matches!(
5015        state.global().lua_version,
5016        lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
5017    ) {
5018        suffixed_line
5019    } else {
5020        line
5021    };
5022    let call_pc = emit_inst(ls.fs.as_mut().unwrap(), call_line, call_inst);
5023    init_exp(f, ExprKind::Call, call_pc);
5024    ls.fs.as_mut().unwrap().freereg = base as u8 + 1;
5025    Ok(())
5026}
5027
5028// ── §12 Expression parsing ────────────────────────────────────────────────────
5029
5030fn primaryexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
5031    match ls.t.token {
5032        c if c == b'(' as TokenKind => {
5033            let line = ls.lastline;
5034            lex_next(ls, state)?;
5035            expr(ls, state, v)?;
5036            check_match(ls, state, b')' as TokenKind, b'(' as TokenKind, line)?;
5037            cg_discharge_vars(ls.fs.as_mut().unwrap(), line, v)?;
5038        }
5039        TK_NAME => {
5040            singlevar(ls, state, v)?;
5041        }
5042        _ => {
5043            return Err(lua_lex::syntax_error(&mut ls.lex, b"unexpected symbol"));
5044        }
5045    }
5046    Ok(())
5047}
5048
5049fn suffixedexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
5050    let start_line = ls.linenumber;
5051    primaryexp(ls, state, v)?;
5052    loop {
5053        match ls.t.token {
5054            c if c == b'.' as TokenKind => {
5055                fieldsel(ls, state, v)?;
5056            }
5057            c if c == b'[' as TokenKind => {
5058                let mut key = ExprDesc::default();
5059                let line = ls.lastline;
5060                cg_exp_to_any_reg_up(ls.fs.as_mut().unwrap(), line, v)?;
5061                yindex(ls, state, &mut key)?;
5062                cg_indexed(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
5063            }
5064            c if c == b':' as TokenKind => {
5065                let mut key = ExprDesc::default();
5066                lex_next(ls, state)?;
5067                codename(ls, state, &mut key)?;
5068                let line = ls.lastline;
5069                let keep_self_opcode_for_register_key =
5070                    state.global().lua_version != lua_types::LuaVersion::V55;
5071                cg_self(
5072                    ls.fs.as_mut().unwrap(),
5073                    line,
5074                    v,
5075                    &mut key,
5076                    keep_self_opcode_for_register_key,
5077                )?;
5078                funcargs(ls, state, v, start_line)?;
5079            }
5080            c if c == b'(' as TokenKind || c == TK_STRING || c == b'{' as TokenKind => {
5081                let line = ls.lastline;
5082                cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, v)?;
5083                funcargs(ls, state, v, start_line)?;
5084            }
5085            _ => return Ok(()),
5086        }
5087    }
5088}
5089
5090fn simpleexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
5091    match ls.t.token {
5092        TK_FLT => {
5093            init_exp(v, ExprKind::KFlt, 0);
5094            v.u.nval = ls.t.seminfo.r;
5095        }
5096        TK_INT => {
5097            init_exp(v, ExprKind::KInt, 0);
5098            v.u.ival = ls.t.seminfo.i;
5099        }
5100        TK_STRING => {
5101            let s =
5102                ls.t.seminfo
5103                    .ts
5104                    .clone()
5105                    .ok_or_else(|| LuaError::syntax(format_args!("string value missing")))?;
5106            codestring(v, s);
5107        }
5108        TK_NIL => {
5109            init_exp(v, ExprKind::Nil, 0);
5110        }
5111        TK_TRUE => {
5112            init_exp(v, ExprKind::True, 0);
5113        }
5114        TK_FALSE => {
5115            init_exp(v, ExprKind::False, 0);
5116        }
5117        TK_DOTS => {
5118            let is_vararg = ls.fs.as_ref().unwrap().f.is_vararg;
5119            if !is_vararg {
5120                return Err(lua_lex::syntax_error(
5121                    &mut ls.lex,
5122                    b"cannot use '...' outside a vararg function",
5123                ));
5124            }
5125            if state.global().lua_version == lua_types::LuaVersion::V51 {
5126                clear_arg_table_needed(ls.fs.as_mut().unwrap());
5127            }
5128            let line = ls.lastline;
5129            let inst =
5130                lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::VarArg, 0, 0, 1, 0);
5131            let pc = emit_inst(ls.fs.as_mut().unwrap(), line, inst);
5132            init_exp(v, ExprKind::VarArg, pc);
5133        }
5134        c if c == b'{' as TokenKind => {
5135            constructor(ls, state, v)?;
5136            return Ok(());
5137        }
5138        TK_FUNCTION => {
5139            lex_next(ls, state)?;
5140            let line = ls.lastline;
5141            body(ls, state, v, false, line)?;
5142            return Ok(());
5143        }
5144        _ => {
5145            suffixedexp(ls, state, v)?;
5146            return Ok(());
5147        }
5148    }
5149    lex_next(ls, state)?;
5150    Ok(())
5151}
5152
5153fn getunopr(op: TokenKind) -> UnOpr {
5154    match op {
5155        TK_NOT => UnOpr::Not,
5156        c if c == b'-' as TokenKind => UnOpr::Minus,
5157        c if c == b'~' as TokenKind => UnOpr::BNot,
5158        c if c == b'#' as TokenKind => UnOpr::Len,
5159        _ => UnOpr::NoUnOpr,
5160    }
5161}
5162
5163fn getbinopr(op: TokenKind) -> BinOpr {
5164    match op {
5165        c if c == b'+' as TokenKind => BinOpr::Add,
5166        c if c == b'-' as TokenKind => BinOpr::Sub,
5167        c if c == b'*' as TokenKind => BinOpr::Mul,
5168        c if c == b'%' as TokenKind => BinOpr::Mod,
5169        c if c == b'^' as TokenKind => BinOpr::Pow,
5170        c if c == b'/' as TokenKind => BinOpr::Div,
5171        TK_IDIV => BinOpr::IDiv,
5172        c if c == b'&' as TokenKind => BinOpr::BAnd,
5173        c if c == b'|' as TokenKind => BinOpr::BOr,
5174        c if c == b'~' as TokenKind => BinOpr::BXor,
5175        TK_SHL => BinOpr::Shl,
5176        TK_SHR => BinOpr::Shr,
5177        TK_CONCAT => BinOpr::Concat,
5178        TK_NE => BinOpr::Ne,
5179        TK_EQ => BinOpr::Eq,
5180        c if c == b'<' as TokenKind => BinOpr::Lt,
5181        TK_LE => BinOpr::Le,
5182        c if c == b'>' as TokenKind => BinOpr::Gt,
5183        TK_GE => BinOpr::Ge,
5184        TK_AND => BinOpr::And,
5185        TK_OR => BinOpr::Or,
5186        _ => BinOpr::NoBinOpr,
5187    }
5188}
5189
5190/// Whether the active version is the float-only legacy family (5.1/5.2), which
5191/// has no bitwise operators (`&`, `|`, `~`, `<<`, `>>`).
5192fn parser_is_float_only(state: &LuaState) -> bool {
5193    matches!(
5194        state.global().lua_version,
5195        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
5196    )
5197}
5198
5199/// Version-aware [`getbinopr`]: under 5.1/5.2 the bitwise binops `&`/`|`/`~`
5200/// are not operators (they were added in 5.3), so they resolve to
5201/// [`BinOpr::NoBinOpr`]. The lexer already withholds `<<`/`>>`/`//` there.
5202/// This reproduces upstream lua5.2.4's "')' expected near '&'" surface: the
5203/// `&` simply terminates the expression and the parser then expects the
5204/// enclosing delimiter.
5205fn getbinopr_versioned(op: TokenKind, state: &LuaState) -> BinOpr {
5206    let r = getbinopr(op);
5207    if parser_is_float_only(state) && matches!(r, BinOpr::BAnd | BinOpr::BOr | BinOpr::BXor) {
5208        return BinOpr::NoBinOpr;
5209    }
5210    r
5211}
5212
5213/// Version-aware [`getunopr`]: under 5.1/5.2 the unary `~` (bitwise NOT) is not
5214/// an operator. A leading `~` there is "unexpected symbol near '~'".
5215fn getunopr_versioned(op: TokenKind, state: &LuaState) -> UnOpr {
5216    let r = getunopr(op);
5217    if parser_is_float_only(state) && matches!(r, UnOpr::BNot) {
5218        return UnOpr::NoUnOpr;
5219    }
5220    r
5221}
5222
5223/// Parses a sub-expression with operators of priority > `limit`.
5224/// Returns the first untreated (lower-priority) operator.
5225fn subexpr(
5226    ls: &mut LexState,
5227    state: &mut LuaState,
5228    v: &mut ExprDesc,
5229    limit: i32,
5230) -> Result<BinOpr, LuaError> {
5231    enter_level(ls, state)?;
5232
5233    let uop = getunopr_versioned(ls.t.token, state);
5234    if uop != UnOpr::NoUnOpr {
5235        // so this is the operator's own line, not the prior token's.
5236        let line = ls.linenumber;
5237        lex_next(ls, state)?; // skip unary operator
5238        subexpr(ls, state, v, UNARY_PRIORITY)?;
5239        cg_prefix(ls.fs.as_mut().unwrap(), uop, v, line)?;
5240    } else {
5241        simpleexp(ls, state, v)?;
5242    }
5243
5244    let mut op = getbinopr_versioned(ls.t.token, state);
5245    while op != BinOpr::NoBinOpr && PRIORITY[op as usize].0 as i32 > limit {
5246        let mut v2 = ExprDesc::default();
5247        // errors.lua's `lineerror` cases check that runtime arith errors are
5248        // attributed to the operator's line, not the operand's.
5249        let line = ls.linenumber;
5250        lex_next(ls, state)?;
5251        cg_infix(ls.fs.as_mut().unwrap(), op, v, line)?;
5252        let nextop = subexpr(ls, state, &mut v2, PRIORITY[op as usize].1 as i32)?;
5253        cg_posfix_fold(ls.fs.as_mut().unwrap(), op, v, &mut v2, line)?;
5254        op = nextop;
5255    }
5256
5257    leave_level(ls);
5258    Ok(op)
5259}
5260
5261fn expr(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
5262    subexpr(ls, state, v, 0)?;
5263    Ok(())
5264}
5265
5266// ── §13 Statement rules ───────────────────────────────────────────────────────
5267
5268fn block(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5269    enter_block(ls, false);
5270    statlist(ls, state)?;
5271    leave_block(ls, state)?;
5272    Ok(())
5273}
5274
5275/// Checks and fixes register/upvalue conflicts in multi-assignment.
5276///
5277/// When a non-indexed LHS variable `v` also appears as the table or key in an
5278/// indexed LHS variable, the indexed entry must be redirected to a copy made
5279/// before any assignments occur. For an upvalue table that becomes a register
5280/// copy, the ExprKind is changed from IndexUp to IndexStr so cg_storevar emits
5281/// SETFIELD (register table) instead of SETTABUP (upvalue table).
5282fn check_conflict(
5283    ls: &mut LexState,
5284    _state: &mut LuaState,
5285    lh: &mut LhsAssign,
5286    v: &ExprDesc,
5287) -> Result<(), LuaError> {
5288    let extra = ls.fs.as_ref().unwrap().freereg as i32;
5289    let line = ls.lastline;
5290    let mut conflict = false;
5291
5292    conflict |= check_one_lhs_entry(&mut lh.v, v, extra);
5293    let mut prev = lh.prev.as_deref_mut();
5294    while let Some(node) = prev {
5295        conflict |= check_one_lhs_entry(&mut node.v, v, extra);
5296        prev = node.prev.as_deref_mut();
5297    }
5298
5299    if conflict {
5300        let fs = ls.fs.as_mut().unwrap();
5301        let inst = if v.k == ExprKind::Local {
5302            lua_code::opcodes::Instruction::abck(
5303                lua_code::opcodes::OpCode::Move,
5304                extra as u32,
5305                v.u.var_ridx as u32,
5306                0,
5307                0,
5308            )
5309        } else {
5310            lua_code::opcodes::Instruction::abck(
5311                lua_code::opcodes::OpCode::GetUpVal,
5312                extra as u32,
5313                v.u.info as u32,
5314                0,
5315                0,
5316            )
5317        };
5318        emit_inst(fs, line, inst);
5319        reserve_regs(fs, 1)?;
5320    }
5321    Ok(())
5322}
5323
5324fn check_one_lhs_entry(entry: &mut ExprDesc, v: &ExprDesc, extra: i32) -> bool {
5325    if !entry.k.is_indexed() {
5326        return false;
5327    }
5328    let mut found = false;
5329    if entry.k == ExprKind::IndexUp {
5330        if v.k == ExprKind::UpVal && entry.u.ind_t == v.u.info as u8 {
5331            found = true;
5332            entry.k = ExprKind::IndexStr;
5333            entry.u.ind_t = extra as u8;
5334        }
5335    } else {
5336        if v.k == ExprKind::Local && entry.u.ind_t == v.u.var_ridx {
5337            found = true;
5338            entry.u.ind_t = extra as u8;
5339        }
5340        if entry.k == ExprKind::Indexed
5341            && v.k == ExprKind::Local
5342            && entry.u.ind_idx == v.u.var_ridx as i16
5343        {
5344            found = true;
5345            entry.u.ind_idx = extra as i16;
5346        }
5347    }
5348    found
5349}
5350
5351fn restassign(
5352    ls: &mut LexState,
5353    state: &mut LuaState,
5354    lh: &mut LhsAssign,
5355    nvars: i32,
5356) -> Result<(), LuaError> {
5357    if !lh.v.k.is_var() {
5358        return Err(lua_lex::syntax_error(&mut ls.lex, b"syntax error"));
5359    }
5360    check_readonly(ls, state, &lh.v.clone())?;
5361
5362    if test_next(ls, state, b',' as TokenKind)? {
5363        // The new target is not back-linked into the LHS chain (`prev: None`);
5364        // check_conflict therefore only inspects the immediate parent `lh`, not
5365        // the full chain back to the first target. A known divergence from
5366        // upstream that the bytecode-parity oracle does not surface on the test
5367        // corpus; not fixed here to avoid touching codegen behavior.
5368        let mut nv_assign = LhsAssign {
5369            prev: None,
5370            v: ExprDesc::default(),
5371        };
5372        suffixedexp(ls, state, &mut nv_assign.v)?;
5373        if !nv_assign.v.k.is_indexed() {
5374            check_conflict(ls, state, lh, &nv_assign.v.clone())?;
5375        }
5376        enter_level(ls, state)?;
5377        restassign(ls, state, &mut nv_assign, nvars + 1)?;
5378        leave_level(ls);
5379    } else {
5380        let mut e = ExprDesc::default();
5381        check_next(ls, state, b'=' as TokenKind)?;
5382        let nexps = explist(ls, state, &mut e)?;
5383        if nexps != nvars {
5384            adjust_assign(ls, state, nvars, nexps, &mut e)?;
5385        } else {
5386            let line = ls.lastline;
5387            let fs = ls.fs.as_mut().unwrap();
5388            cg_set_one_ret(fs, &mut e);
5389            cg_storevar(fs, line, &lh.v, &mut e)?;
5390            return Ok(());
5391        }
5392    }
5393    let line = ls.lastline;
5394    let fs = ls.fs.as_mut().unwrap();
5395    let freereg = fs.freereg as i32 - 1;
5396    let mut e = ExprDesc::default();
5397    init_exp(&mut e, ExprKind::NonReloc, freereg);
5398    cg_storevar(fs, line, &lh.v, &mut e)?;
5399    Ok(())
5400}
5401
5402/// Parses a condition expression; returns its 'exit when false' patch list.
5403fn cond(ls: &mut LexState, state: &mut LuaState) -> Result<i32, LuaError> {
5404    let mut v = ExprDesc::default();
5405    expr(ls, state, &mut v)?;
5406    if v.k == ExprKind::Nil {
5407        v.k = ExprKind::False;
5408    }
5409    let line = ls.lastline;
5410    cg_go_if_true(ls.fs.as_mut().unwrap(), line, &mut v)?;
5411    Ok(v.f)
5412}
5413
5414fn gotostat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5415    let line = ls.lastline;
5416    let name = str_check_name(ls, state)?;
5417    let lb = findlabel_for_goto(ls, state, &name);
5418    if lb.is_none() {
5419        let pc = cg_jump(ls.fs.as_mut().unwrap(), line);
5420        new_goto_entry(ls, state, name, line, pc)?;
5421    } else {
5422        let lb_idx = lb.unwrap();
5423        let lb_pc = ls.dyd.label[lb_idx].pc;
5424        let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
5425        let lb_local_level = local_level_for_scope_level(ls, lb_nactvar);
5426        let lblevel = reg_level(ls, ls.fs.as_ref().unwrap(), lb_local_level);
5427        let cur_nvarstack = {
5428            let fs = ls.fs.as_ref().unwrap();
5429            nvarstack(ls, fs)
5430        };
5431        if cur_nvarstack > lblevel {
5432            let inst = lua_code::opcodes::Instruction::abck(
5433                lua_code::opcodes::OpCode::Close,
5434                lblevel as u32,
5435                0,
5436                0,
5437                0,
5438            );
5439            emit_inst(ls.fs.as_mut().unwrap(), line, inst);
5440        }
5441        let jpc = cg_jump(ls.fs.as_mut().unwrap(), line);
5442        cg_patch_list(ls.fs.as_mut().unwrap(), jpc, lb_pc)?;
5443    }
5444    Ok(())
5445}
5446
5447/// True if any enclosing block of the current function is a loop, i.e. `break`
5448/// has somewhere to go.
5449fn has_enclosing_loop(ls: &LexState) -> bool {
5450    let mut bl = ls.fs.as_ref().unwrap().bl.as_deref();
5451    while let Some(b) = bl {
5452        if b.isloop {
5453            return true;
5454        }
5455        bl = b.previous.as_deref();
5456    }
5457    false
5458}
5459
5460fn breakstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5461    let version = state.global().lua_version;
5462    let line = ls.lastline;
5463    // `break` outside a loop is reported in three different ways across versions
5464    // (see also `undef_goto` for the 5.2-5.4 deferred forms):
5465    //   5.5 raises eagerly while the current token is still `break`
5466    //       → "break outside loop near 'break'".
5467    //   5.1 raises eagerly after consuming `break`
5468    //       → "no loop to break near '<next token>'".
5469    //   5.2/5.3/5.4 defer to the goto machinery (resolved in `undef_goto`).
5470    if version == lua_types::LuaVersion::V55 && !has_enclosing_loop(ls) {
5471        return Err(lua_lex::syntax_error(&mut ls.lex, b"break outside loop"));
5472    }
5473    lex_next(ls, state)?;
5474    if version == lua_types::LuaVersion::V51 && !has_enclosing_loop(ls) {
5475        return Err(lua_lex::syntax_error(&mut ls.lex, b"no loop to break"));
5476    }
5477    let break_str = state.intern_str(b"break")?;
5478    let pc = cg_jump(ls.fs.as_mut().unwrap(), line);
5479    new_goto_entry(ls, state, break_str, line, pc)?;
5480    Ok(())
5481}
5482
5483/// Checks whether `name` collides with an already-defined label.
5484///
5485/// The scope of the collision check differs by Lua version. 5.2 and 5.3
5486/// (upstream `checkrepeated`) scan only the labels of the **current block**
5487/// (`fs->bl->firstlabel`), so a label in an inner block may shadow a same-named
5488/// label in an enclosing block. 5.4 and 5.5 rewrote `checkrepeated` to call
5489/// `findlabel`, which scans the **whole function** (`fs->firstlabel`), making
5490/// any repeated label name in the function an error. 5.1 has no `goto`/labels.
5491fn checkrepeated(
5492    ls: &mut LexState,
5493    state: &LuaState,
5494    name: &GcRef<LuaString>,
5495) -> Result<(), LuaError> {
5496    let block_scoped = matches!(
5497        state.global().lua_version,
5498        lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
5499    );
5500    let first = if block_scoped {
5501        ls.fs
5502            .as_ref()
5503            .unwrap()
5504            .bl
5505            .as_ref()
5506            .map_or(0, |b| b.firstlabel) as usize
5507    } else {
5508        ls.fs.as_ref().unwrap().firstlabel as usize
5509    };
5510    let mut dup_line: Option<i32> = None;
5511    for i in first..ls.dyd.label.len() {
5512        let lb = &ls.dyd.label[i];
5513        if lb.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
5514            dup_line = Some(lb.line);
5515            break;
5516        }
5517    }
5518    if let Some(line) = dup_line {
5519        let name_str = String::from_utf8_lossy(name.as_bytes());
5520        let msg = format!("label '{}' already defined on line {}", name_str, line);
5521        let saved_line = ls.lex.linenumber;
5522        ls.lex.linenumber = ls.lastline;
5523        let err = lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0);
5524        ls.lex.linenumber = saved_line;
5525        return Err(err);
5526    }
5527    Ok(())
5528}
5529
5530fn labelstat(
5531    ls: &mut LexState,
5532    state: &mut LuaState,
5533    name: GcRef<LuaString>,
5534    line: i32,
5535) -> Result<(), LuaError> {
5536    check_next(ls, state, TK_DBCOLON)?;
5537    while ls.t.token == b';' as TokenKind || ls.t.token == TK_DBCOLON {
5538        statement(ls, state)?;
5539    }
5540    checkrepeated(ls, state, &name)?;
5541    let is_last = block_follow(ls, false);
5542    createlabel(ls, state, name, line, is_last)?;
5543    Ok(())
5544}
5545
5546fn whilestat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5547    lex_next(ls, state)?;
5548    let whileinit = cg_get_label(ls.fs.as_mut().unwrap());
5549    let condexit = cond(ls, state)?;
5550    enter_block(ls, true);
5551    check_next(ls, state, TK_DO)?;
5552    block(ls, state)?;
5553    // Use `lastline` (line of the just-parsed body's last token) rather than
5554    // `linenumber` (which has already advanced to END) so the back-jump's
5555    // line attribution matches lua-c's bytecode and the line hook does not
5556    // spuriously fire for the END line on every iteration.
5557    let back = cg_jump(ls.fs.as_mut().unwrap(), ls.lastline);
5558    cg_patch_list(ls.fs.as_mut().unwrap(), back, whileinit)?;
5559    check_match(ls, state, TK_END, TK_WHILE, line)?;
5560    leave_block(ls, state)?;
5561    cg_patch_to_here(ls.fs.as_mut().unwrap(), condexit)?;
5562    Ok(())
5563}
5564
5565fn repeatstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5566    let repeat_init = cg_get_label(ls.fs.as_mut().unwrap());
5567    enter_block(ls, true);
5568    enter_block(ls, false);
5569    lex_next(ls, state)?;
5570    statlist(ls, state)?;
5571    check_match(ls, state, TK_UNTIL, TK_REPEAT, line)?;
5572    let condexit = cond(ls, state)?;
5573
5574    let bl2_upval = ls.fs.as_ref().unwrap().bl.as_ref().unwrap().upval;
5575    let bl2_nactvar = ls.fs.as_ref().unwrap().bl.as_ref().unwrap().nactvar as i32;
5576    leave_block(ls, state)?;
5577
5578    let mut condexit = condexit;
5579    if bl2_upval {
5580        let exit = cg_jump(ls.fs.as_mut().unwrap(), line);
5581        cg_patch_to_here(ls.fs.as_mut().unwrap(), condexit)?;
5582        let close_level = reg_level(ls, ls.fs.as_ref().unwrap(), bl2_nactvar) as u32;
5583        let close_inst = lua_code::opcodes::Instruction::abck(
5584            lua_code::opcodes::OpCode::Close,
5585            close_level,
5586            0,
5587            0,
5588            0,
5589        );
5590        emit_inst(ls.fs.as_mut().unwrap(), line, close_inst);
5591        condexit = cg_jump(ls.fs.as_mut().unwrap(), line);
5592        cg_patch_to_here(ls.fs.as_mut().unwrap(), exit)?;
5593    }
5594    cg_patch_list(ls.fs.as_mut().unwrap(), condexit, repeat_init)?;
5595    leave_block(ls, state)?;
5596    Ok(())
5597}
5598
5599/// Parse an expression and emit it to the next register.
5600fn exp1(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5601    let mut e = ExprDesc::default();
5602    expr(ls, state, &mut e)?;
5603    let line = ls.lastline;
5604    cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut e)?;
5605    debug_assert!(e.k == ExprKind::NonReloc);
5606    Ok(())
5607}
5608
5609fn fixforjump(fs: &mut FuncState, pc: i32, dest: i32, back: bool) -> Result<(), LuaError> {
5610    let mut offset = dest - (pc + 1);
5611    if back {
5612        offset = -offset;
5613    }
5614    if offset > MAXARG_BX {
5615        return Err(LuaError::syntax(format_args!("control structure too long")));
5616    }
5617    let raw = fs.f.code[pc as usize].0;
5618    let mut inst = lua_code::opcodes::Instruction(raw);
5619    inst.set_arg_bx(offset as u32);
5620    fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(inst.0);
5621    Ok(())
5622}
5623
5624fn forbody(
5625    ls: &mut LexState,
5626    state: &mut LuaState,
5627    base: i32,
5628    line: i32,
5629    nvars: i32,
5630    isgen: bool,
5631) -> Result<(), LuaError> {
5632    check_next(ls, state, TK_DO)?;
5633    let prep_op = if isgen {
5634        OpCode::TForPrep
5635    } else {
5636        OpCode::ForPrep
5637    };
5638    let prep = {
5639        let fs = ls.fs.as_mut().unwrap();
5640        let inst = lua_code::opcodes::Instruction::abx(prep_op, base as u32, 0);
5641        emit_inst(fs, line, inst)
5642    };
5643    if isgen && state.global().lua_version == lua_types::LuaVersion::V55 {
5644        let fs = ls.fs.as_mut().unwrap();
5645        fs.freereg = fs.freereg.saturating_sub(1);
5646    }
5647
5648    enter_block(ls, false);
5649    adjust_local_vars(ls, state, nvars)?;
5650    reserve_regs(ls.fs.as_mut().unwrap(), nvars)?;
5651    block(ls, state)?;
5652    leave_block(ls, state)?;
5653
5654    let label_pc = ls.fs.as_ref().unwrap().pc;
5655    fixforjump(ls.fs.as_mut().unwrap(), prep, label_pc, false)?;
5656
5657    if isgen {
5658        let fs = ls.fs.as_mut().unwrap();
5659        let inst =
5660            lua_code::opcodes::Instruction::abck(OpCode::TForCall, base as u32, 0, nvars as u32, 0);
5661        emit_inst(fs, line, inst);
5662    }
5663    let loop_op = if isgen {
5664        OpCode::TForLoop
5665    } else {
5666        OpCode::ForLoop
5667    };
5668    let endfor = {
5669        let fs = ls.fs.as_mut().unwrap();
5670        let inst = lua_code::opcodes::Instruction::abx(loop_op, base as u32, 0);
5671        emit_inst(fs, line, inst)
5672    };
5673    fixforjump(ls.fs.as_mut().unwrap(), endfor, prep + 1, true)?;
5674    Ok(())
5675}
5676
5677fn fornum(
5678    ls: &mut LexState,
5679    state: &mut LuaState,
5680    varname: GcRef<LuaString>,
5681    line: i32,
5682) -> Result<(), LuaError> {
5683    let base = ls.fs.as_ref().unwrap().freereg as i32;
5684    let for_state_str = state.intern_str(b"(for state)")?;
5685    new_local_var(ls, state, for_state_str.clone())?;
5686    new_local_var(ls, state, for_state_str.clone())?;
5687    new_local_var(ls, state, for_state_str)?;
5688    let ctrl_vidx = new_local_var(ls, state, varname)?;
5689    // Lua 5.5: the numeric for-loop control variable is read-only — assigning
5690    // to it is a compile error. The FORLOOP opcode still updates the register
5691    // directly, so loop progress is unaffected. (No effect on pre-5.5.)
5692    if state.global().lua_version == lua_types::LuaVersion::V55 {
5693        let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
5694        get_local_var_desc_mut(ls, firstlocal, ctrl_vidx).kind = VarKind::Const;
5695    }
5696    check_next(ls, state, b'=' as TokenKind)?;
5697    exp1(ls, state)?; // initial value
5698    check_next(ls, state, b',' as TokenKind)?;
5699    exp1(ls, state)?; // limit
5700    if test_next(ls, state, b',' as TokenKind)? {
5701        exp1(ls, state)?; // optional step
5702    } else {
5703        let fs = ls.fs.as_mut().unwrap();
5704        let reg = fs.freereg as u32;
5705        let bx = (1i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
5706        let inst = lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::LoadI, reg, bx);
5707        emit_inst(fs, line, inst);
5708        reserve_regs(fs, 1)?;
5709    }
5710    adjust_local_vars(ls, state, 3)?; // control variables
5711    forbody(ls, state, base, line, 1, false)?;
5712    Ok(())
5713}
5714
5715fn forlist(
5716    ls: &mut LexState,
5717    state: &mut LuaState,
5718    indexname: GcRef<LuaString>,
5719) -> Result<(), LuaError> {
5720    let is_v55 = state.global().lua_version == lua_types::LuaVersion::V55;
5721    let mut nvars: i32 = if is_v55 { 4 } else { 5 };
5722    let base = ls.fs.as_ref().unwrap().freereg as i32;
5723    let for_state_str = state.intern_str(b"(for state)")?;
5724    new_local_var(ls, state, for_state_str.clone())?;
5725    new_local_var(ls, state, for_state_str.clone())?;
5726    new_local_var(ls, state, for_state_str.clone())?;
5727    if !is_v55 {
5728        new_local_var(ls, state, for_state_str)?;
5729    }
5730    let idx_vidx = new_local_var(ls, state, indexname)?;
5731    // Lua 5.5: the first control variable of a generic for is read-only (the
5732    // remaining loop variables stay assignable).
5733    if state.global().lua_version == lua_types::LuaVersion::V55 {
5734        let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
5735        get_local_var_desc_mut(ls, firstlocal, idx_vidx).kind = VarKind::Const;
5736    }
5737    while test_next(ls, state, b',' as TokenKind)? {
5738        let extra_name = str_check_name(ls, state)?;
5739        new_local_var(ls, state, extra_name)?;
5740        nvars += 1;
5741    }
5742    check_next(ls, state, TK_IN)?;
5743    // After `in`, linenumber is the line of the operand — used for the
5744    // for-in control instructions so runtime errors point at the operand,
5745    // not the `in` keyword. errors.lua:401 depends on this.
5746    let line = ls.linenumber;
5747    let mut e = ExprDesc::default();
5748    let nexps = explist(ls, state, &mut e)?;
5749    adjust_assign(ls, state, 4, nexps, &mut e)?;
5750    adjust_local_vars(ls, state, if is_v55 { 3 } else { 4 })?;
5751    marktobeclosed(ls.fs.as_mut().unwrap()); // last active internal var must be closed
5752    let internal_vars = if is_v55 { 3 } else { 4 };
5753    forbody(ls, state, base, line, nvars - internal_vars, true)?;
5754    Ok(())
5755}
5756
5757fn forstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5758    enter_block(ls, true); // scope for loop and control variables
5759    lex_next(ls, state)?;
5760    let varname = str_check_name(ls, state)?;
5761    match ls.t.token {
5762        c if c == b'=' as TokenKind => fornum(ls, state, varname, line)?,
5763        c if c == b',' as TokenKind || c == TK_IN => forlist(ls, state, varname)?,
5764        _ => {
5765            return Err(LuaError::syntax(format_args!("'=' or 'in' expected")));
5766        }
5767    }
5768    check_match(ls, state, TK_END, TK_FOR, line)?;
5769    leave_block(ls, state)?; // loop scope ('break' jumps to this point)
5770    Ok(())
5771}
5772
5773fn test_then_block(
5774    ls: &mut LexState,
5775    state: &mut LuaState,
5776    escapelist: &mut i32,
5777) -> Result<(), LuaError> {
5778    lex_next(ls, state)?;
5779    let mut v = ExprDesc::default();
5780    expr(ls, state, &mut v)?;
5781    // Lua 5.5 attributes the conditional `TEST`/`JMP` to the
5782    // condition-expression line (captured here, before `then` is consumed);
5783    // 5.1-5.4 attribute them to the `then`-keyword line (`ls.lastline` after
5784    // `check_next`). Observable via `debug.sethook(f,"l")`: a multi-line
5785    // `if / <cond> / then` fires a line event for the `then` line on <=5.4 but
5786    // not on 5.5 (issue #92). `while`/`repeat` already use the condition line on
5787    // every version (their `cond()` captures it before `do`/`until`).
5788    let cond_line = ls.lastline;
5789    let fold_onto_cond = state.global().lua_version == lua_types::LuaVersion::V55;
5790    check_next(ls, state, TK_THEN)?;
5791
5792    let jf: i32;
5793    if ls.t.token == TK_BREAK {
5794        let line = ls.linenumber;
5795        cg_go_if_false(ls.fs.as_mut().unwrap(), line, &mut v)?;
5796        lex_next(ls, state)?; // skip 'break'
5797        enter_block(ls, false);
5798        let break_str = state.intern_str(b"break")?;
5799        new_goto_entry(ls, state, break_str, line, v.t)?;
5800        while test_next(ls, state, b';' as TokenKind)? {}
5801        if block_follow(ls, false) {
5802            leave_block(ls, state)?;
5803            return Ok(());
5804        } else {
5805            jf = cg_jump(ls.fs.as_mut().unwrap(), ls.linenumber);
5806        }
5807    } else {
5808        let line = if fold_onto_cond {
5809            cond_line
5810        } else {
5811            ls.lastline
5812        };
5813        cg_go_if_true(ls.fs.as_mut().unwrap(), line, &mut v)?;
5814        enter_block(ls, false);
5815        jf = v.f;
5816    }
5817
5818    statlist(ls, state)?;
5819    leave_block(ls, state)?;
5820
5821    if ls.t.token == TK_ELSE || ls.t.token == TK_ELSEIF {
5822        let line = ls.lastline;
5823        let j = cg_jump(ls.fs.as_mut().unwrap(), line);
5824        cg_concat(ls.fs.as_mut().unwrap(), escapelist, j)?;
5825    }
5826    cg_patch_to_here(ls.fs.as_mut().unwrap(), jf)?;
5827    Ok(())
5828}
5829
5830fn ifstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5831    let mut escapelist = NO_JUMP;
5832    test_then_block(ls, state, &mut escapelist)?; // IF cond THEN block
5833    while ls.t.token == TK_ELSEIF {
5834        test_then_block(ls, state, &mut escapelist)?;
5835    }
5836    if test_next(ls, state, TK_ELSE)? {
5837        block(ls, state)?;
5838    }
5839    check_match(ls, state, TK_END, TK_IF, line)?;
5840    cg_patch_to_here(ls.fs.as_mut().unwrap(), escapelist)?;
5841    Ok(())
5842}
5843
5844fn localfunc(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5845    let mut b = ExprDesc::default();
5846    let _fvar = ls.fs.as_ref().unwrap().nactvar as i32;
5847    let name = str_check_name(ls, state)?;
5848    new_local_var(ls, state, name)?;
5849    adjust_local_vars(ls, state, 1)?; // enter its scope
5850    let line = ls.lastline;
5851    body(ls, state, &mut b, false, line)?;
5852    let _pc = ls.fs.as_ref().unwrap().pc;
5853    Ok(())
5854}
5855
5856/// Whether the active Lua version supports `<const>`/`<close>` local-variable
5857/// attributes. True for 5.4 and 5.5; false for 5.1/5.2/5.3.
5858fn version_has_attributes(state: &LuaState) -> bool {
5859    use lua_types::LuaVersion;
5860    matches!(
5861        state.global().lua_version,
5862        LuaVersion::V54 | LuaVersion::V55
5863    )
5864}
5865
5866/// Parses an optional '<const>' or '<close>' attribute.
5867///
5868/// The `<const>`/`<close>` attribute syntax is a Lua 5.4 addition (5.4 §8.1,
5869/// `specs/research/5.3-upstream-delta.md` delta #7). Under Lua 5.3 the `<`
5870/// after a local name is not an attribute opener at all — it is left
5871/// unconsumed so the surrounding statement reports it as an unexpected symbol,
5872/// exactly as the 5.3 parser does. Versions are gated on
5873/// [`lua_types::LuaVersion`], read from the state set at construction.
5874fn getlocalattribute(
5875    ls: &mut LexState,
5876    state: &mut LuaState,
5877    df: VarKind,
5878) -> Result<VarKind, LuaError> {
5879    if !version_has_attributes(state) {
5880        return Ok(df);
5881    }
5882    if test_next(ls, state, b'<' as TokenKind)? {
5883        let attr_name = str_check_name(ls, state)?;
5884        check_next(ls, state, b'>' as TokenKind)?;
5885        let bytes = attr_name.as_bytes();
5886        if bytes == b"const" {
5887            return Ok(VarKind::Const);
5888        } else if bytes == b"close" {
5889            return Ok(VarKind::ToBeClosed);
5890        } else {
5891            let msg = format!("unknown attribute '{}'", String::from_utf8_lossy(bytes));
5892            return Err(lua_lex::sem_error(&mut ls.lex, msg.as_bytes()));
5893        }
5894    }
5895    Ok(df)
5896}
5897
5898fn checktoclose(ls: &mut LexState, _state: &mut LuaState, level: i32) -> Result<(), LuaError> {
5899    if level != -1 {
5900        marktobeclosed(ls.fs.as_mut().unwrap());
5901        let rl = reg_level(ls, ls.fs.as_ref().unwrap(), level);
5902        let line = ls.lastline;
5903        let inst = lua_code::opcodes::Instruction::abck(
5904            lua_code::opcodes::OpCode::Tbc,
5905            rl as u32,
5906            0,
5907            0,
5908            0,
5909        );
5910        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
5911    }
5912    Ok(())
5913}
5914
5915/// Lua 5.5 `global` declaration statement — PRELIMINARY GROUNDWORK STUB.
5916///
5917/// Grammar (manual §3.3.7, `specs/research/5.5-upstream-delta.md` §1b):
5918/// ```text
5919/// stat ::= global attnamelist ['=' explist]
5920/// stat ::= global [attrib] '*'
5921/// attnamelist ::= [attrib] Name [attrib] {',' Name [attrib]}
5922/// attrib ::= '<' Name '>'        -- only <const> is legal for a global; <close> is an error
5923/// ```
5924///
5925/// HOW FAR THIS GETS: this entry point is only reached on the `LuaVersion::V55`
5926/// path (the lexer only emits [`TK_GLOBAL`] there). It RECOGNIZES and fully
5927/// *consumes* both grammar forms — the collective `global *` (with an optional
5928/// leading `<const>` attribute) and the `global x <const>, y` name list with an
5929/// optional `= explist` initializer — so a syntactically valid `global`
5930/// statement parses without error. The declared names and their attributes are
5931/// parsed and then DROPPED (parse-and-noop). No bytecode is emitted and the
5932/// scope resolver is not touched.
5933///
5934/// WHAT THE FULL STATEFUL SCOPE MODEL STILL NEEDS (manual §2.2,
5935/// `specs/research/5.5-upstream-delta.md` §1c/§1d):
5936///  1. Per-scope mode flag: a chunk starts with an implicit `global *` (every
5937///     free name is `_ENV.name`, as in 5.4). The FIRST explicit `global` decl
5938///     in a scope VOIDS that implicit declaration for the rest of the scope.
5939///  2. Declared-set tracking: in a voided scope, every free name must resolve
5940///     to a local, an upvalue, or a name in some in-scope `global` declaration;
5941///     upstream encodes this with `VGLOBAL` and the sentinel `var->u.info == -1`
5942///     meaning "preambular `global *` still active".
5943///  3. Undeclared-name compile error: a free name with no declaration is a
5944///     COMPILE-TIME error, emitted via the new `OP_ERRNNIL` opcode
5945///     (`A Bx`, "raise error if R[A] ~= nil", K[Bx-1] is the global name). That
5946///     opcode, the `ivABC` operand mode, and the reordered SHRI/SHLI are not yet
5947///     in `lua-code`, so even storing to a declared global cannot be codegen'd
5948///     faithfully yet.
5949///  4. `<const>` globals must be read-only (compile error on assignment); a
5950///     `global` decl with an initializer raises a RUNTIME error if the global
5951///     already holds a non-nil value; `<close>` on a global is a compile error.
5952///  5. `global *` (optionally `global <const> *`) re-enables global-by-default
5953///     for the scope.
5954///  6. The `LUA_COMPAT_GLOBAL` axis (default on upstream): un-reserves `global`
5955///     as a keyword and recognizes the statement only contextually. We model
5956///     the strict (compat-off) behavior; a per-state compat flag is future work.
5957/// Parses an optional `<const>` attribute on a global declaration, returning
5958/// whether the declaration is `const`. When no `<...>` attribute is present,
5959/// returns the default `df`.
5960///
5961/// Only `<const>` is legal for a global; `<close>` is the dedicated semantic
5962/// error `global variables cannot be to-be-closed`, and any other attribute
5963/// name is `unknown attribute '<name>'`. Both are emitted via
5964/// [`lua_lex::sem_error`] (location prefix, no `near` suffix).
5965fn get_global_attribute(
5966    ls: &mut LexState,
5967    state: &mut LuaState,
5968    df: bool,
5969) -> Result<bool, LuaError> {
5970    if !test_next(ls, state, b'<' as TokenKind)? {
5971        return Ok(df);
5972    }
5973    let attr = str_check_name(ls, state)?;
5974    check_next(ls, state, b'>' as TokenKind)?;
5975    match attr.as_bytes() {
5976        b"const" => Ok(true),
5977        b"close" => Err(lua_lex::sem_error(
5978            &mut ls.lex,
5979            b"global variables cannot be to-be-closed",
5980        )),
5981        other => {
5982            let msg = format!("unknown attribute '{}'", String::from_utf8_lossy(other));
5983            Err(lua_lex::sem_error(&mut ls.lex, msg.as_bytes()))
5984        }
5985    }
5986}
5987
5988fn globalstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5989    lex_next(ls, state)?; // skip 'global'
5990
5991    // `global function NAME body` — the global-function declaration form:
5992    // declares NAME as a regular global, compiles the body, runs the same
5993    // already-defined guard as `global NAME = expr`, then stores the closure.
5994    if ls.t.token == TK_FUNCTION {
5995        let line = ls.linenumber;
5996        lex_next(ls, state)?; // skip 'function'
5997        let name = str_check_name(ls, state)?;
5998        ls.declared_globals.push((name.clone(), false));
5999        add_scope_barrier(ls, name.clone());
6000        // Build the `_ENV[name]` lvalue (IndexUp; no register cost).
6001        let envn = ls
6002            .envn
6003            .clone()
6004            .expect("envn must be set when resolving globals");
6005        let mut target = ExprDesc::default();
6006        let upper = ls.scope_barriers.len();
6007        let mut fs_box = ls.fs.take();
6008        let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut target, true, upper);
6009        ls.fs = fs_box;
6010        r?;
6011        // Reference `buildglobal`: a `global function _ENV`, or a prior
6012        // `global _ENV`, makes `_ENV` itself resolve to a shadowing global —
6013        // there is no environment to store the function into (§5).
6014        if target.k == ExprKind::Void {
6015            let msg = format!(
6016                "{} is global when accessing variable '{}'",
6017                lua_lex::LUA_ENV.escape_ascii(),
6018                String::from_utf8_lossy(name.as_bytes())
6019            );
6020            return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
6021        }
6022        let lline = ls.lastline;
6023        {
6024            let fs = ls.fs.as_mut().unwrap();
6025            cg_exp_to_any_reg_up(fs, lline, &mut target)?;
6026            let mut key = ExprDesc::default();
6027            codestring(&mut key, name.clone());
6028            cg_indexed(fs, lline, &mut target, &mut key)?;
6029        }
6030        let mut b = ExprDesc::default();
6031        let body_result = body(ls, state, &mut b, false, line);
6032        body_result?;
6033        {
6034            let fs = ls.fs.as_mut().unwrap();
6035            cg_check_global(fs, line, &target, name)?;
6036            cg_storevar(fs, line, &target, &mut b)?;
6037        }
6038        ls.global_strict = true;
6039        return Ok(());
6040    }
6041
6042    // Parse the optional prefixed attribute FIRST (the default kind for the
6043    // whole declaration), then branch on `*` (collective form) vs a name list.
6044    //
6045    //   globalstat -> (GLOBAL) attrib '*'
6046    //   globalstat -> (GLOBAL) attrib NAME attrib {',' NAME attrib}
6047    //
6048    // The leading `<const>` is NOT tied to `*`; `global <const> a, b` is a
6049    // const name list (each name defaults to the prefixed attribute and may
6050    // still carry its own per-name attribute).
6051    let defkind = get_global_attribute(ls, state, false)?;
6052
6053    // `global [attrib] '*'` — the collective form enables global-by-default for
6054    // the rest of the scope. Upstream keeps `*` as a declaration entry that
6055    // coexists with named `global` decls (a later `global name` does NOT void
6056    // it), so a wildcard flag (not merely clearing strict) models it: with the
6057    // wildcard active, every free name resolves as a global.
6058    if test_next(ls, state, b'*' as TokenKind)? {
6059        let star = state.intern_str(b"*")?;
6060        add_scope_barrier(ls, star);
6061        ls.global_strict = false;
6062        ls.global_wildcard = true;
6063        ls.global_wildcard_const = defkind;
6064        return Ok(());
6065    }
6066
6067    // `global attnamelist ['=' explist]` — the name-list form. Record each
6068    // declared name (with its `<const>`-ness) and switch the scope into strict
6069    // mode so subsequent free names must be declared (manual §2.2).
6070    let mut names: Vec<GcRef<LuaString>> = Vec::new();
6071    let mut declarations: Vec<(GcRef<LuaString>, bool)> = Vec::new();
6072    loop {
6073        let name = str_check_name(ls, state)?;
6074        let is_const = get_global_attribute(ls, state, defkind)?;
6075        names.push(name.clone());
6076        declarations.push((name, is_const));
6077        if !test_next(ls, state, b',' as TokenKind)? {
6078            break;
6079        }
6080    }
6081    // `= explist` initializer: assign the values to the declared globals, i.e.
6082    // `_ENV.name = value`. Mirrors `restassign`'s multiple-assignment codegen —
6083    // build an `_ENV[name]` lvalue per declared name (these are IndexUp, no
6084    // register cost), evaluate the RHS, adjust to the variable count, then store
6085    // each target from the top register down. (Initializers were previously
6086    // parsed and dropped.)
6087    if test_next(ls, state, b'=' as TokenKind)? {
6088        // The Lua 5.5 already-defined guard reports the error at the line of the
6089        // initializer (upstream `globalnames` passes `ls->linenumber` here).
6090        let init_line = ls.linenumber;
6091        let mut targets: Vec<ExprDesc> = Vec::with_capacity(names.len());
6092        for name in &names {
6093            let envn = ls
6094                .envn
6095                .clone()
6096                .expect("envn must be set when resolving globals");
6097            let mut env_var = ExprDesc::default();
6098            let upper = ls.scope_barriers.len();
6099            let mut fs_box = ls.fs.take();
6100            let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut env_var, true, upper);
6101            ls.fs = fs_box;
6102            r?;
6103            // Reference `buildglobal`: a prior `global _ENV` makes `_ENV` a
6104            // shadowing global, so there is no environment to assign into (§5).
6105            if env_var.k == ExprKind::Void {
6106                let msg = format!(
6107                    "{} is global when accessing variable '{}'",
6108                    lua_lex::LUA_ENV.escape_ascii(),
6109                    String::from_utf8_lossy(name.as_bytes())
6110                );
6111                return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
6112            }
6113            let line = ls.lastline;
6114            let fs = ls.fs.as_mut().unwrap();
6115            cg_exp_to_any_reg_up(fs, line, &mut env_var)?;
6116            let mut key = ExprDesc::default();
6117            codestring(&mut key, name.clone());
6118            cg_indexed(fs, line, &mut env_var, &mut key)?;
6119            targets.push(env_var);
6120        }
6121        let nvars = targets.len() as i32;
6122        let mut e = ExprDesc::default();
6123        let nexps = explist(ls, state, &mut e)?;
6124        adjust_assign(ls, state, nvars, nexps, &mut e)?;
6125        // Mirror upstream `initglobal`: after the RHS is evaluated, for each
6126        // declared name emit `checkglobal` (the `OP_ERRNNIL` guard) immediately
6127        // before its store. The guard reads the global's *current* runtime value
6128        // and raises `global '<name>' already defined` if it is non-nil. Only
6129        // Lua 5.5 declares `global`; pre-5.5 never reaches this path.
6130        for (i, target) in targets.iter().enumerate().rev() {
6131            let name = names[i].clone();
6132            {
6133                let fs = ls.fs.as_mut().unwrap();
6134                cg_check_global(fs, init_line, target, name)?;
6135            }
6136            let line = ls.lastline;
6137            let fs = ls.fs.as_mut().unwrap();
6138            let freereg = fs.freereg as i32 - 1;
6139            let mut v = ExprDesc::default();
6140            init_exp(&mut v, ExprKind::NonReloc, freereg);
6141            cg_storevar(fs, line, target, &mut v)?;
6142        }
6143    }
6144    for (name, is_const) in declarations {
6145        ls.declared_globals.push((name.clone(), is_const));
6146        add_scope_barrier(ls, name);
6147    }
6148    ls.global_strict = true;
6149    Ok(())
6150}
6151
6152fn localstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
6153    let local_line = ls.lastline;
6154    let mut toclose: i32 = -1;
6155    let mut nvars: i32 = 0;
6156    let mut vidx: i32;
6157    // Lua 5.5 accepts a PREFIXED attribute applied as the default for every
6158    // variable in the list — e.g. `local <const> a, b`. On 5.4/5.3 no prefixed
6159    // attribute exists, so a `<` before the first name stays the reference error
6160    // `<name> expected near '<'`; gate the prefix parse on 5.5.
6161    use lua_types::LuaVersion;
6162    let defkind = if matches!(state.global().lua_version, LuaVersion::V55) {
6163        getlocalattribute(ls, state, VarKind::Reg)?
6164    } else {
6165        VarKind::Reg
6166    };
6167    loop {
6168        let name = str_check_name(ls, state)?;
6169        vidx = new_local_var(ls, state, name)?;
6170        let kind = getlocalattribute(ls, state, defkind)?;
6171        get_local_var_desc_mut(ls, ls.fs.as_ref().unwrap().firstlocal, vidx).kind = kind;
6172        if kind == VarKind::ToBeClosed {
6173            if toclose != -1 {
6174                let saved_line = ls.lex.linenumber;
6175                ls.lex.linenumber = local_line;
6176                let err = lua_lex::lex_error(
6177                    &mut ls.lex,
6178                    b"multiple to-be-closed variables in local list",
6179                    0,
6180                );
6181                ls.lex.linenumber = saved_line;
6182                return Err(err);
6183            }
6184            toclose = ls.fs.as_ref().unwrap().nactvar as i32 + nvars;
6185        }
6186        nvars += 1;
6187        if !test_next(ls, state, b',' as TokenKind)? {
6188            break;
6189        }
6190    }
6191    let nexps: i32;
6192    let mut e = ExprDesc::default();
6193    if test_next(ls, state, b'=' as TokenKind)? {
6194        nexps = explist(ls, state, &mut e)?;
6195    } else {
6196        e.k = ExprKind::Void;
6197        nexps = 0;
6198    }
6199    let first_local = ls.fs.as_ref().unwrap().firstlocal;
6200    let last_vd_kind = ls.dyd.actvar[(first_local + vidx) as usize].kind;
6201    // Mirrors C's `localstat` fold (lparser.c): when the initializer count
6202    // matches the variable count, the last variable is `<const>`, and its
6203    // initializer is a compile-time constant, fold it — store the value on the
6204    // descriptor, mark the variable RDKCTC, and emit NO register/local for it.
6205    // `e` here is the last initializer straight from `explist` (a literal or a
6206    // constant-folded expression), so `cg_exp2const` reads its literal fields
6207    // directly. `adjust_local_vars(nvars - 1)` EXCLUDES the const (no locvar, no
6208    // register); `nactvar += 1` still counts it so scope resolution sees it.
6209    // Ordering is load-bearing: write `const_val` before flipping `kind`.
6210    let folded = if nvars == nexps && last_vd_kind == VarKind::Const {
6211        cg_exp2const(&e)
6212    } else {
6213        None
6214    };
6215    if let Some(v) = folded {
6216        ls.dyd.actvar[(first_local + vidx) as usize].const_val = v;
6217        ls.dyd.actvar[(first_local + vidx) as usize].kind = VarKind::CompileTimeConst;
6218        adjust_local_vars(ls, state, nvars - 1)?;
6219        ls.fs.as_mut().unwrap().nactvar += 1;
6220    } else {
6221        adjust_assign(ls, state, nvars, nexps, &mut e)?;
6222        adjust_local_vars(ls, state, nvars)?;
6223    }
6224    checktoclose(ls, state, toclose)?;
6225    Ok(())
6226}
6227
6228/// Parses a function name (NAME {'.' NAME} [':' NAME]). Returns ismethod.
6229fn funcname(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<bool, LuaError> {
6230    let mut ismethod = false;
6231    singlevar(ls, state, v)?;
6232    while ls.t.token == b'.' as TokenKind {
6233        fieldsel(ls, state, v)?;
6234    }
6235    if ls.t.token == b':' as TokenKind {
6236        ismethod = true;
6237        fieldsel(ls, state, v)?;
6238    }
6239    Ok(ismethod)
6240}
6241
6242fn funcstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
6243    lex_next(ls, state)?;
6244    let mut v = ExprDesc::default();
6245    let mut b = ExprDesc::default();
6246    let ismethod = funcname(ls, state, &mut v)?;
6247    check_readonly(ls, state, &v.clone())?;
6248    body(ls, state, &mut b, ismethod, line)?;
6249    check_readonly(ls, state, &v.clone())?;
6250    let fs = ls.fs.as_mut().unwrap();
6251    cg_storevar(fs, line, &v, &mut b)?;
6252    Ok(())
6253}
6254
6255fn exprstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
6256    let mut v_assign = LhsAssign {
6257        prev: None,
6258        v: ExprDesc::default(),
6259    };
6260    suffixedexp(ls, state, &mut v_assign.v)?;
6261    if ls.t.token == b'=' as TokenKind || ls.t.token == b',' as TokenKind {
6262        restassign(ls, state, &mut v_assign, 1)?;
6263    } else {
6264        if v_assign.v.k != ExprKind::Call {
6265            // Lua 5.1's `exprstat` falls into `assignment`, which requires an
6266            // `=`, so a bare primary expression statement reports `'=' expected`.
6267            // 5.2+ rewrote this path to report the generic `syntax error`. Match
6268            // the version. This is what makes `goto done` (where `goto` lexes as
6269            // a name under V51) report `'=' expected near 'done'`. See
6270            // specs/followup/5.1-roster-syntax.md §2.
6271            if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
6272                return Err(error_expected(ls, b'=' as TokenKind));
6273            }
6274            return Err(lua_lex::syntax_error(&mut ls.lex, b"syntax error"));
6275        }
6276        let info = v_assign.v.u.info as usize;
6277        let fs = ls.fs.as_mut().unwrap();
6278        let mut lc = lua_code::opcodes::Instruction(fs.f.code[info].0);
6279        lc.set_arg_c(1);
6280        fs.f.code[info] = lua_types::opcode::Instruction::new(lc.0);
6281    }
6282    Ok(())
6283}
6284
6285fn retstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
6286    let mut first = {
6287        let fs = ls.fs.as_ref().unwrap();
6288        nvarstack(ls, fs)
6289    };
6290    let mut nret: i32;
6291    if block_follow(ls, true) || ls.t.token == b';' as TokenKind {
6292        nret = 0;
6293    } else {
6294        let mut e = ExprDesc::default();
6295        nret = explist(ls, state, &mut e)?;
6296        if e.k.has_mult_ret() {
6297            cg_set_returns(ls.fs.as_mut().unwrap(), &mut e, LUA_MULTRET);
6298            if e.k == ExprKind::Call && nret == 1 {
6299                let insidetbc = ls
6300                    .fs
6301                    .as_ref()
6302                    .unwrap()
6303                    .bl
6304                    .as_ref()
6305                    .map_or(false, |b| b.insidetbc);
6306                if !insidetbc {
6307                    let fs = ls.fs.as_mut().unwrap();
6308                    let info = e.u.info as usize;
6309                    let mut lc = lua_code::opcodes::Instruction(fs.f.code[info].0);
6310                    lc.set_opcode(lua_code::opcodes::OpCode::TailCall);
6311                    fs.f.code[info] = lua_types::opcode::Instruction::new(lc.0);
6312                }
6313            }
6314            nret = LUA_MULTRET;
6315        } else {
6316            let line = ls.lastline;
6317            if nret == 1 {
6318                first = cg_exp_to_any_reg(ls.fs.as_mut().unwrap(), line, &mut e)? as i32;
6319            } else {
6320                cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut e)?;
6321            }
6322        }
6323    }
6324    let line = ls.lastline;
6325    let version = state.global().lua_version;
6326    cg_emit_return(ls.fs.as_mut().unwrap(), line, first, nret, version)?;
6327    test_next(ls, state, b';' as TokenKind)?;
6328    Ok(())
6329}
6330
6331/// Top-level statement dispatcher.
6332fn statement(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
6333    // This is the line of the current keyword (for/while/if/...), captured
6334    // BEFORE consuming. Used both for error messages on unmatched blocks
6335    // AND for runtime-error line attribution on control-flow instructions
6336    // (FORPREP, etc). errors.lua's lineerror tests depend on this.
6337    let line = ls.linenumber;
6338    enter_level(ls, state)?;
6339    match ls.t.token {
6340        c if c == b';' as TokenKind
6341            && state.global().lua_version != lua_types::LuaVersion::V51 =>
6342        {
6343            lex_next(ls, state)?;
6344        }
6345        TK_IF => {
6346            ifstat(ls, state, line)?;
6347        }
6348        TK_WHILE => {
6349            whilestat(ls, state, line)?;
6350        }
6351        TK_DO => {
6352            lex_next(ls, state)?; // skip DO
6353            block(ls, state)?;
6354            check_match(ls, state, TK_END, TK_DO, line)?;
6355        }
6356        TK_FOR => {
6357            forstat(ls, state, line)?;
6358        }
6359        TK_REPEAT => {
6360            repeatstat(ls, state, line)?;
6361        }
6362        TK_FUNCTION => {
6363            funcstat(ls, state, line)?;
6364        }
6365        TK_LOCAL => {
6366            lex_next(ls, state)?; // skip LOCAL
6367            if test_next(ls, state, TK_FUNCTION)? {
6368                localfunc(ls, state)?;
6369            } else {
6370                localstat(ls, state)?;
6371            }
6372        }
6373        TK_DBCOLON => {
6374            lex_next(ls, state)?; // skip '::'
6375            let name = str_check_name(ls, state)?;
6376            labelstat(ls, state, name, line)?;
6377        }
6378        TK_RETURN => {
6379            lex_next(ls, state)?; // skip RETURN
6380            retstat(ls, state)?;
6381        }
6382        TK_BREAK => {
6383            breakstat(ls, state)?;
6384        }
6385        TK_GOTO => {
6386            lex_next(ls, state)?; // skip 'goto'
6387            gotostat(ls, state)?;
6388        }
6389        _ => {
6390            // Lua 5.5 with the upstream-default LUA_COMPAT_GLOBAL: `global` is
6391            // NOT a reserved word. It introduces a declaration only when, at
6392            // statement start, the name `global` is followed by a Name, `*`, or
6393            // `<` (the collective `global <const> *` form). Otherwise it is an
6394            // ordinary identifier and the statement is a normal assignment/call.
6395            let is_global_decl = state.global().lua_version == lua_types::LuaVersion::V55
6396                && ls.t.token == TK_NAME
6397                && ls
6398                    .t
6399                    .seminfo
6400                    .ts
6401                    .as_ref()
6402                    .map_or(false, |s| s.as_bytes() == b"global")
6403                && {
6404                    let nxt = lex_lookahead(ls, state)?;
6405                    nxt == TK_NAME
6406                        || nxt == b'*' as TokenKind
6407                        || nxt == b'<' as TokenKind
6408                        || nxt == TK_FUNCTION
6409                };
6410            if is_global_decl {
6411                globalstat(ls, state)?;
6412            } else {
6413                exprstat(ls, state)?;
6414            }
6415        }
6416    }
6417    debug_assert!(
6418        ls.fs.as_ref().unwrap().f.maxstacksize >= ls.fs.as_ref().unwrap().freereg
6419            && ls.fs.as_ref().unwrap().freereg as i32 >= nvarstack(ls, ls.fs.as_ref().unwrap())
6420    );
6421    let nv = nvarstack(ls, ls.fs.as_ref().unwrap());
6422    ls.fs.as_mut().unwrap().freereg = nv as u8;
6423    leave_level(ls);
6424    Ok(())
6425}
6426
6427// ── §14 Main function and entry point ────────────────────────────────────────
6428
6429/// Compiles the main chunk (always a vararg function with _ENV upvalue).
6430fn mainfunc(
6431    ls: &mut LexState,
6432    state: &mut LuaState,
6433    main_fs: FuncState,
6434) -> Result<Box<LuaProto>, LuaError> {
6435    open_func(ls, state, main_fs)?;
6436
6437    setvararg(ls.fs.as_mut().unwrap(), state, 0)?;
6438
6439    let env_name = ls.envn.clone();
6440    {
6441        let version = ls.lex.version;
6442        let idx = alloc_upvalue(ls.fs.as_mut().unwrap(), version)?;
6443        let up = &mut ls.fs.as_mut().unwrap().f.upvalues[idx];
6444        up.instack = true;
6445        up.idx = 0;
6446        up.kind = VarKind::Reg.as_u8();
6447        up.name = env_name.clone();
6448    }
6449
6450    lex_next(ls, state)?;
6451
6452    statlist(ls, state)?;
6453
6454    check(ls, TK_EOS)?;
6455
6456    close_func(ls, state)
6457}
6458
6459/// Top-level entry point: parses a whole chunk and returns the prototype of its
6460/// main function. The caller wraps this `Box<LuaProto>` into a closure and hands
6461/// it to the GC; that boundary is the public contract of this crate.
6462///
6463/// # Precondition — GC must be stopped for the whole parse window
6464///
6465/// The parser holds untraced references to GC-managed objects for the duration
6466/// of a parse: interned name/string handles, the half-built `Box<LuaProto>`,
6467/// long-string anchors, and — for `<const>` folding — the value stored in a
6468/// `VarDesc::const_val` / `ExprPayload::const_snapshot` (which may be an
6469/// interned string). None of these are reachable from a GC root while parsing,
6470/// so a collection cycle during `parse` could free a live constant and produce
6471/// a use-after-free. The supported entry points satisfy this: the loader stops
6472/// the collector across the entire production parse window (`do_.rs` f_parser),
6473/// and explicit `collectgarbage` requests early-return while internally stopped.
6474/// A direct caller of this function that has NOT stopped the GC violates the
6475/// contract — this is a pre-existing whole-parser requirement (the constant
6476/// table has always needed it), not specific to `<const>` folding.
6477pub fn parse(
6478    state: &mut LuaState,
6479    dyd: DynData,
6480    z: &mut lua_vm::zio::ZIO,
6481    name: &[u8],
6482    firstchar: i32,
6483) -> Result<Box<LuaProto>, LuaError> {
6484    let source_str = state.intern_str(name)?;
6485    let envn_str = state.intern_str(lua_lex::LUA_ENV)?;
6486
6487    let z = z.take();
6488
6489    let lex_ls = lua_lex::LexState {
6490        current: firstchar,
6491        linenumber: 1,
6492        lastline: 1,
6493        t: lua_lex::Token::eos(),
6494        lookahead: lua_lex::Token::eos(),
6495        fs: None,
6496        z,
6497        buff: lua_lex::LexBuffer::new(),
6498        h: None,
6499        long_str_anchor: std::collections::HashMap::new(),
6500        dyd: None,
6501        source: source_str.clone(),
6502        envn: envn_str.clone(),
6503        version: state.global().lua_version,
6504    };
6505
6506    let mut lexstate = LexState {
6507        current: lex_ls.current,
6508        linenumber: lex_ls.linenumber,
6509        lastline: lex_ls.lastline,
6510        t: LexToken::default(),
6511        lookahead: LexToken::default(),
6512        fs: None,
6513        dyd,
6514        source: Some(source_str.clone()),
6515        envn: Some(lex_ls.envn.clone()),
6516        lex: lex_ls,
6517        recursion_depth: 0,
6518        global_strict: false,
6519        global_wildcard: false,
6520        global_wildcard_const: false,
6521        declared_globals: Vec::new(),
6522        scope_barriers: Vec::new(),
6523    };
6524    //   `mainfunc`; it does NOT pre-read the first token. `mainfunc` itself
6525    //   issues the initial `luaX_next` once its prelude (open_func, vararg
6526    //   marker, _ENV upvalue) is in place.
6527
6528    let mut main_proto = Box::new(LuaProto::placeholder());
6529    main_proto.source = Some(source_str);
6530    main_proto.is_vararg = true;
6531    let main_fs = FuncState {
6532        f: main_proto,
6533        prev: None,
6534        bl: None,
6535        pc: 0,
6536        lasttarget: 0,
6537        previousline: 0,
6538        nk: 0,
6539        np: 0,
6540        nabslineinfo: 0,
6541        firstlocal: 0,
6542        firstlabel: 0,
6543        ndebugvars: 0,
6544        nactvar: 0,
6545        nactvar_reg: 0,
6546        first_scope_barrier: 0,
6547        nups: 0,
6548        freereg: 0,
6549        iwthabs: 0,
6550        needclose: false,
6551        last_token_line: 0,
6552    };
6553
6554    mainfunc(&mut lexstate, state, main_fs)
6555}
6556
6557/// Convert a `lua_lex::TokenValue` into the local `parse::TokenValue` flat shape.
6558///
6559/// The parser's local `LexState` predates the lex-side enum and uses a flat
6560/// (r, i, ts) record; this picks out whichever variant the lexer produced.
6561fn local_token_value(v: &lua_lex::TokenValue) -> TokenValue {
6562    match v {
6563        lua_lex::TokenValue::None => TokenValue::default(),
6564        lua_lex::TokenValue::Float(r) => TokenValue {
6565            r: *r,
6566            i: 0,
6567            ts: None,
6568        },
6569        lua_lex::TokenValue::Int(i) => TokenValue {
6570            r: 0.0,
6571            i: *i,
6572            ts: None,
6573        },
6574        lua_lex::TokenValue::Str(s) => TokenValue {
6575            r: 0.0,
6576            i: 0,
6577            ts: Some(s.clone()),
6578        },
6579    }
6580}
6581
6582#[cfg(test)]
6583mod tests {
6584    use super::*;
6585
6586    /// A bare [`FuncState`] with an empty prototype, enough to exercise the
6587    /// codegen primitives that only read/write `f.code` (jump emission and the
6588    /// jump-list cursor).
6589    fn bare_fs() -> FuncState {
6590        FuncState {
6591            f: Box::new(LuaProto::placeholder()),
6592            prev: None,
6593            bl: None,
6594            pc: 0,
6595            lasttarget: 0,
6596            previousline: 0,
6597            nk: 0,
6598            np: 0,
6599            nabslineinfo: 0,
6600            firstlocal: 0,
6601            firstlabel: 0,
6602            ndebugvars: 0,
6603            nactvar: 0,
6604            nactvar_reg: 0,
6605            first_scope_barrier: 0,
6606            nups: 0,
6607            freereg: 0,
6608            iwthabs: 0,
6609            needclose: false,
6610            last_token_line: 0,
6611        }
6612    }
6613
6614    /// Emit three `OP_JMP`s, thread them into one list via [`cg_concat`], then
6615    /// confirm the [`JumpList`] cursor yields exactly the pc sequence a manual
6616    /// `while pc != NO_JUMP { pc = cg_get_jump(fs, pc) }` walk produces. This is
6617    /// the behavioral invariant the iterator transformation must preserve.
6618    #[test]
6619    fn jumplist_yields_same_pcs_as_manual_walk() {
6620        let mut fs = bare_fs();
6621
6622        let mut list = NO_JUMP;
6623        let mut emitted = Vec::new();
6624        for _ in 0..3 {
6625            let pc = cg_jump(&mut fs, 1);
6626            emitted.push(pc);
6627            cg_concat(&mut fs, &mut list, pc).unwrap();
6628        }
6629
6630        let mut manual = Vec::new();
6631        let mut pc = list;
6632        while pc != NO_JUMP {
6633            manual.push(pc);
6634            pc = cg_get_jump(&fs, pc);
6635        }
6636
6637        let mut via_cursor = Vec::new();
6638        let mut walk = JumpList::new(list);
6639        while let Some(pc) = walk.next(&fs) {
6640            via_cursor.push(pc);
6641        }
6642
6643        assert_eq!(manual, via_cursor);
6644        assert_eq!(manual.len(), 3);
6645        let mut sorted = manual.clone();
6646        sorted.sort_unstable();
6647        let mut sorted_emitted = emitted.clone();
6648        sorted_emitted.sort_unstable();
6649        assert_eq!(sorted, sorted_emitted);
6650    }
6651
6652    /// An empty list yields nothing; a single-node list yields exactly that pc.
6653    #[test]
6654    fn jumplist_empty_and_single() {
6655        let mut fs = bare_fs();
6656
6657        let mut empty = JumpList::new(NO_JUMP);
6658        assert_eq!(empty.next(&fs), None);
6659
6660        let pc = cg_jump(&mut fs, 1);
6661        let mut single = JumpList::new(pc);
6662        assert_eq!(single.next(&fs), Some(pc));
6663        assert_eq!(single.next(&fs), None);
6664    }
6665
6666    /// [`cg_concat`] must still fix the tail of an existing list to point at the
6667    /// appended jump — the cursor-based tail walk must find the same tail node
6668    /// the old hand loop did.
6669    #[test]
6670    fn cg_concat_links_tail_to_appended_jump() {
6671        let mut fs = bare_fs();
6672        let a = cg_jump(&mut fs, 1);
6673        let b = cg_jump(&mut fs, 1);
6674        let mut list = a;
6675        cg_concat(&mut fs, &mut list, b).unwrap();
6676        assert_eq!(list, a);
6677        assert_eq!(cg_get_jump(&fs, a), b);
6678        assert_eq!(cg_get_jump(&fs, b), NO_JUMP);
6679    }
6680
6681    /// Spot-check the token-to-binop mapping and the load-bearing invariant that
6682    /// every [`BinOpr`] discriminant is a valid index into [`PRIORITY`]. The
6683    /// expression parser indexes `PRIORITY[op as usize]`; a reordered or
6684    /// short-by-one table would silently mis-climb operator precedence.
6685    #[test]
6686    fn binopr_mapping_and_priority_table_are_consistent() {
6687        assert_eq!(getbinopr(b'+' as TokenKind), BinOpr::Add);
6688        assert_eq!(getbinopr(b'/' as TokenKind), BinOpr::Div);
6689        assert_eq!(getbinopr(TK_IDIV), BinOpr::IDiv);
6690        assert_eq!(getbinopr(TK_SHL), BinOpr::Shl);
6691        assert_eq!(getbinopr(TK_CONCAT), BinOpr::Concat);
6692        assert_eq!(getbinopr(TK_AND), BinOpr::And);
6693        assert_eq!(getbinopr(b'@' as TokenKind), BinOpr::NoBinOpr);
6694
6695        for op in [
6696            BinOpr::Add,
6697            BinOpr::Pow,
6698            BinOpr::Concat,
6699            BinOpr::Eq,
6700            BinOpr::And,
6701            BinOpr::Or,
6702        ] {
6703            assert!(
6704                (op as usize) < PRIORITY.len(),
6705                "{op:?} out of PRIORITY range"
6706            );
6707        }
6708        assert_eq!(BinOpr::Or as usize, PRIORITY.len() - 1);
6709
6710        assert_eq!(getunopr(b'-' as TokenKind), UnOpr::Minus);
6711        assert_eq!(getunopr(TK_NOT), UnOpr::Not);
6712        assert_eq!(getunopr(b'#' as TokenKind), UnOpr::Len);
6713        assert_eq!(getunopr(b'+' as TokenKind), UnOpr::NoUnOpr);
6714    }
6715}