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