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/// result. For a Call this leaves the already-emitted instruction alone (it
2254/// was emitted with `ARG_C = 2`, i.e. exactly one result) and reclassifies
2255/// `e` as `NonReloc` pointing at the result register (the Call's `ARG_A`).
2256/// For a VarArg this patches `ARG_C = 2` and leaves `e` as `Reloc` so the
2257/// caller can place the single result into a destination register.
2258fn cg_set_one_ret(fs: &mut FuncState, e: &mut ExprDesc) {
2259    if e.k == ExprKind::Call {
2260        let pc_idx = e.u.info as usize;
2261        let lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
2262        debug_assert_eq!(lc.arg_c(), 2);
2263        e.u.info = lc.arg_a() as i32;
2264        e.k = ExprKind::NonReloc;
2265    } else if e.k == ExprKind::VarArg {
2266        let pc_idx = e.u.info as usize;
2267        let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
2268        lc.set_arg_c(2);
2269        fs.f.code[pc_idx] = lua_types::opcode::Instruction::new(lc.0);
2270        e.k = ExprKind::Reloc;
2271    }
2272}
2273
2274/// by `var`. Handles VLocal (move into register), VUpVal (OP_SETUPVAL),
2275/// VIndexUp (OP_SETTABUP), VIndexI/IndexStr/Indexed (OP_SETI/SETFIELD/SETTABLE).
2276fn cg_storevar(
2277    fs: &mut FuncState,
2278    line: i32,
2279    var: &ExprDesc,
2280    ex: &mut ExprDesc,
2281) -> Result<(), LuaError> {
2282    match var.k {
2283        ExprKind::Local => {
2284            cg_free_exp(fs, ex);
2285            cg_exp_to_reg(fs, line, ex, var.u.var_ridx as u8)?;
2286            return Ok(());
2287        }
2288        ExprKind::UpVal => {
2289            let e_reg = cg_exp_to_any_reg(fs, line, ex)?;
2290            let inst = lua_code::opcodes::Instruction::abck(
2291                lua_code::opcodes::OpCode::SetUpVal,
2292                e_reg as u32,
2293                var.u.info as u32,
2294                0,
2295                0,
2296            );
2297            emit_inst(fs, line, inst);
2298        }
2299        ExprKind::IndexUp => {
2300            cg_store_abrk(
2301                fs,
2302                line,
2303                lua_code::opcodes::OpCode::SetTabUp,
2304                var.u.ind_t as u32,
2305                var.u.ind_idx as u32,
2306                ex,
2307            )?;
2308        }
2309        ExprKind::IndexI => {
2310            cg_store_abrk(
2311                fs,
2312                line,
2313                lua_code::opcodes::OpCode::SetI,
2314                var.u.ind_t as u32,
2315                var.u.ind_idx as u32,
2316                ex,
2317            )?;
2318        }
2319        ExprKind::IndexStr => {
2320            cg_store_abrk(
2321                fs,
2322                line,
2323                lua_code::opcodes::OpCode::SetField,
2324                var.u.ind_t as u32,
2325                var.u.ind_idx as u32,
2326                ex,
2327            )?;
2328        }
2329        ExprKind::Indexed => {
2330            cg_store_abrk(
2331                fs,
2332                line,
2333                lua_code::opcodes::OpCode::SetTable,
2334                var.u.ind_t as u32,
2335                var.u.ind_idx as u32,
2336                ex,
2337            )?;
2338        }
2339        ExprKind::VarArgIndex => {
2340            mark_vararg_table_needed(fs);
2341            cg_store_abrk(
2342                fs,
2343                line,
2344                lua_code::opcodes::OpCode::SetTable,
2345                var.u.ind_t as u32,
2346                var.u.ind_idx as u32,
2347                ex,
2348            )?;
2349        }
2350        _ => {
2351            return Err(LuaError::syntax(format_args!(
2352                "internal: cg_storevar: invalid var kind {:?}",
2353                var.k
2354            )));
2355        }
2356    }
2357    cg_free_exp(fs, ex);
2358    Ok(())
2359}
2360
2361/// Helper for cg_storevar: emit an ABRK-form store. Mirrors C's `codeABRK`
2362/// for the SetTabUp/SetI/SetField/SetTable family. When `ex` is a constant
2363/// the K bit is set; otherwise the value is forced into a register.
2364fn cg_store_abrk(
2365    fs: &mut FuncState,
2366    line: i32,
2367    op: lua_code::opcodes::OpCode,
2368    a: u32,
2369    b: u32,
2370    ex: &mut ExprDesc,
2371) -> Result<(), LuaError> {
2372    if cg_exp_to_const_k(fs, ex, lua_code::opcodes::MAXARG_C) {
2373        let inst = lua_code::opcodes::Instruction::abck(op, a, b, ex.u.info as u32, 1);
2374        emit_inst(fs, line, inst);
2375        return Ok(());
2376    }
2377    let c_reg = cg_exp_to_any_reg(fs, line, ex)?;
2378    let inst = lua_code::opcodes::Instruction::abck(op, a, b, c_reg as u32, 0);
2379    emit_inst(fs, line, inst);
2380    Ok(())
2381}
2382
2383/// Mirrors C's `discharge2reg` from `lcode.c`: places the value described by
2384/// `e` into `reg`. For `Jmp` this is a no-op (the caller — `cg_exp_to_reg` —
2385/// is responsible for stitching the jump into `e.t` and emitting the
2386/// LoadTrue / LFalseSkip pair if a concrete value is needed).
2387fn cg_discharge_to_reg(
2388    fs: &mut FuncState,
2389    line: i32,
2390    e: &mut ExprDesc,
2391    reg: u8,
2392) -> Result<(), LuaError> {
2393    cg_discharge_vars(fs, line, e)?;
2394    match e.k {
2395        ExprKind::Jmp => {
2396            return Ok(());
2397        }
2398        ExprKind::NonReloc => {
2399            if e.u.info as u8 != reg {
2400                let inst = lua_code::opcodes::Instruction::abck(
2401                    lua_code::opcodes::OpCode::Move,
2402                    reg as u32,
2403                    e.u.info as u32,
2404                    0,
2405                    0,
2406                );
2407                emit_inst(fs, line, inst);
2408            }
2409        }
2410        ExprKind::Reloc => {
2411            let pc = e.u.info as usize;
2412            let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc].0);
2413            lc.set_arg_a(reg as u32);
2414            fs.f.code[pc] = lua_types::opcode::Instruction::new(lc.0);
2415        }
2416        ExprKind::Nil => {
2417            let inst = lua_code::opcodes::Instruction::abck(
2418                lua_code::opcodes::OpCode::LoadNil,
2419                reg as u32,
2420                0,
2421                0,
2422                0,
2423            );
2424            emit_inst(fs, line, inst);
2425        }
2426        ExprKind::True => {
2427            let inst = lua_code::opcodes::Instruction::abck(
2428                lua_code::opcodes::OpCode::LoadTrue,
2429                reg as u32,
2430                0,
2431                0,
2432                0,
2433            );
2434            emit_inst(fs, line, inst);
2435        }
2436        ExprKind::False => {
2437            let inst = lua_code::opcodes::Instruction::abck(
2438                lua_code::opcodes::OpCode::LoadFalse,
2439                reg as u32,
2440                0,
2441                0,
2442                0,
2443            );
2444            emit_inst(fs, line, inst);
2445        }
2446        ExprKind::KInt => {
2447            let i = e.u.ival;
2448            let max = lua_code::opcodes::MAXARG_BX as i64 - lua_code::opcodes::OFFSET_S_BX as i64;
2449            let min = -(lua_code::opcodes::OFFSET_S_BX as i64);
2450            if i >= min && i <= max {
2451                let bx = (i as i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
2452                let inst = lua_code::opcodes::Instruction::abx(
2453                    lua_code::opcodes::OpCode::LoadI,
2454                    reg as u32,
2455                    bx,
2456                );
2457                emit_inst(fs, line, inst);
2458            } else {
2459                let k_idx = add_k_value(fs, LuaValue::Int(i));
2460                let inst = lua_code::opcodes::Instruction::abx(
2461                    lua_code::opcodes::OpCode::LoadK,
2462                    reg as u32,
2463                    k_idx as u32,
2464                );
2465                emit_inst(fs, line, inst);
2466            }
2467        }
2468        ExprKind::KFlt => {
2469            let f = e.u.nval;
2470            let max = lua_code::opcodes::MAXARG_BX as i64 - lua_code::opcodes::OFFSET_S_BX as i64;
2471            let min = -(lua_code::opcodes::OFFSET_S_BX as i64);
2472            let fi_opt: Option<i64> = if f.fract() == 0.0 && f.abs() < i64::MAX as f64 {
2473                Some(f as i64)
2474            } else {
2475                None
2476            };
2477            if let Some(fi) = fi_opt.filter(|fi| *fi >= min && *fi <= max) {
2478                let bx = (fi as i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
2479                let inst = lua_code::opcodes::Instruction::abx(
2480                    lua_code::opcodes::OpCode::LoadF,
2481                    reg as u32,
2482                    bx,
2483                );
2484                emit_inst(fs, line, inst);
2485            } else {
2486                let k_idx = add_k_value(fs, LuaValue::Float(f));
2487                let inst = lua_code::opcodes::Instruction::abx(
2488                    lua_code::opcodes::OpCode::LoadK,
2489                    reg as u32,
2490                    k_idx as u32,
2491                );
2492                emit_inst(fs, line, inst);
2493            }
2494        }
2495        ExprKind::KStr => {
2496            let s =
2497                e.u.strval.clone().ok_or_else(|| {
2498                    LuaError::syntax(format_args!("internal: VKStr with no strval"))
2499                })?;
2500            let k_idx = add_k_string(fs, s);
2501            let inst = lua_code::opcodes::Instruction::abx(
2502                lua_code::opcodes::OpCode::LoadK,
2503                reg as u32,
2504                k_idx as u32,
2505            );
2506            emit_inst(fs, line, inst);
2507        }
2508        ExprKind::K => {
2509            let inst = lua_code::opcodes::Instruction::abx(
2510                lua_code::opcodes::OpCode::LoadK,
2511                reg as u32,
2512                e.u.info as u32,
2513            );
2514            emit_inst(fs, line, inst);
2515        }
2516        _ => {
2517            return Err(LuaError::syntax(format_args!(
2518                "internal: cg_discharge_to_reg cannot discharge {:?}",
2519                e.k
2520            )));
2521        }
2522    }
2523    e.u.info = reg as i32;
2524    e.k = ExprKind::NonReloc;
2525    Ok(())
2526}
2527
2528/// Mirrors C's `need_value` from `lcode.c`: walks the jump-list `list` and
2529/// returns true if any controlling instruction is *not* an `OP_TESTSET`,
2530/// meaning a concrete LoadTrue / LFalseSkip pair must be emitted to provide
2531/// the value at the fallthrough.
2532fn cg_need_value(fs: &FuncState, list: i32) -> bool {
2533    let mut walk = JumpList::new(list);
2534    while let Some(pc) = walk.next(fs) {
2535        let ctrl_pc = cg_get_jump_control(fs, pc);
2536        let ctrl = cg_inst_at(fs, ctrl_pc);
2537        if ctrl.opcode() != Some(lua_code::opcodes::OpCode::TestSet) {
2538            return true;
2539        }
2540    }
2541    false
2542}
2543
2544/// Mirrors C's `code_loadbool` from `lcode.c`: records `fs.pc` as a jump
2545/// label, then emits the requested LoadTrue / LoadFalse / LFalseSkip
2546/// instruction and returns its pc.
2547fn cg_code_loadbool(fs: &mut FuncState, line: i32, reg: i32, op: lua_code::opcodes::OpCode) -> i32 {
2548    cg_get_label(fs);
2549    let inst = lua_code::opcodes::Instruction::abck(op, reg as u32, 0, 0, 0);
2550    emit_inst(fs, line, inst)
2551}
2552
2553/// Mirrors C's `patchlistaux` from `lcode.c`: walks the jump-list `list`,
2554/// rewriting `TESTSET` controllers to write `reg` (and routing them to
2555/// `vtarget`) and leaving plain tests to fall through to `dtarget`.
2556fn cg_patch_list_aux(
2557    fs: &mut FuncState,
2558    list: i32,
2559    vtarget: i32,
2560    reg: u32,
2561    dtarget: i32,
2562) -> Result<(), LuaError> {
2563    let mut walk = JumpList::new(list);
2564    while let Some(pc) = walk.next(fs) {
2565        if cg_patch_test_reg(fs, pc, reg) {
2566            cg_fix_jump(fs, pc, vtarget)?;
2567        } else {
2568            cg_fix_jump(fs, pc, dtarget)?;
2569        }
2570    }
2571    Ok(())
2572}
2573
2574/// Discharge `e` into the specific register `reg`. Mirrors C's `exp2reg`
2575/// from `lcode.c`: delegates to `cg_discharge_to_reg`, then folds the jump
2576/// at `e.u.info` into `e.t` (when `e` is itself a test) and patches any
2577/// pending `e.t` / `e.f` jump-lists. When the lists actually need a value
2578/// (i.e. any controller isn't a `TESTSET`), emits the LFalseSkip / LoadTrue
2579/// pair around which the jumps land.
2580fn cg_exp_to_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc, reg: u8) -> Result<(), LuaError> {
2581    cg_discharge_to_reg(fs, line, e, reg)?;
2582    if e.k == ExprKind::Jmp {
2583        let info = e.u.info;
2584        cg_concat(fs, &mut e.t, info)?;
2585    }
2586    if e.t != e.f {
2587        let mut p_f = NO_JUMP;
2588        let mut p_t = NO_JUMP;
2589        if cg_need_value(fs, e.t) || cg_need_value(fs, e.f) {
2590            let fj = if e.k == ExprKind::Jmp {
2591                NO_JUMP
2592            } else {
2593                cg_jump(fs, line)
2594            };
2595            p_f = cg_code_loadbool(fs, line, reg as i32, lua_code::opcodes::OpCode::LFalseSkip);
2596            p_t = cg_code_loadbool(fs, line, reg as i32, lua_code::opcodes::OpCode::LoadTrue);
2597            cg_patch_to_here(fs, fj)?;
2598        }
2599        let final_pc = cg_get_label(fs);
2600        cg_patch_list_aux(fs, e.f, final_pc, reg as u32, p_f)?;
2601        cg_patch_list_aux(fs, e.t, final_pc, reg as u32, p_t)?;
2602    }
2603    e.f = NO_JUMP;
2604    e.t = NO_JUMP;
2605    e.u.info = reg as i32;
2606    e.k = ExprKind::NonReloc;
2607    Ok(())
2608}
2609
2610/// Like `cg_free_reg`, but only acts when the index actually belongs to a
2611/// temporary register (one above `fs.nactvar`). Used by indexed-get
2612/// dischargers, which may operate on either a temp result or a local.
2613fn cg_free_reg_if_temp(fs: &mut FuncState, reg: i32) {
2614    if reg >= fs.nactvar as i32 {
2615        debug_assert!(reg < fs.freereg as i32);
2616        if reg == fs.freereg as i32 - 1 {
2617            fs.freereg -= 1;
2618        }
2619    }
2620}
2621
2622/// Mirrors C's `luaK_exp2nextreg` from `lcode.c`: discharge variable forms,
2623/// free any temp held by `e`, reserve the next register, then call
2624/// `cg_exp_to_reg` to place the value (handling `Jmp` and pending
2625/// `e.t` / `e.f` jump-lists through the shared `exp2reg` path).
2626/// Emit the Lua 5.5 `global name = expr` already-defined guard for one global.
2627///
2628/// Mirrors upstream `checkglobal`/`luaK_codecheckglobal` (`lcode.c`): read the
2629/// global's current value into a temporary register and emit `OP_ERRNNIL`,
2630/// which raises `global '<name>' already defined` at runtime if that value is
2631/// non-nil. `target` is the `_ENV[name]` lvalue; it is cloned so the caller's
2632/// copy is left intact for the subsequent store. The temporary is freed
2633/// immediately so the store's `freereg - 1` source slot is undisturbed.
2634///
2635/// Bx encodes the name like upstream: `0` means the name index is unavailable
2636/// (renders as `?`), otherwise `Bx - 1` is the constant-table index of the
2637/// name string. The error reports `line`, the initializer's line number.
2638fn cg_check_global(
2639    fs: &mut FuncState,
2640    line: i32,
2641    target: &ExprDesc,
2642    name: GcRef<LuaString>,
2643) -> Result<(), LuaError> {
2644    let k = add_k_string(fs, name);
2645    let bx = if (k as u32) >= lua_code::opcodes::MAXARG_BX {
2646        0
2647    } else {
2648        (k + 1) as u32
2649    };
2650    let mut probe = target.clone();
2651    cg_exp_to_next_reg(fs, line, &mut probe)?;
2652    let reg = probe.u.info;
2653    let inst =
2654        lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::ErrNNil, reg as u32, bx);
2655    emit_inst(fs, line, inst);
2656    cg_free_reg(fs, reg);
2657    Ok(())
2658}
2659
2660fn cg_exp_to_next_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
2661    cg_discharge_vars(fs, line, e)?;
2662    cg_free_exp(fs, e);
2663    let reg = reserve_reg(fs)?;
2664    cg_exp_to_reg(fs, line, e, reg)
2665}
2666
2667/// it produces `nresults` values (or LUA_MULTRET when `nresults == -1`).
2668fn cg_set_returns(fs: &mut FuncState, e: &mut ExprDesc, nresults: i32) {
2669    let pc_idx = e.u.info as usize;
2670    let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
2671    if e.k == ExprKind::Call {
2672        lc.set_arg_c((nresults + 1) as u32);
2673    } else {
2674        debug_assert_eq!(e.k, ExprKind::VarArg);
2675        lc.set_arg_c((nresults + 1) as u32);
2676        lc.set_arg_a(fs.freereg as u32);
2677        // Upstream `luaK_setreturns` reserves the slot via `luaK_reserveregs`,
2678        // which also grows `maxstacksize`. A bare `freereg += 1` left the high
2679        // watermark stale and tripped the `maxstacksize >= freereg` invariant
2680        // whenever the VARARG sat above register 0 (e.g. a 5.5 named-vararg
2681        // local occupying a lower slot).
2682        fs.freereg += 1;
2683        bump_maxstack(fs, fs.freereg);
2684    }
2685    fs.f.code[pc_idx] = lua_types::opcode::Instruction::new(lc.0);
2686}
2687
2688/// `OP_JMP` instructions to the final landing pc. Capped at 100 hops to
2689/// avoid infinite loops on malformed code.
2690fn cg_final_target(fs: &FuncState, mut i: i32) -> i32 {
2691    for _ in 0..100 {
2692        let inst = cg_inst_at(fs, i);
2693        if inst.opcode() != Some(lua_code::opcodes::OpCode::Jmp) {
2694            break;
2695        }
2696        i += inst.arg_s_j() + 1;
2697    }
2698    i
2699}
2700
2701///
2702/// Patches `OP_RETURN`/`OP_RETURN0`/`OP_RETURN1`/`OP_TAILCALL` to record the
2703/// vararg signature (so the VM can roll back `ci->func` on return) and the
2704/// `needclose` flag (so it closes pending upvalues). Also resolves chained
2705/// `OP_JMP` jumps to their final target.
2706fn cg_finish(fs: &mut FuncState) {
2707    use lua_code::opcodes::OpCode;
2708    let needclose = fs.needclose;
2709    let is_vararg = fs.f.is_vararg;
2710    let numparams = fs.f.numparams as u32;
2711    let pc_end = fs.pc;
2712    for i in 0..pc_end {
2713        let mut inst = cg_inst_at(fs, i);
2714        match inst.opcode() {
2715            Some(OpCode::Return0) | Some(OpCode::Return1) => {
2716                if !(needclose || is_vararg) {
2717                    continue;
2718                }
2719                inst.set_opcode(OpCode::Return);
2720                if needclose {
2721                    inst.set_arg_k(1);
2722                }
2723                if is_vararg {
2724                    inst.set_arg_c(numparams + 1);
2725                }
2726                cg_set_inst_at(fs, i, inst);
2727            }
2728            Some(OpCode::Return) | Some(OpCode::TailCall) => {
2729                if needclose {
2730                    inst.set_arg_k(1);
2731                }
2732                if is_vararg {
2733                    inst.set_arg_c(numparams + 1);
2734                }
2735                cg_set_inst_at(fs, i, inst);
2736            }
2737            Some(OpCode::Jmp) => {
2738                let target = cg_final_target(fs, i);
2739                let _ = cg_fix_jump(fs, i, target);
2740            }
2741            _ => {}
2742        }
2743    }
2744}
2745
2746/// based on `nret`. `first` is the first result register; `nret` is the
2747/// number of values to return (`LUA_MULTRET` for "all values on top").
2748fn cg_emit_return(
2749    fs: &mut FuncState,
2750    line: i32,
2751    first: i32,
2752    nret: i32,
2753    version: lua_types::LuaVersion,
2754) -> Result<(), LuaError> {
2755    let op = match nret {
2756        0 => lua_code::opcodes::OpCode::Return0,
2757        1 => lua_code::opcodes::OpCode::Return1,
2758        _ => lua_code::opcodes::OpCode::Return,
2759    };
2760    if matches!(version, lua_types::LuaVersion::V55) {
2761        check_limit(fs, nret + 1, lua_code::opcodes::MAXARG_B as i32, "returns")?;
2762    }
2763    let inst = lua_code::opcodes::Instruction::abck(op, first as u32, (nret + 1) as u32, 0, 0);
2764    emit_inst(fs, line, inst);
2765    Ok(())
2766}
2767
2768// ── Free functions ──────────────────────────────────────────────────────────
2769
2770// (Both defined later in this file; Rust has no forward declarations.)
2771
2772// ── §1 Error helpers ────────────────────────────────────────────────────────
2773
2774/// Constructs a syntax error for a missing expected token.
2775/// In Rust, `l_noret` becomes returning `LuaError`; callers use
2776/// `return Err(error_expected(...))`.
2777fn error_expected(ls: &mut LexState, token: TokenKind) -> LuaError {
2778    let tok_str = lua_lex::token2str(&ls.lex, token);
2779    let mut msg: Vec<u8> = Vec::with_capacity(tok_str.len() + 10);
2780    msg.extend_from_slice(&tok_str);
2781    msg.extend_from_slice(b" expected");
2782    lua_lex::syntax_error(&mut ls.lex, &msg)
2783}
2784
2785/// Constructs a compile-time limit-exceeded syntax error.
2786fn error_limit(fs: &FuncState, limit: i32, what: &str) -> LuaError {
2787    let line = fs.f.linedefined;
2788    if line == 0 {
2789        LuaError::syntax(format_args!(
2790            "too many {} (limit is {}) in main function",
2791            what, limit
2792        ))
2793    } else {
2794        LuaError::syntax(format_args!(
2795            "too many {} (limit is {}) in function at line {}",
2796            what, limit, line
2797        ))
2798    }
2799}
2800
2801fn check_limit(fs: &FuncState, v: i32, l: i32, what: &str) -> Result<(), LuaError> {
2802    if v > l {
2803        return Err(error_limit(fs, l, what));
2804    }
2805    Ok(())
2806}
2807
2808/// Constructs Lua 5.1's `errorlimit` message, which predates the modern
2809/// `"too many %s (limit is %d) ..."` wording produced by [`error_limit`].
2810///
2811/// Lua 5.1's `lparser.c errorlimit` emits `"function at line %d has more than
2812/// %d %s"` (or `"main function has more than %d %s"` when `linedefined == 0`),
2813/// reporting the *limit* rather than the attempted count. The limit value also
2814/// differs from later versions for upvalues: 5.1 caps a function at
2815/// `LUAI_MAXUPVALUES = 60`, whereas 5.2+ allow `MAXUPVAL = 255`. Used only on
2816/// the [`lua_types::LuaVersion::V51`] path so 5.2–5.5 stay byte-identical.
2817fn error_limit_v51(fs: &FuncState, limit: i32, what: &str) -> LuaError {
2818    let line = fs.f.linedefined;
2819    if line == 0 {
2820        LuaError::syntax(format_args!("main function has more than {} {}", limit, what))
2821    } else {
2822        LuaError::syntax(format_args!(
2823            "function at line {} has more than {} {}",
2824            line, limit, what
2825        ))
2826    }
2827}
2828
2829// ── §2 Basic parse utilities ─────────────────────────────────────────────────
2830
2831/// If the current token matches `c`, consume it and return true.
2832fn test_next(ls: &mut LexState, state: &mut LuaState, c: TokenKind) -> Result<bool, LuaError> {
2833    if ls.t.token == c {
2834        lex_next(ls, state)?;
2835        Ok(true)
2836    } else {
2837        Ok(false)
2838    }
2839}
2840
2841fn check(ls: &mut LexState, c: TokenKind) -> Result<(), LuaError> {
2842    if ls.t.token != c {
2843        return Err(error_expected(ls, c));
2844    }
2845    Ok(())
2846}
2847
2848fn check_next(ls: &mut LexState, state: &mut LuaState, c: TokenKind) -> Result<(), LuaError> {
2849    check(ls, c)?;
2850    lex_next(ls, state)?;
2851    Ok(())
2852}
2853
2854/// Expects TK_NAME, returns the name string, advances.
2855fn str_check_name(ls: &mut LexState, state: &mut LuaState) -> Result<GcRef<LuaString>, LuaError> {
2856    check(ls, TK_NAME)?;
2857    let ts =
2858        ls.t.seminfo
2859            .ts
2860            .clone()
2861            .ok_or_else(|| LuaError::syntax(format_args!("name expected")))?;
2862    lex_next(ls, state)?;
2863    Ok(ts)
2864}
2865
2866fn init_exp(e: &mut ExprDesc, k: ExprKind, i: i32) {
2867    e.f = NO_JUMP;
2868    e.t = NO_JUMP;
2869    e.k = k;
2870    e.u.info = i;
2871}
2872
2873fn codestring(e: &mut ExprDesc, s: GcRef<LuaString>) {
2874    e.f = NO_JUMP;
2875    e.t = NO_JUMP;
2876    e.k = ExprKind::KStr;
2877    e.u.strval = Some(s);
2878}
2879
2880fn codename(ls: &mut LexState, state: &mut LuaState, e: &mut ExprDesc) -> Result<(), LuaError> {
2881    let name = str_check_name(ls, state)?;
2882    codestring(e, name);
2883    Ok(())
2884}
2885
2886// ── §3 Variable handling ─────────────────────────────────────────────────────
2887
2888/// Registers a local variable in the proto's debug-info locvars array.
2889/// Returns the index in locvars (= fs->ndebugvars before increment).
2890fn register_local_var(
2891    _ls: &mut LexState,
2892    _state: &mut LuaState,
2893    fs: &mut FuncState,
2894    varname: GcRef<LuaString>,
2895) -> Result<i32, LuaError> {
2896    // In Rust, Vec grows automatically; just push a placeholder if needed.
2897    let idx = fs.ndebugvars as usize;
2898    while fs.f.locvars.len() <= idx {
2899        fs.f.locvars.push(LocalVar {
2900            varname: varname.clone(), // placeholder; overwritten below
2901            startpc: 0,
2902            endpc: 0,
2903        });
2904    }
2905    fs.f.locvars[idx].varname = varname;
2906    fs.f.locvars[idx].startpc = fs.pc;
2907    let result = fs.ndebugvars as i32;
2908    fs.ndebugvars += 1;
2909    Ok(result)
2910}
2911
2912/// Creates a new local variable entry in dyd.actvar.
2913/// Returns the variable's index relative to fs->firstlocal.
2914fn new_local_var(
2915    ls: &mut LexState,
2916    _state: &mut LuaState,
2917    name: GcRef<LuaString>,
2918) -> Result<i32, LuaError> {
2919    let fs = ls.fs.as_ref().unwrap();
2920    let n = ls.dyd.actvar.len() as i32;
2921    let first_local = fs.firstlocal;
2922    check_limit(fs, n + 1 - first_local, MAX_VARS, "local variables")?;
2923
2924    let mut var = VarDesc::default();
2925    var.kind = VarKind::Reg;
2926    var.name = Some(name);
2927    ls.dyd.actvar.push(var);
2928    let result = ls.dyd.actvar.len() as i32 - 1 - first_local;
2929    Ok(result)
2930}
2931
2932/// Returns a reference to the VarDesc at index `fs->firstlocal + vidx`.
2933fn get_local_var_desc<'a>(ls: &'a LexState, fs: &FuncState, vidx: i32) -> &'a VarDesc {
2934    &ls.dyd.actvar[(fs.firstlocal + vidx) as usize]
2935}
2936
2937fn get_local_var_desc_mut(ls: &mut LexState, first_local: i32, vidx: i32) -> &mut VarDesc {
2938    &mut ls.dyd.actvar[(first_local + vidx) as usize]
2939}
2940
2941/// Converts a compiler-index level to its register number.
2942fn reg_level(ls: &LexState, fs: &FuncState, nvar: i32) -> i32 {
2943    let mut nvar = nvar;
2944    while nvar > 0 {
2945        nvar -= 1;
2946        let vd = get_local_var_desc(ls, fs, nvar);
2947        if vd.kind != VarKind::CompileTimeConst {
2948            return vd.ridx as i32 + 1;
2949        }
2950    }
2951    0
2952}
2953
2954/// Returns the number of variables currently occupying registers.
2955/// LUAI_FUNC visibility.
2956pub fn nvarstack(ls: &LexState, fs: &FuncState) -> i32 {
2957    reg_level(ls, fs, fs.nactvar as i32)
2958}
2959
2960fn init_var(ls: &LexState, fs: &FuncState, e: &mut ExprDesc, vidx: i32) {
2961    e.f = NO_JUMP;
2962    e.t = NO_JUMP;
2963    e.k = ExprKind::Local;
2964    e.u.var_vidx = vidx as u16;
2965    e.u.var_ridx = get_local_var_desc(ls, fs, vidx).ridx;
2966}
2967
2968/// Raises an error if expression `e` describes a read-only variable.
2969fn check_readonly(ls: &mut LexState, state: &mut LuaState, e: &ExprDesc) -> Result<(), LuaError> {
2970    // Lua 5.5: assignment to a `global x <const>` declared global is rejected
2971    // at compile time, tagged on the resolved expression by `singlevar`.
2972    if let Some(name) = e.u.global_const_name.as_ref() {
2973        let msg = format!(
2974            "attempt to assign to const variable '{}'",
2975            String::from_utf8_lossy(name.as_bytes())
2976        );
2977        // Semantic error (C's luaK_semerror): no "near <token>" suffix.
2978        return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
2979    }
2980    let varname: Option<GcRef<LuaString>> = {
2981        let fs = ls.fs.as_ref().unwrap();
2982        match e.k {
2983            ExprKind::Const => ls.dyd.actvar[e.u.info as usize].name.clone(),
2984            ExprKind::Local | ExprKind::VarArgVar => {
2985                let vd = get_local_var_desc(ls, fs, e.u.var_vidx as i32);
2986                if vd.kind != VarKind::Reg {
2987                    vd.name.clone()
2988                } else {
2989                    None
2990                }
2991            }
2992            ExprKind::UpVal => {
2993                let up = &fs.f.upvalues[e.u.info as usize];
2994                if VarKind::from_u8(up.kind) != VarKind::Reg {
2995                    up.name.clone()
2996                } else {
2997                    None
2998                }
2999            }
3000            _ => None,
3001        }
3002    };
3003    if let Some(vname) = varname {
3004        // C's luaK_semerror: a semantic error carries no "near <token>" suffix
3005        // (it zeroes ls->t.token before luaX_syntaxerror). Use lex_error with
3006        // token 0 to match the reference exactly for every version. constructs.lua's
3007        // checkload(":1: attempt to assign...") still matches (prefix).
3008        let _ = state;
3009        let msg = format!(
3010            "attempt to assign to const variable '{}'",
3011            String::from_utf8_lossy(vname.as_bytes())
3012        );
3013        return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
3014    }
3015    Ok(())
3016}
3017
3018/// Starts the scope for the last `nvars` created variables.
3019fn adjust_local_vars(ls: &mut LexState, state: &mut LuaState, nvars: i32) -> Result<(), LuaError> {
3020    // Extract needed data to avoid borrow conflict with ls.fs and ls.dyd
3021    let first_local = ls.fs.as_ref().unwrap().firstlocal;
3022    let nactvar_start = ls.fs.as_ref().unwrap().nactvar as i32;
3023    let mut reglevel_val = {
3024        let fs = ls.fs.as_ref().unwrap();
3025        reg_level(ls, fs, fs.nactvar as i32)
3026    };
3027
3028    for i in 0..nvars {
3029        let vidx = nactvar_start + i;
3030        ls.fs.as_mut().unwrap().nactvar += 1;
3031        let var_name = ls.dyd.actvar[(first_local + vidx) as usize].name.clone();
3032        ls.dyd.actvar[(first_local + vidx) as usize].ridx = reglevel_val as u8;
3033        reglevel_val += 1;
3034        if let Some(vn) = var_name {
3035            let mut fs_box = ls.fs.take().unwrap();
3036            let pidx_result = register_local_var(ls, state, &mut fs_box, vn);
3037            ls.fs = Some(fs_box);
3038            let pidx = pidx_result?;
3039            ls.dyd.actvar[(first_local + vidx) as usize].pidx = pidx as i16;
3040        } else {
3041            // TODO(port): variable has no name — shouldn't happen in valid source
3042        }
3043    }
3044    Ok(())
3045}
3046
3047/// Closes scope for all variables above `tolevel`, updating their endpc.
3048fn remove_vars(ls: &mut LexState, fs: &mut FuncState, tolevel: i32) {
3049    //
3050    // C just decrements a length counter; the underlying array memory is
3051    // untouched and the subsequent loop reads from it freely. A Rust
3052    // `truncate` would actually free the entries, leaving the loop reading
3053    // out-of-range and silently writing every iteration's endpc to
3054    // `locvars[0]` (via the `unwrap_or(0)` fallback below). Defer the
3055    // truncate until after the loop walks each soon-to-be-removed entry.
3056    let delta = fs.nactvar as i32 - tolevel;
3057    while fs.nactvar as i32 > tolevel {
3058        fs.nactvar -= 1;
3059        let nactvar = fs.nactvar as i32;
3060        let vd_kind = {
3061            let first_local = fs.firstlocal;
3062            ls.dyd
3063                .actvar
3064                .get((first_local + nactvar) as usize)
3065                .map(|v| v.kind)
3066                .unwrap_or(VarKind::Reg)
3067        };
3068        if vd_kind != VarKind::CompileTimeConst {
3069            let vd_pidx = {
3070                let first_local = fs.firstlocal;
3071                ls.dyd
3072                    .actvar
3073                    .get((first_local + nactvar) as usize)
3074                    .map(|v| v.pidx)
3075                    .unwrap_or(0)
3076            };
3077            if let Some(lv) = fs.f.locvars.get_mut(vd_pidx as usize) {
3078                lv.endpc = fs.pc;
3079            }
3080        }
3081    }
3082    if delta > 0 {
3083        let new_len = ls.dyd.actvar.len().saturating_sub(delta as usize);
3084        ls.dyd.actvar.truncate(new_len);
3085    }
3086}
3087
3088// ── §4 Upvalue handling ──────────────────────────────────────────────────────
3089
3090/// Returns the index of an upvalue named `name`, or -1 if not found.
3091fn search_upvalue(fs: &FuncState, name: &GcRef<LuaString>) -> i32 {
3092    for (i, up) in fs.f.upvalues.iter().enumerate() {
3093        if up.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
3094            return i as i32;
3095        }
3096    }
3097    -1
3098}
3099
3100/// Grows upvalues array and returns index of the new slot.
3101///
3102/// `version` selects the upvalue ceiling and the limit-error wording: Lua 5.1
3103/// caps a function at [`MAX_UPVAL_V51`] = 60 and reports it via
3104/// [`error_limit_v51`] (`"function at line %d has more than 60 upvalues"`),
3105/// while 5.2–5.5 keep [`MAX_UPVAL`] = 255 and the modern [`error_limit`]
3106/// wording.
3107fn alloc_upvalue(
3108    fs: &mut FuncState,
3109    version: lua_types::LuaVersion,
3110) -> Result<usize, LuaError> {
3111    if version == lua_types::LuaVersion::V51 {
3112        if fs.nups as i32 + 1 > MAX_UPVAL_V51 {
3113            return Err(error_limit_v51(fs, MAX_UPVAL_V51, "upvalues"));
3114        }
3115    } else if fs.nups as i32 + 1 > MAX_UPVAL as i32 {
3116        return Err(error_limit(fs, MAX_UPVAL as i32, "upvalues"));
3117    }
3118    let idx = fs.nups as usize;
3119    while fs.f.upvalues.len() <= idx {
3120        fs.f.upvalues.push(UpvalDesc {
3121            name: None,
3122            instack: false,
3123            idx: 0,
3124            kind: 0,
3125        });
3126    }
3127    fs.nups += 1;
3128    Ok(idx)
3129}
3130
3131/// Adds a new upvalue descriptor and returns its index.
3132fn new_upvalue(
3133    ls: &LexState,
3134    fs: &mut FuncState,
3135    name: GcRef<LuaString>,
3136    v: &ExprDesc,
3137) -> Result<i32, LuaError> {
3138    let idx = alloc_upvalue(fs, ls.lex.version)?;
3139    let kind: u8 = if v.k == ExprKind::Local {
3140        let prev = fs
3141            .prev
3142            .as_deref()
3143            .expect("upvalue capture requires enclosing FuncState");
3144        get_local_var_desc(ls, prev, v.u.var_vidx as i32)
3145            .kind
3146            .as_u8()
3147    } else {
3148        let prev = fs
3149            .prev
3150            .as_deref()
3151            .expect("upvalue chain requires enclosing FuncState");
3152        prev.f.upvalues[v.u.info as usize].kind
3153    };
3154    let up = &mut fs.f.upvalues[idx];
3155    if v.k == ExprKind::Local {
3156        up.instack = true;
3157        up.idx = v.u.var_ridx;
3158    } else {
3159        up.instack = false;
3160        up.idx = v.u.info as u8;
3161    }
3162    up.kind = kind;
3163    up.name = Some(name);
3164    Ok(fs.nups as i32 - 1)
3165}
3166
3167/// Searches the active local variables of `fs` for one named `n`, scanning
3168/// from the most-recently-declared backwards so that the innermost shadowing
3169/// declaration wins. On a hit it initializes `var` and returns its [`ExprKind`]
3170/// encoded as `i32`; on a miss it returns `-1`.
3171fn searchvar(ls: &LexState, fs: &FuncState, n: &GcRef<LuaString>, var: &mut ExprDesc) -> i32 {
3172    for i in (0..fs.nactvar as i32).rev() {
3173        let vd = get_local_var_desc(ls, fs, i);
3174        if vd.name.as_ref().is_some_and(|nm| GcRef::ptr_eq(nm, n)) {
3175            if vd.kind == VarKind::CompileTimeConst {
3176                init_exp(var, ExprKind::Const, fs.firstlocal + i);
3177            } else {
3178                init_var(ls, fs, var, i);
3179                if vd.kind == VarKind::VarArg {
3180                    var.k = ExprKind::VarArgVar;
3181                }
3182            }
3183            return var.k as i32;
3184        }
3185    }
3186    -1
3187}
3188
3189/// Marks the block where the variable at `level` was defined as having an upvalue.
3190fn markupval(fs: &mut FuncState, level: i32) {
3191    let mut current = fs.bl.as_deref_mut();
3192    while let Some(b) = current {
3193        if (b.nactvar as i32) <= level {
3194            b.upval = true;
3195            break;
3196        }
3197        current = b.previous.as_deref_mut();
3198    }
3199    fs.needclose = true;
3200}
3201
3202fn marktobeclosed(fs: &mut FuncState) {
3203    if let Some(bl) = fs.bl.as_mut() {
3204        bl.upval = true;
3205        bl.insidetbc = true;
3206    }
3207    fs.needclose = true;
3208}
3209
3210// ── §5 Variable resolution ───────────────────────────────────────────────────
3211
3212/// Recursively finds variable `n` in `fs` and its enclosing functions.
3213/// If not found at any level, sets var->k = VVOID (global).
3214fn singlevaraux(
3215    ls: &LexState,
3216    fs: Option<&mut FuncState>,
3217    n: &GcRef<LuaString>,
3218    var: &mut ExprDesc,
3219    base: bool,
3220) -> Result<(), LuaError> {
3221    match fs {
3222        None => {
3223            init_exp(var, ExprKind::Void, 0);
3224        }
3225        Some(fs) => {
3226            let v = searchvar(ls, fs, n, var);
3227            if v >= 0 {
3228                if !base {
3229                    if var.k == ExprKind::VarArgVar {
3230                        mark_vararg_table_needed(fs);
3231                        var.k = ExprKind::Local;
3232                    }
3233                    if var.k == ExprKind::Local {
3234                        markupval(fs, var.u.var_vidx as i32);
3235                    }
3236                }
3237            } else {
3238                let idx = search_upvalue(fs, n);
3239                let final_idx = if idx < 0 {
3240                    singlevaraux(ls, fs.prev.as_deref_mut(), n, var, false)?;
3241                    if var.k == ExprKind::Local
3242                        || var.k == ExprKind::VarArgVar
3243                        || var.k == ExprKind::UpVal
3244                    {
3245                        if var.k == ExprKind::VarArgVar {
3246                            var.k = ExprKind::Local;
3247                        }
3248                        new_upvalue(ls, fs, n.clone(), var)?
3249                    } else {
3250                        return Ok(());
3251                    }
3252                } else {
3253                    idx
3254                };
3255                init_exp(var, ExprKind::UpVal, final_idx);
3256            }
3257        }
3258    }
3259    Ok(())
3260}
3261
3262/// Finds the variable named by the next TK_NAME token.
3263fn singlevar(ls: &mut LexState, state: &mut LuaState, var: &mut ExprDesc) -> Result<(), LuaError> {
3264    let name_line = ls.linenumber;
3265    let varname = str_check_name(ls, state)?;
3266    let mut fs_box = ls.fs.take();
3267    let recurse_result = singlevaraux(ls, fs_box.as_deref_mut(), &varname, var, true);
3268    ls.fs = fs_box;
3269    recurse_result?;
3270    if state.global().lua_version == lua_types::LuaVersion::V55 {
3271        match var.k {
3272            ExprKind::Local | ExprKind::Const => {
3273                if let Some(global_level) = latest_matching_global_barrier_current(ls, &varname) {
3274                    let local_level = scope_level_for_local_level(ls, var.u.var_vidx as u8);
3275                    if global_level > local_level {
3276                        init_exp(var, ExprKind::Void, 0);
3277                    }
3278                }
3279            }
3280            ExprKind::UpVal => {
3281                if is_active_global_function_name(ls, &varname) {
3282                    init_exp(var, ExprKind::Void, 0);
3283                }
3284            }
3285            _ => {}
3286        }
3287    }
3288    if var.k == ExprKind::Void {
3289        // Lua 5.5: once a scope is in strict mode (an explicit `global`
3290        // declaration was seen), a free name must be a declared global —
3291        // otherwise it is a compile-time error (manual §2.2). `global_strict`
3292        // is only ever set on the 5.5 path, so pre-5.5 resolution is unchanged.
3293        let mut declared_const: Option<bool> = None;
3294        for (n, c) in ls.declared_globals.iter().rev() {
3295            if GcRef::ptr_eq(n, &varname) {
3296                declared_const = Some(*c);
3297                break;
3298            }
3299        }
3300        let is_const_global = match declared_const {
3301            Some(c) => c,
3302            None if ls.global_wildcard => ls.global_wildcard_const,
3303            None if ls.global_strict => {
3304                let msg = format!(
3305                    "variable '{}' not declared",
3306                    String::from_utf8_lossy(varname.as_bytes())
3307                );
3308                // Semantic error (C's luaK_semerror): no "near <token>" suffix.
3309                let saved_line = ls.lex.linenumber;
3310                ls.lex.linenumber = name_line;
3311                let err = lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0);
3312                ls.lex.linenumber = saved_line;
3313                return Err(err);
3314            }
3315            None => false,
3316        };
3317        let envn = ls
3318            .envn
3319            .clone()
3320            .expect("envn must be set when resolving globals");
3321        if has_active_global_barrier(ls, &envn) {
3322            let msg = format!(
3323                "{} is global when accessing variable '{}'",
3324                lua_lex::LUA_ENV.escape_ascii(),
3325                String::from_utf8_lossy(varname.as_bytes())
3326            );
3327            return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
3328        }
3329        let mut env_var = ExprDesc::default();
3330        let mut fs_box = ls.fs.take();
3331        let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut env_var, true);
3332        ls.fs = fs_box;
3333        r?;
3334        debug_assert!(env_var.k != ExprKind::Void, "_ENV must resolve");
3335        let line = ls.lastline;
3336        let fs = ls.fs.as_mut().unwrap();
3337        cg_exp_to_any_reg_up(fs, line, &mut env_var)?;
3338        let mut key = ExprDesc::default();
3339        let const_name = if is_const_global {
3340            Some(varname.clone())
3341        } else {
3342            None
3343        };
3344        codestring(&mut key, varname);
3345        cg_indexed(fs, line, &mut env_var, &mut key)?;
3346        *var = env_var;
3347        var.u.global_const_name = const_name;
3348    }
3349    Ok(())
3350}
3351
3352fn adjust_assign(
3353    ls: &mut LexState,
3354    _state: &mut LuaState,
3355    nvars: i32,
3356    nexps: i32,
3357    e: &mut ExprDesc,
3358) -> Result<(), LuaError> {
3359    let needed = nvars - nexps;
3360    let line = ls.lastline;
3361    let fs = ls.fs.as_mut().unwrap();
3362    if e.k.has_mult_ret() {
3363        let extra = if needed + 1 < 0 { 0 } else { needed + 1 };
3364        cg_set_returns(fs, e, extra);
3365    } else {
3366        if e.k != ExprKind::Void {
3367            cg_exp_to_next_reg(fs, line, e)?;
3368        }
3369        if needed > 0 {
3370            let from = fs.freereg as i32;
3371            cg_emit_nil(fs, line, from, needed);
3372        }
3373    }
3374    if needed > 0 {
3375        for _ in 0..needed {
3376            reserve_reg(fs)?;
3377        }
3378    } else {
3379        fs.freereg = (fs.freereg as i32 + needed) as u8;
3380    }
3381    Ok(())
3382}
3383
3384/// Emits `OP_NEWTABLE` followed by the required `OP_EXTRAARG` slot. The two
3385/// instructions are written as placeholders; `cg_settablesize` later patches
3386/// them with the final array/hash sizes. Returns the pc of `OP_NEWTABLE`.
3387fn cg_emit_newtable(fs: &mut FuncState, line: i32) -> i32 {
3388    let newtable =
3389        lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::NewTable, 0, 0, 0, 0);
3390    let pc = emit_inst(fs, line, newtable);
3391    let extra = lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, 0);
3392    emit_inst(fs, line, extra);
3393    pc
3394}
3395
3396/// Patches a previously-emitted `OP_NEWTABLE`/`OP_EXTRAARG` pair with the
3397/// final array size (`asize`) and hash size (`hsize`). Mirrors
3398/// `luaK_settablesize` from `lcode.c`.
3399fn cg_settablesize(fs: &mut FuncState, pc: i32, ra: i32, asize: i32, hsize: i32) {
3400    let rb = if hsize != 0 {
3401        (hsize as u32).next_power_of_two().trailing_zeros() as i32 + 1
3402    } else {
3403        0
3404    };
3405    let maxc = lua_code::opcodes::MAXARG_C as i32 + 1;
3406    let extra = asize / maxc;
3407    let rc = asize % maxc;
3408    let k = if extra > 0 { 1u32 } else { 0u32 };
3409    let newtable = lua_code::opcodes::Instruction::abck(
3410        lua_code::opcodes::OpCode::NewTable,
3411        ra as u32,
3412        rb as u32,
3413        rc as u32,
3414        k,
3415    );
3416    fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(newtable.0);
3417    let extra_inst =
3418        lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, extra as u32);
3419    fs.f.code[pc as usize + 1] = lua_types::opcode::Instruction::new(extra_inst.0);
3420}
3421
3422/// Emits `OP_SETLIST` for `tostore` elements starting at `base+1`, with
3423/// `nelems` already-stored elements preceding them. `tostore == -1` means
3424/// `LUA_MULTRET` (encoded as 0 in the B field). Also resets `fs.freereg`
3425/// to `base + 1`, mirroring `luaK_setlist`.
3426fn cg_setlist(fs: &mut FuncState, line: i32, base: i32, nelems: i32, tostore: i32) {
3427    let maxc = lua_code::opcodes::MAXARG_C as i32;
3428    let tostore_arg = if tostore == LUA_MULTRET { 0 } else { tostore };
3429    if nelems <= maxc {
3430        let inst = lua_code::opcodes::Instruction::abck(
3431            lua_code::opcodes::OpCode::SetList,
3432            base as u32,
3433            tostore_arg as u32,
3434            nelems as u32,
3435            0,
3436        );
3437        emit_inst(fs, line, inst);
3438    } else {
3439        let extra = nelems / (maxc + 1);
3440        let nelems_lo = nelems % (maxc + 1);
3441        let inst = lua_code::opcodes::Instruction::abck(
3442            lua_code::opcodes::OpCode::SetList,
3443            base as u32,
3444            tostore_arg as u32,
3445            nelems_lo as u32,
3446            1,
3447        );
3448        emit_inst(fs, line, inst);
3449        let extra_inst =
3450            lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, extra as u32);
3451        emit_inst(fs, line, extra_inst);
3452    }
3453    fs.freereg = (base + 1) as u8;
3454}
3455
3456/// Converts a table-and-key expression pair into the appropriate `VINDEX*`
3457/// variant. Mirrors `luaK_indexed` from `lcode.c`. Assumes `t` is already a
3458/// value-producing form (`VLOCAL`, `VNONRELOC`, or `VUPVAL`) and that any
3459/// short-string key has already been promoted to a `VKSTR` constant index.
3460fn cg_indexed(
3461    fs: &mut FuncState,
3462    line: i32,
3463    t: &mut ExprDesc,
3464    k: &mut ExprDesc,
3465) -> Result<(), LuaError> {
3466    t.u.global_const_name = None;
3467    if k.k == ExprKind::KStr {
3468        let s =
3469            k.u.strval
3470                .clone()
3471                .ok_or_else(|| LuaError::syntax(format_args!("internal: VKStr with no strval")))?;
3472        let k_idx = add_k_string(fs, s);
3473        k.u.info = k_idx;
3474        k.k = ExprKind::K;
3475    }
3476    let k_is_kstr =
3477        k.k == ExprKind::K && k.u.info >= 0 && (k.u.info as u32) <= lua_code::opcodes::MAXARG_B;
3478    if t.k == ExprKind::VarArgVar {
3479        cg_exp_to_any_reg(fs, line, k)?;
3480        t.u.ind_t = t.u.var_ridx;
3481        t.u.ind_idx = k.u.info as i16;
3482        t.k = ExprKind::VarArgIndex;
3483        return Ok(());
3484    }
3485    if t.k == ExprKind::UpVal && !k_is_kstr {
3486        cg_exp_to_any_reg(fs, line, t)?;
3487    }
3488    if t.k == ExprKind::UpVal {
3489        let temp = t.u.info as u8;
3490        t.u.ind_t = temp;
3491        t.u.ind_idx = k.u.info as i16;
3492        t.k = ExprKind::IndexUp;
3493        return Ok(());
3494    }
3495    let t_reg = match t.k {
3496        ExprKind::Local => t.u.var_ridx,
3497        ExprKind::NonReloc => t.u.info as u8,
3498        _ => {
3499            return Err(LuaError::syntax(format_args!(
3500                "internal: cg_indexed on non-register table kind {:?}",
3501                t.k
3502            )))
3503        }
3504    };
3505    t.u.ind_t = t_reg;
3506    if k.k == ExprKind::K && k_is_kstr {
3507        t.u.ind_idx = k.u.info as i16;
3508        t.k = ExprKind::IndexStr;
3509    } else if k.k == ExprKind::KInt && cg_fits_int_key(k.u.ival) {
3510        t.u.ind_idx = k.u.ival as i16;
3511        t.k = ExprKind::IndexI;
3512    } else {
3513        cg_exp_to_any_reg(fs, line, k)?;
3514        t.u.ind_idx = k.u.info as i16;
3515        t.k = ExprKind::Indexed;
3516    }
3517    Ok(())
3518}
3519
3520fn cg_fits_int_key(i: i64) -> bool {
3521    i >= 0 && (i as u32) <= lua_code::opcodes::MAXARG_C
3522}
3523
3524/// Emits OP_SELF, converting `e:key(...)` into the equivalent of `(e.key)(e, ...)`.
3525/// Leaves `e` as VNONRELOC pointing at the function register (base); the self
3526/// register is `base + 1`. `key` must be a string expression (VKStr).
3527fn cg_self(
3528    fs: &mut FuncState,
3529    line: i32,
3530    e: &mut ExprDesc,
3531    key: &mut ExprDesc,
3532    keep_self_opcode_for_register_key: bool,
3533) -> Result<(), LuaError> {
3534    cg_exp_to_any_reg(fs, line, e)?;
3535    let ereg = e.u.info;
3536    cg_free_exp(fs, e);
3537    let base = fs.freereg as i32;
3538    e.u.info = base;
3539    e.k = ExprKind::NonReloc;
3540    reserve_regs(fs, 2)?;
3541    let key_str = key.u.strval.clone().ok_or_else(|| {
3542        LuaError::syntax(format_args!(
3543            "internal: cg_self expected VKStr key, got {:?}",
3544            key.k
3545        ))
3546    })?;
3547    let k_idx = add_k_string(fs, key_str);
3548    if (k_idx as u32) <= lua_code::opcodes::MAXINDEXRK {
3549        let inst = lua_code::opcodes::Instruction::abck(
3550            lua_code::opcodes::OpCode::Self_,
3551            base as u32,
3552            ereg as u32,
3553            k_idx as u32,
3554            1,
3555        );
3556        emit_inst(fs, line, inst);
3557    } else if keep_self_opcode_for_register_key {
3558        key.k = ExprKind::K;
3559        key.u.info = k_idx;
3560        cg_exp_to_any_reg(fs, line, key)?;
3561        let inst = lua_code::opcodes::Instruction::abck(
3562            lua_code::opcodes::OpCode::Self_,
3563            base as u32,
3564            ereg as u32,
3565            key.u.info as u32,
3566            0,
3567        );
3568        emit_inst(fs, line, inst);
3569    } else {
3570        key.k = ExprKind::K;
3571        key.u.info = k_idx;
3572        cg_exp_to_any_reg(fs, line, key)?;
3573        let move_inst = lua_code::opcodes::Instruction::abck(
3574            lua_code::opcodes::OpCode::Move,
3575            (base + 1) as u32,
3576            ereg as u32,
3577            0,
3578            0,
3579        );
3580        emit_inst(fs, line, move_inst);
3581        let get_inst = lua_code::opcodes::Instruction::abck(
3582            lua_code::opcodes::OpCode::GetTable,
3583            base as u32,
3584            ereg as u32,
3585            key.u.info as u32,
3586            0,
3587        );
3588        emit_inst(fs, line, get_inst);
3589    }
3590    cg_free_exp(fs, key);
3591    Ok(())
3592}
3593
3594/// Minimal `luaK_exp2anyregup`: if `e` is an upvalue or constant, leave it as
3595/// is; otherwise discharge it into some register.
3596fn cg_exp_to_any_reg_up(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
3597    if matches!(e.k, ExprKind::UpVal | ExprKind::K | ExprKind::VarArgVar) {
3598        return Ok(());
3599    }
3600    cg_exp_to_any_reg(fs, line, e)?;
3601    Ok(())
3602}
3603
3604/// Minimal `luaK_nil`: emits a LoadNil instruction filling `n` consecutive
3605/// registers starting at `from` with `nil`. Does not perform the C
3606/// optimization that merges with a preceding LoadNil.
3607fn cg_emit_nil(fs: &mut FuncState, line: i32, from: i32, n: i32) {
3608    let inst = lua_code::opcodes::Instruction::abck(
3609        lua_code::opcodes::OpCode::LoadNil,
3610        from as u32,
3611        (n - 1) as u32,
3612        0,
3613        0,
3614    );
3615    emit_inst(fs, line, inst);
3616}
3617
3618// ── §6 Label / goto management ───────────────────────────────────────────────
3619
3620fn current_scope_level(ls: &LexState) -> u8 {
3621    let (local_count, first_barrier) = ls.fs.as_ref().map_or((0usize, 0usize), |fs| {
3622        (fs.nactvar as usize, fs.first_scope_barrier)
3623    });
3624    let barrier_count = ls.scope_barriers.len().saturating_sub(first_barrier);
3625    let level = local_count + barrier_count;
3626    level.min(u8::MAX as usize) as u8
3627}
3628
3629fn local_level_for_scope_level(ls: &LexState, scope_level: u8) -> i32 {
3630    let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3631    let barriers_before = ls.scope_barriers[first_barrier..]
3632        .iter()
3633        .filter(|b| b.level < scope_level)
3634        .count();
3635    let locals = scope_level as i32 - barriers_before as i32;
3636    let max_locals = ls.fs.as_ref().map_or(0i32, |fs| fs.nactvar as i32);
3637    locals.clamp(0, max_locals)
3638}
3639
3640fn scope_level_for_local_level(ls: &LexState, local_level: u8) -> u8 {
3641    let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3642    let target = local_level as usize;
3643    let mut locals_seen = 0usize;
3644    for level in 0..=current_scope_level(ls) {
3645        if ls.scope_barriers[first_barrier..]
3646            .iter()
3647            .any(|b| b.level == level)
3648        {
3649            continue;
3650        }
3651        if locals_seen == target {
3652            return level;
3653        }
3654        locals_seen += 1;
3655    }
3656    local_level
3657}
3658
3659fn add_scope_barrier(ls: &mut LexState, name: GcRef<LuaString>) {
3660    let level = current_scope_level(ls);
3661    ls.scope_barriers.push(ScopeBarrier { level, name });
3662}
3663
3664fn latest_matching_global_barrier_current(ls: &LexState, name: &GcRef<LuaString>) -> Option<u8> {
3665    let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3666    ls.scope_barriers[first_barrier..]
3667        .iter()
3668        .rev()
3669        .find(|b| GcRef::ptr_eq(&b.name, name))
3670        .map(|b| b.level)
3671}
3672
3673fn has_active_global_barrier(ls: &LexState, name: &GcRef<LuaString>) -> bool {
3674    ls.scope_barriers
3675        .iter()
3676        .rev()
3677        .any(|b| GcRef::ptr_eq(&b.name, name))
3678}
3679
3680fn is_active_global_function_name(ls: &LexState, name: &GcRef<LuaString>) -> bool {
3681    ls.global_function_names
3682        .iter()
3683        .rev()
3684        .any(|n| GcRef::ptr_eq(n, name))
3685}
3686
3687fn scope_name_at(ls: &LexState, level: u8, label_nactvar: u8) -> Vec<u8> {
3688    let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3689    for scope_level in level..label_nactvar {
3690        if let Some(barrier) = ls.scope_barriers[first_barrier..]
3691            .iter()
3692            .find(|b| b.level == scope_level)
3693        {
3694            return barrier.name.as_bytes().to_vec();
3695        }
3696
3697        let barriers_before = ls.scope_barriers[first_barrier..]
3698            .iter()
3699            .filter(|b| b.level < scope_level)
3700            .count();
3701        let vidx = scope_level as i32 - barriers_before as i32;
3702        if vidx < 0 {
3703            continue;
3704        }
3705        if let Some(name) = ls.fs.as_ref().and_then(|fs| {
3706            if (fs.firstlocal + vidx) >= 0
3707                && ((fs.firstlocal + vidx) as usize) < ls.dyd.actvar.len()
3708            {
3709                let vd = get_local_var_desc(ls, fs, vidx);
3710                vd.name.as_ref().map(|n| n.as_bytes().to_vec())
3711            } else {
3712                None
3713            }
3714        }) {
3715            return name;
3716        }
3717    }
3718
3719    b"*".to_vec()
3720}
3721
3722fn jumpscopeerror(
3723    ls: &LexState,
3724    version: lua_types::LuaVersion,
3725    gt_idx: usize,
3726    label_nactvar: u8,
3727) -> LuaError {
3728    let gt = &ls.dyd.gt[gt_idx];
3729    let line = gt.line;
3730    let gt_name_bytes: &[u8] = gt.name.as_ref().map(|n| n.as_bytes()).unwrap_or(b"");
3731    let gt_name = String::from_utf8_lossy(gt_name_bytes);
3732    let varname_bytes = scope_name_at(ls, gt.nactvar, label_nactvar);
3733    let varname = String::from_utf8_lossy(&varname_bytes);
3734    if version == lua_types::LuaVersion::V55 {
3735        LuaError::syntax(format_args!(
3736            "<goto {}> at line {} jumps into the scope of '{}'",
3737            gt_name, line, varname
3738        ))
3739    } else {
3740        LuaError::syntax(format_args!(
3741            "<goto {}> at line {} jumps into the scope of local '{}'",
3742            gt_name, line, varname
3743        ))
3744    }
3745}
3746
3747/// Resolves goto at index `g` to `label`, removing it from pending list.
3748fn solvegoto(
3749    ls: &mut LexState,
3750    state: &mut LuaState,
3751    g: usize,
3752    label_pc: i32,
3753    label_nactvar: u8,
3754) -> Result<(), LuaError> {
3755    if ls.dyd.gt[g].nactvar < label_nactvar {
3756        let version = state.global().lua_version;
3757        return Err(jumpscopeerror(ls, version, g, label_nactvar));
3758    }
3759    let gt_pc = ls.dyd.gt[g].pc;
3760    cg_patch_list(ls.fs.as_mut().unwrap(), gt_pc, label_pc)?;
3761    ls.dyd.gt.remove(g);
3762    Ok(())
3763}
3764
3765/// Searches for an active label with the given name, starting the scan at the
3766/// label-list index `first`.
3767///
3768/// The scan-start encodes the version-specific scope of goto resolution. In Lua
3769/// 5.2/5.3, upstream `gotostat` resolves a goto against labels of the **current
3770/// block only** (`fs->bl->firstlabel`); a goto that matches no current-block
3771/// label stays pending and is resolved later when its label is declared (or is
3772/// moved out to the enclosing block on block exit). In 5.4/5.5 `findlabel` was
3773/// changed to scan the whole function (`fs->firstlabel`).
3774fn findlabel_from(ls: &LexState, name: &GcRef<LuaString>, first: usize) -> Option<usize> {
3775    for i in first..ls.dyd.label.len() {
3776        let lb = &ls.dyd.label[i];
3777        if lb.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
3778            return Some(i);
3779        }
3780    }
3781    None
3782}
3783
3784/// Resolves a goto against labels visible per the active version's rules.
3785///
3786/// 5.2/5.3 scan only the current block; 5.4/5.5 scan the whole function.
3787fn findlabel_for_goto(ls: &LexState, state: &LuaState, name: &GcRef<LuaString>) -> Option<usize> {
3788    let block_scoped = matches!(
3789        state.global().lua_version,
3790        lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3791    );
3792    let first = if block_scoped {
3793        ls.fs
3794            .as_ref()
3795            .unwrap()
3796            .bl
3797            .as_ref()
3798            .map_or(0, |b| b.firstlabel) as usize
3799    } else {
3800        ls.fs.as_ref().unwrap().firstlabel as usize
3801    };
3802    findlabel_from(ls, name, first)
3803}
3804
3805/// Adds a new label/goto entry; returns its index.
3806fn new_label_entry(
3807    ls: &mut LexState,
3808    _state: &mut LuaState,
3809    is_goto: bool,
3810    name: GcRef<LuaString>,
3811    line: i32,
3812    pc: i32,
3813) -> Result<usize, LuaError> {
3814    let nactvar = current_scope_level(ls);
3815    let entry = LabelDesc {
3816        name: Some(name),
3817        pc,
3818        line,
3819        nactvar,
3820        close: false,
3821    };
3822    let list = if is_goto {
3823        &mut ls.dyd.gt
3824    } else {
3825        &mut ls.dyd.label
3826    };
3827    let n = list.len();
3828    list.push(entry);
3829    Ok(n)
3830}
3831
3832fn new_goto_entry(
3833    ls: &mut LexState,
3834    state: &mut LuaState,
3835    name: GcRef<LuaString>,
3836    line: i32,
3837    pc: i32,
3838) -> Result<usize, LuaError> {
3839    new_label_entry(ls, state, true, name, line, pc)
3840}
3841
3842/// Resolves all pending gotos that match label `lb`.
3843/// Returns true if any goto needed close.
3844fn solvegotos(ls: &mut LexState, state: &mut LuaState, lb_idx: usize) -> Result<bool, LuaError> {
3845    let lb_name = ls.dyd.label[lb_idx].name.clone();
3846    let lb_pc = ls.dyd.label[lb_idx].pc;
3847    let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
3848    let first_goto = ls
3849        .fs
3850        .as_ref()
3851        .unwrap()
3852        .bl
3853        .as_ref()
3854        .map_or(0, |b| b.firstgoto) as usize;
3855
3856    let mut i = first_goto;
3857    let mut needs_close = false;
3858    while i < ls.dyd.gt.len() {
3859        let gt_name = ls.dyd.gt[i].name.clone();
3860        let names_match = lb_name
3861            .as_ref()
3862            .and_then(|ln| gt_name.as_ref().map(|gn| GcRef::ptr_eq(ln, gn)))
3863            .unwrap_or(false);
3864        if names_match {
3865            needs_close |= ls.dyd.gt[i].close;
3866            // solvegoto removes element i, so don't increment i
3867            solvegoto(ls, state, i, lb_pc, lb_nactvar)?;
3868        } else {
3869            i += 1;
3870        }
3871    }
3872    Ok(needs_close)
3873}
3874
3875/// Creates a new label; resolves pending gotos. Returns true if CLOSE emitted.
3876fn createlabel(
3877    ls: &mut LexState,
3878    state: &mut LuaState,
3879    name: GcRef<LuaString>,
3880    line: i32,
3881    last: bool,
3882) -> Result<bool, LuaError> {
3883    let label_pc = cg_get_label(ls.fs.as_mut().unwrap());
3884    let l = new_label_entry(ls, state, false, name, line, label_pc)?;
3885    if last {
3886        let bl_scope_level = ls
3887            .fs
3888            .as_ref()
3889            .unwrap()
3890            .bl
3891            .as_ref()
3892            .map_or(0, |b| b.scope_level);
3893        ls.dyd.label[l].nactvar = bl_scope_level;
3894    }
3895    let needs_close = solvegotos(ls, state, l)?;
3896    if needs_close {
3897        let nstack = nvarstack(ls, ls.fs.as_ref().unwrap()) as u32;
3898        let inst =
3899            lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::Close, nstack, 0, 0, 0);
3900        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
3901        return Ok(true);
3902    }
3903    Ok(false)
3904}
3905
3906/// Adjusts pending gotos to outer block level when leaving a block.
3907///
3908/// For 5.4/5.5 this only re-levels the pending gotos to the enclosing block
3909/// (backward gotos were already resolved eagerly in `gotostat`, whose
3910/// `findlabel` scans the whole function). For 5.2/5.3, `gotostat` resolves a
3911/// goto only against the current block, so a backward goto to an enclosing
3912/// block's label is still pending here; upstream 5.3 `movegotosout` re-runs
3913/// the (now current-block-scoped) `findlabel` to close such gotos. This must be
3914/// called *after* the leaving block has been popped, so the current block is
3915/// the enclosing one.
3916fn movegotosout(
3917    ls: &mut LexState,
3918    state: &mut LuaState,
3919    bl_firstgoto: usize,
3920    bl_scope_level: u8,
3921    bl_upval: bool,
3922) -> Result<(), LuaError> {
3923    let reresolve = matches!(
3924        state.global().lua_version,
3925        lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3926    );
3927    let mut i = bl_firstgoto;
3928    while i < ls.dyd.gt.len() {
3929        if reresolve {
3930            if ls.dyd.gt[i].nactvar > bl_scope_level {
3931                if bl_upval {
3932                    ls.dyd.gt[i].close = true;
3933                }
3934                ls.dyd.gt[i].nactvar = bl_scope_level;
3935            }
3936        } else {
3937            if bl_upval {
3938                ls.dyd.gt[i].close = true;
3939            }
3940            ls.dyd.gt[i].nactvar = bl_scope_level;
3941        }
3942        if reresolve {
3943            let gt_name = ls.dyd.gt[i].name.clone();
3944            let lb_idx = gt_name
3945                .as_ref()
3946                .and_then(|n| findlabel_for_goto(ls, state, n));
3947            if let Some(lb_idx) = lb_idx {
3948                let lb_pc = ls.dyd.label[lb_idx].pc;
3949                let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
3950                let trigger1 = ls.dyd.gt[i].close;
3951                let close_level = goto_close_level(ls, lb_nactvar, bl_scope_level, trigger1);
3952                if let Some(level) = close_level {
3953                    resolve_goto_with_close(ls, state, i, lb_pc, lb_nactvar, level)?;
3954                } else {
3955                    solvegoto(ls, state, i, lb_pc, lb_nactvar)?;
3956                }
3957                continue;
3958            }
3959        }
3960        i += 1;
3961    }
3962    Ok(())
3963}
3964
3965/// Computes the scope level at which a backward goto resolving to an
3966/// enclosing-block label (`label_nactvar`) must close upvalues, or `None` if no
3967/// close is needed.
3968///
3969/// This mirrors the two `luaK_patchclose` callsites upstream 5.3 reaches while
3970/// resolving a pending goto in `movegotosout`:
3971///
3972///   1. `movegotosout` itself: if the exited block captured upvalues and the
3973///      goto leaves that block's scope, close at the exited block's level
3974///      (`bl_scope_level`). This is exactly when the goto entry's `close` flag
3975///      was set just before re-leveling, passed in as `trigger1`.
3976///   2. `findlabel`: if the goto also leaves the target label's scope
3977///      (`bl_scope_level > label_nactvar`, since the goto's level was already
3978///      re-leveled to `bl_scope_level`) and the enclosing block either captured
3979///      upvalues or holds at least one label, close at the *label's* level
3980///      (`label_nactvar`).
3981///
3982/// Upstream applies these with `SETARG_A` so the later (smaller, more inclusive)
3983/// level wins; this returns that minimum. Trigger 2 dominates whenever it fires
3984/// because `label_nactvar <= bl_scope_level` for an enclosing label, so closing
3985/// at the label's level also covers locals declared after the label in the
3986/// label's own block (e.g. `goto.lua`'s `local b` redeclared just after `::l1::`).
3987fn goto_close_level(
3988    ls: &LexState,
3989    label_nactvar: u8,
3990    bl_scope_level: u8,
3991    trigger1: bool,
3992) -> Option<u8> {
3993    let enclosing = ls.fs.as_ref().unwrap().bl.as_ref();
3994    let enclosing_upval = enclosing.map_or(false, |b| b.upval);
3995    let enclosing_has_label =
3996        enclosing.map_or(false, |b| ls.dyd.label.len() as i32 > b.firstlabel);
3997    let trigger2 = bl_scope_level > label_nactvar && (enclosing_upval || enclosing_has_label);
3998    match (trigger1, trigger2) {
3999        (_, true) => Some(label_nactvar),
4000        (true, false) => Some(bl_scope_level),
4001        (false, false) => None,
4002    }
4003}
4004
4005/// Resolves a pending backward goto (index `g`) to an enclosing-block label at
4006/// `label_pc`, closing the upvalues of the locals the goto exits at scope level
4007/// `close_scope_level` (from [`goto_close_level`]).
4008///
4009/// In block-scoped goto (5.2/5.3) a backward goto whose target label lives in an
4010/// enclosing block is resolved here, in `movegotosout`, after the inner block
4011/// has been popped. Upstream lua-c patches the goto's own `OP_JMP` to carry a
4012/// close (`luaK_patchclose`, the JMP's `A` field). This port's bytecode is the
4013/// 5.4 format, whose `OP_JMP` carries no close field — closes are explicit
4014/// `OP_CLOSE` instructions. So instead of patching the JMP in place, this emits a
4015/// `CLOSE; JMP→label` trampoline at the current pc and redirects the goto's
4016/// original JMP to land on the `CLOSE`. The upvalues of the exited locals are
4017/// therefore closed on every backward iteration, giving each iteration a fresh
4018/// upvalue cell (the behavior `goto.lua`'s upvalue-closing tests assert under
4019/// 5.2/5.3).
4020fn resolve_goto_with_close(
4021    ls: &mut LexState,
4022    state: &mut LuaState,
4023    g: usize,
4024    label_pc: i32,
4025    label_nactvar: u8,
4026    close_scope_level: u8,
4027) -> Result<(), LuaError> {
4028    if ls.dyd.gt[g].nactvar < label_nactvar {
4029        let version = state.global().lua_version;
4030        return Err(jumpscopeerror(ls, version, g, label_nactvar));
4031    }
4032    let line = ls.dyd.gt[g].line;
4033    let gt_pc = ls.dyd.gt[g].pc;
4034    let close_local_level = local_level_for_scope_level(ls, close_scope_level);
4035    let close_level = reg_level(ls, ls.fs.as_ref().unwrap(), close_local_level) as u32;
4036    let close_pc = {
4037        let inst = lua_code::opcodes::Instruction::abck(
4038            lua_code::opcodes::OpCode::Close,
4039            close_level,
4040            0,
4041            0,
4042            0,
4043        );
4044        emit_inst(ls.fs.as_mut().unwrap(), line, inst)
4045    };
4046    let jmp_pc = cg_jump(ls.fs.as_mut().unwrap(), line);
4047    cg_patch_list(ls.fs.as_mut().unwrap(), jmp_pc, label_pc)?;
4048    cg_patch_list(ls.fs.as_mut().unwrap(), gt_pc, close_pc)?;
4049    ls.dyd.gt.remove(g);
4050    Ok(())
4051}
4052
4053/// Pushes a new block scope onto fs->bl.
4054fn enter_block(ls: &mut LexState, isloop: bool) {
4055    let firstlabel = ls.dyd.label.len() as i32;
4056    let firstgoto = ls.dyd.gt.len() as i32;
4057    let saved_global_strict = ls.global_strict;
4058    let saved_declared_globals = ls.declared_globals.len();
4059    let saved_global_wildcard = ls.global_wildcard;
4060    let saved_global_wildcard_const = ls.global_wildcard_const;
4061    let saved_scope_barriers = ls.scope_barriers.len();
4062    let scope_level = current_scope_level(ls);
4063    let insidetbc = ls
4064        .fs
4065        .as_ref()
4066        .and_then(|f| f.bl.as_ref())
4067        .map_or(false, |b| b.insidetbc);
4068    let fs = ls.fs.as_mut().unwrap();
4069    let nactvar = fs.nactvar;
4070    let new_bl = Box::new(BlockCnt {
4071        previous: fs.bl.take(),
4072        firstlabel,
4073        firstgoto,
4074        nactvar,
4075        scope_level,
4076        upval: false,
4077        isloop,
4078        insidetbc,
4079        saved_global_strict,
4080        saved_declared_globals,
4081        saved_global_wildcard,
4082        saved_global_wildcard_const,
4083        saved_scope_barriers,
4084    });
4085    fs.bl = Some(new_bl);
4086    debug_assert!(
4087        fs.freereg as i32 == {
4088            // TODO(port): nvarstack(ls, fs) -- circular borrow
4089            fs.freereg as i32 // placeholder assertion
4090        }
4091    );
4092}
4093
4094fn undef_goto(ls: &mut LexState, version: lua_types::LuaVersion, gt_idx: usize) -> LuaError {
4095    let (line, name_bytes): (i32, Vec<u8>) = {
4096        let gt = &ls.dyd.gt[gt_idx];
4097        (
4098            gt.line,
4099            gt.name
4100                .as_ref()
4101                .map(|n| n.as_bytes().to_vec())
4102                .unwrap_or_default(),
4103        )
4104    };
4105    let msg = if name_bytes == b"break" {
4106        // 5.2/5.3 word the deferred break-outside-loop error differently from
4107        // 5.4. (5.1/5.5 raise eagerly in `breakstat` and never reach here.)
4108        if matches!(
4109            version,
4110            lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
4111        ) {
4112            format!("<break> at line {} not inside a loop", line)
4113        } else {
4114            format!("break outside loop at line {}", line)
4115        }
4116    } else {
4117        let name_str = String::from_utf8_lossy(&name_bytes);
4118        format!(
4119            "no visible label '{}' for <goto> at line {}",
4120            name_str, line
4121        )
4122    };
4123    lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0)
4124}
4125
4126/// Pops the innermost block scope, emitting CLOSE if needed.
4127fn leave_block(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4128    // Snapshot block fields without popping; createlabel below relies on
4129    // fs->bl still pointing at this (loop) block so solvegotos can read
4130    // fs->bl->firstgoto.
4131    let (bl_nactvar, bl_scope_level, bl_isloop, bl_upval, bl_firstgoto, bl_firstlabel) = {
4132        let bl = ls
4133            .fs
4134            .as_ref()
4135            .unwrap()
4136            .bl
4137            .as_ref()
4138            .expect("leave_block: no current block");
4139        (
4140            bl.nactvar,
4141            bl.scope_level,
4142            bl.isloop,
4143            bl.upval,
4144            bl.firstgoto,
4145            bl.firstlabel,
4146        )
4147    };
4148
4149    // Lua 5.5: restore the `global`-declaration scope to what it was on block
4150    // entry, so an explicit `global` decl (and the strict mode it triggers) is
4151    // confined to its enclosing block.
4152    {
4153        let (sgs, sdg, sgw, sgwc, ssb) = {
4154            let bl = ls.fs.as_ref().unwrap().bl.as_ref().unwrap();
4155            (
4156                bl.saved_global_strict,
4157                bl.saved_declared_globals,
4158                bl.saved_global_wildcard,
4159                bl.saved_global_wildcard_const,
4160                bl.saved_scope_barriers,
4161            )
4162        };
4163        ls.global_strict = sgs;
4164        ls.declared_globals.truncate(sdg);
4165        ls.global_wildcard = sgw;
4166        ls.global_wildcard_const = sgwc;
4167        ls.scope_barriers.truncate(ssb);
4168    }
4169
4170    let stklevel = reg_level(ls, ls.fs.as_ref().unwrap(), bl_nactvar as i32);
4171    let mut fs_box = ls.fs.take().unwrap();
4172    remove_vars(ls, &mut fs_box, bl_nactvar as i32);
4173    debug_assert!(bl_nactvar == fs_box.nactvar);
4174    ls.fs = Some(fs_box);
4175
4176    let hasclose = if bl_isloop {
4177        let break_str = state.intern_str(b"break")?;
4178        createlabel(ls, state, break_str, 0, false)?
4179    } else {
4180        false
4181    };
4182
4183    // Now pop the block off fs.bl, restoring its previous link.
4184    let mut bl_box = ls.fs.as_mut().unwrap().bl.take().unwrap();
4185    let previous = bl_box.previous.take();
4186    ls.fs.as_mut().unwrap().bl = previous;
4187
4188    let has_prev_block = ls.fs.as_ref().unwrap().bl.is_some();
4189    if !hasclose && has_prev_block && bl_upval {
4190        // Use `lastline` so the OP_CLOSE attributes to the block's terminating
4191        // token (END/UNTIL) rather than whatever the parser has peeked to next.
4192        // Mirrors lua-c's `savelineinfo(fs, f, fs->ls->lastline)`.
4193        let line = ls.lastline;
4194        let inst = lua_code::opcodes::Instruction::abck(
4195            lua_code::opcodes::OpCode::Close,
4196            stklevel as u32,
4197            0,
4198            0,
4199            0,
4200        );
4201        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4202    }
4203    ls.fs.as_mut().unwrap().freereg = stklevel as u8;
4204
4205    ls.dyd.label.truncate(bl_firstlabel as usize);
4206
4207    if has_prev_block {
4208        movegotosout(ls, state, bl_firstgoto as usize, bl_scope_level, bl_upval)?;
4209    } else {
4210        if (bl_firstgoto as usize) < ls.dyd.gt.len() {
4211            let version = state.global().lua_version;
4212            return Err(undef_goto(ls, version, bl_firstgoto as usize));
4213        }
4214    }
4215    Ok(())
4216}
4217
4218// ── §7 Proto management ──────────────────────────────────────────────────────
4219
4220/// Adds a new prototype slot to the current function's proto list.
4221/// Returns a mutable reference to the new prototype.
4222fn add_prototype(ls: &mut LexState, _state: &mut LuaState) -> Result<Box<LuaProto>, LuaError> {
4223    let np = ls.fs.as_ref().unwrap().np as usize;
4224    // TODO(port): allocate via state.gc().new_proto() in Phase B
4225    let new_proto = Box::new(LuaProto::placeholder());
4226    while ls.fs.as_ref().unwrap().f.p.len() <= np {
4227        ls.fs
4228            .as_mut()
4229            .unwrap()
4230            .f
4231            .p
4232            .push(GcRef::new(LuaProto::placeholder()));
4233    }
4234    ls.fs.as_mut().unwrap().np += 1;
4235    Ok(new_proto)
4236}
4237
4238/// Emits OP_CLOSURE in the parent function and fixes up v.
4239fn codeclosure(ls: &mut LexState, _state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4240    let line = ls.lastline;
4241    let mut child = ls.fs.take().expect("codeclosure: no current FuncState");
4242    let result = (|| -> Result<(), LuaError> {
4243        let parent = child
4244            .prev
4245            .as_mut()
4246            .expect("codeclosure: child FuncState has no parent (called outside body()?)");
4247        let bx = (parent.np - 1) as u32;
4248        let inst = lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::Closure, 0, bx);
4249        let pc = emit_inst(parent, line, inst);
4250        init_exp(v, ExprKind::Reloc, pc);
4251        cg_exp_to_next_reg(parent, line, v)
4252    })();
4253    ls.fs = Some(child);
4254    result
4255}
4256
4257/// Installs `new_fs` as the current FuncState, pushing old one as `prev`.
4258fn open_func(
4259    ls: &mut LexState,
4260    _state: &mut LuaState,
4261    mut new_fs: FuncState,
4262) -> Result<(), LuaError> {
4263    new_fs.prev = ls.fs.take();
4264
4265    let f = &mut new_fs.f;
4266    new_fs.pc = 0;
4267    new_fs.previousline = f.linedefined;
4268    new_fs.iwthabs = 0;
4269    new_fs.lasttarget = 0;
4270    new_fs.freereg = 0;
4271    new_fs.nk = 0;
4272    new_fs.nabslineinfo = 0;
4273    new_fs.np = 0;
4274    new_fs.nups = 0;
4275    new_fs.ndebugvars = 0;
4276    new_fs.nactvar = 0;
4277    new_fs.needclose = false;
4278
4279    new_fs.firstlocal = ls.dyd.actvar.len() as i32;
4280    new_fs.firstlabel = ls.dyd.label.len() as i32;
4281    new_fs.bl = None;
4282
4283    new_fs.f.source = ls.source.clone();
4284    new_fs.f.maxstacksize = 2;
4285
4286    ls.fs = Some(Box::new(new_fs));
4287
4288    enter_block(ls, false);
4289    Ok(())
4290}
4291
4292/// Finalizes and pops the current FuncState.
4293/// Returns the completed LuaProto.
4294fn close_func(ls: &mut LexState, state: &mut LuaState) -> Result<Box<LuaProto>, LuaError> {
4295    {
4296        let first = {
4297            let fs = ls.fs.as_ref().unwrap();
4298            nvarstack(ls, fs)
4299        };
4300        let line = ls.lastline;
4301        let fs = ls.fs.as_mut().unwrap();
4302        let inst = lua_code::opcodes::Instruction::abck(
4303            lua_code::opcodes::OpCode::Return0,
4304            first as u32,
4305            1,
4306            0,
4307            0,
4308        );
4309        emit_inst(fs, line, inst);
4310    }
4311    leave_block(ls, state)?;
4312    debug_assert!(ls.fs.as_ref().unwrap().bl.is_none());
4313
4314    //                     and needclose, and resolve JMP chains to final target.
4315    cg_finish(ls.fs.as_mut().unwrap());
4316
4317    {
4318        let fs = ls.fs.as_mut().unwrap();
4319        let pc = fs.pc as usize;
4320        let nabslineinfo = fs.nabslineinfo as usize;
4321        let nk = fs.nk as usize;
4322        let np = fs.np as usize;
4323        let ndebugvars = fs.ndebugvars as usize;
4324        let nups = fs.nups as usize;
4325        fs.f.code.truncate(pc);
4326        fs.f.lineinfo.truncate(pc);
4327        fs.f.abslineinfo.truncate(nabslineinfo);
4328        fs.f.k.truncate(nk);
4329        fs.f.p.truncate(np);
4330        fs.f.locvars.truncate(ndebugvars);
4331        fs.f.upvalues.truncate(nups);
4332    }
4333
4334    let mut fs_box = ls.fs.take().unwrap();
4335    ls.fs = fs_box.prev.take();
4336
4337    Ok(fs_box.f)
4338}
4339
4340// ── §8 Grammar rules — block / statement lists ───────────────────────────────
4341
4342/// Returns true if the current token can end a block.
4343fn block_follow(ls: &LexState, withuntil: bool) -> bool {
4344    match ls.t.token {
4345        TK_ELSE | TK_ELSEIF | TK_END | TK_EOS => true,
4346        TK_UNTIL => withuntil,
4347        _ => false,
4348    }
4349}
4350
4351fn statlist(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4352    let v51 = state.global().lua_version == lua_types::LuaVersion::V51;
4353    while !block_follow(ls, true) {
4354        if ls.t.token == TK_RETURN {
4355            statement(ls, state)?;
4356            return Ok(());
4357        }
4358        statement(ls, state)?;
4359        if v51 {
4360            test_next(ls, state, b';' as TokenKind)?;
4361        }
4362    }
4363    Ok(())
4364}
4365
4366/// Handles '.' NAME or ':' NAME field selection.
4367fn fieldsel(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4368    let line = ls.lastline;
4369    cg_exp_to_any_reg_up(ls.fs.as_mut().unwrap(), line, v)?;
4370    lex_next(ls, state)?; // skip '.' or ':'
4371    let mut key = ExprDesc::default();
4372    codename(ls, state, &mut key)?;
4373    cg_indexed(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
4374    Ok(())
4375}
4376
4377/// Handles '[' expr ']' indexing.
4378/// Port of `luaK_exp2val` (`lcode.c`): if the expression carries a pending jump
4379/// list (a relational/boolean result), force it into a real register so its
4380/// boolean materialization is emitted before any later instruction; otherwise
4381/// just discharge its variable form. Used by `yindex` so an upvalue indexed by
4382/// a comparison key (`_ENV[1<2]`) lowers correctly.
4383///
4384/// `materialize_jmp` ports the version-specific guard. Lua 5.5's `luaK_exp2val`
4385/// reads `if (e->k == VJMP || hasjumps(e))`; Lua 5.3 and 5.4 read only
4386/// `if (hasjumps(e))`. Because our shared codegen lowers an upvalue index to a
4387/// register-based GETTABUP for every version (unlike 5.3's RK-based form), the
4388/// `VJMP` clause must also be applied for 5.3 to reproduce its `nil` result.
4389/// Lua 5.4 deliberately omits the clause — its reference genuinely raises
4390/// "attempt to index a number value" for `_ENV[1<2]`, an upstream behavior 5.5
4391/// later fixed — so `materialize_jmp` is false on 5.4.
4392fn exp_to_val(
4393    fs: &mut FuncState,
4394    line: i32,
4395    e: &mut ExprDesc,
4396    materialize_jmp: bool,
4397) -> Result<(), LuaError> {
4398    if (materialize_jmp && e.k == ExprKind::Jmp) || e.t != e.f {
4399        cg_exp_to_any_reg(fs, line, e)?;
4400    } else {
4401        cg_discharge_vars(fs, line, e)?;
4402    }
4403    Ok(())
4404}
4405
4406fn yindex(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4407    lex_next(ls, state)?;
4408    expr(ls, state, v)?;
4409    let line = ls.linenumber;
4410    let materialize_jmp = state.global().lua_version != lua_types::LuaVersion::V54;
4411    exp_to_val(ls.fs.as_mut().unwrap(), line, v, materialize_jmp)?;
4412    check_next(ls, state, b']' as TokenKind)?;
4413    Ok(())
4414}
4415
4416// ── §9 Constructor rules ─────────────────────────────────────────────────────
4417
4418fn recfield(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
4419    let reg = ls.fs.as_ref().unwrap().freereg as i32;
4420    let mut key = ExprDesc::default();
4421    let mut val = ExprDesc::default();
4422    if ls.t.token == TK_NAME {
4423        let fs = ls.fs.as_ref().unwrap();
4424        check_limit(fs, cc.nh, i32::MAX, "items in a constructor")?;
4425        codename(ls, state, &mut key)?;
4426    } else {
4427        yindex(ls, state, &mut key)?;
4428    }
4429    cc.nh += 1;
4430    check_next(ls, state, b'=' as TokenKind)?;
4431    let mut tab = cc.t.clone();
4432    let line = ls.lastline;
4433    cg_indexed(ls.fs.as_mut().unwrap(), line, &mut tab, &mut key)?;
4434    expr(ls, state, &mut val)?;
4435    cg_storevar(ls.fs.as_mut().unwrap(), line, &tab, &mut val)?;
4436    ls.fs.as_mut().unwrap().freereg = reg as u8;
4437    Ok(())
4438}
4439
4440fn closelistfield(
4441    ls: &mut LexState,
4442    state: &mut LuaState,
4443    cc: &mut ConsControl,
4444) -> Result<(), LuaError> {
4445    let _ = state;
4446    if cc.v.k == ExprKind::Void {
4447        return Ok(());
4448    }
4449    let line = ls.lastline;
4450    cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut cc.v)?;
4451    cc.v.k = ExprKind::Void;
4452    if cc.tostore == LFIELDS_PER_FLUSH {
4453        let t_info = cc.t.u.info;
4454        cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, cc.tostore);
4455        cc.na += cc.tostore;
4456        cc.tostore = 0;
4457    }
4458    Ok(())
4459}
4460
4461fn lastlistfield(
4462    ls: &mut LexState,
4463    state: &mut LuaState,
4464    cc: &mut ConsControl,
4465) -> Result<(), LuaError> {
4466    let _ = state;
4467    if cc.tostore == 0 {
4468        return Ok(());
4469    }
4470    let t_info = cc.t.u.info;
4471    let line = ls.lastline;
4472    if cc.v.k.has_mult_ret() {
4473        cg_set_returns(ls.fs.as_mut().unwrap(), &mut cc.v, LUA_MULTRET);
4474        cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, LUA_MULTRET);
4475        cc.na -= 1;
4476    } else {
4477        if cc.v.k != ExprKind::Void {
4478            cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut cc.v)?;
4479        }
4480        cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, cc.tostore);
4481    }
4482    cc.na += cc.tostore;
4483    Ok(())
4484}
4485
4486fn listfield(
4487    ls: &mut LexState,
4488    state: &mut LuaState,
4489    cc: &mut ConsControl,
4490) -> Result<(), LuaError> {
4491    expr(ls, state, &mut cc.v)?;
4492    cc.tostore += 1;
4493    Ok(())
4494}
4495
4496fn field(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
4497    match ls.t.token {
4498        TK_NAME => {
4499            let next_is_eq = lex_lookahead(ls, state)? == b'=' as TokenKind;
4500            if !next_is_eq {
4501                listfield(ls, state, cc)?;
4502            } else {
4503                recfield(ls, state, cc)?;
4504            }
4505        }
4506        c if c == b'[' as TokenKind => {
4507            recfield(ls, state, cc)?;
4508        }
4509        _ => {
4510            listfield(ls, state, cc)?;
4511        }
4512    }
4513    Ok(())
4514}
4515
4516fn constructor(ls: &mut LexState, state: &mut LuaState, t: &mut ExprDesc) -> Result<(), LuaError> {
4517    let line = ls.lastline;
4518    let pc = cg_emit_newtable(ls.fs.as_mut().unwrap(), line);
4519
4520    let freereg = ls.fs.as_ref().unwrap().freereg as i32;
4521    init_exp(t, ExprKind::NonReloc, freereg);
4522    reserve_regs(ls.fs.as_mut().unwrap(), 1)?;
4523
4524    let mut cc = ConsControl {
4525        v: ExprDesc::default(),
4526        t: t.clone(),
4527        nh: 0,
4528        na: 0,
4529        tostore: 0,
4530    };
4531
4532    check_next(ls, state, b'{' as TokenKind)?;
4533    loop {
4534        debug_assert!(cc.v.k == ExprKind::Void || cc.tostore > 0);
4535        if ls.t.token == b'}' as TokenKind {
4536            break;
4537        }
4538        closelistfield(ls, state, &mut cc)?;
4539        field(ls, state, &mut cc)?;
4540        if !test_next(ls, state, b',' as TokenKind)? && !test_next(ls, state, b';' as TokenKind)? {
4541            break;
4542        }
4543    }
4544    check_match(ls, state, b'}' as TokenKind, b'{' as TokenKind, line)?;
4545    lastlistfield(ls, state, &mut cc)?;
4546
4547    let t_info = t.u.info;
4548    cg_settablesize(ls.fs.as_mut().unwrap(), pc, t_info, cc.na, cc.nh);
4549    Ok(())
4550}
4551
4552// ── §10 Parameter list and function body ─────────────────────────────────────
4553
4554fn setvararg(fs: &mut FuncState, _state: &mut LuaState, nparams: i32) -> Result<(), LuaError> {
4555    fs.f.is_vararg = true;
4556    let inst = lua_code::opcodes::Instruction::abck(
4557        lua_code::opcodes::OpCode::VarArgPrep,
4558        nparams as u32,
4559        0,
4560        0,
4561        0,
4562    );
4563    let line = fs.previousline;
4564    emit_inst(fs, line, inst);
4565    Ok(())
4566}
4567
4568fn parlist(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4569    let mut nparams: i32 = 0;
4570    let mut isvararg = false;
4571    // Lua 5.5 adds a vararg-parameter local after the fixed parameters. In the
4572    // named form (`function f(...t)`) it is the packed table `t`; in the plain
4573    // form (`function f(...)`) it is a hidden "(vararg table)" debug local.
4574    // Pre-5.5 versions do not reserve that local, and a name after `...` stays
4575    // a parse error because the loop breaks as soon as it sees `...`.
4576    let is_v55 = state.global().lua_version == lua_types::LuaVersion::V55;
4577    // Lua 5.1 (`LUA_COMPAT_VARARG`) gives every vararg function an implicit local
4578    // named `arg`, a `table.pack`-style table of the extra arguments (`arg.n` is
4579    // the count). It is declared as an ordinary local right after the fixed
4580    // parameters, mirroring `parlist`'s `new_localvarliteral(ls, "arg", ...)`
4581    // plus `VARARG_HASARG | VARARG_NEEDSARG`. 5.2 removed it, so this is V51-only.
4582    let is_v51 = state.global().lua_version == lua_types::LuaVersion::V51;
4583    let mut has_vararg_local = false;
4584    let mut has_vararg_name = false;
4585    let mut has_arg_local = false;
4586    let mut vararg_name_vidx: Option<i32> = None;
4587    if ls.t.token != b')' as TokenKind {
4588        loop {
4589            match ls.t.token {
4590                TK_NAME => {
4591                    let name = str_check_name(ls, state)?;
4592                    new_local_var(ls, state, name)?;
4593                    nparams += 1;
4594                }
4595                TK_DOTS => {
4596                    lex_next(ls, state)?;
4597                    isvararg = true;
4598                    // 5.5 named varargs: a NAME after `...` is the vararg-table
4599                    // parameter. Push it as a local here (mirroring upstream's
4600                    // `new_varkind(..., RDKVAVAR)`); it is activated by the
4601                    // separate `adjust_local_vars(1)` below, and materialized at
4602                    // function entry by VARARGPACK.
4603                    if is_v55 && ls.t.token == TK_NAME {
4604                        let name = str_check_name(ls, state)?;
4605                        vararg_name_vidx = Some(new_local_var(ls, state, name)?);
4606                        has_vararg_local = true;
4607                        has_vararg_name = true;
4608                    } else if is_v55 {
4609                        let name = state.intern_str(b"(vararg table)")?;
4610                        new_local_var(ls, state, name)?;
4611                        has_vararg_local = true;
4612                    } else if is_v51 {
4613                        let name = state.intern_str(b"arg")?;
4614                        new_local_var(ls, state, name)?;
4615                        has_vararg_local = true;
4616                        has_arg_local = true;
4617                    }
4618                }
4619                _ => {
4620                    return Err(LuaError::syntax(format_args!("<name> or '...' expected")));
4621                }
4622            }
4623            if isvararg || !test_next(ls, state, b',' as TokenKind)? {
4624                break;
4625            }
4626        }
4627    }
4628    adjust_local_vars(ls, state, nparams)?;
4629    let numparams = ls.fs.as_ref().unwrap().nactvar;
4630    ls.fs.as_mut().unwrap().f.numparams = numparams;
4631    if isvararg {
4632        setvararg(ls.fs.as_mut().unwrap(), state, numparams as i32)?;
4633    }
4634    if has_vararg_local {
4635        adjust_local_vars(ls, state, 1)?;
4636        if let Some(vidx) = vararg_name_vidx {
4637            let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
4638            get_local_var_desc_mut(ls, firstlocal, vidx).kind = VarKind::VarArg;
4639        }
4640        if has_arg_local {
4641            let fs = ls.fs.as_mut().unwrap();
4642            let arg_locvar = (fs.ndebugvars - 1) as usize;
4643            fs.f.locvars[arg_locvar].startpc = 0;
4644        }
4645    }
4646    // Reserve registers for parameters (plus the vararg-table parameter, if
4647    // present), in one call as upstream does (`luaK_reserveregs(fs, nactvar)`).
4648    let nactvar = ls.fs.as_ref().unwrap().nactvar as i32;
4649    reserve_regs(ls.fs.as_mut().unwrap(), nactvar)?;
4650    // Materialize the named-vararg table into its register: VARARGPACK packs
4651    // all extra args (table.pack semantics) into a fresh table at the vararg
4652    // local's slot, which is the topmost active local.
4653    if has_vararg_name {
4654        let reg = nvarstack(ls, ls.fs.as_ref().unwrap()) - 1;
4655        let inst = lua_code::opcodes::Instruction::abck(
4656            lua_code::opcodes::OpCode::VarArgPack,
4657            reg as u32,
4658            0,
4659            0,
4660            0,
4661        );
4662        let line = ls.fs.as_ref().unwrap().previousline;
4663        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4664        // Record the vararg-table register so `OP_VARARG` unpacks live from this
4665        // table (shared storage), making `t` mutations visible through `...`.
4666        ls.fs.as_mut().unwrap().f.vararg_table_reg = Some(reg as u8);
4667    }
4668    // Materialize the Lua 5.1 implicit `arg` table the same way, but with the K
4669    // bit set so VARARGPACK builds the table unconditionally at entry (it is the
4670    // default; `simpleexp`'s `...` arm calls `clear_arg_table_needed`, which
4671    // rewrites this entry VARARGPACK into a LOADNIL when the body actually uses
4672    // `...`, matching C's `is_vararg &= ~VARARG_NEEDSARG` — `arg` stays a
4673    // declared local but reads nil). Unlike the 5.5 named form, `arg` is an
4674    // ordinary local with no `vararg_table_reg` aliasing, so `...` keeps reading
4675    // the raw extra args independently of `arg`.
4676    if has_arg_local {
4677        let reg = nvarstack(ls, ls.fs.as_ref().unwrap()) - 1;
4678        let inst = lua_code::opcodes::Instruction::abck(
4679            lua_code::opcodes::OpCode::VarArgPack,
4680            reg as u32,
4681            0,
4682            0,
4683            1,
4684        );
4685        let line = ls.fs.as_ref().unwrap().previousline;
4686        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4687    }
4688    Ok(())
4689}
4690
4691fn check_match(
4692    ls: &mut LexState,
4693    state: &mut LuaState,
4694    what: TokenKind,
4695    who: TokenKind,
4696    where_line: i32,
4697) -> Result<(), LuaError> {
4698    if !test_next(ls, state, what)? {
4699        if where_line == ls.linenumber {
4700            return Err(error_expected(ls, what));
4701        } else {
4702            let what_str = lua_lex::token2str(&ls.lex, what);
4703            let who_str = lua_lex::token2str(&ls.lex, who);
4704            let mut msg: Vec<u8> = Vec::new();
4705            msg.extend_from_slice(&what_str);
4706            msg.extend_from_slice(b" expected (to close ");
4707            msg.extend_from_slice(&who_str);
4708            use std::io::Write as _;
4709            let _ = write!(msg, " at line {})", where_line);
4710            return Err(lua_lex::syntax_error(&mut ls.lex, &msg));
4711        }
4712    }
4713    Ok(())
4714}
4715
4716fn body(
4717    ls: &mut LexState,
4718    state: &mut LuaState,
4719    e: &mut ExprDesc,
4720    ismethod: bool,
4721    line: i32,
4722) -> Result<(), LuaError> {
4723    let new_proto = add_prototype(ls, state)?;
4724    let mut new_fs = FuncState {
4725        f: new_proto,
4726        prev: None,
4727        bl: None,
4728        pc: 0,
4729        lasttarget: 0,
4730        previousline: line,
4731        nk: 0,
4732        np: 0,
4733        nabslineinfo: 0,
4734        firstlocal: 0,
4735        firstlabel: 0,
4736        ndebugvars: 0,
4737        nactvar: 0,
4738        first_scope_barrier: ls.scope_barriers.len(),
4739        nups: 0,
4740        freereg: 0,
4741        iwthabs: 0,
4742        needclose: false,
4743        last_token_line: ls.lastline,
4744    };
4745    new_fs.f.linedefined = line;
4746    open_func(ls, state, new_fs)?;
4747
4748    check_next(ls, state, b'(' as TokenKind)?;
4749    if ismethod {
4750        let self_str = state.intern_str(b"self")?;
4751        new_local_var(ls, state, self_str)?;
4752        adjust_local_vars(ls, state, 1)?;
4753    }
4754    parlist(ls, state)?;
4755    check_next(ls, state, b')' as TokenKind)?;
4756    statlist(ls, state)?;
4757    ls.fs.as_mut().unwrap().f.lastlinedefined = ls.linenumber;
4758    check_match(ls, state, TK_END, TK_FUNCTION, line)?;
4759    codeclosure(ls, state, e)?;
4760    let inner_proto = close_func(ls, state)?;
4761    let parent = ls
4762        .fs
4763        .as_mut()
4764        .expect("body: close_func left no parent FuncState");
4765    let slot = (parent.np - 1) as usize;
4766    if parent.f.p.len() <= slot {
4767        parent
4768            .f
4769            .p
4770            .resize_with(slot + 1, || GcRef::new(LuaProto::placeholder()));
4771    }
4772    let inner_ref = GcRef::new(*inner_proto);
4773    inner_ref.account_buffer(inner_ref.buffer_bytes() as isize);
4774    parent.f.p[slot] = inner_ref;
4775    Ok(())
4776}
4777
4778// ── §11 Expression list and function arguments ────────────────────────────────
4779
4780fn explist(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<i32, LuaError> {
4781    let mut n = 1;
4782    expr(ls, state, v)?;
4783    while test_next(ls, state, b',' as TokenKind)? {
4784        let line = ls.lastline;
4785        cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, v)?;
4786        expr(ls, state, v)?;
4787        n += 1;
4788    }
4789    Ok(n)
4790}
4791
4792/// Parses a function call's argument list and emits the CALL.
4793///
4794/// `suffixed_line` is the line captured at the start of the enclosing
4795/// [`suffixedexp`] (the callee's first line). Lua 5.2 and 5.3 attribute the
4796/// CALL instruction to that line via `luaK_fixline`, so a runtime call-error on
4797/// `a\n(\n23)` reports the callee's line (1), not the open-paren line (2). Lua
4798/// 5.4/5.5 dropped that fixup and attribute the CALL to the open-paren line, so
4799/// those versions keep using `ls.linenumber` at funcargs entry and their
4800/// bytecode line info is unchanged.
4801fn funcargs(
4802    ls: &mut LexState,
4803    state: &mut LuaState,
4804    f: &mut ExprDesc,
4805    suffixed_line: i32,
4806) -> Result<(), LuaError> {
4807    let mut args = ExprDesc::default();
4808    // BEFORE consuming, so the OP_CALL/etc emissions attribute to the call site.
4809    // errors.lua tests `a\n(\n23)` expects error at line of `(`, not line of `a`.
4810    let line = ls.linenumber;
4811    match ls.t.token {
4812        c if c == b'(' as TokenKind => {
4813            if state.global().lua_version == lua_types::LuaVersion::V51
4814                && ls.linenumber != ls.lastline
4815            {
4816                return Err(lua_lex::syntax_error(
4817                    &mut ls.lex,
4818                    b"ambiguous syntax (function call x new statement)",
4819                ));
4820            }
4821            lex_next(ls, state)?; // skip '('
4822            if ls.t.token == b')' as TokenKind {
4823                args.k = ExprKind::Void;
4824            } else {
4825                explist(ls, state, &mut args)?;
4826                if args.k.has_mult_ret() {
4827                    // Call/VarArg to produce LUA_MULTRET so all of its return
4828                    // values become arguments to the enclosing call.
4829                    cg_set_returns(ls.fs.as_mut().unwrap(), &mut args, LUA_MULTRET);
4830                }
4831            }
4832            check_match(ls, state, b')' as TokenKind, b'(' as TokenKind, line)?;
4833        }
4834        c if c == b'{' as TokenKind => {
4835            constructor(ls, state, &mut args)?;
4836        }
4837        TK_STRING => {
4838            let s =
4839                ls.t.seminfo
4840                    .ts
4841                    .clone()
4842                    .ok_or_else(|| LuaError::syntax(format_args!("string expected")))?;
4843            codestring(&mut args, s);
4844            lex_next(ls, state)?;
4845        }
4846        _ => {
4847            return Err(LuaError::syntax(format_args!(
4848                "function arguments expected"
4849            )));
4850        }
4851    }
4852    debug_assert!(f.k == ExprKind::NonReloc);
4853    let base = f.u.info;
4854    let nparams: i32 = if args.k.has_mult_ret() {
4855        // TODO(port): luaK_setmultret for VVarArg / VCall args; only single
4856        // non-multret args are supported by the bootstrap codegen.
4857        LUA_MULTRET
4858    } else {
4859        if args.k != ExprKind::Void {
4860            cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut args)?;
4861        }
4862        ls.fs.as_ref().unwrap().freereg as i32 - (base + 1)
4863    };
4864    let call_inst = lua_code::opcodes::Instruction::abck(
4865        lua_code::opcodes::OpCode::Call,
4866        base as u32,
4867        (nparams + 1) as u32,
4868        2,
4869        0,
4870    );
4871    let call_line = if matches!(
4872        state.global().lua_version,
4873        lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
4874    ) {
4875        suffixed_line
4876    } else {
4877        line
4878    };
4879    let call_pc = emit_inst(ls.fs.as_mut().unwrap(), call_line, call_inst);
4880    init_exp(f, ExprKind::Call, call_pc);
4881    ls.fs.as_mut().unwrap().freereg = base as u8 + 1;
4882    Ok(())
4883}
4884
4885// ── §12 Expression parsing ────────────────────────────────────────────────────
4886
4887fn primaryexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4888    match ls.t.token {
4889        c if c == b'(' as TokenKind => {
4890            let line = ls.lastline;
4891            lex_next(ls, state)?;
4892            expr(ls, state, v)?;
4893            check_match(ls, state, b')' as TokenKind, b'(' as TokenKind, line)?;
4894            cg_discharge_vars(ls.fs.as_mut().unwrap(), line, v)?;
4895        }
4896        TK_NAME => {
4897            singlevar(ls, state, v)?;
4898        }
4899        _ => {
4900            return Err(lua_lex::syntax_error(&mut ls.lex, b"unexpected symbol"));
4901        }
4902    }
4903    Ok(())
4904}
4905
4906fn suffixedexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4907    let start_line = ls.linenumber;
4908    primaryexp(ls, state, v)?;
4909    loop {
4910        match ls.t.token {
4911            c if c == b'.' as TokenKind => {
4912                fieldsel(ls, state, v)?;
4913            }
4914            c if c == b'[' as TokenKind => {
4915                let mut key = ExprDesc::default();
4916                let line = ls.lastline;
4917                cg_exp_to_any_reg_up(ls.fs.as_mut().unwrap(), line, v)?;
4918                yindex(ls, state, &mut key)?;
4919                cg_indexed(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
4920            }
4921            c if c == b':' as TokenKind => {
4922                let mut key = ExprDesc::default();
4923                lex_next(ls, state)?;
4924                codename(ls, state, &mut key)?;
4925                let line = ls.lastline;
4926                let keep_self_opcode_for_register_key =
4927                    state.global().lua_version != lua_types::LuaVersion::V55;
4928                cg_self(
4929                    ls.fs.as_mut().unwrap(),
4930                    line,
4931                    v,
4932                    &mut key,
4933                    keep_self_opcode_for_register_key,
4934                )?;
4935                funcargs(ls, state, v, start_line)?;
4936            }
4937            c if c == b'(' as TokenKind || c == TK_STRING || c == b'{' as TokenKind => {
4938                let line = ls.lastline;
4939                cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, v)?;
4940                funcargs(ls, state, v, start_line)?;
4941            }
4942            _ => return Ok(()),
4943        }
4944    }
4945}
4946
4947fn simpleexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4948    match ls.t.token {
4949        TK_FLT => {
4950            init_exp(v, ExprKind::KFlt, 0);
4951            v.u.nval = ls.t.seminfo.r;
4952        }
4953        TK_INT => {
4954            init_exp(v, ExprKind::KInt, 0);
4955            v.u.ival = ls.t.seminfo.i;
4956        }
4957        TK_STRING => {
4958            let s =
4959                ls.t.seminfo
4960                    .ts
4961                    .clone()
4962                    .ok_or_else(|| LuaError::syntax(format_args!("string value missing")))?;
4963            codestring(v, s);
4964        }
4965        TK_NIL => {
4966            init_exp(v, ExprKind::Nil, 0);
4967        }
4968        TK_TRUE => {
4969            init_exp(v, ExprKind::True, 0);
4970        }
4971        TK_FALSE => {
4972            init_exp(v, ExprKind::False, 0);
4973        }
4974        TK_DOTS => {
4975            let is_vararg = ls.fs.as_ref().unwrap().f.is_vararg;
4976            if !is_vararg {
4977                return Err(lua_lex::syntax_error(
4978                    &mut ls.lex,
4979                    b"cannot use '...' outside a vararg function",
4980                ));
4981            }
4982            if state.global().lua_version == lua_types::LuaVersion::V51 {
4983                clear_arg_table_needed(ls.fs.as_mut().unwrap());
4984            }
4985            let line = ls.lastline;
4986            let inst =
4987                lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::VarArg, 0, 0, 1, 0);
4988            let pc = emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4989            init_exp(v, ExprKind::VarArg, pc);
4990        }
4991        c if c == b'{' as TokenKind => {
4992            constructor(ls, state, v)?;
4993            return Ok(());
4994        }
4995        TK_FUNCTION => {
4996            lex_next(ls, state)?;
4997            let line = ls.lastline;
4998            body(ls, state, v, false, line)?;
4999            return Ok(());
5000        }
5001        _ => {
5002            suffixedexp(ls, state, v)?;
5003            return Ok(());
5004        }
5005    }
5006    lex_next(ls, state)?;
5007    Ok(())
5008}
5009
5010fn getunopr(op: TokenKind) -> UnOpr {
5011    match op {
5012        TK_NOT => UnOpr::Not,
5013        c if c == b'-' as TokenKind => UnOpr::Minus,
5014        c if c == b'~' as TokenKind => UnOpr::BNot,
5015        c if c == b'#' as TokenKind => UnOpr::Len,
5016        _ => UnOpr::NoUnOpr,
5017    }
5018}
5019
5020fn getbinopr(op: TokenKind) -> BinOpr {
5021    match op {
5022        c if c == b'+' as TokenKind => BinOpr::Add,
5023        c if c == b'-' as TokenKind => BinOpr::Sub,
5024        c if c == b'*' as TokenKind => BinOpr::Mul,
5025        c if c == b'%' as TokenKind => BinOpr::Mod,
5026        c if c == b'^' as TokenKind => BinOpr::Pow,
5027        c if c == b'/' as TokenKind => BinOpr::Div,
5028        TK_IDIV => BinOpr::IDiv,
5029        c if c == b'&' as TokenKind => BinOpr::BAnd,
5030        c if c == b'|' as TokenKind => BinOpr::BOr,
5031        c if c == b'~' as TokenKind => BinOpr::BXor,
5032        TK_SHL => BinOpr::Shl,
5033        TK_SHR => BinOpr::Shr,
5034        TK_CONCAT => BinOpr::Concat,
5035        TK_NE => BinOpr::Ne,
5036        TK_EQ => BinOpr::Eq,
5037        c if c == b'<' as TokenKind => BinOpr::Lt,
5038        TK_LE => BinOpr::Le,
5039        c if c == b'>' as TokenKind => BinOpr::Gt,
5040        TK_GE => BinOpr::Ge,
5041        TK_AND => BinOpr::And,
5042        TK_OR => BinOpr::Or,
5043        _ => BinOpr::NoBinOpr,
5044    }
5045}
5046
5047/// Whether the active version is the float-only legacy family (5.1/5.2), which
5048/// has no bitwise operators (`&`, `|`, `~`, `<<`, `>>`).
5049fn parser_is_float_only(state: &LuaState) -> bool {
5050    matches!(
5051        state.global().lua_version,
5052        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
5053    )
5054}
5055
5056/// Version-aware [`getbinopr`]: under 5.1/5.2 the bitwise binops `&`/`|`/`~`
5057/// are not operators (they were added in 5.3), so they resolve to
5058/// [`BinOpr::NoBinOpr`]. The lexer already withholds `<<`/`>>`/`//` there.
5059/// This reproduces upstream lua5.2.4's "')' expected near '&'" surface: the
5060/// `&` simply terminates the expression and the parser then expects the
5061/// enclosing delimiter.
5062fn getbinopr_versioned(op: TokenKind, state: &LuaState) -> BinOpr {
5063    let r = getbinopr(op);
5064    if parser_is_float_only(state) && matches!(r, BinOpr::BAnd | BinOpr::BOr | BinOpr::BXor) {
5065        return BinOpr::NoBinOpr;
5066    }
5067    r
5068}
5069
5070/// Version-aware [`getunopr`]: under 5.1/5.2 the unary `~` (bitwise NOT) is not
5071/// an operator. A leading `~` there is "unexpected symbol near '~'".
5072fn getunopr_versioned(op: TokenKind, state: &LuaState) -> UnOpr {
5073    let r = getunopr(op);
5074    if parser_is_float_only(state) && matches!(r, UnOpr::BNot) {
5075        return UnOpr::NoUnOpr;
5076    }
5077    r
5078}
5079
5080/// Parses a sub-expression with operators of priority > `limit`.
5081/// Returns the first untreated (lower-priority) operator.
5082fn subexpr(
5083    ls: &mut LexState,
5084    state: &mut LuaState,
5085    v: &mut ExprDesc,
5086    limit: i32,
5087) -> Result<BinOpr, LuaError> {
5088    enter_level(ls, state)?;
5089
5090    let uop = getunopr_versioned(ls.t.token, state);
5091    if uop != UnOpr::NoUnOpr {
5092        // so this is the operator's own line, not the prior token's.
5093        let line = ls.linenumber;
5094        lex_next(ls, state)?; // skip unary operator
5095        subexpr(ls, state, v, UNARY_PRIORITY)?;
5096        cg_prefix(ls.fs.as_mut().unwrap(), uop, v, line)?;
5097    } else {
5098        simpleexp(ls, state, v)?;
5099    }
5100
5101    let mut op = getbinopr_versioned(ls.t.token, state);
5102    while op != BinOpr::NoBinOpr && PRIORITY[op as usize].0 as i32 > limit {
5103        let mut v2 = ExprDesc::default();
5104        // errors.lua's `lineerror` cases check that runtime arith errors are
5105        // attributed to the operator's line, not the operand's.
5106        let line = ls.linenumber;
5107        lex_next(ls, state)?;
5108        cg_infix(ls.fs.as_mut().unwrap(), op, v, line)?;
5109        let nextop = subexpr(ls, state, &mut v2, PRIORITY[op as usize].1 as i32)?;
5110        cg_posfix_fold(ls.fs.as_mut().unwrap(), op, v, &mut v2, line)?;
5111        op = nextop;
5112    }
5113
5114    leave_level(ls);
5115    Ok(op)
5116}
5117
5118fn expr(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
5119    subexpr(ls, state, v, 0)?;
5120    Ok(())
5121}
5122
5123// ── §13 Statement rules ───────────────────────────────────────────────────────
5124
5125fn block(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5126    enter_block(ls, false);
5127    statlist(ls, state)?;
5128    leave_block(ls, state)?;
5129    Ok(())
5130}
5131
5132/// Checks and fixes register/upvalue conflicts in multi-assignment.
5133///
5134/// When a non-indexed LHS variable `v` also appears as the table or key in an
5135/// indexed LHS variable, the indexed entry must be redirected to a copy made
5136/// before any assignments occur. For an upvalue table that becomes a register
5137/// copy, the ExprKind is changed from IndexUp to IndexStr so cg_storevar emits
5138/// SETFIELD (register table) instead of SETTABUP (upvalue table).
5139fn check_conflict(
5140    ls: &mut LexState,
5141    _state: &mut LuaState,
5142    lh: &mut LhsAssign,
5143    v: &ExprDesc,
5144) -> Result<(), LuaError> {
5145    let extra = ls.fs.as_ref().unwrap().freereg as i32;
5146    let line = ls.lastline;
5147    let mut conflict = false;
5148
5149    conflict |= check_one_lhs_entry(&mut lh.v, v, extra);
5150    let mut prev = lh.prev.as_deref_mut();
5151    while let Some(node) = prev {
5152        conflict |= check_one_lhs_entry(&mut node.v, v, extra);
5153        prev = node.prev.as_deref_mut();
5154    }
5155
5156    if conflict {
5157        let fs = ls.fs.as_mut().unwrap();
5158        let inst = if v.k == ExprKind::Local {
5159            lua_code::opcodes::Instruction::abck(
5160                lua_code::opcodes::OpCode::Move,
5161                extra as u32,
5162                v.u.var_ridx as u32,
5163                0,
5164                0,
5165            )
5166        } else {
5167            lua_code::opcodes::Instruction::abck(
5168                lua_code::opcodes::OpCode::GetUpVal,
5169                extra as u32,
5170                v.u.info as u32,
5171                0,
5172                0,
5173            )
5174        };
5175        emit_inst(fs, line, inst);
5176        reserve_regs(fs, 1)?;
5177    }
5178    Ok(())
5179}
5180
5181fn check_one_lhs_entry(entry: &mut ExprDesc, v: &ExprDesc, extra: i32) -> bool {
5182    if !entry.k.is_indexed() {
5183        return false;
5184    }
5185    let mut found = false;
5186    if entry.k == ExprKind::IndexUp {
5187        if v.k == ExprKind::UpVal && entry.u.ind_t == v.u.info as u8 {
5188            found = true;
5189            entry.k = ExprKind::IndexStr;
5190            entry.u.ind_t = extra as u8;
5191        }
5192    } else {
5193        if v.k == ExprKind::Local && entry.u.ind_t == v.u.var_ridx {
5194            found = true;
5195            entry.u.ind_t = extra as u8;
5196        }
5197        if entry.k == ExprKind::Indexed
5198            && v.k == ExprKind::Local
5199            && entry.u.ind_idx == v.u.var_ridx as i16
5200        {
5201            found = true;
5202            entry.u.ind_idx = extra as i16;
5203        }
5204    }
5205    found
5206}
5207
5208fn restassign(
5209    ls: &mut LexState,
5210    state: &mut LuaState,
5211    lh: &mut LhsAssign,
5212    nvars: i32,
5213) -> Result<(), LuaError> {
5214    if !lh.v.k.is_var() {
5215        return Err(lua_lex::syntax_error(&mut ls.lex, b"syntax error"));
5216    }
5217    check_readonly(ls, state, &lh.v.clone())?;
5218
5219    if test_next(ls, state, b',' as TokenKind)? {
5220        // The new target is not back-linked into the LHS chain (`prev: None`);
5221        // check_conflict therefore only inspects the immediate parent `lh`, not
5222        // the full chain back to the first target. A known divergence from
5223        // upstream that the bytecode-parity oracle does not surface on the test
5224        // corpus; not fixed here to avoid touching codegen behavior.
5225        let mut nv_assign = LhsAssign {
5226            prev: None,
5227            v: ExprDesc::default(),
5228        };
5229        suffixedexp(ls, state, &mut nv_assign.v)?;
5230        if !nv_assign.v.k.is_indexed() {
5231            check_conflict(ls, state, lh, &nv_assign.v.clone())?;
5232        }
5233        enter_level(ls, state)?;
5234        restassign(ls, state, &mut nv_assign, nvars + 1)?;
5235        leave_level(ls);
5236    } else {
5237        let mut e = ExprDesc::default();
5238        check_next(ls, state, b'=' as TokenKind)?;
5239        let nexps = explist(ls, state, &mut e)?;
5240        if nexps != nvars {
5241            adjust_assign(ls, state, nvars, nexps, &mut e)?;
5242        } else {
5243            let line = ls.lastline;
5244            let fs = ls.fs.as_mut().unwrap();
5245            cg_set_one_ret(fs, &mut e);
5246            cg_storevar(fs, line, &lh.v, &mut e)?;
5247            return Ok(());
5248        }
5249    }
5250    let line = ls.lastline;
5251    let fs = ls.fs.as_mut().unwrap();
5252    let freereg = fs.freereg as i32 - 1;
5253    let mut e = ExprDesc::default();
5254    init_exp(&mut e, ExprKind::NonReloc, freereg);
5255    cg_storevar(fs, line, &lh.v, &mut e)?;
5256    Ok(())
5257}
5258
5259/// Parses a condition expression; returns its 'exit when false' patch list.
5260fn cond(ls: &mut LexState, state: &mut LuaState) -> Result<i32, LuaError> {
5261    let mut v = ExprDesc::default();
5262    expr(ls, state, &mut v)?;
5263    if v.k == ExprKind::Nil {
5264        v.k = ExprKind::False;
5265    }
5266    let line = ls.lastline;
5267    cg_go_if_true(ls.fs.as_mut().unwrap(), line, &mut v)?;
5268    Ok(v.f)
5269}
5270
5271fn gotostat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5272    let line = ls.lastline;
5273    let name = str_check_name(ls, state)?;
5274    let lb = findlabel_for_goto(ls, state, &name);
5275    if lb.is_none() {
5276        let pc = cg_jump(ls.fs.as_mut().unwrap(), line);
5277        new_goto_entry(ls, state, name, line, pc)?;
5278    } else {
5279        let lb_idx = lb.unwrap();
5280        let lb_pc = ls.dyd.label[lb_idx].pc;
5281        let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
5282        let lb_local_level = local_level_for_scope_level(ls, lb_nactvar);
5283        let lblevel = reg_level(ls, ls.fs.as_ref().unwrap(), lb_local_level);
5284        let cur_nvarstack = {
5285            let fs = ls.fs.as_ref().unwrap();
5286            nvarstack(ls, fs)
5287        };
5288        if cur_nvarstack > lblevel {
5289            let inst = lua_code::opcodes::Instruction::abck(
5290                lua_code::opcodes::OpCode::Close,
5291                lblevel as u32,
5292                0,
5293                0,
5294                0,
5295            );
5296            emit_inst(ls.fs.as_mut().unwrap(), line, inst);
5297        }
5298        let jpc = cg_jump(ls.fs.as_mut().unwrap(), line);
5299        cg_patch_list(ls.fs.as_mut().unwrap(), jpc, lb_pc)?;
5300    }
5301    Ok(())
5302}
5303
5304/// True if any enclosing block of the current function is a loop, i.e. `break`
5305/// has somewhere to go.
5306fn has_enclosing_loop(ls: &LexState) -> bool {
5307    let mut bl = ls.fs.as_ref().unwrap().bl.as_deref();
5308    while let Some(b) = bl {
5309        if b.isloop {
5310            return true;
5311        }
5312        bl = b.previous.as_deref();
5313    }
5314    false
5315}
5316
5317fn breakstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5318    let version = state.global().lua_version;
5319    let line = ls.lastline;
5320    // `break` outside a loop is reported in three different ways across versions
5321    // (see also `undef_goto` for the 5.2-5.4 deferred forms):
5322    //   5.5 raises eagerly while the current token is still `break`
5323    //       → "break outside loop near 'break'".
5324    //   5.1 raises eagerly after consuming `break`
5325    //       → "no loop to break near '<next token>'".
5326    //   5.2/5.3/5.4 defer to the goto machinery (resolved in `undef_goto`).
5327    if version == lua_types::LuaVersion::V55 && !has_enclosing_loop(ls) {
5328        return Err(lua_lex::syntax_error(&mut ls.lex, b"break outside loop"));
5329    }
5330    lex_next(ls, state)?;
5331    if version == lua_types::LuaVersion::V51 && !has_enclosing_loop(ls) {
5332        return Err(lua_lex::syntax_error(&mut ls.lex, b"no loop to break"));
5333    }
5334    let break_str = state.intern_str(b"break")?;
5335    let pc = cg_jump(ls.fs.as_mut().unwrap(), line);
5336    new_goto_entry(ls, state, break_str, line, pc)?;
5337    Ok(())
5338}
5339
5340/// Checks whether `name` collides with an already-defined label.
5341///
5342/// The scope of the collision check differs by Lua version. 5.2 and 5.3
5343/// (upstream `checkrepeated`) scan only the labels of the **current block**
5344/// (`fs->bl->firstlabel`), so a label in an inner block may shadow a same-named
5345/// label in an enclosing block. 5.4 and 5.5 rewrote `checkrepeated` to call
5346/// `findlabel`, which scans the **whole function** (`fs->firstlabel`), making
5347/// any repeated label name in the function an error. 5.1 has no `goto`/labels.
5348fn checkrepeated(
5349    ls: &mut LexState,
5350    state: &LuaState,
5351    name: &GcRef<LuaString>,
5352) -> Result<(), LuaError> {
5353    let block_scoped = matches!(
5354        state.global().lua_version,
5355        lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
5356    );
5357    let first = if block_scoped {
5358        ls.fs
5359            .as_ref()
5360            .unwrap()
5361            .bl
5362            .as_ref()
5363            .map_or(0, |b| b.firstlabel) as usize
5364    } else {
5365        ls.fs.as_ref().unwrap().firstlabel as usize
5366    };
5367    let mut dup_line: Option<i32> = None;
5368    for i in first..ls.dyd.label.len() {
5369        let lb = &ls.dyd.label[i];
5370        if lb.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
5371            dup_line = Some(lb.line);
5372            break;
5373        }
5374    }
5375    if let Some(line) = dup_line {
5376        let name_str = String::from_utf8_lossy(name.as_bytes());
5377        let msg = format!("label '{}' already defined on line {}", name_str, line);
5378        let saved_line = ls.lex.linenumber;
5379        ls.lex.linenumber = ls.lastline;
5380        let err = lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0);
5381        ls.lex.linenumber = saved_line;
5382        return Err(err);
5383    }
5384    Ok(())
5385}
5386
5387fn labelstat(
5388    ls: &mut LexState,
5389    state: &mut LuaState,
5390    name: GcRef<LuaString>,
5391    line: i32,
5392) -> Result<(), LuaError> {
5393    check_next(ls, state, TK_DBCOLON)?;
5394    while ls.t.token == b';' as TokenKind || ls.t.token == TK_DBCOLON {
5395        statement(ls, state)?;
5396    }
5397    checkrepeated(ls, state, &name)?;
5398    let is_last = block_follow(ls, false);
5399    createlabel(ls, state, name, line, is_last)?;
5400    Ok(())
5401}
5402
5403fn whilestat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5404    lex_next(ls, state)?;
5405    let whileinit = cg_get_label(ls.fs.as_mut().unwrap());
5406    let condexit = cond(ls, state)?;
5407    enter_block(ls, true);
5408    check_next(ls, state, TK_DO)?;
5409    block(ls, state)?;
5410    // Use `lastline` (line of the just-parsed body's last token) rather than
5411    // `linenumber` (which has already advanced to END) so the back-jump's
5412    // line attribution matches lua-c's bytecode and the line hook does not
5413    // spuriously fire for the END line on every iteration.
5414    let back = cg_jump(ls.fs.as_mut().unwrap(), ls.lastline);
5415    cg_patch_list(ls.fs.as_mut().unwrap(), back, whileinit)?;
5416    check_match(ls, state, TK_END, TK_WHILE, line)?;
5417    leave_block(ls, state)?;
5418    cg_patch_to_here(ls.fs.as_mut().unwrap(), condexit)?;
5419    Ok(())
5420}
5421
5422fn repeatstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5423    let repeat_init = cg_get_label(ls.fs.as_mut().unwrap());
5424    enter_block(ls, true);
5425    enter_block(ls, false);
5426    lex_next(ls, state)?;
5427    statlist(ls, state)?;
5428    check_match(ls, state, TK_UNTIL, TK_REPEAT, line)?;
5429    let condexit = cond(ls, state)?;
5430
5431    let bl2_upval = ls.fs.as_ref().unwrap().bl.as_ref().unwrap().upval;
5432    let bl2_nactvar = ls.fs.as_ref().unwrap().bl.as_ref().unwrap().nactvar as i32;
5433    leave_block(ls, state)?;
5434
5435    let mut condexit = condexit;
5436    if bl2_upval {
5437        let exit = cg_jump(ls.fs.as_mut().unwrap(), line);
5438        cg_patch_to_here(ls.fs.as_mut().unwrap(), condexit)?;
5439        let close_level = reg_level(ls, ls.fs.as_ref().unwrap(), bl2_nactvar) as u32;
5440        let close_inst = lua_code::opcodes::Instruction::abck(
5441            lua_code::opcodes::OpCode::Close,
5442            close_level,
5443            0,
5444            0,
5445            0,
5446        );
5447        emit_inst(ls.fs.as_mut().unwrap(), line, close_inst);
5448        condexit = cg_jump(ls.fs.as_mut().unwrap(), line);
5449        cg_patch_to_here(ls.fs.as_mut().unwrap(), exit)?;
5450    }
5451    cg_patch_list(ls.fs.as_mut().unwrap(), condexit, repeat_init)?;
5452    leave_block(ls, state)?;
5453    Ok(())
5454}
5455
5456/// Parse an expression and emit it to the next register.
5457fn exp1(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5458    let mut e = ExprDesc::default();
5459    expr(ls, state, &mut e)?;
5460    let line = ls.lastline;
5461    cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut e)?;
5462    debug_assert!(e.k == ExprKind::NonReloc);
5463    Ok(())
5464}
5465
5466fn fixforjump(fs: &mut FuncState, pc: i32, dest: i32, back: bool) -> Result<(), LuaError> {
5467    let mut offset = dest - (pc + 1);
5468    if back {
5469        offset = -offset;
5470    }
5471    if offset > MAXARG_BX {
5472        return Err(LuaError::syntax(format_args!("control structure too long")));
5473    }
5474    let raw = fs.f.code[pc as usize].0;
5475    let mut inst = lua_code::opcodes::Instruction(raw);
5476    inst.set_arg_bx(offset as u32);
5477    fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(inst.0);
5478    Ok(())
5479}
5480
5481fn forbody(
5482    ls: &mut LexState,
5483    state: &mut LuaState,
5484    base: i32,
5485    line: i32,
5486    nvars: i32,
5487    isgen: bool,
5488) -> Result<(), LuaError> {
5489    check_next(ls, state, TK_DO)?;
5490    let prep_op = if isgen {
5491        OpCode::TForPrep
5492    } else {
5493        OpCode::ForPrep
5494    };
5495    let prep = {
5496        let fs = ls.fs.as_mut().unwrap();
5497        let inst = lua_code::opcodes::Instruction::abx(prep_op, base as u32, 0);
5498        emit_inst(fs, line, inst)
5499    };
5500    if isgen && state.global().lua_version == lua_types::LuaVersion::V55 {
5501        let fs = ls.fs.as_mut().unwrap();
5502        fs.freereg = fs.freereg.saturating_sub(1);
5503    }
5504
5505    enter_block(ls, false);
5506    adjust_local_vars(ls, state, nvars)?;
5507    reserve_regs(ls.fs.as_mut().unwrap(), nvars)?;
5508    block(ls, state)?;
5509    leave_block(ls, state)?;
5510
5511    let label_pc = ls.fs.as_ref().unwrap().pc;
5512    fixforjump(ls.fs.as_mut().unwrap(), prep, label_pc, false)?;
5513
5514    if isgen {
5515        let fs = ls.fs.as_mut().unwrap();
5516        let inst =
5517            lua_code::opcodes::Instruction::abck(OpCode::TForCall, base as u32, 0, nvars as u32, 0);
5518        emit_inst(fs, line, inst);
5519    }
5520    let loop_op = if isgen {
5521        OpCode::TForLoop
5522    } else {
5523        OpCode::ForLoop
5524    };
5525    let endfor = {
5526        let fs = ls.fs.as_mut().unwrap();
5527        let inst = lua_code::opcodes::Instruction::abx(loop_op, base as u32, 0);
5528        emit_inst(fs, line, inst)
5529    };
5530    fixforjump(ls.fs.as_mut().unwrap(), endfor, prep + 1, true)?;
5531    Ok(())
5532}
5533
5534fn fornum(
5535    ls: &mut LexState,
5536    state: &mut LuaState,
5537    varname: GcRef<LuaString>,
5538    line: i32,
5539) -> Result<(), LuaError> {
5540    let base = ls.fs.as_ref().unwrap().freereg as i32;
5541    let for_state_str = state.intern_str(b"(for state)")?;
5542    new_local_var(ls, state, for_state_str.clone())?;
5543    new_local_var(ls, state, for_state_str.clone())?;
5544    new_local_var(ls, state, for_state_str)?;
5545    let ctrl_vidx = new_local_var(ls, state, varname)?;
5546    // Lua 5.5: the numeric for-loop control variable is read-only — assigning
5547    // to it is a compile error. The FORLOOP opcode still updates the register
5548    // directly, so loop progress is unaffected. (No effect on pre-5.5.)
5549    if state.global().lua_version == lua_types::LuaVersion::V55 {
5550        let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
5551        get_local_var_desc_mut(ls, firstlocal, ctrl_vidx).kind = VarKind::Const;
5552    }
5553    check_next(ls, state, b'=' as TokenKind)?;
5554    exp1(ls, state)?; // initial value
5555    check_next(ls, state, b',' as TokenKind)?;
5556    exp1(ls, state)?; // limit
5557    if test_next(ls, state, b',' as TokenKind)? {
5558        exp1(ls, state)?; // optional step
5559    } else {
5560        let fs = ls.fs.as_mut().unwrap();
5561        let reg = fs.freereg as u32;
5562        let bx = (1i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
5563        let inst = lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::LoadI, reg, bx);
5564        emit_inst(fs, line, inst);
5565        reserve_regs(fs, 1)?;
5566    }
5567    adjust_local_vars(ls, state, 3)?; // control variables
5568    forbody(ls, state, base, line, 1, false)?;
5569    Ok(())
5570}
5571
5572fn forlist(
5573    ls: &mut LexState,
5574    state: &mut LuaState,
5575    indexname: GcRef<LuaString>,
5576) -> Result<(), LuaError> {
5577    let is_v55 = state.global().lua_version == lua_types::LuaVersion::V55;
5578    let mut nvars: i32 = if is_v55 { 4 } else { 5 };
5579    let base = ls.fs.as_ref().unwrap().freereg as i32;
5580    let for_state_str = state.intern_str(b"(for state)")?;
5581    new_local_var(ls, state, for_state_str.clone())?;
5582    new_local_var(ls, state, for_state_str.clone())?;
5583    new_local_var(ls, state, for_state_str.clone())?;
5584    if !is_v55 {
5585        new_local_var(ls, state, for_state_str)?;
5586    }
5587    let idx_vidx = new_local_var(ls, state, indexname)?;
5588    // Lua 5.5: the first control variable of a generic for is read-only (the
5589    // remaining loop variables stay assignable).
5590    if state.global().lua_version == lua_types::LuaVersion::V55 {
5591        let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
5592        get_local_var_desc_mut(ls, firstlocal, idx_vidx).kind = VarKind::Const;
5593    }
5594    while test_next(ls, state, b',' as TokenKind)? {
5595        let extra_name = str_check_name(ls, state)?;
5596        new_local_var(ls, state, extra_name)?;
5597        nvars += 1;
5598    }
5599    check_next(ls, state, TK_IN)?;
5600    // After `in`, linenumber is the line of the operand — used for the
5601    // for-in control instructions so runtime errors point at the operand,
5602    // not the `in` keyword. errors.lua:401 depends on this.
5603    let line = ls.linenumber;
5604    let mut e = ExprDesc::default();
5605    let nexps = explist(ls, state, &mut e)?;
5606    adjust_assign(ls, state, 4, nexps, &mut e)?;
5607    adjust_local_vars(ls, state, if is_v55 { 3 } else { 4 })?;
5608    marktobeclosed(ls.fs.as_mut().unwrap()); // last active internal var must be closed
5609                                             // TODO(port): lua_code::check_stack(ls.fs.as_mut().unwrap(), 3)?;
5610    let internal_vars = if is_v55 { 3 } else { 4 };
5611    forbody(ls, state, base, line, nvars - internal_vars, true)?;
5612    Ok(())
5613}
5614
5615fn forstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5616    enter_block(ls, true); // scope for loop and control variables
5617    lex_next(ls, state)?;
5618    let varname = str_check_name(ls, state)?;
5619    match ls.t.token {
5620        c if c == b'=' as TokenKind => fornum(ls, state, varname, line)?,
5621        c if c == b',' as TokenKind || c == TK_IN => forlist(ls, state, varname)?,
5622        _ => {
5623            return Err(LuaError::syntax(format_args!("'=' or 'in' expected")));
5624        }
5625    }
5626    check_match(ls, state, TK_END, TK_FOR, line)?;
5627    leave_block(ls, state)?; // loop scope ('break' jumps to this point)
5628    Ok(())
5629}
5630
5631fn test_then_block(
5632    ls: &mut LexState,
5633    state: &mut LuaState,
5634    escapelist: &mut i32,
5635) -> Result<(), LuaError> {
5636    lex_next(ls, state)?;
5637    let mut v = ExprDesc::default();
5638    expr(ls, state, &mut v)?;
5639    // Lua 5.5 attributes the conditional `TEST`/`JMP` to the
5640    // condition-expression line (captured here, before `then` is consumed);
5641    // 5.1-5.4 attribute them to the `then`-keyword line (`ls.lastline` after
5642    // `check_next`). Observable via `debug.sethook(f,"l")`: a multi-line
5643    // `if / <cond> / then` fires a line event for the `then` line on <=5.4 but
5644    // not on 5.5 (issue #92). `while`/`repeat` already use the condition line on
5645    // every version (their `cond()` captures it before `do`/`until`).
5646    let cond_line = ls.lastline;
5647    let fold_onto_cond = state.global().lua_version == lua_types::LuaVersion::V55;
5648    check_next(ls, state, TK_THEN)?;
5649
5650    let jf: i32;
5651    if ls.t.token == TK_BREAK {
5652        let line = ls.linenumber;
5653        cg_go_if_false(ls.fs.as_mut().unwrap(), line, &mut v)?;
5654        lex_next(ls, state)?; // skip 'break'
5655        enter_block(ls, false);
5656        let break_str = state.intern_str(b"break")?;
5657        new_goto_entry(ls, state, break_str, line, v.t)?;
5658        while test_next(ls, state, b';' as TokenKind)? {}
5659        if block_follow(ls, false) {
5660            leave_block(ls, state)?;
5661            return Ok(());
5662        } else {
5663            jf = cg_jump(ls.fs.as_mut().unwrap(), ls.linenumber);
5664        }
5665    } else {
5666        let line = if fold_onto_cond {
5667            cond_line
5668        } else {
5669            ls.lastline
5670        };
5671        cg_go_if_true(ls.fs.as_mut().unwrap(), line, &mut v)?;
5672        enter_block(ls, false);
5673        jf = v.f;
5674    }
5675
5676    statlist(ls, state)?;
5677    leave_block(ls, state)?;
5678
5679    if ls.t.token == TK_ELSE || ls.t.token == TK_ELSEIF {
5680        let line = ls.lastline;
5681        let j = cg_jump(ls.fs.as_mut().unwrap(), line);
5682        cg_concat(ls.fs.as_mut().unwrap(), escapelist, j)?;
5683    }
5684    cg_patch_to_here(ls.fs.as_mut().unwrap(), jf)?;
5685    Ok(())
5686}
5687
5688fn ifstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5689    let mut escapelist = NO_JUMP;
5690    test_then_block(ls, state, &mut escapelist)?; // IF cond THEN block
5691    while ls.t.token == TK_ELSEIF {
5692        test_then_block(ls, state, &mut escapelist)?;
5693    }
5694    if test_next(ls, state, TK_ELSE)? {
5695        block(ls, state)?;
5696    }
5697    check_match(ls, state, TK_END, TK_IF, line)?;
5698    cg_patch_to_here(ls.fs.as_mut().unwrap(), escapelist)?;
5699    Ok(())
5700}
5701
5702fn localfunc(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5703    let mut b = ExprDesc::default();
5704    let _fvar = ls.fs.as_ref().unwrap().nactvar as i32;
5705    let name = str_check_name(ls, state)?;
5706    new_local_var(ls, state, name)?;
5707    adjust_local_vars(ls, state, 1)?; // enter its scope
5708    let line = ls.lastline;
5709    body(ls, state, &mut b, false, line)?;
5710    let _pc = ls.fs.as_ref().unwrap().pc;
5711    // TODO(port): local_debug_info(ls, ls.fs.as_mut().unwrap(), fvar).map(|lv| lv.startpc = pc);
5712    Ok(())
5713}
5714
5715/// Whether the active Lua version supports `<const>`/`<close>` local-variable
5716/// attributes. True for 5.4 and 5.5; false for 5.1/5.2/5.3.
5717fn version_has_attributes(state: &LuaState) -> bool {
5718    use lua_types::LuaVersion;
5719    matches!(
5720        state.global().lua_version,
5721        LuaVersion::V54 | LuaVersion::V55
5722    )
5723}
5724
5725/// Parses an optional '<const>' or '<close>' attribute.
5726///
5727/// The `<const>`/`<close>` attribute syntax is a Lua 5.4 addition (5.4 §8.1,
5728/// `specs/research/5.3-upstream-delta.md` delta #7). Under Lua 5.3 the `<`
5729/// after a local name is not an attribute opener at all — it is left
5730/// unconsumed so the surrounding statement reports it as an unexpected symbol,
5731/// exactly as the 5.3 parser does. Versions are gated on
5732/// [`lua_types::LuaVersion`], read from the state set at construction.
5733fn getlocalattribute(
5734    ls: &mut LexState,
5735    state: &mut LuaState,
5736    df: VarKind,
5737) -> Result<VarKind, LuaError> {
5738    if !version_has_attributes(state) {
5739        return Ok(df);
5740    }
5741    if test_next(ls, state, b'<' as TokenKind)? {
5742        let attr_name = str_check_name(ls, state)?;
5743        check_next(ls, state, b'>' as TokenKind)?;
5744        let bytes = attr_name.as_bytes();
5745        if bytes == b"const" {
5746            return Ok(VarKind::Const);
5747        } else if bytes == b"close" {
5748            return Ok(VarKind::ToBeClosed);
5749        } else {
5750            let msg = format!("unknown attribute '{}'", String::from_utf8_lossy(bytes));
5751            return Err(lua_lex::sem_error(&mut ls.lex, msg.as_bytes()));
5752        }
5753    }
5754    Ok(df)
5755}
5756
5757fn checktoclose(ls: &mut LexState, _state: &mut LuaState, level: i32) -> Result<(), LuaError> {
5758    if level != -1 {
5759        marktobeclosed(ls.fs.as_mut().unwrap());
5760        let rl = reg_level(ls, ls.fs.as_ref().unwrap(), level);
5761        let line = ls.lastline;
5762        let inst = lua_code::opcodes::Instruction::abck(
5763            lua_code::opcodes::OpCode::Tbc,
5764            rl as u32,
5765            0,
5766            0,
5767            0,
5768        );
5769        emit_inst(ls.fs.as_mut().unwrap(), line, inst);
5770    }
5771    Ok(())
5772}
5773
5774/// Lua 5.5 `global` declaration statement — PRELIMINARY GROUNDWORK STUB.
5775///
5776/// Grammar (manual §3.3.7, `specs/research/5.5-upstream-delta.md` §1b):
5777/// ```text
5778/// stat ::= global attnamelist ['=' explist]
5779/// stat ::= global [attrib] '*'
5780/// attnamelist ::= [attrib] Name [attrib] {',' Name [attrib]}
5781/// attrib ::= '<' Name '>'        -- only <const> is legal for a global; <close> is an error
5782/// ```
5783///
5784/// HOW FAR THIS GETS: this entry point is only reached on the `LuaVersion::V55`
5785/// path (the lexer only emits [`TK_GLOBAL`] there). It RECOGNIZES and fully
5786/// *consumes* both grammar forms — the collective `global *` (with an optional
5787/// leading `<const>` attribute) and the `global x <const>, y` name list with an
5788/// optional `= explist` initializer — so a syntactically valid `global`
5789/// statement parses without error. The declared names and their attributes are
5790/// parsed and then DROPPED (parse-and-noop). No bytecode is emitted and the
5791/// scope resolver is not touched.
5792///
5793/// WHAT THE FULL STATEFUL SCOPE MODEL STILL NEEDS (manual §2.2,
5794/// `specs/research/5.5-upstream-delta.md` §1c/§1d):
5795///  1. Per-scope mode flag: a chunk starts with an implicit `global *` (every
5796///     free name is `_ENV.name`, as in 5.4). The FIRST explicit `global` decl
5797///     in a scope VOIDS that implicit declaration for the rest of the scope.
5798///  2. Declared-set tracking: in a voided scope, every free name must resolve
5799///     to a local, an upvalue, or a name in some in-scope `global` declaration;
5800///     upstream encodes this with `VGLOBAL` and the sentinel `var->u.info == -1`
5801///     meaning "preambular `global *` still active".
5802///  3. Undeclared-name compile error: a free name with no declaration is a
5803///     COMPILE-TIME error, emitted via the new `OP_ERRNNIL` opcode
5804///     (`A Bx`, "raise error if R[A] ~= nil", K[Bx-1] is the global name). That
5805///     opcode, the `ivABC` operand mode, and the reordered SHRI/SHLI are not yet
5806///     in `lua-code`, so even storing to a declared global cannot be codegen'd
5807///     faithfully yet.
5808///  4. `<const>` globals must be read-only (compile error on assignment); a
5809///     `global` decl with an initializer raises a RUNTIME error if the global
5810///     already holds a non-nil value; `<close>` on a global is a compile error.
5811///  5. `global *` (optionally `global <const> *`) re-enables global-by-default
5812///     for the scope.
5813///  6. The `LUA_COMPAT_GLOBAL` axis (default on upstream): un-reserves `global`
5814///     as a keyword and recognizes the statement only contextually. We model
5815///     the strict (compat-off) behavior; a per-state compat flag is future work.
5816/// Parses an optional `<const>` attribute on a global declaration, returning
5817/// whether the declaration is `const`. When no `<...>` attribute is present,
5818/// returns the default `df`.
5819///
5820/// Only `<const>` is legal for a global; `<close>` is the dedicated semantic
5821/// error `global variables cannot be to-be-closed`, and any other attribute
5822/// name is `unknown attribute '<name>'`. Both are emitted via
5823/// [`lua_lex::sem_error`] (location prefix, no `near` suffix).
5824fn get_global_attribute(
5825    ls: &mut LexState,
5826    state: &mut LuaState,
5827    df: bool,
5828) -> Result<bool, LuaError> {
5829    if !test_next(ls, state, b'<' as TokenKind)? {
5830        return Ok(df);
5831    }
5832    let attr = str_check_name(ls, state)?;
5833    check_next(ls, state, b'>' as TokenKind)?;
5834    match attr.as_bytes() {
5835        b"const" => Ok(true),
5836        b"close" => Err(lua_lex::sem_error(
5837            &mut ls.lex,
5838            b"global variables cannot be to-be-closed",
5839        )),
5840        other => {
5841            let msg = format!("unknown attribute '{}'", String::from_utf8_lossy(other));
5842            Err(lua_lex::sem_error(&mut ls.lex, msg.as_bytes()))
5843        }
5844    }
5845}
5846
5847fn globalstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5848    lex_next(ls, state)?; // skip 'global'
5849
5850    // `global function NAME body` — the global-function declaration form:
5851    // declares NAME as a regular global, compiles the body, runs the same
5852    // already-defined guard as `global NAME = expr`, then stores the closure.
5853    if ls.t.token == TK_FUNCTION {
5854        let line = ls.linenumber;
5855        lex_next(ls, state)?; // skip 'function'
5856        let name = str_check_name(ls, state)?;
5857        ls.declared_globals.push((name.clone(), false));
5858        add_scope_barrier(ls, name.clone());
5859        // Build the `_ENV[name]` lvalue (IndexUp; no register cost).
5860        let envn = ls
5861            .envn
5862            .clone()
5863            .expect("envn must be set when resolving globals");
5864        let mut target = ExprDesc::default();
5865        let mut fs_box = ls.fs.take();
5866        let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut target, true);
5867        ls.fs = fs_box;
5868        r?;
5869        let lline = ls.lastline;
5870        {
5871            let fs = ls.fs.as_mut().unwrap();
5872            cg_exp_to_any_reg_up(fs, lline, &mut target)?;
5873            let mut key = ExprDesc::default();
5874            codestring(&mut key, name.clone());
5875            cg_indexed(fs, lline, &mut target, &mut key)?;
5876        }
5877        let mut b = ExprDesc::default();
5878        ls.global_function_names.push(name.clone());
5879        let body_result = body(ls, state, &mut b, false, line);
5880        ls.global_function_names.pop();
5881        body_result?;
5882        {
5883            let fs = ls.fs.as_mut().unwrap();
5884            cg_check_global(fs, line, &target, name)?;
5885            cg_storevar(fs, line, &target, &mut b)?;
5886        }
5887        ls.global_strict = true;
5888        return Ok(());
5889    }
5890
5891    // Parse the optional prefixed attribute FIRST (the default kind for the
5892    // whole declaration), then branch on `*` (collective form) vs a name list.
5893    //
5894    //   globalstat -> (GLOBAL) attrib '*'
5895    //   globalstat -> (GLOBAL) attrib NAME attrib {',' NAME attrib}
5896    //
5897    // The leading `<const>` is NOT tied to `*`; `global <const> a, b` is a
5898    // const name list (each name defaults to the prefixed attribute and may
5899    // still carry its own per-name attribute).
5900    let defkind = get_global_attribute(ls, state, false)?;
5901
5902    // `global [attrib] '*'` — the collective form enables global-by-default for
5903    // the rest of the scope. Upstream keeps `*` as a declaration entry that
5904    // coexists with named `global` decls (a later `global name` does NOT void
5905    // it), so a wildcard flag (not merely clearing strict) models it: with the
5906    // wildcard active, every free name resolves as a global.
5907    if test_next(ls, state, b'*' as TokenKind)? {
5908        let star = state.intern_str(b"*")?;
5909        add_scope_barrier(ls, star);
5910        ls.global_strict = false;
5911        ls.global_wildcard = true;
5912        ls.global_wildcard_const = defkind;
5913        return Ok(());
5914    }
5915
5916    // `global attnamelist ['=' explist]` — the name-list form. Record each
5917    // declared name (with its `<const>`-ness) and switch the scope into strict
5918    // mode so subsequent free names must be declared (manual §2.2).
5919    let mut names: Vec<GcRef<LuaString>> = Vec::new();
5920    let mut declarations: Vec<(GcRef<LuaString>, bool)> = Vec::new();
5921    loop {
5922        let name = str_check_name(ls, state)?;
5923        let is_const = get_global_attribute(ls, state, defkind)?;
5924        names.push(name.clone());
5925        declarations.push((name, is_const));
5926        if !test_next(ls, state, b',' as TokenKind)? {
5927            break;
5928        }
5929    }
5930    // `= explist` initializer: assign the values to the declared globals, i.e.
5931    // `_ENV.name = value`. Mirrors `restassign`'s multiple-assignment codegen —
5932    // build an `_ENV[name]` lvalue per declared name (these are IndexUp, no
5933    // register cost), evaluate the RHS, adjust to the variable count, then store
5934    // each target from the top register down. (Initializers were previously
5935    // parsed and dropped.)
5936    if test_next(ls, state, b'=' as TokenKind)? {
5937        // The Lua 5.5 already-defined guard reports the error at the line of the
5938        // initializer (upstream `globalnames` passes `ls->linenumber` here).
5939        let init_line = ls.linenumber;
5940        let mut targets: Vec<ExprDesc> = Vec::with_capacity(names.len());
5941        for name in &names {
5942            let envn = ls
5943                .envn
5944                .clone()
5945                .expect("envn must be set when resolving globals");
5946            let mut env_var = ExprDesc::default();
5947            let mut fs_box = ls.fs.take();
5948            let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut env_var, true);
5949            ls.fs = fs_box;
5950            r?;
5951            let line = ls.lastline;
5952            let fs = ls.fs.as_mut().unwrap();
5953            cg_exp_to_any_reg_up(fs, line, &mut env_var)?;
5954            let mut key = ExprDesc::default();
5955            codestring(&mut key, name.clone());
5956            cg_indexed(fs, line, &mut env_var, &mut key)?;
5957            targets.push(env_var);
5958        }
5959        let nvars = targets.len() as i32;
5960        let mut e = ExprDesc::default();
5961        let nexps = explist(ls, state, &mut e)?;
5962        adjust_assign(ls, state, nvars, nexps, &mut e)?;
5963        // Mirror upstream `initglobal`: after the RHS is evaluated, for each
5964        // declared name emit `checkglobal` (the `OP_ERRNNIL` guard) immediately
5965        // before its store. The guard reads the global's *current* runtime value
5966        // and raises `global '<name>' already defined` if it is non-nil. Only
5967        // Lua 5.5 declares `global`; pre-5.5 never reaches this path.
5968        for (i, target) in targets.iter().enumerate().rev() {
5969            let name = names[i].clone();
5970            {
5971                let fs = ls.fs.as_mut().unwrap();
5972                cg_check_global(fs, init_line, target, name)?;
5973            }
5974            let line = ls.lastline;
5975            let fs = ls.fs.as_mut().unwrap();
5976            let freereg = fs.freereg as i32 - 1;
5977            let mut v = ExprDesc::default();
5978            init_exp(&mut v, ExprKind::NonReloc, freereg);
5979            cg_storevar(fs, line, target, &mut v)?;
5980        }
5981    }
5982    for (name, is_const) in declarations {
5983        ls.declared_globals.push((name.clone(), is_const));
5984        add_scope_barrier(ls, name);
5985    }
5986    ls.global_strict = true;
5987    Ok(())
5988}
5989
5990fn localstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5991    let local_line = ls.lastline;
5992    let mut toclose: i32 = -1;
5993    let mut nvars: i32 = 0;
5994    let mut vidx: i32;
5995    // Lua 5.5 accepts a PREFIXED attribute applied as the default for every
5996    // variable in the list — e.g. `local <const> a, b`. On 5.4/5.3 no prefixed
5997    // attribute exists, so a `<` before the first name stays the reference error
5998    // `<name> expected near '<'`; gate the prefix parse on 5.5.
5999    use lua_types::LuaVersion;
6000    let defkind = if matches!(state.global().lua_version, LuaVersion::V55) {
6001        getlocalattribute(ls, state, VarKind::Reg)?
6002    } else {
6003        VarKind::Reg
6004    };
6005    loop {
6006        let name = str_check_name(ls, state)?;
6007        vidx = new_local_var(ls, state, name)?;
6008        let kind = getlocalattribute(ls, state, defkind)?;
6009        get_local_var_desc_mut(ls, ls.fs.as_ref().unwrap().firstlocal, vidx).kind = kind;
6010        if kind == VarKind::ToBeClosed {
6011            if toclose != -1 {
6012                let saved_line = ls.lex.linenumber;
6013                ls.lex.linenumber = local_line;
6014                let err = lua_lex::lex_error(
6015                    &mut ls.lex,
6016                    b"multiple to-be-closed variables in local list",
6017                    0,
6018                );
6019                ls.lex.linenumber = saved_line;
6020                return Err(err);
6021            }
6022            toclose = ls.fs.as_ref().unwrap().nactvar as i32 + nvars;
6023        }
6024        nvars += 1;
6025        if !test_next(ls, state, b',' as TokenKind)? {
6026            break;
6027        }
6028    }
6029    let nexps: i32;
6030    let mut e = ExprDesc::default();
6031    if test_next(ls, state, b'=' as TokenKind)? {
6032        nexps = explist(ls, state, &mut e)?;
6033    } else {
6034        e.k = ExprKind::Void;
6035        nexps = 0;
6036    }
6037    let first_local = ls.fs.as_ref().unwrap().firstlocal;
6038    let last_vd_kind = ls.dyd.actvar[(first_local + vidx) as usize].kind;
6039    if nvars == nexps && last_vd_kind == VarKind::Const {
6040        // TODO(port): let is_const = lua_code::exp_to_const(ls.fs.as_mut().unwrap(), &mut e, &mut var_k)?;
6041        let is_const = false; // placeholder
6042        if is_const {
6043            ls.dyd.actvar[(first_local + vidx) as usize].kind = VarKind::CompileTimeConst;
6044            adjust_local_vars(ls, state, nvars - 1)?;
6045            ls.fs.as_mut().unwrap().nactvar += 1;
6046        } else {
6047            adjust_assign(ls, state, nvars, nexps, &mut e)?;
6048            adjust_local_vars(ls, state, nvars)?;
6049        }
6050    } else {
6051        adjust_assign(ls, state, nvars, nexps, &mut e)?;
6052        adjust_local_vars(ls, state, nvars)?;
6053    }
6054    checktoclose(ls, state, toclose)?;
6055    Ok(())
6056}
6057
6058/// Parses a function name (NAME {'.' NAME} [':' NAME]). Returns ismethod.
6059fn funcname(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<bool, LuaError> {
6060    let mut ismethod = false;
6061    singlevar(ls, state, v)?;
6062    while ls.t.token == b'.' as TokenKind {
6063        fieldsel(ls, state, v)?;
6064    }
6065    if ls.t.token == b':' as TokenKind {
6066        ismethod = true;
6067        fieldsel(ls, state, v)?;
6068    }
6069    Ok(ismethod)
6070}
6071
6072fn funcstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
6073    lex_next(ls, state)?;
6074    let mut v = ExprDesc::default();
6075    let mut b = ExprDesc::default();
6076    let ismethod = funcname(ls, state, &mut v)?;
6077    check_readonly(ls, state, &v.clone())?;
6078    body(ls, state, &mut b, ismethod, line)?;
6079    check_readonly(ls, state, &v.clone())?;
6080    let fs = ls.fs.as_mut().unwrap();
6081    cg_storevar(fs, line, &v, &mut b)?;
6082    // TODO(port): lua_code::fix_line(ls.fs.as_mut().unwrap(), line);
6083    Ok(())
6084}
6085
6086fn exprstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
6087    let mut v_assign = LhsAssign {
6088        prev: None,
6089        v: ExprDesc::default(),
6090    };
6091    suffixedexp(ls, state, &mut v_assign.v)?;
6092    if ls.t.token == b'=' as TokenKind || ls.t.token == b',' as TokenKind {
6093        restassign(ls, state, &mut v_assign, 1)?;
6094    } else {
6095        if v_assign.v.k != ExprKind::Call {
6096            // Lua 5.1's `exprstat` falls into `assignment`, which requires an
6097            // `=`, so a bare primary expression statement reports `'=' expected`.
6098            // 5.2+ rewrote this path to report the generic `syntax error`. Match
6099            // the version. This is what makes `goto done` (where `goto` lexes as
6100            // a name under V51) report `'=' expected near 'done'`. See
6101            // specs/followup/5.1-roster-syntax.md §2.
6102            if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
6103                return Err(error_expected(ls, b'=' as TokenKind));
6104            }
6105            return Err(lua_lex::syntax_error(&mut ls.lex, b"syntax error"));
6106        }
6107        let info = v_assign.v.u.info as usize;
6108        let fs = ls.fs.as_mut().unwrap();
6109        let mut lc = lua_code::opcodes::Instruction(fs.f.code[info].0);
6110        lc.set_arg_c(1);
6111        fs.f.code[info] = lua_types::opcode::Instruction::new(lc.0);
6112    }
6113    Ok(())
6114}
6115
6116fn retstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
6117    let mut first = {
6118        let fs = ls.fs.as_ref().unwrap();
6119        nvarstack(ls, fs)
6120    };
6121    let mut nret: i32;
6122    if block_follow(ls, true) || ls.t.token == b';' as TokenKind {
6123        nret = 0;
6124    } else {
6125        let mut e = ExprDesc::default();
6126        nret = explist(ls, state, &mut e)?;
6127        if e.k.has_mult_ret() {
6128            cg_set_returns(ls.fs.as_mut().unwrap(), &mut e, LUA_MULTRET);
6129            if e.k == ExprKind::Call && nret == 1 {
6130                let insidetbc = ls
6131                    .fs
6132                    .as_ref()
6133                    .unwrap()
6134                    .bl
6135                    .as_ref()
6136                    .map_or(false, |b| b.insidetbc);
6137                if !insidetbc {
6138                    let fs = ls.fs.as_mut().unwrap();
6139                    let info = e.u.info as usize;
6140                    let mut lc = lua_code::opcodes::Instruction(fs.f.code[info].0);
6141                    lc.set_opcode(lua_code::opcodes::OpCode::TailCall);
6142                    fs.f.code[info] = lua_types::opcode::Instruction::new(lc.0);
6143                }
6144            }
6145            nret = LUA_MULTRET;
6146        } else {
6147            let line = ls.lastline;
6148            if nret == 1 {
6149                first = cg_exp_to_any_reg(ls.fs.as_mut().unwrap(), line, &mut e)? as i32;
6150            } else {
6151                cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut e)?;
6152            }
6153        }
6154    }
6155    let line = ls.lastline;
6156    let version = state.global().lua_version;
6157    cg_emit_return(ls.fs.as_mut().unwrap(), line, first, nret, version)?;
6158    test_next(ls, state, b';' as TokenKind)?;
6159    Ok(())
6160}
6161
6162/// Top-level statement dispatcher.
6163fn statement(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
6164    // This is the line of the current keyword (for/while/if/...), captured
6165    // BEFORE consuming. Used both for error messages on unmatched blocks
6166    // AND for runtime-error line attribution on control-flow instructions
6167    // (FORPREP, etc). errors.lua's lineerror tests depend on this.
6168    let line = ls.linenumber;
6169    enter_level(ls, state)?;
6170    match ls.t.token {
6171        c if c == b';' as TokenKind
6172            && state.global().lua_version != lua_types::LuaVersion::V51 =>
6173        {
6174            lex_next(ls, state)?;
6175        }
6176        TK_IF => {
6177            ifstat(ls, state, line)?;
6178        }
6179        TK_WHILE => {
6180            whilestat(ls, state, line)?;
6181        }
6182        TK_DO => {
6183            lex_next(ls, state)?; // skip DO
6184            block(ls, state)?;
6185            check_match(ls, state, TK_END, TK_DO, line)?;
6186        }
6187        TK_FOR => {
6188            forstat(ls, state, line)?;
6189        }
6190        TK_REPEAT => {
6191            repeatstat(ls, state, line)?;
6192        }
6193        TK_FUNCTION => {
6194            funcstat(ls, state, line)?;
6195        }
6196        TK_LOCAL => {
6197            lex_next(ls, state)?; // skip LOCAL
6198            if test_next(ls, state, TK_FUNCTION)? {
6199                localfunc(ls, state)?;
6200            } else {
6201                localstat(ls, state)?;
6202            }
6203        }
6204        TK_DBCOLON => {
6205            lex_next(ls, state)?; // skip '::'
6206            let name = str_check_name(ls, state)?;
6207            labelstat(ls, state, name, line)?;
6208        }
6209        TK_RETURN => {
6210            lex_next(ls, state)?; // skip RETURN
6211            retstat(ls, state)?;
6212        }
6213        TK_BREAK => {
6214            breakstat(ls, state)?;
6215        }
6216        TK_GOTO => {
6217            lex_next(ls, state)?; // skip 'goto'
6218            gotostat(ls, state)?;
6219        }
6220        _ => {
6221            // Lua 5.5 with the upstream-default LUA_COMPAT_GLOBAL: `global` is
6222            // NOT a reserved word. It introduces a declaration only when, at
6223            // statement start, the name `global` is followed by a Name, `*`, or
6224            // `<` (the collective `global <const> *` form). Otherwise it is an
6225            // ordinary identifier and the statement is a normal assignment/call.
6226            let is_global_decl = state.global().lua_version == lua_types::LuaVersion::V55
6227                && ls.t.token == TK_NAME
6228                && ls
6229                    .t
6230                    .seminfo
6231                    .ts
6232                    .as_ref()
6233                    .map_or(false, |s| s.as_bytes() == b"global")
6234                && {
6235                    let nxt = lex_lookahead(ls, state)?;
6236                    nxt == TK_NAME
6237                        || nxt == b'*' as TokenKind
6238                        || nxt == b'<' as TokenKind
6239                        || nxt == TK_FUNCTION
6240                };
6241            if is_global_decl {
6242                globalstat(ls, state)?;
6243            } else {
6244                exprstat(ls, state)?;
6245            }
6246        }
6247    }
6248    debug_assert!(
6249        ls.fs.as_ref().unwrap().f.maxstacksize >= ls.fs.as_ref().unwrap().freereg
6250            && ls.fs.as_ref().unwrap().freereg as i32 >= nvarstack(ls, ls.fs.as_ref().unwrap())
6251    );
6252    let nv = nvarstack(ls, ls.fs.as_ref().unwrap());
6253    ls.fs.as_mut().unwrap().freereg = nv as u8;
6254    leave_level(ls);
6255    Ok(())
6256}
6257
6258// ── §14 Main function and entry point ────────────────────────────────────────
6259
6260/// Compiles the main chunk (always a vararg function with _ENV upvalue).
6261fn mainfunc(
6262    ls: &mut LexState,
6263    state: &mut LuaState,
6264    main_fs: FuncState,
6265) -> Result<Box<LuaProto>, LuaError> {
6266    open_func(ls, state, main_fs)?;
6267
6268    setvararg(ls.fs.as_mut().unwrap(), state, 0)?;
6269
6270    let env_name = ls.envn.clone();
6271    {
6272        let version = ls.lex.version;
6273        let idx = alloc_upvalue(ls.fs.as_mut().unwrap(), version)?;
6274        let up = &mut ls.fs.as_mut().unwrap().f.upvalues[idx];
6275        up.instack = true;
6276        up.idx = 0;
6277        up.kind = VarKind::Reg.as_u8();
6278        up.name = env_name.clone();
6279    }
6280
6281    lex_next(ls, state)?;
6282
6283    statlist(ls, state)?;
6284
6285    check(ls, TK_EOS)?;
6286
6287    close_func(ls, state)
6288}
6289
6290/// Top-level entry point: parses a whole chunk and returns the prototype of its
6291/// main function. The caller wraps this `Box<LuaProto>` into a closure and hands
6292/// it to the GC; that boundary is the public contract of this crate.
6293pub fn parse(
6294    state: &mut LuaState,
6295    dyd: DynData,
6296    z: &mut lua_vm::zio::ZIO,
6297    name: &[u8],
6298    firstchar: i32,
6299) -> Result<Box<LuaProto>, LuaError> {
6300    let source_str = state.intern_str(name)?;
6301    let envn_str = state.intern_str(lua_lex::LUA_ENV)?;
6302
6303    let z = z.take();
6304
6305    let lex_ls = lua_lex::LexState {
6306        current: firstchar,
6307        linenumber: 1,
6308        lastline: 1,
6309        t: lua_lex::Token::eos(),
6310        lookahead: lua_lex::Token::eos(),
6311        fs: None,
6312        z,
6313        buff: lua_lex::LexBuffer::new(),
6314        h: None,
6315        long_str_anchor: std::collections::HashMap::new(),
6316        dyd: None,
6317        source: source_str.clone(),
6318        envn: envn_str.clone(),
6319        version: state.global().lua_version,
6320    };
6321
6322    let mut lexstate = LexState {
6323        current: lex_ls.current,
6324        linenumber: lex_ls.linenumber,
6325        lastline: lex_ls.lastline,
6326        t: LexToken::default(),
6327        lookahead: LexToken::default(),
6328        fs: None,
6329        dyd,
6330        source: Some(source_str.clone()),
6331        envn: Some(lex_ls.envn.clone()),
6332        lex: lex_ls,
6333        recursion_depth: 0,
6334        global_strict: false,
6335        global_wildcard: false,
6336        global_wildcard_const: false,
6337        declared_globals: Vec::new(),
6338        scope_barriers: Vec::new(),
6339        global_function_names: Vec::new(),
6340    };
6341    //   `mainfunc`; it does NOT pre-read the first token. `mainfunc` itself
6342    //   issues the initial `luaX_next` once its prelude (open_func, vararg
6343    //   marker, _ENV upvalue) is in place.
6344
6345    let mut main_proto = Box::new(LuaProto::placeholder());
6346    main_proto.source = Some(source_str);
6347    main_proto.is_vararg = true;
6348    let main_fs = FuncState {
6349        f: main_proto,
6350        prev: None,
6351        bl: None,
6352        pc: 0,
6353        lasttarget: 0,
6354        previousline: 0,
6355        nk: 0,
6356        np: 0,
6357        nabslineinfo: 0,
6358        firstlocal: 0,
6359        firstlabel: 0,
6360        ndebugvars: 0,
6361        nactvar: 0,
6362        first_scope_barrier: 0,
6363        nups: 0,
6364        freereg: 0,
6365        iwthabs: 0,
6366        needclose: false,
6367        last_token_line: 0,
6368    };
6369
6370    mainfunc(&mut lexstate, state, main_fs)
6371}
6372
6373/// Convert a `lua_lex::TokenValue` into the local `parse::TokenValue` flat shape.
6374///
6375/// The parser's local `LexState` predates the lex-side enum and uses a flat
6376/// (r, i, ts) record; this picks out whichever variant the lexer produced.
6377fn local_token_value(v: &lua_lex::TokenValue) -> TokenValue {
6378    match v {
6379        lua_lex::TokenValue::None => TokenValue::default(),
6380        lua_lex::TokenValue::Float(r) => TokenValue {
6381            r: *r,
6382            i: 0,
6383            ts: None,
6384        },
6385        lua_lex::TokenValue::Int(i) => TokenValue {
6386            r: 0.0,
6387            i: *i,
6388            ts: None,
6389        },
6390        lua_lex::TokenValue::Str(s) => TokenValue {
6391            r: 0.0,
6392            i: 0,
6393            ts: Some(s.clone()),
6394        },
6395    }
6396}
6397
6398#[cfg(test)]
6399mod tests {
6400    use super::*;
6401
6402    /// A bare [`FuncState`] with an empty prototype, enough to exercise the
6403    /// codegen primitives that only read/write `f.code` (jump emission and the
6404    /// jump-list cursor).
6405    fn bare_fs() -> FuncState {
6406        FuncState {
6407            f: Box::new(LuaProto::placeholder()),
6408            prev: None,
6409            bl: None,
6410            pc: 0,
6411            lasttarget: 0,
6412            previousline: 0,
6413            nk: 0,
6414            np: 0,
6415            nabslineinfo: 0,
6416            firstlocal: 0,
6417            firstlabel: 0,
6418            ndebugvars: 0,
6419            nactvar: 0,
6420            first_scope_barrier: 0,
6421            nups: 0,
6422            freereg: 0,
6423            iwthabs: 0,
6424            needclose: false,
6425            last_token_line: 0,
6426        }
6427    }
6428
6429    /// Emit three `OP_JMP`s, thread them into one list via [`cg_concat`], then
6430    /// confirm the [`JumpList`] cursor yields exactly the pc sequence a manual
6431    /// `while pc != NO_JUMP { pc = cg_get_jump(fs, pc) }` walk produces. This is
6432    /// the behavioral invariant the iterator transformation must preserve.
6433    #[test]
6434    fn jumplist_yields_same_pcs_as_manual_walk() {
6435        let mut fs = bare_fs();
6436
6437        let mut list = NO_JUMP;
6438        let mut emitted = Vec::new();
6439        for _ in 0..3 {
6440            let pc = cg_jump(&mut fs, 1);
6441            emitted.push(pc);
6442            cg_concat(&mut fs, &mut list, pc).unwrap();
6443        }
6444
6445        let mut manual = Vec::new();
6446        let mut pc = list;
6447        while pc != NO_JUMP {
6448            manual.push(pc);
6449            pc = cg_get_jump(&fs, pc);
6450        }
6451
6452        let mut via_cursor = Vec::new();
6453        let mut walk = JumpList::new(list);
6454        while let Some(pc) = walk.next(&fs) {
6455            via_cursor.push(pc);
6456        }
6457
6458        assert_eq!(manual, via_cursor);
6459        assert_eq!(manual.len(), 3);
6460        let mut sorted = manual.clone();
6461        sorted.sort_unstable();
6462        let mut sorted_emitted = emitted.clone();
6463        sorted_emitted.sort_unstable();
6464        assert_eq!(sorted, sorted_emitted);
6465    }
6466
6467    /// An empty list yields nothing; a single-node list yields exactly that pc.
6468    #[test]
6469    fn jumplist_empty_and_single() {
6470        let mut fs = bare_fs();
6471
6472        let mut empty = JumpList::new(NO_JUMP);
6473        assert_eq!(empty.next(&fs), None);
6474
6475        let pc = cg_jump(&mut fs, 1);
6476        let mut single = JumpList::new(pc);
6477        assert_eq!(single.next(&fs), Some(pc));
6478        assert_eq!(single.next(&fs), None);
6479    }
6480
6481    /// [`cg_concat`] must still fix the tail of an existing list to point at the
6482    /// appended jump — the cursor-based tail walk must find the same tail node
6483    /// the old hand loop did.
6484    #[test]
6485    fn cg_concat_links_tail_to_appended_jump() {
6486        let mut fs = bare_fs();
6487        let a = cg_jump(&mut fs, 1);
6488        let b = cg_jump(&mut fs, 1);
6489        let mut list = a;
6490        cg_concat(&mut fs, &mut list, b).unwrap();
6491        assert_eq!(list, a);
6492        assert_eq!(cg_get_jump(&fs, a), b);
6493        assert_eq!(cg_get_jump(&fs, b), NO_JUMP);
6494    }
6495
6496    /// Spot-check the token-to-binop mapping and the load-bearing invariant that
6497    /// every [`BinOpr`] discriminant is a valid index into [`PRIORITY`]. The
6498    /// expression parser indexes `PRIORITY[op as usize]`; a reordered or
6499    /// short-by-one table would silently mis-climb operator precedence.
6500    #[test]
6501    fn binopr_mapping_and_priority_table_are_consistent() {
6502        assert_eq!(getbinopr(b'+' as TokenKind), BinOpr::Add);
6503        assert_eq!(getbinopr(b'/' as TokenKind), BinOpr::Div);
6504        assert_eq!(getbinopr(TK_IDIV), BinOpr::IDiv);
6505        assert_eq!(getbinopr(TK_SHL), BinOpr::Shl);
6506        assert_eq!(getbinopr(TK_CONCAT), BinOpr::Concat);
6507        assert_eq!(getbinopr(TK_AND), BinOpr::And);
6508        assert_eq!(getbinopr(b'@' as TokenKind), BinOpr::NoBinOpr);
6509
6510        for op in [
6511            BinOpr::Add,
6512            BinOpr::Pow,
6513            BinOpr::Concat,
6514            BinOpr::Eq,
6515            BinOpr::And,
6516            BinOpr::Or,
6517        ] {
6518            assert!(
6519                (op as usize) < PRIORITY.len(),
6520                "{op:?} out of PRIORITY range"
6521            );
6522        }
6523        assert_eq!(BinOpr::Or as usize, PRIORITY.len() - 1);
6524
6525        assert_eq!(getunopr(b'-' as TokenKind), UnOpr::Minus);
6526        assert_eq!(getunopr(TK_NOT), UnOpr::Not);
6527        assert_eq!(getunopr(b'#' as TokenKind), UnOpr::Len);
6528        assert_eq!(getunopr(b'+' as TokenKind), UnOpr::NoUnOpr);
6529    }
6530}
6531
6532// ──────────────────────────────────────────────────────────────────────────
6533// PORT STATUS
6534//   source:        originally ported from src/lparser.c + src/lparser.h with
6535//                  src/lcode.c codegen folded in; the C correspondence has since
6536//                  been GRADUATED away (see GRADUATED.md and the module-level
6537//                  doc). This file no longer tracks the C line-by-line — it is
6538//                  idiomatic Rust guarded by the oracle.
6539//   target_crate:  lua-parse
6540//   confidence:    high
6541//   todos:         8  (genuine deferred-codegen markers, not crutch: integer
6542//                  stack-check, debug-var startpc, local const-fold, explicit
6543//                  fix_line, GC proto allocation, single-vs-multret arg, and the
6544//                  unnamed-var defensive branch — each kept because the
6545//                  bytecode-parity oracle proves they do not move output, and
6546//                  removing them would hide a real divergence from full lcode.c)
6547//   port_notes:    0  (C-correspondence crutches removed in idiomatization S1)
6548//   unsafe_blocks: 0
6549//   notes:         Idiomatized (Sprint 1, P1b — subsumes P1c, since lcode.c is
6550//                  folded in here and the standalone lua-code crate is only the
6551//                  opcode tables). The emit/register-alloc/jump-offset/line-info/
6552//                  constant-fold CORE was deliberately left structurally faithful
6553//                  (the hot-loop exception). The oracle that now guards behaviour:
6554//                  bytecode parity (parser+codegen → identical luac -l -l), the
6555//                  multiversion_oracle, the full official suite, and the
6556//                  check.sh 5.1..5.5 version batteries. Do NOT reach for
6557//                  lparser.c / lcode.c to debug this file — see GRADUATED.md.
6558// ──────────────────────────────────────────────────────────────────────────