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