Skip to main content

solar_parse/lexer/
mod.rs

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