luna-core 2.11.0

Pure-Rust Lua runtime (interpreter only, zero third-party dependencies). The JIT-equipped variant lives in the `luna-jit` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! Byte-driven lexer. The source is an arbitrary byte sequence (Lua sources
//! and string literals are not required to be UTF-8); only `\u{...}` escapes
//! produce UTF-8 output.

use crate::frontend::error::SyntaxError;
use crate::frontend::span::Span;
use crate::frontend::token::{Token, TokenInfo};
use crate::numeric::{self, Num, hex_digit};
use crate::version::LuaVersion;

/// Streaming Lua lexer. Holds a borrowed reference to the source bytes and
/// the current line counter; `next_token()` produces one [`TokenInfo`] at a
/// time.
pub struct Lexer<'s> {
    src: &'s [u8],
    pos: usize,
    line: u32,
    version: LuaVersion,
}

impl<'s> Lexer<'s> {
    /// Build a lexer over `src` for the given Lua dialect.
    pub fn new(src: &'s [u8], version: LuaVersion) -> Lexer<'s> {
        Lexer {
            src,
            pos: 0,
            line: 1,
            version,
        }
    }

    /// Borrow the source bytes the lexer is iterating.
    pub fn src(&self) -> &'s [u8] {
        self.src
    }

    /// Strip a leading UTF-8 BOM and `#...` shebang line from a *file* chunk,
    /// as PUC's `luaL_loadfilex` does. String `load()` never strips these, so
    /// this is applied by the file loaders only — not in the lexer itself. The
    /// terminating newline is left in place so line numbers count the shebang
    /// line as line 1.
    pub fn strip_shebang_bom(src: &[u8]) -> &[u8] {
        let mut p = 0;
        if src.starts_with(&[0xEF, 0xBB, 0xBF]) {
            p = 3;
        }
        if src.get(p) == Some(&b'#') {
            while !matches!(src.get(p), None | Some(b'\n') | Some(b'\r')) {
                p += 1;
            }
        }
        &src[p..]
    }

    fn cur(&self) -> Option<u8> {
        self.src.get(self.pos).copied()
    }

    fn at(&self, off: usize) -> Option<u8> {
        self.src.get(self.pos + off).copied()
    }

    fn bump(&mut self) {
        self.pos += 1;
    }

    /// Consume `\n`, `\r`, `\n\r` or `\r\n` as a single line break.
    fn newline(&mut self) {
        let first = self.cur();
        self.bump();
        if let (Some(a), Some(b)) = (first, self.cur())
            && (b == b'\n' || b == b'\r')
            && b != a
        {
            self.bump();
        }
        self.line += 1;
    }

    fn err(&self, line: u32, msg: impl Into<String>) -> SyntaxError {
        SyntaxError {
            line,
            msg: msg.into().into_bytes(),
        }
    }

    /// Like `err` but accepts a `Vec<u8>` directly, for the lexer's raw-byte
    /// near-token paths (PUC 5.1 `near '\xff'` cases need the offending byte
    /// in the message verbatim, which a `String` round-trip would garble).
    fn err_bytes(&self, line: u32, msg: Vec<u8>) -> SyntaxError {
        SyntaxError { line, msg }
    }

    fn err_near(&self, line: u32, msg: &str, start: usize) -> SyntaxError {
        // PUC `luaX_token2str` rendered a non-printable single byte through
        // three successive forms:
        //   - 5.1: `iscntrl` → `char(N)` (unwrapped), otherwise the raw byte
        //          (`\xff` fails `iscntrl` in the C locale).
        //   - 5.2: `char(N)` for any non-printable byte, unwrapped.
        //   - 5.3+: `'<\N>'` (decimal, single-quoted by `luaX_token2str`).
        // errors.lua exercises each: 5.1 :196 raw, 5.2 :352 `char(255)`,
        // 5.3 :461 / 5.4 :620 `<\255>`. `SyntaxError.msg` is `Vec<u8>` so
        // the 5.1 raw-byte branch can carry `\xff` verbatim — `errors.lua`
        // 5.1 :20's `checksyntax([[\xffa = 1]], …, "\xff", 1)` pattern
        // `near '%\xff'` then matches.
        let bytes = &self.src[start..self.pos];
        if bytes.len() == 1 && !bytes[0].is_ascii_graphic() {
            let b = bytes[0];
            // is_ascii_control covers C0 controls (0x00..0x1f, 0x7f). 5.1
            // routes those through `char(N)` and other high-bit bytes
            // through the raw form.
            let raw_byte_form = self.version <= LuaVersion::Lua51 && !b.is_ascii_control();
            if self.version >= LuaVersion::Lua53 {
                return self.err(line, format!("{msg} near '<\\{b}>'"));
            }
            if raw_byte_form {
                let mut out = Vec::with_capacity(msg.len() + 6);
                out.extend_from_slice(msg.as_bytes());
                out.extend_from_slice(b" near '");
                out.push(b);
                out.push(b'\'');
                return self.err_bytes(line, out);
            }
            return self.err(line, format!("{msg} near char({b})"));
        }
        let text = String::from_utf8_lossy(bytes).into_owned();
        self.err(line, format!("{msg} near '{text}'"))
    }

    /// Error inside a string literal: the near-token is the raw source of the
    /// string contents read so far (`content_start..pos`), mirroring PUC's
    /// `txtToken` over the lex buffer.
    ///
    /// `consume_current = true` mirrors PUC `esccheck`'s pattern of saving the
    /// offending byte into the buffer before raising (e.g. `\g` — the bad
    /// escape *letter* is part of the report). For errors that fire after the
    /// escape has been fully consumed (e.g. `\999` — overflow checked after
    /// the third digit) the caller passes `false` so the trailing string-
    /// delimiter doesn't sneak into the report.
    fn str_err(
        &mut self,
        line: u32,
        msg: &str,
        content_start: usize,
        consume_current: bool,
    ) -> SyntaxError {
        if consume_current && self.cur().is_some() {
            self.bump();
        }
        let text = String::from_utf8_lossy(&self.src[content_start..self.pos]);
        self.err(line, format!("{msg} near '{text}'"))
    }

    /// Lex the next token. Returns `Token::Eof` (with the final source line)
    /// at end-of-input; returns a [`SyntaxError`] on malformed input.
    pub fn next_token(&mut self) -> Result<TokenInfo, SyntaxError> {
        loop {
            let start = self.pos;
            let line = self.line;
            let Some(c) = self.cur() else {
                return Ok(TokenInfo {
                    tok: Token::Eof,
                    span: Span::new(self.pos, self.pos),
                    line: self.line,
                });
            };
            match c {
                b'\n' | b'\r' => self.newline(),
                b' ' | b'\t' | 0x0B | 0x0C => self.bump(),
                b'-' if self.at(1) == Some(b'-') => {
                    self.pos += 2;
                    self.comment()?;
                }
                _ => {
                    let tok = self.token(c, start, line)?;
                    return Ok(TokenInfo {
                        tok,
                        span: Span::new(start, self.pos),
                        line,
                    });
                }
            }
        }
    }

    fn comment(&mut self) -> Result<(), SyntaxError> {
        if self.cur() == Some(b'[')
            && let Some(level) = self.long_bracket_level()
        {
            self.pos += 2 + level as usize;
            self.long_string(level, true)?;
            return Ok(());
        }
        while !matches!(self.cur(), None | Some(b'\n') | Some(b'\r')) {
            self.bump();
        }
        Ok(())
    }

    fn token(&mut self, c: u8, start: usize, line: u32) -> Result<Token, SyntaxError> {
        match c {
            b'A'..=b'Z' | b'a'..=b'z' | b'_' => Ok(self.name_or_keyword()),
            b'0'..=b'9' => self.number(start, line),
            b'"' | b'\'' => self.string(c),
            b'[' => match self.long_bracket_level() {
                Some(level) => {
                    self.pos += 2 + level as usize;
                    Ok(Token::Str(self.long_string(level, false)?))
                }
                None if self.at(1) == Some(b'=') => {
                    self.bump();
                    while self.cur() == Some(b'=') {
                        self.bump();
                    }
                    Err(self.err_near(line, "invalid long string delimiter", start))
                }
                None => {
                    self.bump();
                    Ok(Token::LBracket)
                }
            },
            b'+' => {
                self.bump();
                Ok(Token::Plus)
            }
            b'-' => {
                self.bump();
                Ok(Token::Minus)
            }
            b'*' => {
                self.bump();
                Ok(Token::Star)
            }
            b'/' => {
                self.bump();
                if self.cur() == Some(b'/') && self.version.has_idiv() {
                    self.bump();
                    Ok(Token::DSlash)
                } else {
                    Ok(Token::Slash)
                }
            }
            b'%' => {
                self.bump();
                Ok(Token::Percent)
            }
            b'^' => {
                self.bump();
                Ok(Token::Caret)
            }
            b'#' => {
                self.bump();
                Ok(Token::Hash)
            }
            b'&' if self.version.has_bitwise_ops() => {
                self.bump();
                Ok(Token::Amp)
            }
            b'|' if self.version.has_bitwise_ops() => {
                self.bump();
                Ok(Token::Pipe)
            }
            b'~' => {
                self.bump();
                if self.cur() == Some(b'=') {
                    self.bump();
                    Ok(Token::Ne)
                } else if self.version.has_bitwise_ops() {
                    Ok(Token::Tilde)
                } else {
                    Err(self.err_near(line, "unexpected symbol", start))
                }
            }
            b'<' => {
                self.bump();
                match self.cur() {
                    Some(b'=') => {
                        self.bump();
                        Ok(Token::Le)
                    }
                    Some(b'<') if self.version.has_bitwise_ops() => {
                        self.bump();
                        Ok(Token::Shl)
                    }
                    _ => Ok(Token::Lt),
                }
            }
            b'>' => {
                self.bump();
                match self.cur() {
                    Some(b'=') => {
                        self.bump();
                        Ok(Token::Ge)
                    }
                    Some(b'>') if self.version.has_bitwise_ops() => {
                        self.bump();
                        Ok(Token::Shr)
                    }
                    _ => Ok(Token::Gt),
                }
            }
            b'=' => {
                self.bump();
                if self.cur() == Some(b'=') {
                    self.bump();
                    Ok(Token::Eq)
                } else {
                    Ok(Token::Assign)
                }
            }
            b'(' => {
                self.bump();
                Ok(Token::LParen)
            }
            b')' => {
                self.bump();
                Ok(Token::RParen)
            }
            b'{' => {
                self.bump();
                Ok(Token::LBrace)
            }
            b'}' => {
                self.bump();
                // MacroLua: `}@` closes a `@{ ... }@` explicit quote block.
                // PUC 5.1-5.5 always reads a plain `}` here.
                if self.version.is_macro_lua() && self.cur() == Some(b'@') {
                    self.bump();
                    Ok(Token::MacroBraceClose)
                } else {
                    Ok(Token::RBrace)
                }
            }
            b']' => {
                self.bump();
                Ok(Token::RBracket)
            }
            b';' => {
                self.bump();
                Ok(Token::Semi)
            }
            b',' => {
                self.bump();
                Ok(Token::Comma)
            }
            b':' => {
                self.bump();
                if self.cur() == Some(b':') && self.version.has_goto() {
                    self.bump();
                    Ok(Token::DColon)
                } else {
                    Ok(Token::Colon)
                }
            }
            b'.' => match self.at(1) {
                Some(b'.') => {
                    self.pos += 2;
                    if self.cur() == Some(b'.') {
                        self.bump();
                        Ok(Token::Ellipsis)
                    } else {
                        Ok(Token::Concat)
                    }
                }
                Some(b'0'..=b'9') => self.number(start, line),
                _ => {
                    self.bump();
                    Ok(Token::Dot)
                }
            },
            // MacroLua (v1.3 Phase ML): `@` introduces a macro invocation
            // (`@name(args)` / `@quote{...}`) or an explicit quote-block
            // opener `@{`. PUC 5.1-5.5 falls through to the catch-all and
            // errors `unexpected symbol near '@'` exactly as before.
            b'@' if self.version.is_macro_lua() => {
                self.bump();
                if self.cur() == Some(b'{') {
                    self.bump();
                    Ok(Token::MacroBraceOpen)
                } else {
                    Ok(Token::At)
                }
            }
            _ => {
                self.bump();
                Err(self.err_near(line, "unexpected symbol", start))
            }
        }
    }

    fn name_or_keyword(&mut self) -> Token {
        let start = self.pos;
        while matches!(
            self.cur(),
            Some(b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_')
        ) {
            self.bump();
        }
        let text = &self.src[start..self.pos];
        match text {
            b"and" => Token::And,
            b"break" => Token::Break,
            b"do" => Token::Do,
            b"else" => Token::Else,
            b"elseif" => Token::Elseif,
            b"end" => Token::End,
            b"false" => Token::False,
            b"for" => Token::For,
            b"function" => Token::Function,
            // `global` is a *contextual* keyword in 5.5, not a reserved word:
            // it is only a declaration when it leads a statement (decided by
            // the parser via lookahead). Lexed as an ordinary name so uses like
            // `global = 1` / `return global` stay valid.
            b"goto" if self.version.has_goto() => Token::Goto,
            b"if" => Token::If,
            b"in" => Token::In,
            b"local" => Token::Local,
            b"nil" => Token::Nil,
            b"not" => Token::Not,
            b"or" => Token::Or,
            b"repeat" => Token::Repeat,
            b"return" => Token::Return,
            b"then" => Token::Then,
            b"true" => Token::True,
            b"until" => Token::Until,
            b"while" => Token::While,
            _ => Token::Name(str::from_utf8(text).expect("ascii identifier").into()),
        }
    }

    // ---- long brackets ----

    /// At `[`: returns the level if this position opens a long bracket
    /// (`[[`, `[=[`, ...), without consuming anything.
    fn long_bracket_level(&self) -> Option<u32> {
        let mut n = 0;
        while self.at(1 + n as usize) == Some(b'=') {
            n += 1;
        }
        (self.at(1 + n as usize) == Some(b'[')).then_some(n)
    }

    /// Body of a long string/comment; opener already consumed.
    fn long_string(&mut self, level: u32, is_comment: bool) -> Result<Vec<u8>, SyntaxError> {
        let open_line = self.line;
        let mut out = Vec::new();
        // a newline right after the opening bracket is skipped
        if matches!(self.cur(), Some(b'\n' | b'\r')) {
            self.newline();
        }
        loop {
            match self.cur() {
                None => {
                    let what = if is_comment { "comment" } else { "string" };
                    return Err(self.err(
                        self.line,
                        format!("unfinished long {what} (starting at line {open_line}) near <eof>"),
                    ));
                }
                Some(b']') => {
                    let mut n = 0;
                    while self.at(1 + n as usize) == Some(b'=') {
                        n += 1;
                    }
                    if n == level && self.at(1 + n as usize) == Some(b']') {
                        self.pos += 2 + n as usize;
                        return Ok(out);
                    }
                    out.push(b']');
                    self.bump();
                }
                Some(b'[')
                    if !is_comment
                        && level == 0
                        && self.at(1) == Some(b'[')
                        && self.version.rejects_nested_long_string() =>
                {
                    return Err(self.err(self.line, "nesting of [[...]] is deprecated near '['"));
                }
                Some(b'\n' | b'\r') => {
                    out.push(b'\n');
                    self.newline();
                }
                Some(c) => {
                    out.push(c);
                    self.bump();
                }
            }
        }
    }

    // ---- short strings ----

    fn string(&mut self, quote: u8) -> Result<Token, SyntaxError> {
        self.bump();
        let content_start = self.pos;
        let mut out = Vec::new();
        loop {
            match self.cur() {
                None | Some(b'\n') | Some(b'\r') => {
                    return Err(self.err(self.line, "unfinished string near <eof>"));
                }
                Some(c) if c == quote => {
                    self.bump();
                    return Ok(Token::Str(out));
                }
                Some(b'\\') => {
                    // PUC `escerror` resets the lex buffer to just the
                    // offending `\<esc>` before raising for `\x` / decimal
                    // escapes — so the "near 'X'" suffix only quotes the
                    // escape, not the whole string body. `\u{…}` errors keep
                    // the full buffer (PUC's `utf8esc` calls `esccheck`
                    // without the buffer reset). `escape` gets both starts
                    // and picks the right one per error.
                    let esc_start = self.pos;
                    self.bump();
                    self.escape(&mut out, content_start, esc_start)?;
                }
                Some(c) => {
                    out.push(c);
                    self.bump();
                }
            }
        }
    }

    fn escape(
        &mut self,
        out: &mut Vec<u8>,
        full_start: usize,
        esc_start: usize,
    ) -> Result<(), SyntaxError> {
        // `esc_start` clips the near-token to just the offending escape
        // (matches PUC's `escerror` for `\x` / decimal); `full_start` keeps
        // the whole string body in the report (matches PUC's `\u{…}` path).
        let content_start = esc_start;
        let _ = full_start;
        let Some(c) = self.cur() else {
            return Err(self.err(self.line, "unfinished string near <eof>"));
        };
        match c {
            b'a' => {
                out.push(7);
                self.bump();
            }
            b'b' => {
                out.push(8);
                self.bump();
            }
            b'f' => {
                out.push(12);
                self.bump();
            }
            b'n' => {
                out.push(b'\n');
                self.bump();
            }
            b'r' => {
                out.push(b'\r');
                self.bump();
            }
            b't' => {
                out.push(b'\t');
                self.bump();
            }
            b'v' => {
                out.push(11);
                self.bump();
            }
            b'\\' | b'"' | b'\'' => {
                out.push(c);
                self.bump();
            }
            b'\n' | b'\r' => {
                self.newline();
                out.push(b'\n');
            }
            b'x' if self.version.has_extended_escapes() => {
                self.bump();
                let mut v: u32 = 0;
                for _ in 0..2 {
                    let Some(d) = self.cur().and_then(hex_digit) else {
                        return Err(self.str_err(
                            self.line,
                            "hexadecimal digit expected",
                            content_start,
                            true,
                        ));
                    };
                    v = v * 16 + d;
                    self.bump();
                }
                out.push(v as u8);
            }
            b'z' if self.version.has_extended_escapes() => {
                self.bump();
                loop {
                    match self.cur() {
                        Some(b'\n' | b'\r') => self.newline(),
                        Some(b' ' | b'\t' | 0x0B | 0x0C) => self.bump(),
                        _ => break,
                    }
                }
            }
            b'u' if self.version.has_extended_escapes() => {
                self.bump();
                if self.cur() != Some(b'{') {
                    return Err(self.str_err(
                        self.line,
                        "missing '{' in \\u{xxxx}",
                        full_start,
                        true,
                    ));
                }
                self.bump();
                let Some(d0) = self.cur().and_then(hex_digit) else {
                    return Err(self.str_err(
                        self.line,
                        "hexadecimal digit expected",
                        full_start,
                        true,
                    ));
                };
                let mut v: u64 = d0 as u64;
                self.bump();
                // PUC 5.3 caps \u escapes at the Unicode max 0x10FFFF; 5.4
                // widened the lexer cap to 0x7FFFFFFF (extended UTF-8). The
                // shift-then-check pattern matches PUC's loop so the offending
                // digit becomes the near token's last char.
                let cap = if self.version >= LuaVersion::Lua54 {
                    0x07FF_FFFFu64
                } else {
                    0x0010_FFFFu64 / 16
                };
                while let Some(d) = self.cur().and_then(hex_digit) {
                    if v > cap {
                        return Err(self.str_err(
                            self.line,
                            "UTF-8 value too large",
                            full_start,
                            true,
                        ));
                    }
                    v = v * 16 + d as u64;
                    self.bump();
                }
                if v > if self.version >= LuaVersion::Lua54 {
                    0x7FFF_FFFF
                } else {
                    0x0010_FFFF
                } {
                    return Err(self.str_err(self.line, "UTF-8 value too large", full_start, true));
                }
                if self.cur() != Some(b'}') {
                    return Err(self.str_err(
                        self.line,
                        "missing '}' in \\u{xxxx}",
                        full_start,
                        true,
                    ));
                }
                self.bump();
                push_utf8(out, v as u32);
            }
            b'0'..=b'9' => {
                let mut v: u32 = 0;
                for _ in 0..3 {
                    let Some(d @ b'0'..=b'9') = self.cur() else {
                        break;
                    };
                    v = v * 10 + (d - b'0') as u32;
                    self.bump();
                }
                if v > 255 {
                    // PUC 5.2's `escerror` reports the escape only (`\999`);
                    // 5.3+ extended it to also include the byte that follows
                    // (`\999"`). The literals.lua expectation flipped with the
                    // PUC change, so we mirror it per-dialect.
                    let consume = self.version >= LuaVersion::Lua53;
                    return Err(self.str_err(
                        self.line,
                        "decimal escape too large",
                        content_start,
                        consume,
                    ));
                }
                out.push(v as u8);
            }
            _ => {
                return Err(self.str_err(
                    self.line,
                    "invalid escape sequence",
                    content_start,
                    true,
                ));
            }
        }
        Ok(())
    }

    // ---- numbers ----

    /// Greedy scan (PUC-style: alphanumerics, '.', and exponent signs), then
    /// strict validation; mirrors read_numeral + lua_strtonumber.
    fn number(&mut self, start: usize, line: u32) -> Result<Token, SyntaxError> {
        let hex = self.cur() == Some(b'0') && matches!(self.at(1), Some(b'x' | b'X'));
        if hex {
            self.pos += 2;
        }
        let exp_marks: &[u8] = if hex { b"pP" } else { b"eE" };
        while let Some(c) = self.cur() {
            if exp_marks.contains(&c) {
                self.bump();
                if matches!(self.cur(), Some(b'+' | b'-')) {
                    self.bump();
                }
            } else if c.is_ascii_alphanumeric() || c == b'.' {
                self.bump();
            } else {
                break;
            }
        }
        let text = &self.src[start..self.pos];
        let malformed = || SyntaxError {
            line,
            msg: format!("malformed number near '{}'", String::from_utf8_lossy(text)).into_bytes(),
        };
        let int_ok = self.version.has_integers();
        let num = if hex {
            numeric::hex_literal(&text[2..], int_ok, self.version.has_hex_float())
        } else {
            // a numeric literal carries no sign (unary minus is a separate
            // operator), so the magnitude 2^63 stays a float here
            numeric::dec_literal(text, int_ok, false)
        };
        match num {
            Some(Num::Int(i)) => Ok(Token::Int(i)),
            Some(Num::Float(f)) => Ok(Token::Float(f)),
            None => Err(malformed()),
        }
    }
}

/// Extended UTF-8 (up to 6 bytes, values to 2^31-1), as luaO_utf8esc.
fn push_utf8(out: &mut Vec<u8>, mut x: u32) {
    if x < 0x80 {
        out.push(x as u8);
        return;
    }
    let mut cont = [0u8; 6];
    let mut n = 0;
    let mut mfb: u32 = 0x3f;
    loop {
        cont[n] = 0x80 | (x & 0x3f) as u8;
        n += 1;
        x >>= 6;
        mfb >>= 1;
        if x <= mfb {
            break;
        }
    }
    out.push(((!mfb << 1) | x) as u8);
    out.extend(cont[..n].iter().rev());
}

#[cfg(test)]
mod tests {
    use super::*;

    fn toks(src: &str, v: LuaVersion) -> Result<Vec<Token>, SyntaxError> {
        let mut lex = Lexer::new(src.as_bytes(), v);
        let mut out = Vec::new();
        loop {
            let t = lex.next_token()?;
            if t.tok == Token::Eof {
                return Ok(out);
            }
            out.push(t.tok);
        }
    }

    #[test]
    fn numbers_55() {
        let v = LuaVersion::Lua55;
        assert_eq!(toks("3", v).unwrap(), vec![Token::Int(3)]);
        assert_eq!(toks("3.0", v).unwrap(), vec![Token::Float(3.0)]);
        assert_eq!(toks("345", v).unwrap(), vec![Token::Int(345)]);
        assert_eq!(toks("0xff", v).unwrap(), vec![Token::Int(255)]);
        assert_eq!(toks("0x1p4", v).unwrap(), vec![Token::Float(16.0)]);
        assert_eq!(toks("0x0.8", v).unwrap(), vec![Token::Float(0.5)]);
        assert_eq!(toks("0xA.8p1", v).unwrap(), vec![Token::Float(21.0)]);
        assert_eq!(toks(".5e2", v).unwrap(), vec![Token::Float(50.0)]);
        assert_eq!(toks("1e2", v).unwrap(), vec![Token::Float(100.0)]);
        // decimal i64 overflow becomes a float
        assert_eq!(
            toks("9223372036854775808", v).unwrap(),
            vec![Token::Float(9223372036854775808.0)]
        );
        // hex wraps modulo 2^64
        assert_eq!(toks("0xFFFFFFFFFFFFFFFF", v).unwrap(), vec![Token::Int(-1)]);
        assert!(toks("3..2", v).is_err());
        assert!(toks("3a", v).is_err());
        assert!(toks("0x", v).is_err());
        assert!(toks("1e+", v).is_err());
    }

    #[test]
    fn numbers_51() {
        let v = LuaVersion::Lua51;
        assert_eq!(toks("3", v).unwrap(), vec![Token::Float(3.0)]);
        assert_eq!(toks("0x10", v).unwrap(), vec![Token::Float(16.0)]);
        assert!(toks("0x1p4", v).is_err());
    }

    #[test]
    fn strings() {
        let v = LuaVersion::Lua55;
        assert_eq!(
            toks(r#""a\65\x42\u{48}c""#, v).unwrap(),
            vec![Token::Str(b"aABHc".to_vec())]
        );
        assert_eq!(
            toks("\"a\\z  \n  b\"", v).unwrap(),
            vec![Token::Str(b"ab".to_vec())]
        );
        assert_eq!(
            toks("[==[\nhey]]==]", v).unwrap(),
            vec![Token::Str(b"hey]".to_vec())]
        );
        assert!(toks(r#""\x4""#, v).is_err());
        assert!(toks(r#""\300""#, v).is_err());
        assert!(toks(r#""\x41""#, LuaVersion::Lua51).is_err());
    }

    #[test]
    fn version_gates() {
        assert!(
            toks("a // b", LuaVersion::Lua51).is_err() || {
                // `//` lexes as two Slash tokens in 5.1; parser rejects later
                toks("a // b", LuaVersion::Lua51)
                    .unwrap()
                    .contains(&Token::Slash)
            }
        );
        assert_eq!(
            toks("goto", LuaVersion::Lua51).unwrap(),
            vec![Token::Name("goto".into())]
        );
        assert_eq!(toks("goto", LuaVersion::Lua55).unwrap(), vec![Token::Goto]);
        // `global` is a contextual keyword (parser decides); the lexer always
        // produces a plain name in every version.
        assert_eq!(
            toks("global", LuaVersion::Lua54).unwrap(),
            vec![Token::Name("global".into())]
        );
        assert_eq!(
            toks("global", LuaVersion::Lua55).unwrap(),
            vec![Token::Name("global".into())]
        );
        assert!(toks("a & b", LuaVersion::Lua51).is_err());
    }

    #[test]
    fn shebang_and_bom() {
        // shebang/BOM stripping is a file-load concern, not the lexer's: the
        // helper removes them, leaving the newline so line counts are kept.
        assert_eq!(
            Lexer::strip_shebang_bom(b"#!/usr/bin/lua\nreturn"),
            b"\nreturn"
        );
        assert_eq!(Lexer::strip_shebang_bom(&[0xEF, 0xBB, 0xBF, b'x']), b"x");
        // a string chunk keeps `#` as the length operator (no stripping here)
        let v = LuaVersion::Lua55;
        assert_eq!(
            toks("#a", v).unwrap(),
            vec![Token::Hash, Token::Name("a".into())]
        );
    }
}