Skip to main content

hexicon_compiler/
lex.rs

1//! Finding the next token in a line of source text.
2//!
3//! The scanner works on bytes. Source text is UTF-8, and everything the
4//! scanner looks for is ASCII, so a byte at a time finds the same tokens
5//! as a character at a time would: no byte of a longer character is ever
6//! an ASCII one.
7//!
8//! A line that the preprocessor is working on can also hold marker bytes
9//! that never appear in source text (they are below a tab, and such
10//! characters in source are turned into spaces as a line is read). The
11//! markers stand for a macro's parameters and record what has already
12//! been expanded.
13
14/// In a macro's stored expansion: a parameter. The next byte is the
15/// parameter's number, counting from one.
16pub(crate) const FORMAL_FLAG: u8 = 0x01;
17/// Before a symbol: it has been through macro expansion already and is
18/// not to be expanded again.
19pub(crate) const FULLY_EXPANDED_FLAG: u8 = 0x02;
20/// After a macro's expansion: the expansion of the macro whose number
21/// follows, in [`MACRO_ID_LEN`] bytes, ends here.
22pub(crate) const MACRO_EXP_END: u8 = 0x03;
23/// The end of a preprocessor directive's line. Nothing is read past it.
24pub(crate) const END_PP_LINE: u8 = 0x04;
25/// In a macro's stored expansion: `#foreach` on the variable arguments.
26pub(crate) const FOREACH_FLAG: u8 = 0x05;
27/// In a macro's stored expansion: `#argcount`.
28pub(crate) const ARGCOUNT_FLAG: u8 = 0x06;
29/// In a macro's stored expansion: `#ifempty`.
30pub(crate) const IFEMPTY_FLAG: u8 = 0x07;
31/// In a macro's stored expansion: `#ifnempty`.
32pub(crate) const IFNEMPTY_FLAG: u8 = 0x08;
33
34/// How many bytes after [`MACRO_EXP_END`] hold the macro's number.
35pub(crate) const MACRO_ID_LEN: usize = 4;
36
37/// The longest a symbol can usefully be; the rest is ignored, with a
38/// warning.
39pub(crate) const SYM_MAX_LEN: usize = 80;
40
41/// The bytes that record the end of a macro's expansion. Each byte of
42/// the number has its top bit set, so that none is mistaken for a marker,
43/// for the end of the text, or for an ASCII character.
44pub(crate) fn macro_end_marker(id: usize) -> [u8; 1 + MACRO_ID_LEN] {
45    let mut bytes = [MACRO_EXP_END; 1 + MACRO_ID_LEN];
46    for (index, byte) in bytes[1..].iter_mut().enumerate() {
47        *byte = 0x80 | ((id >> (7 * index)) & 0x7f) as u8;
48    }
49    bytes
50}
51
52/// The macro number recorded after a [`MACRO_EXP_END`] at `pos`.
53pub(crate) fn macro_end_id(buf: &[u8], pos: usize) -> usize {
54    (0..MACRO_ID_LEN)
55        .map(|index| usize::from(at(buf, pos + 1 + index) & 0x7f) << (7 * index))
56        .sum()
57}
58
59/// The byte at a position, or zero past the end, as text that ends in a
60/// zero byte would read.
61pub(crate) fn at(buf: &[u8], pos: usize) -> u8 {
62    buf.get(pos).copied().unwrap_or(0)
63}
64
65pub(crate) fn is_space(c: u8) -> bool {
66    matches!(c, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
67}
68
69pub(crate) fn is_digit(c: u8) -> bool {
70    c.is_ascii_digit()
71}
72
73fn is_odigit(c: u8) -> bool {
74    (b'0'..=b'7').contains(&c)
75}
76
77fn is_xdigit(c: u8) -> bool {
78    c.is_ascii_hexdigit()
79}
80
81pub(crate) fn is_syminit(c: u8) -> bool {
82    c == b'_' || c.is_ascii_alphabetic()
83}
84
85pub(crate) fn is_sym(c: u8) -> bool {
86    c == b'_' || c.is_ascii_alphanumeric()
87}
88
89/// The kinds of token. They are in the order the reference compiler has
90/// them in, so that a kind's number here is its number there, which is
91/// what lets the two tokenizers' output be compared.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93#[allow(missing_docs)]
94pub enum Tok {
95    Invalid,
96    /// Nothing: the reader should go on to the next token.
97    NullTok,
98    /// The end of the line, or of the source.
99    Eof,
100    MacroFormal,
101    MacroForeach,
102    MacroArgCount,
103    MacroIfEmpty,
104    MacroIfNEmpty,
105    Sym,
106    Int,
107    SStr,
108    SStrStart,
109    SStrMid,
110    SStrEnd,
111    DStr,
112    DStrStart,
113    DStrMid,
114    DStrEnd,
115    ReStr,
116    LPar,
117    RPar,
118    Comma,
119    Dot,
120    LBrace,
121    RBrace,
122    LBrack,
123    RBrack,
124    Eq,
125    EqEq,
126    /// `:=`, which the language no longer has.
127    Asi,
128    Plus,
129    Minus,
130    Times,
131    Div,
132    Mod,
133    Gt,
134    Lt,
135    Ge,
136    Le,
137    Ne,
138    Arrow,
139    Colon,
140    Sem,
141    And,
142    AndAnd,
143    Or,
144    OrOr,
145    Xor,
146    Shl,
147    AShr,
148    LShr,
149    Inc,
150    Dec,
151    PlusEq,
152    MinEq,
153    TimesEq,
154    DivEq,
155    ModEq,
156    AndEq,
157    OrEq,
158    XorEq,
159    ShlEq,
160    AShrEq,
161    LShrEq,
162    Not,
163    BNot,
164    Pound,
165    PoundPound,
166    PoundAt,
167    Ellipsis,
168    Question,
169    QQ,
170    ColonColon,
171    Float,
172    /// An integer too big to be one, to be made a floating-point number.
173    BigInt,
174    At,
175    DotDot,
176    /// The format in `<<%fmt expr>>`.
177    FmtSpec,
178
179    // Keywords.
180    SelfKw,
181    Inherited,
182    ArgCount,
183    If,
184    Else,
185    For,
186    While,
187    Do,
188    Switch,
189    Case,
190    Default,
191    Goto,
192    Break,
193    Continue,
194    Function,
195    Return,
196    Local,
197    Object,
198    Nil,
199    True,
200    Pass,
201    External,
202    Extern,
203    FormatString,
204    Class,
205    Replace,
206    Modify,
207    New,
208    Delete,
209    Throw,
210    Try,
211    Catch,
212    Finally,
213    Builtin,
214    Dictionary,
215    Grammar,
216    Enum,
217    Template,
218    Static,
219    Foreach,
220    Export,
221    Delegated,
222    TargetProp,
223    PropertySet,
224    TargetObj,
225    DefiningObj,
226    Transient,
227    Replaced,
228    Property,
229    Operator,
230    Method,
231    Invokee,
232}
233
234/// The keyword a symbol is, if it is one.
235pub(crate) fn keyword(text: &[u8]) -> Option<Tok> {
236    Some(match text {
237        b"self" => Tok::SelfKw,
238        b"targetprop" => Tok::TargetProp,
239        b"targetobj" => Tok::TargetObj,
240        b"definingobj" => Tok::DefiningObj,
241        b"inherited" => Tok::Inherited,
242        b"delegated" => Tok::Delegated,
243        b"argcount" => Tok::ArgCount,
244        b"if" => Tok::If,
245        b"else" => Tok::Else,
246        b"for" => Tok::For,
247        b"while" => Tok::While,
248        b"do" => Tok::Do,
249        b"switch" => Tok::Switch,
250        b"case" => Tok::Case,
251        b"default" => Tok::Default,
252        b"goto" => Tok::Goto,
253        b"break" => Tok::Break,
254        b"continue" => Tok::Continue,
255        b"function" => Tok::Function,
256        b"return" => Tok::Return,
257        b"local" => Tok::Local,
258        b"object" => Tok::Object,
259        b"nil" => Tok::Nil,
260        b"true" => Tok::True,
261        b"pass" => Tok::Pass,
262        b"external" => Tok::External,
263        b"extern" => Tok::Extern,
264        b"formatstring" => Tok::FormatString,
265        b"class" => Tok::Class,
266        b"replace" => Tok::Replace,
267        b"modify" => Tok::Modify,
268        b"new" => Tok::New,
269        b"throw" => Tok::Throw,
270        b"try" => Tok::Try,
271        b"catch" => Tok::Catch,
272        b"finally" => Tok::Finally,
273        b"builtin" => Tok::Builtin,
274        b"dictionary" => Tok::Dictionary,
275        b"grammar" => Tok::Grammar,
276        b"enum" => Tok::Enum,
277        b"template" => Tok::Template,
278        b"static" => Tok::Static,
279        b"foreach" => Tok::Foreach,
280        b"export" => Tok::Export,
281        b"propertyset" => Tok::PropertySet,
282        b"transient" => Tok::Transient,
283        b"replaced" => Tok::Replaced,
284        b"property" => Tok::Property,
285        b"operator" => Tok::Operator,
286        b"method" => Tok::Method,
287        b"invokee" => Tok::Invokee,
288        _ => return None,
289    })
290}
291
292/// A token: its kind and where its text is in the buffer it came from.
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294pub(crate) struct Token {
295    pub typ: Tok,
296    pub pos: usize,
297    pub len: usize,
298    /// The symbol was marked as already expanded.
299    pub fully_expanded: bool,
300    /// The value of an integer token.
301    pub int_val: u32,
302}
303
304impl Token {
305    pub(crate) fn new(typ: Tok) -> Self {
306        Self {
307            typ,
308            pos: 0,
309            len: 0,
310            fully_expanded: false,
311            int_val: 0,
312        }
313    }
314
315    pub(crate) fn end(&self) -> usize {
316        self.pos + self.len
317    }
318
319    pub(crate) fn text<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
320        let end = self.end().min(buf.len());
321        &buf[self.pos.min(end)..end]
322    }
323}
324
325/// How deep embedded expressions can nest: a string in an expression in a
326/// string, and so on.
327const EMBED_DEPTH: usize = 10;
328
329#[derive(Debug, Clone, Copy, Default)]
330struct EmbedLevel {
331    /// The quote of the string the expression is in.
332    quote: u8,
333    triple: bool,
334    /// How many brackets are open within the expression.
335    parens: i32,
336}
337
338/// Where the scanner is in strings with embedded expressions: inside
339/// `<<` and `>>`, the text is tokens, and the `>>` goes back to the
340/// string.
341#[derive(Debug, Clone, Copy, Default)]
342pub(crate) struct EmbedCtx {
343    level: usize,
344    stack: [EmbedLevel; EMBED_DEPTH],
345}
346
347impl EmbedCtx {
348    /// The level in use, if within reach.
349    fn current(&mut self) -> Option<&mut EmbedLevel> {
350        match self.level {
351            0 => None,
352            level if level <= EMBED_DEPTH => Some(&mut self.stack[level - 1]),
353            // Deeper than the stack: the reference goes on using the
354            // last level it had room for.
355            _ => Some(&mut self.stack[EMBED_DEPTH - 1]),
356        }
357    }
358
359    fn peek(&self) -> Option<&EmbedLevel> {
360        match self.level {
361            0 => None,
362            level => Some(&self.stack[level.min(EMBED_DEPTH) - 1]),
363        }
364    }
365
366    /// Enter an expression embedded in a string. Returns false if that
367    /// is deeper than expressions can nest.
368    pub(crate) fn start_expr(&mut self, quote: u8, triple: bool) -> bool {
369        let fits = self.level < EMBED_DEPTH;
370        if fits {
371            self.stack[self.level] = EmbedLevel {
372                quote,
373                triple,
374                parens: 0,
375            };
376        }
377        self.level += 1;
378        fits
379    }
380
381    pub(crate) fn end_expr(&mut self) {
382        if self.level > 0 {
383            self.level -= 1;
384        }
385    }
386
387    pub(crate) fn in_expr(&self) -> bool {
388        self.level != 0
389    }
390
391    pub(crate) fn parens(&self) -> i32 {
392        self.peek().map_or(0, |level| level.parens)
393    }
394
395    pub(crate) fn add_parens(&mut self, change: i32) {
396        if let Some(level) = self.current() {
397            level.parens = (level.parens + change).max(0);
398        }
399    }
400
401    pub(crate) fn quote(&self) -> u8 {
402        self.peek().map_or(0, |level| level.quote)
403    }
404
405    pub(crate) fn triple(&self) -> bool {
406        self.peek().is_some_and(|level| level.triple)
407    }
408}
409
410/// Something the scanner noticed that the caller may want to report.
411#[derive(Debug, Clone, PartialEq, Eq)]
412pub(crate) enum LexNote {
413    /// A number that starts with zero, so is octal, has an 8 or a 9.
414    DecimalInOctal(Vec<u8>),
415    /// A symbol has a character that is not ASCII.
416    NonAsciiSymbol(Vec<u8>),
417    /// A symbol is longer than symbols can be.
418    SymbolTruncated(Vec<u8>),
419    /// Expressions embedded in strings are nested too deeply.
420    EmbeddingTooDeep,
421    /// A string in a preprocessor expression has no end.
422    UntermString,
423}
424
425/// What the scanner needs besides the text.
426pub(crate) struct LexCtx<'a> {
427    /// Embedded expressions are followed, if this is given.
428    pub ec: Option<&'a mut EmbedCtx>,
429    /// The text is being scanned for macro expansion, not to be compiled,
430    /// so problems with it are not reported yet.
431    pub expanding: bool,
432    /// The text is a preprocessor expression.
433    pub in_pp_expr: bool,
434    pub notes: &'a mut Vec<LexNote>,
435}
436
437/// How many of a quote character there are in a row.
438pub(crate) fn count_quotes(buf: &[u8], pos: usize, quote: u8) -> usize {
439    let mut count = 0;
440    while at(buf, pos + count) == quote {
441        count += 1;
442    }
443    count
444}
445
446/// Skip spaces and the markers that end macro expansions.
447pub(crate) fn skip_ws_and_markers(buf: &[u8], pos: &mut usize) {
448    loop {
449        let c = at(buf, *pos);
450        if c == MACRO_EXP_END {
451            *pos += 1 + MACRO_ID_LEN;
452        } else if is_space(c) {
453            *pos += 1;
454        } else {
455            return;
456        }
457    }
458}
459
460/// Skip one character of a string, or a whole escape sequence.
461pub(crate) fn skip_escape(buf: &[u8], pos: &mut usize) {
462    if at(buf, *pos) != b'\\' {
463        *pos += 1;
464        return;
465    }
466    *pos += 1;
467    match at(buf, *pos) {
468        0 => {}
469        // An octal character code: up to three digits, and no more than
470        // fit in a byte.
471        b'0'..=b'7' => {
472            let mut acc: u32 = 0;
473            for _ in 0..3 {
474                let c = at(buf, *pos);
475                if !is_odigit(c) || 8 * acc + u32::from(c - b'0') > 255 {
476                    break;
477                }
478                acc = 8 * acc + u32::from(c - b'0');
479                *pos += 1;
480            }
481        }
482        // A hexadecimal character code: two digits after `x`, four after
483        // `u`.
484        code @ (b'x' | b'u') => {
485            *pos += 1;
486            let most = if code == b'x' { 2 } else { 4 };
487            let mut count = 0;
488            while count < most && is_xdigit(at(buf, *pos)) {
489                *pos += 1;
490                count += 1;
491            }
492        }
493        _ => *pos += 1,
494    }
495}
496
497/// Skip the format after `<<%`: flags, width, precision, and the letter
498/// that says what kind of value it is.
499pub(crate) fn scan_sprintf_spec(buf: &[u8], pos: &mut usize) {
500    *pos += 1;
501    loop {
502        match at(buf, *pos) {
503            b'[' => {
504                *pos += 1;
505                while is_digit(at(buf, *pos)) {
506                    *pos += 1;
507                }
508                if at(buf, *pos) == b']' {
509                    *pos += 1;
510                }
511            }
512            b'_' => {
513                *pos += 1;
514                if at(buf, *pos) != 0 {
515                    skip_escape(buf, pos);
516                }
517            }
518            b'-' | b'+' | b' ' | b',' | b'#' => *pos += 1,
519            _ => break,
520        }
521    }
522    while is_digit(at(buf, *pos)) {
523        *pos += 1;
524    }
525    if at(buf, *pos) == b'.' {
526        *pos += 1;
527        while is_digit(at(buf, *pos)) {
528            *pos += 1;
529        }
530    }
531    if at(buf, *pos) != 0 {
532        skip_escape(buf, pos);
533    }
534}
535
536/// Scan a string, or the part of one up to an embedded expression, or
537/// the part after one.
538fn tokenize_string(buf: &[u8], pos: &mut usize, cx: &mut LexCtx<'_>) -> Token {
539    let start = *pos;
540    let regex = at(buf, *pos) == b'R';
541    if regex {
542        *pos += 1;
543    }
544    let mut quote = at(buf, *pos);
545    *pos += 1;
546    let mut triple = false;
547    if (quote == b'"' || quote == b'\'') && count_quotes(buf, *pos, quote) >= 2 {
548        triple = true;
549        *pos += 2;
550    }
551
552    let mut typ;
553    let mut allow_embedding;
554    match quote {
555        b'\'' => {
556            typ = Tok::SStr;
557            allow_embedding = cx.ec.is_some();
558        }
559        b'"' => {
560            typ = Tok::DStr;
561            allow_embedding = cx.ec.is_some();
562        }
563        b'>' => {
564            // The end of an embedded expression: the string it was in
565            // carries on.
566            match cx.ec.as_deref_mut() {
567                Some(ec) => {
568                    typ = if !ec.in_expr() {
569                        Tok::Invalid
570                    } else if ec.quote() == b'"' {
571                        Tok::DStrEnd
572                    } else {
573                        Tok::SStrEnd
574                    };
575                    quote = ec.quote();
576                    triple = ec.triple();
577                    allow_embedding = true;
578                    ec.end_expr();
579                }
580                None => {
581                    typ = Tok::Invalid;
582                    quote = b'"';
583                    allow_embedding = false;
584                }
585            }
586            *pos += 1;
587        }
588        _ => {
589            typ = Tok::Invalid;
590            quote = b'"';
591            allow_embedding = false;
592        }
593    }
594    if regex {
595        allow_embedding = false;
596        typ = Tok::ReStr;
597    }
598
599    loop {
600        let cur = at(buf, *pos);
601        if cur == b'\\' {
602            *pos += 1;
603            // In a triple-quoted string, a backslash escapes a whole run
604            // of quotes.
605            if triple && at(buf, *pos) == quote {
606                while at(buf, *pos) == quote {
607                    *pos += 1;
608                }
609                continue;
610            }
611        } else if cur == b'<' && allow_embedding && at(buf, *pos + 1) == b'<' {
612            typ = match typ {
613                Tok::DStr => Tok::DStrStart,
614                Tok::DStrEnd => Tok::DStrMid,
615                Tok::SStr => Tok::SStrStart,
616                Tok::SStrEnd => Tok::SStrMid,
617                other => other,
618            };
619            if let Some(ec) = cx.ec.as_deref_mut()
620                && !ec.start_expr(quote, triple)
621                && !cx.expanding
622            {
623                cx.notes.push(LexNote::EmbeddingTooDeep);
624            }
625            *pos += 2;
626            break;
627        } else if cur == quote {
628            if triple {
629                let count = count_quotes(buf, *pos, quote);
630                if count >= 3 {
631                    *pos += count;
632                } else {
633                    *pos += count;
634                    continue;
635                }
636            } else {
637                *pos += 1;
638            }
639            break;
640        } else if cur == 0 {
641            if cx.in_pp_expr {
642                cx.notes.push(LexNote::UntermString);
643            }
644            break;
645        }
646        *pos += 1;
647    }
648
649    Token {
650        typ,
651        pos: start,
652        len: *pos - start,
653        fully_expanded: false,
654        int_val: 0,
655    }
656}
657
658/// Get the next token on the line, starting at `pos`, and leave `pos`
659/// after it.
660pub(crate) fn next_on_line(buf: &[u8], pos: &mut usize, cx: &mut LexCtx<'_>) -> Token {
661    skip_ws_and_markers(buf, pos);
662    let mut start = *pos;
663    let mut cur = at(buf, *pos);
664    let mut tok = Token::new(Tok::Eof);
665    tok.pos = start;
666    if cur == 0 {
667        return tok;
668    }
669    *pos += 1;
670
671    let typ;
672    let mut symbol = false;
673    match cur {
674        FORMAL_FLAG => {
675            typ = Tok::MacroFormal;
676            *pos += 1;
677        }
678        FOREACH_FLAG => typ = Tok::MacroForeach,
679        IFEMPTY_FLAG => typ = Tok::MacroIfEmpty,
680        IFNEMPTY_FLAG => typ = Tok::MacroIfNEmpty,
681        ARGCOUNT_FLAG => typ = Tok::MacroArgCount,
682        FULLY_EXPANDED_FLAG => {
683            tok.fully_expanded = true;
684            start = *pos;
685            cur = at(buf, *pos);
686            *pos += 1;
687            symbol = true;
688            typ = Tok::Sym;
689        }
690        END_PP_LINE => {
691            // Stay on the marker, so that every later read is the end of
692            // the line too.
693            *pos = start;
694            typ = Tok::Eof;
695        }
696        b'0'..=b'9' => {
697            let (number_typ, value) = scan_number(buf, pos, start, cur, cx);
698            typ = number_typ;
699            tok.int_val = value;
700        }
701        b'"' | b'\'' => {
702            *pos = start;
703            return tokenize_string(buf, pos, cx);
704        }
705        b'(' => {
706            typ = Tok::LPar;
707            add_parens(cx, 1);
708        }
709        b')' => {
710            typ = Tok::RPar;
711            add_parens(cx, -1);
712        }
713        b',' => typ = Tok::Comma,
714        b'.' => {
715            if at(buf, *pos) == b'.' {
716                *pos += 1;
717                if at(buf, *pos) == b'.' {
718                    *pos += 1;
719                    typ = Tok::Ellipsis;
720                } else {
721                    typ = Tok::DotDot;
722                }
723            } else if is_digit(at(buf, *pos)) {
724                typ = scan_float(buf, pos, start, Tok::Float);
725            } else {
726                typ = Tok::Dot;
727            }
728        }
729        b'{' => {
730            typ = Tok::LBrace;
731            add_parens(cx, 1);
732        }
733        b'}' => {
734            typ = Tok::RBrace;
735            add_parens(cx, -1);
736        }
737        b'[' => {
738            typ = Tok::LBrack;
739            add_parens(cx, 1);
740        }
741        b']' => {
742            typ = Tok::RBrack;
743            add_parens(cx, -1);
744        }
745        b'=' => typ = two(buf, pos, &[(b'=', Tok::EqEq)], Tok::Eq),
746        b':' => typ = two(buf, pos, &[(b':', Tok::ColonColon)], Tok::Colon),
747        b'?' => typ = two(buf, pos, &[(b'?', Tok::QQ)], Tok::Question),
748        b'+' => {
749            typ = two(
750                buf,
751                pos,
752                &[(b'+', Tok::Inc), (b'=', Tok::PlusEq)],
753                Tok::Plus,
754            )
755        }
756        b'-' => {
757            typ = two(
758                buf,
759                pos,
760                &[(b'-', Tok::Dec), (b'=', Tok::MinEq), (b'>', Tok::Arrow)],
761                Tok::Minus,
762            );
763        }
764        b'*' => typ = two(buf, pos, &[(b'=', Tok::TimesEq)], Tok::Times),
765        b'/' => typ = two(buf, pos, &[(b'=', Tok::DivEq)], Tok::Div),
766        b'%' => typ = two(buf, pos, &[(b'=', Tok::ModEq)], Tok::Mod),
767        b'>' => {
768            if at(buf, *pos) == b'=' {
769                *pos += 1;
770                typ = Tok::Ge;
771            } else if at(buf, *pos) == b'>' {
772                // The end of an embedded expression, if one is open and
773                // its brackets are all closed.
774                if cx
775                    .ec
776                    .as_deref()
777                    .is_some_and(|ec| ec.in_expr() && ec.parens() == 0)
778                {
779                    *pos = start;
780                    return tokenize_string(buf, pos, cx);
781                }
782                *pos += 1;
783                if at(buf, *pos) == b'>' {
784                    *pos += 1;
785                    typ = two(buf, pos, &[(b'=', Tok::LShrEq)], Tok::LShr);
786                } else {
787                    typ = two(buf, pos, &[(b'=', Tok::AShrEq)], Tok::AShr);
788                }
789            } else {
790                typ = Tok::Gt;
791            }
792        }
793        b'<' => {
794            if at(buf, *pos) == b'=' {
795                *pos += 1;
796                typ = Tok::Le;
797            } else if at(buf, *pos) == b'<' {
798                *pos += 1;
799                typ = two(buf, pos, &[(b'=', Tok::ShlEq)], Tok::Shl);
800            } else {
801                typ = Tok::Lt;
802            }
803        }
804        b';' => typ = Tok::Sem,
805        b'&' => {
806            typ = two(
807                buf,
808                pos,
809                &[(b'&', Tok::AndAnd), (b'=', Tok::AndEq)],
810                Tok::And,
811            )
812        }
813        b'|' => typ = two(buf, pos, &[(b'|', Tok::OrOr), (b'=', Tok::OrEq)], Tok::Or),
814        b'^' => typ = two(buf, pos, &[(b'=', Tok::XorEq)], Tok::Xor),
815        b'!' => typ = two(buf, pos, &[(b'=', Tok::Ne)], Tok::Not),
816        b'~' => typ = Tok::BNot,
817        b'@' => typ = Tok::At,
818        b'#' => {
819            typ = two(
820                buf,
821                pos,
822                &[(b'#', Tok::PoundPound), (b'@', Tok::PoundAt)],
823                Tok::Pound,
824            )
825        }
826        b'R' if at(buf, *pos) == b'"' || at(buf, *pos) == b'\'' => {
827            *pos = start;
828            return tokenize_string(buf, pos, cx);
829        }
830        _ => {
831            if is_syminit(cur) || !cur.is_ascii() {
832                symbol = true;
833                typ = Tok::Sym;
834            } else {
835                typ = Tok::Invalid;
836            }
837        }
838    }
839
840    if symbol {
841        let mut non_ascii = !cur.is_ascii();
842        let mut too_long = false;
843        loop {
844            let ch = at(buf, *pos);
845            if !ch.is_ascii() {
846                non_ascii = true;
847            } else if !is_sym(ch) {
848                break;
849            }
850            *pos += 1;
851            if *pos - start >= SYM_MAX_LEN {
852                too_long = true;
853            }
854        }
855        if non_ascii {
856            cx.notes
857                .push(LexNote::NonAsciiSymbol(buf[start..*pos].to_vec()));
858        }
859        if too_long && !cx.expanding {
860            cx.notes
861                .push(LexNote::SymbolTruncated(buf[start..*pos].to_vec()));
862        }
863    }
864
865    tok.typ = typ;
866    tok.pos = start;
867    tok.len = *pos - start;
868    tok
869}
870
871fn add_parens(cx: &mut LexCtx<'_>, change: i32) {
872    if let Some(ec) = cx.ec.as_deref_mut() {
873        ec.add_parens(change);
874    }
875}
876
877/// A one-character operator, unless the next character makes it one of
878/// the two-character ones given.
879fn two(buf: &[u8], pos: &mut usize, longer: &[(u8, Tok)], single: Tok) -> Tok {
880    let next = at(buf, *pos);
881    for &(second, typ) in longer {
882        if next == second {
883            *pos += 1;
884            return typ;
885        }
886    }
887    single
888}
889
890/// Scan a number whose first digit, `first`, has been read.
891fn scan_number(
892    buf: &[u8],
893    pos: &mut usize,
894    start: usize,
895    first: u8,
896    cx: &mut LexCtx<'_>,
897) -> (Tok, u32) {
898    let mut acc: u32 = u32::from(first - b'0');
899    let mut overflow = false;
900    if first == b'0' {
901        if at(buf, *pos) == b'x' || at(buf, *pos) == b'X' {
902            *pos += 1;
903            while is_xdigit(at(buf, *pos)) {
904                if acc & 0xF000_0000 != 0 {
905                    overflow = true;
906                    break;
907                }
908                let digit = (at(buf, *pos) as char).to_digit(16).unwrap_or(0);
909                acc = acc * 16 + digit;
910                *pos += 1;
911            }
912        } else {
913            while is_odigit(at(buf, *pos)) {
914                if acc & 0xE000_0000 != 0 {
915                    overflow = true;
916                    break;
917                }
918                acc = 8 * acc + u32::from(at(buf, *pos) - b'0');
919                *pos += 1;
920            }
921            if !overflow && is_digit(at(buf, *pos)) {
922                *pos += 1;
923                while is_digit(at(buf, *pos)) {
924                    *pos += 1;
925                }
926                if !cx.expanding {
927                    cx.notes
928                        .push(LexNote::DecimalInOctal(buf[start..*pos].to_vec()));
929                }
930            }
931        }
932    } else {
933        while is_digit(at(buf, *pos)) {
934            if acc > 214_748_364 {
935                overflow = true;
936                break;
937            }
938            acc *= 10;
939            let digit = u32::from(at(buf, *pos) - b'0');
940            if acc > 2_147_483_647 - digit {
941                overflow = true;
942                break;
943            }
944            acc += digit;
945            *pos += 1;
946        }
947    }
948    if overflow {
949        return (scan_float(buf, pos, start, Tok::BigInt), 0);
950    }
951    // A decimal point or an exponent makes it a floating-point number,
952    // but two periods are a range, not a decimal point.
953    let next = at(buf, *pos);
954    if (next == b'.' && at(buf, *pos + 1) != b'.') || next == b'e' || next == b'E' {
955        return (scan_float(buf, pos, start, Tok::Float), 0);
956    }
957    (Tok::Int, acc)
958}
959
960/// Scan a floating-point number from its start. `typ` says whether it
961/// began as an integer that turned out too big.
962fn scan_float(buf: &[u8], pos: &mut usize, start: usize, typ: Tok) -> Tok {
963    let mut typ = typ;
964    let mut found_point = false;
965    let mut hex = false;
966    *pos = start;
967    if at(buf, *pos) == b'-' {
968        *pos += 1;
969    }
970    if typ == Tok::BigInt && at(buf, *pos) == b'0' && matches!(at(buf, *pos + 1), b'x' | b'X') {
971        hex = true;
972        *pos += 2;
973    }
974    loop {
975        let cur = at(buf, *pos);
976        if is_digit(cur) || (hex && is_xdigit(cur)) {
977            // Another digit.
978        } else if !found_point && !hex && cur == b'.' {
979            found_point = true;
980            if typ == Tok::BigInt {
981                typ = Tok::Float;
982            }
983        } else if cur == b'e' || cur == b'E' {
984            // An exponent, if digits follow.
985            let mut ahead = *pos + 1;
986            if matches!(at(buf, ahead), b'-' | b'+') {
987                ahead += 1;
988            }
989            if !is_digit(at(buf, ahead)) {
990                break;
991            }
992            while is_digit(at(buf, ahead)) {
993                ahead += 1;
994            }
995            *pos = ahead;
996            if typ == Tok::BigInt {
997                typ = Tok::Float;
998            }
999            break;
1000        } else {
1001            break;
1002        }
1003        *pos += 1;
1004    }
1005    typ
1006}