Skip to main content

solar_parse/lexer/cursor/
mod.rs

1//! Low-level Solidity lexer.
2//!
3//! Modified from Rust's [`rustc_lexer`](https://github.com/rust-lang/rust/blob/45749b21b7fd836f6c4f11dd40376f7c83e2791b/compiler/rustc_lexer/src/lib.rs).
4
5use memchr::memmem;
6use solar_ast::{
7    Base, StrKind,
8    token::{BinOpToken, Delimiter},
9};
10use solar_data_structures::hint::{likely, unlikely};
11use std::sync::OnceLock;
12
13pub mod token;
14use token::{RawLiteralKind, RawToken, RawTokenKind};
15
16mod char_info;
17pub use char_info::*;
18
19#[cfg(test)]
20mod tests;
21
22/// Peekable iterator over a char sequence.
23///
24/// Next characters can be peeked via `first` method,
25/// and position can be shifted forward via `bump` method.
26#[derive(Clone, Debug)]
27pub struct Cursor<'a> {
28    bytes: std::slice::Iter<'a, u8>,
29}
30
31impl<'a> Cursor<'a> {
32    /// Creates a new cursor over the given input string slice.
33    #[inline]
34    pub fn new(input: &'a str) -> Self {
35        Cursor { bytes: input.as_bytes().iter() }
36    }
37
38    /// Creates a new iterator that also returns the position of each token in the input string.
39    ///
40    /// Note that the position currently always starts at 0 when this method is called, so if called
41    /// after tokens are parsed the position will be relative to when this method is called, not the
42    /// beginning of the string.
43    #[inline]
44    pub fn with_position(self) -> CursorWithPosition<'a> {
45        CursorWithPosition::new(self)
46    }
47
48    /// Slops up a token from the input string.
49    ///
50    /// Advances the cursor by the length of the token.
51    /// Prefer using `Cursor::with_position`, or using it as an iterator instead.
52    pub fn slop(&mut self) -> RawToken {
53        // Use the pointer instead of the length to track how many bytes were consumed, since
54        // internally the iterator is a pair of `start` and `end` pointers.
55        let start = self.as_ptr();
56
57        let Some(first_char) = self.bump_ret() else { return RawToken::EOF };
58        let token_kind = self.advance_token_kind(first_char);
59
60        // SAFETY: `start` points to the same string.
61        let len = unsafe { self.as_ptr().offset_from_unsigned(start) };
62
63        RawToken::new(token_kind, len as u32)
64    }
65
66    #[inline]
67    fn advance_token_kind(&mut self, first_char: u8) -> RawTokenKind {
68        match first_char {
69            // Slash, comment or block comment.
70            b'/' => match self.first() {
71                b'/' => self.line_comment(),
72                b'*' => self.block_comment(),
73                b'=' => {
74                    self.bump();
75                    RawTokenKind::BinOpEq(BinOpToken::Slash)
76                }
77                _ => RawTokenKind::BinOp(BinOpToken::Slash),
78            },
79
80            // Whitespace sequence.
81            c if is_whitespace_byte(c) => self.whitespace(),
82
83            // Identifier. This should be checked after other variants that can start as identifier.
84            c if is_id_start_byte(c) => self.ident_or_prefixed_literal(c),
85
86            // Numeric literal.
87            b'0'..=b'9' => {
88                let kind = self.number(first_char);
89                RawTokenKind::Literal { kind }
90            }
91            b'.' if self.first().is_ascii_digit() => {
92                let kind = self.rational_number_after_dot(Base::Decimal);
93                RawTokenKind::Literal { kind }
94            }
95
96            // One-symbol tokens.
97            b';' => RawTokenKind::Semi,
98            b',' => RawTokenKind::Comma,
99            b'.' => RawTokenKind::Dot,
100            b'(' => RawTokenKind::OpenDelim(Delimiter::Parenthesis),
101            b')' => RawTokenKind::CloseDelim(Delimiter::Parenthesis),
102            b'{' => RawTokenKind::OpenDelim(Delimiter::Brace),
103            b'}' => RawTokenKind::CloseDelim(Delimiter::Brace),
104            b'[' => RawTokenKind::OpenDelim(Delimiter::Bracket),
105            b']' => RawTokenKind::CloseDelim(Delimiter::Bracket),
106            b'~' => RawTokenKind::Tilde,
107            b'?' => RawTokenKind::Question,
108
109            // Multi-character tokens.
110            // : :=
111            b':' => match self.first() {
112                b'=' => {
113                    self.bump();
114                    RawTokenKind::Walrus
115                }
116                _ => RawTokenKind::Colon,
117            },
118            // = == =>
119            b'=' => match self.first() {
120                b'=' => {
121                    self.bump();
122                    RawTokenKind::EqEq
123                }
124                b'>' => {
125                    self.bump();
126                    RawTokenKind::FatArrow
127                }
128                _ => RawTokenKind::Eq,
129            },
130            // ! !=
131            b'!' => match self.first() {
132                b'=' => {
133                    self.bump();
134                    RawTokenKind::Ne
135                }
136                _ => RawTokenKind::Not,
137            },
138            // < <= << <<=
139            b'<' => match self.first() {
140                b'=' => {
141                    self.bump();
142                    RawTokenKind::Le
143                }
144                b'<' => {
145                    self.bump();
146                    if self.first() == b'=' {
147                        self.bump();
148                        RawTokenKind::BinOpEq(BinOpToken::Shl)
149                    } else {
150                        RawTokenKind::BinOp(BinOpToken::Shl)
151                    }
152                }
153                _ => RawTokenKind::Lt,
154            },
155            // https://github.com/rust-lang/rustfmt/issues/6660
156            // `> >= >> >>= >>> >>>=`
157            b'>' => match self.first() {
158                b'=' => {
159                    self.bump();
160                    RawTokenKind::Ge
161                }
162                b'>' => {
163                    self.bump();
164                    match self.first() {
165                        b'>' => {
166                            self.bump();
167                            if self.first() == b'=' {
168                                self.bump();
169                                RawTokenKind::BinOpEq(BinOpToken::Sar)
170                            } else {
171                                RawTokenKind::BinOp(BinOpToken::Sar)
172                            }
173                        }
174                        b'=' => {
175                            self.bump();
176                            RawTokenKind::BinOpEq(BinOpToken::Shr)
177                        }
178                        _ => RawTokenKind::BinOp(BinOpToken::Shr),
179                    }
180                }
181                _ => RawTokenKind::Gt,
182            },
183            // - -- -= ->
184            b'-' => match self.first() {
185                b'-' => {
186                    self.bump();
187                    RawTokenKind::MinusMinus
188                }
189                b'=' => {
190                    self.bump();
191                    RawTokenKind::BinOpEq(BinOpToken::Minus)
192                }
193                b'>' => {
194                    self.bump();
195                    RawTokenKind::Arrow
196                }
197                _ => RawTokenKind::BinOp(BinOpToken::Minus),
198            },
199            // & && &=
200            b'&' => match self.first() {
201                b'&' => {
202                    self.bump();
203                    RawTokenKind::AndAnd
204                }
205                b'=' => {
206                    self.bump();
207                    RawTokenKind::BinOpEq(BinOpToken::And)
208                }
209                _ => RawTokenKind::BinOp(BinOpToken::And),
210            },
211            // | || |=
212            b'|' => match self.first() {
213                b'|' => {
214                    self.bump();
215                    RawTokenKind::OrOr
216                }
217                b'=' => {
218                    self.bump();
219                    RawTokenKind::BinOpEq(BinOpToken::Or)
220                }
221                _ => RawTokenKind::BinOp(BinOpToken::Or),
222            },
223            // + ++ +=
224            b'+' => match self.first() {
225                b'+' => {
226                    self.bump();
227                    RawTokenKind::PlusPlus
228                }
229                b'=' => {
230                    self.bump();
231                    RawTokenKind::BinOpEq(BinOpToken::Plus)
232                }
233                _ => RawTokenKind::BinOp(BinOpToken::Plus),
234            },
235            // * ** *=
236            b'*' => match self.first() {
237                b'*' => {
238                    self.bump();
239                    RawTokenKind::StarStar
240                }
241                b'=' => {
242                    self.bump();
243                    RawTokenKind::BinOpEq(BinOpToken::Star)
244                }
245                _ => RawTokenKind::BinOp(BinOpToken::Star),
246            },
247            // ^ ^=
248            b'^' => match self.first() {
249                b'=' => {
250                    self.bump();
251                    RawTokenKind::BinOpEq(BinOpToken::Caret)
252                }
253                _ => RawTokenKind::BinOp(BinOpToken::Caret),
254            },
255            // % %=
256            b'%' => match self.first() {
257                b'=' => {
258                    self.bump();
259                    RawTokenKind::BinOpEq(BinOpToken::Percent)
260                }
261                _ => RawTokenKind::BinOp(BinOpToken::Percent),
262            },
263            b'@' => RawTokenKind::At,
264
265            // String literal.
266            b'\'' | b'"' => {
267                let terminated = self.eat_string(first_char);
268                let kind = RawLiteralKind::Str { kind: StrKind::Str, terminated };
269                RawTokenKind::Literal { kind }
270            }
271
272            _ => {
273                if unlikely(!first_char.is_ascii()) {
274                    self.bump_utf8_with(first_char);
275                }
276                RawTokenKind::Unknown
277            }
278        }
279    }
280
281    #[inline(never)]
282    fn line_comment(&mut self) -> RawTokenKind {
283        debug_assert!(self.prev() == b'/' && self.first() == b'/');
284        self.bump();
285
286        // `////` (more than 3 slashes) is not considered a doc comment.
287        let is_doc = matches!(self.first(), b'/' if self.second() != b'/');
288
289        // Take into account Windows line ending (CRLF)
290        self.eat_until_either(b'\n', b'\r');
291        RawTokenKind::LineComment { is_doc }
292    }
293
294    #[inline(never)]
295    fn block_comment(&mut self) -> RawTokenKind {
296        debug_assert!(self.prev() == b'/' && self.first() == b'*');
297        self.bump();
298
299        // `/***` (more than 2 stars) is not considered a doc comment.
300        // `/**/` is not considered a doc comment.
301        let is_doc = matches!(self.first(), b'*' if !matches!(self.second(), b'*' | b'/'));
302
303        let b = self.as_bytes();
304        static FINDER: OnceLock<memmem::Finder<'static>> = OnceLock::new();
305        let (terminated, n) = FINDER
306            .get_or_init(|| memmem::Finder::new(b"*/"))
307            .find(b)
308            .map_or((false, b.len()), |pos| (true, pos + 2));
309        self.ignore_bytes(n);
310
311        RawTokenKind::BlockComment { is_doc, terminated }
312    }
313
314    fn whitespace(&mut self) -> RawTokenKind {
315        debug_assert!(is_whitespace_byte(self.prev()));
316        self.eat_while(is_whitespace_byte);
317        RawTokenKind::Whitespace
318    }
319
320    fn ident_or_prefixed_literal(&mut self, first: u8) -> RawTokenKind {
321        debug_assert!(is_id_start_byte(self.prev()));
322
323        // Start is already eaten, eat the rest of identifier.
324        let start = self.as_ptr();
325        self.eat_while(is_id_continue_byte);
326
327        // Check if the identifier is a string literal prefix.
328        if unlikely(matches!(first, b'h' | b'u')) {
329            // SAFETY: within bounds and lifetime of `self.chars`.
330            let id = unsafe {
331                let start = start.sub(1);
332                std::slice::from_raw_parts(start, self.as_ptr().offset_from_unsigned(start))
333            };
334            let is_hex = id == b"hex";
335            if (is_hex || id == b"unicode")
336                && let quote @ (b'\'' | b'"') = self.first()
337            {
338                self.bump();
339                let terminated = self.eat_string(quote);
340                let kind = if is_hex { StrKind::Hex } else { StrKind::Unicode };
341                return RawTokenKind::Literal { kind: RawLiteralKind::Str { kind, terminated } };
342            }
343        }
344
345        RawTokenKind::Ident
346    }
347
348    fn number(&mut self, first_digit: u8) -> RawLiteralKind {
349        debug_assert!(self.prev().is_ascii_digit());
350        let mut base = Base::Decimal;
351        if first_digit == b'0' {
352            // Attempt to parse encoding base.
353            let has_digits = match self.first() {
354                b'b' => {
355                    base = Base::Binary;
356                    self.bump();
357                    self.eat_decimal_digits()
358                }
359                b'o' => {
360                    base = Base::Octal;
361                    self.bump();
362                    self.eat_decimal_digits()
363                }
364                b'x' => {
365                    base = Base::Hexadecimal;
366                    self.bump();
367                    self.eat_hexadecimal_digits()
368                }
369                // Not a base prefix.
370                b'0'..=b'9' | b'_' | b'.' | b'e' | b'E' => {
371                    self.eat_decimal_digits();
372                    true
373                }
374                // Just a 0.
375                _ => return RawLiteralKind::Int { base, empty_int: false },
376            };
377            // Base prefix was provided, but there were no digits after it, e.g. "0x".
378            if !has_digits {
379                return RawLiteralKind::Int { base, empty_int: true };
380            }
381        } else {
382            // No base prefix, parse number in the usual way.
383            self.eat_decimal_digits();
384        };
385
386        match self.first() {
387            // Don't be greedy if this is actually an integer literal followed by field/method
388            // access (`12.foo()`).
389            // `_` is special cased, we assume it's always an invalid rational: https://github.com/argotorg/solidity/blob/c012b725bb8ce755b93ce0dd05e83c34c499acd6/liblangutil/Scanner.cpp#L979
390            b'.' if !is_id_start_byte(self.second()) || self.second() == b'_' => {
391                self.bump();
392                self.rational_number_after_dot(base)
393            }
394            b'e' | b'E' => {
395                self.bump();
396                let empty_exponent = !self.eat_exponent();
397                RawLiteralKind::Rational { base, empty_exponent }
398            }
399            _ => RawLiteralKind::Int { base, empty_int: false },
400        }
401    }
402
403    #[cold]
404    fn rational_number_after_dot(&mut self, base: Base) -> RawLiteralKind {
405        self.eat_decimal_digits();
406        let empty_exponent = match self.first() {
407            b'e' | b'E' => {
408                self.bump();
409                !self.eat_exponent()
410            }
411            _ => false,
412        };
413        RawLiteralKind::Rational { base, empty_exponent }
414    }
415
416    /// Eats a string until the given quote character. Returns `true` if the string was terminated.
417    fn eat_string(&mut self, quote: u8) -> bool {
418        debug_assert_eq!(self.prev(), quote);
419        loop {
420            if unlikely(!self.eat_until_either(quote, b'\\')) {
421                return false;
422            }
423            // SAFETY: `eat_until_either` returns `true` if `quote` or `b'\\'` was found.
424            let c = unsafe { self.bump_ret().unwrap_unchecked() };
425            if likely(c == quote) {
426                return true;
427            }
428            // `\\` or `\"`: skip the escaped character.
429            debug_assert_eq!(c, b'\\');
430            let next = self.first();
431            if next == b'\\' || next == quote {
432                // Bump again to skip escaped character.
433                self.bump();
434            }
435        }
436    }
437
438    /// Eats characters for a decimal number. Returns `true` if any digits were encountered.
439    fn eat_decimal_digits(&mut self) -> bool {
440        self.eat_digits(is_decimal_digit)
441    }
442
443    /// Eats characters for a hexadecimal number. Returns `true` if any digits were encountered.
444    fn eat_hexadecimal_digits(&mut self) -> bool {
445        self.eat_digits(is_hex_digit)
446    }
447
448    fn eat_digits(&mut self, mut is_digit: impl FnMut(u8) -> bool) -> bool {
449        let mut has_digits = false;
450        loop {
451            match self.first() {
452                b'_' => {
453                    self.bump();
454                }
455                c if is_digit(c) => {
456                    has_digits = true;
457                    self.bump();
458                }
459                _ => break,
460            }
461        }
462        has_digits
463    }
464
465    /// Eats the exponent. Returns `true` if any digits were encountered.
466    fn eat_exponent(&mut self) -> bool {
467        debug_assert!(self.prev() == b'e' || self.prev() == b'E');
468        // b'+' is not a valid prefix for an exponent, but we accept it here and let the parser
469        // reject it later.
470        if matches!(self.first(), b'-' | b'+') {
471            self.bump();
472        }
473        self.eat_decimal_digits()
474    }
475
476    /// Returns the remaining input as a byte slice.
477    #[inline]
478    pub fn as_bytes(&self) -> &'a [u8] {
479        self.bytes.as_slice()
480    }
481
482    /// Returns the pointer to the first byte of the remaining input.
483    #[inline]
484    pub fn as_ptr(&self) -> *const u8 {
485        self.bytes.as_slice().as_ptr()
486    }
487
488    /// Returns the last eaten byte.
489    #[inline]
490    fn prev(&self) -> u8 {
491        // SAFETY: We always bump at least one character before calling this method.
492        unsafe { *self.as_ptr().sub(1) }
493    }
494
495    /// Peeks the next byte from the input stream without consuming it.
496    /// If requested position doesn't exist, `EOF` is returned.
497    /// However, getting `EOF` doesn't always mean actual end of file,
498    /// it should be checked with `is_eof` method.
499    #[inline]
500    fn first(&self) -> u8 {
501        self.peek_byte(0)
502    }
503
504    /// Peeks the second byte from the input stream without consuming it.
505    #[inline]
506    fn second(&self) -> u8 {
507        // This function is only called after `first` was called and checked, so in practice it
508        // doesn't matter if it's part of the first UTF-8 character.
509        self.peek_byte(1)
510    }
511
512    // Do not use directly.
513    #[doc(hidden)]
514    #[inline]
515    fn peek_byte(&self, index: usize) -> u8 {
516        self.as_bytes().get(index).copied().unwrap_or(EOF)
517    }
518
519    /// Moves to the next character.
520    fn bump(&mut self) {
521        self.bytes.next();
522    }
523
524    /// Skips to the end of the current UTF-8 character sequence, with `x` as the first byte.
525    ///
526    /// Assumes that `x` is the previously consumed byte.
527    #[cold]
528    #[allow(clippy::match_overlapping_arm)]
529    fn bump_utf8_with(&mut self, x: u8) {
530        debug_assert_eq!(self.prev(), x);
531        let skip = match x {
532            ..0x80 => 0,
533            ..0xE0 => 1,
534            ..0xF0 => 2,
535            _ => 3,
536        };
537        // NOTE: The internal iterator was created with from valid UTF-8 string, so we can freely
538        // skip bytes here without checking bounds.
539        self.ignore_bytes(skip);
540    }
541
542    /// Moves to the next character, returning the current one.
543    fn bump_ret(&mut self) -> Option<u8> {
544        let c = self.as_bytes().first().copied();
545        self.bytes.next();
546        c
547    }
548
549    /// Advances `n` bytes.
550    #[inline]
551    #[cfg_attr(debug_assertions, track_caller)]
552    fn ignore_bytes(&mut self, n: usize) {
553        debug_assert!(n <= self.as_bytes().len());
554        self.bytes = unsafe { self.as_bytes().get_unchecked(n..) }.iter();
555    }
556
557    /// Eats symbols until `ch1` or `ch2` is found or until the end of file is reached.
558    ///
559    /// Returns `true` if `ch1` or `ch2` was found, `false` if the end of file was reached.
560    #[inline]
561    fn eat_until_either(&mut self, ch1: u8, ch2: u8) -> bool {
562        let b = self.as_bytes();
563        let res = memchr::memchr2(ch1, ch2, b);
564        self.ignore_bytes(res.unwrap_or(b.len()));
565        res.is_some()
566    }
567
568    /// Eats symbols while predicate returns true or until the end of file is reached.
569    #[inline]
570    fn eat_while(&mut self, mut predicate: impl FnMut(u8) -> bool) {
571        while predicate(self.first()) {
572            self.bump();
573        }
574    }
575}
576
577impl Iterator for Cursor<'_> {
578    type Item = RawToken;
579
580    #[inline]
581    fn next(&mut self) -> Option<Self::Item> {
582        let token = self.slop();
583        if token.kind == RawTokenKind::Eof { None } else { Some(token) }
584    }
585}
586
587impl std::iter::FusedIterator for Cursor<'_> {}
588
589/// [`Cursor`] that also tracks the position of each token in the input string.
590///
591/// Created by calling [`Cursor::with_position`]. See that method and [`Cursor`] for more details.
592#[derive(Clone, Debug)]
593pub struct CursorWithPosition<'a> {
594    cursor: Cursor<'a>,
595    position: u32,
596}
597
598impl<'a> CursorWithPosition<'a> {
599    /// Creates a new cursor with position tracking from the given cursor.
600    #[inline]
601    fn new(cursor: Cursor<'a>) -> Self {
602        CursorWithPosition { cursor, position: 0 }
603    }
604
605    /// Returns a reference to the inner cursor.
606    #[inline]
607    pub fn inner(&self) -> &Cursor<'a> {
608        &self.cursor
609    }
610
611    /// Returns a mutable reference to the inner cursor.
612    #[inline]
613    pub fn inner_mut(&mut self) -> &mut Cursor<'a> {
614        &mut self.cursor
615    }
616
617    /// Returns the current position in the input string.
618    #[inline]
619    pub fn position(&self) -> usize {
620        self.position as usize
621    }
622}
623
624impl Iterator for CursorWithPosition<'_> {
625    type Item = (usize, RawToken);
626
627    #[inline]
628    fn next(&mut self) -> Option<Self::Item> {
629        self.cursor.next().map(|t| {
630            let pos = self.position;
631            self.position = pos + t.len;
632            (pos as usize, t)
633        })
634    }
635
636    #[inline]
637    fn size_hint(&self) -> (usize, Option<usize>) {
638        self.cursor.size_hint()
639    }
640}
641
642impl std::iter::FusedIterator for CursorWithPosition<'_> {}