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/// Pre-intern `_ENV` and every reserved word.
593///
594/// C's `luaX_init` is load-bearing for two reasons that don't apply to this
595/// port: it tags each reserved-word `TString` with an `extra` index so
596/// `read_name` in `llex.c` can recognize keywords in O(1) by pointer/field
597/// check, and it calls `luaC_fix` to pin those strings permanently so the
598/// tag survives for the process lifetime. This port's keyword recognition
599/// (see the reserved-word lookup in `next`, below) instead matches the
600/// freshly scanned byte slice directly against [`LUAX_TOKENS`], so it never
601/// depends on any string created here being the "same" object, tagged, or even
602/// still alive — a byte-identical re-intern after collection works exactly
603/// as well. And unlike `luaC_fix`, this function does not durably root
604/// anything: the returned `GcRef`s are dropped immediately, so any string
605/// it interns is just as collectible afterward as if `init` had never run.
606///
607/// So this function has no observable lexical/parse effect and no startup
608/// correctness dependency: every reserved word is re-interned anyway by
609/// [`new_string`] the first time it is actually scanned, and `_ENV` is
610/// re-interned by every [`set_input`] call. (It is not literally side-effect
611/// free — it allocates the interned strings, charges the GC, and sets
612/// `gc_check_needed` like any other interning — but nothing about lexing,
613/// parsing, or VM startup depends on those effects having happened.) It has
614/// zero call sites and is safe to leave uncalled; despite its name, no VM
615/// startup path requires it.
616pub fn init(state: &mut LuaState) -> Result<(), LuaError> {
617    let _e = intern_str_stub(state, LUA_ENV)?;
618
619    for i in 0..NUM_RESERVED {
620        let ts = intern_str_stub(state, LUAX_TOKENS[i])?;
621        let _ = ts;
622    }
623
624    Ok(())
625}
626
627/// Initialise `ls` for lexing a new chunk from stream `z`.
628pub fn set_input(
629    state: &mut LuaState,
630    ls: &mut LexState,
631    z: ZIO,
632    source: GcRef<LuaString>,
633    firstchar: i32,
634) -> Result<(), LuaError> {
635    ls.t = Token::new(0);
636    ls.current = firstchar;
637    ls.lookahead = Token::eos();
638    ls.z = z;
639    ls.fs = None;
640    ls.linenumber = 1;
641    ls.lastline = 1;
642    ls.source = source;
643    ls.version = state.global().lua_version;
644    ls.envn = intern_str_stub(state, LUA_ENV)?;
645    ls.buff.resize(state, LUA_MIN_BUFFER)?;
646    Ok(())
647}
648
649/// Create (or retrieve) a Lua string and anchor it in the parser's GC-protection
650/// table `ls.h` so it cannot be collected before the end of compilation.
651///
652/// Also internalises long strings so that each unique content has exactly one
653/// copy in memory.  The table `ls.h` is used as a set: the string is both the
654/// key and the value.
655pub(crate) fn new_string(
656    state: &mut LuaState,
657    ls: &mut LexState,
658    bytes: &[u8],
659) -> Result<GcRef<LuaString>, LuaError> {
660    // The `long_str_anchor` map dedups so a second occurrence of the same
661    // literal in the chunk returns the originally-created string; identity is
662    // determined by the `Rc` allocation. Short strings already share identity
663    // via the global pool; long strings (>40 bytes) need this session-level map.
664    if let Some(existing) = ls.long_str_anchor.get(bytes) {
665        return Ok(existing.clone());
666    }
667    let ts = intern_str_stub(state, bytes)?;
668    ls.long_str_anchor.insert(bytes.to_vec(), ts.clone());
669    Ok(ts)
670}
671
672// ── Public advance / lookahead ─────────────────────────────────────────────────
673
674/// Consume the current token; load the next one from the stream.
675///
676/// If a lookahead token was set, it becomes the current token without re-reading
677/// from the stream.
678pub fn next(state: &mut LuaState, ls: &mut LexState) -> Result<(), LuaError> {
679    ls.lastline = ls.linenumber;
680
681    if ls.lookahead.kind != TK_EOS {
682        // Clone to avoid borrow conflict; LuaString inside TokenValue is GcRef (Rc).
683        ls.t = ls.lookahead.clone();
684        ls.lookahead = Token::eos();
685    } else {
686        let mut val = TokenValue::None;
687        let kind = llex(state, ls, &mut val)?;
688        ls.t = Token { kind, value: val };
689    }
690    Ok(())
691}
692
693/// Peek at the next token without consuming the current one.
694///
695/// The lookahead token is cached in `ls.lookahead` and returned.  Only one
696/// token of lookahead is supported; calling this twice without an intervening
697/// [`next`] is a logic error (asserted in debug builds).
698pub fn lookahead(state: &mut LuaState, ls: &mut LexState) -> Result<i32, LuaError> {
699    debug_assert!(
700        ls.lookahead.kind == TK_EOS,
701        "luaX_lookahead: lookahead already set"
702    );
703
704    let mut val = TokenValue::None;
705    let kind = llex(state, ls, &mut val)?;
706    ls.lookahead = Token { kind, value: val };
707
708    Ok(ls.lookahead.kind)
709}
710
711// ── Private lexer helpers ──────────────────────────────────────────────────────
712
713/// If the current character equals `c`, advance and return `true`.
714fn check_next1(state: &mut LuaState, ls: &mut LexState, c: i32) -> Result<bool, LuaError> {
715    if ls.current == c {
716        advance(state, ls)?;
717        Ok(true)
718    } else {
719        Ok(false)
720    }
721}
722
723/// If the current character is either of the two bytes in `set`, save-and-advance
724/// and return `true`.
725fn check_next2(ls: &mut LexState, state: &mut LuaState, set: &[u8; 2]) -> Result<bool, LuaError> {
726    if ls.current == set[0] as i32 || ls.current == set[1] as i32 {
727        save_and_next(ls, state)?;
728        Ok(true)
729    } else {
730        Ok(false)
731    }
732}
733
734/// Increment the line counter and consume the newline sequence.
735///
736/// Handles `\n`, `\r`, `\n\r`, and `\r\n`: a second newline byte is only
737/// consumed when it differs from the first, so a `\n\n` (two blank lines)
738/// is not collapsed into one.
739fn inc_line_number(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
740    debug_assert!(curr_is_newline(ls), "inc_line_number: not at a newline");
741
742    let old = ls.current;
743    advance(state, ls)?;
744
745    if curr_is_newline(ls) && ls.current != old {
746        advance(state, ls)?;
747    }
748
749    ls.linenumber += 1;
750    if ls.linenumber >= i32::MAX {
751        return Err(lex_error(ls, b"chunk has too many lines", 0));
752    }
753    Ok(())
754}
755
756/// Scan a numeric literal (integer or float, decimal or hex).
757///
758/// The caller may have already read an initial dot.  Accepts the pattern:
759/// `%d(%x|%.|(Ee[+-]?))*` or `0[Xx](%x|%.|(Pp[+-]?))*`.
760///
761/// Returns `TK_INT` for integers, `TK_FLT` for floats.
762fn read_numeral(
763    state: &mut LuaState,
764    ls: &mut LexState,
765    seminfo: &mut TokenValue,
766) -> Result<i32, LuaError> {
767    let mut expo: &[u8; 2] = b"Ee";
768
769    let first = ls.current;
770
771    debug_assert!(is_digit(ls.current), "read_numeral: not at a digit");
772
773    save_and_next(ls, state)?;
774
775    let is_hex = first == b'0' as i32 && check_next2(ls, state, b"xX")?;
776
777    // Lua 5.1 has no hexadecimal-aware number scanner: it never recognizes a
778    // binary (`Pp`) exponent, a signed binary exponent, or a fractional `.`
779    // inside a hex literal. Its scanner reads decimal digits/`.`, an optional
780    // `Ee` exponent, then swallows the rest of the alphanumeric run (the hex
781    // body) and hands the whole token to `strtod`/`strtoul`. So:
782    //   * `0x1p4`  -> the `p4` rides the alphanumeric tail -> strtod -> 16
783    //   * `0x1p-2` -> the tail stops at `-`, leaving `0x1p` -> malformed
784    //   * `0x1.8p0`-> the main loop stops at `.`, leaving `0x1` (=1); `.8p0`
785    //                 then lexes as a fresh, malformed decimal numeral.
786    // 5.2+ added the hex-aware scanner (`Pp` exponent + signed exponent +
787    // fractional `.`), so the hex-special path below is gated off for V51.
788    let is_v51 = matches!(state.global().lua_version, lua_types::LuaVersion::V51);
789    let hex_aware = is_hex && !is_v51;
790    if hex_aware {
791        expo = b"Pp";
792    }
793
794    // For a 5.1 hex literal the digit-scanning main loop is skipped entirely so
795    // its `Ee`-exponent probe cannot mistake a hex `e`/`E` digit for a decimal
796    // exponent (`0x1e2` is 482, not `0x1` × 10^2); the whole hex body rides the
797    // alphanumeric tail below, exactly as 5.1's scanner does.
798    let scan_digits = !(is_hex && is_v51);
799    while scan_digits {
800        if check_next2(ls, state, expo)? {
801            check_next2(ls, state, b"-+")?;
802        } else if is_xdigit(ls.current) || (ls.current == b'.' as i32 && (!is_hex || hex_aware)) {
803            save_and_next(ls, state)?;
804        } else {
805            break;
806        }
807    }
808
809    // Numeral "touching a letter" handling. 5.2+ append a single trailing letter
810    // to force a malformed-number error (the alphanumeric run after it lexes
811    // separately). Lua 5.1's scanner instead swallows the *entire* alphanumeric
812    // (and `_`) run into the numeral, so a malformed 5.1 numeral reports the full
813    // run in its `near '...'` snippet (`.8p0`, `3xyz`), not just its first letter.
814    if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
815        while is_lalnum(ls.current) {
816            save_and_next(ls, state)?;
817        }
818    } else if is_lalpha(ls.current) {
819        save_and_next(ls, state)?;
820    }
821
822    save(ls, state, 0)?;
823
824    match parse_numeral(ls.buff.without_trailing_nul()) {
825        None => Err(lex_error(ls, b"malformed number", TK_FLT)),
826        Some(lua_types::LuaValue::Int(i)) => {
827            if is_float_only(state) {
828                // The float-only family (5.1/5.2) has no integer subtype: every
829                // numeral becomes a float. A hex integer literal is read through
830                // C's `strtoul(.., 16)`, an *unsigned* 64-bit conversion, so an
831                // overflowing hex literal (top bit set) becomes a large positive
832                // double — `0xFFFFFFFFFFFFFFFF` is `1.844674407371e+19`, not -1.
833                // `str2int` wraps into `i64`, so reinterpret the bit pattern as
834                // `u64` before widening; for any non-overflowing literal this is
835                // identical to `i as f64`.
836                let widened = if is_hex { (i as u64) as f64 } else { i as f64 };
837                *seminfo = TokenValue::Float(widened);
838                Ok(TK_FLT)
839            } else {
840                *seminfo = TokenValue::Int(i);
841                Ok(TK_INT)
842            }
843        }
844        Some(lua_types::LuaValue::Float(f)) => {
845            *seminfo = TokenValue::Float(f);
846            Ok(TK_FLT)
847        }
848        Some(other) => unreachable!("parse_numeral yielded non-numeric value: {other:?}"),
849    }
850}
851
852/// Scan a `[=*[` or `]=*]` sequence; leave the last bracket as current char.
853///
854/// Returns:
855/// - `count + 2` if well-formed (where `count` is the number of `=` signs),
856/// - `1` if a single bracket with no `=`s and no second bracket,
857/// - `0` if malformed (e.g. `[==` with no closing bracket).
858fn skip_sep(state: &mut LuaState, ls: &mut LexState) -> Result<usize, LuaError> {
859    let mut count: usize = 0;
860    let s = ls.current;
861    debug_assert!(
862        s == b'[' as i32 || s == b']' as i32,
863        "skip_sep: not at bracket"
864    );
865
866    save_and_next(ls, state)?;
867
868    while ls.current == b'=' as i32 {
869        save_and_next(ls, state)?;
870        count += 1;
871    }
872
873    if ls.current == s {
874        Ok(count + 2)
875    } else if count == 0 {
876        Ok(1)
877    } else {
878        Ok(0)
879    }
880}
881
882/// Scan a long string or long comment delimited by `[=*[` … `]=*]`.
883///
884/// `seminfo` is `Some` when reading a string literal; `None` when skipping a
885/// long comment.  When `None`, buffer contents are discarded on each newline
886/// to avoid wasting memory.
887fn read_long_string(
888    state: &mut LuaState,
889    ls: &mut LexState,
890    seminfo: Option<&mut TokenValue>,
891    sep: usize,
892) -> Result<(), LuaError> {
893    let line = ls.linenumber;
894
895    save_and_next(ls, state)?;
896
897    if curr_is_newline(ls) {
898        inc_line_number(ls, state)?;
899    }
900
901    // is_string: whether we are reading a string (true) or a comment (false)
902    let is_string = seminfo.is_some();
903
904    loop {
905        match ls.current {
906            c if c == EOZ => {
907                let what: &[u8] = if is_string { b"string" } else { b"comment" };
908                let mut msg: Vec<u8> = Vec::new();
909                msg.extend_from_slice(b"unfinished long ");
910                msg.extend_from_slice(what);
911                // The "(starting at line N)" clause was added in 5.3. The
912                // float-only family (5.1/5.2) reports the bare
913                // "unfinished long string"/"unfinished long comment".
914                if !is_float_only(state) {
915                    msg.extend_from_slice(b" (starting at line ");
916                    let _ = write!(&mut msg, "{}", line);
917                    msg.push(b')');
918                }
919                return Err(lex_error(ls, &msg, TK_EOS));
920            }
921            c if c == b']' as i32 => {
922                let s = skip_sep(state, ls)?;
923                if s == sep {
924                    save_and_next(ls, state)?;
925                    break;
926                }
927                // else: the ']' sequence wasn't the closing delimiter; continue
928            }
929            c if c == b'\n' as i32 || c == b'\r' as i32 => {
930                save(ls, state, b'\n' as i32)?;
931                inc_line_number(ls, state)?;
932                if !is_string {
933                    ls.buff.clear();
934                }
935            }
936            _ => {
937                if is_string {
938                    save_and_next(ls, state)?;
939                } else {
940                    advance(state, ls)?;
941                }
942            }
943        }
944    }
945
946    if let Some(out) = seminfo {
947        // The buffer holds `[=*[` + content + `]=*]`, each delimiter `sep` bytes
948        // wide; strip both to recover the content.
949        let content = ls.buff.trim_ends(sep);
950        let ts = new_string(state, ls, &content)?;
951        *out = TokenValue::Str(ts);
952    }
953    Ok(())
954}
955
956/// Check `c` is non-zero (truthy); if not, save the current char and raise a
957/// string-escape error.
958fn esc_check(
959    state: &mut LuaState,
960    ls: &mut LexState,
961    ok: bool,
962    msg: &[u8],
963) -> Result<(), LuaError> {
964    if !ok {
965        if ls.current != EOZ {
966            save_and_next(ls, state)?;
967        }
968        return Err(lex_error(ls, msg, TK_STRING));
969    }
970    Ok(())
971}
972
973/// Build a Lua 5.2-family escape-sequence error whose `near '...'` snippet is
974/// the backslash plus the offending escape characters (`'\j'`, `'\256'`,
975/// `'\xZ'`), not the buffer collected so far.
976///
977/// This mirrors 5.2's `escerror`, which resets the token buffer and saves `'\\'`
978/// followed by the escape characters before raising. (5.3+ leaves the whole
979/// buffer in place, so its snippet keeps the opening quote and prior content —
980/// that path stays on [`esc_check`].) Trailing `EOZ` markers in `chars` are
981/// dropped, matching `escerror`'s `c[i] != EOZ` guard.
982fn esc_error_legacy(ls: &mut LexState, chars: &[i32], msg: &[u8]) -> LuaError {
983    ls.buff.clear();
984    ls.buff.push_byte(b'\\');
985    for &c in chars {
986        if c == EOZ {
987            break;
988        }
989        ls.buff.push_byte(c as u8);
990    }
991    lex_error(ls, msg, TK_STRING)
992}
993
994/// Save-and-advance, then verify the new current char is a hex digit; return
995/// its numeric value (0-15).
996///
997/// On failure the `near '...'` snippet is version-gated. 5.2 reports `\x` plus
998/// the characters read so far (`'\xZ'`, `'\x1Z'`), built by resetting the buffer
999/// (mirroring `escerror`); `chars` carries the hex characters already consumed by
1000/// the enclosing `\x` escape so the snippet can be rebuilt. 5.3+ report the whole
1001/// buffer-so-far via the save-and-next inside `esc_check`. (5.2 has no `\u`, so a
1002/// hex-digit error here always belongs to a `\x` escape.)
1003fn get_hexa(state: &mut LuaState, ls: &mut LexState, chars: &mut Vec<i32>) -> Result<u32, LuaError> {
1004    save_and_next(ls, state)?;
1005    if !is_xdigit(ls.current) {
1006        if matches!(state.global().lua_version, lua_types::LuaVersion::V52) {
1007            let mut esc: Vec<i32> = Vec::with_capacity(chars.len() + 2);
1008            esc.push(b'x' as i32);
1009            esc.extend_from_slice(chars);
1010            esc.push(ls.current);
1011            return Err(esc_error_legacy(ls, &esc, b"hexadecimal digit expected"));
1012        }
1013        esc_check(state, ls, false, b"hexadecimal digit expected")?;
1014    }
1015    chars.push(ls.current);
1016    Ok(hex_value_stub(ls.current))
1017}
1018
1019/// Scan a `\xNN` hex escape; return the decoded byte value.
1020fn read_hex_esc(state: &mut LuaState, ls: &mut LexState) -> Result<u32, LuaError> {
1021    let mut chars: Vec<i32> = Vec::with_capacity(2);
1022    let r = get_hexa(state, ls, &mut chars)?;
1023    let r = (r << 4) + get_hexa(state, ls, &mut chars)?;
1024    ls.buff.truncate_by(2);
1025    Ok(r)
1026}
1027
1028/// Scan a `\u{XXXXXX}` UTF-8 escape; return the Unicode codepoint.
1029fn read_utf8_esc(state: &mut LuaState, ls: &mut LexState) -> Result<u32, LuaError> {
1030    let mut i: usize = 4;
1031
1032    save_and_next(ls, state)?;
1033
1034    esc_check(state, ls, ls.current == b'{' as i32, b"missing '{'")?;
1035
1036    // `\u{...}` exists only on 5.3+, so the 5.2 reset-buffer error branch in
1037    // `get_hexa` is never taken from here; the accumulator is unused.
1038    let mut hex_chars: Vec<i32> = Vec::new();
1039    let mut r = get_hexa(state, ls, &mut hex_chars)?;
1040
1041    // The codepoint upper bound is version-gated, and the digit-accumulation
1042    // order differs between the families:
1043    //   * 5.3: accumulate the digit FIRST (`r = (r<<4)+digit`), THEN bound the
1044    //     running value at 0x10FFFF.
1045    //   * 5.4 / 5.5: bound BEFORE the shift (`r <= 0x7FFFFFFF >> 4`), then
1046    //     accumulate — allowing codepoints up to 0x7FFFFFFF.
1047    // The order (check-before-shift vs shift-before-check) is load-bearing: it
1048    // also determines how many digits land in the `near '...'` snippet of the
1049    // "UTF-8 value too large" error, so a too-large `\u{...}` reports the same
1050    // message and offset as the matching reference binary.
1051    let is_v53 = matches!(state.global().lua_version, lua_types::LuaVersion::V53);
1052
1053    loop {
1054        save_and_next(ls, state)?;
1055        if !is_xdigit(ls.current) {
1056            break;
1057        }
1058        i += 1;
1059        if is_v53 {
1060            r = (r << 4) + hex_value_stub(ls.current);
1061            esc_check(state, ls, r <= 0x10_FFFF, b"UTF-8 value too large")?;
1062        } else {
1063            esc_check(
1064                state,
1065                ls,
1066                r <= (0x7FFF_FFFFu32 >> 4),
1067                b"UTF-8 value too large",
1068            )?;
1069            r = (r << 4) + hex_value_stub(ls.current);
1070        }
1071    }
1072
1073    esc_check(state, ls, ls.current == b'}' as i32, b"missing '}'")?;
1074
1075    advance(state, ls)?;
1076
1077    ls.buff.truncate_by(i);
1078
1079    Ok(r)
1080}
1081
1082/// Scan `\u{...}` and append the UTF-8 encoding of the codepoint to the buffer.
1083fn utf8_esc(state: &mut LuaState, ls: &mut LexState) -> Result<(), LuaError> {
1084    let codepoint = read_utf8_esc(state, ls)?;
1085
1086    let encoded = utf8_encode_stub(codepoint);
1087
1088    for &b in &encoded {
1089        save(ls, state, b as i32)?;
1090    }
1091    Ok(())
1092}
1093
1094/// Scan a decimal escape `\ddd` (up to 3 digits); return the byte value.
1095fn read_dec_esc(state: &mut LuaState, ls: &mut LexState) -> Result<u32, LuaError> {
1096    let mut i: usize = 0;
1097    let mut r: u32 = 0;
1098    let mut digits: Vec<i32> = Vec::with_capacity(3);
1099
1100    while i < 3 && is_digit(ls.current) {
1101        r = 10 * r + (ls.current as u32 - b'0' as u32);
1102        digits.push(ls.current);
1103        save_and_next(ls, state)?;
1104        i += 1;
1105    }
1106
1107    if r > u8::MAX as u32 {
1108        // The "too large" message and `near '...'` snippet are version-gated:
1109        //   * 5.1: spelled "escape sequence too large"; its scanner saves
1110        //     neither the backslash nor the digits, so the snippet is just the
1111        //     opening quote (`'"'`). The shared decode path *did* buffer them
1112        //     here, so trim the backslash + `i` digits back off before raising.
1113        //   * 5.2: "decimal escape too large", snippet is `\` + the digits
1114        //     (`'\256'`), built by resetting the buffer (see `esc_error_legacy`).
1115        //   * 5.3+: "decimal escape too large", snippet is the buffer collected
1116        //     so far (opening quote + content + `\` + digits + the trailing char
1117        //     `esc_check` save-and-nexts on).
1118        let version = state.global().lua_version;
1119        match version {
1120            lua_types::LuaVersion::V51 => {
1121                ls.buff.truncate_by(i + 1);
1122                return Err(lex_error(ls, b"escape sequence too large", TK_STRING));
1123            }
1124            lua_types::LuaVersion::V52 => {
1125                return Err(esc_error_legacy(ls, &digits, b"decimal escape too large"));
1126            }
1127            _ => {
1128                esc_check(state, ls, false, b"decimal escape too large")?;
1129            }
1130        }
1131    }
1132
1133    ls.buff.truncate_by(i);
1134    Ok(r)
1135}
1136
1137/// Scan a short (single/double-quoted) string literal.
1138///
1139/// Escape-sequence handling decodes a byte and then dispatches via the local
1140/// [`EscapeResult`] enum.
1141fn read_string(
1142    state: &mut LuaState,
1143    ls: &mut LexState,
1144    del: i32,
1145    seminfo: &mut TokenValue,
1146) -> Result<(), LuaError> {
1147    // What the escape-sequence handler does after decoding a byte.
1148    //
1149    // ReadSave:  advance, remove '\' from buffer, save decoded byte.
1150    // OnlySave:  remove '\' from buffer, save decoded byte (no advance).
1151    // NoSave:    nothing (just break from the escape case).
1152    enum EscapeResult {
1153        ReadSave(i32),
1154        OnlySave(i32),
1155        NoSave,
1156    }
1157
1158    save_and_next(ls, state)?;
1159
1160    while ls.current != del {
1161        match ls.current {
1162            c if c == EOZ => {
1163                return Err(lex_error(ls, b"unfinished string", TK_EOS));
1164            }
1165            c if c == b'\n' as i32 || c == b'\r' as i32 => {
1166                return Err(lex_error(ls, b"unfinished string", TK_STRING));
1167            }
1168            c if c == b'\\' as i32 => {
1169                save_and_next(ls, state)?;
1170
1171                // Lua 5.1's lexer does NOT recognize `\x`, `\z`, or `\u`, and it
1172                // does NOT raise on an unknown escape. For any escape char outside
1173                // the known set, the 5.1 lexer silently drops the backslash and
1174                // keeps the next character verbatim (`"\x41"` → bytes `x41`,
1175                // `"\z"` → `z`, `"\q"` → `q`). Decimal escapes (`\ddd`) and the
1176                // standard letter/quote/newline escapes still work. Verified
1177                // against lua5.1.5; see specs/followup/5.1-roster-syntax.md §2.
1178                let is_v51 = matches!(state.global().lua_version, lua_types::LuaVersion::V51);
1179                // The `\u{...}` escape is a 5.3 addition. 5.1 has no `\u` at all
1180                // (silently drops the backslash); 5.2 added `\x` and `\z` but NOT
1181                // `\u`, so on the float-only family `\u` is an invalid escape.
1182                let has_u_escape = !is_float_only(state);
1183
1184                // Inner switch on the escape character
1185                let esc = match ls.current {
1186                    c if c == b'a' as i32 => EscapeResult::ReadSave(b'\x07' as i32),
1187                    c if c == b'b' as i32 => EscapeResult::ReadSave(b'\x08' as i32),
1188                    c if c == b'f' as i32 => EscapeResult::ReadSave(b'\x0C' as i32),
1189                    c if c == b'n' as i32 => EscapeResult::ReadSave(b'\n' as i32),
1190                    c if c == b'r' as i32 => EscapeResult::ReadSave(b'\r' as i32),
1191                    c if c == b't' as i32 => EscapeResult::ReadSave(b'\t' as i32),
1192                    c if c == b'v' as i32 => EscapeResult::ReadSave(b'\x0B' as i32),
1193                    c if c == b'x' as i32 && !is_v51 => {
1194                        let decoded = read_hex_esc(state, ls)?;
1195                        EscapeResult::ReadSave(decoded as i32)
1196                    }
1197                    c if c == b'u' as i32 && has_u_escape => {
1198                        utf8_esc(state, ls)?;
1199                        EscapeResult::NoSave
1200                    }
1201                    c if c == b'\n' as i32 || c == b'\r' as i32 => {
1202                        inc_line_number(ls, state)?;
1203                        EscapeResult::OnlySave(b'\n' as i32)
1204                    }
1205                    c if c == b'\\' as i32 || c == b'"' as i32 || c == b'\'' as i32 => {
1206                        EscapeResult::ReadSave(c)
1207                    }
1208                    c if c == EOZ => EscapeResult::NoSave,
1209                    c if c == b'z' as i32 && !is_v51 => {
1210                        ls.buff.truncate_by(1);
1211                        advance(state, ls)?;
1212                        while is_space(ls.current) {
1213                            if curr_is_newline(ls) {
1214                                inc_line_number(ls, state)?;
1215                            } else {
1216                                advance(state, ls)?;
1217                            }
1218                        }
1219                        EscapeResult::NoSave
1220                    }
1221                    c if is_v51 && !is_digit(c) => {
1222                        // 5.1 unknown escape: drop the backslash, emit the char.
1223                        EscapeResult::ReadSave(c)
1224                    }
1225                    _ => {
1226                        if !is_digit(ls.current) {
1227                            // 5.2 reports the invalid escape as `\` + the offending
1228                            // char (`'\j'`, `'\u'`) by resetting the buffer; 5.3+
1229                            // report the whole buffer-so-far (`'"\j'`) via the
1230                            // save-and-next inside `esc_check`.
1231                            if matches!(state.global().lua_version, lua_types::LuaVersion::V52) {
1232                                return Err(esc_error_legacy(
1233                                    ls,
1234                                    &[ls.current],
1235                                    b"invalid escape sequence",
1236                                ));
1237                            }
1238                            esc_check(state, ls, false, b"invalid escape sequence")?;
1239                        }
1240                        let decoded = read_dec_esc(state, ls)?;
1241                        EscapeResult::OnlySave(decoded as i32)
1242                    }
1243                };
1244
1245                match esc {
1246                    EscapeResult::ReadSave(c) => {
1247                        advance(state, ls)?;
1248                        ls.buff.truncate_by(1);
1249                        save(ls, state, c)?;
1250                    }
1251                    EscapeResult::OnlySave(c) => {
1252                        ls.buff.truncate_by(1);
1253                        save(ls, state, c)?;
1254                    }
1255                    EscapeResult::NoSave => {}
1256                }
1257            }
1258            _ => {
1259                save_and_next(ls, state)?;
1260            }
1261        }
1262    }
1263
1264    save_and_next(ls, state)?;
1265
1266    // The buffer holds the opening quote + content + closing quote; strip the
1267    // one-byte delimiter from each end.
1268    let content = ls.buff.trim_ends(1);
1269    let ts = new_string(state, ls, &content)?;
1270    *seminfo = TokenValue::Str(ts);
1271    Ok(())
1272}
1273
1274/// Whether the active version is the float-only legacy family (5.1/5.2), which
1275/// lacks the 5.3 integer operators (`//`, `<<`, `>>`, and the bitwise binops).
1276fn is_float_only(state: &LuaState) -> bool {
1277    matches!(
1278        state.global().lua_version,
1279        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1280    )
1281}
1282
1283/// The lexer's view of the current input character.
1284///
1285/// `ls.current` is stored as `i32` (a byte, or [`EOZ`] = `-1`) at the stream
1286/// boundary; this enum is the lexer's *internal* dispatch shape so the main
1287/// scan loop can `match` on byte literals (`Byte(b'=')`) and on end-of-stream
1288/// (`Eoz`) directly instead of an `i32` guard chain. It does not cross the
1289/// public boundary: scanned tokens are still reported as `TK_*` / ASCII `i32`.
1290enum Peek {
1291    Byte(u8),
1292    Eoz,
1293}
1294
1295/// Classify [`LexState::current`] into the internal [`Peek`] dispatch shape.
1296fn peek(ls: &LexState) -> Peek {
1297    match u8::try_from(ls.current) {
1298        Ok(b) => Peek::Byte(b),
1299        Err(_) => Peek::Eoz,
1300    }
1301}
1302
1303/// Core lexer dispatch: consume and return the next raw token kind.
1304///
1305/// The heart of the lexer: a scan loop that classifies the current character
1306/// (via [`Peek`]) and dispatches to the appropriate scanner. Single-character
1307/// tokens are returned as their ASCII `i32`; multi-character and reserved-word
1308/// tokens as the `TK_*` constants.
1309fn llex(
1310    state: &mut LuaState,
1311    ls: &mut LexState,
1312    seminfo: &mut TokenValue,
1313) -> Result<i32, LuaError> {
1314    ls.buff.clear();
1315
1316    loop {
1317        match peek(ls) {
1318            Peek::Byte(b'\n' | b'\r') => {
1319                inc_line_number(ls, state)?;
1320                // Shebang handling: the reference loader strips a leading '#'
1321                // line (Unix shebang). Our test harness prepends a global-setup
1322                // preamble to every official test, so the script's '#' line is
1323                // not at byte zero. Apply the same rule at any token-scan line
1324                // start: treat a line whose first character is '#' as a
1325                // single-line comment. This sits in the dispatch loop (not
1326                // inc_line_number) so it does not affect newlines inside
1327                // long-bracket strings.
1328                if ls.current == b'#' as i32 {
1329                    while !curr_is_newline(ls) && ls.current != EOZ {
1330                        advance(state, ls)?;
1331                    }
1332                }
1333            }
1334
1335            Peek::Byte(b' ' | b'\x0C' | b'\t' | b'\x0B') => {
1336                advance(state, ls)?;
1337            }
1338
1339            Peek::Byte(b'-') => {
1340                advance(state, ls)?;
1341                if ls.current != b'-' as i32 {
1342                    return Ok(b'-' as i32);
1343                }
1344                advance(state, ls)?;
1345
1346                if ls.current == b'[' as i32 {
1347                    let sep = skip_sep(state, ls)?;
1348                    ls.buff.clear();
1349                    if sep >= 2 {
1350                        read_long_string(state, ls, None, sep)?;
1351                        ls.buff.clear();
1352                        continue;
1353                    }
1354                }
1355                while !curr_is_newline(ls) && ls.current != EOZ {
1356                    advance(state, ls)?;
1357                }
1358                // loop continues (no token emitted for comments)
1359            }
1360
1361            Peek::Byte(b'[') => {
1362                let sep = skip_sep(state, ls)?;
1363                if sep >= 2 {
1364                    read_long_string(state, ls, Some(seminfo), sep)?;
1365                    return Ok(TK_STRING);
1366                } else if sep == 0 {
1367                    return Err(lex_error(ls, b"invalid long string delimiter", TK_STRING));
1368                }
1369                return Ok(b'[' as i32);
1370            }
1371
1372            Peek::Byte(b'=') => {
1373                advance(state, ls)?;
1374                if check_next1(state, ls, b'=' as i32)? {
1375                    return Ok(TK_EQ);
1376                }
1377                return Ok(b'=' as i32);
1378            }
1379
1380            Peek::Byte(b'<') => {
1381                advance(state, ls)?;
1382                if check_next1(state, ls, b'=' as i32)? {
1383                    return Ok(TK_LE);
1384                } else if !is_float_only(state) && check_next1(state, ls, b'<' as i32)? {
1385                    // The `<<` shift operator is a Lua 5.3 addition. Under the
1386                    // float-only legacy family (5.1/5.2) it does not exist: a
1387                    // bare `<` is returned, so a second `<` then surfaces
1388                    // upstream's "unexpected symbol near '<'".
1389                    return Ok(TK_SHL);
1390                }
1391                return Ok(b'<' as i32);
1392            }
1393
1394            Peek::Byte(b'>') => {
1395                advance(state, ls)?;
1396                if check_next1(state, ls, b'=' as i32)? {
1397                    return Ok(TK_GE);
1398                } else if !is_float_only(state) && check_next1(state, ls, b'>' as i32)? {
1399                    // `>>` is a 5.3 addition; absent in 5.1/5.2.
1400                    return Ok(TK_SHR);
1401                }
1402                return Ok(b'>' as i32);
1403            }
1404
1405            Peek::Byte(b'/') => {
1406                advance(state, ls)?;
1407                if !is_float_only(state) && check_next1(state, ls, b'/' as i32)? {
1408                    // Floor division `//` is a 5.3 addition; absent in 5.1/5.2,
1409                    // where the second `/` becomes "unexpected symbol near '/'".
1410                    return Ok(TK_IDIV);
1411                }
1412                return Ok(b'/' as i32);
1413            }
1414
1415            Peek::Byte(b'~') => {
1416                advance(state, ls)?;
1417                if check_next1(state, ls, b'=' as i32)? {
1418                    return Ok(TK_NE);
1419                }
1420                return Ok(b'~' as i32);
1421            }
1422
1423            Peek::Byte(b':') => {
1424                advance(state, ls)?;
1425                // Lua 5.1 has no `::label::` token; `::` was added with `goto` in
1426                // 5.2. Under V51 the second `:` is left for the parser, which
1427                // reports `unexpected symbol near ':'`. See
1428                // specs/followup/5.1-roster-syntax.md §2.
1429                let is_v51 = matches!(state.global().lua_version, lua_types::LuaVersion::V51);
1430                if !is_v51 && check_next1(state, ls, b':' as i32)? {
1431                    return Ok(TK_DBCOLON);
1432                }
1433                return Ok(b':' as i32);
1434            }
1435
1436            Peek::Byte(b'"' | b'\'') => {
1437                let del = ls.current;
1438                read_string(state, ls, del, seminfo)?;
1439                return Ok(TK_STRING);
1440            }
1441
1442            Peek::Byte(b'.') => {
1443                save_and_next(ls, state)?;
1444                if check_next1(state, ls, b'.' as i32)? {
1445                    if check_next1(state, ls, b'.' as i32)? {
1446                        return Ok(TK_DOTS);
1447                    }
1448                    return Ok(TK_CONCAT);
1449                } else if !is_digit(ls.current) {
1450                    return Ok(b'.' as i32);
1451                } else {
1452                    return read_numeral(state, ls, seminfo);
1453                }
1454            }
1455
1456            Peek::Byte(b'0'..=b'9') => {
1457                return read_numeral(state, ls, seminfo);
1458            }
1459
1460            Peek::Eoz => {
1461                return Ok(TK_EOS);
1462            }
1463
1464            Peek::Byte(c) => {
1465                if is_lalpha(c as i32) {
1466                    loop {
1467                        save_and_next(ls, state)?;
1468                        if !is_lalnum(ls.current) {
1469                            break;
1470                        }
1471                    }
1472
1473                    let content = ls.buff.to_owned_text();
1474                    let ts = new_string(state, ls, &content)?;
1475
1476                    // Recover the keyword index directly from the interned bytes
1477                    // via the `LUAX_TOKENS` table: the first `NUM_RESERVED`
1478                    // entries are the keywords in declaration order, so a match
1479                    // gives token id = `FIRST_RESERVED + index`.
1480                    let reserved_token: Option<i32> = LUAX_TOKENS[..NUM_RESERVED]
1481                        .iter()
1482                        .position(|kw| *kw == content.as_slice())
1483                        .map(|i| FIRST_RESERVED + i as i32);
1484                    *seminfo = TokenValue::Str(ts);
1485
1486                    if let Some(tk) = reserved_token {
1487                        // Lua 5.1 has no `goto` keyword — `goto` is an ordinary
1488                        // identifier (`local goto = 5` is valid). The keyword and
1489                        // the `::label::` grammar were added in 5.2. So under V51
1490                        // `goto` lexes as a plain name; the parser then treats
1491                        // `goto done` as a name beginning an assignment, yielding
1492                        // the incidental `'=' expected near 'done'` the oracle
1493                        // reports. See specs/followup/5.1-roster-syntax.md §2.
1494                        if tk == TK_GOTO
1495                            && matches!(state.global().lua_version, lua_types::LuaVersion::V51)
1496                        {
1497                            return Ok(TK_NAME);
1498                        }
1499                        return Ok(tk);
1500                    }
1501
1502                    // Lua 5.5: with the upstream-default `LUA_COMPAT_GLOBAL`, the
1503                    // `global` declaration word is NOT reserved — `global` stays a
1504                    // valid identifier, and the parser recognizes the declaration
1505                    // statement contextually (see `globalstat` in lua-parse). So
1506                    // `global` always lexes as a plain name, on every version.
1507                    return Ok(TK_NAME);
1508                } else {
1509                    let tok = ls.current;
1510                    advance(state, ls)?;
1511                    return Ok(tok);
1512                }
1513            }
1514        }
1515    }
1516}
1517
1518// ── Cross-crate helpers ────────────────────────────────────────────────────────
1519
1520fn intern_str_stub(state: &mut LuaState, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
1521    state.intern_str(bytes)
1522}
1523
1524/// Parse numeral bytes into an integer or float value, or `None` if malformed.
1525///
1526/// Wraps `lua_vm::object::str2num`, whose C-derived calling convention is an
1527/// out-parameter plus a `usize` status (`0` = no parse). The lexer never needs
1528/// the consumed-byte count — the whole token buffer is the numeral — so this
1529/// reduces the convention to an idiomatic `Option<LuaValue>`: `Some(value)` on
1530/// a successful parse, `None` on a malformed numeral.
1531fn parse_numeral(bytes: &[u8]) -> Option<lua_types::LuaValue> {
1532    let mut out = lua_types::LuaValue::Nil;
1533    if lua_vm::object::str2num(bytes, &mut out) == 0 {
1534        None
1535    } else {
1536        Some(out)
1537    }
1538}
1539
1540fn hex_value_stub(c: i32) -> u32 {
1541    match c {
1542        c if c >= b'0' as i32 && c <= b'9' as i32 => (c - b'0' as i32) as u32,
1543        c if c >= b'a' as i32 && c <= b'f' as i32 => (c - b'a' as i32 + 10) as u32,
1544        c if c >= b'A' as i32 && c <= b'F' as i32 => (c - b'A' as i32 + 10) as u32,
1545        _ => 0,
1546    }
1547}
1548
1549/// Encode a Unicode codepoint as a Lua-extended UTF-8 byte sequence (1 to 6 bytes).
1550///
1551/// Lua permits codepoints up to `0x7FFFFFFF` (5- and 6-byte sequences are
1552/// non-strict UTF-8 but accepted by `\u{...}` escapes per literals.lua test
1553/// cases).
1554fn utf8_encode_stub(codepoint: u32) -> Vec<u8> {
1555    debug_assert!(codepoint <= 0x7FFF_FFFF);
1556    if codepoint < 0x80 {
1557        return vec![codepoint as u8];
1558    }
1559    let mut x = codepoint;
1560    let mut mfb: u32 = 0x3f;
1561    let mut buf: Vec<u8> = Vec::with_capacity(8);
1562    loop {
1563        buf.push(0x80 | ((x & 0x3f) as u8));
1564        x >>= 6;
1565        mfb >>= 1;
1566        if x <= mfb {
1567            break;
1568        }
1569    }
1570    buf.push(((!mfb << 1) | x) as u8);
1571    buf.reverse();
1572    buf
1573}
1574
1575#[cfg(test)]
1576mod tests {
1577    use super::*;
1578    use lua_types::LuaVersion;
1579    use lua_vm::state::new_state;
1580
1581    /// Activates the state's own heap for the test body and stops the
1582    /// collector, mirroring production lexing: `protected_parser` pushes a
1583    /// heap context and stops the GC for the whole parse. Both halves
1584    /// matter — without the guard the lexer's interned strings hit
1585    /// `GcRef::new` with no active heap and panic (issue #249's guard-coverage
1586    /// class), and without the GC stop a mid-lex step sweeps strings these
1587    /// tests hold outside any traced root.
1588    fn state_heap_guard(state: &mut lua_vm::state::LuaState) -> lua_gc::HeapGuard {
1589        let _ = state.global_mut().stop_gc_internal();
1590        let g = state.global();
1591        lua_gc::HeapGuard::push(&g.heap)
1592    }
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    /// Returns the state alongside the tokens: `Token` carries
1620    /// `GcRef<LuaString>` handles into the state's heap, which frees every
1621    /// box when the state drops — a token examined after that reads freed
1622    /// memory. (These tests originally got away with it because lexer
1623    /// allocations leaked as detached boxes; the issue #249 fix made the
1624    /// heap own them, which is what surfaced this.)
1625    fn lex(ver: LuaVersion, src: &[u8]) -> (lua_vm::state::LuaState, Vec<Token>) {
1626        let mut state = new_state().expect("state init");
1627        let _heap_guard = state_heap_guard(&mut state);
1628        state.global_mut().lua_version = ver;
1629
1630        let source = state.intern_str(b"@test").expect("intern source");
1631        let firstchar = src.first().map_or(EOZ, |&b| b as i32);
1632        let rest: Vec<u8> = src.iter().skip(1).copied().collect();
1633
1634        let mut ls = empty_lexstate(source.clone(), ver);
1635        set_input(&mut state, &mut ls, ZIO::from_bytes(rest), source, firstchar)
1636            .expect("set_input");
1637
1638        let mut out = Vec::new();
1639        loop {
1640            next(&mut state, &mut ls).expect("next");
1641            let kind = ls.t.kind;
1642            out.push(ls.t.clone());
1643            if kind == TK_EOS {
1644                break;
1645            }
1646        }
1647        (state, out)
1648    }
1649
1650    /// Just the token-kind sequence, dropping the trailing `TK_EOS`.
1651    fn kinds(ver: LuaVersion, src: &[u8]) -> Vec<i32> {
1652        let (_state, mut v) = lex(ver, src);
1653        v.pop();
1654        v.into_iter().map(|t| t.kind).collect()
1655    }
1656
1657    /// Lex `src` and return the bytes of its single string-literal token.
1658    fn one_string(ver: LuaVersion, src: &[u8]) -> Vec<u8> {
1659        let (_state, toks) = lex(ver, src);
1660        let str_tok = toks
1661            .iter()
1662            .find(|t| t.kind == TK_STRING)
1663            .expect("a string token");
1664        match &str_tok.value {
1665            TokenValue::Str(s) => s.as_bytes().to_vec(),
1666            _ => panic!("string token without Str payload"),
1667        }
1668    }
1669
1670    #[test]
1671    fn crlf_and_lfcr_pair_into_single_lines() {
1672        // Three logical lines joined by CRLF; the `+` lands on line 3, so a
1673        // lex error there must report line 3 (CRLF counts as ONE newline).
1674        let (_state, toks) = lex(LuaVersion::V54, b"a\r\nb\r\n+");
1675        // a(name) b(name) +  EOS  -> the '+' is a single-byte token on line 3.
1676        assert_eq!(toks[0].kind, TK_NAME);
1677        assert_eq!(toks[1].kind, TK_NAME);
1678        assert_eq!(toks[2].kind, b'+' as i32);
1679        // LFCR also pairs.
1680        let (_state2, toks2) = lex(LuaVersion::V54, b"a\n\rb");
1681        assert_eq!(toks2[0].kind, TK_NAME);
1682        assert_eq!(toks2[1].kind, TK_NAME);
1683        assert_eq!(toks2[2].kind, TK_EOS);
1684    }
1685
1686    #[test]
1687    fn crlf_line_number_attribution() {
1688        // The error message must carry line 3 for a malformed numeral there.
1689        let mut state = new_state().expect("state init");
1690        let _heap_guard = state_heap_guard(&mut state);
1691        state.global_mut().lua_version = LuaVersion::V54;
1692        let source = state.intern_str(b"@t").unwrap();
1693        let src = b"\r\n\r\n0x".to_vec();
1694        let firstchar = src[0] as i32;
1695        let rest: Vec<u8> = src.iter().skip(1).copied().collect();
1696        let mut ls = empty_lexstate(source.clone(), LuaVersion::V54);
1697        set_input(&mut state, &mut ls, ZIO::from_bytes(rest), source, firstchar).unwrap();
1698        // `0x` with no hex digits is a malformed numeral on line 3.
1699        let err = loop {
1700            match next(&mut state, &mut ls) {
1701                Ok(()) if ls.t.kind == TK_EOS => panic!("expected a lex error"),
1702                Ok(()) => continue,
1703                Err(e) => break e,
1704            }
1705        };
1706        let msg = err.message_lossy();
1707        assert!(msg.contains(":3:"), "error should be on line 3, got: {msg}");
1708        assert!(msg.contains("malformed number"), "got: {msg}");
1709    }
1710
1711    #[test]
1712    fn hex_escape_decodes_to_bytes() {
1713        assert_eq!(one_string(LuaVersion::V54, br#""\x41\x42""#), b"AB");
1714        assert_eq!(one_string(LuaVersion::V54, br#""\x00\xff""#), b"\x00\xff");
1715    }
1716
1717    #[test]
1718    fn utf8_escape_encodes_codepoint() {
1719        assert_eq!(one_string(LuaVersion::V54, br#""\u{48}\u{49}""#), b"HI");
1720        // U+00E9 (é) → two UTF-8 bytes 0xC3 0xA9.
1721        assert_eq!(one_string(LuaVersion::V54, br#""\u{e9}""#), b"\xc3\xa9");
1722        // A 6-byte (non-strict) sequence is accepted up to 0x7FFFFFFF in 5.4.
1723        assert_eq!(
1724            one_string(LuaVersion::V54, br#""\u{7FFFFFFF}""#),
1725            b"\xFD\xBF\xBF\xBF\xBF\xBF"
1726        );
1727    }
1728
1729    #[test]
1730    fn decimal_escape_and_z_skip() {
1731        assert_eq!(one_string(LuaVersion::V54, br#""\65\66""#), b"AB");
1732        // \z swallows the following whitespace run (including newlines).
1733        assert_eq!(one_string(LuaVersion::V54, b"\"a\\z   \n\t b\""), b"ab");
1734    }
1735
1736    #[test]
1737    fn long_brackets_with_levels() {
1738        assert_eq!(one_string(LuaVersion::V54, b"[[ hello ]]"), b" hello ");
1739        assert_eq!(one_string(LuaVersion::V54, b"[==[ hi ]==]"), b" hi ");
1740        // A leading newline immediately after the open bracket is dropped.
1741        assert_eq!(one_string(LuaVersion::V54, b"[[\nx]]"), b"x");
1742        // An inner `]=]` that is not the matching close is kept as content.
1743        assert_eq!(one_string(LuaVersion::V54, b"[==[a]=]b]==]"), b"a]=]b");
1744    }
1745
1746    #[test]
1747    fn long_string_normalizes_newlines() {
1748        // CRLF inside a long string is normalized to a single \n.
1749        assert_eq!(one_string(LuaVersion::V54, b"[[a\r\nb]]"), b"a\nb");
1750    }
1751
1752    #[test]
1753    fn numeral_int_float_boundary() {
1754        // Integer literals → TK_INT with the exact i64; floats → TK_FLT.
1755        let (_state_dec, dec) = lex(LuaVersion::V54, b"3");
1756        assert_eq!(dec[0].kind, TK_INT);
1757        assert!(matches!(dec[0].value, TokenValue::Int(3)));
1758
1759        let (_state_hex, hex) = lex(LuaVersion::V54, b"0x10");
1760        assert_eq!(hex[0].kind, TK_INT);
1761        assert!(matches!(hex[0].value, TokenValue::Int(16)));
1762
1763        let (_state_flt, flt) = lex(LuaVersion::V54, b"3.0");
1764        assert_eq!(flt[0].kind, TK_FLT);
1765        assert!(matches!(flt[0].value, TokenValue::Float(f) if f == 3.0));
1766
1767        let (_state_expo, expo) = lex(LuaVersion::V54, b"1e2");
1768        assert_eq!(expo[0].kind, TK_FLT);
1769        assert!(matches!(expo[0].value, TokenValue::Float(f) if f == 100.0));
1770
1771        // A bare dot followed by digits is a float; a lone dot is the '.' token.
1772        let (_state_dotnum, dotnum) = lex(LuaVersion::V54, b".5");
1773        assert_eq!(dotnum[0].kind, TK_FLT);
1774    }
1775
1776    #[test]
1777    fn float_only_versions_widen_integer_literals() {
1778        // 5.1/5.2 have no integer subtype: every numeral lexes as a float.
1779        let (_state_v51, v51) = lex(LuaVersion::V51, b"3");
1780        assert_eq!(v51[0].kind, TK_FLT);
1781        assert!(matches!(v51[0].value, TokenValue::Float(f) if f == 3.0));
1782
1783        let (_state_v52, v52) = lex(LuaVersion::V52, b"42");
1784        assert_eq!(v52[0].kind, TK_FLT);
1785    }
1786
1787    #[test]
1788    fn version_gated_operators() {
1789        // `<<` is a 5.3+ token; on 5.4 it is one TK_SHL.
1790        assert_eq!(kinds(LuaVersion::V54, b"1 << 2"), vec![TK_INT, TK_SHL, TK_INT]);
1791        // On the float-only family it is NOT a token: two bare '<' bytes.
1792        assert_eq!(
1793            kinds(LuaVersion::V51, b"1 << 2"),
1794            vec![TK_FLT, b'<' as i32, b'<' as i32, TK_FLT]
1795        );
1796        // `//` floor-division: TK_IDIV on 5.4, two '/' on 5.1.
1797        assert_eq!(kinds(LuaVersion::V54, b"7 // 2"), vec![TK_INT, TK_IDIV, TK_INT]);
1798        assert_eq!(
1799            kinds(LuaVersion::V51, b"7 // 2"),
1800            vec![TK_FLT, b'/' as i32, b'/' as i32, TK_FLT]
1801        );
1802        // `::` label delimiter: TK_DBCOLON on 5.4, two ':' on 5.1.
1803        assert_eq!(kinds(LuaVersion::V54, b"::x::"), vec![TK_DBCOLON, TK_NAME, TK_DBCOLON]);
1804        assert_eq!(
1805            kinds(LuaVersion::V51, b"::x"),
1806            vec![b':' as i32, b':' as i32, TK_NAME]
1807        );
1808    }
1809
1810    #[test]
1811    fn version_gated_reserved_words() {
1812        // `goto` is a keyword on 5.2+ but a plain name on 5.1.
1813        assert_eq!(kinds(LuaVersion::V54, b"goto"), vec![TK_GOTO]);
1814        assert_eq!(kinds(LuaVersion::V51, b"goto"), vec![TK_NAME]);
1815        // `global` is never reserved — always a name.
1816        assert_eq!(kinds(LuaVersion::V55, b"global"), vec![TK_NAME]);
1817        assert_eq!(kinds(LuaVersion::V54, b"global"), vec![TK_NAME]);
1818        // An ordinary keyword still maps to its TK_* on every version.
1819        assert_eq!(kinds(LuaVersion::V54, b"while"), vec![TK_WHILE]);
1820        assert_eq!(kinds(LuaVersion::V51, b"while"), vec![TK_WHILE]);
1821    }
1822
1823    #[test]
1824    fn multichar_symbols_and_dots() {
1825        assert_eq!(kinds(LuaVersion::V54, b"=="), vec![TK_EQ]);
1826        assert_eq!(kinds(LuaVersion::V54, b"~="), vec![TK_NE]);
1827        assert_eq!(kinds(LuaVersion::V54, b"<="), vec![TK_LE]);
1828        assert_eq!(kinds(LuaVersion::V54, b">="), vec![TK_GE]);
1829        assert_eq!(kinds(LuaVersion::V54, b".."), vec![TK_CONCAT]);
1830        assert_eq!(kinds(LuaVersion::V54, b"..."), vec![TK_DOTS]);
1831        // A lone dot is its single-byte token.
1832        assert_eq!(kinds(LuaVersion::V54, b"."), vec![b'.' as i32]);
1833    }
1834
1835    #[test]
1836    fn comments_emit_no_tokens() {
1837        // Short comment to end of line, then a name.
1838        assert_eq!(kinds(LuaVersion::V54, b"-- a comment\nx"), vec![TK_NAME]);
1839        // Long comment.
1840        assert_eq!(kinds(LuaVersion::V54, b"--[[ block\ncomment ]] y"), vec![TK_NAME]);
1841    }
1842
1843    #[test]
1844    fn empty_input_is_just_eos() {
1845        let (_state, toks) = lex(LuaVersion::V54, b"");
1846        assert_eq!(toks.len(), 1);
1847        assert_eq!(toks[0].kind, TK_EOS);
1848    }
1849
1850    #[test]
1851    fn peek_maps_byte_and_eoz() {
1852        // The internal dispatch shape: a byte maps to Peek::Byte, EOZ to Peek::Eoz.
1853        let mut state = new_state().unwrap();
1854        let _heap_guard = state_heap_guard(&mut state);
1855        let source = state.intern_str(b"@t").unwrap();
1856        let mut ls = empty_lexstate(source, LuaVersion::V54);
1857        ls.current = b'=' as i32;
1858        assert!(matches!(peek(&ls), Peek::Byte(b'=')));
1859        ls.current = EOZ;
1860        assert!(matches!(peek(&ls), Peek::Eoz));
1861    }
1862
1863    #[test]
1864    fn zio_yields_bytes_then_eoz() {
1865        let mut state = new_state().expect("state init");
1866        let _heap_guard = state_heap_guard(&mut state);
1867        let mut z = ZIO::from_bytes(b"ab".to_vec());
1868        assert_eq!(z.getc(&mut state).unwrap(), b'a' as i32);
1869        assert_eq!(z.getc(&mut state).unwrap(), b'b' as i32);
1870        assert_eq!(z.getc(&mut state).unwrap(), EOZ);
1871        assert_eq!(z.getc(&mut state).unwrap(), EOZ);
1872        // An empty source is immediately EOZ.
1873        let mut empty = ZIO::from_bytes(Vec::new());
1874        assert_eq!(empty.getc(&mut state).unwrap(), EOZ);
1875    }
1876
1877    #[test]
1878    fn lexbuffer_extraction_helpers() {
1879        let mut b = LexBuffer::new();
1880        for &c in b"\"hello\"" {
1881            b.push_byte(c);
1882        }
1883        assert_eq!(b.trim_ends(1), b"hello");
1884        assert_eq!(b.to_owned_text(), b"\"hello\"");
1885        // Too-short buffer for the requested delimiter width → empty content.
1886        let mut tiny = LexBuffer::new();
1887        tiny.push_byte(b'"');
1888        assert_eq!(tiny.trim_ends(1), b"");
1889        // Trailing-NUL trim drops exactly one sentinel.
1890        let mut num = LexBuffer::new();
1891        for &c in b"123\0" {
1892            num.push_byte(c);
1893        }
1894        assert_eq!(num.without_trailing_nul(), b"123");
1895    }
1896}