solar_parse/lexer/
mod.rs

1//! Solidity and Yul lexer.
2
3use solar_ast::{
4    Base, StrKind,
5    token::{BinOpToken, CommentKind, Delimiter, Token, TokenKind, TokenLitKind},
6};
7use solar_interface::{
8    BytePos, Session, Span, Symbol, diagnostics::DiagCtxt, source_map::SourceFile,
9};
10
11mod cursor;
12use cursor::token::{RawLiteralKind, RawToken, RawTokenKind};
13pub use cursor::*;
14
15pub mod unescape;
16
17mod unicode_chars;
18
19mod utf8;
20
21/// Solidity and Yul lexer.
22///
23/// Converts a [`Cursor`]'s output from simple [`RawTokenKind`]s into rich [`TokenKind`]s, by
24/// converting strings into interned symbols, concatenating tokens together, and running additional
25/// validation.
26pub struct Lexer<'sess, 'src> {
27    /// The parsing context.
28    pub(crate) sess: &'sess Session,
29
30    /// Initial position, read-only.
31    start_pos: BytePos,
32
33    /// The absolute offset within the source_map of the current character.
34    pos: BytePos,
35
36    /// Source text to tokenize.
37    src: &'src str,
38
39    /// Cursor for getting lexer tokens.
40    cursor: Cursor<'src>,
41
42    /// The current token which has not been processed by `next_token` yet.
43    token: Token,
44
45    /// When a "unknown start of token: \u{a0}" has already been emitted earlier
46    /// in this file, it's safe to treat further occurrences of the non-breaking
47    /// space character as whitespace.
48    nbsp_is_whitespace: bool,
49}
50
51impl<'sess, 'src> Lexer<'sess, 'src> {
52    /// Creates a new `Lexer` for the given source string.
53    pub fn new(sess: &'sess Session, src: &'src str) -> Self {
54        Self::with_start_pos(sess, src, BytePos(0))
55    }
56
57    /// Creates a new `Lexer` for the given source file.
58    ///
59    /// Note that the source file must be added to the source map before calling this function.
60    pub fn from_source_file(sess: &'sess Session, file: &'src SourceFile) -> Self {
61        Self::with_start_pos(sess, &file.src, file.start_pos)
62    }
63
64    /// Creates a new `Lexer` for the given source string and starting position.
65    pub fn with_start_pos(sess: &'sess Session, src: &'src str, start_pos: BytePos) -> Self {
66        let mut lexer = Self {
67            sess,
68            start_pos,
69            pos: start_pos,
70            src,
71            cursor: Cursor::new(src),
72            token: Token::DUMMY,
73            nbsp_is_whitespace: false,
74        };
75        (lexer.token, _) = lexer.bump();
76        lexer
77    }
78
79    /// Returns a reference to the diagnostic context.
80    #[inline]
81    pub fn dcx(&self) -> &'sess DiagCtxt {
82        &self.sess.dcx
83    }
84
85    /// Consumes the lexer and collects the remaining tokens into a vector.
86    ///
87    /// Note that this skips comments, as [required by the parser](crate::Parser::new).
88    ///
89    /// Prefer using this method instead of manually collecting tokens using [`Iterator`].
90    #[instrument(name = "lex", level = "debug", skip_all)]
91    pub fn into_tokens(mut self) -> Vec<Token> {
92        // This is an estimate of the number of tokens in the source.
93        let mut tokens = Vec::with_capacity(self.src.len() / 4);
94        loop {
95            let token = self.next_token();
96            if token.is_eof() {
97                break;
98            }
99            if token.is_comment() {
100                continue;
101            }
102            tokens.push(token);
103        }
104        trace!(
105            src.len = self.src.len(),
106            tokens.len = tokens.len(),
107            tokens.capacity = tokens.capacity(),
108            ratio = %format_args!("{:.2}", self.src.len() as f64 / tokens.len() as f64),
109            "lexed"
110        );
111        tokens
112    }
113
114    /// Returns the next token, advancing the lexer.
115    pub fn next_token(&mut self) -> Token {
116        let mut next_token;
117        loop {
118            let preceded_by_whitespace;
119            (next_token, preceded_by_whitespace) = self.bump();
120            if preceded_by_whitespace {
121                break;
122            } else if let Some(glued) = self.token.glue(next_token) {
123                self.token = glued;
124            } else {
125                break;
126            }
127        }
128        std::mem::replace(&mut self.token, next_token)
129    }
130
131    fn bump(&mut self) -> (Token, bool) {
132        let mut preceded_by_whitespace = false;
133        let mut swallow_next_invalid = 0;
134        loop {
135            let RawToken { kind: raw_kind, len } = self.cursor.advance_token();
136            let start = self.pos;
137            self.pos += len;
138
139            // Now "cook" the token, converting the simple `RawTokenKind` into a rich `TokenKind`.
140            // This turns strings into interned symbols and runs additional validation.
141            let kind = match raw_kind {
142                RawTokenKind::LineComment { is_doc } => {
143                    preceded_by_whitespace = true;
144
145                    // Opening delimiter is not included into the symbol.
146                    let content_start = start + BytePos(if is_doc { 3 } else { 2 });
147                    let content = self.str_from(content_start);
148                    self.cook_doc_comment(content_start, content, is_doc, CommentKind::Line)
149                }
150                RawTokenKind::BlockComment { is_doc, terminated } => {
151                    preceded_by_whitespace = true;
152
153                    if !terminated {
154                        let msg = if is_doc {
155                            "unterminated block doc-comment"
156                        } else {
157                            "unterminated block comment"
158                        };
159                        self.dcx().err(msg).span(self.new_span(start, self.pos)).emit();
160                    }
161
162                    // Opening delimiter and closing delimiter are not included into the symbol.
163                    let content_start = start + BytePos(if is_doc { 3 } else { 2 });
164                    let content_end = self.pos - (terminated as u32) * 2;
165                    let content = self.str_from_to(content_start, content_end);
166                    self.cook_doc_comment(content_start, content, is_doc, CommentKind::Block)
167                }
168                RawTokenKind::Whitespace => {
169                    preceded_by_whitespace = true;
170                    continue;
171                }
172                RawTokenKind::Ident => {
173                    let sym = self.symbol_from(start);
174                    TokenKind::Ident(sym)
175                }
176                RawTokenKind::Literal { kind } => {
177                    let (kind, symbol) = self.cook_literal(start, self.pos, kind);
178                    TokenKind::Literal(kind, symbol)
179                }
180
181                RawTokenKind::Semi => TokenKind::Semi,
182                RawTokenKind::Comma => TokenKind::Comma,
183                RawTokenKind::Dot => TokenKind::Dot,
184                RawTokenKind::OpenParen => TokenKind::OpenDelim(Delimiter::Parenthesis),
185                RawTokenKind::CloseParen => TokenKind::CloseDelim(Delimiter::Parenthesis),
186                RawTokenKind::OpenBrace => TokenKind::OpenDelim(Delimiter::Brace),
187                RawTokenKind::CloseBrace => TokenKind::CloseDelim(Delimiter::Brace),
188                RawTokenKind::OpenBracket => TokenKind::OpenDelim(Delimiter::Bracket),
189                RawTokenKind::CloseBracket => TokenKind::CloseDelim(Delimiter::Bracket),
190                RawTokenKind::Tilde => TokenKind::Tilde,
191                RawTokenKind::Question => TokenKind::Question,
192                RawTokenKind::Colon => TokenKind::Colon,
193                RawTokenKind::Eq => TokenKind::Eq,
194                RawTokenKind::Bang => TokenKind::Not,
195                RawTokenKind::Lt => TokenKind::Lt,
196                RawTokenKind::Gt => TokenKind::Gt,
197                RawTokenKind::Minus => TokenKind::BinOp(BinOpToken::Minus),
198                RawTokenKind::And => TokenKind::BinOp(BinOpToken::And),
199                RawTokenKind::Or => TokenKind::BinOp(BinOpToken::Or),
200                RawTokenKind::Plus => TokenKind::BinOp(BinOpToken::Plus),
201                RawTokenKind::Star => TokenKind::BinOp(BinOpToken::Star),
202                RawTokenKind::Slash => TokenKind::BinOp(BinOpToken::Slash),
203                RawTokenKind::Caret => TokenKind::BinOp(BinOpToken::Caret),
204                RawTokenKind::Percent => TokenKind::BinOp(BinOpToken::Percent),
205
206                RawTokenKind::Unknown => {
207                    // Don't emit diagnostics for sequences of the same invalid token
208                    if swallow_next_invalid > 0 {
209                        swallow_next_invalid -= 1;
210                        continue;
211                    }
212                    let mut it = self.str_from_to_end(start).chars();
213                    let c = it.next().unwrap();
214                    if c == '\u{00a0}' {
215                        // If an error has already been reported on non-breaking
216                        // space characters earlier in the file, treat all
217                        // subsequent occurrences as whitespace.
218                        if self.nbsp_is_whitespace {
219                            preceded_by_whitespace = true;
220                            continue;
221                        }
222                        self.nbsp_is_whitespace = true;
223                    }
224
225                    let repeats = it.take_while(|c1| *c1 == c).count();
226                    swallow_next_invalid = repeats;
227
228                    let (token, sugg) =
229                        unicode_chars::check_for_substitution(self, start, c, repeats + 1);
230
231                    let span = self
232                        .new_span(start, self.pos + BytePos::from_usize(repeats * c.len_utf8()));
233                    let msg = format!("unknown start of token: {}", escaped_char(c));
234                    let mut err = self.dcx().err(msg).span(span);
235                    if let Some(sugg) = sugg {
236                        match sugg {
237                            unicode_chars::TokenSubstitution::DirectedQuotes {
238                                span,
239                                suggestion: _,
240                                ascii_str,
241                                ascii_name,
242                            } => {
243                                let msg = format!(
244                                    "Unicode characters '“' (Left Double Quotation Mark) and '”' (Right Double Quotation Mark) look like '{ascii_str}' ({ascii_name}), but are not"
245                                );
246                                err = err.span_help(span, msg);
247                            }
248                            unicode_chars::TokenSubstitution::Other {
249                                span,
250                                suggestion: _,
251                                ch,
252                                u_name,
253                                ascii_str,
254                                ascii_name,
255                            } => {
256                                let msg = format!(
257                                    "Unicode character '{ch}' ({u_name}) looks like '{ascii_str}' ({ascii_name}), but it is not"
258                                );
259                                err = err.span_help(span, msg);
260                            }
261                        }
262                    }
263                    if c == '\0' {
264                        let help = "source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used";
265                        err = err.help(help);
266                    }
267                    if repeats > 0 {
268                        let note = match repeats {
269                            1 => "once more".to_string(),
270                            _ => format!("{repeats} more times"),
271                        };
272                        err = err.note(format!("character repeats {note}"));
273                    }
274                    err.emit();
275
276                    if let Some(token) = token {
277                        token
278                    } else {
279                        preceded_by_whitespace = true;
280                        continue;
281                    }
282                }
283
284                RawTokenKind::Eof => TokenKind::Eof,
285            };
286            let span = self.new_span(start, self.pos);
287            return (Token::new(kind, span), preceded_by_whitespace);
288        }
289    }
290
291    fn cook_doc_comment(
292        &self,
293        _content_start: BytePos,
294        content: &str,
295        is_doc: bool,
296        comment_kind: CommentKind,
297    ) -> TokenKind {
298        TokenKind::Comment(is_doc, comment_kind, Symbol::intern(content))
299    }
300
301    fn cook_literal(
302        &self,
303        start: BytePos,
304        end: BytePos,
305        kind: RawLiteralKind,
306    ) -> (TokenLitKind, Symbol) {
307        match kind {
308            RawLiteralKind::Str { kind, terminated } => {
309                if !terminated {
310                    let span = self.new_span(start, end);
311                    let guar = self.dcx().err("unterminated string").span(span).emit();
312                    (TokenLitKind::Err(guar), self.symbol_from_to(start, end))
313                } else {
314                    (kind.into(), self.cook_quoted(kind, start, end))
315                }
316            }
317            RawLiteralKind::Int { base, empty_int } => {
318                if empty_int {
319                    let span = self.new_span(start, end);
320                    self.dcx().err("no valid digits found for number").span(span).emit();
321                    (TokenLitKind::Integer, self.symbol_from_to(start, end))
322                } else {
323                    if matches!(base, Base::Binary | Base::Octal) {
324                        let start = start + 2;
325                        // To uncomment if binary and octal literals are ever supported.
326                        /*
327                        let base = base as u32;
328                        let s = self.str_from_to(start, end);
329                        for (i, c) in s.char_indices() {
330                            if c != '_' && c.to_digit(base).is_none() {
331                                let msg = format!("invalid digit for a base {base} literal");
332                                let lo = start + BytePos::from_usize(i);
333                                let hi = lo + BytePos::from_usize(c.len_utf8());
334                                let span = self.new_span(lo, hi);
335                                self.dcx().err(msg).span(span).emit();
336                            }
337                        }
338                        */
339                        let msg = format!("integers in base {base} are not supported");
340                        self.dcx().err(msg).span(self.new_span(start, end)).emit();
341                    }
342                    (TokenLitKind::Integer, self.symbol_from_to(start, end))
343                }
344            }
345            RawLiteralKind::Rational { base, empty_exponent } => {
346                if empty_exponent {
347                    let span = self.new_span(start, self.pos);
348                    self.dcx().err("expected at least one digit in exponent").span(span).emit();
349                }
350
351                let unsupported_base =
352                    matches!(base, Base::Binary | Base::Octal | Base::Hexadecimal);
353                if unsupported_base {
354                    let msg = format!("{base} rational numbers are not supported");
355                    self.dcx().err(msg).span(self.new_span(start, end)).emit();
356                }
357
358                (TokenLitKind::Rational, self.symbol_from_to(start, end))
359            }
360        }
361    }
362
363    fn cook_quoted(&self, kind: StrKind, start: BytePos, end: BytePos) -> Symbol {
364        // Account for quote (`"` or `'`) and prefix.
365        let content_start = start + 1 + BytePos(kind.prefix().len() as u32);
366        let content_end = end - 1;
367        let lit_content = self.str_from_to(content_start, content_end);
368        Symbol::intern(lit_content)
369    }
370
371    #[inline]
372    fn new_span(&self, lo: BytePos, hi: BytePos) -> Span {
373        Span::new(lo, hi)
374    }
375
376    #[inline]
377    fn src_index(&self, pos: BytePos) -> usize {
378        (pos - self.start_pos).to_usize()
379    }
380
381    /// Slice of the source text from `start` up to but excluding `self.pos`,
382    /// meaning the slice does not include the character `self.ch`.
383    fn symbol_from(&self, start: BytePos) -> Symbol {
384        self.symbol_from_to(start, self.pos)
385    }
386
387    /// Slice of the source text from `start` up to but excluding `self.pos`,
388    /// meaning the slice does not include the character `self.ch`.
389    fn str_from(&self, start: BytePos) -> &'src str {
390        self.str_from_to(start, self.pos)
391    }
392
393    /// Same as `symbol_from`, with an explicit endpoint.
394    fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
395        Symbol::intern(self.str_from_to(start, end))
396    }
397
398    /// Slice of the source text spanning from `start` up to but excluding `end`.
399    #[track_caller]
400    fn str_from_to(&self, start: BytePos, end: BytePos) -> &'src str {
401        &self.src[self.src_index(start)..self.src_index(end)]
402    }
403
404    /// Slice of the source text spanning from `start` until the end.
405    fn str_from_to_end(&self, start: BytePos) -> &'src str {
406        &self.src[self.src_index(start)..]
407    }
408}
409
410impl Iterator for Lexer<'_, '_> {
411    type Item = Token;
412
413    #[inline]
414    fn next(&mut self) -> Option<Token> {
415        let token = self.next_token();
416        if token.is_eof() { None } else { Some(token) }
417    }
418}
419
420impl std::iter::FusedIterator for Lexer<'_, '_> {}
421
422/// Pushes a character to a message string for error reporting
423fn escaped_char(c: char) -> String {
424    match c {
425        '\u{20}'..='\u{7e}' => {
426            // Don't escape \, ' or " for user-facing messages
427            c.to_string()
428        }
429        _ => c.escape_default().to_string(),
430    }
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436    use BinOpToken::*;
437    use TokenKind::*;
438    use std::ops::Range;
439
440    type Expected<'a> = &'a [(Range<usize>, TokenKind)];
441
442    fn check(src: &str, should_fail: bool, expected: Expected<'_>) {
443        let sess = Session::builder().with_silent_emitter(None).build();
444        let tokens: Vec<_> = Lexer::new(&sess, src)
445            .filter(|t| !t.is_comment())
446            .map(|t| (t.span.lo().to_usize()..t.span.hi().to_usize(), t.kind))
447            .collect();
448        assert_eq!(sess.dcx.has_errors().is_err(), should_fail, "{src:?}");
449        assert_eq!(tokens, expected, "{src:?}");
450    }
451
452    fn checks(tests: &[(&str, Expected<'_>)]) {
453        for &(src, expected) in tests {
454            check(src, false, expected);
455        }
456    }
457
458    fn checks_full(tests: &[(&str, bool, Expected<'_>)]) {
459        for &(src, should_fail, expected) in tests {
460            check(src, should_fail, expected);
461        }
462    }
463
464    fn lit(kind: TokenLitKind, symbol: &str) -> TokenKind {
465        Literal(kind, sym(symbol))
466    }
467
468    fn id(symbol: &str) -> TokenKind {
469        Ident(sym(symbol))
470    }
471
472    fn sym(s: &str) -> Symbol {
473        Symbol::intern(s)
474    }
475
476    #[test]
477    fn empty() {
478        checks(&[
479            ("", &[]),
480            (" ", &[]),
481            (" \n", &[]),
482            ("\n", &[]),
483            ("\n\t", &[]),
484            ("\n \t", &[]),
485            ("\n \t ", &[]),
486            (" \n \t \t", &[]),
487        ]);
488    }
489
490    #[test]
491    fn literals() {
492        use TokenLitKind::*;
493        solar_interface::SessionGlobals::default().set(|| {
494            checks(&[
495                ("\"\"", &[(0..2, lit(Str, ""))]),
496                ("\"\"\"\"", &[(0..2, lit(Str, "")), (2..4, lit(Str, ""))]),
497                ("\"\" \"\"", &[(0..2, lit(Str, "")), (3..5, lit(Str, ""))]),
498                ("\"\\\"\"", &[(0..4, lit(Str, "\\\""))]),
499                ("unicode\"\"", &[(0..9, lit(UnicodeStr, ""))]),
500                ("unicode \"\"", &[(0..7, id("unicode")), (8..10, lit(Str, ""))]),
501                ("hex\"\"", &[(0..5, lit(HexStr, ""))]),
502                ("hex \"\"", &[(0..3, id("hex")), (4..6, lit(Str, ""))]),
503                //
504                ("0", &[(0..1, lit(Integer, "0"))]),
505                ("0a", &[(0..1, lit(Integer, "0")), (1..2, id("a"))]),
506                ("0.e1", &[(0..1, lit(Integer, "0")), (1..2, Dot), (2..4, id("e1"))]),
507                (
508                    "0.e-1",
509                    &[
510                        (0..1, lit(Integer, "0")),
511                        (1..2, Dot),
512                        (2..3, id("e")),
513                        (3..4, BinOp(Minus)),
514                        (4..5, lit(Integer, "1")),
515                    ],
516                ),
517                ("0.0", &[(0..3, lit(Rational, "0.0"))]),
518                ("0.", &[(0..2, lit(Rational, "0."))]),
519                (".0", &[(0..2, lit(Rational, ".0"))]),
520                ("0.0e1", &[(0..5, lit(Rational, "0.0e1"))]),
521                ("0.0e-1", &[(0..6, lit(Rational, "0.0e-1"))]),
522                ("0e1", &[(0..3, lit(Rational, "0e1"))]),
523                ("0e1.", &[(0..3, lit(Rational, "0e1")), (3..4, Dot)]),
524            ]);
525
526            checks_full(&[
527                ("0b0", true, &[(0..3, lit(Integer, "0b0"))]),
528                ("0B0", false, &[(0..1, lit(Integer, "0")), (1..3, id("B0"))]),
529                ("0o0", true, &[(0..3, lit(Integer, "0o0"))]),
530                ("0O0", false, &[(0..1, lit(Integer, "0")), (1..3, id("O0"))]),
531                ("0xa", false, &[(0..3, lit(Integer, "0xa"))]),
532                ("0Xa", false, &[(0..1, lit(Integer, "0")), (1..3, id("Xa"))]),
533            ]);
534        });
535    }
536
537    #[test]
538    fn idents() {
539        solar_interface::SessionGlobals::default().set(|| {
540            checks(&[
541                ("$", &[(0..1, id("$"))]),
542                ("a$", &[(0..2, id("a$"))]),
543                ("a_$123_", &[(0..7, id("a_$123_"))]),
544                ("   b", &[(3..4, id("b"))]),
545                (" c\t ", &[(1..2, id("c"))]),
546                (" \td ", &[(2..3, id("d"))]),
547                (" \t\nef ", &[(3..5, id("ef"))]),
548                (" \t\n\tghi ", &[(4..7, id("ghi"))]),
549            ]);
550        });
551    }
552
553    #[test]
554    fn doc_comments() {
555        use CommentKind::*;
556
557        fn doc(kind: CommentKind, symbol: &str) -> TokenKind {
558            Comment(true, kind, sym(symbol))
559        }
560
561        solar_interface::SessionGlobals::default().set(|| {
562            checks(&[
563                ("// line comment", &[]),
564                ("// / line comment", &[]),
565                ("// ! line comment", &[]),
566                ("// /* line comment", &[]), // */ <-- aaron-bond.better-comments doesn't like this
567                ("/// line doc-comment", &[(0..20, doc(Line, " line doc-comment"))]),
568                ("//// invalid doc-comment", &[]),
569                ("///// invalid doc-comment", &[]),
570                //
571                ("/**/", &[]),
572                ("/***/", &[]),
573                ("/****/", &[]),
574                ("/*/*/", &[]),
575                ("/* /*/", &[]),
576                ("/*/**/", &[]),
577                ("/* /**/", &[]),
578                ("/* normal block comment */", &[]),
579                ("/* /* normal block comment */", &[]),
580                ("/** block doc-comment */", &[(0..24, doc(Block, " block doc-comment "))]),
581                ("/** /* block doc-comment */", &[(0..27, doc(Block, " /* block doc-comment "))]),
582                ("/** block doc-comment /*/", &[(0..25, doc(Block, " block doc-comment /"))]),
583            ]);
584        });
585    }
586
587    #[test]
588    fn operators() {
589        use Delimiter::*;
590        // From Solc `TOKEN_LIST`: https://github.com/ethereum/solidity/blob/194b114664c7daebc2ff68af3c573272f5d28913/liblangutil/Token.h#L67
591        checks(&[
592            (")", &[(0..1, CloseDelim(Parenthesis))]),
593            ("(", &[(0..1, OpenDelim(Parenthesis))]),
594            ("[", &[(0..1, OpenDelim(Bracket))]),
595            ("]", &[(0..1, CloseDelim(Bracket))]),
596            ("{", &[(0..1, OpenDelim(Brace))]),
597            ("}", &[(0..1, CloseDelim(Brace))]),
598            (":", &[(0..1, Colon)]),
599            (";", &[(0..1, Semi)]),
600            (".", &[(0..1, Dot)]),
601            ("?", &[(0..1, Question)]),
602            ("=>", &[(0..2, FatArrow)]),
603            ("->", &[(0..2, Arrow)]),
604            ("=", &[(0..1, Eq)]),
605            ("|=", &[(0..2, BinOpEq(Or))]),
606            ("^=", &[(0..2, BinOpEq(Caret))]),
607            ("&=", &[(0..2, BinOpEq(And))]),
608            ("<<=", &[(0..3, BinOpEq(Shl))]),
609            (">>=", &[(0..3, BinOpEq(Shr))]),
610            (">>>=", &[(0..4, BinOpEq(Sar))]),
611            ("+=", &[(0..2, BinOpEq(Plus))]),
612            ("-=", &[(0..2, BinOpEq(Minus))]),
613            ("*=", &[(0..2, BinOpEq(Star))]),
614            ("/=", &[(0..2, BinOpEq(Slash))]),
615            ("%=", &[(0..2, BinOpEq(Percent))]),
616            (",", &[(0..1, Comma)]),
617            ("||", &[(0..2, OrOr)]),
618            ("&&", &[(0..2, AndAnd)]),
619            ("|", &[(0..1, BinOp(Or))]),
620            ("^", &[(0..1, BinOp(Caret))]),
621            ("&", &[(0..1, BinOp(And))]),
622            ("<<", &[(0..2, BinOp(Shl))]),
623            (">>", &[(0..2, BinOp(Shr))]),
624            (">>>", &[(0..3, BinOp(Sar))]),
625            ("+", &[(0..1, BinOp(Plus))]),
626            ("-", &[(0..1, BinOp(Minus))]),
627            ("*", &[(0..1, BinOp(Star))]),
628            ("/", &[(0..1, BinOp(Slash))]),
629            ("%", &[(0..1, BinOp(Percent))]),
630            ("**", &[(0..2, StarStar)]),
631            ("==", &[(0..2, EqEq)]),
632            ("!=", &[(0..2, Ne)]),
633            ("<", &[(0..1, Lt)]),
634            (">", &[(0..1, Gt)]),
635            ("<=", &[(0..2, Le)]),
636            (">=", &[(0..2, Ge)]),
637            ("!", &[(0..1, Not)]),
638            ("~", &[(0..1, Tilde)]),
639            ("++", &[(0..2, PlusPlus)]),
640            ("--", &[(0..2, MinusMinus)]),
641            (":=", &[(0..2, Walrus)]),
642        ]);
643    }
644
645    #[test]
646    fn glueing() {
647        checks(&[
648            ("=", &[(0..1, Eq)]),
649            ("==", &[(0..2, EqEq)]),
650            ("= =", &[(0..1, Eq), (2..3, Eq)]),
651            ("===", &[(0..2, EqEq), (2..3, Eq)]),
652            ("== =", &[(0..2, EqEq), (3..4, Eq)]),
653            ("= ==", &[(0..1, Eq), (2..4, EqEq)]),
654            ("====", &[(0..2, EqEq), (2..4, EqEq)]),
655            ("== ==", &[(0..2, EqEq), (3..5, EqEq)]),
656            ("= ===", &[(0..1, Eq), (2..4, EqEq), (4..5, Eq)]),
657            ("=====", &[(0..2, EqEq), (2..4, EqEq), (4..5, Eq)]),
658            //
659            (" <", &[(1..2, Lt)]),
660            (" <=", &[(1..3, Le)]),
661            (" < =", &[(1..2, Lt), (3..4, Eq)]),
662            (" <<", &[(1..3, BinOp(Shl))]),
663            (" <<=", &[(1..4, BinOpEq(Shl))]),
664            //
665            (" >", &[(1..2, Gt)]),
666            (" >=", &[(1..3, Ge)]),
667            (" > =", &[(1..2, Gt), (3..4, Eq)]),
668            (" >>", &[(1..3, BinOp(Shr))]),
669            (" >>>", &[(1..4, BinOp(Sar))]),
670            (" >>>=", &[(1..5, BinOpEq(Sar))]),
671            //
672            ("+", &[(0..1, BinOp(Plus))]),
673            ("++", &[(0..2, PlusPlus)]),
674            ("+++", &[(0..2, PlusPlus), (2..3, BinOp(Plus))]),
675            ("+ =", &[(0..1, BinOp(Plus)), (2..3, Eq)]),
676            ("+ +=", &[(0..1, BinOp(Plus)), (2..4, BinOpEq(Plus))]),
677            ("+++=", &[(0..2, PlusPlus), (2..4, BinOpEq(Plus))]),
678            ("+ +", &[(0..1, BinOp(Plus)), (2..3, BinOp(Plus))]),
679            //
680            ("-", &[(0..1, BinOp(Minus))]),
681            ("--", &[(0..2, MinusMinus)]),
682            ("---", &[(0..2, MinusMinus), (2..3, BinOp(Minus))]),
683            ("- =", &[(0..1, BinOp(Minus)), (2..3, Eq)]),
684            ("- -=", &[(0..1, BinOp(Minus)), (2..4, BinOpEq(Minus))]),
685            ("---=", &[(0..2, MinusMinus), (2..4, BinOpEq(Minus))]),
686            ("- -", &[(0..1, BinOp(Minus)), (2..3, BinOp(Minus))]),
687        ]);
688    }
689}