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