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, LuaError, LuaString, LuaValue, LuaProto, UpvalDesc, LocalVar};
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}
99
100impl VarKind {
101    pub fn from_u8(v: u8) -> Self {
102        match v {
103            0 => VarKind::Reg,
104            1 => VarKind::Const,
105            2 => VarKind::ToBeClosed,
106            3 => VarKind::CompileTimeConst,
107            _ => VarKind::Reg,
108        }
109    }
110    pub fn as_u8(self) -> u8 { self as u8 }
111}
112
113// ── ExprKind ────────────────────────────────────────────────────────────────
114
115/// Variants correspond exactly to the C enum in lparser.h.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum ExprKind {
118    Void,       // VVOID: empty expression list
119    Nil,        // VNIL: constant nil
120    True,       // VTRUE: constant true
121    False,      // VFALSE: constant false
122    K,          // VK: constant in k[]; info = index
123    KFlt,       // VKFLT: float constant; u.nval
124    KInt,       // VKINT: integer constant; u.ival
125    KStr,       // VKSTR: string constant; u.strval
126    NonReloc,   // VNONRELOC: value in fixed register; info = reg
127    Local,      // VLOCAL: local variable; u.var.ridx, u.var.vidx
128    UpVal,      // VUPVAL: upvalue; info = upvalue index
129    Const,      // VCONST: compile-time const; info = absolute actvar index
130    Indexed,    // VINDEXED: indexed by reg key; u.ind.t, u.ind.idx
131    IndexUp,    // VINDEXUP: indexed upvalue; u.ind.t, u.ind.idx
132    IndexI,     // VINDEXI: indexed by int; u.ind.t, u.ind.idx
133    IndexStr,   // VINDEXSTR: indexed by string; u.ind.t, u.ind.idx
134    Jmp,        // VJMP: test/comparison; info = jump instruction pc
135    Reloc,      // VRELOC: result in any register; info = instruction pc
136    Call,       // VCALL: function call; info = instruction pc
137    VarArg,     // VVARARG: vararg; info = instruction pc
138}
139
140impl ExprKind {
141    #[inline]
142    pub fn has_mult_ret(self) -> bool {
143        matches!(self, ExprKind::Call | ExprKind::VarArg)
144    }
145
146    #[inline]
147    pub fn is_var(self) -> bool {
148        matches!(
149            self,
150            ExprKind::Local
151                | ExprKind::UpVal
152                | ExprKind::Const
153                | ExprKind::Indexed
154                | ExprKind::IndexUp
155                | ExprKind::IndexI
156                | ExprKind::IndexStr
157        )
158    }
159
160    #[inline]
161    pub fn is_indexed(self) -> bool {
162        matches!(
163            self,
164            ExprKind::Indexed | ExprKind::IndexUp | ExprKind::IndexI | ExprKind::IndexStr
165        )
166    }
167}
168
169// ── ExprPayload ─────────────────────────────────────────────────────────────
170
171/// PORT NOTE: C uses a union; all arms share memory. Rust keeps all fields in
172///   one struct for Phase A simplicity. Phase B may refactor to a proper enum.
173#[derive(Debug, Clone, Default)]
174pub struct ExprPayload {
175    pub ival: i64,
176    pub nval: f64,
177    pub strval: Option<GcRef<LuaString>>,
178    pub info: i32,
179    pub ind_idx: i16,
180    pub ind_t: u8,
181    pub var_ridx: u8,
182    pub var_vidx: u16,
183    /// Lua 5.5: when this expression resolves a global that was declared
184    /// `global x <const>`, the declared name is recorded here so that an
185    /// assignment to it is rejected by [`check_readonly`]. `None` for every
186    /// other expression (and on all pre-5.5 versions).
187    pub global_const_name: Option<GcRef<LuaString>>,
188}
189
190// ── ExprDesc ────────────────────────────────────────────────────────────────
191
192/// Field `t`/`f` are patch-lists for short-circuit boolean evaluation.
193#[derive(Debug, Clone)]
194pub struct ExprDesc {
195    pub k: ExprKind,
196    pub u: ExprPayload,
197    pub t: i32,
198    pub f: i32,
199}
200
201impl Default for ExprDesc {
202    fn default() -> Self {
203        ExprDesc { k: ExprKind::Void, u: ExprPayload::default(), t: NO_JUMP, f: NO_JUMP }
204    }
205}
206
207// ── VarDesc ─────────────────────────────────────────────────────────────────
208
209/// PORT NOTE: C uses a union (vd fields + k for const value). Rust keeps all
210///   fields in a struct. The `const_val` field is only meaningful when
211///   `kind == VarKind::CompileTimeConst`.
212#[derive(Debug, Clone)]
213pub struct VarDesc {
214    pub kind: VarKind,
215    pub ridx: u8,
216    pub pidx: i16,
217    pub name: Option<GcRef<LuaString>>,
218    pub const_val: LuaValue,
219}
220
221impl Default for VarDesc {
222    fn default() -> Self {
223        VarDesc {
224            kind: VarKind::Reg,
225            ridx: 0,
226            pidx: 0,
227            name: None,
228            const_val: LuaValue::Nil,
229        }
230    }
231}
232
233// ── LabelDesc ───────────────────────────────────────────────────────────────
234
235#[derive(Debug, Clone)]
236pub struct LabelDesc {
237    pub name: Option<GcRef<LuaString>>,
238    pub pc: i32,
239    pub line: i32,
240    pub nactvar: u8,
241    pub close: bool,
242}
243
244// ── DynData ─────────────────────────────────────────────────────────────────
245
246/// C stored C-style dynamic arrays (arr/n/size); Rust uses Vec.
247#[derive(Debug, Default)]
248pub struct DynData {
249    pub actvar: Vec<VarDesc>,
250    pub gt: Vec<LabelDesc>,
251    pub label: Vec<LabelDesc>,
252}
253
254// ── BlockCnt ────────────────────────────────────────────────────────────────
255
256/// In C: stack-allocated, chained via raw `*previous` pointer.
257/// In Rust: heap-allocated in an `Option<Box<BlockCnt>>` chain on FuncState.
258#[derive(Debug)]
259pub struct BlockCnt {
260    pub previous: Option<Box<BlockCnt>>,
261    pub firstlabel: i32,
262    pub firstgoto: i32,
263    pub nactvar: u8,
264    pub upval: bool,
265    pub isloop: bool,
266    pub insidetbc: bool,
267    /// Lua 5.5: the `global`-declaration scope state (LexState `global_strict`
268    /// and the length of `declared_globals`) saved on block entry and restored
269    /// on exit, so a `global` declaration is scoped to its enclosing block —
270    /// e.g. `do global x end` does not leak strict mode past the block.
271    pub saved_global_strict: bool,
272    pub saved_declared_globals: usize,
273}
274
275// ── FuncState ───────────────────────────────────────────────────────────────
276
277/// In C: stack-allocated in `body()`, chained via raw `*prev` pointer.
278/// In Rust: heap-allocated via `Option<Box<FuncState>>` in LexState.
279#[derive(Debug)]
280pub struct FuncState {
281    /// PORT NOTE: types.tsv maps this to GcRef<LuaProto>; we use Box<LuaProto>
282    ///   during compilation to avoid RefCell overhead. close_func hands it to
283    ///   the GC/parent at close time.
284    pub f: Box<LuaProto>,
285    pub prev: Option<Box<FuncState>>,
286    pub bl: Option<Box<BlockCnt>>,
287    pub pc: i32,
288    pub lasttarget: i32,
289    pub previousline: i32,
290    pub nk: i32,
291    pub np: i32,
292    pub nabslineinfo: i32,
293    pub firstlocal: i32,
294    pub firstlabel: i32,
295    pub ndebugvars: i16,
296    pub nactvar: u8,
297    pub nups: u8,
298    pub freereg: u8,
299    pub iwthabs: u8,
300    pub needclose: bool,
301    /// Current `ls.lastline` value, mirrored on every `sync_from_lex`.
302    /// Used by `emit_inst` to attribute the line to the just-consumed token
303    /// (matching lua-c's `savelineinfo(fs, f, fs->ls->lastline)`), instead
304    /// of whatever `line` the caller threaded down. The threaded `line`
305    /// param is preserved only for explicit overrides (luaK_fixline-style).
306    pub last_token_line: i32,
307}
308
309// ── ConsControl ─────────────────────────────────────────────────────────────
310
311/// PORT NOTE: C stores `expdesc *t` as a pointer to the caller's expdesc.
312///   Rust stores a copy of the table descriptor; callers must sync back
313///   if they mutate it. Phase B may restructure.
314#[derive(Debug)]
315pub struct ConsControl {
316    pub v: ExprDesc,
317    pub t: ExprDesc,
318    pub nh: i32,
319    pub na: i32,
320    pub tostore: i32,
321}
322
323// ── LhsAssign ───────────────────────────────────────────────────────────────
324
325/// In C: stack-allocated, chained via raw `*prev`. In Rust: `Option<Box<...>>`.
326#[derive(Debug)]
327pub struct LhsAssign {
328    pub prev: Option<Box<LhsAssign>>,
329    pub v: ExprDesc,
330}
331
332// ── Unary / binary operator enums ───────────────────────────────────────────
333// TODO(port): unify with lua_code::UnOpr / BinOpr when lua-code lands.
334
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336pub enum UnOpr {
337    Minus,    // OPR_MINUS
338    BNot,     // OPR_BNOT
339    Not,      // OPR_NOT
340    Len,      // OPR_LEN
341    NoUnOpr,  // OPR_NOUNOPR
342}
343
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub enum BinOpr {
346    Add,     // OPR_ADD
347    Sub,     // OPR_SUB
348    Mul,     // OPR_MUL
349    Mod,     // OPR_MOD
350    Pow,     // OPR_POW
351    Div,     // OPR_DIV
352    IDiv,    // OPR_IDIV
353    BAnd,    // OPR_BAND
354    BOr,     // OPR_BOR
355    BXor,    // OPR_BXOR
356    Shl,     // OPR_SHL
357    Shr,     // OPR_SHR
358    Concat,  // OPR_CONCAT
359    Eq,      // OPR_EQ
360    Lt,      // OPR_LT
361    Le,      // OPR_LE
362    Ne,      // OPR_NE
363    Gt,      // OPR_GT
364    Ge,      // OPR_GE
365    And,     // OPR_AND
366    Or,      // OPR_OR
367    NoBinOpr, // OPR_NOBINOPR
368}
369
370/// Indexed by BinOpr discriminant (0 = Add, ... 20 = Or).
371const PRIORITY: [(u8, u8); 21] = [
372    (10, 10), (10, 10),       // Add, Sub
373    (11, 11), (11, 11),       // Mul, Mod
374    (14, 13),                 // Pow (right-associative)
375    (11, 11), (11, 11),       // Div, IDiv
376    (6, 6), (4, 4), (5, 5),  // BAnd, BOr, BXor
377    (7, 7), (7, 7),           // Shl, Shr
378    (9, 8),                   // Concat (right-associative)
379    (3, 3), (3, 3), (3, 3),  // Eq, Lt, Le
380    (3, 3), (3, 3), (3, 3),  // Ne, Gt, Ge
381    (2, 2), (1, 1),           // And, Or
382];
383
384// TODO_ARCH(phase-b-reconcile): re-exporting canonical OpCode from lua-code.
385pub use lua_code::opcodes::OpCode;
386
387// ── Minimal LexState stub ───────────────────────────────────────────────────
388// PORT NOTE: In C, LexState is defined in llex.h (→ lua-lex crate).
389//   We declare a minimal stub here for Phase A so function bodies can be
390//   written. Phase B will replace with `lua_lex::LexState` and remove this.
391
392/// Semantic info attached to a token.
393#[derive(Debug, Clone, Default)]
394pub struct TokenValue {
395    pub r: f64,
396    pub i: i64,
397    pub ts: Option<GcRef<LuaString>>,
398}
399
400#[derive(Debug, Clone, Default)]
401pub struct LexToken {
402    pub token: TokenKind,
403    pub seminfo: TokenValue,
404}
405
406/// PORT NOTE: This is a Phase A stub. In Phase B, `LexState` lives in
407///   `lua-lex` and `lua-parse` imports it. `FuncState` will move here
408///   or be passed separately. The `fs` field creates a circular-crate
409///   dependency that Phase B must resolve (likely: both live in one crate).
410pub struct LexState {
411    pub current: i32,
412    pub linenumber: i32,
413    pub lastline: i32,
414    pub t: LexToken,
415    pub lookahead: LexToken,
416    pub fs: Option<Box<FuncState>>,
417    pub dyd: DynData,
418    pub source: Option<GcRef<LuaString>>,
419    pub envn: Option<GcRef<LuaString>>,
420    /// Underlying lexer state that owns the ZIO stream and lex buffer.
421    /// The parser drives the lexer by calling `lex_next` / `lex_lookahead`,
422    /// which forward to `lua_lex::next` / `lua_lex::lookahead` on this inner
423    /// state and then mirror the resulting token into `self.t` / `self.lookahead`.
424    pub lex: lua_lex::LexState,
425    /// Parser recursion depth for C-Lua's `enterlevel` / `leavelevel` guard.
426    pub recursion_depth: u32,
427    /// Lua 5.5 global-declaration mode (manual §2.2). A chunk begins with an
428    /// implicit `global *` (`false` here): every free name is a global, as in
429    /// 5.4. The first explicit `global name, …` declaration flips this to
430    /// `true` ("strict"), after which a free name must appear in
431    /// [`Self::declared_globals`] or it is a compile-time error. `global *`
432    /// flips it back to `false`. Only ever set on the 5.5 path (the lexer emits
433    /// `TK_GLOBAL` only there), so pre-5.5 versions are unaffected.
434    pub global_strict: bool,
435    /// Names declared via `global`, each paired with whether it was declared
436    /// `<const>` (read-only). Consulted by name resolution under
437    /// [`Self::global_strict`].
438    pub declared_globals: Vec<(GcRef<LuaString>, bool)>,
439}
440
441const PARSER_MAX_C_CALLS: u32 = 200;
442
443fn enter_level(ls: &mut LexState) -> Result<(), LuaError> {
444    ls.recursion_depth += 1;
445    if ls.recursion_depth >= PARSER_MAX_C_CALLS {
446        Err(LuaError::syntax(format_args!("C stack overflow")))
447    } else {
448        Ok(())
449    }
450}
451
452fn leave_level(ls: &mut LexState) {
453    ls.recursion_depth = ls.recursion_depth.saturating_sub(1);
454}
455
456/// Advance the lexer one token and mirror the resulting state into the
457/// parser's outer `LexState` fields. This is the canonical replacement for the
458/// Phase A `// TODO(port): lua_lex::next(ls, state)?;` stubs.
459fn lex_next(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
460    lua_lex::next(state, &mut ls.lex)?;
461    sync_from_lex(ls);
462    Ok(())
463}
464
465/// Populate the lookahead token and mirror lexer state. Replaces the
466/// `// TODO(port): lua_lex::lookahead(ls, state)?` stub.
467fn lex_lookahead(ls: &mut LexState, state: &mut LuaState) -> Result<TokenKind, LuaError> {
468    let kind = lua_lex::lookahead(state, &mut ls.lex)?;
469    sync_from_lex(ls);
470    Ok(kind)
471}
472
473/// Copy lexer-side current/line/token/lookahead values back into the parser's
474/// outer LexState. Used after every `lua_lex::next` / `lua_lex::lookahead`.
475fn sync_from_lex(ls: &mut LexState) {
476    ls.current = ls.lex.current;
477    ls.linenumber = ls.lex.linenumber;
478    ls.lastline = ls.lex.lastline;
479    ls.t = LexToken {
480        token: ls.lex.t.kind,
481        seminfo: local_token_value(&ls.lex.t.value),
482    };
483    ls.lookahead = LexToken {
484        token: ls.lex.lookahead.kind,
485        seminfo: local_token_value(&ls.lex.lookahead.value),
486    };
487    // Mirror lastline into the active FuncState so emit_inst can read it
488    // without needing access to LexState. This matches lua-c's
489    // `savelineinfo(fs, f, fs->ls->lastline)` semantics.
490    if let Some(fs) = ls.fs.as_mut() {
491        fs.last_token_line = ls.lastline;
492    }
493}
494
495// TODO_ARCH(phase-b-reconcile): re-exporting canonical LuaState from lua-vm.
496pub use lua_vm::state::LuaState;
497
498// ── Minimal inline codegen (Phase A bootstrap) ──────────────────────────────
499//
500// The full code generator lives in `lua-code` but operates on its own
501// placeholder `FuncState` / `ExprDesc` types (see `lua-code/src/codegen.rs`
502// "PHASE B PLACEHOLDERS"), so it cannot yet be called from `lua-parse` with
503// the real types defined here. Until that reconciliation lands, the parser
504// emits the small subset of bytecode required to execute simple programs
505// (global lookup + function call + string literal arg) directly, using the
506// shared `Instruction` encoding from `lua-code::opcodes`.
507//
508// These helpers mirror the behaviour of the C codegen functions they replace
509// (`luaK_codeABC`, `luaK_stringK`, `luaK_dischargevars` for the VINDEXUP
510// case, `luaK_exp2nextreg` for the VKSTR case). Phase B should delete this
511// section once lua-code is reachable from lua-parse with unified types.
512
513fn emit_inst(fs: &mut FuncState, line: i32, inst: lua_code::opcodes::Instruction) -> i32 {
514    const MAX_IWTH_ABS: i32 = 128;
515    const LIM_LINE_DIFF: i32 = 0x80;
516    const ABS_LINE_INFO: i8 = -0x80i8;
517    let pc = fs.pc as usize;
518    if fs.f.code.len() <= pc {
519        fs.f.code.resize(pc + 1, lua_types::opcode::Instruction::default());
520    }
521    fs.f.code[pc] = lua_types::opcode::Instruction::new(inst.0);
522    if fs.f.lineinfo.len() <= pc {
523        fs.f.lineinfo.resize(pc + 1, 0i8);
524    }
525    let linedif_raw = line - fs.previousline;
526    let need_abs = linedif_raw.abs() >= LIM_LINE_DIFF || {
527        let over = fs.iwthabs as i32 >= MAX_IWTH_ABS;
528        if !over { fs.iwthabs += 1; }
529        over
530    };
531    if need_abs {
532        fs.f.abslineinfo.push(AbsLineInfo { pc: pc as i32, line });
533        fs.nabslineinfo += 1;
534        fs.f.lineinfo[pc] = ABS_LINE_INFO;
535        fs.iwthabs = 1;
536    } else {
537        fs.f.lineinfo[pc] = linedif_raw as i8;
538    }
539    fs.previousline = line;
540    let result = fs.pc;
541    fs.pc += 1;
542    result
543}
544
545fn add_k_value(fs: &mut FuncState, v: LuaValue) -> i32 {
546    let idx = fs.nk;
547    if (fs.f.k.len() as i32) <= idx {
548        fs.f.k.resize((idx + 1) as usize, LuaValue::Nil);
549    }
550    fs.f.k[idx as usize] = v;
551    fs.nk += 1;
552    idx
553}
554
555fn add_k_string(fs: &mut FuncState, s: GcRef<LuaString>) -> i32 {
556    for (i, k) in fs.f.k.iter().take(fs.nk as usize).enumerate() {
557        if let LuaValue::Str(existing) = k {
558            if GcRef::ptr_eq(existing, &s) {
559                return i as i32;
560            }
561        }
562    }
563    add_k_value(fs, LuaValue::Str(s))
564}
565
566fn bump_maxstack(fs: &mut FuncState, n: u8) {
567    if fs.f.maxstacksize < n {
568        fs.f.maxstacksize = n;
569    }
570}
571
572fn reserve_reg(fs: &mut FuncState) -> Result<u8, LuaError> {
573    if fs.freereg == u8::MAX {
574        return Err(LuaError::syntax(format_args!(
575            "function or expression needs too many registers"
576        )));
577    }
578    let r = fs.freereg;
579    fs.freereg += 1;
580    bump_maxstack(fs, fs.freereg);
581    Ok(r)
582}
583
584fn reserve_regs(fs: &mut FuncState, n: i32) -> Result<(), LuaError> {
585    let newstack = fs.freereg as i32 + n;
586    if newstack >= 255 {
587        return Err(LuaError::syntax(format_args!(
588            "function or expression needs too many registers"
589        )));
590    }
591    fs.freereg = newstack as u8;
592    bump_maxstack(fs, fs.freereg);
593    Ok(())
594}
595
596/// Free `reg` if it sits above the active-local watermark.
597///
598/// Mirrors C's `freereg` from `lcode.c`: registers below `nactvar` belong to
599/// declared locals and must not be popped; temporaries above that watermark
600/// are freed by decrementing `fs.freereg`.
601fn cg_free_reg(fs: &mut FuncState, reg: i32) {
602    if reg >= fs.nactvar as i32 {
603        debug_assert_eq!(reg, fs.freereg as i32 - 1);
604        fs.freereg = fs.freereg.saturating_sub(1);
605    }
606}
607
608/// Free the temporary register held by `e` if any.
609///
610/// Mirrors C's `freeexp` from `lcode.c`: only `VNONRELOC` carries a concrete
611/// register that may need releasing.
612fn cg_free_exp(fs: &mut FuncState, e: &ExprDesc) {
613    if e.k == ExprKind::NonReloc {
614        cg_free_reg(fs, e.u.info);
615    }
616}
617
618/// Free temporary registers held by `e1` and `e2`, releasing the higher
619/// register first so the LIFO invariant on `fs.freereg` holds.
620///
621/// Mirrors C's `freeexps` from `lcode.c`.
622fn cg_free_exps(fs: &mut FuncState, e1: &ExprDesc, e2: &ExprDesc) {
623    let r1 = if e1.k == ExprKind::NonReloc { e1.u.info } else { -1 };
624    let r2 = if e2.k == ExprKind::NonReloc { e2.u.info } else { -1 };
625    if r1 > r2 {
626        cg_free_reg(fs, r1);
627        cg_free_reg(fs, r2);
628    } else {
629        cg_free_reg(fs, r2);
630        cg_free_reg(fs, r1);
631    }
632}
633
634/// Constant-folding `luaK_posfix` for arithmetic binary operators where both
635/// operands are already numeric literals (`KInt` / `KFlt`). Mirrors the
636/// `constfolding` branch in C's `luaK_posfix`: when both operands are
637/// numerals, the result is computed at compile time and stored back into
638/// `e1`. Non-foldable arithmetic / bitwise binops fall through to the
639/// two-register emit path (`OP_ADD` ... `OP_SHR`) plus an `OP_MMBIN`
640/// metamethod-dispatch instruction. `Concat` is delegated to
641/// `cg_emit_concat`; comparisons to `cg_emit_order` / `cg_emit_eq`;
642/// `And` / `Or` short-circuit jumps to `cg_concat`.
643fn cg_posfix_fold(
644    fs: &mut FuncState,
645    op: BinOpr,
646    e1: &mut ExprDesc,
647    e2: &mut ExprDesc,
648    line: i32,
649) -> Result<(), LuaError> {
650    // Lua C records line info at emit time from `ls->lastline`. By the time
651    // postfix code runs, the RHS has already been parsed, so discharging RHS
652    // indexed expressions must use the current token line, not the saved
653    // operator line. The operator line is still used below for the binop/MMBIN
654    // instructions themselves.
655    let rhs_line = fs.last_token_line;
656    cg_discharge_vars(fs, rhs_line, e2)?;
657
658    let promote = |k: ExprKind, u: &ExprPayload| -> Option<f64> {
659        match k {
660            ExprKind::KInt => Some(u.ival as f64),
661            ExprKind::KFlt => Some(u.nval),
662            _ => None,
663        }
664    };
665
666    let foldable = e1.t == NO_JUMP && e1.f == NO_JUMP
667        && e2.t == NO_JUMP && e2.f == NO_JUMP;
668
669    if foldable {
670    if let (ExprKind::KInt, ExprKind::KInt) = (e1.k, e2.k) {
671        let a = e1.u.ival;
672        let b = e2.u.ival;
673        let r: Option<i64> = match op {
674            BinOpr::Add => Some(a.wrapping_add(b)),
675            BinOpr::Sub => Some(a.wrapping_sub(b)),
676            BinOpr::Mul => Some(a.wrapping_mul(b)),
677            BinOpr::Mod if b != 0 => Some(a.rem_euclid(b)),
678            BinOpr::IDiv if b != 0 => Some(a.div_euclid(b)),
679            BinOpr::BAnd => Some(a & b),
680            BinOpr::BOr  => Some(a | b),
681            BinOpr::BXor => Some(a ^ b),
682            _ => None,
683        };
684        if let Some(v) = r {
685            e1.k = ExprKind::KInt;
686            e1.u.ival = v;
687            return Ok(());
688        }
689    }
690    if let (Some(a), Some(b)) = (promote(e1.k, &e1.u), promote(e2.k, &e2.u)) {
691        let r: Option<f64> = match op {
692            BinOpr::Add => Some(a + b),
693            BinOpr::Sub => Some(a - b),
694            BinOpr::Mul => Some(a * b),
695            BinOpr::Div => Some(a / b),
696            BinOpr::Pow => Some(a.powf(b)),
697            _ => None,
698        };
699        if let Some(v) = r {
700            if v.is_finite() {
701                e1.k = ExprKind::KFlt;
702                e1.u.nval = v;
703                return Ok(());
704            }
705        }
706    }
707    }
708
709    if matches!(op, BinOpr::Lt | BinOpr::Le) {
710        return cg_emit_order(fs, op, e1, e2, line);
711    }
712
713    if matches!(op, BinOpr::Gt | BinOpr::Ge) {
714        let swap_op = if matches!(op, BinOpr::Gt) { BinOpr::Lt } else { BinOpr::Le };
715        std::mem::swap(e1, e2);
716        return cg_emit_order(fs, swap_op, e1, e2, line);
717    }
718
719    if matches!(op, BinOpr::Eq | BinOpr::Ne) {
720        return cg_emit_eq(fs, op, e1, e2, line);
721    }
722
723    if matches!(op, BinOpr::And) {
724        debug_assert_eq!(e1.t, NO_JUMP);
725        cg_concat(fs, &mut e2.f, e1.f)?;
726        *e1 = e2.clone();
727        return Ok(());
728    }
729
730    if matches!(op, BinOpr::Or) {
731        debug_assert_eq!(e1.f, NO_JUMP);
732        cg_concat(fs, &mut e2.t, e1.t)?;
733        *e1 = e2.clone();
734        return Ok(());
735    }
736
737    if matches!(op, BinOpr::Concat) {
738        return cg_emit_concat(fs, e1, e2, line);
739    }
740
741    let (opcode, event) = match op {
742        BinOpr::Add  => (lua_code::opcodes::OpCode::Add,  lua_types::tagmethod::TagMethod::Add),
743        BinOpr::Sub  => (lua_code::opcodes::OpCode::Sub,  lua_types::tagmethod::TagMethod::Sub),
744        BinOpr::Mul  => (lua_code::opcodes::OpCode::Mul,  lua_types::tagmethod::TagMethod::Mul),
745        BinOpr::Mod  => (lua_code::opcodes::OpCode::Mod,  lua_types::tagmethod::TagMethod::Mod),
746        BinOpr::Pow  => (lua_code::opcodes::OpCode::Pow,  lua_types::tagmethod::TagMethod::Pow),
747        BinOpr::Div  => (lua_code::opcodes::OpCode::Div,  lua_types::tagmethod::TagMethod::Div),
748        BinOpr::IDiv => (lua_code::opcodes::OpCode::IDiv, lua_types::tagmethod::TagMethod::Idiv),
749        BinOpr::BAnd => (lua_code::opcodes::OpCode::BAnd, lua_types::tagmethod::TagMethod::Band),
750        BinOpr::BOr  => (lua_code::opcodes::OpCode::BOr,  lua_types::tagmethod::TagMethod::Bor),
751        BinOpr::BXor => (lua_code::opcodes::OpCode::BXOr, lua_types::tagmethod::TagMethod::Bxor),
752        BinOpr::Shl  => (lua_code::opcodes::OpCode::Shl,  lua_types::tagmethod::TagMethod::Shl),
753        BinOpr::Shr  => (lua_code::opcodes::OpCode::Shr,  lua_types::tagmethod::TagMethod::Shr),
754        BinOpr::Concat | BinOpr::Eq | BinOpr::Lt | BinOpr::Le | BinOpr::Ne
755        | BinOpr::Gt | BinOpr::Ge | BinOpr::And | BinOpr::Or | BinOpr::NoBinOpr => {
756            unreachable!("cg_posfix_fold reached opcode match with non-arith op {:?}", op)
757        }
758    };
759
760    cg_discharge_vars(fs, line, e1)?;
761    cg_discharge_vars(fs, line, e2)?;
762    let v2 = cg_exp_to_any_reg(fs, line, e2)?;
763    let v1 = cg_exp_to_any_reg(fs, line, e1)?;
764
765    let inst = lua_code::opcodes::Instruction::abck(opcode, 0, v1 as u32, v2 as u32, 0);
766    let pc = emit_inst(fs, line, inst);
767    cg_free_exps(fs, e1, e2);
768    e1.u.info = pc;
769    e1.k = ExprKind::Reloc;
770
771    let mm_inst = lua_code::opcodes::Instruction::abck(
772        lua_code::opcodes::OpCode::MmBin,
773        v1 as u32,
774        v2 as u32,
775        event as u32,
776        0,
777    );
778    emit_inst(fs, line, mm_inst);
779    Ok(())
780}
781
782/// Mirrors C's `codeorder` from `lcode.c` for relational binops (`<`, `<=`,
783/// `>`, `>=`). Emits a comparison opcode (with `k = 1`) followed by an
784/// `OP_JMP` with offset `NO_JUMP`; the resulting `VJMP` expression carries
785/// the jump's pc in `e1.u.info` so the surrounding control-flow logic can
786/// patch it. When one operand is a small-integer literal that fits the
787/// signed-C field, the immediate forms (`OP_LTI` / `OP_GTI`) are used;
788/// otherwise both operands are discharged to registers and the register
789/// form (`OP_LT`) is emitted.
790fn cg_emit_order(
791    fs: &mut FuncState,
792    op: BinOpr,
793    e1: &mut ExprDesc,
794    e2: &mut ExprDesc,
795    line: i32,
796) -> Result<(), LuaError> {
797    debug_assert!(matches!(op, BinOpr::Lt | BinOpr::Le));
798    let is_le = matches!(op, BinOpr::Le);
799    let (op_imm_e2, op_imm_e1, op_reg) = if is_le {
800        (
801            lua_code::opcodes::OpCode::LeI,
802            lua_code::opcodes::OpCode::GeI,
803            lua_code::opcodes::OpCode::Le,
804        )
805    } else {
806        (
807            lua_code::opcodes::OpCode::LtI,
808            lua_code::opcodes::OpCode::GtI,
809            lua_code::opcodes::OpCode::Lt,
810        )
811    };
812    let (r1, r2, cmp_op) = if let Some(im) = cg_sc_int(e2) {
813        let r1 = cg_exp_to_any_reg(fs, line, e1)?;
814        (r1, im, op_imm_e2)
815    } else if let Some(im) = cg_sc_int(e1) {
816        let r1 = cg_exp_to_any_reg(fs, line, e2)?;
817        (r1, im, op_imm_e1)
818    } else {
819        let r2 = cg_exp_to_any_reg(fs, line, e2)?;
820        let r1 = cg_exp_to_any_reg(fs, line, e1)?;
821        (r1, r2, op_reg)
822    };
823    cg_free_exps(fs, e1, e2);
824    let cmp = lua_code::opcodes::Instruction::abck(
825        cmp_op,
826        r1 as u32,
827        r2 as u32,
828        0,
829        1,
830    );
831    emit_inst(fs, line, cmp);
832    let jmp_arg = (NO_JUMP + lua_code::opcodes::OFFSET_S_J) as u32;
833    let jmp = lua_code::opcodes::Instruction::sj(
834        lua_code::opcodes::OpCode::Jmp,
835        jmp_arg,
836        0,
837    );
838    let jmp_pc = emit_inst(fs, line, jmp);
839    e1.u.info = jmp_pc;
840    e1.k = ExprKind::Jmp;
841    Ok(())
842}
843
844/// Mirrors C's `codeeq` from `lcode.c` for the equality binops (`==`, `~=`).
845/// Emits an `OP_EQ` (or its `OP_EQI` immediate form when the right operand
846/// is a small-integer literal) followed by an `OP_JMP` whose pc is stored
847/// in `e1.u.info`; `e1.k` becomes `VJMP`. The `k` bit selects between `==`
848/// (k=1) and `~=` (k=0) so the same opcode pair handles both operators.
849///
850/// The Phase-A bootstrap deliberately omits the constant-table (`OP_EQK`)
851/// fast path used by C; both operands fall back to register form when no
852/// signed-C immediate fits. Correctness is unchanged.
853fn cg_emit_eq(
854    fs: &mut FuncState,
855    op: BinOpr,
856    e1: &mut ExprDesc,
857    e2: &mut ExprDesc,
858    line: i32,
859) -> Result<(), LuaError> {
860    debug_assert!(matches!(op, BinOpr::Eq | BinOpr::Ne));
861    if e1.k != ExprKind::NonReloc {
862        std::mem::swap(e1, e2);
863    }
864    let r1 = cg_exp_to_any_reg(fs, line, e1)?;
865    let (r2, cmp_op) = if let Some(im) = cg_sc_int(e2) {
866        (im, lua_code::opcodes::OpCode::EqI)
867    } else {
868        let r = cg_exp_to_any_reg(fs, line, e2)?;
869        (r, lua_code::opcodes::OpCode::Eq)
870    };
871    cg_free_exps(fs, e1, e2);
872    let k_bit = if matches!(op, BinOpr::Eq) { 1 } else { 0 };
873    let cmp = lua_code::opcodes::Instruction::abck(
874        cmp_op,
875        r1 as u32,
876        r2 as u32,
877        0,
878        k_bit,
879    );
880    emit_inst(fs, line, cmp);
881    let jmp_pc = cg_jump(fs, line);
882    e1.u.info = jmp_pc;
883    e1.k = ExprKind::Jmp;
884    Ok(())
885}
886
887/// Mirrors C's `previousinstruction` from `lcode.c`: returns the index of the
888/// last emitted instruction, but only when `pc` is past `lasttarget` (i.e. the
889/// previous instruction is reachable without crossing a jump label). Used by
890/// peephole merges such as the `OP_CONCAT` chain fold.
891fn previous_instruction_idx(fs: &FuncState) -> Option<usize> {
892    if fs.pc > fs.lasttarget {
893        Some((fs.pc - 1) as usize)
894    } else {
895        None
896    }
897}
898
899/// Mirrors C's `codeconcat` from `lcode.c`. The left operand `e1` has
900/// already been placed on the stack by `cg_infix`'s `OPR_CONCAT` arm
901/// (`luaK_exp2nextreg`); here we only push `e2` onto the next register and
902/// emit (or fold into) the `OP_CONCAT`. When the previous instruction is
903/// itself an `OP_CONCAT` whose `A` register is exactly `e1.u.info + 1`,
904/// the chain is merged by widening that instruction's `B` field;
905/// otherwise a fresh `OP_CONCAT A=e1.u.info, B=2` is emitted. In both
906/// branches the temporary register holding `e2` is freed.
907fn cg_emit_concat(
908    fs: &mut FuncState,
909    e1: &mut ExprDesc,
910    e2: &mut ExprDesc,
911    line: i32,
912) -> Result<(), LuaError> {
913    cg_exp_to_next_reg(fs, line, e2)?;
914
915    if let Some(prev_idx) = previous_instruction_idx(fs) {
916        let prev = lua_code::opcodes::Instruction(fs.f.code[prev_idx].0);
917        if prev.opcode() == Some(lua_code::opcodes::OpCode::Concat) {
918            let n = prev.arg_b();
919            debug_assert_eq!(e1.u.info + 1, prev.arg_a() as i32);
920            cg_free_exp(fs, e2);
921            let mut updated = prev;
922            updated.set_arg_a(e1.u.info as u32);
923            updated.set_arg_b(n + 1);
924            fs.f.code[prev_idx] = lua_types::opcode::Instruction::new(updated.0);
925            return Ok(());
926        }
927    }
928
929    let inst = lua_code::opcodes::Instruction::abck(
930        lua_code::opcodes::OpCode::Concat,
931        e1.u.info as u32,
932        2,
933        0,
934        0,
935    );
936    emit_inst(fs, line, inst);
937    cg_free_exp(fs, e2);
938    Ok(())
939}
940
941/// Mirrors C's `luaK_prefix` from `lcode.c`. Discharges `e`, then for
942/// `Minus` / `BNot` / `Len` emits the unary opcode via `codeunexpval`
943/// (place operand in a register, emit `OP_UNM` / `OP_BNOT` / `OP_LEN`
944/// with `A` left as 0 so the result is relocatable). Constant folding
945/// for `Minus` / `BNot` is skipped here; the runtime falls back to the
946/// register form, matching C semantics (just less efficient). `Not`
947/// is routed through `cg_codenot`, which performs literal folding,
948/// JMP-condition flipping, or emits `OP_NOT` for register operands.
949fn cg_prefix(
950    fs: &mut FuncState,
951    op: UnOpr,
952    e: &mut ExprDesc,
953    line: i32,
954) -> Result<(), LuaError> {
955    cg_discharge_vars(fs, line, e)?;
956    let opcode = match op {
957        UnOpr::Minus => lua_code::opcodes::OpCode::Unm,
958        UnOpr::BNot  => lua_code::opcodes::OpCode::BNot,
959        UnOpr::Len   => lua_code::opcodes::OpCode::Len,
960        UnOpr::Not   => return cg_codenot(fs, line, e),
961        UnOpr::NoUnOpr => return Ok(()),
962    };
963    let r = cg_exp_to_any_reg(fs, line, e)?;
964    cg_free_exp(fs, e);
965    let inst = lua_code::opcodes::Instruction::abck(opcode, 0, r as u32, 0, 0);
966    let pc = emit_inst(fs, line, inst);
967    e.u.info = pc;
968    e.k = ExprKind::Reloc;
969    Ok(())
970}
971
972/// Return the pc of the test instruction that controls the jump at `pc`,
973/// or `pc` itself if the jump is unconditional.
974///
975/// Mirrors C's `getjumpcontrol` from `lcode.c`: when `pc >= 1` and the
976/// preceding opcode has the T-mode bit set (i.e. it's a test that is always
977/// paired with a following `OP_JMP`), the control lives at `pc - 1`.
978fn cg_get_jump_control(fs: &FuncState, pc: i32) -> i32 {
979    if pc >= 1 {
980        let prev = cg_inst_at(fs, pc - 1);
981        if let Some(op) = prev.opcode() {
982            if lua_code::opcodes::test_t_mode(op) {
983                return pc - 1;
984            }
985        }
986    }
987    pc
988}
989
990/// Patch the destination register of a `TESTSET` that controls the jump at
991/// `node`. If the control isn't a `TESTSET`, returns `false`. With `reg ==
992/// NO_REG` (or when `reg` already equals B), the instruction is rewritten to
993/// a plain `OP_TEST` (preserving the original `k` bit) — the test no longer
994/// produces a value.
995///
996/// Mirrors C's `patchtestreg` from `lcode.c`.
997fn cg_patch_test_reg(fs: &mut FuncState, node: i32, reg: u32) -> bool {
998    let ctrl_pc = cg_get_jump_control(fs, node);
999    let mut inst = cg_inst_at(fs, ctrl_pc);
1000    if inst.opcode() != Some(lua_code::opcodes::OpCode::TestSet) {
1001        return false;
1002    }
1003    let b = inst.arg_b();
1004    let k = inst.arg_k();
1005    if reg != lua_code::opcodes::NO_REG && reg != b {
1006        inst.set_arg_a(reg);
1007        cg_set_inst_at(fs, ctrl_pc, inst);
1008    } else {
1009        let test = lua_code::opcodes::Instruction::abck(
1010            lua_code::opcodes::OpCode::Test,
1011            b,
1012            0,
1013            0,
1014            k,
1015        );
1016        cg_set_inst_at(fs, ctrl_pc, test);
1017    }
1018    true
1019}
1020
1021/// Walk the jump-list rooted at `list` and strip every `TESTSET` of its
1022/// destination register, leaving plain `OP_TEST`s behind. Used after
1023/// `not <expr>` swaps `e.t` / `e.f`: any pending value-producing tests in
1024/// the new lists would write the unnegated value, which is wrong.
1025///
1026/// Mirrors C's `removevalues` from `lcode.c`.
1027fn cg_remove_values(fs: &mut FuncState, list: i32) {
1028    let mut list = list;
1029    while list != NO_JUMP {
1030        let next = cg_get_jump(fs, list);
1031        cg_patch_test_reg(fs, list, lua_code::opcodes::NO_REG);
1032        list = next;
1033    }
1034}
1035
1036/// Mirrors C's `codenot` from `lcode.c`. Handles constant folding for `not`
1037/// (nil/false → true; any other constant → false), flips the condition bit
1038/// of a jump-result expression, or emits `OP_NOT` for in-register operands.
1039/// After negation, `e.t` and `e.f` are swapped (the old true-exit list now
1040/// fires when the negated value is false, and vice versa) and any
1041/// value-producing tests in the new lists are downgraded to plain tests via
1042/// `cg_remove_values`.
1043fn cg_codenot(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1044    match e.k {
1045        ExprKind::Nil | ExprKind::False => {
1046            e.k = ExprKind::True;
1047        }
1048        ExprKind::K
1049        | ExprKind::KFlt
1050        | ExprKind::KInt
1051        | ExprKind::KStr
1052        | ExprKind::True => {
1053            e.k = ExprKind::False;
1054        }
1055        ExprKind::Jmp => {
1056            cg_negate_condition(fs, e);
1057        }
1058        ExprKind::Reloc | ExprKind::NonReloc => {
1059            let reg = cg_exp_to_any_reg(fs, line, e)?;
1060            cg_free_exp(fs, e);
1061            let inst = lua_code::opcodes::Instruction::abck(
1062                lua_code::opcodes::OpCode::Not,
1063                0,
1064                reg as u32,
1065                0,
1066                0,
1067            );
1068            let pc = emit_inst(fs, line, inst);
1069            e.u.info = pc;
1070            e.k = ExprKind::Reloc;
1071        }
1072        _ => debug_assert!(false, "cg_codenot: unexpected ExprKind {:?}", e.k),
1073    }
1074    std::mem::swap(&mut e.f, &mut e.t);
1075    cg_remove_values(fs, e.f);
1076    cg_remove_values(fs, e.t);
1077    Ok(())
1078}
1079
1080/// Emit OP_JMP with NO_JUMP offset; return its pc.
1081///
1082/// Mirrors C's `luaK_jump`.
1083fn cg_jump(fs: &mut FuncState, line: i32) -> i32 {
1084    let jmp_arg = (NO_JUMP + lua_code::opcodes::OFFSET_S_J) as u32;
1085    let jmp = lua_code::opcodes::Instruction::sj(
1086        lua_code::opcodes::OpCode::Jmp,
1087        jmp_arg,
1088        0,
1089    );
1090    emit_inst(fs, line, jmp)
1091}
1092
1093/// Read an instruction word from `fs.f.code` wrapped in the methodful
1094/// `lua_code::opcodes::Instruction` so accessor helpers are available.
1095fn cg_inst_at(fs: &FuncState, pc: i32) -> lua_code::opcodes::Instruction {
1096    lua_code::opcodes::Instruction(fs.f.code[pc as usize].0)
1097}
1098
1099/// Store an instruction word into `fs.f.code` from a methodful
1100/// `lua_code::opcodes::Instruction`.
1101fn cg_set_inst_at(fs: &mut FuncState, pc: i32, inst: lua_code::opcodes::Instruction) {
1102    fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(inst.0);
1103}
1104
1105/// Return the absolute pc that the jump at `pc` targets, or `NO_JUMP` if the
1106/// jump's offset field is still the sentinel.
1107///
1108/// Mirrors C's `getjump` from `lcode.c`.
1109fn cg_get_jump(fs: &FuncState, pc: i32) -> i32 {
1110    let offset = cg_inst_at(fs, pc).arg_s_j();
1111    if offset == NO_JUMP { NO_JUMP } else { (pc + 1) + offset }
1112}
1113
1114/// Patch the jump at `pc` to land at absolute `dest`.
1115///
1116/// Mirrors C's `fixjump` from `lcode.c`.
1117fn cg_fix_jump(fs: &mut FuncState, pc: i32, dest: i32) -> Result<(), LuaError> {
1118    debug_assert!(dest != NO_JUMP);
1119    let offset = dest - (pc + 1);
1120    let max = lua_code::opcodes::MAXARG_S_J as i32 - lua_code::opcodes::OFFSET_S_J;
1121    let min = -lua_code::opcodes::OFFSET_S_J;
1122    if offset < min || offset > max {
1123        return Err(LuaError::syntax(format_args!("control structure too long")));
1124    }
1125    let mut inst = cg_inst_at(fs, pc);
1126    inst.set_arg_s_j(offset);
1127    cg_set_inst_at(fs, pc, inst);
1128    Ok(())
1129}
1130
1131/// Record `fs.pc` as a jump label and return it.
1132///
1133/// Mirrors C's `luaK_getlabel` from `lcode.c`.
1134fn cg_get_label(fs: &mut FuncState) -> i32 {
1135    fs.lasttarget = fs.pc;
1136    fs.pc
1137}
1138
1139/// Concatenate jump-list `l2` onto the tail of `*l1`.
1140///
1141/// Mirrors C's `luaK_concat` from `lcode.c`.
1142fn cg_concat(fs: &mut FuncState, l1: &mut i32, l2: i32) -> Result<(), LuaError> {
1143    if l2 == NO_JUMP { return Ok(()); }
1144    if *l1 == NO_JUMP { *l1 = l2; return Ok(()); }
1145    let mut list = *l1;
1146    loop {
1147        let next = cg_get_jump(fs, list);
1148        if next == NO_JUMP { break; }
1149        list = next;
1150    }
1151    cg_fix_jump(fs, list, l2)
1152}
1153
1154/// Patch every jump in the singly-linked list rooted at `list` to land at
1155/// absolute pc `target`.
1156///
1157/// Mirrors C's `luaK_patchlist`, which delegates to `patchlistaux(fs, list,
1158/// target, NO_REG, target)`: every `TESTSET` controller in the list gets
1159/// rewritten to a plain `OP_TEST` (the value-producing destination register
1160/// is no longer wanted at a fall-through target), and every jump is fixed to
1161/// `target`.
1162fn cg_patch_list(fs: &mut FuncState, list: i32, target: i32) -> Result<(), LuaError> {
1163    cg_patch_list_aux(fs, list, target, lua_code::opcodes::NO_REG, target)
1164}
1165
1166/// Patch every jump in `list` to land at the current `fs.pc`.
1167///
1168/// Mirrors C's `luaK_patchtohere` from `lcode.c`.
1169fn cg_patch_to_here(fs: &mut FuncState, list: i32) -> Result<(), LuaError> {
1170    let target = cg_get_label(fs);
1171    cg_patch_list(fs, list, target)
1172}
1173
1174/// Flip the `k` (condition) bit of the test instruction that immediately
1175/// precedes `e`'s JMP. After this, the jump fires on the opposite truth
1176/// value of the original comparison.
1177///
1178/// Mirrors C's `negatecondition` from `lcode.c`.
1179fn cg_negate_condition(fs: &mut FuncState, e: &ExprDesc) {
1180    let pc = e.u.info - 1;
1181    let mut inst = cg_inst_at(fs, pc);
1182    let k = inst.arg_k();
1183    inst.set_arg_k(k ^ 1);
1184    cg_set_inst_at(fs, pc, inst);
1185}
1186
1187/// Arrange for control to fall through when `e` is true and to jump (via the
1188/// patch list rooted at `e.f`) when `e` is false. After this call `e.t` has
1189/// been patched to the current pc and `e.f` holds the false-exit list.
1190///
1191/// Mirrors C's `luaK_goiftrue` from `lcode.c`. `VJMP` (comparison results)
1192/// negate the condition so the jump fires on false; literal-true forms emit
1193/// no jump; any other kind is forced into a register and tested with
1194/// `OP_TESTSET` via `cg_jump_on_cond`.
1195fn cg_go_if_true(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1196    cg_discharge_vars(fs, line, e)?;
1197    let pc: i32 = match e.k {
1198        ExprKind::Jmp => {
1199            cg_negate_condition(fs, e);
1200            e.u.info
1201        }
1202        ExprKind::K | ExprKind::KFlt | ExprKind::KInt | ExprKind::KStr | ExprKind::True => {
1203            NO_JUMP
1204        }
1205        _ => cg_jump_on_cond(fs, line, e, 0)?,
1206    };
1207    cg_concat(fs, &mut e.f, pc)?;
1208    cg_patch_to_here(fs, e.t)?;
1209    e.t = NO_JUMP;
1210    Ok(())
1211}
1212
1213/// Mirror of `cg_go_if_true` for false short-circuit (`or` operator and
1214/// `while not <cond>` shaped control flow). Falls through when `e` is false
1215/// and jumps when true. After this call `e.f` has been patched to the
1216/// current pc and `e.t` holds the true-exit list.
1217///
1218/// Mirrors C's `luaK_goiffalse` from `lcode.c`.
1219fn cg_go_if_false(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1220    cg_discharge_vars(fs, line, e)?;
1221    let pc: i32 = match e.k {
1222        ExprKind::Jmp => e.u.info,
1223        ExprKind::Nil | ExprKind::False => NO_JUMP,
1224        _ => cg_jump_on_cond(fs, line, e, 1)?,
1225    };
1226    cg_concat(fs, &mut e.t, pc)?;
1227    cg_patch_to_here(fs, e.f)?;
1228    e.f = NO_JUMP;
1229    Ok(())
1230}
1231
1232/// Emit `OP_TESTSET R[NO_REG], R[e.info], cond` followed by an `OP_JMP` so
1233/// control transfers to the jump's patch list when `e`'s truth value equals
1234/// `cond`. Returns the pc of the emitted jump so the caller can append it
1235/// to the appropriate exit list.
1236///
1237/// Mirrors C's `jumponcond` from `lcode.c`. The `OP_NOT` peephole that C
1238/// applies for `VRELOC` operands is intentionally skipped for the Phase-A
1239/// bootstrap; correctness is unaffected and the optimisation can land with
1240/// the codegen reconciliation pass.
1241fn cg_jump_on_cond(
1242    fs: &mut FuncState,
1243    line: i32,
1244    e: &mut ExprDesc,
1245    cond: u8,
1246) -> Result<i32, LuaError> {
1247    let reg = cg_exp_to_any_reg(fs, line, e)?;
1248    cg_free_exp(fs, e);
1249    let test = lua_code::opcodes::Instruction::abck(
1250        lua_code::opcodes::OpCode::TestSet,
1251        lua_code::opcodes::NO_REG,
1252        reg as u32,
1253        0,
1254        cond as u32,
1255    );
1256    emit_inst(fs, line, test);
1257    Ok(cg_jump(fs, line))
1258}
1259
1260/// First half of `luaK_posfix`: pre-process the left operand `v` of a binary
1261/// operator before the right operand is parsed. Mirrors C's `luaK_infix`
1262/// from `lcode.c`. The codegen reconciliation has not yet routed parser
1263/// calls through `lua_code::infix`, so this lives in the parser file
1264/// alongside the other `cg_*` helpers.
1265///
1266/// For `And`/`Or` the operand is converted into a short-circuit form (jump
1267/// list closed via `cg_go_if_true` / `cg_go_if_false`). For `Concat` it is
1268/// pushed onto the next register. Other arithmetic, bitwise, and comparison
1269/// operators rely on `cg_posfix_fold` to discharge their operands after the
1270/// right-hand side is known, so `cg_infix` only calls `cg_discharge_vars`
1271/// for them.
1272fn cg_infix(
1273    fs: &mut FuncState,
1274    op: BinOpr,
1275    v: &mut ExprDesc,
1276    line: i32,
1277) -> Result<(), LuaError> {
1278    match op {
1279        BinOpr::And => cg_go_if_true(fs, line, v),
1280        BinOpr::Or => cg_go_if_false(fs, line, v),
1281        BinOpr::Concat => cg_exp_to_next_reg(fs, line, v),
1282        BinOpr::Add | BinOpr::Sub | BinOpr::Mul | BinOpr::Div | BinOpr::IDiv
1283        | BinOpr::Mod | BinOpr::Pow
1284        | BinOpr::BAnd | BinOpr::BOr | BinOpr::BXor
1285        | BinOpr::Shl | BinOpr::Shr
1286        | BinOpr::Eq | BinOpr::Ne
1287        | BinOpr::Lt | BinOpr::Le | BinOpr::Gt | BinOpr::Ge => {
1288            if matches!(v.k, ExprKind::KInt | ExprKind::KFlt)
1289                && v.t == NO_JUMP && v.f == NO_JUMP
1290            {
1291                cg_discharge_vars(fs, line, v)
1292            } else {
1293                cg_exp_to_any_reg(fs, line, v).map(|_| ())
1294            }
1295        }
1296        _ => cg_discharge_vars(fs, line, v),
1297    }
1298}
1299
1300/// Mirrors C's `isSCint` from `lcode.c` (a restriction of `isSCnumber` to
1301/// the integer case): returns `Some(int2sC(ival))` if `e` is a `VKINT`
1302/// literal whose value fits the signed-C 8-bit operand field, else `None`.
1303/// The returned byte is already pre-encoded with the `OFFSET_sC` bias so
1304/// the caller can drop it straight into an `sC` argument slot.
1305fn cg_sc_int(e: &ExprDesc) -> Option<u8> {
1306    if !matches!(e.k, ExprKind::KInt) {
1307        return None;
1308    }
1309    if e.t != NO_JUMP || e.f != NO_JUMP {
1310        return None;
1311    }
1312    let biased = (e.u.ival as u64).wrapping_add(lua_code::opcodes::OFFSET_S_C as u64);
1313    if biased <= lua_code::opcodes::MAXARG_C as u64 {
1314        Some(biased as u8)
1315    } else {
1316        None
1317    }
1318}
1319
1320/// Minimal `luaK_exp2anyreg`: ensure `e` ends up in *some* register. If `e`
1321/// is already `VNONRELOC` and its register is at or above `nactvar`, keep it
1322/// there; otherwise discharge to the next free register.
1323fn cg_exp_to_any_reg(
1324    fs: &mut FuncState,
1325    line: i32,
1326    e: &mut ExprDesc,
1327) -> Result<u8, LuaError> {
1328    cg_discharge_vars(fs, line, e)?;
1329    if e.k == ExprKind::NonReloc {
1330        if e.t == NO_JUMP && e.f == NO_JUMP {
1331            return Ok(e.u.info as u8);
1332        }
1333        if e.u.info >= fs.nactvar as i32 {
1334            cg_exp_to_reg(fs, line, e, e.u.info as u8)?;
1335            return Ok(e.u.info as u8);
1336        }
1337    }
1338    cg_exp_to_next_reg(fs, line, e)?;
1339    Ok(e.u.info as u8)
1340}
1341
1342/// Minimal `luaK_dischargevars` covering the cases the parser bootstrap can
1343/// produce: `VLOCAL`, `VUpVal`, `VIndexUp`, `VKStr`. Other variants are left
1344/// untouched. Returns Ok(()) on success.
1345fn cg_discharge_vars(
1346    fs: &mut FuncState,
1347    line: i32,
1348    e: &mut ExprDesc,
1349) -> Result<(), LuaError> {
1350    match e.k {
1351        ExprKind::Local => {
1352            e.u.info = e.u.var_ridx as i32;
1353            e.k = ExprKind::NonReloc;
1354        }
1355        ExprKind::UpVal => {
1356            let inst = lua_code::opcodes::Instruction::abck(
1357                lua_code::opcodes::OpCode::GetUpVal,
1358                0,
1359                e.u.info as u32,
1360                0,
1361                0,
1362            );
1363            let pc = emit_inst(fs, line, inst);
1364            e.u.info = pc;
1365            e.k = ExprKind::Reloc;
1366        }
1367        ExprKind::IndexUp => {
1368            let inst = lua_code::opcodes::Instruction::abck(
1369                lua_code::opcodes::OpCode::GetTabUp,
1370                0,
1371                e.u.ind_t as u32,
1372                e.u.ind_idx as u32,
1373                0,
1374            );
1375            let pc = emit_inst(fs, line, inst);
1376            e.u.info = pc;
1377            e.k = ExprKind::Reloc;
1378        }
1379        ExprKind::IndexI => {
1380            cg_free_reg_if_temp(fs, e.u.ind_t as i32);
1381            let inst = lua_code::opcodes::Instruction::abck(
1382                lua_code::opcodes::OpCode::GetI,
1383                0,
1384                e.u.ind_t as u32,
1385                e.u.ind_idx as u32,
1386                0,
1387            );
1388            let pc = emit_inst(fs, line, inst);
1389            e.u.info = pc;
1390            e.k = ExprKind::Reloc;
1391        }
1392        ExprKind::IndexStr => {
1393            cg_free_reg_if_temp(fs, e.u.ind_t as i32);
1394            let inst = lua_code::opcodes::Instruction::abck(
1395                lua_code::opcodes::OpCode::GetField,
1396                0,
1397                e.u.ind_t as u32,
1398                e.u.ind_idx as u32,
1399                0,
1400            );
1401            let pc = emit_inst(fs, line, inst);
1402            e.u.info = pc;
1403            e.k = ExprKind::Reloc;
1404        }
1405        ExprKind::Indexed => {
1406            let t_reg = e.u.ind_t as i32;
1407            let idx_reg = e.u.ind_idx as i32;
1408            if idx_reg > t_reg {
1409                cg_free_reg_if_temp(fs, idx_reg);
1410                cg_free_reg_if_temp(fs, t_reg);
1411            } else {
1412                cg_free_reg_if_temp(fs, t_reg);
1413                cg_free_reg_if_temp(fs, idx_reg);
1414            }
1415            let inst = lua_code::opcodes::Instruction::abck(
1416                lua_code::opcodes::OpCode::GetTable,
1417                0,
1418                e.u.ind_t as u32,
1419                e.u.ind_idx as u32,
1420                0,
1421            );
1422            let pc = emit_inst(fs, line, inst);
1423            e.u.info = pc;
1424            e.k = ExprKind::Reloc;
1425        }
1426        ExprKind::VarArg | ExprKind::Call => {
1427            cg_set_one_ret(fs, e);
1428        }
1429        _ => {}
1430    }
1431    Ok(())
1432}
1433
1434/// result. For a Call this leaves the already-emitted instruction alone (it
1435/// was emitted with `ARG_C = 2`, i.e. exactly one result) and reclassifies
1436/// `e` as `NonReloc` pointing at the result register (the Call's `ARG_A`).
1437/// For a VarArg this patches `ARG_C = 2` and leaves `e` as `Reloc` so the
1438/// caller can place the single result into a destination register.
1439fn cg_set_one_ret(fs: &mut FuncState, e: &mut ExprDesc) {
1440    if e.k == ExprKind::Call {
1441        let pc_idx = e.u.info as usize;
1442        let lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
1443        debug_assert_eq!(lc.arg_c(), 2);
1444        e.u.info = lc.arg_a() as i32;
1445        e.k = ExprKind::NonReloc;
1446    } else if e.k == ExprKind::VarArg {
1447        let pc_idx = e.u.info as usize;
1448        let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
1449        lc.set_arg_c(2);
1450        fs.f.code[pc_idx] = lua_types::opcode::Instruction::new(lc.0);
1451        e.k = ExprKind::Reloc;
1452    }
1453}
1454
1455/// by `var`. Handles VLocal (move into register), VUpVal (OP_SETUPVAL),
1456/// VIndexUp (OP_SETTABUP), VIndexI/IndexStr/Indexed (OP_SETI/SETFIELD/SETTABLE).
1457fn cg_storevar(
1458    fs: &mut FuncState,
1459    line: i32,
1460    var: &ExprDesc,
1461    ex: &mut ExprDesc,
1462) -> Result<(), LuaError> {
1463    match var.k {
1464        ExprKind::Local => {
1465            cg_free_exp(fs, ex);
1466            cg_exp_to_reg(fs, line, ex, var.u.var_ridx as u8)?;
1467            return Ok(());
1468        }
1469        ExprKind::UpVal => {
1470            let e_reg = cg_exp_to_any_reg(fs, line, ex)?;
1471            let inst = lua_code::opcodes::Instruction::abck(
1472                lua_code::opcodes::OpCode::SetUpVal,
1473                e_reg as u32,
1474                var.u.info as u32,
1475                0,
1476                0,
1477            );
1478            emit_inst(fs, line, inst);
1479        }
1480        ExprKind::IndexUp => {
1481            cg_store_abrk(fs, line, lua_code::opcodes::OpCode::SetTabUp,
1482                var.u.ind_t as u32, var.u.ind_idx as u32, ex)?;
1483        }
1484        ExprKind::IndexI => {
1485            cg_store_abrk(fs, line, lua_code::opcodes::OpCode::SetI,
1486                var.u.ind_t as u32, var.u.ind_idx as u32, ex)?;
1487        }
1488        ExprKind::IndexStr => {
1489            cg_store_abrk(fs, line, lua_code::opcodes::OpCode::SetField,
1490                var.u.ind_t as u32, var.u.ind_idx as u32, ex)?;
1491        }
1492        ExprKind::Indexed => {
1493            cg_store_abrk(fs, line, lua_code::opcodes::OpCode::SetTable,
1494                var.u.ind_t as u32, var.u.ind_idx as u32, ex)?;
1495        }
1496        _ => {
1497            return Err(LuaError::syntax(format_args!(
1498                "internal: cg_storevar: invalid var kind {:?}", var.k
1499            )));
1500        }
1501    }
1502    cg_free_exp(fs, ex);
1503    Ok(())
1504}
1505
1506/// Helper for cg_storevar: emit an ABRK-form store. Mirrors C's `codeABRK`
1507/// for the SetTabUp/SetI/SetField/SetTable family. When `ex` is a constant
1508/// the K bit is set; otherwise the value is forced into a register.
1509fn cg_store_abrk(
1510    fs: &mut FuncState,
1511    line: i32,
1512    op: lua_code::opcodes::OpCode,
1513    a: u32,
1514    b: u32,
1515    ex: &mut ExprDesc,
1516) -> Result<(), LuaError> {
1517    let c_reg = cg_exp_to_any_reg(fs, line, ex)?;
1518    let inst = lua_code::opcodes::Instruction::abck(op, a, b, c_reg as u32, 0);
1519    emit_inst(fs, line, inst);
1520    Ok(())
1521}
1522
1523/// Mirrors C's `discharge2reg` from `lcode.c`: places the value described by
1524/// `e` into `reg`. For `Jmp` this is a no-op (the caller — `cg_exp_to_reg` —
1525/// is responsible for stitching the jump into `e.t` and emitting the
1526/// LoadTrue / LFalseSkip pair if a concrete value is needed).
1527fn cg_discharge_to_reg(
1528    fs: &mut FuncState,
1529    line: i32,
1530    e: &mut ExprDesc,
1531    reg: u8,
1532) -> Result<(), LuaError> {
1533    cg_discharge_vars(fs, line, e)?;
1534    match e.k {
1535        ExprKind::Jmp => {
1536            return Ok(());
1537        }
1538        ExprKind::NonReloc => {
1539            if e.u.info as u8 != reg {
1540                let inst = lua_code::opcodes::Instruction::abck(
1541                    lua_code::opcodes::OpCode::Move,
1542                    reg as u32,
1543                    e.u.info as u32,
1544                    0, 0,
1545                );
1546                emit_inst(fs, line, inst);
1547            }
1548        }
1549        ExprKind::Reloc => {
1550            let pc = e.u.info as usize;
1551            let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc].0);
1552            lc.set_arg_a(reg as u32);
1553            fs.f.code[pc] = lua_types::opcode::Instruction::new(lc.0);
1554        }
1555        ExprKind::Nil => {
1556            let inst = lua_code::opcodes::Instruction::abck(
1557                lua_code::opcodes::OpCode::LoadNil, reg as u32, 0, 0, 0,
1558            );
1559            emit_inst(fs, line, inst);
1560        }
1561        ExprKind::True => {
1562            let inst = lua_code::opcodes::Instruction::abck(
1563                lua_code::opcodes::OpCode::LoadTrue, reg as u32, 0, 0, 0,
1564            );
1565            emit_inst(fs, line, inst);
1566        }
1567        ExprKind::False => {
1568            let inst = lua_code::opcodes::Instruction::abck(
1569                lua_code::opcodes::OpCode::LoadFalse, reg as u32, 0, 0, 0,
1570            );
1571            emit_inst(fs, line, inst);
1572        }
1573        ExprKind::KInt => {
1574            let i = e.u.ival;
1575            let max = lua_code::opcodes::MAXARG_BX as i64 - lua_code::opcodes::OFFSET_S_BX as i64;
1576            let min = -(lua_code::opcodes::OFFSET_S_BX as i64);
1577            if i >= min && i <= max {
1578                let bx = (i as i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
1579                let inst = lua_code::opcodes::Instruction::abx(
1580                    lua_code::opcodes::OpCode::LoadI, reg as u32, bx,
1581                );
1582                emit_inst(fs, line, inst);
1583            } else {
1584                let k_idx = add_k_value(fs, LuaValue::Int(i));
1585                let inst = lua_code::opcodes::Instruction::abx(
1586                    lua_code::opcodes::OpCode::LoadK, reg as u32, k_idx as u32,
1587                );
1588                emit_inst(fs, line, inst);
1589            }
1590        }
1591        ExprKind::KFlt => {
1592            let f = e.u.nval;
1593            let max = lua_code::opcodes::MAXARG_BX as i64 - lua_code::opcodes::OFFSET_S_BX as i64;
1594            let min = -(lua_code::opcodes::OFFSET_S_BX as i64);
1595            let fi_opt: Option<i64> = if f.fract() == 0.0 && f.abs() < i64::MAX as f64 {
1596                Some(f as i64)
1597            } else {
1598                None
1599            };
1600            if let Some(fi) = fi_opt.filter(|fi| *fi >= min && *fi <= max) {
1601                let bx = (fi as i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
1602                let inst = lua_code::opcodes::Instruction::abx(
1603                    lua_code::opcodes::OpCode::LoadF, reg as u32, bx,
1604                );
1605                emit_inst(fs, line, inst);
1606            } else {
1607                let k_idx = add_k_value(fs, LuaValue::Float(f));
1608                let inst = lua_code::opcodes::Instruction::abx(
1609                    lua_code::opcodes::OpCode::LoadK, reg as u32, k_idx as u32,
1610                );
1611                emit_inst(fs, line, inst);
1612            }
1613        }
1614        ExprKind::KStr => {
1615            let s = e.u.strval.clone()
1616                .ok_or_else(|| LuaError::syntax(format_args!("internal: VKStr with no strval")))?;
1617            let k_idx = add_k_string(fs, s);
1618            let inst = lua_code::opcodes::Instruction::abx(
1619                lua_code::opcodes::OpCode::LoadK,
1620                reg as u32,
1621                k_idx as u32,
1622            );
1623            emit_inst(fs, line, inst);
1624        }
1625        ExprKind::K => {
1626            let inst = lua_code::opcodes::Instruction::abx(
1627                lua_code::opcodes::OpCode::LoadK,
1628                reg as u32,
1629                e.u.info as u32,
1630            );
1631            emit_inst(fs, line, inst);
1632        }
1633        _ => {
1634            return Err(LuaError::syntax(format_args!(
1635                "internal: cg_discharge_to_reg cannot discharge {:?}", e.k
1636            )));
1637        }
1638    }
1639    e.u.info = reg as i32;
1640    e.k = ExprKind::NonReloc;
1641    Ok(())
1642}
1643
1644/// Mirrors C's `need_value` from `lcode.c`: walks the jump-list `list` and
1645/// returns true if any controlling instruction is *not* an `OP_TESTSET`,
1646/// meaning a concrete LoadTrue / LFalseSkip pair must be emitted to provide
1647/// the value at the fallthrough.
1648fn cg_need_value(fs: &FuncState, list: i32) -> bool {
1649    let mut list = list;
1650    while list != NO_JUMP {
1651        let ctrl_pc = cg_get_jump_control(fs, list);
1652        let ctrl = cg_inst_at(fs, ctrl_pc);
1653        if ctrl.opcode() != Some(lua_code::opcodes::OpCode::TestSet) {
1654            return true;
1655        }
1656        list = cg_get_jump(fs, list);
1657    }
1658    false
1659}
1660
1661/// Mirrors C's `code_loadbool` from `lcode.c`: records `fs.pc` as a jump
1662/// label, then emits the requested LoadTrue / LoadFalse / LFalseSkip
1663/// instruction and returns its pc.
1664fn cg_code_loadbool(fs: &mut FuncState, line: i32, reg: i32, op: lua_code::opcodes::OpCode) -> i32 {
1665    cg_get_label(fs);
1666    let inst = lua_code::opcodes::Instruction::abck(op, reg as u32, 0, 0, 0);
1667    emit_inst(fs, line, inst)
1668}
1669
1670/// Mirrors C's `patchlistaux` from `lcode.c`: walks the jump-list `list`,
1671/// rewriting `TESTSET` controllers to write `reg` (and routing them to
1672/// `vtarget`) and leaving plain tests to fall through to `dtarget`.
1673fn cg_patch_list_aux(
1674    fs: &mut FuncState,
1675    list: i32,
1676    vtarget: i32,
1677    reg: u32,
1678    dtarget: i32,
1679) -> Result<(), LuaError> {
1680    let mut list = list;
1681    while list != NO_JUMP {
1682        let next = cg_get_jump(fs, list);
1683        if cg_patch_test_reg(fs, list, reg) {
1684            cg_fix_jump(fs, list, vtarget)?;
1685        } else {
1686            cg_fix_jump(fs, list, dtarget)?;
1687        }
1688        list = next;
1689    }
1690    Ok(())
1691}
1692
1693/// Discharge `e` into the specific register `reg`. Mirrors C's `exp2reg`
1694/// from `lcode.c`: delegates to `cg_discharge_to_reg`, then folds the jump
1695/// at `e.u.info` into `e.t` (when `e` is itself a test) and patches any
1696/// pending `e.t` / `e.f` jump-lists. When the lists actually need a value
1697/// (i.e. any controller isn't a `TESTSET`), emits the LFalseSkip / LoadTrue
1698/// pair around which the jumps land.
1699fn cg_exp_to_reg(
1700    fs: &mut FuncState,
1701    line: i32,
1702    e: &mut ExprDesc,
1703    reg: u8,
1704) -> Result<(), LuaError> {
1705    cg_discharge_to_reg(fs, line, e, reg)?;
1706    if e.k == ExprKind::Jmp {
1707        let info = e.u.info;
1708        cg_concat(fs, &mut e.t, info)?;
1709    }
1710    if e.t != e.f {
1711        let mut p_f = NO_JUMP;
1712        let mut p_t = NO_JUMP;
1713        if cg_need_value(fs, e.t) || cg_need_value(fs, e.f) {
1714            let fj = if e.k == ExprKind::Jmp {
1715                NO_JUMP
1716            } else {
1717                cg_jump(fs, line)
1718            };
1719            p_f = cg_code_loadbool(fs, line, reg as i32, lua_code::opcodes::OpCode::LFalseSkip);
1720            p_t = cg_code_loadbool(fs, line, reg as i32, lua_code::opcodes::OpCode::LoadTrue);
1721            cg_patch_to_here(fs, fj)?;
1722        }
1723        let final_pc = cg_get_label(fs);
1724        cg_patch_list_aux(fs, e.f, final_pc, reg as u32, p_f)?;
1725        cg_patch_list_aux(fs, e.t, final_pc, reg as u32, p_t)?;
1726    }
1727    e.f = NO_JUMP;
1728    e.t = NO_JUMP;
1729    e.u.info = reg as i32;
1730    e.k = ExprKind::NonReloc;
1731    Ok(())
1732}
1733
1734/// Like `cg_free_reg`, but only acts when the index actually belongs to a
1735/// temporary register (one above `fs.nactvar`). Used by indexed-get
1736/// dischargers, which may operate on either a temp result or a local.
1737fn cg_free_reg_if_temp(fs: &mut FuncState, reg: i32) {
1738    if reg >= fs.nactvar as i32 {
1739        debug_assert!(reg < fs.freereg as i32);
1740        if reg == fs.freereg as i32 - 1 {
1741            fs.freereg -= 1;
1742        }
1743    }
1744}
1745
1746/// Mirrors C's `luaK_exp2nextreg` from `lcode.c`: discharge variable forms,
1747/// free any temp held by `e`, reserve the next register, then call
1748/// `cg_exp_to_reg` to place the value (handling `Jmp` and pending
1749/// `e.t` / `e.f` jump-lists through the shared `exp2reg` path).
1750fn cg_exp_to_next_reg(
1751    fs: &mut FuncState,
1752    line: i32,
1753    e: &mut ExprDesc,
1754) -> Result<(), LuaError> {
1755    cg_discharge_vars(fs, line, e)?;
1756    cg_free_exp(fs, e);
1757    let reg = reserve_reg(fs)?;
1758    cg_exp_to_reg(fs, line, e, reg)
1759}
1760
1761/// it produces `nresults` values (or LUA_MULTRET when `nresults == -1`).
1762fn cg_set_returns(fs: &mut FuncState, e: &mut ExprDesc, nresults: i32) {
1763    let pc_idx = e.u.info as usize;
1764    let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
1765    if e.k == ExprKind::Call {
1766        lc.set_arg_c((nresults + 1) as u32);
1767    } else {
1768        debug_assert_eq!(e.k, ExprKind::VarArg);
1769        lc.set_arg_c((nresults + 1) as u32);
1770        lc.set_arg_a(fs.freereg as u32);
1771        fs.freereg += 1;
1772    }
1773    fs.f.code[pc_idx] = lua_types::opcode::Instruction::new(lc.0);
1774}
1775
1776/// `OP_JMP` instructions to the final landing pc. Capped at 100 hops to
1777/// avoid infinite loops on malformed code.
1778fn cg_final_target(fs: &FuncState, mut i: i32) -> i32 {
1779    for _ in 0..100 {
1780        let inst = cg_inst_at(fs, i);
1781        if inst.opcode() != Some(lua_code::opcodes::OpCode::Jmp) {
1782            break;
1783        }
1784        i += inst.arg_s_j() + 1;
1785    }
1786    i
1787}
1788
1789///
1790/// Patches `OP_RETURN`/`OP_RETURN0`/`OP_RETURN1`/`OP_TAILCALL` to record the
1791/// vararg signature (so the VM can roll back `ci->func` on return) and the
1792/// `needclose` flag (so it closes pending upvalues). Also resolves chained
1793/// `OP_JMP` jumps to their final target.
1794fn cg_finish(fs: &mut FuncState) {
1795    use lua_code::opcodes::OpCode;
1796    let needclose = fs.needclose;
1797    let is_vararg = fs.f.is_vararg;
1798    let numparams = fs.f.numparams as u32;
1799    let pc_end = fs.pc;
1800    for i in 0..pc_end {
1801        let mut inst = cg_inst_at(fs, i);
1802        match inst.opcode() {
1803            Some(OpCode::Return0) | Some(OpCode::Return1) => {
1804                if !(needclose || is_vararg) {
1805                    continue;
1806                }
1807                inst.set_opcode(OpCode::Return);
1808                if needclose {
1809                    inst.set_arg_k(1);
1810                }
1811                if is_vararg {
1812                    inst.set_arg_c(numparams + 1);
1813                }
1814                cg_set_inst_at(fs, i, inst);
1815            }
1816            Some(OpCode::Return) | Some(OpCode::TailCall) => {
1817                if needclose {
1818                    inst.set_arg_k(1);
1819                }
1820                if is_vararg {
1821                    inst.set_arg_c(numparams + 1);
1822                }
1823                cg_set_inst_at(fs, i, inst);
1824            }
1825            Some(OpCode::Jmp) => {
1826                let target = cg_final_target(fs, i);
1827                let _ = cg_fix_jump(fs, i, target);
1828            }
1829            _ => {}
1830        }
1831    }
1832}
1833
1834/// based on `nret`. `first` is the first result register; `nret` is the
1835/// number of values to return (`LUA_MULTRET` for "all values on top").
1836fn cg_emit_return(fs: &mut FuncState, line: i32, first: i32, nret: i32) {
1837    let op = match nret {
1838        0 => lua_code::opcodes::OpCode::Return0,
1839        1 => lua_code::opcodes::OpCode::Return1,
1840        _ => lua_code::opcodes::OpCode::Return,
1841    };
1842    let inst = lua_code::opcodes::Instruction::abck(
1843        op,
1844        first as u32,
1845        (nret + 1) as u32,
1846        0,
1847        0,
1848    );
1849    emit_inst(fs, line, inst);
1850}
1851
1852// ── Free functions ──────────────────────────────────────────────────────────
1853
1854// (Both defined later in this file; Rust has no forward declarations.)
1855
1856// ── §1 Error helpers ────────────────────────────────────────────────────────
1857
1858/// Constructs a syntax error for a missing expected token.
1859/// In Rust, `l_noret` becomes returning `LuaError`; callers use
1860/// `return Err(error_expected(...))`.
1861fn error_expected(ls: &mut LexState, token: TokenKind) -> LuaError {
1862    let tok_str = lua_lex::token2str(&ls.lex, token);
1863    let mut msg: Vec<u8> = Vec::with_capacity(tok_str.len() + 10);
1864    msg.extend_from_slice(&tok_str);
1865    msg.extend_from_slice(b" expected");
1866    lua_lex::syntax_error(&mut ls.lex, &msg)
1867}
1868
1869/// Constructs a compile-time limit-exceeded syntax error.
1870fn error_limit(fs: &FuncState, limit: i32, what: &str) -> LuaError {
1871    let line = fs.f.linedefined;
1872    if line == 0 {
1873        LuaError::syntax(format_args!(
1874            "too many {} (limit is {}) in main function", what, limit
1875        ))
1876    } else {
1877        LuaError::syntax(format_args!(
1878            "too many {} (limit is {}) in function at line {}", what, limit, line
1879        ))
1880    }
1881}
1882
1883fn check_limit(fs: &FuncState, v: i32, l: i32, what: &str) -> Result<(), LuaError> {
1884    if v > l {
1885        return Err(error_limit(fs, l, what));
1886    }
1887    Ok(())
1888}
1889
1890// ── §2 Basic parse utilities ─────────────────────────────────────────────────
1891
1892/// If the current token matches `c`, consume it and return true.
1893fn test_next(ls: &mut LexState, state: &mut LuaState, c: TokenKind) -> Result<bool, LuaError> {
1894    if ls.t.token == c {
1895        lex_next(ls, state)?;
1896        Ok(true)
1897    } else {
1898        Ok(false)
1899    }
1900}
1901
1902fn check(ls: &mut LexState, c: TokenKind) -> Result<(), LuaError> {
1903    if ls.t.token != c {
1904        return Err(error_expected(ls, c));
1905    }
1906    Ok(())
1907}
1908
1909fn check_next(ls: &mut LexState, state: &mut LuaState, c: TokenKind) -> Result<(), LuaError> {
1910    check(ls, c)?;
1911    lex_next(ls, state)?;
1912    Ok(())
1913}
1914
1915/// Expects TK_NAME, returns the name string, advances.
1916fn str_check_name(ls: &mut LexState, state: &mut LuaState) -> Result<GcRef<LuaString>, LuaError> {
1917    check(ls, TK_NAME)?;
1918    let ts = ls.t.seminfo.ts.clone()
1919        .ok_or_else(|| LuaError::syntax(format_args!("name expected")))?;
1920    lex_next(ls, state)?;
1921    Ok(ts)
1922}
1923
1924fn init_exp(e: &mut ExprDesc, k: ExprKind, i: i32) {
1925    e.f = NO_JUMP;
1926    e.t = NO_JUMP;
1927    e.k = k;
1928    e.u.info = i;
1929}
1930
1931fn codestring(e: &mut ExprDesc, s: GcRef<LuaString>) {
1932    e.f = NO_JUMP;
1933    e.t = NO_JUMP;
1934    e.k = ExprKind::KStr;
1935    e.u.strval = Some(s);
1936}
1937
1938fn codename(ls: &mut LexState, state: &mut LuaState, e: &mut ExprDesc) -> Result<(), LuaError> {
1939    let name = str_check_name(ls, state)?;
1940    codestring(e, name);
1941    Ok(())
1942}
1943
1944// ── §3 Variable handling ─────────────────────────────────────────────────────
1945
1946/// Registers a local variable in the proto's debug-info locvars array.
1947/// Returns the index in locvars (= fs->ndebugvars before increment).
1948fn register_local_var(
1949    _ls: &mut LexState,
1950    _state: &mut LuaState,
1951    fs: &mut FuncState,
1952    varname: GcRef<LuaString>,
1953) -> Result<i32, LuaError> {
1954    // In Rust, Vec grows automatically; just push a placeholder if needed.
1955    let idx = fs.ndebugvars as usize;
1956    while fs.f.locvars.len() <= idx {
1957        fs.f.locvars.push(LocalVar {
1958            varname: varname.clone(), // placeholder; overwritten below
1959            startpc: 0,
1960            endpc: 0,
1961        });
1962    }
1963    fs.f.locvars[idx].varname = varname;
1964    fs.f.locvars[idx].startpc = fs.pc;
1965    let result = fs.ndebugvars as i32;
1966    fs.ndebugvars += 1;
1967    Ok(result)
1968}
1969
1970/// Creates a new local variable entry in dyd.actvar.
1971/// Returns the variable's index relative to fs->firstlocal.
1972fn new_local_var(
1973    ls: &mut LexState,
1974    _state: &mut LuaState,
1975    name: GcRef<LuaString>,
1976) -> Result<i32, LuaError> {
1977    let fs = ls.fs.as_ref().unwrap();
1978    let n = ls.dyd.actvar.len() as i32;
1979    let first_local = fs.firstlocal;
1980    check_limit(fs, n + 1 - first_local, MAX_VARS, "local variables")?;
1981
1982    let mut var = VarDesc::default();
1983    var.kind = VarKind::Reg;
1984    var.name = Some(name);
1985    ls.dyd.actvar.push(var);
1986    let result = ls.dyd.actvar.len() as i32 - 1 - first_local;
1987    Ok(result)
1988}
1989
1990/// Returns a reference to the VarDesc at index `fs->firstlocal + vidx`.
1991fn get_local_var_desc<'a>(ls: &'a LexState, fs: &FuncState, vidx: i32) -> &'a VarDesc {
1992    &ls.dyd.actvar[(fs.firstlocal + vidx) as usize]
1993}
1994
1995fn get_local_var_desc_mut(ls: &mut LexState, first_local: i32, vidx: i32) -> &mut VarDesc {
1996    &mut ls.dyd.actvar[(first_local + vidx) as usize]
1997}
1998
1999/// Converts a compiler-index level to its register number.
2000fn reg_level(ls: &LexState, fs: &FuncState, nvar: i32) -> i32 {
2001    let mut nvar = nvar;
2002    while nvar > 0 {
2003        nvar -= 1;
2004        let vd = get_local_var_desc(ls, fs, nvar);
2005        if vd.kind != VarKind::CompileTimeConst {
2006            return vd.ridx as i32 + 1;
2007        }
2008    }
2009    0
2010}
2011
2012/// Returns the number of variables currently occupying registers.
2013/// LUAI_FUNC visibility.
2014pub fn nvarstack(ls: &LexState, fs: &FuncState) -> i32 {
2015    reg_level(ls, fs, fs.nactvar as i32)
2016}
2017
2018fn init_var(ls: &LexState, fs: &FuncState, e: &mut ExprDesc, vidx: i32) {
2019    e.f = NO_JUMP;
2020    e.t = NO_JUMP;
2021    e.k = ExprKind::Local;
2022    e.u.var_vidx = vidx as u16;
2023    e.u.var_ridx = get_local_var_desc(ls, fs, vidx).ridx;
2024}
2025
2026/// Raises an error if expression `e` describes a read-only variable.
2027fn check_readonly(ls: &mut LexState, state: &mut LuaState, e: &ExprDesc) -> Result<(), LuaError> {
2028    // Lua 5.5: assignment to a `global x <const>` declared global is rejected
2029    // at compile time, tagged on the resolved expression by `singlevar`.
2030    if let Some(name) = e.u.global_const_name.as_ref() {
2031        let msg = format!(
2032            "attempt to assign to const variable '{}'",
2033            String::from_utf8_lossy(name.as_bytes())
2034        );
2035        // Semantic error (C's luaK_semerror): no "near <token>" suffix.
2036        return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
2037    }
2038    let varname: Option<GcRef<LuaString>> = {
2039        let fs = ls.fs.as_ref().unwrap();
2040        match e.k {
2041            ExprKind::Const => {
2042                ls.dyd.actvar[e.u.info as usize].name.clone()
2043            }
2044            ExprKind::Local => {
2045                let vd = get_local_var_desc(ls, fs, e.u.var_vidx as i32);
2046                if vd.kind != VarKind::Reg {
2047                    vd.name.clone()
2048                } else {
2049                    None
2050                }
2051            }
2052            ExprKind::UpVal => {
2053                let up = &fs.f.upvalues[e.u.info as usize];
2054                if VarKind::from_u8(up.kind) != VarKind::Reg {
2055                    up.name.clone()
2056                } else {
2057                    None
2058                }
2059            }
2060            _ => None,
2061        }
2062    };
2063    if let Some(vname) = varname {
2064        // C's luaK_semerror: a semantic error carries no "near <token>" suffix
2065        // (it zeroes ls->t.token before luaX_syntaxerror). Use lex_error with
2066        // token 0 to match the reference exactly for every version. constructs.lua's
2067        // checkload(":1: attempt to assign...") still matches (prefix).
2068        let _ = state;
2069        let msg = format!(
2070            "attempt to assign to const variable '{}'",
2071            String::from_utf8_lossy(vname.as_bytes())
2072        );
2073        return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
2074    }
2075    Ok(())
2076}
2077
2078/// Starts the scope for the last `nvars` created variables.
2079fn adjust_local_vars(ls: &mut LexState, state: &mut LuaState, nvars: i32) -> Result<(), LuaError> {
2080    // Extract needed data to avoid borrow conflict with ls.fs and ls.dyd
2081    let first_local = ls.fs.as_ref().unwrap().firstlocal;
2082    let nactvar_start = ls.fs.as_ref().unwrap().nactvar as i32;
2083    let mut reglevel_val = {
2084        let fs = ls.fs.as_ref().unwrap();
2085        reg_level(ls, fs, fs.nactvar as i32)
2086    };
2087
2088    for i in 0..nvars {
2089        let vidx = nactvar_start + i;
2090        ls.fs.as_mut().unwrap().nactvar += 1;
2091        let var_name = ls.dyd.actvar[(first_local + vidx) as usize].name.clone();
2092        ls.dyd.actvar[(first_local + vidx) as usize].ridx = reglevel_val as u8;
2093        reglevel_val += 1;
2094        if let Some(vn) = var_name {
2095            let mut fs_box = ls.fs.take().unwrap();
2096            let pidx_result = register_local_var(ls, state, &mut fs_box, vn);
2097            ls.fs = Some(fs_box);
2098            let pidx = pidx_result?;
2099            ls.dyd.actvar[(first_local + vidx) as usize].pidx = pidx as i16;
2100        } else {
2101            // TODO(port): variable has no name — shouldn't happen in valid source
2102        }
2103    }
2104    Ok(())
2105}
2106
2107/// Closes scope for all variables above `tolevel`, updating their endpc.
2108fn remove_vars(ls: &mut LexState, fs: &mut FuncState, tolevel: i32) {
2109    //
2110    // C just decrements a length counter; the underlying array memory is
2111    // untouched and the subsequent loop reads from it freely. A Rust
2112    // `truncate` would actually free the entries, leaving the loop reading
2113    // out-of-range and silently writing every iteration's endpc to
2114    // `locvars[0]` (via the `unwrap_or(0)` fallback below). Defer the
2115    // truncate until after the loop walks each soon-to-be-removed entry.
2116    let delta = fs.nactvar as i32 - tolevel;
2117    while fs.nactvar as i32 > tolevel {
2118        fs.nactvar -= 1;
2119        let nactvar = fs.nactvar as i32;
2120        let vd_kind = {
2121            let first_local = fs.firstlocal;
2122            ls.dyd.actvar.get((first_local + nactvar) as usize)
2123                .map(|v| v.kind)
2124                .unwrap_or(VarKind::Reg)
2125        };
2126        if vd_kind != VarKind::CompileTimeConst {
2127            let vd_pidx = {
2128                let first_local = fs.firstlocal;
2129                ls.dyd.actvar.get((first_local + nactvar) as usize)
2130                    .map(|v| v.pidx)
2131                    .unwrap_or(0)
2132            };
2133            if let Some(lv) = fs.f.locvars.get_mut(vd_pidx as usize) {
2134                lv.endpc = fs.pc;
2135            }
2136        }
2137    }
2138    if delta > 0 {
2139        let new_len = ls.dyd.actvar.len().saturating_sub(delta as usize);
2140        ls.dyd.actvar.truncate(new_len);
2141    }
2142}
2143
2144// ── §4 Upvalue handling ──────────────────────────────────────────────────────
2145
2146/// Returns the index of an upvalue named `name`, or -1 if not found.
2147fn search_upvalue(fs: &FuncState, name: &GcRef<LuaString>) -> i32 {
2148    for (i, up) in fs.f.upvalues.iter().enumerate() {
2149        if up.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
2150            return i as i32;
2151        }
2152    }
2153    -1
2154}
2155
2156/// Grows upvalues array and returns index of the new slot.
2157fn alloc_upvalue(fs: &mut FuncState) -> Result<usize, LuaError> {
2158    if fs.nups as i32 + 1 > MAX_UPVAL as i32 {
2159        return Err(error_limit(fs, MAX_UPVAL as i32, "upvalues"));
2160    }
2161    let idx = fs.nups as usize;
2162    while fs.f.upvalues.len() <= idx {
2163        fs.f.upvalues.push(UpvalDesc { name: None, instack: false, idx: 0, kind: 0 });
2164    }
2165    fs.nups += 1;
2166    Ok(idx)
2167}
2168
2169/// Adds a new upvalue descriptor and returns its index.
2170fn new_upvalue(
2171    ls: &LexState,
2172    fs: &mut FuncState,
2173    name: GcRef<LuaString>,
2174    v: &ExprDesc,
2175) -> Result<i32, LuaError> {
2176    let idx = alloc_upvalue(fs)?;
2177    let kind: u8 = if v.k == ExprKind::Local {
2178        let prev = fs.prev.as_deref().expect("upvalue capture requires enclosing FuncState");
2179        get_local_var_desc(ls, prev, v.u.var_vidx as i32).kind.as_u8()
2180    } else {
2181        let prev = fs.prev.as_deref().expect("upvalue chain requires enclosing FuncState");
2182        prev.f.upvalues[v.u.info as usize].kind
2183    };
2184    let up = &mut fs.f.upvalues[idx];
2185    if v.k == ExprKind::Local {
2186        up.instack = true;
2187        up.idx = v.u.var_ridx;
2188    } else {
2189        up.instack = false;
2190        up.idx = v.u.info as u8;
2191    }
2192    up.kind = kind;
2193    up.name = Some(name);
2194    Ok(fs.nups as i32 - 1)
2195}
2196
2197/// Searches for a local variable named `n`. Returns ExprKind as i32 or -1.
2198fn searchvar(
2199    ls: &LexState,
2200    fs: &FuncState,
2201    n: &GcRef<LuaString>,
2202    var: &mut ExprDesc,
2203) -> i32 {
2204    let mut i = fs.nactvar as i32 - 1;
2205    while i >= 0 {
2206        let vd = get_local_var_desc(ls, fs, i);
2207        if vd.name.as_ref().map_or(false, |nm| GcRef::ptr_eq(nm, n)) {
2208            if vd.kind == VarKind::CompileTimeConst {
2209                init_exp(var, ExprKind::Const, fs.firstlocal + i);
2210            } else {
2211                init_var(ls, fs, var, i);
2212            }
2213            return var.k as i32; // PORT NOTE: encoding ExprKind as i32 for C compat
2214        }
2215        i -= 1;
2216    }
2217    -1
2218}
2219
2220/// Marks the block where the variable at `level` was defined as having an upvalue.
2221fn markupval(fs: &mut FuncState, level: i32) {
2222    let mut current = fs.bl.as_deref_mut();
2223    while let Some(b) = current {
2224        if (b.nactvar as i32) <= level {
2225            b.upval = true;
2226            break;
2227        }
2228        current = b.previous.as_deref_mut();
2229    }
2230    fs.needclose = true;
2231}
2232
2233fn marktobeclosed(fs: &mut FuncState) {
2234    if let Some(bl) = fs.bl.as_mut() {
2235        bl.upval = true;
2236        bl.insidetbc = true;
2237    }
2238    fs.needclose = true;
2239}
2240
2241// ── §5 Variable resolution ───────────────────────────────────────────────────
2242
2243/// Recursively finds variable `n` in `fs` and its enclosing functions.
2244/// If not found at any level, sets var->k = VVOID (global).
2245fn singlevaraux(
2246    ls: &LexState,
2247    fs: Option<&mut FuncState>,
2248    n: &GcRef<LuaString>,
2249    var: &mut ExprDesc,
2250    base: bool,
2251) -> Result<(), LuaError> {
2252    match fs {
2253        None => {
2254            init_exp(var, ExprKind::Void, 0);
2255        }
2256        Some(fs) => {
2257            let v = searchvar(ls, fs, n, var);
2258            if v >= 0 {
2259                if v == ExprKind::Local as i32 && !base {
2260                    markupval(fs, var.u.var_vidx as i32);
2261                }
2262            } else {
2263                let idx = search_upvalue(fs, n);
2264                let final_idx = if idx < 0 {
2265                    singlevaraux(ls, fs.prev.as_deref_mut(), n, var, false)?;
2266                    if var.k == ExprKind::Local || var.k == ExprKind::UpVal {
2267                        new_upvalue(ls, fs, n.clone(), var)?
2268                    } else {
2269                        return Ok(());
2270                    }
2271                } else {
2272                    idx
2273                };
2274                init_exp(var, ExprKind::UpVal, final_idx);
2275            }
2276        }
2277    }
2278    Ok(())
2279}
2280
2281/// Finds the variable named by the next TK_NAME token.
2282fn singlevar(ls: &mut LexState, state: &mut LuaState, var: &mut ExprDesc) -> Result<(), LuaError> {
2283    let varname = str_check_name(ls, state)?;
2284    let mut fs_box = ls.fs.take();
2285    let recurse_result = singlevaraux(ls, fs_box.as_deref_mut(), &varname, var, true);
2286    ls.fs = fs_box;
2287    recurse_result?;
2288    if var.k == ExprKind::Void {
2289        // Lua 5.5: once a scope is in strict mode (an explicit `global`
2290        // declaration was seen), a free name must be a declared global —
2291        // otherwise it is a compile-time error (manual §2.2). `global_strict`
2292        // is only ever set on the 5.5 path, so pre-5.5 resolution is unchanged.
2293        let is_const_global = if ls.global_strict {
2294            let mut declared_const: Option<bool> = None;
2295            for (n, c) in &ls.declared_globals {
2296                if GcRef::ptr_eq(n, &varname) {
2297                    declared_const = Some(*c);
2298                    break;
2299                }
2300            }
2301            match declared_const {
2302                None => {
2303                    let msg = format!(
2304                        "variable '{}' not declared",
2305                        String::from_utf8_lossy(varname.as_bytes())
2306                    );
2307                    // Semantic error (C's luaK_semerror): no "near <token>" suffix.
2308                    return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
2309                }
2310                Some(c) => c,
2311            }
2312        } else {
2313            false
2314        };
2315        let envn = ls.envn.clone().expect("envn must be set when resolving globals");
2316        let mut env_var = ExprDesc::default();
2317        let mut fs_box = ls.fs.take();
2318        let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut env_var, true);
2319        ls.fs = fs_box;
2320        r?;
2321        debug_assert!(env_var.k != ExprKind::Void, "_ENV must resolve");
2322        let line = ls.lastline;
2323        let fs = ls.fs.as_mut().unwrap();
2324        cg_exp_to_any_reg_up(fs, line, &mut env_var)?;
2325        let mut key = ExprDesc::default();
2326        let const_name = if is_const_global { Some(varname.clone()) } else { None };
2327        codestring(&mut key, varname);
2328        cg_indexed(fs, line, &mut env_var, &mut key)?;
2329        *var = env_var;
2330        var.u.global_const_name = const_name;
2331    }
2332    Ok(())
2333}
2334
2335fn adjust_assign(
2336    ls: &mut LexState,
2337    _state: &mut LuaState,
2338    nvars: i32,
2339    nexps: i32,
2340    e: &mut ExprDesc,
2341) -> Result<(), LuaError> {
2342    let needed = nvars - nexps;
2343    let line = ls.lastline;
2344    let fs = ls.fs.as_mut().unwrap();
2345    if e.k.has_mult_ret() {
2346        let extra = if needed + 1 < 0 { 0 } else { needed + 1 };
2347        cg_set_returns(fs, e, extra);
2348    } else {
2349        if e.k != ExprKind::Void {
2350            cg_exp_to_next_reg(fs, line, e)?;
2351        }
2352        if needed > 0 {
2353            let from = fs.freereg as i32;
2354            cg_emit_nil(fs, line, from, needed);
2355        }
2356    }
2357    if needed > 0 {
2358        for _ in 0..needed {
2359            reserve_reg(fs)?;
2360        }
2361    } else {
2362        fs.freereg = (fs.freereg as i32 + needed) as u8;
2363    }
2364    Ok(())
2365}
2366
2367/// Emits `OP_NEWTABLE` followed by the required `OP_EXTRAARG` slot. The two
2368/// instructions are written as placeholders; `cg_settablesize` later patches
2369/// them with the final array/hash sizes. Returns the pc of `OP_NEWTABLE`.
2370fn cg_emit_newtable(fs: &mut FuncState, line: i32) -> i32 {
2371    let newtable = lua_code::opcodes::Instruction::abck(
2372        lua_code::opcodes::OpCode::NewTable, 0, 0, 0, 0,
2373    );
2374    let pc = emit_inst(fs, line, newtable);
2375    let extra = lua_code::opcodes::Instruction::ax(
2376        lua_code::opcodes::OpCode::ExtraArg, 0,
2377    );
2378    emit_inst(fs, line, extra);
2379    pc
2380}
2381
2382/// Patches a previously-emitted `OP_NEWTABLE`/`OP_EXTRAARG` pair with the
2383/// final array size (`asize`) and hash size (`hsize`). Mirrors
2384/// `luaK_settablesize` from `lcode.c`.
2385fn cg_settablesize(fs: &mut FuncState, pc: i32, ra: i32, asize: i32, hsize: i32) {
2386    let rb = if hsize != 0 {
2387        (hsize as u32).next_power_of_two().trailing_zeros() as i32 + 1
2388    } else {
2389        0
2390    };
2391    let maxc = lua_code::opcodes::MAXARG_C as i32 + 1;
2392    let extra = asize / maxc;
2393    let rc = asize % maxc;
2394    let k = if extra > 0 { 1u32 } else { 0u32 };
2395    let newtable = lua_code::opcodes::Instruction::abck(
2396        lua_code::opcodes::OpCode::NewTable,
2397        ra as u32, rb as u32, rc as u32, k,
2398    );
2399    fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(newtable.0);
2400    let extra_inst = lua_code::opcodes::Instruction::ax(
2401        lua_code::opcodes::OpCode::ExtraArg, extra as u32,
2402    );
2403    fs.f.code[pc as usize + 1] = lua_types::opcode::Instruction::new(extra_inst.0);
2404}
2405
2406/// Emits `OP_SETLIST` for `tostore` elements starting at `base+1`, with
2407/// `nelems` already-stored elements preceding them. `tostore == -1` means
2408/// `LUA_MULTRET` (encoded as 0 in the B field). Also resets `fs.freereg`
2409/// to `base + 1`, mirroring `luaK_setlist`.
2410fn cg_setlist(fs: &mut FuncState, line: i32, base: i32, nelems: i32, tostore: i32) {
2411    let maxc = lua_code::opcodes::MAXARG_C as i32;
2412    let tostore_arg = if tostore == LUA_MULTRET { 0 } else { tostore };
2413    if nelems <= maxc {
2414        let inst = lua_code::opcodes::Instruction::abck(
2415            lua_code::opcodes::OpCode::SetList,
2416            base as u32, tostore_arg as u32, nelems as u32, 0,
2417        );
2418        emit_inst(fs, line, inst);
2419    } else {
2420        let extra = nelems / (maxc + 1);
2421        let nelems_lo = nelems % (maxc + 1);
2422        let inst = lua_code::opcodes::Instruction::abck(
2423            lua_code::opcodes::OpCode::SetList,
2424            base as u32, tostore_arg as u32, nelems_lo as u32, 1,
2425        );
2426        emit_inst(fs, line, inst);
2427        let extra_inst = lua_code::opcodes::Instruction::ax(
2428            lua_code::opcodes::OpCode::ExtraArg, extra as u32,
2429        );
2430        emit_inst(fs, line, extra_inst);
2431    }
2432    fs.freereg = (base + 1) as u8;
2433}
2434
2435/// Converts a table-and-key expression pair into the appropriate `VINDEX*`
2436/// variant. Mirrors `luaK_indexed` from `lcode.c`. Assumes `t` is already a
2437/// value-producing form (`VLOCAL`, `VNONRELOC`, or `VUPVAL`) and that any
2438/// short-string key has already been promoted to a `VKSTR` constant index.
2439fn cg_indexed(fs: &mut FuncState, line: i32, t: &mut ExprDesc, k: &mut ExprDesc) -> Result<(), LuaError> {
2440    if k.k == ExprKind::KStr {
2441        let s = k.u.strval.clone()
2442            .ok_or_else(|| LuaError::syntax(format_args!("internal: VKStr with no strval")))?;
2443        let k_idx = add_k_string(fs, s);
2444        k.u.info = k_idx;
2445        k.k = ExprKind::K;
2446    }
2447    let k_is_kstr = k.k == ExprKind::K
2448        && k.u.info >= 0
2449        && (k.u.info as u32) <= lua_code::opcodes::MAXARG_B;
2450    if t.k == ExprKind::UpVal && !k_is_kstr {
2451        cg_exp_to_any_reg(fs, line, t)?;
2452    }
2453    if t.k == ExprKind::UpVal {
2454        let temp = t.u.info as u8;
2455        t.u.ind_t = temp;
2456        t.u.ind_idx = k.u.info as i16;
2457        t.k = ExprKind::IndexUp;
2458        return Ok(());
2459    }
2460    let t_reg = match t.k {
2461        ExprKind::Local => t.u.var_ridx,
2462        ExprKind::NonReloc => t.u.info as u8,
2463        _ => return Err(LuaError::syntax(format_args!(
2464            "internal: cg_indexed on non-register table kind {:?}", t.k
2465        ))),
2466    };
2467    t.u.ind_t = t_reg;
2468    if k.k == ExprKind::K && k_is_kstr {
2469        t.u.ind_idx = k.u.info as i16;
2470        t.k = ExprKind::IndexStr;
2471    } else if k.k == ExprKind::KInt && cg_fits_int_key(k.u.ival) {
2472        t.u.ind_idx = k.u.ival as i16;
2473        t.k = ExprKind::IndexI;
2474    } else {
2475        cg_exp_to_any_reg(fs, line, k)?;
2476        t.u.ind_idx = k.u.info as i16;
2477        t.k = ExprKind::Indexed;
2478    }
2479    Ok(())
2480}
2481
2482fn cg_fits_int_key(i: i64) -> bool {
2483    i >= 0 && (i as u32) <= lua_code::opcodes::MAXARG_C
2484}
2485
2486/// Emits OP_SELF, converting `e:key(...)` into the equivalent of `(e.key)(e, ...)`.
2487/// Leaves `e` as VNONRELOC pointing at the function register (base); the self
2488/// register is `base + 1`. `key` must be a string expression (VKStr).
2489fn cg_self(
2490    fs: &mut FuncState,
2491    line: i32,
2492    e: &mut ExprDesc,
2493    key: &mut ExprDesc,
2494) -> Result<(), LuaError> {
2495    cg_exp_to_any_reg(fs, line, e)?;
2496    let ereg = e.u.info;
2497    cg_free_exp(fs, e);
2498    let base = fs.freereg as i32;
2499    e.u.info = base;
2500    e.k = ExprKind::NonReloc;
2501    reserve_regs(fs, 2)?;
2502    let key_str = key.u.strval.clone()
2503        .ok_or_else(|| LuaError::syntax(format_args!(
2504            "internal: cg_self expected VKStr key, got {:?}", key.k
2505        )))?;
2506    let k_idx = add_k_string(fs, key_str);
2507    let (c_arg, k_flag) = if (k_idx as u32) <= lua_code::opcodes::MAXINDEXRK {
2508        (k_idx as u32, 1u32)
2509    } else {
2510        key.k = ExprKind::K;
2511        key.u.info = k_idx;
2512        cg_exp_to_any_reg(fs, line, key)?;
2513        (key.u.info as u32, 0u32)
2514    };
2515    let inst = lua_code::opcodes::Instruction::abck(
2516        lua_code::opcodes::OpCode::Self_,
2517        base as u32,
2518        ereg as u32,
2519        c_arg,
2520        k_flag,
2521    );
2522    emit_inst(fs, line, inst);
2523    cg_free_exp(fs, key);
2524    Ok(())
2525}
2526
2527/// Minimal `luaK_exp2anyregup`: if `e` is an upvalue or constant, leave it as
2528/// is; otherwise discharge it into some register.
2529fn cg_exp_to_any_reg_up(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
2530    if matches!(e.k, ExprKind::UpVal | ExprKind::K) {
2531        return Ok(());
2532    }
2533    cg_exp_to_any_reg(fs, line, e)?;
2534    Ok(())
2535}
2536
2537/// Minimal `luaK_nil`: emits a LoadNil instruction filling `n` consecutive
2538/// registers starting at `from` with `nil`. Does not perform the C
2539/// optimization that merges with a preceding LoadNil.
2540fn cg_emit_nil(fs: &mut FuncState, line: i32, from: i32, n: i32) {
2541    let inst = lua_code::opcodes::Instruction::abck(
2542        lua_code::opcodes::OpCode::LoadNil,
2543        from as u32,
2544        (n - 1) as u32,
2545        0,
2546        0,
2547    );
2548    emit_inst(fs, line, inst);
2549}
2550
2551// ── §6 Label / goto management ───────────────────────────────────────────────
2552
2553fn jumpscopeerror(ls: &LexState, gt_idx: usize) -> LuaError {
2554    let gt = &ls.dyd.gt[gt_idx];
2555    let line = gt.line;
2556    let gt_name_bytes: &[u8] = gt.name.as_ref().map(|n| n.as_bytes()).unwrap_or(b"");
2557    let gt_name = String::from_utf8_lossy(gt_name_bytes);
2558    let varname_bytes: &[u8] = ls.fs.as_ref()
2559        .and_then(|fs| {
2560            let vidx = gt.nactvar as i32;
2561            if (fs.firstlocal + vidx) >= 0 && ((fs.firstlocal + vidx) as usize) < ls.dyd.actvar.len() {
2562                let vd = get_local_var_desc(ls, fs, vidx);
2563                vd.name.as_ref().map(|n| n.as_bytes())
2564            } else {
2565                None
2566            }
2567        })
2568        .unwrap_or(b"");
2569    let varname = String::from_utf8_lossy(varname_bytes);
2570    LuaError::syntax(format_args!(
2571        "<goto {}> at line {} jumps into the scope of local '{}'", gt_name, line, varname
2572    ))
2573}
2574
2575/// Resolves goto at index `g` to `label`, removing it from pending list.
2576fn solvegoto(
2577    ls: &mut LexState,
2578    _state: &mut LuaState,
2579    g: usize,
2580    label_pc: i32,
2581    label_nactvar: u8,
2582) -> Result<(), LuaError> {
2583    if ls.dyd.gt[g].nactvar < label_nactvar {
2584        return Err(jumpscopeerror(ls, g));
2585    }
2586    let gt_pc = ls.dyd.gt[g].pc;
2587    cg_patch_list(ls.fs.as_mut().unwrap(), gt_pc, label_pc)?;
2588    ls.dyd.gt.remove(g);
2589    Ok(())
2590}
2591
2592/// Searches for an active label with the given name in the current function.
2593fn findlabel(ls: &LexState, name: &GcRef<LuaString>) -> Option<usize> {
2594    let first = ls.fs.as_ref().unwrap().firstlabel as usize;
2595    for i in first..ls.dyd.label.len() {
2596        let lb = &ls.dyd.label[i];
2597        if lb.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
2598            return Some(i);
2599        }
2600    }
2601    None
2602}
2603
2604/// Adds a new label/goto entry; returns its index.
2605fn new_label_entry(
2606    ls: &mut LexState,
2607    _state: &mut LuaState,
2608    is_goto: bool,
2609    name: GcRef<LuaString>,
2610    line: i32,
2611    pc: i32,
2612) -> Result<usize, LuaError> {
2613    let nactvar = ls.fs.as_ref().unwrap().nactvar;
2614    let entry = LabelDesc { name: Some(name), pc, line, nactvar, close: false };
2615    let list = if is_goto { &mut ls.dyd.gt } else { &mut ls.dyd.label };
2616    let n = list.len();
2617    list.push(entry);
2618    Ok(n)
2619}
2620
2621fn new_goto_entry(
2622    ls: &mut LexState,
2623    state: &mut LuaState,
2624    name: GcRef<LuaString>,
2625    line: i32,
2626    pc: i32,
2627) -> Result<usize, LuaError> {
2628    new_label_entry(ls, state, true, name, line, pc)
2629}
2630
2631/// Resolves all pending gotos that match label `lb`.
2632/// Returns true if any goto needed close.
2633fn solvegotos(ls: &mut LexState, state: &mut LuaState, lb_idx: usize) -> Result<bool, LuaError> {
2634    let lb_name = ls.dyd.label[lb_idx].name.clone();
2635    let lb_pc = ls.dyd.label[lb_idx].pc;
2636    let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
2637    let first_goto = ls.fs.as_ref().unwrap().bl.as_ref().map_or(0, |b| b.firstgoto) as usize;
2638
2639    let mut i = first_goto;
2640    let mut needs_close = false;
2641    while i < ls.dyd.gt.len() {
2642        let gt_name = ls.dyd.gt[i].name.clone();
2643        let names_match = lb_name.as_ref().and_then(|ln| gt_name.as_ref().map(|gn| GcRef::ptr_eq(ln, gn))).unwrap_or(false);
2644        if names_match {
2645            needs_close |= ls.dyd.gt[i].close;
2646            // solvegoto removes element i, so don't increment i
2647            solvegoto(ls, state, i, lb_pc, lb_nactvar)?;
2648        } else {
2649            i += 1;
2650        }
2651    }
2652    Ok(needs_close)
2653}
2654
2655/// Creates a new label; resolves pending gotos. Returns true if CLOSE emitted.
2656fn createlabel(
2657    ls: &mut LexState,
2658    state: &mut LuaState,
2659    name: GcRef<LuaString>,
2660    line: i32,
2661    last: bool,
2662) -> Result<bool, LuaError> {
2663    let label_pc = cg_get_label(ls.fs.as_mut().unwrap());
2664    let l = new_label_entry(ls, state, false, name, line, label_pc)?;
2665    if last {
2666        let bl_nactvar = ls.fs.as_ref().unwrap().bl.as_ref().map_or(0, |b| b.nactvar);
2667        ls.dyd.label[l].nactvar = bl_nactvar;
2668    }
2669    let needs_close = solvegotos(ls, state, l)?;
2670    if needs_close {
2671        let nstack = nvarstack(ls, ls.fs.as_ref().unwrap()) as u32;
2672        let inst = lua_code::opcodes::Instruction::abck(
2673            lua_code::opcodes::OpCode::Close,
2674            nstack,
2675            0,
2676            0,
2677            0,
2678        );
2679        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
2680        return Ok(true);
2681    }
2682    Ok(false)
2683}
2684
2685/// Adjusts pending gotos to outer block level when leaving a block.
2686fn movegotosout(ls: &mut LexState, bl_firstgoto: usize, bl_nactvar: u8, bl_upval: bool) {
2687    let _ = ls.fs.as_ref().unwrap();
2688    let first_goto = bl_firstgoto;
2689    let _n_gt = ls.dyd.gt.len();
2690
2691    for i in first_goto..ls.dyd.gt.len() {
2692        let _gt_nactvar = ls.dyd.gt[i].nactvar;
2693        // TODO(port): compute reg_level properly using ls+fs
2694        if bl_upval {
2695            ls.dyd.gt[i].close = true;
2696        }
2697        ls.dyd.gt[i].nactvar = bl_nactvar;
2698    }
2699}
2700
2701/// Pushes a new block scope onto fs->bl.
2702fn enter_block(ls: &mut LexState, isloop: bool) {
2703    let firstlabel = ls.dyd.label.len() as i32;
2704    let firstgoto = ls.dyd.gt.len() as i32;
2705    let saved_global_strict = ls.global_strict;
2706    let saved_declared_globals = ls.declared_globals.len();
2707    let insidetbc = ls.fs.as_ref()
2708        .and_then(|f| f.bl.as_ref())
2709        .map_or(false, |b| b.insidetbc);
2710    let fs = ls.fs.as_mut().unwrap();
2711    let nactvar = fs.nactvar;
2712    let new_bl = Box::new(BlockCnt {
2713        previous: fs.bl.take(),
2714        firstlabel,
2715        firstgoto,
2716        nactvar,
2717        upval: false,
2718        isloop,
2719        insidetbc,
2720        saved_global_strict,
2721        saved_declared_globals,
2722    });
2723    fs.bl = Some(new_bl);
2724    debug_assert!(fs.freereg as i32 == {
2725        // TODO(port): nvarstack(ls, fs) -- circular borrow
2726        fs.freereg as i32 // placeholder assertion
2727    });
2728}
2729
2730fn undef_goto(ls: &LexState, gt_idx: usize) -> LuaError {
2731    let gt = &ls.dyd.gt[gt_idx];
2732    let line = gt.line;
2733    let name_bytes: &[u8] = gt.name.as_ref().map(|n| n.as_bytes()).unwrap_or(b"");
2734    if name_bytes == b"break" {
2735        LuaError::syntax(format_args!("break outside loop at line {}", line))
2736    } else {
2737        let name_str = String::from_utf8_lossy(name_bytes);
2738        LuaError::syntax(format_args!("no visible label '{}' for <goto> at line {}", name_str, line))
2739    }
2740}
2741
2742/// Pops the innermost block scope, emitting CLOSE if needed.
2743fn leave_block(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
2744    // Snapshot block fields without popping; createlabel below relies on
2745    // fs->bl still pointing at this (loop) block so solvegotos can read
2746    // fs->bl->firstgoto.
2747    let (bl_nactvar, bl_isloop, bl_upval, bl_firstgoto, bl_firstlabel) = {
2748        let bl = ls
2749            .fs
2750            .as_ref()
2751            .unwrap()
2752            .bl
2753            .as_ref()
2754            .expect("leave_block: no current block");
2755        (bl.nactvar, bl.isloop, bl.upval, bl.firstgoto, bl.firstlabel)
2756    };
2757
2758    // Lua 5.5: restore the `global`-declaration scope to what it was on block
2759    // entry, so an explicit `global` decl (and the strict mode it triggers) is
2760    // confined to its enclosing block.
2761    {
2762        let (sgs, sdg) = {
2763            let bl = ls.fs.as_ref().unwrap().bl.as_ref().unwrap();
2764            (bl.saved_global_strict, bl.saved_declared_globals)
2765        };
2766        ls.global_strict = sgs;
2767        ls.declared_globals.truncate(sdg);
2768    }
2769
2770    let stklevel = reg_level(ls, ls.fs.as_ref().unwrap(), bl_nactvar as i32);
2771    let mut fs_box = ls.fs.take().unwrap();
2772    remove_vars(ls, &mut fs_box, bl_nactvar as i32);
2773    debug_assert!(bl_nactvar == fs_box.nactvar);
2774    ls.fs = Some(fs_box);
2775
2776    let hasclose = if bl_isloop {
2777        let break_str = state.intern_str(b"break")?;
2778        createlabel(ls, state, break_str, 0, false)?
2779    } else {
2780        false
2781    };
2782
2783    // Now pop the block off fs.bl, restoring its previous link.
2784    let mut bl_box = ls.fs.as_mut().unwrap().bl.take().unwrap();
2785    let previous = bl_box.previous.take();
2786    ls.fs.as_mut().unwrap().bl = previous;
2787
2788    let has_prev_block = ls.fs.as_ref().unwrap().bl.is_some();
2789    if !hasclose && has_prev_block && bl_upval {
2790        // Use `lastline` so the OP_CLOSE attributes to the block's terminating
2791        // token (END/UNTIL) rather than whatever the parser has peeked to next.
2792        // Mirrors lua-c's `savelineinfo(fs, f, fs->ls->lastline)`.
2793        let line = ls.lastline;
2794        let inst = lua_code::opcodes::Instruction::abck(
2795            lua_code::opcodes::OpCode::Close,
2796            stklevel as u32,
2797            0,
2798            0,
2799            0,
2800        );
2801        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
2802    }
2803    ls.fs.as_mut().unwrap().freereg = stklevel as u8;
2804
2805    ls.dyd.label.truncate(bl_firstlabel as usize);
2806
2807    if has_prev_block {
2808        movegotosout(ls, bl_firstgoto as usize, bl_nactvar, bl_upval);
2809    } else {
2810        if (bl_firstgoto as usize) < ls.dyd.gt.len() {
2811            return Err(undef_goto(ls, bl_firstgoto as usize));
2812        }
2813    }
2814    Ok(())
2815}
2816
2817// ── §7 Proto management ──────────────────────────────────────────────────────
2818
2819/// Adds a new prototype slot to the current function's proto list.
2820/// Returns a mutable reference to the new prototype.
2821fn add_prototype(ls: &mut LexState, _state: &mut LuaState) -> Result<Box<LuaProto>, LuaError> {
2822    let np = ls.fs.as_ref().unwrap().np as usize;
2823    // TODO(port): allocate via state.gc().new_proto() in Phase B
2824    let new_proto = Box::new(LuaProto::placeholder());
2825    while ls.fs.as_ref().unwrap().f.p.len() <= np {
2826        ls.fs
2827            .as_mut()
2828            .unwrap()
2829            .f
2830            .p
2831            .push(GcRef::new(LuaProto::placeholder()));
2832    }
2833    ls.fs.as_mut().unwrap().np += 1;
2834    Ok(new_proto)
2835}
2836
2837/// Emits OP_CLOSURE in the parent function and fixes up v.
2838fn codeclosure(ls: &mut LexState, _state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
2839    let line = ls.lastline;
2840    let mut child = ls.fs.take().expect("codeclosure: no current FuncState");
2841    let result = (|| -> Result<(), LuaError> {
2842        let parent = child.prev.as_mut().expect(
2843            "codeclosure: child FuncState has no parent (called outside body()?)",
2844        );
2845        let bx = (parent.np - 1) as u32;
2846        let inst = lua_code::opcodes::Instruction::abx(
2847            lua_code::opcodes::OpCode::Closure,
2848            0,
2849            bx,
2850        );
2851        let pc = emit_inst(parent, line, inst);
2852        init_exp(v, ExprKind::Reloc, pc);
2853        cg_exp_to_next_reg(parent, line, v)
2854    })();
2855    ls.fs = Some(child);
2856    result
2857}
2858
2859/// Installs `new_fs` as the current FuncState, pushing old one as `prev`.
2860fn open_func(ls: &mut LexState, _state: &mut LuaState, mut new_fs: FuncState) -> Result<(), LuaError> {
2861    new_fs.prev = ls.fs.take();
2862
2863    let f = &mut new_fs.f;
2864    new_fs.pc = 0;
2865    new_fs.previousline = f.linedefined;
2866    new_fs.iwthabs = 0;
2867    new_fs.lasttarget = 0;
2868    new_fs.freereg = 0;
2869    new_fs.nk = 0;
2870    new_fs.nabslineinfo = 0;
2871    new_fs.np = 0;
2872    new_fs.nups = 0;
2873    new_fs.ndebugvars = 0;
2874    new_fs.nactvar = 0;
2875    new_fs.needclose = false;
2876
2877    new_fs.firstlocal = ls.dyd.actvar.len() as i32;
2878    new_fs.firstlabel = ls.dyd.label.len() as i32;
2879    new_fs.bl = None;
2880
2881    new_fs.f.source = ls.source.clone();
2882    new_fs.f.maxstacksize = 2;
2883
2884
2885    ls.fs = Some(Box::new(new_fs));
2886
2887    enter_block(ls, false);
2888    Ok(())
2889}
2890
2891/// Finalizes and pops the current FuncState.
2892/// Returns the completed LuaProto.
2893fn close_func(ls: &mut LexState, state: &mut LuaState) -> Result<Box<LuaProto>, LuaError> {
2894    {
2895        let first = {
2896            let fs = ls.fs.as_ref().unwrap();
2897            nvarstack(ls, fs)
2898        };
2899        let line = ls.lastline;
2900        let fs = ls.fs.as_mut().unwrap();
2901        let inst = lua_code::opcodes::Instruction::abck(
2902            lua_code::opcodes::OpCode::Return0,
2903            first as u32,
2904            1,
2905            0,
2906            0,
2907        );
2908        emit_inst(fs, line, inst);
2909    }
2910    leave_block(ls, state)?;
2911    debug_assert!(ls.fs.as_ref().unwrap().bl.is_none());
2912
2913    //                     and needclose, and resolve JMP chains to final target.
2914    cg_finish(ls.fs.as_mut().unwrap());
2915
2916    {
2917        let fs = ls.fs.as_mut().unwrap();
2918        let pc = fs.pc as usize;
2919        let nabslineinfo = fs.nabslineinfo as usize;
2920        let nk = fs.nk as usize;
2921        let np = fs.np as usize;
2922        let ndebugvars = fs.ndebugvars as usize;
2923        let nups = fs.nups as usize;
2924        fs.f.code.truncate(pc);
2925        fs.f.lineinfo.truncate(pc);
2926        fs.f.abslineinfo.truncate(nabslineinfo);
2927        fs.f.k.truncate(nk);
2928        fs.f.p.truncate(np);
2929        fs.f.locvars.truncate(ndebugvars);
2930        fs.f.upvalues.truncate(nups);
2931    }
2932
2933    let mut fs_box = ls.fs.take().unwrap();
2934    ls.fs = fs_box.prev.take();
2935
2936    Ok(fs_box.f)
2937}
2938
2939// ── §8 Grammar rules — block / statement lists ───────────────────────────────
2940
2941/// Returns true if the current token can end a block.
2942fn block_follow(ls: &LexState, withuntil: bool) -> bool {
2943    match ls.t.token {
2944        TK_ELSE | TK_ELSEIF | TK_END | TK_EOS => true,
2945        TK_UNTIL => withuntil,
2946        _ => false,
2947    }
2948}
2949
2950fn statlist(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
2951    while !block_follow(ls, true) {
2952        if ls.t.token == TK_RETURN {
2953            statement(ls, state)?;
2954            return Ok(());
2955        }
2956        statement(ls, state)?;
2957    }
2958    Ok(())
2959}
2960
2961/// Handles '.' NAME or ':' NAME field selection.
2962fn fieldsel(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
2963    let line = ls.lastline;
2964    cg_exp_to_any_reg_up(ls.fs.as_mut().unwrap(), line, v)?;
2965    lex_next(ls, state)?; // skip '.' or ':'
2966    let mut key = ExprDesc::default();
2967    codename(ls, state, &mut key)?;
2968    cg_indexed(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
2969    Ok(())
2970}
2971
2972/// Handles '[' expr ']' indexing.
2973fn yindex(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
2974    lex_next(ls, state)?;
2975    expr(ls, state, v)?;
2976    // TODO(port): lua_code::exp_to_val(ls.fs.as_mut().unwrap(), v)?;
2977    check_next(ls, state, b']' as TokenKind)?;
2978    Ok(())
2979}
2980
2981// ── §9 Constructor rules ─────────────────────────────────────────────────────
2982
2983fn recfield(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
2984    let reg = ls.fs.as_ref().unwrap().freereg as i32;
2985    let mut key = ExprDesc::default();
2986    let mut val = ExprDesc::default();
2987    if ls.t.token == TK_NAME {
2988        let fs = ls.fs.as_ref().unwrap();
2989        check_limit(fs, cc.nh, i32::MAX, "items in a constructor")?;
2990        codename(ls, state, &mut key)?;
2991    } else {
2992        yindex(ls, state, &mut key)?;
2993    }
2994    cc.nh += 1;
2995    check_next(ls, state, b'=' as TokenKind)?;
2996    let mut tab = cc.t.clone();
2997    let line = ls.lastline;
2998    cg_indexed(ls.fs.as_mut().unwrap(), line, &mut tab, &mut key)?;
2999    expr(ls, state, &mut val)?;
3000    cg_storevar(ls.fs.as_mut().unwrap(), line, &tab, &mut val)?;
3001    ls.fs.as_mut().unwrap().freereg = reg as u8;
3002    Ok(())
3003}
3004
3005fn closelistfield(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
3006    let _ = state;
3007    if cc.v.k == ExprKind::Void {
3008        return Ok(());
3009    }
3010    let line = ls.lastline;
3011    cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut cc.v)?;
3012    cc.v.k = ExprKind::Void;
3013    if cc.tostore == LFIELDS_PER_FLUSH {
3014        let t_info = cc.t.u.info;
3015        cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, cc.tostore);
3016        cc.na += cc.tostore;
3017        cc.tostore = 0;
3018    }
3019    Ok(())
3020}
3021
3022fn lastlistfield(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
3023    let _ = state;
3024    if cc.tostore == 0 {
3025        return Ok(());
3026    }
3027    let t_info = cc.t.u.info;
3028    let line = ls.lastline;
3029    if cc.v.k.has_mult_ret() {
3030        cg_set_returns(ls.fs.as_mut().unwrap(), &mut cc.v, LUA_MULTRET);
3031        cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, LUA_MULTRET);
3032        cc.na -= 1;
3033    } else {
3034        if cc.v.k != ExprKind::Void {
3035            cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut cc.v)?;
3036        }
3037        cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, cc.tostore);
3038    }
3039    cc.na += cc.tostore;
3040    Ok(())
3041}
3042
3043fn listfield(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
3044    expr(ls, state, &mut cc.v)?;
3045    cc.tostore += 1;
3046    Ok(())
3047}
3048
3049fn field(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
3050    match ls.t.token {
3051        TK_NAME => {
3052            let next_is_eq = lex_lookahead(ls, state)? == b'=' as TokenKind;
3053            if !next_is_eq {
3054                listfield(ls, state, cc)?;
3055            } else {
3056                recfield(ls, state, cc)?;
3057            }
3058        }
3059        c if c == b'[' as TokenKind => {
3060            recfield(ls, state, cc)?;
3061        }
3062        _ => {
3063            listfield(ls, state, cc)?;
3064        }
3065    }
3066    Ok(())
3067}
3068
3069fn constructor(ls: &mut LexState, state: &mut LuaState, t: &mut ExprDesc) -> Result<(), LuaError> {
3070    let line = ls.lastline;
3071    let pc = cg_emit_newtable(ls.fs.as_mut().unwrap(), line);
3072
3073    let freereg = ls.fs.as_ref().unwrap().freereg as i32;
3074    init_exp(t, ExprKind::NonReloc, freereg);
3075    reserve_regs(ls.fs.as_mut().unwrap(), 1)?;
3076
3077    let mut cc = ConsControl {
3078        v: ExprDesc::default(),
3079        t: t.clone(),
3080        nh: 0,
3081        na: 0,
3082        tostore: 0,
3083    };
3084
3085    check_next(ls, state, b'{' as TokenKind)?;
3086    loop {
3087        debug_assert!(cc.v.k == ExprKind::Void || cc.tostore > 0);
3088        if ls.t.token == b'}' as TokenKind {
3089            break;
3090        }
3091        closelistfield(ls, state, &mut cc)?;
3092        field(ls, state, &mut cc)?;
3093        if !test_next(ls, state, b',' as TokenKind)?
3094            && !test_next(ls, state, b';' as TokenKind)?
3095        {
3096            break;
3097        }
3098    }
3099    check_match(ls, state, b'}' as TokenKind, b'{' as TokenKind, line)?;
3100    lastlistfield(ls, state, &mut cc)?;
3101
3102    let t_info = t.u.info;
3103    cg_settablesize(ls.fs.as_mut().unwrap(), pc, t_info, cc.na, cc.nh);
3104    Ok(())
3105}
3106
3107// ── §10 Parameter list and function body ─────────────────────────────────────
3108
3109fn setvararg(fs: &mut FuncState, _state: &mut LuaState, nparams: i32) -> Result<(), LuaError> {
3110    fs.f.is_vararg = true;
3111    let inst = lua_code::opcodes::Instruction::abck(
3112        lua_code::opcodes::OpCode::VarArgPrep,
3113        nparams as u32,
3114        0, 0, 0,
3115    );
3116    let line = fs.previousline;
3117    emit_inst(fs, line, inst);
3118    Ok(())
3119}
3120
3121fn parlist(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
3122    let mut nparams: i32 = 0;
3123    let mut isvararg = false;
3124    if ls.t.token != b')' as TokenKind {
3125        loop {
3126            match ls.t.token {
3127                TK_NAME => {
3128                    let name = str_check_name(ls, state)?;
3129                    new_local_var(ls, state, name)?;
3130                    nparams += 1;
3131                }
3132                TK_DOTS => {
3133                    lex_next(ls, state)?;
3134                    isvararg = true;
3135                }
3136                _ => {
3137                    return Err(LuaError::syntax(format_args!("<name> or '...' expected")));
3138                }
3139            }
3140            if isvararg || !test_next(ls, state, b',' as TokenKind)? {
3141                break;
3142            }
3143        }
3144    }
3145    adjust_local_vars(ls, state, nparams)?;
3146    let numparams = ls.fs.as_ref().unwrap().nactvar;
3147    ls.fs.as_mut().unwrap().f.numparams = numparams;
3148    if isvararg {
3149        setvararg(ls.fs.as_mut().unwrap(), state, numparams as i32)?;
3150    }
3151    let nactvar = ls.fs.as_ref().unwrap().nactvar as i32;
3152    reserve_regs(ls.fs.as_mut().unwrap(), nactvar)?;
3153    Ok(())
3154}
3155
3156fn check_match(
3157    ls: &mut LexState,
3158    state: &mut LuaState,
3159    what: TokenKind,
3160    who: TokenKind,
3161    where_line: i32,
3162) -> Result<(), LuaError> {
3163    if !test_next(ls, state, what)? {
3164        if where_line == ls.linenumber {
3165            return Err(error_expected(ls, what));
3166        } else {
3167            let what_str = lua_lex::token2str(&ls.lex, what);
3168            let who_str = lua_lex::token2str(&ls.lex, who);
3169            let mut msg: Vec<u8> = Vec::new();
3170            msg.extend_from_slice(&what_str);
3171            msg.extend_from_slice(b" expected (to close ");
3172            msg.extend_from_slice(&who_str);
3173            use std::io::Write as _;
3174            let _ = write!(msg, " at line {})", where_line);
3175            return Err(lua_lex::syntax_error(&mut ls.lex, &msg));
3176        }
3177    }
3178    Ok(())
3179}
3180
3181fn body(
3182    ls: &mut LexState,
3183    state: &mut LuaState,
3184    e: &mut ExprDesc,
3185    ismethod: bool,
3186    line: i32,
3187) -> Result<(), LuaError> {
3188    let new_proto = add_prototype(ls, state)?;
3189    let mut new_fs = FuncState {
3190        f: new_proto,
3191        prev: None,
3192        bl: None,
3193        pc: 0,
3194        lasttarget: 0,
3195        previousline: line,
3196        nk: 0,
3197        np: 0,
3198        nabslineinfo: 0,
3199        firstlocal: 0,
3200        firstlabel: 0,
3201        ndebugvars: 0,
3202        nactvar: 0,
3203        nups: 0,
3204        freereg: 0,
3205        iwthabs: 0,
3206        needclose: false,
3207        last_token_line: ls.lastline,
3208    };
3209    new_fs.f.linedefined = line;
3210    open_func(ls, state, new_fs)?;
3211
3212    check_next(ls, state, b'(' as TokenKind)?;
3213    if ismethod {
3214        let self_str = state.intern_str(b"self")?;
3215        new_local_var(ls, state, self_str)?;
3216        adjust_local_vars(ls, state, 1)?;
3217    }
3218    parlist(ls, state)?;
3219    check_next(ls, state, b')' as TokenKind)?;
3220    statlist(ls, state)?;
3221    ls.fs.as_mut().unwrap().f.lastlinedefined = ls.linenumber;
3222    check_match(ls, state, TK_END, TK_FUNCTION, line)?;
3223    codeclosure(ls, state, e)?;
3224    let inner_proto = close_func(ls, state)?;
3225    let parent = ls.fs.as_mut().expect("body: close_func left no parent FuncState");
3226    let slot = (parent.np - 1) as usize;
3227    if parent.f.p.len() <= slot {
3228        parent.f.p.resize_with(slot + 1, || GcRef::new(LuaProto::placeholder()));
3229    }
3230    parent.f.p[slot] = GcRef::new(*inner_proto);
3231    Ok(())
3232}
3233
3234// ── §11 Expression list and function arguments ────────────────────────────────
3235
3236fn explist(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<i32, LuaError> {
3237    let mut n = 1;
3238    expr(ls, state, v)?;
3239    while test_next(ls, state, b',' as TokenKind)? {
3240        let line = ls.lastline;
3241        cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, v)?;
3242        expr(ls, state, v)?;
3243        n += 1;
3244    }
3245    Ok(n)
3246}
3247
3248fn funcargs(ls: &mut LexState, state: &mut LuaState, f: &mut ExprDesc) -> Result<(), LuaError> {
3249    let mut args = ExprDesc::default();
3250    // BEFORE consuming, so the OP_CALL/etc emissions attribute to the call site.
3251    // errors.lua tests `a\n(\n23)` expects error at line of `(`, not line of `a`.
3252    let line = ls.linenumber;
3253    match ls.t.token {
3254        c if c == b'(' as TokenKind => {
3255            lex_next(ls, state)?; // skip '('
3256            if ls.t.token == b')' as TokenKind {
3257                args.k = ExprKind::Void;
3258            } else {
3259                explist(ls, state, &mut args)?;
3260                if args.k.has_mult_ret() {
3261                    // Call/VarArg to produce LUA_MULTRET so all of its return
3262                    // values become arguments to the enclosing call.
3263                    cg_set_returns(ls.fs.as_mut().unwrap(), &mut args, LUA_MULTRET);
3264                }
3265            }
3266            check_match(ls, state, b')' as TokenKind, b'(' as TokenKind, line)?;
3267        }
3268        c if c == b'{' as TokenKind => {
3269            constructor(ls, state, &mut args)?;
3270        }
3271        TK_STRING => {
3272            let s = ls.t.seminfo.ts.clone()
3273                .ok_or_else(|| LuaError::syntax(format_args!("string expected")))?;
3274            codestring(&mut args, s);
3275            lex_next(ls, state)?;
3276        }
3277        _ => {
3278            return Err(LuaError::syntax(format_args!("function arguments expected")));
3279        }
3280    }
3281    debug_assert!(f.k == ExprKind::NonReloc);
3282    let base = f.u.info;
3283    let nparams: i32 = if args.k.has_mult_ret() {
3284        // TODO(port): luaK_setmultret for VVarArg / VCall args; only single
3285        // non-multret args are supported by the bootstrap codegen.
3286        LUA_MULTRET
3287    } else {
3288        if args.k != ExprKind::Void {
3289            cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut args)?;
3290        }
3291        ls.fs.as_ref().unwrap().freereg as i32 - (base + 1)
3292    };
3293    let call_inst = lua_code::opcodes::Instruction::abck(
3294        lua_code::opcodes::OpCode::Call,
3295        base as u32,
3296        (nparams + 1) as u32,
3297        2,
3298        0,
3299    );
3300    let call_pc = emit_inst(ls.fs.as_mut().unwrap(), line, call_inst);
3301    init_exp(f, ExprKind::Call, call_pc);
3302    ls.fs.as_mut().unwrap().freereg = base as u8 + 1;
3303    Ok(())
3304}
3305
3306// ── §12 Expression parsing ────────────────────────────────────────────────────
3307
3308fn primaryexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
3309    match ls.t.token {
3310        c if c == b'(' as TokenKind => {
3311            let line = ls.lastline;
3312            lex_next(ls, state)?;
3313            expr(ls, state, v)?;
3314            check_match(ls, state, b')' as TokenKind, b'(' as TokenKind, line)?;
3315            cg_discharge_vars(ls.fs.as_mut().unwrap(), line, v)?;
3316        }
3317        TK_NAME => {
3318            singlevar(ls, state, v)?;
3319        }
3320        _ => {
3321            return Err(lua_lex::syntax_error(&mut ls.lex, b"unexpected symbol"));
3322        }
3323    }
3324    Ok(())
3325}
3326
3327fn suffixedexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
3328    primaryexp(ls, state, v)?;
3329    loop {
3330        match ls.t.token {
3331            c if c == b'.' as TokenKind => {
3332                fieldsel(ls, state, v)?;
3333            }
3334            c if c == b'[' as TokenKind => {
3335                let mut key = ExprDesc::default();
3336                let line = ls.lastline;
3337                cg_exp_to_any_reg_up(ls.fs.as_mut().unwrap(), line, v)?;
3338                yindex(ls, state, &mut key)?;
3339                cg_indexed(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
3340            }
3341            c if c == b':' as TokenKind => {
3342                let mut key = ExprDesc::default();
3343                lex_next(ls, state)?;
3344                codename(ls, state, &mut key)?;
3345                let line = ls.lastline;
3346                cg_self(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
3347                funcargs(ls, state, v)?;
3348            }
3349            c if c == b'(' as TokenKind || c == TK_STRING || c == b'{' as TokenKind => {
3350                let line = ls.lastline;
3351                cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, v)?;
3352                funcargs(ls, state, v)?;
3353            }
3354            _ => return Ok(()),
3355        }
3356    }
3357}
3358
3359fn simpleexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
3360    match ls.t.token {
3361        TK_FLT => {
3362            init_exp(v, ExprKind::KFlt, 0);
3363            v.u.nval = ls.t.seminfo.r;
3364        }
3365        TK_INT => {
3366            init_exp(v, ExprKind::KInt, 0);
3367            v.u.ival = ls.t.seminfo.i;
3368        }
3369        TK_STRING => {
3370            let s = ls.t.seminfo.ts.clone()
3371                .ok_or_else(|| LuaError::syntax(format_args!("string value missing")))?;
3372            codestring(v, s);
3373        }
3374        TK_NIL => {
3375            init_exp(v, ExprKind::Nil, 0);
3376        }
3377        TK_TRUE => {
3378            init_exp(v, ExprKind::True, 0);
3379        }
3380        TK_FALSE => {
3381            init_exp(v, ExprKind::False, 0);
3382        }
3383        TK_DOTS => {
3384            let is_vararg = ls.fs.as_ref().unwrap().f.is_vararg;
3385            if !is_vararg {
3386                return Err(LuaError::syntax(format_args!(
3387                    "cannot use '...' outside a vararg function"
3388                )));
3389            }
3390            let line = ls.lastline;
3391            let inst = lua_code::opcodes::Instruction::abck(
3392                lua_code::opcodes::OpCode::VarArg,
3393                0,
3394                0,
3395                1,
3396                0,
3397            );
3398            let pc = emit_inst(ls.fs.as_mut().unwrap(), line, inst);
3399            init_exp(v, ExprKind::VarArg, pc);
3400        }
3401        c if c == b'{' as TokenKind => {
3402            constructor(ls, state, v)?;
3403            return Ok(());
3404        }
3405        TK_FUNCTION => {
3406            lex_next(ls, state)?;
3407            let line = ls.lastline;
3408            body(ls, state, v, false, line)?;
3409            return Ok(());
3410        }
3411        _ => {
3412            suffixedexp(ls, state, v)?;
3413            return Ok(());
3414        }
3415    }
3416    lex_next(ls, state)?;
3417    Ok(())
3418}
3419
3420fn getunopr(op: TokenKind) -> UnOpr {
3421    match op {
3422        TK_NOT => UnOpr::Not,
3423        c if c == b'-' as TokenKind => UnOpr::Minus,
3424        c if c == b'~' as TokenKind => UnOpr::BNot,
3425        c if c == b'#' as TokenKind => UnOpr::Len,
3426        _ => UnOpr::NoUnOpr,
3427    }
3428}
3429
3430fn getbinopr(op: TokenKind) -> BinOpr {
3431    match op {
3432        c if c == b'+' as TokenKind => BinOpr::Add,
3433        c if c == b'-' as TokenKind => BinOpr::Sub,
3434        c if c == b'*' as TokenKind => BinOpr::Mul,
3435        c if c == b'%' as TokenKind => BinOpr::Mod,
3436        c if c == b'^' as TokenKind => BinOpr::Pow,
3437        c if c == b'/' as TokenKind => BinOpr::Div,
3438        TK_IDIV => BinOpr::IDiv,
3439        c if c == b'&' as TokenKind => BinOpr::BAnd,
3440        c if c == b'|' as TokenKind => BinOpr::BOr,
3441        c if c == b'~' as TokenKind => BinOpr::BXor,
3442        TK_SHL => BinOpr::Shl,
3443        TK_SHR => BinOpr::Shr,
3444        TK_CONCAT => BinOpr::Concat,
3445        TK_NE => BinOpr::Ne,
3446        TK_EQ => BinOpr::Eq,
3447        c if c == b'<' as TokenKind => BinOpr::Lt,
3448        TK_LE => BinOpr::Le,
3449        c if c == b'>' as TokenKind => BinOpr::Gt,
3450        TK_GE => BinOpr::Ge,
3451        TK_AND => BinOpr::And,
3452        TK_OR => BinOpr::Or,
3453        _ => BinOpr::NoBinOpr,
3454    }
3455}
3456
3457/// Parses a sub-expression with operators of priority > `limit`.
3458/// Returns the first untreated (lower-priority) operator.
3459fn subexpr(
3460    ls: &mut LexState,
3461    state: &mut LuaState,
3462    v: &mut ExprDesc,
3463    limit: i32,
3464) -> Result<BinOpr, LuaError> {
3465    enter_level(ls)?;
3466
3467    let uop = getunopr(ls.t.token);
3468    if uop != UnOpr::NoUnOpr {
3469        // so this is the operator's own line, not the prior token's.
3470        let line = ls.linenumber;
3471        lex_next(ls, state)?; // skip unary operator
3472        subexpr(ls, state, v, UNARY_PRIORITY)?;
3473        cg_prefix(ls.fs.as_mut().unwrap(), uop, v, line)?;
3474    } else {
3475        simpleexp(ls, state, v)?;
3476    }
3477
3478    let mut op = getbinopr(ls.t.token);
3479    while op != BinOpr::NoBinOpr && PRIORITY[op as usize].0 as i32 > limit {
3480        let mut v2 = ExprDesc::default();
3481        // errors.lua's `lineerror` cases check that runtime arith errors are
3482        // attributed to the operator's line, not the operand's.
3483        let line = ls.linenumber;
3484        lex_next(ls, state)?;
3485        cg_infix(ls.fs.as_mut().unwrap(), op, v, line)?;
3486        let nextop = subexpr(ls, state, &mut v2, PRIORITY[op as usize].1 as i32)?;
3487        cg_posfix_fold(ls.fs.as_mut().unwrap(), op, v, &mut v2, line)?;
3488        op = nextop;
3489    }
3490
3491    leave_level(ls);
3492    Ok(op)
3493}
3494
3495fn expr(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
3496    subexpr(ls, state, v, 0)?;
3497    Ok(())
3498}
3499
3500// ── §13 Statement rules ───────────────────────────────────────────────────────
3501
3502fn block(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
3503    enter_block(ls, false);
3504    statlist(ls, state)?;
3505    leave_block(ls, state)?;
3506    Ok(())
3507}
3508
3509/// Checks and fixes register/upvalue conflicts in multi-assignment.
3510///
3511/// When a non-indexed LHS variable `v` also appears as the table or key in an
3512/// indexed LHS variable, the indexed entry must be redirected to a copy made
3513/// before any assignments occur. For an upvalue table that becomes a register
3514/// copy, the ExprKind is changed from IndexUp to IndexStr so cg_storevar emits
3515/// SETFIELD (register table) instead of SETTABUP (upvalue table).
3516fn check_conflict(
3517    ls: &mut LexState,
3518    _state: &mut LuaState,
3519    lh: &mut LhsAssign,
3520    v: &ExprDesc,
3521) -> Result<(), LuaError> {
3522    let extra = ls.fs.as_ref().unwrap().freereg as i32;
3523    let line = ls.lastline;
3524    let mut conflict = false;
3525
3526    conflict |= check_one_lhs_entry(&mut lh.v, v, extra);
3527    let mut prev = lh.prev.as_deref_mut();
3528    while let Some(node) = prev {
3529        conflict |= check_one_lhs_entry(&mut node.v, v, extra);
3530        prev = node.prev.as_deref_mut();
3531    }
3532
3533    if conflict {
3534        let fs = ls.fs.as_mut().unwrap();
3535        let inst = if v.k == ExprKind::Local {
3536            lua_code::opcodes::Instruction::abck(
3537                lua_code::opcodes::OpCode::Move,
3538                extra as u32, v.u.var_ridx as u32, 0, 0,
3539            )
3540        } else {
3541            lua_code::opcodes::Instruction::abck(
3542                lua_code::opcodes::OpCode::GetUpVal,
3543                extra as u32, v.u.info as u32, 0, 0,
3544            )
3545        };
3546        emit_inst(fs, line, inst);
3547        reserve_regs(fs, 1)?;
3548    }
3549    Ok(())
3550}
3551
3552fn check_one_lhs_entry(entry: &mut ExprDesc, v: &ExprDesc, extra: i32) -> bool {
3553    if !entry.k.is_indexed() {
3554        return false;
3555    }
3556    let mut found = false;
3557    if entry.k == ExprKind::IndexUp {
3558        if v.k == ExprKind::UpVal && entry.u.ind_t == v.u.info as u8 {
3559            found = true;
3560            entry.k = ExprKind::IndexStr;
3561            entry.u.ind_t = extra as u8;
3562        }
3563    } else {
3564        if v.k == ExprKind::Local && entry.u.ind_t == v.u.var_ridx {
3565            found = true;
3566            entry.u.ind_t = extra as u8;
3567        }
3568        if entry.k == ExprKind::Indexed
3569            && v.k == ExprKind::Local
3570            && entry.u.ind_idx == v.u.var_ridx as i16
3571        {
3572            found = true;
3573            entry.u.ind_idx = extra as i16;
3574        }
3575    }
3576    found
3577}
3578
3579fn restassign(
3580    ls: &mut LexState,
3581    state: &mut LuaState,
3582    lh: &mut LhsAssign,
3583    nvars: i32,
3584) -> Result<(), LuaError> {
3585    if !lh.v.k.is_var() {
3586        return Err(lua_lex::syntax_error(&mut ls.lex, b"syntax error"));
3587    }
3588    check_readonly(ls, state, &lh.v.clone())?;
3589
3590    if test_next(ls, state, b',' as TokenKind)? {
3591        let mut nv_assign = LhsAssign {
3592            prev: None, // We don't link here — Phase B restructures
3593            v: ExprDesc::default(),
3594        };
3595        suffixedexp(ls, state, &mut nv_assign.v)?;
3596        if !nv_assign.v.k.is_indexed() {
3597            check_conflict(ls, state, lh, &nv_assign.v.clone())?;
3598        }
3599        enter_level(ls)?;
3600        restassign(ls, state, &mut nv_assign, nvars + 1)?;
3601        leave_level(ls);
3602    } else {
3603        let mut e = ExprDesc::default();
3604        check_next(ls, state, b'=' as TokenKind)?;
3605        let nexps = explist(ls, state, &mut e)?;
3606        if nexps != nvars {
3607            adjust_assign(ls, state, nvars, nexps, &mut e)?;
3608        } else {
3609            let line = ls.lastline;
3610            let fs = ls.fs.as_mut().unwrap();
3611            cg_set_one_ret(fs, &mut e);
3612            cg_storevar(fs, line, &lh.v, &mut e)?;
3613            return Ok(());
3614        }
3615    }
3616    let line = ls.lastline;
3617    let fs = ls.fs.as_mut().unwrap();
3618    let freereg = fs.freereg as i32 - 1;
3619    let mut e = ExprDesc::default();
3620    init_exp(&mut e, ExprKind::NonReloc, freereg);
3621    cg_storevar(fs, line, &lh.v, &mut e)?;
3622    Ok(())
3623}
3624
3625/// Parses a condition expression; returns its 'exit when false' patch list.
3626fn cond(ls: &mut LexState, state: &mut LuaState) -> Result<i32, LuaError> {
3627    let mut v = ExprDesc::default();
3628    expr(ls, state, &mut v)?;
3629    if v.k == ExprKind::Nil {
3630        v.k = ExprKind::False;
3631    }
3632    let line = ls.lastline;
3633    cg_go_if_true(ls.fs.as_mut().unwrap(), line, &mut v)?;
3634    Ok(v.f)
3635}
3636
3637fn gotostat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
3638    let line = ls.lastline;
3639    let name = str_check_name(ls, state)?;
3640    let lb = findlabel(ls, &name);
3641    if lb.is_none() {
3642        let pc = cg_jump(ls.fs.as_mut().unwrap(), line);
3643        new_goto_entry(ls, state, name, line, pc)?;
3644    } else {
3645        let lb_idx = lb.unwrap();
3646        let lb_pc = ls.dyd.label[lb_idx].pc;
3647        let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
3648        let lblevel = reg_level(ls, ls.fs.as_ref().unwrap(), lb_nactvar as i32);
3649        let cur_nvarstack = {
3650            let fs = ls.fs.as_ref().unwrap();
3651            nvarstack(ls, fs)
3652        };
3653        if cur_nvarstack > lblevel {
3654            let inst = lua_code::opcodes::Instruction::abck(
3655                lua_code::opcodes::OpCode::Close,
3656                lblevel as u32,
3657                0,
3658                0,
3659                0,
3660            );
3661            emit_inst(ls.fs.as_mut().unwrap(), line, inst);
3662        }
3663        let jpc = cg_jump(ls.fs.as_mut().unwrap(), line);
3664        cg_patch_list(ls.fs.as_mut().unwrap(), jpc, lb_pc)?;
3665    }
3666    Ok(())
3667}
3668
3669fn breakstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
3670    let line = ls.lastline;
3671    lex_next(ls, state)?;
3672    let break_str = state.intern_str(b"break")?;
3673    let pc = cg_jump(ls.fs.as_mut().unwrap(), line);
3674    new_goto_entry(ls, state, break_str, line, pc)?;
3675    Ok(())
3676}
3677
3678fn checkrepeated(ls: &LexState, name: &GcRef<LuaString>) -> Result<(), LuaError> {
3679    if let Some(lb_idx) = findlabel(ls, name) {
3680        let name_str = String::from_utf8_lossy(name.as_bytes());
3681        let line = ls.dyd.label[lb_idx].line;
3682        return Err(LuaError::syntax(format_args!(
3683            "label '{}' already defined on line {}", name_str, line
3684        )));
3685    }
3686    Ok(())
3687}
3688
3689fn labelstat(
3690    ls: &mut LexState,
3691    state: &mut LuaState,
3692    name: GcRef<LuaString>,
3693    line: i32,
3694) -> Result<(), LuaError> {
3695    check_next(ls, state, TK_DBCOLON)?;
3696    while ls.t.token == b';' as TokenKind || ls.t.token == TK_DBCOLON {
3697        statement(ls, state)?;
3698    }
3699    checkrepeated(ls, &name)?;
3700    let is_last = block_follow(ls, false);
3701    createlabel(ls, state, name, line, is_last)?;
3702    Ok(())
3703}
3704
3705fn whilestat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
3706    lex_next(ls, state)?;
3707    let whileinit = cg_get_label(ls.fs.as_mut().unwrap());
3708    let condexit = cond(ls, state)?;
3709    enter_block(ls, true);
3710    check_next(ls, state, TK_DO)?;
3711    block(ls, state)?;
3712    // Use `lastline` (line of the just-parsed body's last token) rather than
3713    // `linenumber` (which has already advanced to END) so the back-jump's
3714    // line attribution matches lua-c's bytecode and the line hook does not
3715    // spuriously fire for the END line on every iteration.
3716    let back = cg_jump(ls.fs.as_mut().unwrap(), ls.lastline);
3717    cg_patch_list(ls.fs.as_mut().unwrap(), back, whileinit)?;
3718    check_match(ls, state, TK_END, TK_WHILE, line)?;
3719    leave_block(ls, state)?;
3720    cg_patch_to_here(ls.fs.as_mut().unwrap(), condexit)?;
3721    Ok(())
3722}
3723
3724fn repeatstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
3725    let repeat_init = cg_get_label(ls.fs.as_mut().unwrap());
3726    enter_block(ls, true);
3727    enter_block(ls, false);
3728    lex_next(ls, state)?;
3729    statlist(ls, state)?;
3730    check_match(ls, state, TK_UNTIL, TK_REPEAT, line)?;
3731    let condexit = cond(ls, state)?;
3732
3733    let bl2_upval = ls.fs.as_ref().unwrap().bl.as_ref().unwrap().upval;
3734    let bl2_nactvar = ls.fs.as_ref().unwrap().bl.as_ref().unwrap().nactvar as i32;
3735    leave_block(ls, state)?;
3736
3737    let mut condexit = condexit;
3738    if bl2_upval {
3739        let exit = cg_jump(ls.fs.as_mut().unwrap(), line);
3740        cg_patch_to_here(ls.fs.as_mut().unwrap(), condexit)?;
3741        let close_level = reg_level(ls, ls.fs.as_ref().unwrap(), bl2_nactvar) as u32;
3742        let close_inst = lua_code::opcodes::Instruction::abck(
3743            lua_code::opcodes::OpCode::Close,
3744            close_level,
3745            0,
3746            0,
3747            0,
3748        );
3749        emit_inst(ls.fs.as_mut().unwrap(), line, close_inst);
3750        condexit = cg_jump(ls.fs.as_mut().unwrap(), line);
3751        cg_patch_to_here(ls.fs.as_mut().unwrap(), exit)?;
3752    }
3753    cg_patch_list(ls.fs.as_mut().unwrap(), condexit, repeat_init)?;
3754    leave_block(ls, state)?;
3755    Ok(())
3756}
3757
3758/// Parse an expression and emit it to the next register.
3759fn exp1(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
3760    let mut e = ExprDesc::default();
3761    expr(ls, state, &mut e)?;
3762    let line = ls.lastline;
3763    cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut e)?;
3764    debug_assert!(e.k == ExprKind::NonReloc);
3765    Ok(())
3766}
3767
3768fn fixforjump(fs: &mut FuncState, pc: i32, dest: i32, back: bool) -> Result<(), LuaError> {
3769    let mut offset = dest - (pc + 1);
3770    if back {
3771        offset = -offset;
3772    }
3773    if offset > MAXARG_BX {
3774        return Err(LuaError::syntax(format_args!("control structure too long")));
3775    }
3776    let raw = fs.f.code[pc as usize].0;
3777    let mut inst = lua_code::opcodes::Instruction(raw);
3778    inst.set_arg_bx(offset as u32);
3779    fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(inst.0);
3780    Ok(())
3781}
3782
3783fn forbody(
3784    ls: &mut LexState,
3785    state: &mut LuaState,
3786    base: i32,
3787    line: i32,
3788    nvars: i32,
3789    isgen: bool,
3790) -> Result<(), LuaError> {
3791    check_next(ls, state, TK_DO)?;
3792    let prep_op = if isgen { OpCode::TForPrep } else { OpCode::ForPrep };
3793    let prep = {
3794        let fs = ls.fs.as_mut().unwrap();
3795        let inst = lua_code::opcodes::Instruction::abx(prep_op, base as u32, 0);
3796        emit_inst(fs, line, inst)
3797    };
3798
3799    enter_block(ls, false);
3800    adjust_local_vars(ls, state, nvars)?;
3801    reserve_regs(ls.fs.as_mut().unwrap(), nvars)?;
3802    block(ls, state)?;
3803    leave_block(ls, state)?;
3804
3805    let label_pc = ls.fs.as_ref().unwrap().pc;
3806    fixforjump(ls.fs.as_mut().unwrap(), prep, label_pc, false)?;
3807
3808    if isgen {
3809        let fs = ls.fs.as_mut().unwrap();
3810        let inst = lua_code::opcodes::Instruction::abck(
3811            OpCode::TForCall, base as u32, 0, nvars as u32, 0,
3812        );
3813        emit_inst(fs, line, inst);
3814    }
3815    let loop_op = if isgen { OpCode::TForLoop } else { OpCode::ForLoop };
3816    let endfor = {
3817        let fs = ls.fs.as_mut().unwrap();
3818        let inst = lua_code::opcodes::Instruction::abx(loop_op, base as u32, 0);
3819        emit_inst(fs, line, inst)
3820    };
3821    fixforjump(ls.fs.as_mut().unwrap(), endfor, prep + 1, true)?;
3822    Ok(())
3823}
3824
3825fn fornum(
3826    ls: &mut LexState,
3827    state: &mut LuaState,
3828    varname: GcRef<LuaString>,
3829    line: i32,
3830) -> Result<(), LuaError> {
3831    let base = ls.fs.as_ref().unwrap().freereg as i32;
3832    let for_state_str = state.intern_str(b"(for state)")?;
3833    new_local_var(ls, state, for_state_str.clone())?;
3834    new_local_var(ls, state, for_state_str.clone())?;
3835    new_local_var(ls, state, for_state_str)?;
3836    let ctrl_vidx = new_local_var(ls, state, varname)?;
3837    // Lua 5.5: the numeric for-loop control variable is read-only — assigning
3838    // to it is a compile error. The FORLOOP opcode still updates the register
3839    // directly, so loop progress is unaffected. (No effect on pre-5.5.)
3840    if state.global().lua_version == lua_types::LuaVersion::V55 {
3841        let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
3842        get_local_var_desc_mut(ls, firstlocal, ctrl_vidx).kind = VarKind::Const;
3843    }
3844    check_next(ls, state, b'=' as TokenKind)?;
3845    exp1(ls, state)?; // initial value
3846    check_next(ls, state, b',' as TokenKind)?;
3847    exp1(ls, state)?; // limit
3848    if test_next(ls, state, b',' as TokenKind)? {
3849        exp1(ls, state)?; // optional step
3850    } else {
3851        let fs = ls.fs.as_mut().unwrap();
3852        let reg = fs.freereg as u32;
3853        let bx = (1i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
3854        let inst = lua_code::opcodes::Instruction::abx(
3855            lua_code::opcodes::OpCode::LoadI, reg, bx,
3856        );
3857        emit_inst(fs, line, inst);
3858        reserve_regs(fs, 1)?;
3859    }
3860    adjust_local_vars(ls, state, 3)?; // control variables
3861    forbody(ls, state, base, line, 1, false)?;
3862    Ok(())
3863}
3864
3865fn forlist(
3866    ls: &mut LexState,
3867    state: &mut LuaState,
3868    indexname: GcRef<LuaString>,
3869) -> Result<(), LuaError> {
3870    let mut nvars: i32 = 5; // gen, state, control, toclose, 'indexname'
3871    let base = ls.fs.as_ref().unwrap().freereg as i32;
3872    let for_state_str = state.intern_str(b"(for state)")?;
3873    new_local_var(ls, state, for_state_str.clone())?;
3874    new_local_var(ls, state, for_state_str.clone())?;
3875    new_local_var(ls, state, for_state_str.clone())?;
3876    new_local_var(ls, state, for_state_str)?;
3877    let idx_vidx = new_local_var(ls, state, indexname)?;
3878    // Lua 5.5: the first control variable of a generic for is read-only (the
3879    // remaining loop variables stay assignable).
3880    if state.global().lua_version == lua_types::LuaVersion::V55 {
3881        let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
3882        get_local_var_desc_mut(ls, firstlocal, idx_vidx).kind = VarKind::Const;
3883    }
3884    while test_next(ls, state, b',' as TokenKind)? {
3885        let extra_name = str_check_name(ls, state)?;
3886        new_local_var(ls, state, extra_name)?;
3887        nvars += 1;
3888    }
3889    check_next(ls, state, TK_IN)?;
3890    // After `in`, linenumber is the line of the operand — used for the
3891    // for-in control instructions so runtime errors point at the operand,
3892    // not the `in` keyword. errors.lua:401 depends on this.
3893    let line = ls.linenumber;
3894    let mut e = ExprDesc::default();
3895    let nexps = explist(ls, state, &mut e)?;
3896    adjust_assign(ls, state, 4, nexps, &mut e)?;
3897    adjust_local_vars(ls, state, 4)?;
3898    marktobeclosed(ls.fs.as_mut().unwrap()); // last control var must be closed
3899    // TODO(port): lua_code::check_stack(ls.fs.as_mut().unwrap(), 3)?;
3900    forbody(ls, state, base, line, nvars - 4, true)?;
3901    Ok(())
3902}
3903
3904fn forstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
3905    enter_block(ls, true); // scope for loop and control variables
3906    lex_next(ls, state)?;
3907    let varname = str_check_name(ls, state)?;
3908    match ls.t.token {
3909        c if c == b'=' as TokenKind => fornum(ls, state, varname, line)?,
3910        c if c == b',' as TokenKind || c == TK_IN => forlist(ls, state, varname)?,
3911        _ => {
3912            return Err(LuaError::syntax(format_args!("'=' or 'in' expected")));
3913        }
3914    }
3915    check_match(ls, state, TK_END, TK_FOR, line)?;
3916    leave_block(ls, state)?; // loop scope ('break' jumps to this point)
3917    Ok(())
3918}
3919
3920fn test_then_block(
3921    ls: &mut LexState,
3922    state: &mut LuaState,
3923    escapelist: &mut i32,
3924) -> Result<(), LuaError> {
3925    lex_next(ls, state)?;
3926    let mut v = ExprDesc::default();
3927    expr(ls, state, &mut v)?;
3928    check_next(ls, state, TK_THEN)?;
3929
3930    let jf: i32;
3931    if ls.t.token == TK_BREAK {
3932        let line = ls.lastline;
3933        cg_go_if_false(ls.fs.as_mut().unwrap(), line, &mut v)?;
3934        lex_next(ls, state)?; // skip 'break'
3935        enter_block(ls, false);
3936        let break_str = state.intern_str(b"break")?;
3937        new_goto_entry(ls, state, break_str, line, v.t)?;
3938        while test_next(ls, state, b';' as TokenKind)? {}
3939        if block_follow(ls, false) {
3940            leave_block(ls, state)?;
3941            return Ok(());
3942        } else {
3943            jf = cg_jump(ls.fs.as_mut().unwrap(), ls.linenumber);
3944        }
3945    } else {
3946        let line = ls.lastline;
3947        cg_go_if_true(ls.fs.as_mut().unwrap(), line, &mut v)?;
3948        enter_block(ls, false);
3949        jf = v.f;
3950    }
3951
3952    statlist(ls, state)?;
3953    leave_block(ls, state)?;
3954
3955    if ls.t.token == TK_ELSE || ls.t.token == TK_ELSEIF {
3956        let line = ls.lastline;
3957        let j = cg_jump(ls.fs.as_mut().unwrap(), line);
3958        cg_concat(ls.fs.as_mut().unwrap(), escapelist, j)?;
3959    }
3960    cg_patch_to_here(ls.fs.as_mut().unwrap(), jf)?;
3961    Ok(())
3962}
3963
3964fn ifstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
3965    let mut escapelist = NO_JUMP;
3966    test_then_block(ls, state, &mut escapelist)?; // IF cond THEN block
3967    while ls.t.token == TK_ELSEIF {
3968        test_then_block(ls, state, &mut escapelist)?;
3969    }
3970    if test_next(ls, state, TK_ELSE)? {
3971        block(ls, state)?;
3972    }
3973    check_match(ls, state, TK_END, TK_IF, line)?;
3974    cg_patch_to_here(ls.fs.as_mut().unwrap(), escapelist)?;
3975    Ok(())
3976}
3977
3978fn localfunc(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
3979    let mut b = ExprDesc::default();
3980    let _fvar = ls.fs.as_ref().unwrap().nactvar as i32;
3981    let name = str_check_name(ls, state)?;
3982    new_local_var(ls, state, name)?;
3983    adjust_local_vars(ls, state, 1)?; // enter its scope
3984    let line = ls.lastline;
3985    body(ls, state, &mut b, false, line)?;
3986    let _pc = ls.fs.as_ref().unwrap().pc;
3987    // TODO(port): local_debug_info(ls, ls.fs.as_mut().unwrap(), fvar).map(|lv| lv.startpc = pc);
3988    Ok(())
3989}
3990
3991/// Whether the active Lua version supports `<const>`/`<close>` local-variable
3992/// attributes. True for 5.4 and 5.5; false for 5.1/5.2/5.3.
3993fn version_has_attributes(state: &LuaState) -> bool {
3994    use lua_types::LuaVersion;
3995    matches!(
3996        state.global().lua_version,
3997        LuaVersion::V54 | LuaVersion::V55
3998    )
3999}
4000
4001/// Parses an optional '<const>' or '<close>' attribute.
4002///
4003/// The `<const>`/`<close>` attribute syntax is a Lua 5.4 addition (5.4 §8.1,
4004/// `specs/research/5.3-upstream-delta.md` delta #7). Under Lua 5.3 the `<`
4005/// after a local name is not an attribute opener at all — it is left
4006/// unconsumed so the surrounding statement reports it as an unexpected symbol,
4007/// exactly as the 5.3 parser does. Versions are gated on
4008/// [`lua_types::LuaVersion`], read from the state set at construction.
4009fn getlocalattribute(ls: &mut LexState, state: &mut LuaState) -> Result<VarKind, LuaError> {
4010    if !version_has_attributes(state) {
4011        return Ok(VarKind::Reg);
4012    }
4013    if test_next(ls, state, b'<' as TokenKind)? {
4014        let attr_name = str_check_name(ls, state)?;
4015        check_next(ls, state, b'>' as TokenKind)?;
4016        let bytes = attr_name.as_bytes();
4017        if bytes == b"const" {
4018            return Ok(VarKind::Const);
4019        } else if bytes == b"close" {
4020            return Ok(VarKind::ToBeClosed);
4021        } else {
4022            let name_str = String::from_utf8_lossy(bytes);
4023            return Err(LuaError::syntax(format_args!(
4024                "unknown attribute '{}'", name_str
4025            )));
4026        }
4027    }
4028    Ok(VarKind::Reg)
4029}
4030
4031fn checktoclose(ls: &mut LexState, _state: &mut LuaState, level: i32) -> Result<(), LuaError> {
4032    if level != -1 {
4033        marktobeclosed(ls.fs.as_mut().unwrap());
4034        let rl = reg_level(ls, ls.fs.as_ref().unwrap(), level);
4035        let line = ls.lastline;
4036        let inst = lua_code::opcodes::Instruction::abck(
4037            lua_code::opcodes::OpCode::Tbc,
4038            rl as u32,
4039            0,
4040            0,
4041            0,
4042        );
4043        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4044    }
4045    Ok(())
4046}
4047
4048/// Lua 5.5 `global` declaration statement — PRELIMINARY GROUNDWORK STUB.
4049///
4050/// Grammar (manual §3.3.7, `specs/research/5.5-upstream-delta.md` §1b):
4051/// ```text
4052/// stat ::= global attnamelist ['=' explist]
4053/// stat ::= global [attrib] '*'
4054/// attnamelist ::= [attrib] Name [attrib] {',' Name [attrib]}
4055/// attrib ::= '<' Name '>'        -- only <const> is legal for a global; <close> is an error
4056/// ```
4057///
4058/// HOW FAR THIS GETS: this entry point is only reached on the `LuaVersion::V55`
4059/// path (the lexer only emits [`TK_GLOBAL`] there). It RECOGNIZES and fully
4060/// *consumes* both grammar forms — the collective `global *` (with an optional
4061/// leading `<const>` attribute) and the `global x <const>, y` name list with an
4062/// optional `= explist` initializer — so a syntactically valid `global`
4063/// statement parses without error. The declared names and their attributes are
4064/// parsed and then DROPPED (parse-and-noop). No bytecode is emitted and the
4065/// scope resolver is not touched.
4066///
4067/// WHAT THE FULL STATEFUL SCOPE MODEL STILL NEEDS (manual §2.2,
4068/// `specs/research/5.5-upstream-delta.md` §1c/§1d):
4069///  1. Per-scope mode flag: a chunk starts with an implicit `global *` (every
4070///     free name is `_ENV.name`, as in 5.4). The FIRST explicit `global` decl
4071///     in a scope VOIDS that implicit declaration for the rest of the scope.
4072///  2. Declared-set tracking: in a voided scope, every free name must resolve
4073///     to a local, an upvalue, or a name in some in-scope `global` declaration;
4074///     upstream encodes this with `VGLOBAL` and the sentinel `var->u.info == -1`
4075///     meaning "preambular `global *` still active".
4076///  3. Undeclared-name compile error: a free name with no declaration is a
4077///     COMPILE-TIME error, emitted via the new `OP_ERRNNIL` opcode
4078///     (`A Bx`, "raise error if R[A] ~= nil", K[Bx-1] is the global name). That
4079///     opcode, the `ivABC` operand mode, and the reordered SHRI/SHLI are not yet
4080///     in `lua-code`, so even storing to a declared global cannot be codegen'd
4081///     faithfully yet.
4082///  4. `<const>` globals must be read-only (compile error on assignment); a
4083///     `global` decl with an initializer raises a RUNTIME error if the global
4084///     already holds a non-nil value; `<close>` on a global is a compile error.
4085///  5. `global *` (optionally `global <const> *`) re-enables global-by-default
4086///     for the scope.
4087///  6. The `LUA_COMPAT_GLOBAL` axis (default on upstream): un-reserves `global`
4088///     as a keyword and recognizes the statement only contextually. We model
4089///     the strict (compat-off) behavior; a per-state compat flag is future work.
4090fn globalstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4091    lex_next(ls, state)?; // skip 'global'
4092
4093    // `global [<const>] '*'` — the collective form re-enables global-by-default
4094    // for the rest of the scope (voids any earlier strict-mode declaration).
4095    if test_next(ls, state, b'<' as TokenKind)? {
4096        let _attr = str_check_name(ls, state)?;
4097        check_next(ls, state, b'>' as TokenKind)?;
4098        check_next(ls, state, b'*' as TokenKind)?;
4099        ls.global_strict = false;
4100        return Ok(());
4101    }
4102    if test_next(ls, state, b'*' as TokenKind)? {
4103        ls.global_strict = false;
4104        return Ok(());
4105    }
4106
4107    // `global attnamelist ['=' explist]` — the name-list form. Record each
4108    // declared name (with its `<const>`-ness) and switch the scope into strict
4109    // mode so subsequent free names must be declared (manual §2.2).
4110    let mut names: Vec<GcRef<LuaString>> = Vec::new();
4111    loop {
4112        let name = str_check_name(ls, state)?;
4113        let mut is_const = false;
4114        if test_next(ls, state, b'<' as TokenKind)? {
4115            let attr = str_check_name(ls, state)?;
4116            check_next(ls, state, b'>' as TokenKind)?;
4117            match attr.as_bytes() {
4118                b"const" => is_const = true,
4119                b"close" => {
4120                    return Err(lua_lex::syntax_error(
4121                        &mut ls.lex,
4122                        b"<close> is not allowed for a global declaration",
4123                    ));
4124                }
4125                other => {
4126                    let msg = format!(
4127                        "unknown attribute '{}'",
4128                        String::from_utf8_lossy(other)
4129                    );
4130                    return Err(lua_lex::syntax_error(&mut ls.lex, msg.as_bytes()));
4131                }
4132            }
4133        }
4134        ls.declared_globals.push((name.clone(), is_const));
4135        names.push(name);
4136        if !test_next(ls, state, b',' as TokenKind)? {
4137            break;
4138        }
4139    }
4140    // `= explist` initializer: assign the values to the declared globals, i.e.
4141    // `_ENV.name = value`. Mirrors `restassign`'s multiple-assignment codegen —
4142    // build an `_ENV[name]` lvalue per declared name (these are IndexUp, no
4143    // register cost), evaluate the RHS, adjust to the variable count, then store
4144    // each target from the top register down. (Initializers were previously
4145    // parsed and dropped.)
4146    if test_next(ls, state, b'=' as TokenKind)? {
4147        let mut targets: Vec<ExprDesc> = Vec::with_capacity(names.len());
4148        for name in &names {
4149            let envn = ls.envn.clone().expect("envn must be set when resolving globals");
4150            let mut env_var = ExprDesc::default();
4151            let mut fs_box = ls.fs.take();
4152            let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut env_var, true);
4153            ls.fs = fs_box;
4154            r?;
4155            let line = ls.lastline;
4156            let fs = ls.fs.as_mut().unwrap();
4157            cg_exp_to_any_reg_up(fs, line, &mut env_var)?;
4158            let mut key = ExprDesc::default();
4159            codestring(&mut key, name.clone());
4160            cg_indexed(fs, line, &mut env_var, &mut key)?;
4161            targets.push(env_var);
4162        }
4163        let nvars = targets.len() as i32;
4164        let mut e = ExprDesc::default();
4165        let nexps = explist(ls, state, &mut e)?;
4166        adjust_assign(ls, state, nvars, nexps, &mut e)?;
4167        for target in targets.iter().rev() {
4168            let line = ls.lastline;
4169            let fs = ls.fs.as_mut().unwrap();
4170            let freereg = fs.freereg as i32 - 1;
4171            let mut v = ExprDesc::default();
4172            init_exp(&mut v, ExprKind::NonReloc, freereg);
4173            cg_storevar(fs, line, target, &mut v)?;
4174        }
4175    }
4176    ls.global_strict = true;
4177    Ok(())
4178}
4179
4180fn localstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4181    let mut toclose: i32 = -1;
4182    let mut nvars: i32 = 0;
4183    let mut vidx: i32;
4184    loop {
4185        let name = str_check_name(ls, state)?;
4186        vidx = new_local_var(ls, state, name)?;
4187        let kind = getlocalattribute(ls, state)?;
4188        get_local_var_desc_mut(ls, ls.fs.as_ref().unwrap().firstlocal, vidx).kind = kind;
4189        if kind == VarKind::ToBeClosed {
4190            if toclose != -1 {
4191                return Err(LuaError::syntax(format_args!(
4192                    "multiple to-be-closed variables in local list"
4193                )));
4194            }
4195            toclose = ls.fs.as_ref().unwrap().nactvar as i32 + nvars;
4196        }
4197        nvars += 1;
4198        if !test_next(ls, state, b',' as TokenKind)? {
4199            break;
4200        }
4201    }
4202    let nexps: i32;
4203    let mut e = ExprDesc::default();
4204    if test_next(ls, state, b'=' as TokenKind)? {
4205        nexps = explist(ls, state, &mut e)?;
4206    } else {
4207        e.k = ExprKind::Void;
4208        nexps = 0;
4209    }
4210    let first_local = ls.fs.as_ref().unwrap().firstlocal;
4211    let last_vd_kind = ls.dyd.actvar[(first_local + vidx) as usize].kind;
4212    if nvars == nexps
4213        && last_vd_kind == VarKind::Const
4214    {
4215        // TODO(port): let is_const = lua_code::exp_to_const(ls.fs.as_mut().unwrap(), &mut e, &mut var_k)?;
4216        let is_const = false; // placeholder
4217        if is_const {
4218            ls.dyd.actvar[(first_local + vidx) as usize].kind = VarKind::CompileTimeConst;
4219            adjust_local_vars(ls, state, nvars - 1)?;
4220            ls.fs.as_mut().unwrap().nactvar += 1;
4221        } else {
4222            adjust_assign(ls, state, nvars, nexps, &mut e)?;
4223            adjust_local_vars(ls, state, nvars)?;
4224        }
4225    } else {
4226        adjust_assign(ls, state, nvars, nexps, &mut e)?;
4227        adjust_local_vars(ls, state, nvars)?;
4228    }
4229    checktoclose(ls, state, toclose)?;
4230    Ok(())
4231}
4232
4233/// Parses a function name (NAME {'.' NAME} [':' NAME]). Returns ismethod.
4234fn funcname(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<bool, LuaError> {
4235    let mut ismethod = false;
4236    singlevar(ls, state, v)?;
4237    while ls.t.token == b'.' as TokenKind {
4238        fieldsel(ls, state, v)?;
4239    }
4240    if ls.t.token == b':' as TokenKind {
4241        ismethod = true;
4242        fieldsel(ls, state, v)?;
4243    }
4244    Ok(ismethod)
4245}
4246
4247fn funcstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
4248    lex_next(ls, state)?;
4249    let mut v = ExprDesc::default();
4250    let mut b = ExprDesc::default();
4251    let ismethod = funcname(ls, state, &mut v)?;
4252    body(ls, state, &mut b, ismethod, line)?;
4253    check_readonly(ls, state, &v.clone())?;
4254    let fs = ls.fs.as_mut().unwrap();
4255    cg_storevar(fs, line, &v, &mut b)?;
4256    // TODO(port): lua_code::fix_line(ls.fs.as_mut().unwrap(), line);
4257    Ok(())
4258}
4259
4260fn exprstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4261    let mut v_assign = LhsAssign { prev: None, v: ExprDesc::default() };
4262    suffixedexp(ls, state, &mut v_assign.v)?;
4263    if ls.t.token == b'=' as TokenKind || ls.t.token == b',' as TokenKind {
4264        restassign(ls, state, &mut v_assign, 1)?;
4265    } else {
4266        if v_assign.v.k != ExprKind::Call {
4267            return Err(lua_lex::syntax_error(&mut ls.lex, b"syntax error"));
4268        }
4269        let info = v_assign.v.u.info as usize;
4270        let fs = ls.fs.as_mut().unwrap();
4271        let mut lc = lua_code::opcodes::Instruction(fs.f.code[info].0);
4272        lc.set_arg_c(1);
4273        fs.f.code[info] = lua_types::opcode::Instruction::new(lc.0);
4274    }
4275    Ok(())
4276}
4277
4278fn retstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4279    let mut first = {
4280        let fs = ls.fs.as_ref().unwrap();
4281        nvarstack(ls, fs)
4282    };
4283    let mut nret: i32;
4284    if block_follow(ls, true) || ls.t.token == b';' as TokenKind {
4285        nret = 0;
4286    } else {
4287        let mut e = ExprDesc::default();
4288        nret = explist(ls, state, &mut e)?;
4289        if e.k.has_mult_ret() {
4290            cg_set_returns(ls.fs.as_mut().unwrap(), &mut e, LUA_MULTRET);
4291            if e.k == ExprKind::Call && nret == 1 {
4292                let insidetbc = ls.fs.as_ref().unwrap().bl.as_ref().map_or(false, |b| b.insidetbc);
4293                if !insidetbc {
4294                    let fs = ls.fs.as_mut().unwrap();
4295                    let info = e.u.info as usize;
4296                    let mut lc = lua_code::opcodes::Instruction(fs.f.code[info].0);
4297                    lc.set_opcode(lua_code::opcodes::OpCode::TailCall);
4298                    fs.f.code[info] = lua_types::opcode::Instruction::new(lc.0);
4299                }
4300            }
4301            nret = LUA_MULTRET;
4302        } else {
4303            let line = ls.lastline;
4304            if nret == 1 {
4305                first = cg_exp_to_any_reg(ls.fs.as_mut().unwrap(), line, &mut e)? as i32;
4306            } else {
4307                cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut e)?;
4308            }
4309        }
4310    }
4311    let line = ls.lastline;
4312    cg_emit_return(ls.fs.as_mut().unwrap(), line, first, nret);
4313    test_next(ls, state, b';' as TokenKind)?;
4314    Ok(())
4315}
4316
4317/// Top-level statement dispatcher.
4318fn statement(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4319    // This is the line of the current keyword (for/while/if/...), captured
4320    // BEFORE consuming. Used both for error messages on unmatched blocks
4321    // AND for runtime-error line attribution on control-flow instructions
4322    // (FORPREP, etc). errors.lua's lineerror tests depend on this.
4323    let line = ls.linenumber;
4324    enter_level(ls)?;
4325    match ls.t.token {
4326        c if c == b';' as TokenKind => {
4327            lex_next(ls, state)?;
4328        }
4329        TK_IF => {
4330            ifstat(ls, state, line)?;
4331        }
4332        TK_WHILE => {
4333            whilestat(ls, state, line)?;
4334        }
4335        TK_DO => {
4336            lex_next(ls, state)?; // skip DO
4337            block(ls, state)?;
4338            check_match(ls, state, TK_END, TK_DO, line)?;
4339        }
4340        TK_FOR => {
4341            forstat(ls, state, line)?;
4342        }
4343        TK_REPEAT => {
4344            repeatstat(ls, state, line)?;
4345        }
4346        TK_FUNCTION => {
4347            funcstat(ls, state, line)?;
4348        }
4349        TK_LOCAL => {
4350            lex_next(ls, state)?; // skip LOCAL
4351            if test_next(ls, state, TK_FUNCTION)? {
4352                localfunc(ls, state)?;
4353            } else {
4354                localstat(ls, state)?;
4355            }
4356        }
4357        TK_DBCOLON => {
4358            lex_next(ls, state)?; // skip '::'
4359            let name = str_check_name(ls, state)?;
4360            labelstat(ls, state, name, line)?;
4361        }
4362        TK_RETURN => {
4363            lex_next(ls, state)?; // skip RETURN
4364            retstat(ls, state)?;
4365        }
4366        TK_BREAK => {
4367            breakstat(ls, state)?;
4368        }
4369        TK_GOTO => {
4370            lex_next(ls, state)?; // skip 'goto'
4371            gotostat(ls, state)?;
4372        }
4373        _ => {
4374            // Lua 5.5 with the upstream-default LUA_COMPAT_GLOBAL: `global` is
4375            // NOT a reserved word. It introduces a declaration only when, at
4376            // statement start, the name `global` is followed by a Name, `*`, or
4377            // `<` (the collective `global <const> *` form). Otherwise it is an
4378            // ordinary identifier and the statement is a normal assignment/call.
4379            let is_global_decl = state.global().lua_version == lua_types::LuaVersion::V55
4380                && ls.t.token == TK_NAME
4381                && ls
4382                    .t
4383                    .seminfo
4384                    .ts
4385                    .as_ref()
4386                    .map_or(false, |s| s.as_bytes() == b"global")
4387                && {
4388                    let nxt = lex_lookahead(ls, state)?;
4389                    nxt == TK_NAME || nxt == b'*' as TokenKind || nxt == b'<' as TokenKind
4390                };
4391            if is_global_decl {
4392                globalstat(ls, state)?;
4393            } else {
4394                exprstat(ls, state)?;
4395            }
4396        }
4397    }
4398    debug_assert!(
4399        ls.fs.as_ref().unwrap().f.maxstacksize >= ls.fs.as_ref().unwrap().freereg
4400            && ls.fs.as_ref().unwrap().freereg as i32
4401                >= nvarstack(ls, ls.fs.as_ref().unwrap())
4402    );
4403    let nv = nvarstack(ls, ls.fs.as_ref().unwrap());
4404    ls.fs.as_mut().unwrap().freereg = nv as u8;
4405    leave_level(ls);
4406    Ok(())
4407}
4408
4409// ── §14 Main function and entry point ────────────────────────────────────────
4410
4411/// Compiles the main chunk (always a vararg function with _ENV upvalue).
4412fn mainfunc(ls: &mut LexState, state: &mut LuaState, main_fs: FuncState) -> Result<Box<LuaProto>, LuaError> {
4413    open_func(ls, state, main_fs)?;
4414
4415    setvararg(ls.fs.as_mut().unwrap(), state, 0)?;
4416
4417    let env_name = ls.envn.clone();
4418    {
4419        let idx = alloc_upvalue(ls.fs.as_mut().unwrap())?;
4420        let up = &mut ls.fs.as_mut().unwrap().f.upvalues[idx];
4421        up.instack = true;
4422        up.idx = 0;
4423        up.kind = VarKind::Reg.as_u8();
4424        up.name = env_name.clone();
4425    }
4426
4427    lex_next(ls, state)?;
4428
4429    statlist(ls, state)?;
4430
4431    check(ls, TK_EOS)?;
4432
4433    close_func(ls, state)
4434}
4435
4436/// Top-level entry point: parses a chunk and returns the main LClosure.
4437/// LUAI_FUNC visibility.
4438///
4439/// PORT NOTE: In C, returns `LClosure *` (a GC object). In Rust (Phase A),
4440///   we return `Box<LuaProto>` since we don't have GcRef<LuaLClosure> ready.
4441///   Phase B will wrap this in a proper LuaLClosure / GcRef.
4442pub fn parse(
4443    state: &mut LuaState,
4444    dyd: DynData,
4445    source: &[u8],
4446    name: &[u8],
4447    firstchar: i32,
4448) -> Result<Box<LuaProto>, LuaError> {
4449    let source_str = state.intern_str(name)?;
4450    let envn_str = state.intern_str(lua_lex::LUA_ENV)?;
4451
4452    let rest_bytes: Vec<u8> = source.iter().skip(1).copied().collect();
4453    let z = lua_lex::ZIO::from_bytes(rest_bytes);
4454
4455    let lex_ls = lua_lex::LexState {
4456        current: firstchar,
4457        linenumber: 1,
4458        lastline: 1,
4459        t: lua_lex::Token::eos(),
4460        lookahead: lua_lex::Token::eos(),
4461        fs: None,
4462        z,
4463        buff: lua_lex::LexBuffer::new(),
4464        h: None,
4465        long_str_anchor: std::collections::HashMap::new(),
4466        dyd: None,
4467        source: source_str.clone(),
4468        envn: envn_str.clone(),
4469    };
4470
4471    let mut lexstate = LexState {
4472        current: lex_ls.current,
4473        linenumber: lex_ls.linenumber,
4474        lastline: lex_ls.lastline,
4475        t: LexToken::default(),
4476        lookahead: LexToken::default(),
4477        fs: None,
4478        dyd,
4479        source: Some(source_str.clone()),
4480        envn: Some(lex_ls.envn.clone()),
4481        lex: lex_ls,
4482        recursion_depth: 0,
4483        global_strict: false,
4484        declared_globals: Vec::new(),
4485    };
4486    //   `mainfunc`; it does NOT pre-read the first token. `mainfunc` itself
4487    //   issues the initial `luaX_next` once its prelude (open_func, vararg
4488    //   marker, _ENV upvalue) is in place.
4489
4490    let mut main_proto = Box::new(LuaProto::placeholder());
4491    main_proto.source = Some(source_str);
4492    main_proto.is_vararg = true;
4493    let main_fs = FuncState {
4494        f: main_proto,
4495        prev: None,
4496        bl: None,
4497        pc: 0,
4498        lasttarget: 0,
4499        previousline: 0,
4500        nk: 0,
4501        np: 0,
4502        nabslineinfo: 0,
4503        firstlocal: 0,
4504        firstlabel: 0,
4505        ndebugvars: 0,
4506        nactvar: 0,
4507        nups: 0,
4508        freereg: 0,
4509        iwthabs: 0,
4510        needclose: false,
4511        last_token_line: 0,
4512    };
4513
4514    mainfunc(&mut lexstate, state, main_fs)
4515}
4516
4517/// Convert a `lua_lex::TokenValue` into the local `parse::TokenValue` flat shape.
4518///
4519/// The parser's local `LexState` predates the lex-side enum and uses a flat
4520/// (r, i, ts) record; this picks out whichever variant the lexer produced.
4521fn local_token_value(v: &lua_lex::TokenValue) -> TokenValue {
4522    match v {
4523        lua_lex::TokenValue::None => TokenValue::default(),
4524        lua_lex::TokenValue::Float(r) => TokenValue { r: *r, i: 0, ts: None },
4525        lua_lex::TokenValue::Int(i) => TokenValue { r: 0.0, i: *i, ts: None },
4526        lua_lex::TokenValue::Str(s) => TokenValue { r: 0.0, i: 0, ts: Some(s.clone()) },
4527    }
4528}
4529
4530// ──────────────────────────────────────────────────────────────────────────
4531// PORT STATUS
4532//   source:        src/lparser.c  (1968 lines, 95 functions)
4533//   target_crate:  lua-parse
4534//   confidence:    medium
4535//   todos:         184
4536//   port_notes:    14
4537//   unsafe_blocks: 0
4538//   notes:         All 95 functions translated with correct logical structure.
4539//                  184 TODO(port) stubs for cross-crate calls (lua_code::*,
4540//                  lua_lex::*, lua_vm state allocation). Key design choices:
4541//                  BlockCnt/LhsAssign use Option<Box<...>> chains; FuncState
4542//                  uses Box<LuaProto> (not GcRef) for mutable access during
4543//                  build. singlevaraux FuncState.prev chain traversal (upvalue
4544//                  capture across closures) is a known TODO — needs recursive
4545//                  descent through fs.prev without double-mutable-borrow.
4546//                  LexState is a local stub — Phase B must unify with
4547//                  lua_lex::LexState and add lua-lex as a dep. markupval
4548//                  BlockCnt chain traversal also needs Phase B restructure.
4549//                  rustc check: only E0432 (unresolved lua_types import) —
4550//                  expected Phase A name-resolution error; no syntax errors.
4551// ──────────────────────────────────────────────────────────────────────────