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