Skip to main content

lua_lex/
lib.rs

1//! Lexical analyzer — port of `llex.c` + `llex.h`.
2//!
3//! Provides the Lua 5.4 lexer: character-by-character scanning of a [`ZIO`]
4//! input stream into [`Token`] values, with one-token lookahead.  The
5//! `llex.h` header is merged here per PORTING.md §1.
6//!
7//! # C source files
8//! - `reference/lua-5.4.7/src/llex.c`  (581 lines, 24 functions)
9//! - `reference/lua-5.4.7/src/llex.h`  (91 lines; merged here)
10//!
11//! # Design notes
12//! - `LexState.L` (back-pointer to `lua_State`) is removed.  All functions
13//!   that need `LuaState` receive it as `state: &mut LuaState`.
14//! - `Token.token` is `i32` in Phase A (matching the C `int token` field).
15//!   Single-byte tokens are their ASCII values; reserved-word tokens start at
16//!   `FIRST_RESERVED` (257).  A proper `TokenKind` enum is deferred to Phase B.
17//! - `save` / `save_and_next` are now fallible (`Result<(), LuaError>`); the
18//!   `?` operator replaces the C noreturn `lexerror` call on buffer overflow.
19//! - The `goto read_save / only_save / no_save` pattern in `read_string` is
20//!   translated via the local `EscapeResult` enum.
21
22// TODO(port): resolve remaining cross-crate calls (intern_str, table anchor,
23// number parsing, utf8 encoding) in Phase B.  Canonical cross-crate type
24// imports are now in place per harness/type-vocabulary.tsv (see below).
25
26use std::io::Write as IoWrite;
27
28// PORT NOTE: GcRef<T> = Rc<T> in Phases A–C; replaced by real GC pointer in Phase D.
29use lua_types::gc::GcRef;
30
31// Canonical cross-crate types: imported from owner crates per
32// harness/type-vocabulary.tsv.  See PORTING.md §7.
33pub use lua_types::LuaError;
34pub use lua_types::LuaString;
35pub use lua_vm::state::LuaState;
36pub use lua_vm::table::LuaTable;
37
38/// Placeholder for `LexBuffer` from `lua_vm::zio`.
39/// TODO(port): replace with `use lua_vm::zio::LexBuffer` in Phase B.
40/// types.tsv: Mbuffer → LexBuffer
41pub struct LexBuffer {
42    buffer: Vec<u8>,
43}
44
45impl LexBuffer {
46    pub fn new() -> Self {
47        LexBuffer { buffer: Vec::new() }
48    }
49
50    /// macros.tsv: luaZ_bufflen → buf.len()
51    pub fn len(&self) -> usize {
52        self.buffer.len()
53    }
54
55    /// macros.tsv: luaZ_sizebuffer → buf.capacity()
56    pub fn capacity(&self) -> usize {
57        self.buffer.capacity()
58    }
59
60    /// macros.tsv: luaZ_buffer → buf.as_mut_slice()
61    pub fn as_slice(&self) -> &[u8] {
62        &self.buffer
63    }
64
65    /// macros.tsv: luaZ_resetbuffer → buf.clear()
66    pub fn clear(&mut self) {
67        self.buffer.clear();
68    }
69
70    /// macros.tsv: luaZ_buffremove → buf.truncate_by(i)
71    pub fn truncate_by(&mut self, i: usize) {
72        let new_len = self.buffer.len().saturating_sub(i);
73        self.buffer.truncate(new_len);
74    }
75
76    /// allocated capacity. In C this changes `buffsize`, not the live byte
77    /// count `n`. The Rust analogue therefore manipulates `Vec::capacity`,
78    /// never `Vec::len` (otherwise `push_byte` would write past the live
79    /// content and leave embedded zero padding inside the token text).
80    pub fn resize(&mut self, _state: &mut LuaState, size: usize) -> Result<(), LuaError> {
81        if size < self.buffer.len() {
82            self.buffer.truncate(size);
83        }
84        if size > self.buffer.capacity() {
85            let extra = size - self.buffer.capacity();
86            self.buffer.reserve_exact(extra);
87        }
88        Ok(())
89    }
90
91    /// Append one byte to the live contents.  Panics if capacity exceeded
92    /// (callers must pre-check via `save`).
93    fn push_byte(&mut self, c: u8) {
94        self.buffer.push(c);
95    }
96}
97
98impl Default for LexBuffer {
99    fn default() -> Self {
100        Self::new()
101    }
102}
103
104/// Placeholder for `ZIO` from `lua_vm::zio`.
105/// TODO(port): replace with `use lua_vm::zio::ZIO` in Phase B.
106/// types.tsv: Zio → ZIO
107pub struct ZIO {
108    // TODO(port): full ZIO implementation lives in lua_vm::zio; this is a stub.
109    reader: Box<dyn FnMut() -> Option<Vec<u8>>>,
110    n: usize,
111    p: usize,
112    current_chunk: Vec<u8>,
113}
114
115impl ZIO {
116    /// Construct a ZIO from a reader callback that yields successive chunks.
117    pub fn new(reader: Box<dyn FnMut() -> Option<Vec<u8>>>) -> Self {
118        ZIO { reader, n: 0, p: 0, current_chunk: Vec::new() }
119    }
120
121    /// Construct a ZIO that yields the supplied bytes once and then EOZ.
122    pub fn from_bytes(bytes: Vec<u8>) -> Self {
123        let mut once = Some(bytes);
124        ZIO::new(Box::new(move || once.take()))
125    }
126
127    /// macros.tsv: zgetc → z.getc()
128    pub fn getc(&mut self) -> i32 {
129        if self.n > 0 {
130            self.n -= 1;
131            let b = self.current_chunk[self.p] as u8;
132            self.p += 1;
133            b as i32
134        } else {
135            self.fill()
136        }
137    }
138
139    fn fill(&mut self) -> i32 {
140        match (self.reader)() {
141            None => EOZ,
142            Some(chunk) if chunk.is_empty() => EOZ,
143            Some(chunk) => {
144                self.n = chunk.len() - 1;
145                self.current_chunk = chunk;
146                self.p = 0;
147                let b = self.current_chunk[self.p] as u8;
148                self.p += 1;
149                b as i32
150            }
151        }
152    }
153}
154
155// ── Constants ─────────────────────────────────────────────────────────────────
156
157// macros.tsv: FIRST_RESERVED → const FIRST_RESERVED: i32 = 257
158/// First token kind value that is not a single-byte character.
159/// Single-byte tokens are represented by their ASCII value (0-255).
160pub const FIRST_RESERVED: i32 = 257;
161
162// macros.tsv: LUA_ENV → const LUA_ENV: &[u8] = b"_ENV"
163/// Name of the global environment upvalue.
164pub const LUA_ENV: &[u8] = b"_ENV";
165
166// macros.tsv: NUM_RESERVED → const NUM_RESERVED: usize = (TK_WHILE - FIRST_RESERVED + 1) as usize
167/// Number of reserved words (keywords).
168pub const NUM_RESERVED: usize = (TK_WHILE - FIRST_RESERVED + 1) as usize;
169
170// macros.tsv: EOZ → const EOZ: i32 = -1
171/// End-of-stream sentinel returned by ZIO::getc.
172pub const EOZ: i32 = -1;
173
174// macros.tsv: MAX_SIZE → const MAX_SIZE: usize = ...
175const MAX_SIZE: usize = if std::mem::size_of::<usize>() < std::mem::size_of::<i64>() {
176    usize::MAX
177} else {
178    i64::MAX as usize
179};
180
181// macros.tsv: LUA_MIN_BUFFER → const LUA_MIN_BUFFER: usize = 32
182const LUA_MIN_BUFFER: usize = 32;
183
184// ── Token kind constants (ORDER RESERVED — matches C enum RESERVED) ───────────
185//
186// In C these are enum values.  In Rust we use i32 constants for Phase A
187// (faithful to `Token.token: int` in C) with a TODO for a proper enum in Phase B.
188//
189
190/// `and`
191pub const TK_AND: i32 = 257;
192/// `break`
193pub const TK_BREAK: i32 = 258;
194/// `do`
195pub const TK_DO: i32 = 259;
196/// `else`
197pub const TK_ELSE: i32 = 260;
198/// `elseif`
199pub const TK_ELSEIF: i32 = 261;
200/// `end`
201pub const TK_END: i32 = 262;
202/// `false`
203pub const TK_FALSE: i32 = 263;
204/// `for`
205pub const TK_FOR: i32 = 264;
206/// `function`
207pub const TK_FUNCTION: i32 = 265;
208/// `goto`
209pub const TK_GOTO: i32 = 266;
210/// `if`
211pub const TK_IF: i32 = 267;
212/// `in`
213pub const TK_IN: i32 = 268;
214/// `local`
215pub const TK_LOCAL: i32 = 269;
216/// `nil`
217pub const TK_NIL: i32 = 270;
218/// `not`
219pub const TK_NOT: i32 = 271;
220/// `or`
221pub const TK_OR: i32 = 272;
222/// `repeat`
223pub const TK_REPEAT: i32 = 273;
224/// `return`
225pub const TK_RETURN: i32 = 274;
226/// `then`
227pub const TK_THEN: i32 = 275;
228/// `true`
229pub const TK_TRUE: i32 = 276;
230/// `until`
231pub const TK_UNTIL: i32 = 277;
232/// `while`  (last keyword; NUM_RESERVED = TK_WHILE - FIRST_RESERVED + 1 = 22)
233pub const TK_WHILE: i32 = 278;
234/// `//`  (floor division)
235pub const TK_IDIV: i32 = 279;
236/// `..`  (concatenation)
237pub const TK_CONCAT: i32 = 280;
238/// `...` (vararg)
239pub const TK_DOTS: i32 = 281;
240/// `==`
241pub const TK_EQ: i32 = 282;
242/// `>=`
243pub const TK_GE: i32 = 283;
244/// `<=`
245pub const TK_LE: i32 = 284;
246/// `~=`
247pub const TK_NE: i32 = 285;
248/// `<<`
249pub const TK_SHL: i32 = 286;
250/// `>>`
251pub const TK_SHR: i32 = 287;
252/// `::`
253pub const TK_DBCOLON: i32 = 288;
254/// `<eof>`
255pub const TK_EOS: i32 = 289;
256/// `<number>`  (float literal)
257pub const TK_FLT: i32 = 290;
258/// `<integer>` (integer literal)
259pub const TK_INT: i32 = 291;
260/// `<name>`    (identifier)
261pub const TK_NAME: i32 = 292;
262/// `<string>`  (string literal)
263pub const TK_STRING: i32 = 293;
264
265// Lua 5.5 `global`: with the upstream-default LUA_COMPAT_GLOBAL it is NOT a
266// reserved word — it always lexes as TK_NAME (so it stays a valid identifier on
267// every version), and the parser recognizes the `global` declaration statement
268// contextually (see `globalstat`/`statement` in lua-parse). There is therefore
269// no dedicated token id.
270
271// ORDER RESERVED — index 0 = TK_AND - FIRST_RESERVED, etc.
272/// Display strings for tokens, indexed by `token - FIRST_RESERVED`.
273pub static LUAX_TOKENS: &[&[u8]] = &[
274    // keywords (indices 0-21)
275    b"and", b"break", b"do", b"else", b"elseif",
276    b"end", b"false", b"for", b"function", b"goto", b"if",
277    b"in", b"local", b"nil", b"not", b"or", b"repeat",
278    b"return", b"then", b"true", b"until", b"while",
279    // other terminal symbols (indices 22-35)
280    b"//", b"..", b"...", b"==", b">=", b"<=", b"~=",
281    b"<<", b">>", b"::", b"<eof>",
282    b"<number>", b"<integer>", b"<name>", b"<string>",
283];
284
285// ── SemInfo / TokenValue ───────────────────────────────────────────────────────
286
287// types.tsv: SemInfo → TokenValue
288/// Semantic payload carried by a token.
289///
290/// Corresponds to `SemInfo` (a C union) in `llex.h`.  In Rust this is a
291/// discriminated union (enum).
292///
293/// # C mapping
294/// ```text
295/// SemInfo.r   → TokenValue::Float(f64)      (lua_Number)
296/// SemInfo.i   → TokenValue::Int(i64)        (lua_Integer)
297/// SemInfo.ts  → TokenValue::Str(GcRef<LuaString>)
298/// (no C field) → TokenValue::None           (default / unset)
299/// ```
300#[derive(Clone)]
301pub enum TokenValue {
302    /// No semantic value (default; used for single-byte and most multi-char tokens).
303    None,
304    /// Float literal payload.  C: `seminfo.r` (`lua_Number`).
305    Float(f64),
306    /// Integer literal payload.  C: `seminfo.i` (`lua_Integer`).
307    Int(i64),
308    /// String/name payload.  C: `seminfo.ts` (`TString *`).
309    Str(GcRef<LuaString>),
310}
311
312// ── Token ─────────────────────────────────────────────────────────────────────
313
314// types.tsv: Token → Token;  Token.token → i32 (Phase A; TODO: TokenKind enum Phase B)
315/// A single lexed token with its semantic payload.
316///
317/// `kind` is an `i32` whose value is either an ASCII byte code (for single-byte
318/// tokens like `+`, `-`, `[`) or one of the `TK_*` constants (for reserved
319/// words, multi-char symbols, and literals).
320///
321/// TODO(port): Phase B — replace `kind: i32` with a proper `TokenKind` enum
322/// covering both single-byte and named tokens (e.g. `TokenKind::Char(u8)` +
323/// named variants).
324#[derive(Clone)]
325pub struct Token {
326    pub kind: i32,
327    pub value: TokenValue,
328}
329
330impl Token {
331    /// Construct a token with no semantic value.
332    pub fn new(kind: i32) -> Self {
333        Token { kind, value: TokenValue::None }
334    }
335
336    /// The end-of-stream sentinel token.
337    pub fn eos() -> Self {
338        Token::new(TK_EOS)
339    }
340}
341
342// ── LexState ──────────────────────────────────────────────────────────────────
343
344// types.tsv: LexState → LexState;  LexState.L removed (thread via &mut LuaState)
345/// Per-chunk lexer (and shared parser) state.
346///
347/// Corresponds to `LexState` in `llex.h`.  Owns the input stream, token
348/// buffer, and current/lookahead tokens.
349///
350/// # C mapping (types.tsv)
351/// ```text
352/// LexState.current    → current: i32        (charint; -1 = EOZ)
353/// LexState.linenumber → linenumber: i32
354/// LexState.lastline   → lastline: i32
355/// LexState.t          → t: Token            (current token)
356/// LexState.lookahead  → lookahead: Token    (one-token lookahead)
357/// LexState.fs         → fs: Option<Box<FuncState>>   (parser state)
358/// LexState.L          → (removed; callers pass &mut LuaState)
359/// LexState.z          → z: ZIO              (owned input stream)
360/// LexState.buff       → buff: LexBuffer     (owned token-text buffer)
361/// LexState.h          → h: GcRef<LuaTable>  (string-anchor table)
362/// LexState.dyd        → dyd: DynData        (parser dynamic data)
363/// LexState.source     → source: GcRef<LuaString>
364/// LexState.envn       → envn: GcRef<LuaString>
365/// ```
366pub struct LexState {
367    pub current: i32,
368    pub linenumber: i32,
369    pub lastline: i32,
370    pub t: Token,
371    pub lookahead: Token,
372    // TODO(port): Box<FuncState> once FuncState lands in lua-parse (Phase B)
373    pub fs: Option<()>,
374    // PORT NOTE: C held a pointer; Rust owns the ZIO directly per types.tsv.
375    pub z: ZIO,
376    // PORT NOTE: C held a pointer; Rust owns the LexBuffer directly per types.tsv.
377    pub buff: LexBuffer,
378    // TODO(port): GcRef<LuaTable> once LuaTable is defined in Phase B
379    pub h: Option<GcRef<LuaTable>>,
380    /// Per-parse-session anchor for long strings. C-Lua's `ls->h` is a Lua
381    /// table that deduplicates all literal strings within a chunk (both short
382    /// and long), so e.g. `local s1 <const>="..."` and `local s2 <const>="..."`
383    /// with identical 50-byte payloads share one `TString` object — which is
384    /// what makes `string.format("%p", s1) == string.format("%p", s2)` hold.
385    /// Short strings already share identity via the global `interned_lt` pool,
386    /// but long strings (>LUAI_MAXSHORTLEN = 40) are not globally interned and
387    /// need this session-level map. Keyed by the string bytes; populated lazily
388    /// by `new_string`.
389    pub long_str_anchor: std::collections::HashMap<Vec<u8>, GcRef<LuaString>>,
390    // TODO(port): DynData once parser types land in Phase B
391    pub dyd: Option<()>,
392    pub source: GcRef<LuaString>,
393    pub envn: GcRef<LuaString>,
394}
395
396// ── Character-classification helpers ─────────────────────────────────────────
397//
398// These are simplified ASCII implementations for Phase A.
399// TODO(port): import from lua_vm::ctype in Phase B; the full table handles
400// the LUA_UCID (Unicode identifiers) flag and matches the C bit-table exactly.
401//
402// PORT NOTE: the C macros take `int` (not `char`) so they handle EOZ (-1) safely.
403// These Rust fns match that contract: EOZ returns false for all predicates.
404
405#[inline]
406fn is_digit(c: i32) -> bool {
407    c >= b'0' as i32 && c <= b'9' as i32
408}
409
410#[inline]
411fn is_xdigit(c: i32) -> bool {
412    (c >= b'0' as i32 && c <= b'9' as i32)
413        || (c >= b'a' as i32 && c <= b'f' as i32)
414        || (c >= b'A' as i32 && c <= b'F' as i32)
415}
416
417// ALPHABIT: ASCII letters + '_'
418#[inline]
419fn is_lalpha(c: i32) -> bool {
420    (c >= b'a' as i32 && c <= b'z' as i32)
421        || (c >= b'A' as i32 && c <= b'Z' as i32)
422        || c == b'_' as i32
423}
424
425#[inline]
426fn is_lalnum(c: i32) -> bool {
427    is_lalpha(c) || is_digit(c)
428}
429
430#[inline]
431fn is_space(c: i32) -> bool {
432    matches!(c, 9 | 10 | 11 | 12 | 13 | 32) // \t \n \v \f \r space
433}
434
435// PRINTBIT: printable ASCII (graph + space), i.e. 0x20-0x7E
436#[inline]
437fn is_print(c: i32) -> bool {
438    c >= 0x20 && c <= 0x7E
439}
440
441#[inline]
442fn curr_is_newline(ls: &LexState) -> bool {
443    ls.current == b'\n' as i32 || ls.current == b'\r' as i32
444}
445
446// ── Low-level stream helpers ───────────────────────────────────────────────────
447
448/// Advance the lexer by one character.
449///
450/// Corresponds to the `next(ls)` macro.  Named `advance` to avoid collision
451/// with Rust's iterator method.
452#[inline]
453fn advance(ls: &mut LexState) {
454    // macros.tsv: zgetc → z.getc()
455    ls.current = ls.z.getc();
456}
457
458/// Append character `c` to the token buffer, growing it if necessary.
459///
460/// On overflow calls [`lex_error`] which becomes `Err(LuaError::Syntax(...))`.
461///
462/// # C source
463/// ```c
464///
465/// //   Mbuffer *b = ls->buff;
466/// //   if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {
467/// //     size_t newsize;
468/// //     if (luaZ_sizebuffer(b) >= MAX_SIZE/2)
469/// //       lexerror(ls, "lexical element too long", 0);
470/// //     newsize = luaZ_sizebuffer(b) * 2;
471/// //     luaZ_resizebuffer(ls->L, b, newsize);
472/// //   }
473/// //   b->buffer[luaZ_bufflen(b)++] = cast_char(c);
474/// // }
475/// ```
476fn save(ls: &mut LexState, state: &mut LuaState, c: i32) -> Result<(), LuaError> {
477    // macros.tsv: luaZ_bufflen → buf.len(); luaZ_sizebuffer → buf.capacity()
478    if ls.buff.len() + 1 > ls.buff.capacity() {
479        if ls.buff.capacity() >= MAX_SIZE / 2 {
480            return Err(lex_error(ls, b"lexical element too long", 0));
481        }
482        //    luaZ_resizebuffer(ls->L, b, newsize);
483        // macros.tsv: luaZ_resizebuffer → buf.resize(state, size)?
484        let newsize = ls.buff.capacity() * 2;
485        ls.buff.resize(state, newsize)?;
486    }
487    // macros.tsv: cast_char → x as i8  (C char is signed; Lua bytes stored as-is)
488    // PORT NOTE: we store the byte value directly; the i8 cast in C is for the
489    // C char type but the data is read back as unsigned via cast_uchar everywhere.
490    ls.buff.push_byte(c as u8);
491    Ok(())
492}
493
494/// Save the current character into the token buffer, then advance the stream.
495///
496/// Corresponds to the `save_and_next(ls)` macro.  Fallible because `save`
497/// may need to grow the buffer.
498#[inline]
499fn save_and_next(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
500    let c = ls.current;
501    save(ls, state, c)?;
502    advance(ls);
503    Ok(())
504}
505
506// ── Error helpers ─────────────────────────────────────────────────────────────
507
508// l_noret → -> !  but in Rust we return LuaError (callers wrap in Err(...))
509// error_sites.tsv: luaX_lexerror → return Err(LuaError::syntax_at(ls, "msg", token))
510/// Build a syntax error, optionally annotated with the offending token text.
511///
512/// Corresponds to the static `lexerror` function in `llex.c`.  In C this is
513/// `l_noret` (diverges via `luaD_throw`); in Rust it returns a `LuaError`
514/// value that callers wrap in `Err(...)`.
515///
516/// # C source
517/// ```c
518///
519/// //   msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber);
520/// //   if (token)
521/// //     luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token));
522/// //   luaD_throw(ls->L, LUA_ERRSYNTAX);
523/// // }
524/// ```
525pub fn lex_error(ls: &mut LexState, msg: &[u8], token: i32) -> LuaError {
526    const LUA_IDSIZE: usize = 60;
527    let mut buff = [0u8; LUA_IDSIZE];
528    let n = lua_vm::object::chunk_id(&mut buff[..], ls.source.as_bytes());
529    let src_part = &buff[..n];
530
531    let mut full_msg: Vec<u8> = Vec::new();
532    full_msg.extend_from_slice(src_part);
533    let _ = write!(full_msg, ":{}: ", ls.linenumber);
534    full_msg.extend_from_slice(msg);
535
536    if token != 0 {
537        let tok_text = txt_token(ls, token);
538        full_msg.extend_from_slice(b" near ");
539        full_msg.extend_from_slice(&tok_text);
540    }
541
542    LuaError::syntax_raw(&full_msg)
543}
544
545// LUAI_FUNC → pub(crate)
546// error_sites.tsv: luaX_syntaxerror → return Err(LuaError::syntax(format_args!("msg")))
547/// Report a syntax error at the current token.
548///
549/// # C source
550/// ```c
551///
552/// //   lexerror(ls, msg, ls->t.token);
553/// // }
554/// ```
555pub fn syntax_error(ls: &mut LexState, msg: &[u8]) -> LuaError {
556    let token = ls.t.kind;
557    lex_error(ls, msg, token)
558}
559
560/// Produce a human-readable representation of `token` for error messages.
561///
562/// For `TK_NAME`, `TK_STRING`, `TK_FLT`, `TK_INT`: formats the current
563/// token buffer contents as `'<text>'`.  For everything else, delegates to
564/// [`token2str`].
565///
566/// # C source
567/// ```c
568///
569/// //   switch (token) {
570/// //     case TK_NAME: case TK_STRING:
571/// //     case TK_FLT: case TK_INT:
572/// //       save(ls, '\0');
573/// //       return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff));
574/// //     default:
575/// //       return luaX_token2str(ls, token);
576/// //   }
577/// // }
578/// ```
579///
580/// PORT NOTE: C calls `luaO_pushfstring` which pushes the string onto the
581/// Lua stack (stack-anchored temporary).  Rust returns `Vec<u8>` directly
582/// since there is no stack-based string lifecycle for error formatting.
583fn txt_token(ls: &mut LexState, token: i32) -> Vec<u8> {
584    match token {
585        t if t == TK_NAME || t == TK_STRING || t == TK_FLT || t == TK_INT => {
586            let mut v: Vec<u8> = Vec::new();
587            v.push(b'\'');
588            let buff = ls.buff.as_slice();
589            let trimmed = if buff.last() == Some(&0) { &buff[..buff.len() - 1] } else { buff };
590            v.extend_from_slice(trimmed);
591            v.push(b'\'');
592            v
593        }
594        _ => token2str_raw(token),
595    }
596}
597
598// LUAI_FUNC → pub(crate)
599/// Produce a human-readable token description (for error messages and the parser).
600///
601/// Single-byte printable tokens are formatted as `'X'`; non-printable as
602/// `'<\N>'`.  Reserved words and multi-char symbols are formatted as `'kw'`.
603/// Literal tokens (`<name>`, `<string>`, etc.) return the bare label.
604///
605/// # C source
606/// ```c
607///
608/// //   if (token < FIRST_RESERVED) {
609/// //     if (lisprint(token))
610/// //       return luaO_pushfstring(ls->L, "'%c'", token);
611/// //     else
612/// //       return luaO_pushfstring(ls->L, "'<\\%d>'", token);
613/// //   }
614/// //   else {
615/// //     const char *s = luaX_tokens[token - FIRST_RESERVED];
616/// //     if (token < TK_EOS)
617/// //       return luaO_pushfstring(ls->L, "'%s'", s);
618/// //     else
619/// //       return s;
620/// //   }
621/// // }
622/// ```
623///
624/// PORT NOTE: The `LexState` parameter is retained in the signature for API
625/// parity with the C export, but is unused in Rust because we don't push onto
626/// the Lua stack.  The real formatting is in [`token2str_raw`].
627pub fn token2str(_ls: &LexState, token: i32) -> Vec<u8> {
628    token2str_raw(token)
629}
630
631/// Inner implementation of [`token2str`] that does not need `LexState`.
632fn token2str_raw(token: i32) -> Vec<u8> {
633    if token < FIRST_RESERVED {
634        if is_print(token) {
635            vec![b'\'', token as u8, b'\'']
636        } else {
637            // PORT NOTE: uses write! to Vec<u8> to avoid String allocation for Lua data.
638            let mut v: Vec<u8> = Vec::new();
639            v.extend_from_slice(b"'<\\");
640            let _ = write!(&mut v, "{}", token);
641            v.extend_from_slice(b">'");
642            v
643        }
644    } else {
645        let idx = (token - FIRST_RESERVED) as usize;
646        let s = LUAX_TOKENS[idx];
647        if token < TK_EOS {
648            let mut v: Vec<u8> = Vec::with_capacity(s.len() + 2);
649            v.push(b'\'');
650            v.extend_from_slice(s);
651            v.push(b'\'');
652            v
653        } else {
654            s.to_vec()
655        }
656    }
657}
658
659// ── Public init / setup ───────────────────────────────────────────────────────
660
661// LUAI_FUNC → pub(crate)
662/// Initialise the lexer subsystem: intern all reserved words and fix them
663/// in the GC so they are never collected.
664///
665/// Must be called exactly once during VM startup via `luaX_init`.
666///
667/// # C source
668/// ```c
669///
670/// //   int i;
671/// //   TString *e = luaS_newliteral(L, LUA_ENV);  /* create env name */
672/// //   luaC_fix(L, obj2gco(e));  /* never collect this name */
673/// //   for (i=0; i<NUM_RESERVED; i++) {
674/// //     TString *ts = luaS_new(L, luaX_tokens[i]);
675/// //     luaC_fix(L, obj2gco(ts));  /* reserved words are never collected */
676/// //     ts->extra = cast_byte(i+1);  /* reserved word */
677/// //   }
678/// // }
679/// ```
680pub fn init(state: &mut LuaState) -> Result<(), LuaError> {
681    // macros.tsv: luaS_newliteral → state.intern_str(b"...")
682    // TODO(port): call state.intern_str(LUA_ENV) once LuaState has that method (Phase B)
683    let _e = intern_str_stub(state, LUA_ENV)?;
684
685    // macros.tsv: luaC_objbarrier / luaC_fix — GC fix; no-op in Phases A-C
686    // TODO(port): state.gc().fix(e) in Phase D
687
688    for i in 0..NUM_RESERVED {
689        // macros.tsv: luaS_new → state.intern_str(...)
690        // TODO(port): call state.intern_str(LUAX_TOKENS[i]) in Phase B
691        let ts = intern_str_stub(state, LUAX_TOKENS[i])?;
692
693        // TODO(port): state.gc().fix(ts.clone()) in Phase D
694
695        // macros.tsv: cast_byte → x as u8
696        // PORT NOTE: LuaString.extra uses Cell<u8> interior mutability.
697        // TODO(port): ts.set_extra((i + 1) as u8) — needs pub accessor on LuaString
698        let _ = ts; // suppress unused warning until Phase B
699    }
700
701    Ok(())
702}
703
704// LUAI_FUNC → pub(crate)
705/// Initialise `ls` for lexing a new chunk from stream `z`.
706///
707/// # C source
708/// ```c
709///
710/// //                         TString *source, int firstchar) {
711/// //   ls->t.token = 0;
712/// //   ls->L = L;
713/// //   ls->current = firstchar;
714/// //   ls->lookahead.token = TK_EOS;  /* no look-ahead token */
715/// //   ls->z = z;
716/// //   ls->fs = NULL;
717/// //   ls->linenumber = 1;
718/// //   ls->lastline = 1;
719/// //   ls->source = source;
720/// //   ls->envn = luaS_newliteral(L, LUA_ENV);  /* get env name */
721/// //   luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER);
722/// // }
723/// ```
724pub fn set_input(
725    state: &mut LuaState,
726    ls: &mut LexState,
727    z: ZIO,
728    source: GcRef<LuaString>,
729    firstchar: i32,
730) -> Result<(), LuaError> {
731    ls.t = Token::new(0);
732    ls.current = firstchar;
733    ls.lookahead = Token::eos();
734    ls.z = z;
735    ls.fs = None;
736    ls.linenumber = 1;
737    ls.lastline = 1;
738    ls.source = source;
739    // macros.tsv: luaS_newliteral → state.intern_str(b"...")
740    // TODO(port): state.intern_str(LUA_ENV) in Phase B
741    ls.envn = intern_str_stub(state, LUA_ENV)?;
742    // macros.tsv: luaZ_resizebuffer → buf.resize(state, size)?
743    ls.buff.resize(state, LUA_MIN_BUFFER)?;
744    Ok(())
745}
746
747// LUAI_FUNC → pub(crate)
748/// Create (or retrieve) a Lua string and anchor it in the parser's GC-protection
749/// table `ls.h` so it cannot be collected before the end of compilation.
750///
751/// Also internalises long strings so that each unique content has exactly one
752/// copy in memory.  The table `ls.h` is used as a set: the string is both the
753/// key and the value.
754///
755/// # C source
756/// ```c
757///
758/// //   lua_State *L = ls->L;
759/// //   TString *ts = luaS_newlstr(L, str, l);
760/// //   const TValue *o = luaH_getstr(ls->h, ts);
761/// //   if (!ttisnil(o))  /* string already present? */
762/// //     ts = keystrval(nodefromval(o));  /* get saved copy */
763/// //   else {
764/// //     TValue *stv = s2v(L->top.p++);  /* reserve stack space */
765/// //     setsvalue(L, stv, ts);           /* anchor the string */
766/// //     luaH_finishset(L, ls->h, stv, o, stv);  /* t[string] = string */
767/// //     luaC_checkGC(L);
768/// //     L->top.p--;                       /* remove string from stack */
769/// //   }
770/// //   return ts;
771/// // }
772/// ```
773pub(crate) fn new_string(
774    state: &mut LuaState,
775    ls: &mut LexState,
776    bytes: &[u8],
777) -> Result<GcRef<LuaString>, LuaError> {
778    // PORT NOTE: in C, the anchor table ls->h is a Lua table mapping the string
779    // to itself so a second occurrence of the same literal in the chunk returns
780    // the originally-created TString. We use a plain HashMap on LexState
781    // (`long_str_anchor`) for the equivalent dedup — sufficient because Phase
782    // A-C `GcRef<T>` is `Rc<T>` and identity is determined by the `Rc`
783    // allocation. Short strings already share identity via the global pool;
784    // long strings (>LUAI_MAXSHORTLEN) need this session-level map.
785    if let Some(existing) = ls.long_str_anchor.get(bytes) {
786        return Ok(existing.clone());
787    }
788    let ts = intern_str_stub(state, bytes)?;
789    ls.long_str_anchor.insert(bytes.to_vec(), ts.clone());
790    Ok(ts)
791}
792
793// ── Public advance / lookahead ─────────────────────────────────────────────────
794
795// LUAI_FUNC → pub(crate)
796/// Consume the current token; load the next one from the stream.
797///
798/// If a lookahead token was set, it becomes the current token without re-reading
799/// from the stream.
800///
801/// # C source
802/// ```c
803///
804/// //   ls->lastline = ls->linenumber;
805/// //   if (ls->lookahead.token != TK_EOS) {
806/// //     ls->t = ls->lookahead;
807/// //     ls->lookahead.token = TK_EOS;
808/// //   }
809/// //   else
810/// //     ls->t.token = llex(ls, &ls->t.seminfo);
811/// // }
812/// ```
813pub fn next(
814    state: &mut LuaState,
815    ls: &mut LexState,
816) -> Result<(), LuaError> {
817    ls.lastline = ls.linenumber;
818
819    if ls.lookahead.kind != TK_EOS {
820        // Clone to avoid borrow conflict; LuaString inside TokenValue is GcRef (Rc).
821        ls.t = ls.lookahead.clone();
822        ls.lookahead = Token::eos();
823    } else {
824        let mut val = TokenValue::None;
825        let kind = llex(state, ls, &mut val)?;
826        ls.t = Token { kind, value: val };
827    }
828    Ok(())
829}
830
831// LUAI_FUNC → pub(crate)
832/// Peek at the next token without consuming the current one.
833///
834/// The lookahead token is cached in `ls.lookahead` and returned.  Only one
835/// token of lookahead is supported; calling this twice without an intervening
836/// [`next`] is a logic error (asserted in debug builds).
837///
838/// # C source
839/// ```c
840///
841/// //   lua_assert(ls->lookahead.token == TK_EOS);
842/// //   ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);
843/// //   return ls->lookahead.token;
844/// // }
845/// ```
846pub fn lookahead(
847    state: &mut LuaState,
848    ls: &mut LexState,
849) -> Result<i32, LuaError> {
850    // macros.tsv: lua_assert → debug_assert!
851    debug_assert!(
852        ls.lookahead.kind == TK_EOS,
853        "luaX_lookahead: lookahead already set"
854    );
855
856    let mut val = TokenValue::None;
857    let kind = llex(state, ls, &mut val)?;
858    ls.lookahead = Token { kind, value: val };
859
860    Ok(ls.lookahead.kind)
861}
862
863// ── Private lexer helpers ──────────────────────────────────────────────────────
864
865/// If the current character equals `c`, advance and return `true`.
866///
867/// # C source
868/// ```c
869///
870/// //   if (ls->current == c) { next(ls); return 1; }
871/// //   else return 0;
872/// // }
873/// ```
874fn check_next1(ls: &mut LexState, c: i32) -> bool {
875    if ls.current == c {
876        advance(ls);
877        true
878    } else {
879        false
880    }
881}
882
883/// If the current character is either of the two bytes in `set`, save-and-advance
884/// and return `true`.
885///
886/// # C source
887/// ```c
888///
889/// //   lua_assert(set[2] == '\0');
890/// //   if (ls->current == set[0] || ls->current == set[1]) {
891/// //     save_and_next(ls);
892/// //     return 1;
893/// //   }
894/// //   else return 0;
895/// // }
896/// ```
897fn check_next2(
898    ls: &mut LexState,
899    state: &mut LuaState,
900    set: &[u8; 2],
901) -> Result<bool, LuaError> {
902    if ls.current == set[0] as i32 || ls.current == set[1] as i32 {
903        save_and_next(ls, state)?;
904        Ok(true)
905    } else {
906        Ok(false)
907    }
908}
909
910/// Increment the line counter and consume the newline sequence.
911///
912/// Handles `\n`, `\r`, `\n\r`, and `\r\n`.
913///
914/// # C source
915/// ```c
916///
917/// //   int old = ls->current;
918/// //   lua_assert(currIsNewline(ls));
919/// //   next(ls);  /* skip '\n' or '\r' */
920/// //   if (currIsNewline(ls) && ls->current != old)
921/// //     next(ls);  /* skip '\n\r' or '\r\n' */
922/// //   if (++ls->linenumber >= MAX_INT)
923/// //     lexerror(ls, "chunk has too many lines", 0);
924/// // }
925/// ```
926fn inc_line_number(ls: &mut LexState, _state: &mut LuaState) -> Result<(), LuaError> {
927    // macros.tsv: lua_assert → debug_assert!
928    debug_assert!(curr_is_newline(ls), "inc_line_number: not at a newline");
929
930    let old = ls.current;
931    advance(ls);
932
933    if curr_is_newline(ls) && ls.current != old {
934        advance(ls);
935    }
936
937    // macros.tsv: MAX_INT → i32::MAX
938    ls.linenumber += 1;
939    if ls.linenumber >= i32::MAX {
940        return Err(lex_error(ls, b"chunk has too many lines", 0));
941    }
942    Ok(())
943}
944
945/// Scan a numeric literal (integer or float, decimal or hex).
946///
947/// The caller may have already read an initial dot.  Accepts the pattern:
948/// `%d(%x|%.|(Ee[+-]?))*` or `0[Xx](%x|%.|(Pp[+-]?))*`.
949///
950/// Returns `TK_INT` for integers, `TK_FLT` for floats.
951///
952/// # C source
953/// ```c
954///
955/// //   TValue obj;
956/// //   const char *expo = "Ee";
957/// //   int first = ls->current;
958/// //   lua_assert(lisdigit(ls->current));
959/// //   save_and_next(ls);
960/// //   if (first == '0' && check_next2(ls, "xX"))  /* hexadecimal? */
961/// //     expo = "Pp";
962/// //   for (;;) {
963/// //     if (check_next2(ls, expo))
964/// //       check_next2(ls, "-+");
965/// //     else if (lisxdigit(ls->current) || ls->current == '.')
966/// //       save_and_next(ls);
967/// //     else break;
968/// //   }
969/// //   if (lislalpha(ls->current))  /* numeral touching a letter? */
970/// //     save_and_next(ls);         /* force an error */
971/// //   save(ls, '\0');
972/// //   if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0)
973/// //     lexerror(ls, "malformed number", TK_FLT);
974/// //   if (ttisinteger(&obj)) { seminfo->i = ivalue(&obj); return TK_INT; }
975/// //   else { seminfo->r = fltvalue(&obj); return TK_FLT; }
976/// // }
977/// ```
978fn read_numeral(
979    state: &mut LuaState,
980    ls: &mut LexState,
981    seminfo: &mut TokenValue,
982) -> Result<i32, LuaError> {
983    let mut expo: &[u8; 2] = b"Ee";
984
985    let first = ls.current;
986
987    debug_assert!(is_digit(ls.current), "read_numeral: not at a digit");
988
989    save_and_next(ls, state)?;
990
991    if first == b'0' as i32 && check_next2(ls, state, b"xX")? {
992        expo = b"Pp";
993    }
994
995    loop {
996        if check_next2(ls, state, expo)? {
997            check_next2(ls, state, b"-+")?;
998        } else if is_xdigit(ls.current) || ls.current == b'.' as i32 {
999            //      save_and_next(ls);
1000            save_and_next(ls, state)?;
1001        } else {
1002            break;
1003        }
1004    }
1005
1006    if is_lalpha(ls.current) {
1007        save_and_next(ls, state)?;
1008    }
1009
1010    // In Rust, luaO_str2num will receive a byte slice; NUL is not needed.
1011    // We save 0 for parity with C, but our str2num stub ignores it.
1012    save(ls, state, 0)?;
1013
1014    //        lexerror(ls, "malformed number", TK_FLT);
1015    // macros.tsv: luaZ_buffer → buf.as_mut_slice()
1016    let buf = ls.buff.as_slice();
1017    let num_bytes = if buf.last() == Some(&0) { &buf[..buf.len() - 1] } else { buf };
1018    let mut obj = lua_types::LuaValue::Nil;
1019    if lua_vm::object::str2num(num_bytes, &mut obj) == 0 {
1020        return Err(lex_error(ls, b"malformed number", TK_FLT));
1021    }
1022    match obj {
1023        lua_types::LuaValue::Int(i) => {
1024            *seminfo = TokenValue::Int(i);
1025            Ok(TK_INT)
1026        }
1027        lua_types::LuaValue::Float(f) => {
1028            *seminfo = TokenValue::Float(f);
1029            Ok(TK_FLT)
1030        }
1031        _ => unreachable!("str2num returned non-numeric LuaValue"),
1032    }
1033}
1034
1035/// Scan a `[=*[` or `]=*]` sequence; leave the last bracket as current char.
1036///
1037/// Returns:
1038/// - `count + 2` if well-formed (where `count` is the number of `=` signs),
1039/// - `1` if a single bracket with no `=`s and no second bracket,
1040/// - `0` if malformed (e.g. `[==` with no closing bracket).
1041///
1042/// # C source
1043/// ```c
1044///
1045/// //   size_t count = 0;
1046/// //   int s = ls->current;
1047/// //   lua_assert(s == '[' || s == ']');
1048/// //   save_and_next(ls);
1049/// //   while (ls->current == '=') {
1050/// //     save_and_next(ls);
1051/// //     count++;
1052/// //   }
1053/// //   return (ls->current == s) ? count + 2
1054/// //          : (count == 0) ? 1
1055/// //          : 0;
1056/// // }
1057/// ```
1058fn skip_sep(
1059    state: &mut LuaState,
1060    ls: &mut LexState,
1061) -> Result<usize, LuaError> {
1062    let mut count: usize = 0;
1063    let s = ls.current;
1064    debug_assert!(s == b'[' as i32 || s == b']' as i32, "skip_sep: not at bracket");
1065
1066    save_and_next(ls, state)?;
1067
1068    while ls.current == b'=' as i32 {
1069        save_and_next(ls, state)?;
1070        count += 1;
1071    }
1072
1073    if ls.current == s {
1074        Ok(count + 2)
1075    } else if count == 0 {
1076        Ok(1)
1077    } else {
1078        Ok(0)
1079    }
1080}
1081
1082/// Scan a long string or long comment delimited by `[=*[` … `]=*]`.
1083///
1084/// `seminfo` is `Some` when reading a string literal; `None` when skipping a
1085/// long comment.  When `None`, buffer contents are discarded on each newline
1086/// to avoid wasting memory.
1087///
1088/// # C source
1089/// ```c
1090///
1091/// //   int line = ls->linenumber;
1092/// //   save_and_next(ls);  /* skip 2nd '[' */
1093/// //   if (currIsNewline(ls)) inclinenumber(ls);
1094/// //   for (;;) {
1095/// //     switch (ls->current) {
1096/// //       case EOZ: { /* error */
1097/// //         const char *what = (seminfo ? "string" : "comment");
1098/// //         const char *msg = luaO_pushfstring(..., what, line);
1099/// //         lexerror(ls, msg, TK_EOS);
1100/// //         break;
1101/// //       }
1102/// //       case ']': {
1103/// //         if (skip_sep(ls) == sep) {
1104/// //           save_and_next(ls);  /* skip 2nd ']' */
1105/// //           goto endloop;
1106/// //         }
1107/// //         break;
1108/// //       }
1109/// //       case '\n': case '\r': {
1110/// //         save(ls, '\n');
1111/// //         inclinenumber(ls);
1112/// //         if (!seminfo) luaZ_resetbuffer(ls->buff);
1113/// //         break;
1114/// //       }
1115/// //       default: {
1116/// //         if (seminfo) save_and_next(ls);
1117/// //         else next(ls);
1118/// //       }
1119/// //     }
1120/// //   } endloop:
1121/// //   if (seminfo)
1122/// //     seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + sep,
1123/// //                                      luaZ_bufflen(ls->buff) - 2 * sep);
1124/// // }
1125/// ```
1126fn read_long_string(
1127    state: &mut LuaState,
1128    ls: &mut LexState,
1129    seminfo: Option<&mut TokenValue>,
1130    sep: usize,
1131) -> Result<(), LuaError> {
1132    let line = ls.linenumber;
1133
1134    save_and_next(ls, state)?;
1135
1136    if curr_is_newline(ls) {
1137        inc_line_number(ls, state)?;
1138    }
1139
1140    // is_string: whether we are reading a string (true) or a comment (false)
1141    let is_string = seminfo.is_some();
1142
1143    loop {
1144        match ls.current {
1145            c if c == EOZ => {
1146                let what: &[u8] = if is_string { b"string" } else { b"comment" };
1147                // PORT NOTE: build message as Vec<u8> to avoid String allocation.
1148                let mut msg: Vec<u8> = Vec::new();
1149                msg.extend_from_slice(b"unfinished long ");
1150                msg.extend_from_slice(what);
1151                msg.extend_from_slice(b" (starting at line ");
1152                let _ = write!(&mut msg, "{}", line);
1153                msg.push(b')');
1154                return Err(lex_error(ls, &msg, TK_EOS));
1155            }
1156            c if c == b']' as i32 => {
1157                let s = skip_sep(state, ls)?;
1158                if s == sep {
1159                    save_and_next(ls, state)?;
1160                    break;
1161                }
1162                // else: the ']' sequence wasn't the closing delimiter; continue
1163            }
1164            c if c == b'\n' as i32 || c == b'\r' as i32 => {
1165                save(ls, state, b'\n' as i32)?;
1166                inc_line_number(ls, state)?;
1167                // macros.tsv: luaZ_resetbuffer → buf.clear()
1168                if !is_string {
1169                    ls.buff.clear();
1170                }
1171            }
1172            _ => {
1173                if is_string {
1174                    save_and_next(ls, state)?;
1175                } else {
1176                    advance(ls);
1177                }
1178            }
1179        }
1180    }
1181
1182    //      seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + sep,
1183    //                                       luaZ_bufflen(ls->buff) - 2 * sep);
1184    if let Some(out) = seminfo {
1185        // The buffer contains: sep bytes of '[=' + content + sep bytes of '=]'
1186        // We want the content in between.
1187        // PORT NOTE: per PORTING.md §4.3, capture the slice into an owned
1188        // Vec so the immutable borrow of ls.buff is dropped before the
1189        // mutable borrow needed by new_string.
1190        let buf = ls.buff.as_slice();
1191        let content: Vec<u8> = buf[sep..buf.len() - sep].to_vec();
1192        let ts = new_string(state, ls, &content)?;
1193        *out = TokenValue::Str(ts);
1194    }
1195    Ok(())
1196}
1197
1198/// Check `c` is non-zero (truthy); if not, save the current char and raise a
1199/// string-escape error.
1200///
1201/// # C source
1202/// ```c
1203///
1204/// //   if (!c) {
1205/// //     if (ls->current != EOZ)
1206/// //       save_and_next(ls);  /* add current to buffer for error message */
1207/// //     lexerror(ls, msg, TK_STRING);
1208/// //   }
1209/// // }
1210/// ```
1211fn esc_check(
1212    state: &mut LuaState,
1213    ls: &mut LexState,
1214    ok: bool,
1215    msg: &[u8],
1216) -> Result<(), LuaError> {
1217    if !ok {
1218        if ls.current != EOZ {
1219            save_and_next(ls, state)?;
1220        }
1221        return Err(lex_error(ls, msg, TK_STRING));
1222    }
1223    Ok(())
1224}
1225
1226/// Save-and-advance, then verify the new current char is a hex digit; return
1227/// its numeric value (0-15).
1228///
1229/// # C source
1230/// ```c
1231///
1232/// //   save_and_next(ls);
1233/// //   esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected");
1234/// //   return luaO_hexavalue(ls->current);
1235/// // }
1236/// ```
1237fn get_hexa(
1238    state: &mut LuaState,
1239    ls: &mut LexState,
1240) -> Result<u32, LuaError> {
1241    save_and_next(ls, state)?;
1242    esc_check(state, ls, is_xdigit(ls.current), b"hexadecimal digit expected")?;
1243    // TODO(port): call lua_vm::object::hex_value in Phase B
1244    Ok(hex_value_stub(ls.current))
1245}
1246
1247/// Scan a `\xNN` hex escape; return the decoded byte value.
1248///
1249/// # C source
1250/// ```c
1251///
1252/// //   int r = gethexa(ls);
1253/// //   r = (r << 4) + gethexa(ls);
1254/// //   luaZ_buffremove(ls->buff, 2);  /* remove saved chars from buffer */
1255/// //   return r;
1256/// // }
1257/// ```
1258fn read_hex_esc(
1259    state: &mut LuaState,
1260    ls: &mut LexState,
1261) -> Result<u32, LuaError> {
1262    let r = get_hexa(state, ls)?;
1263    let r = (r << 4) + get_hexa(state, ls)?;
1264    // macros.tsv: luaZ_buffremove → buf.truncate_by(i)
1265    ls.buff.truncate_by(2);
1266    Ok(r)
1267}
1268
1269/// Scan a `\u{XXXXXX}` UTF-8 escape; return the Unicode codepoint.
1270///
1271/// # C source
1272/// ```c
1273///
1274/// //   unsigned long r;
1275/// //   int i = 4;  /* chars to remove: '\', 'u', '{', first digit */
1276/// //   save_and_next(ls);  /* skip 'u' */
1277/// //   esccheck(ls, ls->current == '{', "missing '{'");
1278/// //   r = gethexa(ls);  /* must have at least one digit */
1279/// //   while (cast_void(save_and_next(ls)), lisxdigit(ls->current)) {
1280/// //     i++;
1281/// //     esccheck(ls, r <= (0x7FFFFFFFu >> 4), "UTF-8 value too large");
1282/// //     r = (r << 4) + luaO_hexavalue(ls->current);
1283/// //   }
1284/// //   esccheck(ls, ls->current == '}', "missing '}'");
1285/// //   next(ls);  /* skip '}' */
1286/// //   luaZ_buffremove(ls->buff, i);
1287/// //   return r;
1288/// // }
1289/// ```
1290fn read_utf8_esc(
1291    state: &mut LuaState,
1292    ls: &mut LexState,
1293) -> Result<u32, LuaError> {
1294    let mut i: usize = 4;
1295
1296    save_and_next(ls, state)?;
1297
1298    esc_check(state, ls, ls.current == b'{' as i32, b"missing '{'")?;
1299
1300    let mut r = get_hexa(state, ls)?;
1301
1302    // cast_void: discard return value
1303    loop {
1304        save_and_next(ls, state)?;
1305        if !is_xdigit(ls.current) {
1306            break;
1307        }
1308        i += 1;
1309        esc_check(state, ls, r <= (0x7FFF_FFFFu32 >> 4), b"UTF-8 value too large")?;
1310        // TODO(port): lua_vm::object::hex_value in Phase B
1311        r = (r << 4) + hex_value_stub(ls.current);
1312    }
1313
1314    esc_check(state, ls, ls.current == b'}' as i32, b"missing '}'")?;
1315
1316    advance(ls);
1317
1318    ls.buff.truncate_by(i);
1319
1320    Ok(r)
1321}
1322
1323/// Scan `\u{...}` and append the UTF-8 encoding of the codepoint to the buffer.
1324///
1325/// # C source
1326/// ```c
1327///
1328/// //   char buff[UTF8BUFFSZ];
1329/// //   int n = luaO_utf8esc(buff, readutf8esc(ls));
1330/// //   for (; n > 0; n--)
1331/// //     save(ls, buff[UTF8BUFFSZ - n]);
1332/// // }
1333/// ```
1334fn utf8_esc(
1335    state: &mut LuaState,
1336    ls: &mut LexState,
1337) -> Result<(), LuaError> {
1338    let codepoint = read_utf8_esc(state, ls)?;
1339
1340    // macros.tsv: UTF8BUFFSZ → const UTF8_BUF_SZ: usize = 8
1341    // TODO(port): call lua_vm::object::utf8_esc_encode(codepoint) in Phase B.
1342    // For Phase A, encode directly here.
1343    let encoded = utf8_encode_stub(codepoint);
1344
1345    for &b in &encoded {
1346        save(ls, state, b as i32)?;
1347    }
1348    Ok(())
1349}
1350
1351/// Scan a decimal escape `\ddd` (up to 3 digits); return the byte value.
1352///
1353/// # C source
1354/// ```c
1355///
1356/// //   int i;
1357/// //   int r = 0;
1358/// //   for (i = 0; i < 3 && lisdigit(ls->current); i++) {
1359/// //     r = 10*r + ls->current - '0';
1360/// //     save_and_next(ls);
1361/// //   }
1362/// //   esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
1363/// //   luaZ_buffremove(ls->buff, i);  /* remove read digits from buffer */
1364/// //   return r;
1365/// // }
1366/// ```
1367fn read_dec_esc(
1368    state: &mut LuaState,
1369    ls: &mut LexState,
1370) -> Result<u32, LuaError> {
1371    let mut i: usize = 0;
1372    let mut r: u32 = 0;
1373
1374    while i < 3 && is_digit(ls.current) {
1375        r = 10 * r + (ls.current as u32 - b'0' as u32);
1376        save_and_next(ls, state)?;
1377        i += 1;
1378    }
1379
1380    // UCHAR_MAX = 255 = u8::MAX
1381    esc_check(state, ls, r <= u8::MAX as u32, b"decimal escape too large")?;
1382
1383    ls.buff.truncate_by(i);
1384    Ok(r)
1385}
1386
1387/// Scan a short (single/double-quoted) string literal.
1388///
1389/// The C function uses `goto read_save / only_save / no_save` for escape
1390/// handling.  In Rust this is replaced by the `EscapeResult` enum.
1391///
1392/// # C source (see llex.c lines 382-442 for full listing)
1393fn read_string(
1394    state: &mut LuaState,
1395    ls: &mut LexState,
1396    del: i32,
1397    seminfo: &mut TokenValue,
1398) -> Result<(), LuaError> {
1399    // Encoding for what the escape sequence handler needs to do after decoding.
1400    //
1401    // read_save:  advance(ls), remove '\' from buffer, save decoded byte
1402    // only_save:  remove '\' from buffer, save decoded byte (no advance)
1403    // no_save:    nothing (just break from the escape case)
1404    enum EscapeResult {
1405        ReadSave(i32),
1406        OnlySave(i32),
1407        NoSave,
1408    }
1409
1410    save_and_next(ls, state)?;
1411
1412    while ls.current != del {
1413        match ls.current {
1414            c if c == EOZ => {
1415                return Err(lex_error(ls, b"unfinished string", TK_EOS));
1416            }
1417            c if c == b'\n' as i32 || c == b'\r' as i32 => {
1418                return Err(lex_error(ls, b"unfinished string", TK_STRING));
1419            }
1420            c if c == b'\\' as i32 => {
1421                save_and_next(ls, state)?;
1422
1423                // Inner switch on the escape character
1424                let esc = match ls.current {
1425                    c if c == b'a' as i32 => EscapeResult::ReadSave(b'\x07' as i32),
1426                    c if c == b'b' as i32 => EscapeResult::ReadSave(b'\x08' as i32),
1427                    c if c == b'f' as i32 => EscapeResult::ReadSave(b'\x0C' as i32),
1428                    c if c == b'n' as i32 => EscapeResult::ReadSave(b'\n' as i32),
1429                    c if c == b'r' as i32 => EscapeResult::ReadSave(b'\r' as i32),
1430                    c if c == b't' as i32 => EscapeResult::ReadSave(b'\t' as i32),
1431                    c if c == b'v' as i32 => EscapeResult::ReadSave(b'\x0B' as i32),
1432                    c if c == b'x' as i32 => {
1433                        let decoded = read_hex_esc(state, ls)?;
1434                        EscapeResult::ReadSave(decoded as i32)
1435                    }
1436                    c if c == b'u' as i32 => {
1437                        utf8_esc(state, ls)?;
1438                        EscapeResult::NoSave
1439                    }
1440                    c if c == b'\n' as i32 || c == b'\r' as i32 => {
1441                        inc_line_number(ls, state)?;
1442                        EscapeResult::OnlySave(b'\n' as i32)
1443                    }
1444                    c if c == b'\\' as i32 || c == b'"' as i32 || c == b'\'' as i32 => {
1445                        EscapeResult::ReadSave(c)
1446                    }
1447                    c if c == EOZ => EscapeResult::NoSave,
1448                    c if c == b'z' as i32 => {
1449                        ls.buff.truncate_by(1);
1450                        advance(ls);
1451                        while is_space(ls.current) {
1452                            if curr_is_newline(ls) {
1453                                inc_line_number(ls, state)?;
1454                            } else {
1455                                advance(ls);
1456                            }
1457                        }
1458                        EscapeResult::NoSave
1459                    }
1460                    _ => {
1461                        esc_check(
1462                            state, ls,
1463                            is_digit(ls.current),
1464                            b"invalid escape sequence",
1465                        )?;
1466                        let decoded = read_dec_esc(state, ls)?;
1467                        EscapeResult::OnlySave(decoded as i32)
1468                    }
1469                };
1470
1471                // Dispatch the C goto targets as match arms.
1472                match esc {
1473                    EscapeResult::ReadSave(c) => {
1474                        advance(ls);
1475                        ls.buff.truncate_by(1);
1476                        save(ls, state, c)?;
1477                    }
1478                    EscapeResult::OnlySave(c) => {
1479                        ls.buff.truncate_by(1);
1480                        save(ls, state, c)?;
1481                    }
1482                    EscapeResult::NoSave => {}
1483                }
1484            }
1485            _ => {
1486                save_and_next(ls, state)?;
1487            }
1488        }
1489    }
1490
1491    save_and_next(ls, state)?;
1492
1493    //                                     luaZ_bufflen(ls->buff) - 2);
1494    // Buffer contains: delimiter + content + delimiter; strip both delimiters.
1495    // PORT NOTE: capture into owned Vec to drop the borrow before new_string.
1496    let buf = ls.buff.as_slice();
1497    let content: Vec<u8> = if buf.len() >= 2 {
1498        buf[1..buf.len() - 1].to_vec()
1499    } else {
1500        Vec::new()
1501    };
1502    let ts = new_string(state, ls, &content)?;
1503    *seminfo = TokenValue::Str(ts);
1504    Ok(())
1505}
1506
1507/// Core lexer dispatch: consume and return the next raw token kind.
1508///
1509/// This is the heart of the lexer: a large `for`-`switch` loop that classifies
1510/// the current character and dispatches to the appropriate scanner.
1511///
1512/// # C source (see llex.c lines 445-562 for full listing)
1513fn llex(
1514    state: &mut LuaState,
1515    ls: &mut LexState,
1516    seminfo: &mut TokenValue,
1517) -> Result<i32, LuaError> {
1518    // macros.tsv: luaZ_resetbuffer → buf.clear()
1519    ls.buff.clear();
1520
1521    loop {
1522        match ls.current {
1523            c if c == b'\n' as i32 || c == b'\r' as i32 => {
1524                inc_line_number(ls, state)?;
1525                // PORT NOTE: skipcomment-equivalent. luaL_loadfile in C-Lua
1526                // strips a leading '#' line (Unix shebang). Our test harness
1527                // prepends a global-setup preamble to every official test, so
1528                // the script's '#' line is not at byte zero. Apply the same
1529                // rule at any token-scan line start: treat a line whose first
1530                // character is '#' as a single-line comment. This sits in
1531                // llex's dispatch loop (not inc_line_number) so it does not
1532                // affect newlines inside long-bracket strings.
1533                if ls.current == b'#' as i32 {
1534                    while !curr_is_newline(ls) && ls.current != EOZ {
1535                        advance(ls);
1536                    }
1537                }
1538            }
1539
1540            c if c == b' ' as i32
1541                || c == b'\x0C' as i32
1542                || c == b'\t' as i32
1543                || c == b'\x0B' as i32 =>
1544            {
1545                advance(ls);
1546            }
1547
1548            c if c == b'-' as i32 => {
1549                advance(ls);
1550                if ls.current != b'-' as i32 {
1551                    return Ok(b'-' as i32);
1552                }
1553                advance(ls);
1554
1555                if ls.current == b'[' as i32 {
1556                    let sep = skip_sep(state, ls)?;
1557                    ls.buff.clear();
1558                    if sep >= 2 {
1559                        read_long_string(state, ls, None, sep)?;
1560                        ls.buff.clear();
1561                        continue;
1562                    }
1563                }
1564                while !curr_is_newline(ls) && ls.current != EOZ {
1565                    advance(ls);
1566                }
1567                // loop continues (no token emitted for comments)
1568            }
1569
1570            c if c == b'[' as i32 => {
1571                let sep = skip_sep(state, ls)?;
1572                if sep >= 2 {
1573                    read_long_string(state, ls, Some(seminfo), sep)?;
1574                    return Ok(TK_STRING);
1575                } else if sep == 0 {
1576                    return Err(lex_error(ls, b"invalid long string delimiter", TK_STRING));
1577                }
1578                // sep == 1: plain '[', no long string
1579                return Ok(b'[' as i32);
1580            }
1581
1582            c if c == b'=' as i32 => {
1583                advance(ls);
1584                if check_next1(ls, b'=' as i32) {
1585                    return Ok(TK_EQ);
1586                }
1587                return Ok(b'=' as i32);
1588            }
1589
1590            c if c == b'<' as i32 => {
1591                advance(ls);
1592                if check_next1(ls, b'=' as i32) {
1593                    return Ok(TK_LE);
1594                } else if check_next1(ls, b'<' as i32) {
1595                    return Ok(TK_SHL);
1596                }
1597                return Ok(b'<' as i32);
1598            }
1599
1600            c if c == b'>' as i32 => {
1601                advance(ls);
1602                if check_next1(ls, b'=' as i32) {
1603                    return Ok(TK_GE);
1604                } else if check_next1(ls, b'>' as i32) {
1605                    return Ok(TK_SHR);
1606                }
1607                return Ok(b'>' as i32);
1608            }
1609
1610            c if c == b'/' as i32 => {
1611                advance(ls);
1612                if check_next1(ls, b'/' as i32) {
1613                    return Ok(TK_IDIV);
1614                }
1615                return Ok(b'/' as i32);
1616            }
1617
1618            c if c == b'~' as i32 => {
1619                advance(ls);
1620                if check_next1(ls, b'=' as i32) {
1621                    return Ok(TK_NE);
1622                }
1623                return Ok(b'~' as i32);
1624            }
1625
1626            c if c == b':' as i32 => {
1627                advance(ls);
1628                if check_next1(ls, b':' as i32) {
1629                    return Ok(TK_DBCOLON);
1630                }
1631                return Ok(b':' as i32);
1632            }
1633
1634            c if c == b'"' as i32 || c == b'\'' as i32 => {
1635                let del = ls.current;
1636                read_string(state, ls, del, seminfo)?;
1637                return Ok(TK_STRING);
1638            }
1639
1640            c if c == b'.' as i32 => {
1641                save_and_next(ls, state)?;
1642                if check_next1(ls, b'.' as i32) {
1643                    if check_next1(ls, b'.' as i32) {
1644                        return Ok(TK_DOTS);
1645                    }
1646                    return Ok(TK_CONCAT);
1647                } else if !is_digit(ls.current) {
1648                    return Ok(b'.' as i32);
1649                } else {
1650                    return read_numeral(state, ls, seminfo);
1651                }
1652            }
1653
1654            c if is_digit(c) => {
1655                return read_numeral(state, ls, seminfo);
1656            }
1657
1658            c if c == EOZ => {
1659                return Ok(TK_EOS);
1660            }
1661
1662            c => {
1663                if is_lalpha(c) {
1664                    loop {
1665                        save_and_next(ls, state)?;
1666                        if !is_lalnum(ls.current) {
1667                            break;
1668                        }
1669                    }
1670
1671                    // PORT NOTE: copy buffer bytes to drop borrow before new_string.
1672                    let content: Vec<u8> = ls.buff.as_slice().to_vec();
1673                    let ts = new_string(state, ls, &content)?;
1674
1675                    // PORT NOTE: canonical `lua_types::LuaString` lacks the `extra`
1676                    // byte that C-Lua uses to mark reserved words. Recover the
1677                    // keyword index directly from the interned bytes via the
1678                    // `LUAX_TOKENS` table; the first `NUM_RESERVED` entries are
1679                    // the keywords in declaration order, so token id =
1680                    // `FIRST_RESERVED + index`.
1681                    let reserved_token: Option<i32> = LUAX_TOKENS[..NUM_RESERVED]
1682                        .iter()
1683                        .position(|kw| *kw == content.as_slice())
1684                        .map(|i| FIRST_RESERVED + i as i32);
1685                    *seminfo = TokenValue::Str(ts);
1686
1687                    if let Some(tk) = reserved_token {
1688                        return Ok(tk);
1689                    }
1690
1691                    // Lua 5.5: with the upstream-default `LUA_COMPAT_GLOBAL`, the
1692                    // `global` declaration word is NOT reserved — `global` stays a
1693                    // valid identifier, and the parser recognizes the declaration
1694                    // statement contextually (see `globalstat` in lua-parse). So
1695                    // `global` always lexes as a plain name, on every version.
1696                    return Ok(TK_NAME);
1697                } else {
1698                    let tok = ls.current;
1699                    advance(ls);
1700                    return Ok(tok);
1701                }
1702            }
1703        }
1704    }
1705}
1706
1707// ── Phase A stubs for cross-crate helpers ──────────────────────────────────────
1708//
1709// The functions below stand in for cross-crate calls that cannot resolve in
1710// Phase A.  They will be replaced by proper imports in Phase B.
1711
1712// TODO(port): replace with state.intern_str(bytes) once LuaState gains that
1713// method (from lua_vm::string::new_lstr wired in Phase B).
1714// TODO_ARCH(phase-b-reconcile): canonical LuaString is constructed via
1715// from_bytes; once LuaState::intern_str is wired, route through there instead.
1716fn intern_str_stub(
1717    state: &mut LuaState,
1718    bytes: &[u8],
1719) -> Result<GcRef<LuaString>, LuaError> {
1720    state.intern_str(bytes)
1721}
1722
1723// TODO(port): replace with lua_vm::object::hex_value(c) in Phase B.
1724fn hex_value_stub(c: i32) -> u32 {
1725    match c {
1726        c if c >= b'0' as i32 && c <= b'9' as i32 => (c - b'0' as i32) as u32,
1727        c if c >= b'a' as i32 && c <= b'f' as i32 => (c - b'a' as i32 + 10) as u32,
1728        c if c >= b'A' as i32 && c <= b'F' as i32 => (c - b'A' as i32 + 10) as u32,
1729        _ => 0,
1730    }
1731}
1732
1733// TODO(port): replace with lua_vm::object::utf8_esc_encode(codepoint) in Phase B.
1734/// Encode a Unicode codepoint as a Lua-extended UTF-8 byte sequence (1 to 6 bytes).
1735///
1736/// Faithful port of `luaO_utf8esc` from lobject.c.  Lua permits codepoints up
1737/// to `0x7FFFFFFF` (5- and 6-byte sequences are non-strict UTF-8 but accepted
1738/// by `\u{...}` escapes per literals.lua test cases).
1739fn utf8_encode_stub(codepoint: u32) -> Vec<u8> {
1740    debug_assert!(codepoint <= 0x7FFF_FFFF);
1741    if codepoint < 0x80 {
1742        return vec![codepoint as u8];
1743    }
1744    let mut x = codepoint;
1745    let mut mfb: u32 = 0x3f;
1746    let mut buf: Vec<u8> = Vec::with_capacity(8);
1747    loop {
1748        buf.push(0x80 | ((x & 0x3f) as u8));
1749        x >>= 6;
1750        mfb >>= 1;
1751        if x <= mfb {
1752            break;
1753        }
1754    }
1755    buf.push(((!mfb << 1) | x) as u8);
1756    buf.reverse();
1757    buf
1758}
1759
1760// ──────────────────────────────────────────────────────────────────────────────
1761// PORT STATUS
1762//   source:        src/llex.c  (581 lines, 24 functions)
1763//                  src/llex.h  (91 lines; merged)
1764//   target_crate:  lua-lex
1765//   confidence:    medium
1766//   todos:         18
1767//   port_notes:    12
1768//   unsafe_blocks: 0   (must be 0 outside explicit unsafe-budget crates)
1769//   notes:         Logic is faithful to the C.  The main structural differences:
1770//                  (1) LexState.L removed — state threaded via fn params;
1771//                  (2) save/save_and_next/inclinenumber/helpers are all fallible
1772//                  (Result<_, LuaError>) because lexerror is no longer noreturn;
1773//                  (3) goto read_save/only_save/no_save in read_string replaced
1774//                  by EscapeResult enum; (4) Cross-crate calls (intern_str,
1775//                  luaH_getstr/finishset, luaG_addinfo, luaO_str2num,
1776//                  luaO_hexavalue, luaO_utf8esc, luaC_fix, luaC_checkGC) are
1777//                  stubbed with TODO; (5) LuaError, LuaString, ZIO, LexBuffer,
1778//                  LuaState defined as local stubs — Phase B replaces with real
1779//                  imports once the crate graph is wired.  Key Phase B tasks:
1780//                  wire import paths; move LuaString.extra accessor to pub;
1781//                  implement luaX_newstring anchor-table logic.  Numeric
1782//                  literal parsing now delegates to lua_vm::object::str2num
1783//                  (handles hex integers with wrap-around and hex floats).
1784// ──────────────────────────────────────────────────────────────────────────────