Skip to main content

lua_lex/
lib.rs

1//! Lexical analyzer for omniLua.
2//!
3//! Scans a [`ZIO`] byte stream into [`Token`] values one character at a time,
4//! with one-token lookahead. One core lexes Lua 5.1 through 5.5; the lexical
5//! differences between versions (which operators exist, escape handling,
6//! reserved words, error wording) are gated on the active [`LuaVersion`] and are
7//! the behavioural invariant this crate guarantees.
8//!
9//! This file was originally a line-by-line port of `llex.c` but has been
10//! idiomatized and the C correspondence removed (see `GRADUATED.md`); behaviour
11//! is held by bytecode parity plus the lexical-error / line-number oracle, not
12//! by matching the C source.
13//!
14//! [`LuaVersion`]: lua_types::LuaVersion
15
16use std::io::Write as IoWrite;
17
18use lua_types::gc::GcRef;
19
20pub use lua_types::LuaError;
21pub use lua_types::LuaString;
22pub use lua_vm::state::LuaState;
23pub use lua_vm::table::LuaTable;
24pub use lua_vm::zio::ZIO;
25
26/// Growable token-text buffer for the lexer.
27///
28/// TODO: ZIO/LexBuffer will move to lua_vm::zio (separate refactor).
29pub struct LexBuffer {
30    buffer: Vec<u8>,
31}
32
33impl LexBuffer {
34    pub fn new() -> Self {
35        LexBuffer { buffer: Vec::new() }
36    }
37
38    pub fn len(&self) -> usize {
39        self.buffer.len()
40    }
41
42    pub fn capacity(&self) -> usize {
43        self.buffer.capacity()
44    }
45
46    pub fn as_slice(&self) -> &[u8] {
47        &self.buffer
48    }
49
50    pub fn clear(&mut self) {
51        self.buffer.clear();
52    }
53
54    pub fn truncate_by(&mut self, i: usize) {
55        let new_len = self.buffer.len().saturating_sub(i);
56        self.buffer.truncate(new_len);
57    }
58
59    /// Ensure the buffer can hold `size` bytes by adjusting allocated capacity,
60    /// never the live byte count (otherwise `push_byte` would write past the live
61    /// content and leave embedded zero padding inside the token text).
62    pub fn resize(&mut self, _state: &mut LuaState, size: usize) -> Result<(), LuaError> {
63        if size < self.buffer.len() {
64            self.buffer.truncate(size);
65        }
66        if size > self.buffer.capacity() {
67            let extra = size - self.buffer.capacity();
68            self.buffer.reserve_exact(extra);
69        }
70        Ok(())
71    }
72
73    /// Append one byte to the live contents.  Panics if capacity exceeded
74    /// (callers must pre-check via `save`).
75    fn push_byte(&mut self, c: u8) {
76        self.buffer.push(c);
77    }
78
79    /// The token text with `n` bytes removed from each end, copied to an owned
80    /// `Vec`.
81    ///
82    /// This is the delimiter-stripping extraction used after scanning a quoted
83    /// or long-bracket string: the buffer holds `<open-delim><content><close-delim>`
84    /// where each delimiter is `n` bytes (`n = 1` for `"`/`'`, `n = sep` for
85    /// `[=*[`). An empty `Vec` is returned when the buffer is shorter than the
86    /// two delimiters (an empty string literal).
87    ///
88    /// The copy is an ownership requirement, not a leftover C idiom: the caller
89    /// next passes these bytes to `new_string`, which needs `&mut LexState`, so
90    /// the borrow of the buffer must end first.
91    fn trim_ends(&self, n: usize) -> Vec<u8> {
92        match self.buffer.len().checked_sub(2 * n) {
93            Some(_) => self.buffer[n..self.buffer.len() - n].to_vec(),
94            None => Vec::new(),
95        }
96    }
97
98    /// The whole token text, copied to an owned `Vec`.
99    ///
100    /// Used for identifiers/keywords, where the entire buffer is the token. As
101    /// with [`trim_ends`](Self::trim_ends) the copy releases the buffer borrow
102    /// before `new_string` takes `&mut LexState`.
103    fn to_owned_text(&self) -> Vec<u8> {
104        self.buffer.clone()
105    }
106
107    /// The live contents with a single trailing NUL removed, if present.
108    ///
109    /// Numeral scanning and error-message formatting append a `\0` to mirror
110    /// C's NUL-terminated buffer convention before reading the text back; this
111    /// drops that one sentinel byte without copying. A buffer that does not end
112    /// in NUL is returned whole.
113    fn without_trailing_nul(&self) -> &[u8] {
114        match self.buffer.last() {
115            Some(&0) => &self.buffer[..self.buffer.len() - 1],
116            _ => &self.buffer,
117        }
118    }
119}
120
121impl Default for LexBuffer {
122    fn default() -> Self {
123        Self::new()
124    }
125}
126
127// ── Constants ─────────────────────────────────────────────────────────────────
128
129/// First token kind value that is not a single-byte character.
130/// Single-byte tokens are represented by their ASCII value (0-255).
131pub const FIRST_RESERVED: i32 = 257;
132
133/// Name of the global environment upvalue.
134pub const LUA_ENV: &[u8] = b"_ENV";
135
136/// Number of reserved words (keywords).
137pub const NUM_RESERVED: usize = (TK_WHILE - FIRST_RESERVED + 1) as usize;
138
139/// End-of-stream sentinel returned by ZIO::getc.
140pub const EOZ: i32 = -1;
141
142const MAX_SIZE: usize = if std::mem::size_of::<usize>() < std::mem::size_of::<i64>() {
143    usize::MAX
144} else {
145    i64::MAX as usize
146};
147
148const LUA_MIN_BUFFER: usize = 32;
149
150// ── Token kind constants (ORDER RESERVED) ─────────────────────────────────────
151
152/// `and`
153pub const TK_AND: i32 = 257;
154/// `break`
155pub const TK_BREAK: i32 = 258;
156/// `do`
157pub const TK_DO: i32 = 259;
158/// `else`
159pub const TK_ELSE: i32 = 260;
160/// `elseif`
161pub const TK_ELSEIF: i32 = 261;
162/// `end`
163pub const TK_END: i32 = 262;
164/// `false`
165pub const TK_FALSE: i32 = 263;
166/// `for`
167pub const TK_FOR: i32 = 264;
168/// `function`
169pub const TK_FUNCTION: i32 = 265;
170/// `goto`
171pub const TK_GOTO: i32 = 266;
172/// `if`
173pub const TK_IF: i32 = 267;
174/// `in`
175pub const TK_IN: i32 = 268;
176/// `local`
177pub const TK_LOCAL: i32 = 269;
178/// `nil`
179pub const TK_NIL: i32 = 270;
180/// `not`
181pub const TK_NOT: i32 = 271;
182/// `or`
183pub const TK_OR: i32 = 272;
184/// `repeat`
185pub const TK_REPEAT: i32 = 273;
186/// `return`
187pub const TK_RETURN: i32 = 274;
188/// `then`
189pub const TK_THEN: i32 = 275;
190/// `true`
191pub const TK_TRUE: i32 = 276;
192/// `until`
193pub const TK_UNTIL: i32 = 277;
194/// `while`  (last keyword; NUM_RESERVED = TK_WHILE - FIRST_RESERVED + 1 = 22)
195pub const TK_WHILE: i32 = 278;
196/// `//`  (floor division)
197pub const TK_IDIV: i32 = 279;
198/// `..`  (concatenation)
199pub const TK_CONCAT: i32 = 280;
200/// `...` (vararg)
201pub const TK_DOTS: i32 = 281;
202/// `==`
203pub const TK_EQ: i32 = 282;
204/// `>=`
205pub const TK_GE: i32 = 283;
206/// `<=`
207pub const TK_LE: i32 = 284;
208/// `~=`
209pub const TK_NE: i32 = 285;
210/// `<<`
211pub const TK_SHL: i32 = 286;
212/// `>>`
213pub const TK_SHR: i32 = 287;
214/// `::`
215pub const TK_DBCOLON: i32 = 288;
216/// `<eof>`
217pub const TK_EOS: i32 = 289;
218/// `<number>`  (float literal)
219pub const TK_FLT: i32 = 290;
220/// `<integer>` (integer literal)
221pub const TK_INT: i32 = 291;
222/// `<name>`    (identifier)
223pub const TK_NAME: i32 = 292;
224/// `<string>`  (string literal)
225pub const TK_STRING: i32 = 293;
226
227// Lua 5.5 `global`: with the upstream-default LUA_COMPAT_GLOBAL it is NOT a
228// reserved word — it always lexes as TK_NAME (so it stays a valid identifier on
229// every version), and the parser recognizes the `global` declaration statement
230// contextually (see `globalstat`/`statement` in lua-parse). There is therefore
231// no dedicated token id.
232
233// ORDER RESERVED — index 0 = TK_AND - FIRST_RESERVED, etc.
234/// Display strings for tokens, indexed by `token - FIRST_RESERVED`.
235pub static LUAX_TOKENS: &[&[u8]] = &[
236    // keywords (indices 0-21)
237    b"and",
238    b"break",
239    b"do",
240    b"else",
241    b"elseif",
242    b"end",
243    b"false",
244    b"for",
245    b"function",
246    b"goto",
247    b"if",
248    b"in",
249    b"local",
250    b"nil",
251    b"not",
252    b"or",
253    b"repeat",
254    b"return",
255    b"then",
256    b"true",
257    b"until",
258    b"while",
259    // other terminal symbols (indices 22-35)
260    b"//",
261    b"..",
262    b"...",
263    b"==",
264    b">=",
265    b"<=",
266    b"~=",
267    b"<<",
268    b">>",
269    b"::",
270    b"<eof>",
271    b"<number>",
272    b"<integer>",
273    b"<name>",
274    b"<string>",
275];
276
277// ── TokenValue ──────────────────────────────────────────────────────────────────
278
279/// Semantic payload carried by a token.
280#[derive(Clone)]
281pub enum TokenValue {
282    /// No semantic value (default; used for single-byte and most multi-char tokens).
283    None,
284    /// Float literal payload.
285    Float(f64),
286    /// Integer literal payload.
287    Int(i64),
288    /// String/name payload.
289    Str(GcRef<LuaString>),
290}
291
292// ── Token ─────────────────────────────────────────────────────────────────────
293
294/// A single lexed token with its semantic payload.
295///
296/// `kind` is an `i32` whose value is either an ASCII byte code (for single-byte
297/// tokens like `+`, `-`, `[`) or one of the `TK_*` constants (for reserved
298/// words, multi-char symbols, and literals).
299///
300/// The `i32` kind is the **cross-crate boundary**: `lua-parse` and the error
301/// formatters consume these `TK_*` codes directly, so it stays an integer by
302/// design rather than a typed enum. The lexer's own scan loop does its
303/// dispatch on the internal [`Peek`] enum instead — the typed-match lives
304/// inside the lexer, the integer codes cross the boundary.
305#[derive(Clone)]
306pub struct Token {
307    pub kind: i32,
308    pub value: TokenValue,
309}
310
311impl Token {
312    /// Construct a token with no semantic value.
313    pub fn new(kind: i32) -> Self {
314        Token {
315            kind,
316            value: TokenValue::None,
317        }
318    }
319
320    /// The end-of-stream sentinel token.
321    pub fn eos() -> Self {
322        Token::new(TK_EOS)
323    }
324}
325
326// ── LexState ──────────────────────────────────────────────────────────────────
327
328/// Per-chunk lexer (and shared parser) state.
329///
330/// Owns the input stream, token buffer, and current/lookahead tokens.
331pub struct LexState {
332    pub current: i32,
333    pub linenumber: i32,
334    pub lastline: i32,
335    pub t: Token,
336    pub lookahead: Token,
337    pub fs: Option<()>,
338    pub z: ZIO,
339    pub buff: LexBuffer,
340    pub h: Option<GcRef<LuaTable>>,
341    /// Per-parse-session anchor for long strings, deduplicating all literal
342    /// strings within a chunk so e.g. `local s1 <const>="..."` and
343    /// `local s2 <const>="..."` with identical 50-byte payloads share one
344    /// `LuaString` object — which is what makes
345    /// `string.format("%p", s1) == string.format("%p", s2)` hold. Short strings
346    /// already share identity via the global `interned_lt` pool, but long
347    /// strings (>40 bytes) are not globally interned and need this session-level
348    /// map. Keyed by the string bytes; populated lazily by `new_string`.
349    pub long_str_anchor: std::collections::HashMap<Vec<u8>, GcRef<LuaString>>,
350    pub dyd: Option<()>,
351    pub source: GcRef<LuaString>,
352    pub envn: GcRef<LuaString>,
353    /// The active Lua version, snapshotted at lexer setup from
354    /// `state.global().lua_version` (fixed for the lifetime of a parse). The
355    /// error formatters (`lex_error`/`token2str`) take only `&LexState`, so they
356    /// read the version here rather than threading a `&LuaState` through every
357    /// syntax-error callsite. Lua 5.1 quotes the special multi-char token labels
358    /// (`<eof>`, `<name>`, …) in error messages where 5.2+ leaves them bare.
359    pub version: lua_types::LuaVersion,
360}
361
362// ── Character-classification helpers ─────────────────────────────────────────
363//
364// These take `i32` (a byte, or EOZ = -1) so EOZ returns false for all
365// predicates.
366
367#[inline]
368fn is_digit(c: i32) -> bool {
369    c >= b'0' as i32 && c <= b'9' as i32
370}
371
372#[inline]
373fn is_xdigit(c: i32) -> bool {
374    (c >= b'0' as i32 && c <= b'9' as i32)
375        || (c >= b'a' as i32 && c <= b'f' as i32)
376        || (c >= b'A' as i32 && c <= b'F' as i32)
377}
378
379// ASCII letters + '_'
380#[inline]
381fn is_lalpha(c: i32) -> bool {
382    (c >= b'a' as i32 && c <= b'z' as i32)
383        || (c >= b'A' as i32 && c <= b'Z' as i32)
384        || c == b'_' as i32
385}
386
387#[inline]
388fn is_lalnum(c: i32) -> bool {
389    is_lalpha(c) || is_digit(c)
390}
391
392#[inline]
393fn is_space(c: i32) -> bool {
394    matches!(c, 9 | 10 | 11 | 12 | 13 | 32) // \t \n \v \f \r space
395}
396
397// printable ASCII (graph + space), i.e. 0x20-0x7E
398#[inline]
399fn is_print(c: i32) -> bool {
400    c >= 0x20 && c <= 0x7E
401}
402
403/// C-locale `iscntrl`: the control characters are 0x00-0x1F and 0x7F.
404///
405/// Used only by Lua 5.1's `luaX_token2str`, which renders a control byte as
406/// `char(%d)` but any other non-printable byte (e.g. 0x80-0xFF) as the raw byte
407/// itself.
408#[inline]
409fn is_cntrl(c: i32) -> bool {
410    (0x00..=0x1F).contains(&c) || c == 0x7F
411}
412
413#[inline]
414fn curr_is_newline(ls: &LexState) -> bool {
415    ls.current == b'\n' as i32 || ls.current == b'\r' as i32
416}
417
418// ── Low-level stream helpers ───────────────────────────────────────────────────
419
420/// Advance the lexer by one character.
421///
422/// Named `advance` to avoid collision with Rust's iterator method. Fallible:
423/// the underlying `ZIO` may invoke a Lua `load` reader, which can error
424/// mid-stream. When the reader returns no more bytes, `ls.current` becomes
425/// [`EOZ`] and parsing ends normally.
426#[inline]
427fn advance(state: &mut LuaState, ls: &mut LexState) -> Result<(), LuaError> {
428    ls.current = ls.z.getc(state)?;
429    Ok(())
430}
431
432/// Append character `c` to the token buffer, growing it if necessary.
433///
434/// On overflow calls [`lex_error`] which becomes `Err(LuaError::Syntax(...))`.
435fn save(ls: &mut LexState, state: &mut LuaState, c: i32) -> Result<(), LuaError> {
436    if ls.buff.len() + 1 > ls.buff.capacity() {
437        if ls.buff.capacity() >= MAX_SIZE / 2 {
438            return Err(lex_error(ls, b"lexical element too long", 0));
439        }
440        let newsize = ls.buff.capacity() * 2;
441        ls.buff.resize(state, newsize)?;
442    }
443    ls.buff.push_byte(c as u8);
444    Ok(())
445}
446
447/// Save the current character into the token buffer, then advance the stream.
448///
449/// Fallible because `save` may need to grow the buffer.
450#[inline]
451fn save_and_next(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
452    let c = ls.current;
453    save(ls, state, c)?;
454    advance(state, ls)?;
455    Ok(())
456}
457
458// ── Error helpers ─────────────────────────────────────────────────────────────
459
460/// Build a syntax error, optionally annotated with the offending token text.
461///
462/// Returns the constructed [`LuaError`] by value rather than diverging. This is
463/// the lexer's error-construction boundary: the lexer's own callsites wrap it as
464/// `return Err(lex_error(...))`, and `lua-parse` does the same across the crate
465/// boundary, so the by-value return is a deliberate public contract — not a
466/// half-finished translation of a diverging C function. The error text format
467/// (`source:line: message` plus an optional ` near <token>` suffix) is the
468/// behavioural invariant the oracle checks.
469pub fn lex_error(ls: &mut LexState, msg: &[u8], token: i32) -> LuaError {
470    const LUA_IDSIZE: usize = 60;
471    let mut buff = [0u8; LUA_IDSIZE];
472    let n = lua_vm::object::chunk_id(&mut buff[..], ls.source.as_bytes());
473    let src_part = &buff[..n];
474
475    let mut full_msg: Vec<u8> = Vec::new();
476    full_msg.extend_from_slice(src_part);
477    let _ = write!(full_msg, ":{}: ", ls.linenumber);
478    full_msg.extend_from_slice(msg);
479
480    if token != 0 {
481        let tok_text = txt_token(ls, token);
482        full_msg.extend_from_slice(b" near ");
483        full_msg.extend_from_slice(&tok_text);
484    }
485
486    LuaError::syntax_raw(&full_msg)
487}
488
489/// Report a syntax error at the current token.
490pub fn syntax_error(ls: &mut LexState, msg: &[u8]) -> LuaError {
491    let token = ls.t.kind;
492    lex_error(ls, msg, token)
493}
494
495/// Report a semantic error at the current line WITHOUT the `near <token>`
496/// suffix.
497///
498/// The `near` clause is suppressed by passing token `0`. Used for attribute
499/// errors (`unknown attribute '<name>'`, `global variables cannot be
500/// to-be-closed`) where the offending construct is the attribute itself, not
501/// the current lookahead token.
502pub fn sem_error(ls: &mut LexState, msg: &[u8]) -> LuaError {
503    lex_error(ls, msg, 0)
504}
505
506/// Produce a human-readable representation of `token` for error messages.
507///
508/// For `TK_NAME`, `TK_STRING`, `TK_FLT`, `TK_INT`: formats the current
509/// token buffer contents as `'<text>'`.  For everything else, delegates to
510/// [`token2str`].
511fn txt_token(ls: &mut LexState, token: i32) -> Vec<u8> {
512    match token {
513        t if t == TK_NAME || t == TK_STRING || t == TK_FLT || t == TK_INT => {
514            let mut v: Vec<u8> = Vec::new();
515            v.push(b'\'');
516            v.extend_from_slice(ls.buff.without_trailing_nul());
517            v.push(b'\'');
518            v
519        }
520        _ => token2str_raw(token, ls.version),
521    }
522}
523
524/// Produce a human-readable token description (for error messages and the parser).
525///
526/// Single-byte printable tokens are formatted as `'X'`; non-printable as
527/// `'<\N>'`.  Reserved words and multi-char symbols are formatted as `'kw'`.
528/// Literal tokens (`<name>`, `<string>`, etc.) return the bare label.
529pub fn token2str(ls: &LexState, token: i32) -> Vec<u8> {
530    token2str_raw(token, ls.version)
531}
532
533/// Inner implementation of [`token2str`] that does not need `LexState`.
534///
535/// `version` gates the 5.1 special-token quoting. Lua 5.1 wraps the whole
536/// near/expected token in quotes, so the bare multi-char labels (`<eof>`,
537/// `<name>`, …) returned for `token >= TK_EOS` end up quoted. 5.2 leaves those
538/// bare and quotes only symbols/reserved/literals, so for 5.2+ the `>= TK_EOS`
539/// arm stays unquoted. (Issue #105.)
540///
541/// `version` also gates the rendering of a non-printable single byte. Lua 5.1's
542/// `luaX_token2str` renders a control byte (`iscntrl`: 0x00-0x1F, 0x7F) as
543/// `char(%d)` and any other non-printable byte (e.g. 0x80-0xFF) as the byte
544/// itself; in both cases the result is wrapped in the `near '...'` quotes. Lua
545/// 5.2's `luaX_token2str` formats such a byte as the bare label `char(%d)` (the
546/// surrounding `near '...'` quoting is suppressed for tokens whose text starts
547/// with `char(`), whereas 5.3+ render it as the quoted `'<\\%d>'`.
548fn token2str_raw(token: i32, version: lua_types::LuaVersion) -> Vec<u8> {
549    if token < FIRST_RESERVED {
550        if is_print(token) {
551            vec![b'\'', token as u8, b'\'']
552        } else if version == lua_types::LuaVersion::V51 {
553            if is_cntrl(token) {
554                let mut v: Vec<u8> = Vec::new();
555                v.extend_from_slice(b"'char(");
556                let _ = write!(&mut v, "{}", token);
557                v.extend_from_slice(b")'");
558                v
559            } else {
560                vec![b'\'', token as u8, b'\'']
561            }
562        } else if version == lua_types::LuaVersion::V52 {
563            let mut v: Vec<u8> = Vec::new();
564            v.extend_from_slice(b"char(");
565            let _ = write!(&mut v, "{}", token);
566            v.push(b')');
567            v
568        } else {
569            let mut v: Vec<u8> = Vec::new();
570            v.extend_from_slice(b"'<\\");
571            let _ = write!(&mut v, "{}", token);
572            v.extend_from_slice(b">'");
573            v
574        }
575    } else {
576        let idx = (token - FIRST_RESERVED) as usize;
577        let s = LUAX_TOKENS[idx];
578        if token < TK_EOS || version == lua_types::LuaVersion::V51 {
579            let mut v: Vec<u8> = Vec::with_capacity(s.len() + 2);
580            v.push(b'\'');
581            v.extend_from_slice(s);
582            v.push(b'\'');
583            v
584        } else {
585            s.to_vec()
586        }
587    }
588}
589
590// ── Public init / setup ───────────────────────────────────────────────────────
591
592/// Initialise the lexer subsystem: intern all reserved words and fix them
593/// in the GC so they are never collected.
594///
595/// Must be called exactly once during VM startup.
596pub fn init(state: &mut LuaState) -> Result<(), LuaError> {
597    let _e = intern_str_stub(state, LUA_ENV)?;
598
599    for i in 0..NUM_RESERVED {
600        let ts = intern_str_stub(state, LUAX_TOKENS[i])?;
601        let _ = ts;
602    }
603
604    Ok(())
605}
606
607/// Initialise `ls` for lexing a new chunk from stream `z`.
608pub fn set_input(
609    state: &mut LuaState,
610    ls: &mut LexState,
611    z: ZIO,
612    source: GcRef<LuaString>,
613    firstchar: i32,
614) -> Result<(), LuaError> {
615    ls.t = Token::new(0);
616    ls.current = firstchar;
617    ls.lookahead = Token::eos();
618    ls.z = z;
619    ls.fs = None;
620    ls.linenumber = 1;
621    ls.lastline = 1;
622    ls.source = source;
623    ls.version = state.global().lua_version;
624    ls.envn = intern_str_stub(state, LUA_ENV)?;
625    ls.buff.resize(state, LUA_MIN_BUFFER)?;
626    Ok(())
627}
628
629/// Create (or retrieve) a Lua string and anchor it in the parser's GC-protection
630/// table `ls.h` so it cannot be collected before the end of compilation.
631///
632/// Also internalises long strings so that each unique content has exactly one
633/// copy in memory.  The table `ls.h` is used as a set: the string is both the
634/// key and the value.
635pub(crate) fn new_string(
636    state: &mut LuaState,
637    ls: &mut LexState,
638    bytes: &[u8],
639) -> Result<GcRef<LuaString>, LuaError> {
640    // The `long_str_anchor` map dedups so a second occurrence of the same
641    // literal in the chunk returns the originally-created string; identity is
642    // determined by the `Rc` allocation. Short strings already share identity
643    // via the global pool; long strings (>40 bytes) need this session-level map.
644    if let Some(existing) = ls.long_str_anchor.get(bytes) {
645        return Ok(existing.clone());
646    }
647    let ts = intern_str_stub(state, bytes)?;
648    ls.long_str_anchor.insert(bytes.to_vec(), ts.clone());
649    Ok(ts)
650}
651
652// ── Public advance / lookahead ─────────────────────────────────────────────────
653
654/// Consume the current token; load the next one from the stream.
655///
656/// If a lookahead token was set, it becomes the current token without re-reading
657/// from the stream.
658pub fn next(state: &mut LuaState, ls: &mut LexState) -> Result<(), LuaError> {
659    ls.lastline = ls.linenumber;
660
661    if ls.lookahead.kind != TK_EOS {
662        // Clone to avoid borrow conflict; LuaString inside TokenValue is GcRef (Rc).
663        ls.t = ls.lookahead.clone();
664        ls.lookahead = Token::eos();
665    } else {
666        let mut val = TokenValue::None;
667        let kind = llex(state, ls, &mut val)?;
668        ls.t = Token { kind, value: val };
669    }
670    Ok(())
671}
672
673/// Peek at the next token without consuming the current one.
674///
675/// The lookahead token is cached in `ls.lookahead` and returned.  Only one
676/// token of lookahead is supported; calling this twice without an intervening
677/// [`next`] is a logic error (asserted in debug builds).
678pub fn lookahead(state: &mut LuaState, ls: &mut LexState) -> Result<i32, LuaError> {
679    debug_assert!(
680        ls.lookahead.kind == TK_EOS,
681        "luaX_lookahead: lookahead already set"
682    );
683
684    let mut val = TokenValue::None;
685    let kind = llex(state, ls, &mut val)?;
686    ls.lookahead = Token { kind, value: val };
687
688    Ok(ls.lookahead.kind)
689}
690
691// ── Private lexer helpers ──────────────────────────────────────────────────────
692
693/// If the current character equals `c`, advance and return `true`.
694fn check_next1(state: &mut LuaState, ls: &mut LexState, c: i32) -> Result<bool, LuaError> {
695    if ls.current == c {
696        advance(state, ls)?;
697        Ok(true)
698    } else {
699        Ok(false)
700    }
701}
702
703/// If the current character is either of the two bytes in `set`, save-and-advance
704/// and return `true`.
705fn check_next2(ls: &mut LexState, state: &mut LuaState, set: &[u8; 2]) -> Result<bool, LuaError> {
706    if ls.current == set[0] as i32 || ls.current == set[1] as i32 {
707        save_and_next(ls, state)?;
708        Ok(true)
709    } else {
710        Ok(false)
711    }
712}
713
714/// Increment the line counter and consume the newline sequence.
715///
716/// Handles `\n`, `\r`, `\n\r`, and `\r\n`: a second newline byte is only
717/// consumed when it differs from the first, so a `\n\n` (two blank lines)
718/// is not collapsed into one.
719fn inc_line_number(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
720    debug_assert!(curr_is_newline(ls), "inc_line_number: not at a newline");
721
722    let old = ls.current;
723    advance(state, ls)?;
724
725    if curr_is_newline(ls) && ls.current != old {
726        advance(state, ls)?;
727    }
728
729    ls.linenumber += 1;
730    if ls.linenumber >= i32::MAX {
731        return Err(lex_error(ls, b"chunk has too many lines", 0));
732    }
733    Ok(())
734}
735
736/// Scan a numeric literal (integer or float, decimal or hex).
737///
738/// The caller may have already read an initial dot.  Accepts the pattern:
739/// `%d(%x|%.|(Ee[+-]?))*` or `0[Xx](%x|%.|(Pp[+-]?))*`.
740///
741/// Returns `TK_INT` for integers, `TK_FLT` for floats.
742fn read_numeral(
743    state: &mut LuaState,
744    ls: &mut LexState,
745    seminfo: &mut TokenValue,
746) -> Result<i32, LuaError> {
747    let mut expo: &[u8; 2] = b"Ee";
748
749    let first = ls.current;
750
751    debug_assert!(is_digit(ls.current), "read_numeral: not at a digit");
752
753    save_and_next(ls, state)?;
754
755    let is_hex = first == b'0' as i32 && check_next2(ls, state, b"xX")?;
756
757    // Lua 5.1 has no hexadecimal-aware number scanner: it never recognizes a
758    // binary (`Pp`) exponent, a signed binary exponent, or a fractional `.`
759    // inside a hex literal. Its scanner reads decimal digits/`.`, an optional
760    // `Ee` exponent, then swallows the rest of the alphanumeric run (the hex
761    // body) and hands the whole token to `strtod`/`strtoul`. So:
762    //   * `0x1p4`  -> the `p4` rides the alphanumeric tail -> strtod -> 16
763    //   * `0x1p-2` -> the tail stops at `-`, leaving `0x1p` -> malformed
764    //   * `0x1.8p0`-> the main loop stops at `.`, leaving `0x1` (=1); `.8p0`
765    //                 then lexes as a fresh, malformed decimal numeral.
766    // 5.2+ added the hex-aware scanner (`Pp` exponent + signed exponent +
767    // fractional `.`), so the hex-special path below is gated off for V51.
768    let is_v51 = matches!(state.global().lua_version, lua_types::LuaVersion::V51);
769    let hex_aware = is_hex && !is_v51;
770    if hex_aware {
771        expo = b"Pp";
772    }
773
774    // For a 5.1 hex literal the digit-scanning main loop is skipped entirely so
775    // its `Ee`-exponent probe cannot mistake a hex `e`/`E` digit for a decimal
776    // exponent (`0x1e2` is 482, not `0x1` × 10^2); the whole hex body rides the
777    // alphanumeric tail below, exactly as 5.1's scanner does.
778    let scan_digits = !(is_hex && is_v51);
779    while scan_digits {
780        if check_next2(ls, state, expo)? {
781            check_next2(ls, state, b"-+")?;
782        } else if is_xdigit(ls.current) || (ls.current == b'.' as i32 && (!is_hex || hex_aware)) {
783            save_and_next(ls, state)?;
784        } else {
785            break;
786        }
787    }
788
789    // Numeral "touching a letter" handling. 5.2+ append a single trailing letter
790    // to force a malformed-number error (the alphanumeric run after it lexes
791    // separately). Lua 5.1's scanner instead swallows the *entire* alphanumeric
792    // (and `_`) run into the numeral, so a malformed 5.1 numeral reports the full
793    // run in its `near '...'` snippet (`.8p0`, `3xyz`), not just its first letter.
794    if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
795        while is_lalnum(ls.current) {
796            save_and_next(ls, state)?;
797        }
798    } else if is_lalpha(ls.current) {
799        save_and_next(ls, state)?;
800    }
801
802    save(ls, state, 0)?;
803
804    match parse_numeral(ls.buff.without_trailing_nul()) {
805        None => Err(lex_error(ls, b"malformed number", TK_FLT)),
806        Some(lua_types::LuaValue::Int(i)) => {
807            if is_float_only(state) {
808                // The float-only family (5.1/5.2) has no integer subtype: every
809                // numeral becomes a float. A hex integer literal is read through
810                // C's `strtoul(.., 16)`, an *unsigned* 64-bit conversion, so an
811                // overflowing hex literal (top bit set) becomes a large positive
812                // double — `0xFFFFFFFFFFFFFFFF` is `1.844674407371e+19`, not -1.
813                // `str2int` wraps into `i64`, so reinterpret the bit pattern as
814                // `u64` before widening; for any non-overflowing literal this is
815                // identical to `i as f64`.
816                let widened = if is_hex { (i as u64) as f64 } else { i as f64 };
817                *seminfo = TokenValue::Float(widened);
818                Ok(TK_FLT)
819            } else {
820                *seminfo = TokenValue::Int(i);
821                Ok(TK_INT)
822            }
823        }
824        Some(lua_types::LuaValue::Float(f)) => {
825            *seminfo = TokenValue::Float(f);
826            Ok(TK_FLT)
827        }
828        Some(other) => unreachable!("parse_numeral yielded non-numeric value: {other:?}"),
829    }
830}
831
832/// Scan a `[=*[` or `]=*]` sequence; leave the last bracket as current char.
833///
834/// Returns:
835/// - `count + 2` if well-formed (where `count` is the number of `=` signs),
836/// - `1` if a single bracket with no `=`s and no second bracket,
837/// - `0` if malformed (e.g. `[==` with no closing bracket).
838fn skip_sep(state: &mut LuaState, ls: &mut LexState) -> Result<usize, LuaError> {
839    let mut count: usize = 0;
840    let s = ls.current;
841    debug_assert!(
842        s == b'[' as i32 || s == b']' as i32,
843        "skip_sep: not at bracket"
844    );
845
846    save_and_next(ls, state)?;
847
848    while ls.current == b'=' as i32 {
849        save_and_next(ls, state)?;
850        count += 1;
851    }
852
853    if ls.current == s {
854        Ok(count + 2)
855    } else if count == 0 {
856        Ok(1)
857    } else {
858        Ok(0)
859    }
860}
861
862/// Scan a long string or long comment delimited by `[=*[` … `]=*]`.
863///
864/// `seminfo` is `Some` when reading a string literal; `None` when skipping a
865/// long comment.  When `None`, buffer contents are discarded on each newline
866/// to avoid wasting memory.
867fn read_long_string(
868    state: &mut LuaState,
869    ls: &mut LexState,
870    seminfo: Option<&mut TokenValue>,
871    sep: usize,
872) -> Result<(), LuaError> {
873    let line = ls.linenumber;
874
875    save_and_next(ls, state)?;
876
877    if curr_is_newline(ls) {
878        inc_line_number(ls, state)?;
879    }
880
881    // is_string: whether we are reading a string (true) or a comment (false)
882    let is_string = seminfo.is_some();
883
884    loop {
885        match ls.current {
886            c if c == EOZ => {
887                let what: &[u8] = if is_string { b"string" } else { b"comment" };
888                let mut msg: Vec<u8> = Vec::new();
889                msg.extend_from_slice(b"unfinished long ");
890                msg.extend_from_slice(what);
891                // The "(starting at line N)" clause was added in 5.3. The
892                // float-only family (5.1/5.2) reports the bare
893                // "unfinished long string"/"unfinished long comment".
894                if !is_float_only(state) {
895                    msg.extend_from_slice(b" (starting at line ");
896                    let _ = write!(&mut msg, "{}", line);
897                    msg.push(b')');
898                }
899                return Err(lex_error(ls, &msg, TK_EOS));
900            }
901            c if c == b']' as i32 => {
902                let s = skip_sep(state, ls)?;
903                if s == sep {
904                    save_and_next(ls, state)?;
905                    break;
906                }
907                // else: the ']' sequence wasn't the closing delimiter; continue
908            }
909            c if c == b'\n' as i32 || c == b'\r' as i32 => {
910                save(ls, state, b'\n' as i32)?;
911                inc_line_number(ls, state)?;
912                if !is_string {
913                    ls.buff.clear();
914                }
915            }
916            _ => {
917                if is_string {
918                    save_and_next(ls, state)?;
919                } else {
920                    advance(state, ls)?;
921                }
922            }
923        }
924    }
925
926    if let Some(out) = seminfo {
927        // The buffer holds `[=*[` + content + `]=*]`, each delimiter `sep` bytes
928        // wide; strip both to recover the content.
929        let content = ls.buff.trim_ends(sep);
930        let ts = new_string(state, ls, &content)?;
931        *out = TokenValue::Str(ts);
932    }
933    Ok(())
934}
935
936/// Check `c` is non-zero (truthy); if not, save the current char and raise a
937/// string-escape error.
938fn esc_check(
939    state: &mut LuaState,
940    ls: &mut LexState,
941    ok: bool,
942    msg: &[u8],
943) -> Result<(), LuaError> {
944    if !ok {
945        if ls.current != EOZ {
946            save_and_next(ls, state)?;
947        }
948        return Err(lex_error(ls, msg, TK_STRING));
949    }
950    Ok(())
951}
952
953/// Build a Lua 5.2-family escape-sequence error whose `near '...'` snippet is
954/// the backslash plus the offending escape characters (`'\j'`, `'\256'`,
955/// `'\xZ'`), not the buffer collected so far.
956///
957/// This mirrors 5.2's `escerror`, which resets the token buffer and saves `'\\'`
958/// followed by the escape characters before raising. (5.3+ leaves the whole
959/// buffer in place, so its snippet keeps the opening quote and prior content —
960/// that path stays on [`esc_check`].) Trailing `EOZ` markers in `chars` are
961/// dropped, matching `escerror`'s `c[i] != EOZ` guard.
962fn esc_error_legacy(ls: &mut LexState, chars: &[i32], msg: &[u8]) -> LuaError {
963    ls.buff.clear();
964    ls.buff.push_byte(b'\\');
965    for &c in chars {
966        if c == EOZ {
967            break;
968        }
969        ls.buff.push_byte(c as u8);
970    }
971    lex_error(ls, msg, TK_STRING)
972}
973
974/// Save-and-advance, then verify the new current char is a hex digit; return
975/// its numeric value (0-15).
976///
977/// On failure the `near '...'` snippet is version-gated. 5.2 reports `\x` plus
978/// the characters read so far (`'\xZ'`, `'\x1Z'`), built by resetting the buffer
979/// (mirroring `escerror`); `chars` carries the hex characters already consumed by
980/// the enclosing `\x` escape so the snippet can be rebuilt. 5.3+ report the whole
981/// buffer-so-far via the save-and-next inside `esc_check`. (5.2 has no `\u`, so a
982/// hex-digit error here always belongs to a `\x` escape.)
983fn get_hexa(state: &mut LuaState, ls: &mut LexState, chars: &mut Vec<i32>) -> Result<u32, LuaError> {
984    save_and_next(ls, state)?;
985    if !is_xdigit(ls.current) {
986        if matches!(state.global().lua_version, lua_types::LuaVersion::V52) {
987            let mut esc: Vec<i32> = Vec::with_capacity(chars.len() + 2);
988            esc.push(b'x' as i32);
989            esc.extend_from_slice(chars);
990            esc.push(ls.current);
991            return Err(esc_error_legacy(ls, &esc, b"hexadecimal digit expected"));
992        }
993        esc_check(state, ls, false, b"hexadecimal digit expected")?;
994    }
995    chars.push(ls.current);
996    Ok(hex_value_stub(ls.current))
997}
998
999/// Scan a `\xNN` hex escape; return the decoded byte value.
1000fn read_hex_esc(state: &mut LuaState, ls: &mut LexState) -> Result<u32, LuaError> {
1001    let mut chars: Vec<i32> = Vec::with_capacity(2);
1002    let r = get_hexa(state, ls, &mut chars)?;
1003    let r = (r << 4) + get_hexa(state, ls, &mut chars)?;
1004    ls.buff.truncate_by(2);
1005    Ok(r)
1006}
1007
1008/// Scan a `\u{XXXXXX}` UTF-8 escape; return the Unicode codepoint.
1009fn read_utf8_esc(state: &mut LuaState, ls: &mut LexState) -> Result<u32, LuaError> {
1010    let mut i: usize = 4;
1011
1012    save_and_next(ls, state)?;
1013
1014    esc_check(state, ls, ls.current == b'{' as i32, b"missing '{'")?;
1015
1016    // `\u{...}` exists only on 5.3+, so the 5.2 reset-buffer error branch in
1017    // `get_hexa` is never taken from here; the accumulator is unused.
1018    let mut hex_chars: Vec<i32> = Vec::new();
1019    let mut r = get_hexa(state, ls, &mut hex_chars)?;
1020
1021    // The codepoint upper bound is version-gated, and the digit-accumulation
1022    // order differs between the families:
1023    //   * 5.3: accumulate the digit FIRST (`r = (r<<4)+digit`), THEN bound the
1024    //     running value at 0x10FFFF.
1025    //   * 5.4 / 5.5: bound BEFORE the shift (`r <= 0x7FFFFFFF >> 4`), then
1026    //     accumulate — allowing codepoints up to 0x7FFFFFFF.
1027    // The order (check-before-shift vs shift-before-check) is load-bearing: it
1028    // also determines how many digits land in the `near '...'` snippet of the
1029    // "UTF-8 value too large" error, so a too-large `\u{...}` reports the same
1030    // message and offset as the matching reference binary.
1031    let is_v53 = matches!(state.global().lua_version, lua_types::LuaVersion::V53);
1032
1033    loop {
1034        save_and_next(ls, state)?;
1035        if !is_xdigit(ls.current) {
1036            break;
1037        }
1038        i += 1;
1039        if is_v53 {
1040            r = (r << 4) + hex_value_stub(ls.current);
1041            esc_check(state, ls, r <= 0x10_FFFF, b"UTF-8 value too large")?;
1042        } else {
1043            esc_check(
1044                state,
1045                ls,
1046                r <= (0x7FFF_FFFFu32 >> 4),
1047                b"UTF-8 value too large",
1048            )?;
1049            r = (r << 4) + hex_value_stub(ls.current);
1050        }
1051    }
1052
1053    esc_check(state, ls, ls.current == b'}' as i32, b"missing '}'")?;
1054
1055    advance(state, ls)?;
1056
1057    ls.buff.truncate_by(i);
1058
1059    Ok(r)
1060}
1061
1062/// Scan `\u{...}` and append the UTF-8 encoding of the codepoint to the buffer.
1063fn utf8_esc(state: &mut LuaState, ls: &mut LexState) -> Result<(), LuaError> {
1064    let codepoint = read_utf8_esc(state, ls)?;
1065
1066    let encoded = utf8_encode_stub(codepoint);
1067
1068    for &b in &encoded {
1069        save(ls, state, b as i32)?;
1070    }
1071    Ok(())
1072}
1073
1074/// Scan a decimal escape `\ddd` (up to 3 digits); return the byte value.
1075fn read_dec_esc(state: &mut LuaState, ls: &mut LexState) -> Result<u32, LuaError> {
1076    let mut i: usize = 0;
1077    let mut r: u32 = 0;
1078    let mut digits: Vec<i32> = Vec::with_capacity(3);
1079
1080    while i < 3 && is_digit(ls.current) {
1081        r = 10 * r + (ls.current as u32 - b'0' as u32);
1082        digits.push(ls.current);
1083        save_and_next(ls, state)?;
1084        i += 1;
1085    }
1086
1087    if r > u8::MAX as u32 {
1088        // The "too large" message and `near '...'` snippet are version-gated:
1089        //   * 5.1: spelled "escape sequence too large"; its scanner saves
1090        //     neither the backslash nor the digits, so the snippet is just the
1091        //     opening quote (`'"'`). The shared decode path *did* buffer them
1092        //     here, so trim the backslash + `i` digits back off before raising.
1093        //   * 5.2: "decimal escape too large", snippet is `\` + the digits
1094        //     (`'\256'`), built by resetting the buffer (see `esc_error_legacy`).
1095        //   * 5.3+: "decimal escape too large", snippet is the buffer collected
1096        //     so far (opening quote + content + `\` + digits + the trailing char
1097        //     `esc_check` save-and-nexts on).
1098        let version = state.global().lua_version;
1099        match version {
1100            lua_types::LuaVersion::V51 => {
1101                ls.buff.truncate_by(i + 1);
1102                return Err(lex_error(ls, b"escape sequence too large", TK_STRING));
1103            }
1104            lua_types::LuaVersion::V52 => {
1105                return Err(esc_error_legacy(ls, &digits, b"decimal escape too large"));
1106            }
1107            _ => {
1108                esc_check(state, ls, false, b"decimal escape too large")?;
1109            }
1110        }
1111    }
1112
1113    ls.buff.truncate_by(i);
1114    Ok(r)
1115}
1116
1117/// Scan a short (single/double-quoted) string literal.
1118///
1119/// Escape-sequence handling decodes a byte and then dispatches via the local
1120/// [`EscapeResult`] enum.
1121fn read_string(
1122    state: &mut LuaState,
1123    ls: &mut LexState,
1124    del: i32,
1125    seminfo: &mut TokenValue,
1126) -> Result<(), LuaError> {
1127    // What the escape-sequence handler does after decoding a byte.
1128    //
1129    // ReadSave:  advance, remove '\' from buffer, save decoded byte.
1130    // OnlySave:  remove '\' from buffer, save decoded byte (no advance).
1131    // NoSave:    nothing (just break from the escape case).
1132    enum EscapeResult {
1133        ReadSave(i32),
1134        OnlySave(i32),
1135        NoSave,
1136    }
1137
1138    save_and_next(ls, state)?;
1139
1140    while ls.current != del {
1141        match ls.current {
1142            c if c == EOZ => {
1143                return Err(lex_error(ls, b"unfinished string", TK_EOS));
1144            }
1145            c if c == b'\n' as i32 || c == b'\r' as i32 => {
1146                return Err(lex_error(ls, b"unfinished string", TK_STRING));
1147            }
1148            c if c == b'\\' as i32 => {
1149                save_and_next(ls, state)?;
1150
1151                // Lua 5.1's lexer does NOT recognize `\x`, `\z`, or `\u`, and it
1152                // does NOT raise on an unknown escape. For any escape char outside
1153                // the known set, the 5.1 lexer silently drops the backslash and
1154                // keeps the next character verbatim (`"\x41"` → bytes `x41`,
1155                // `"\z"` → `z`, `"\q"` → `q`). Decimal escapes (`\ddd`) and the
1156                // standard letter/quote/newline escapes still work. Verified
1157                // against lua5.1.5; see specs/followup/5.1-roster-syntax.md §2.
1158                let is_v51 = matches!(state.global().lua_version, lua_types::LuaVersion::V51);
1159                // The `\u{...}` escape is a 5.3 addition. 5.1 has no `\u` at all
1160                // (silently drops the backslash); 5.2 added `\x` and `\z` but NOT
1161                // `\u`, so on the float-only family `\u` is an invalid escape.
1162                let has_u_escape = !is_float_only(state);
1163
1164                // Inner switch on the escape character
1165                let esc = match ls.current {
1166                    c if c == b'a' as i32 => EscapeResult::ReadSave(b'\x07' as i32),
1167                    c if c == b'b' as i32 => EscapeResult::ReadSave(b'\x08' as i32),
1168                    c if c == b'f' as i32 => EscapeResult::ReadSave(b'\x0C' as i32),
1169                    c if c == b'n' as i32 => EscapeResult::ReadSave(b'\n' as i32),
1170                    c if c == b'r' as i32 => EscapeResult::ReadSave(b'\r' as i32),
1171                    c if c == b't' as i32 => EscapeResult::ReadSave(b'\t' as i32),
1172                    c if c == b'v' as i32 => EscapeResult::ReadSave(b'\x0B' as i32),
1173                    c if c == b'x' as i32 && !is_v51 => {
1174                        let decoded = read_hex_esc(state, ls)?;
1175                        EscapeResult::ReadSave(decoded as i32)
1176                    }
1177                    c if c == b'u' as i32 && has_u_escape => {
1178                        utf8_esc(state, ls)?;
1179                        EscapeResult::NoSave
1180                    }
1181                    c if c == b'\n' as i32 || c == b'\r' as i32 => {
1182                        inc_line_number(ls, state)?;
1183                        EscapeResult::OnlySave(b'\n' as i32)
1184                    }
1185                    c if c == b'\\' as i32 || c == b'"' as i32 || c == b'\'' as i32 => {
1186                        EscapeResult::ReadSave(c)
1187                    }
1188                    c if c == EOZ => EscapeResult::NoSave,
1189                    c if c == b'z' as i32 && !is_v51 => {
1190                        ls.buff.truncate_by(1);
1191                        advance(state, ls)?;
1192                        while is_space(ls.current) {
1193                            if curr_is_newline(ls) {
1194                                inc_line_number(ls, state)?;
1195                            } else {
1196                                advance(state, ls)?;
1197                            }
1198                        }
1199                        EscapeResult::NoSave
1200                    }
1201                    c if is_v51 && !is_digit(c) => {
1202                        // 5.1 unknown escape: drop the backslash, emit the char.
1203                        EscapeResult::ReadSave(c)
1204                    }
1205                    _ => {
1206                        if !is_digit(ls.current) {
1207                            // 5.2 reports the invalid escape as `\` + the offending
1208                            // char (`'\j'`, `'\u'`) by resetting the buffer; 5.3+
1209                            // report the whole buffer-so-far (`'"\j'`) via the
1210                            // save-and-next inside `esc_check`.
1211                            if matches!(state.global().lua_version, lua_types::LuaVersion::V52) {
1212                                return Err(esc_error_legacy(
1213                                    ls,
1214                                    &[ls.current],
1215                                    b"invalid escape sequence",
1216                                ));
1217                            }
1218                            esc_check(state, ls, false, b"invalid escape sequence")?;
1219                        }
1220                        let decoded = read_dec_esc(state, ls)?;
1221                        EscapeResult::OnlySave(decoded as i32)
1222                    }
1223                };
1224
1225                match esc {
1226                    EscapeResult::ReadSave(c) => {
1227                        advance(state, ls)?;
1228                        ls.buff.truncate_by(1);
1229                        save(ls, state, c)?;
1230                    }
1231                    EscapeResult::OnlySave(c) => {
1232                        ls.buff.truncate_by(1);
1233                        save(ls, state, c)?;
1234                    }
1235                    EscapeResult::NoSave => {}
1236                }
1237            }
1238            _ => {
1239                save_and_next(ls, state)?;
1240            }
1241        }
1242    }
1243
1244    save_and_next(ls, state)?;
1245
1246    // The buffer holds the opening quote + content + closing quote; strip the
1247    // one-byte delimiter from each end.
1248    let content = ls.buff.trim_ends(1);
1249    let ts = new_string(state, ls, &content)?;
1250    *seminfo = TokenValue::Str(ts);
1251    Ok(())
1252}
1253
1254/// Whether the active version is the float-only legacy family (5.1/5.2), which
1255/// lacks the 5.3 integer operators (`//`, `<<`, `>>`, and the bitwise binops).
1256fn is_float_only(state: &LuaState) -> bool {
1257    matches!(
1258        state.global().lua_version,
1259        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1260    )
1261}
1262
1263/// The lexer's view of the current input character.
1264///
1265/// `ls.current` is stored as `i32` (a byte, or [`EOZ`] = `-1`) at the stream
1266/// boundary; this enum is the lexer's *internal* dispatch shape so the main
1267/// scan loop can `match` on byte literals (`Byte(b'=')`) and on end-of-stream
1268/// (`Eoz`) directly instead of an `i32` guard chain. It does not cross the
1269/// public boundary: scanned tokens are still reported as `TK_*` / ASCII `i32`.
1270enum Peek {
1271    Byte(u8),
1272    Eoz,
1273}
1274
1275/// Classify [`LexState::current`] into the internal [`Peek`] dispatch shape.
1276fn peek(ls: &LexState) -> Peek {
1277    match u8::try_from(ls.current) {
1278        Ok(b) => Peek::Byte(b),
1279        Err(_) => Peek::Eoz,
1280    }
1281}
1282
1283/// Core lexer dispatch: consume and return the next raw token kind.
1284///
1285/// The heart of the lexer: a scan loop that classifies the current character
1286/// (via [`Peek`]) and dispatches to the appropriate scanner. Single-character
1287/// tokens are returned as their ASCII `i32`; multi-character and reserved-word
1288/// tokens as the `TK_*` constants.
1289fn llex(
1290    state: &mut LuaState,
1291    ls: &mut LexState,
1292    seminfo: &mut TokenValue,
1293) -> Result<i32, LuaError> {
1294    ls.buff.clear();
1295
1296    loop {
1297        match peek(ls) {
1298            Peek::Byte(b'\n' | b'\r') => {
1299                inc_line_number(ls, state)?;
1300                // Shebang handling: the reference loader strips a leading '#'
1301                // line (Unix shebang). Our test harness prepends a global-setup
1302                // preamble to every official test, so the script's '#' line is
1303                // not at byte zero. Apply the same rule at any token-scan line
1304                // start: treat a line whose first character is '#' as a
1305                // single-line comment. This sits in the dispatch loop (not
1306                // inc_line_number) so it does not affect newlines inside
1307                // long-bracket strings.
1308                if ls.current == b'#' as i32 {
1309                    while !curr_is_newline(ls) && ls.current != EOZ {
1310                        advance(state, ls)?;
1311                    }
1312                }
1313            }
1314
1315            Peek::Byte(b' ' | b'\x0C' | b'\t' | b'\x0B') => {
1316                advance(state, ls)?;
1317            }
1318
1319            Peek::Byte(b'-') => {
1320                advance(state, ls)?;
1321                if ls.current != b'-' as i32 {
1322                    return Ok(b'-' as i32);
1323                }
1324                advance(state, ls)?;
1325
1326                if ls.current == b'[' as i32 {
1327                    let sep = skip_sep(state, ls)?;
1328                    ls.buff.clear();
1329                    if sep >= 2 {
1330                        read_long_string(state, ls, None, sep)?;
1331                        ls.buff.clear();
1332                        continue;
1333                    }
1334                }
1335                while !curr_is_newline(ls) && ls.current != EOZ {
1336                    advance(state, ls)?;
1337                }
1338                // loop continues (no token emitted for comments)
1339            }
1340
1341            Peek::Byte(b'[') => {
1342                let sep = skip_sep(state, ls)?;
1343                if sep >= 2 {
1344                    read_long_string(state, ls, Some(seminfo), sep)?;
1345                    return Ok(TK_STRING);
1346                } else if sep == 0 {
1347                    return Err(lex_error(ls, b"invalid long string delimiter", TK_STRING));
1348                }
1349                return Ok(b'[' as i32);
1350            }
1351
1352            Peek::Byte(b'=') => {
1353                advance(state, ls)?;
1354                if check_next1(state, ls, b'=' as i32)? {
1355                    return Ok(TK_EQ);
1356                }
1357                return Ok(b'=' as i32);
1358            }
1359
1360            Peek::Byte(b'<') => {
1361                advance(state, ls)?;
1362                if check_next1(state, ls, b'=' as i32)? {
1363                    return Ok(TK_LE);
1364                } else if !is_float_only(state) && check_next1(state, ls, b'<' as i32)? {
1365                    // The `<<` shift operator is a Lua 5.3 addition. Under the
1366                    // float-only legacy family (5.1/5.2) it does not exist: a
1367                    // bare `<` is returned, so a second `<` then surfaces
1368                    // upstream's "unexpected symbol near '<'".
1369                    return Ok(TK_SHL);
1370                }
1371                return Ok(b'<' as i32);
1372            }
1373
1374            Peek::Byte(b'>') => {
1375                advance(state, ls)?;
1376                if check_next1(state, ls, b'=' as i32)? {
1377                    return Ok(TK_GE);
1378                } else if !is_float_only(state) && check_next1(state, ls, b'>' as i32)? {
1379                    // `>>` is a 5.3 addition; absent in 5.1/5.2.
1380                    return Ok(TK_SHR);
1381                }
1382                return Ok(b'>' as i32);
1383            }
1384
1385            Peek::Byte(b'/') => {
1386                advance(state, ls)?;
1387                if !is_float_only(state) && check_next1(state, ls, b'/' as i32)? {
1388                    // Floor division `//` is a 5.3 addition; absent in 5.1/5.2,
1389                    // where the second `/` becomes "unexpected symbol near '/'".
1390                    return Ok(TK_IDIV);
1391                }
1392                return Ok(b'/' as i32);
1393            }
1394
1395            Peek::Byte(b'~') => {
1396                advance(state, ls)?;
1397                if check_next1(state, ls, b'=' as i32)? {
1398                    return Ok(TK_NE);
1399                }
1400                return Ok(b'~' as i32);
1401            }
1402
1403            Peek::Byte(b':') => {
1404                advance(state, ls)?;
1405                // Lua 5.1 has no `::label::` token; `::` was added with `goto` in
1406                // 5.2. Under V51 the second `:` is left for the parser, which
1407                // reports `unexpected symbol near ':'`. See
1408                // specs/followup/5.1-roster-syntax.md §2.
1409                let is_v51 = matches!(state.global().lua_version, lua_types::LuaVersion::V51);
1410                if !is_v51 && check_next1(state, ls, b':' as i32)? {
1411                    return Ok(TK_DBCOLON);
1412                }
1413                return Ok(b':' as i32);
1414            }
1415
1416            Peek::Byte(b'"' | b'\'') => {
1417                let del = ls.current;
1418                read_string(state, ls, del, seminfo)?;
1419                return Ok(TK_STRING);
1420            }
1421
1422            Peek::Byte(b'.') => {
1423                save_and_next(ls, state)?;
1424                if check_next1(state, ls, b'.' as i32)? {
1425                    if check_next1(state, ls, b'.' as i32)? {
1426                        return Ok(TK_DOTS);
1427                    }
1428                    return Ok(TK_CONCAT);
1429                } else if !is_digit(ls.current) {
1430                    return Ok(b'.' as i32);
1431                } else {
1432                    return read_numeral(state, ls, seminfo);
1433                }
1434            }
1435
1436            Peek::Byte(b'0'..=b'9') => {
1437                return read_numeral(state, ls, seminfo);
1438            }
1439
1440            Peek::Eoz => {
1441                return Ok(TK_EOS);
1442            }
1443
1444            Peek::Byte(c) => {
1445                if is_lalpha(c as i32) {
1446                    loop {
1447                        save_and_next(ls, state)?;
1448                        if !is_lalnum(ls.current) {
1449                            break;
1450                        }
1451                    }
1452
1453                    let content = ls.buff.to_owned_text();
1454                    let ts = new_string(state, ls, &content)?;
1455
1456                    // Recover the keyword index directly from the interned bytes
1457                    // via the `LUAX_TOKENS` table: the first `NUM_RESERVED`
1458                    // entries are the keywords in declaration order, so a match
1459                    // gives token id = `FIRST_RESERVED + index`.
1460                    let reserved_token: Option<i32> = LUAX_TOKENS[..NUM_RESERVED]
1461                        .iter()
1462                        .position(|kw| *kw == content.as_slice())
1463                        .map(|i| FIRST_RESERVED + i as i32);
1464                    *seminfo = TokenValue::Str(ts);
1465
1466                    if let Some(tk) = reserved_token {
1467                        // Lua 5.1 has no `goto` keyword — `goto` is an ordinary
1468                        // identifier (`local goto = 5` is valid). The keyword and
1469                        // the `::label::` grammar were added in 5.2. So under V51
1470                        // `goto` lexes as a plain name; the parser then treats
1471                        // `goto done` as a name beginning an assignment, yielding
1472                        // the incidental `'=' expected near 'done'` the oracle
1473                        // reports. See specs/followup/5.1-roster-syntax.md §2.
1474                        if tk == TK_GOTO
1475                            && matches!(state.global().lua_version, lua_types::LuaVersion::V51)
1476                        {
1477                            return Ok(TK_NAME);
1478                        }
1479                        return Ok(tk);
1480                    }
1481
1482                    // Lua 5.5: with the upstream-default `LUA_COMPAT_GLOBAL`, the
1483                    // `global` declaration word is NOT reserved — `global` stays a
1484                    // valid identifier, and the parser recognizes the declaration
1485                    // statement contextually (see `globalstat` in lua-parse). So
1486                    // `global` always lexes as a plain name, on every version.
1487                    return Ok(TK_NAME);
1488                } else {
1489                    let tok = ls.current;
1490                    advance(state, ls)?;
1491                    return Ok(tok);
1492                }
1493            }
1494        }
1495    }
1496}
1497
1498// ── Cross-crate helpers ────────────────────────────────────────────────────────
1499
1500fn intern_str_stub(state: &mut LuaState, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
1501    state.intern_str(bytes)
1502}
1503
1504/// Parse numeral bytes into an integer or float value, or `None` if malformed.
1505///
1506/// Wraps `lua_vm::object::str2num`, whose C-derived calling convention is an
1507/// out-parameter plus a `usize` status (`0` = no parse). The lexer never needs
1508/// the consumed-byte count — the whole token buffer is the numeral — so this
1509/// reduces the convention to an idiomatic `Option<LuaValue>`: `Some(value)` on
1510/// a successful parse, `None` on a malformed numeral.
1511fn parse_numeral(bytes: &[u8]) -> Option<lua_types::LuaValue> {
1512    let mut out = lua_types::LuaValue::Nil;
1513    if lua_vm::object::str2num(bytes, &mut out) == 0 {
1514        None
1515    } else {
1516        Some(out)
1517    }
1518}
1519
1520fn hex_value_stub(c: i32) -> u32 {
1521    match c {
1522        c if c >= b'0' as i32 && c <= b'9' as i32 => (c - b'0' as i32) as u32,
1523        c if c >= b'a' as i32 && c <= b'f' as i32 => (c - b'a' as i32 + 10) as u32,
1524        c if c >= b'A' as i32 && c <= b'F' as i32 => (c - b'A' as i32 + 10) as u32,
1525        _ => 0,
1526    }
1527}
1528
1529/// Encode a Unicode codepoint as a Lua-extended UTF-8 byte sequence (1 to 6 bytes).
1530///
1531/// Lua permits codepoints up to `0x7FFFFFFF` (5- and 6-byte sequences are
1532/// non-strict UTF-8 but accepted by `\u{...}` escapes per literals.lua test
1533/// cases).
1534fn utf8_encode_stub(codepoint: u32) -> Vec<u8> {
1535    debug_assert!(codepoint <= 0x7FFF_FFFF);
1536    if codepoint < 0x80 {
1537        return vec![codepoint as u8];
1538    }
1539    let mut x = codepoint;
1540    let mut mfb: u32 = 0x3f;
1541    let mut buf: Vec<u8> = Vec::with_capacity(8);
1542    loop {
1543        buf.push(0x80 | ((x & 0x3f) as u8));
1544        x >>= 6;
1545        mfb >>= 1;
1546        if x <= mfb {
1547            break;
1548        }
1549    }
1550    buf.push(((!mfb << 1) | x) as u8);
1551    buf.reverse();
1552    buf
1553}
1554
1555#[cfg(test)]
1556mod tests {
1557    use super::*;
1558    use lua_types::LuaVersion;
1559    use lua_vm::state::new_state;
1560
1561    /// A `LexState` whose fields are about to be (re)initialised by
1562    /// [`set_input`]; only `source`/`envn`/`version` need to be real up front.
1563    fn empty_lexstate(source: GcRef<LuaString>, ver: LuaVersion) -> LexState {
1564        LexState {
1565            current: EOZ,
1566            linenumber: 1,
1567            lastline: 1,
1568            t: Token::eos(),
1569            lookahead: Token::eos(),
1570            fs: None,
1571            z: ZIO::from_bytes(Vec::new()),
1572            buff: LexBuffer::new(),
1573            h: None,
1574            long_str_anchor: std::collections::HashMap::new(),
1575            dyd: None,
1576            source: source.clone(),
1577            envn: source,
1578            version: ver,
1579        }
1580    }
1581
1582    /// Build a `LexState` over `src` at version `ver` and drive [`next`] until
1583    /// [`TK_EOS`], collecting each token. The lexer is exercised end-to-end (the
1584    /// same path the parser takes), so these tests pin scanning behaviour without
1585    /// the full parser/oracle round-trip.
1586    fn lex(ver: LuaVersion, src: &[u8]) -> Vec<Token> {
1587        let mut state = new_state().expect("state init");
1588        state.global_mut().lua_version = ver;
1589
1590        let source = state.intern_str(b"@test").expect("intern source");
1591        let firstchar = src.first().map_or(EOZ, |&b| b as i32);
1592        let rest: Vec<u8> = src.iter().skip(1).copied().collect();
1593
1594        let mut ls = empty_lexstate(source.clone(), ver);
1595        set_input(&mut state, &mut ls, ZIO::from_bytes(rest), source, firstchar)
1596            .expect("set_input");
1597
1598        let mut out = Vec::new();
1599        loop {
1600            next(&mut state, &mut ls).expect("next");
1601            let kind = ls.t.kind;
1602            out.push(ls.t.clone());
1603            if kind == TK_EOS {
1604                break;
1605            }
1606        }
1607        out
1608    }
1609
1610    /// Just the token-kind sequence, dropping the trailing `TK_EOS`.
1611    fn kinds(ver: LuaVersion, src: &[u8]) -> Vec<i32> {
1612        let mut v = lex(ver, src);
1613        v.pop();
1614        v.into_iter().map(|t| t.kind).collect()
1615    }
1616
1617    /// Lex `src` and return the bytes of its single string-literal token.
1618    fn one_string(ver: LuaVersion, src: &[u8]) -> Vec<u8> {
1619        let toks = lex(ver, src);
1620        let str_tok = toks
1621            .iter()
1622            .find(|t| t.kind == TK_STRING)
1623            .expect("a string token");
1624        match &str_tok.value {
1625            TokenValue::Str(s) => s.as_bytes().to_vec(),
1626            _ => panic!("string token without Str payload"),
1627        }
1628    }
1629
1630    #[test]
1631    fn crlf_and_lfcr_pair_into_single_lines() {
1632        // Three logical lines joined by CRLF; the `+` lands on line 3, so a
1633        // lex error there must report line 3 (CRLF counts as ONE newline).
1634        let toks = lex(LuaVersion::V54, b"a\r\nb\r\n+");
1635        // a(name) b(name) +  EOS  -> the '+' is a single-byte token on line 3.
1636        assert_eq!(toks[0].kind, TK_NAME);
1637        assert_eq!(toks[1].kind, TK_NAME);
1638        assert_eq!(toks[2].kind, b'+' as i32);
1639        // LFCR also pairs.
1640        let toks2 = lex(LuaVersion::V54, b"a\n\rb");
1641        assert_eq!(toks2[0].kind, TK_NAME);
1642        assert_eq!(toks2[1].kind, TK_NAME);
1643        assert_eq!(toks2[2].kind, TK_EOS);
1644    }
1645
1646    #[test]
1647    fn crlf_line_number_attribution() {
1648        // The error message must carry line 3 for a malformed numeral there.
1649        let mut state = new_state().expect("state init");
1650        state.global_mut().lua_version = LuaVersion::V54;
1651        let source = state.intern_str(b"@t").unwrap();
1652        let src = b"\r\n\r\n0x".to_vec();
1653        let firstchar = src[0] as i32;
1654        let rest: Vec<u8> = src.iter().skip(1).copied().collect();
1655        let mut ls = empty_lexstate(source.clone(), LuaVersion::V54);
1656        set_input(&mut state, &mut ls, ZIO::from_bytes(rest), source, firstchar).unwrap();
1657        // `0x` with no hex digits is a malformed numeral on line 3.
1658        let err = loop {
1659            match next(&mut state, &mut ls) {
1660                Ok(()) if ls.t.kind == TK_EOS => panic!("expected a lex error"),
1661                Ok(()) => continue,
1662                Err(e) => break e,
1663            }
1664        };
1665        let msg = err.message_lossy();
1666        assert!(msg.contains(":3:"), "error should be on line 3, got: {msg}");
1667        assert!(msg.contains("malformed number"), "got: {msg}");
1668    }
1669
1670    #[test]
1671    fn hex_escape_decodes_to_bytes() {
1672        assert_eq!(one_string(LuaVersion::V54, br#""\x41\x42""#), b"AB");
1673        assert_eq!(one_string(LuaVersion::V54, br#""\x00\xff""#), b"\x00\xff");
1674    }
1675
1676    #[test]
1677    fn utf8_escape_encodes_codepoint() {
1678        assert_eq!(one_string(LuaVersion::V54, br#""\u{48}\u{49}""#), b"HI");
1679        // U+00E9 (é) → two UTF-8 bytes 0xC3 0xA9.
1680        assert_eq!(one_string(LuaVersion::V54, br#""\u{e9}""#), b"\xc3\xa9");
1681        // A 6-byte (non-strict) sequence is accepted up to 0x7FFFFFFF in 5.4.
1682        assert_eq!(
1683            one_string(LuaVersion::V54, br#""\u{7FFFFFFF}""#),
1684            b"\xFD\xBF\xBF\xBF\xBF\xBF"
1685        );
1686    }
1687
1688    #[test]
1689    fn decimal_escape_and_z_skip() {
1690        assert_eq!(one_string(LuaVersion::V54, br#""\65\66""#), b"AB");
1691        // \z swallows the following whitespace run (including newlines).
1692        assert_eq!(one_string(LuaVersion::V54, b"\"a\\z   \n\t b\""), b"ab");
1693    }
1694
1695    #[test]
1696    fn long_brackets_with_levels() {
1697        assert_eq!(one_string(LuaVersion::V54, b"[[ hello ]]"), b" hello ");
1698        assert_eq!(one_string(LuaVersion::V54, b"[==[ hi ]==]"), b" hi ");
1699        // A leading newline immediately after the open bracket is dropped.
1700        assert_eq!(one_string(LuaVersion::V54, b"[[\nx]]"), b"x");
1701        // An inner `]=]` that is not the matching close is kept as content.
1702        assert_eq!(one_string(LuaVersion::V54, b"[==[a]=]b]==]"), b"a]=]b");
1703    }
1704
1705    #[test]
1706    fn long_string_normalizes_newlines() {
1707        // CRLF inside a long string is normalized to a single \n.
1708        assert_eq!(one_string(LuaVersion::V54, b"[[a\r\nb]]"), b"a\nb");
1709    }
1710
1711    #[test]
1712    fn numeral_int_float_boundary() {
1713        // Integer literals → TK_INT with the exact i64; floats → TK_FLT.
1714        let dec = lex(LuaVersion::V54, b"3");
1715        assert_eq!(dec[0].kind, TK_INT);
1716        assert!(matches!(dec[0].value, TokenValue::Int(3)));
1717
1718        let hex = lex(LuaVersion::V54, b"0x10");
1719        assert_eq!(hex[0].kind, TK_INT);
1720        assert!(matches!(hex[0].value, TokenValue::Int(16)));
1721
1722        let flt = lex(LuaVersion::V54, b"3.0");
1723        assert_eq!(flt[0].kind, TK_FLT);
1724        assert!(matches!(flt[0].value, TokenValue::Float(f) if f == 3.0));
1725
1726        let expo = lex(LuaVersion::V54, b"1e2");
1727        assert_eq!(expo[0].kind, TK_FLT);
1728        assert!(matches!(expo[0].value, TokenValue::Float(f) if f == 100.0));
1729
1730        // A bare dot followed by digits is a float; a lone dot is the '.' token.
1731        let dotnum = lex(LuaVersion::V54, b".5");
1732        assert_eq!(dotnum[0].kind, TK_FLT);
1733    }
1734
1735    #[test]
1736    fn float_only_versions_widen_integer_literals() {
1737        // 5.1/5.2 have no integer subtype: every numeral lexes as a float.
1738        let v51 = lex(LuaVersion::V51, b"3");
1739        assert_eq!(v51[0].kind, TK_FLT);
1740        assert!(matches!(v51[0].value, TokenValue::Float(f) if f == 3.0));
1741
1742        let v52 = lex(LuaVersion::V52, b"42");
1743        assert_eq!(v52[0].kind, TK_FLT);
1744    }
1745
1746    #[test]
1747    fn version_gated_operators() {
1748        // `<<` is a 5.3+ token; on 5.4 it is one TK_SHL.
1749        assert_eq!(kinds(LuaVersion::V54, b"1 << 2"), vec![TK_INT, TK_SHL, TK_INT]);
1750        // On the float-only family it is NOT a token: two bare '<' bytes.
1751        assert_eq!(
1752            kinds(LuaVersion::V51, b"1 << 2"),
1753            vec![TK_FLT, b'<' as i32, b'<' as i32, TK_FLT]
1754        );
1755        // `//` floor-division: TK_IDIV on 5.4, two '/' on 5.1.
1756        assert_eq!(kinds(LuaVersion::V54, b"7 // 2"), vec![TK_INT, TK_IDIV, TK_INT]);
1757        assert_eq!(
1758            kinds(LuaVersion::V51, b"7 // 2"),
1759            vec![TK_FLT, b'/' as i32, b'/' as i32, TK_FLT]
1760        );
1761        // `::` label delimiter: TK_DBCOLON on 5.4, two ':' on 5.1.
1762        assert_eq!(kinds(LuaVersion::V54, b"::x::"), vec![TK_DBCOLON, TK_NAME, TK_DBCOLON]);
1763        assert_eq!(
1764            kinds(LuaVersion::V51, b"::x"),
1765            vec![b':' as i32, b':' as i32, TK_NAME]
1766        );
1767    }
1768
1769    #[test]
1770    fn version_gated_reserved_words() {
1771        // `goto` is a keyword on 5.2+ but a plain name on 5.1.
1772        assert_eq!(kinds(LuaVersion::V54, b"goto"), vec![TK_GOTO]);
1773        assert_eq!(kinds(LuaVersion::V51, b"goto"), vec![TK_NAME]);
1774        // `global` is never reserved — always a name.
1775        assert_eq!(kinds(LuaVersion::V55, b"global"), vec![TK_NAME]);
1776        assert_eq!(kinds(LuaVersion::V54, b"global"), vec![TK_NAME]);
1777        // An ordinary keyword still maps to its TK_* on every version.
1778        assert_eq!(kinds(LuaVersion::V54, b"while"), vec![TK_WHILE]);
1779        assert_eq!(kinds(LuaVersion::V51, b"while"), vec![TK_WHILE]);
1780    }
1781
1782    #[test]
1783    fn multichar_symbols_and_dots() {
1784        assert_eq!(kinds(LuaVersion::V54, b"=="), vec![TK_EQ]);
1785        assert_eq!(kinds(LuaVersion::V54, b"~="), vec![TK_NE]);
1786        assert_eq!(kinds(LuaVersion::V54, b"<="), vec![TK_LE]);
1787        assert_eq!(kinds(LuaVersion::V54, b">="), vec![TK_GE]);
1788        assert_eq!(kinds(LuaVersion::V54, b".."), vec![TK_CONCAT]);
1789        assert_eq!(kinds(LuaVersion::V54, b"..."), vec![TK_DOTS]);
1790        // A lone dot is its single-byte token.
1791        assert_eq!(kinds(LuaVersion::V54, b"."), vec![b'.' as i32]);
1792    }
1793
1794    #[test]
1795    fn comments_emit_no_tokens() {
1796        // Short comment to end of line, then a name.
1797        assert_eq!(kinds(LuaVersion::V54, b"-- a comment\nx"), vec![TK_NAME]);
1798        // Long comment.
1799        assert_eq!(kinds(LuaVersion::V54, b"--[[ block\ncomment ]] y"), vec![TK_NAME]);
1800    }
1801
1802    #[test]
1803    fn empty_input_is_just_eos() {
1804        let toks = lex(LuaVersion::V54, b"");
1805        assert_eq!(toks.len(), 1);
1806        assert_eq!(toks[0].kind, TK_EOS);
1807    }
1808
1809    #[test]
1810    fn peek_maps_byte_and_eoz() {
1811        // The internal dispatch shape: a byte maps to Peek::Byte, EOZ to Peek::Eoz.
1812        let mut state = new_state().unwrap();
1813        let source = state.intern_str(b"@t").unwrap();
1814        let mut ls = empty_lexstate(source, LuaVersion::V54);
1815        ls.current = b'=' as i32;
1816        assert!(matches!(peek(&ls), Peek::Byte(b'=')));
1817        ls.current = EOZ;
1818        assert!(matches!(peek(&ls), Peek::Eoz));
1819    }
1820
1821    #[test]
1822    fn zio_yields_bytes_then_eoz() {
1823        let mut state = new_state().expect("state init");
1824        let mut z = ZIO::from_bytes(b"ab".to_vec());
1825        assert_eq!(z.getc(&mut state).unwrap(), b'a' as i32);
1826        assert_eq!(z.getc(&mut state).unwrap(), b'b' as i32);
1827        assert_eq!(z.getc(&mut state).unwrap(), EOZ);
1828        assert_eq!(z.getc(&mut state).unwrap(), EOZ);
1829        // An empty source is immediately EOZ.
1830        let mut empty = ZIO::from_bytes(Vec::new());
1831        assert_eq!(empty.getc(&mut state).unwrap(), EOZ);
1832    }
1833
1834    #[test]
1835    fn lexbuffer_extraction_helpers() {
1836        let mut b = LexBuffer::new();
1837        for &c in b"\"hello\"" {
1838            b.push_byte(c);
1839        }
1840        assert_eq!(b.trim_ends(1), b"hello");
1841        assert_eq!(b.to_owned_text(), b"\"hello\"");
1842        // Too-short buffer for the requested delimiter width → empty content.
1843        let mut tiny = LexBuffer::new();
1844        tiny.push_byte(b'"');
1845        assert_eq!(tiny.trim_ends(1), b"");
1846        // Trailing-NUL trim drops exactly one sentinel.
1847        let mut num = LexBuffer::new();
1848        for &c in b"123\0" {
1849            num.push_byte(c);
1850        }
1851        assert_eq!(num.without_trailing_nul(), b"123");
1852    }
1853}
1854
1855// ──────────────────────────────────────────────────────────────────────────────
1856// PORT STATUS
1857//   source:        originally ported from src/llex.c + src/llex.h; the C
1858//                  correspondence has since been GRADUATED away (see GRADUATED.md
1859//                  and the module-level doc). This file no longer tracks the C
1860//                  line-by-line — it is idiomatic Rust guarded by the oracle.
1861//   target_crate:  lua-lex
1862//   confidence:    high
1863//   todos:         1  (ZIO/LexBuffer move to lua_vm::zio — separate refactor)
1864//   port_notes:    0  (C-correspondence crutches removed in idiomatization S1)
1865//   unsafe_blocks: 0   (must be 0 outside explicit unsafe-budget crates)
1866//   notes:         Idiomatized (Sprint 1, P1a): byte cursor is a single-cursor
1867//                  chunk reader; numeral parsing returns Option not a C status +
1868//                  out-param; token text uses named LexBuffer extraction methods;
1869//                  the scan loop dispatches on an internal Peek enum while the
1870//                  emitted token kind stays i32 (TK_*) as the lua-parse boundary.
1871//                  The oracle that now guards behaviour: bytecode parity (token
1872//                  stream → identical luac -l -l), the multiversion_oracle, and
1873//                  the literals.lua / errors.lua line-and-message tests. Numeric
1874//                  literal parsing delegates to lua_vm::object::str2num. Do NOT
1875//                  reach for llex.c to debug this file — see GRADUATED.md.
1876// ──────────────────────────────────────────────────────────────────────────────