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