Skip to main content

lua_parse/
lib.rs

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