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