1 // We want to be able to build this crate with a stable compiler, so feature
2 // flags should optional.
3 #![cfg_attr(not(feature = "unicode-xid"), feature(rustc_private))]
4 #![cfg_attr(not(feature = "unicode-xid"), feature(unicode_internals))]
8 use crate::cursor::{Cursor, EOF_CHAR};
15 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
18 BlockComment { terminated: bool },
22 Literal { kind: LiteralKind, suffix_start: usize },
23 Lifetime { starts_with_number: bool },
78 use self::TokenKind::*;
80 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
81 pub enum LiteralKind {
82 Int { base: Base, empty_int: bool },
83 Float { base: Base, empty_exponent: bool },
84 Char { terminated: bool },
85 Byte { terminated: bool },
86 Str { terminated: bool },
87 ByteStr { terminated: bool },
88 RawStr { n_hashes: usize, started: bool, terminated: bool },
89 RawByteStr { n_hashes: usize, started: bool, terminated: bool },
91 use self::LiteralKind::*;
93 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
102 fn new(kind: TokenKind, len: usize) -> Token {
107 pub fn strip_shebang(input: &str) -> Option<usize> {
108 debug_assert!(!input.is_empty());
109 if !input.starts_with("#!") || input.starts_with("#![") {
112 Some(input.find('\n').unwrap_or(input.len()))
115 pub fn first_token(input: &str) -> Token {
116 debug_assert!(!input.is_empty());
117 Cursor::new(input).advance_token()
120 pub fn tokenize(mut input: &str) -> impl Iterator<Item = Token> + '_ {
121 std::iter::from_fn(move || {
122 if input.is_empty() {
125 let token = first_token(input);
126 input = &input[token.len..];
132 fn advance_token(&mut self) -> Token {
133 let first_char = self.bump().unwrap();
134 let token_kind = match first_char {
135 '/' => match self.nth_char(0) {
136 '/' => self.line_comment(),
137 '*' => self.block_comment(),
139 if self.eat_assign() {
146 c if character_properties::is_whitespace(c) => self.whitespace(),
147 'r' => match (self.nth_char(0), self.nth_char(1)) {
148 ('#', c1) if character_properties::is_id_start(c1) => self.raw_ident(),
149 ('#', _) | ('"', _) => {
150 let (n_hashes, started, terminated) = self.raw_double_quoted_string();
151 let suffix_start = self.len_consumed();
153 self.eat_literal_suffix();
155 let kind = RawStr { n_hashes, started, terminated };
156 Literal { kind, suffix_start }
160 'b' => match (self.nth_char(0), self.nth_char(1)) {
163 let terminated = self.single_quoted_string();
164 let suffix_start = self.len_consumed();
166 self.eat_literal_suffix();
168 let kind = Byte { terminated };
169 Literal { kind, suffix_start }
173 let terminated = self.double_quoted_string();
174 let suffix_start = self.len_consumed();
176 self.eat_literal_suffix();
178 let kind = ByteStr { terminated };
179 Literal { kind, suffix_start }
181 ('r', '"') | ('r', '#') => {
183 let (n_hashes, started, terminated) = self.raw_double_quoted_string();
184 let suffix_start = self.len_consumed();
186 self.eat_literal_suffix();
188 let kind = RawByteStr { n_hashes, started, terminated };
189 Literal { kind, suffix_start }
193 c if character_properties::is_id_start(c) => self.ident(),
195 let literal_kind = self.number(c);
196 let suffix_start = self.len_consumed();
197 self.eat_literal_suffix();
198 TokenKind::Literal { kind: literal_kind, suffix_start }
203 if self.nth_char(0) == '.' {
205 if self.nth_char(0) == '.' {
208 } else if self.nth_char(0) == '=' {
229 if self.nth_char(0) == ':' {
238 if self.nth_char(0) == '=' {
241 } else if self.nth_char(0) == '>' {
249 if self.nth_char(0) == '=' {
256 '<' => match self.nth_char(0) {
263 if self.eat_assign() { ShlEq } else { Shl }
271 '>' => match self.nth_char(0) {
278 if self.eat_assign() { ShrEq } else { Shr }
283 if self.nth_char(0) == '>' {
287 if self.eat_assign() { MinusEq } else { Minus }
291 if self.nth_char(0) == '&' {
295 if self.eat_assign() { AndEq } else { And }
299 if self.nth_char(0) == '|' {
303 if self.eat_assign() { OrEq } else { Or }
307 if self.eat_assign() {
314 if self.eat_assign() {
321 if self.eat_assign() {
328 if self.eat_assign() {
334 '\'' => self.lifetime_or_char(),
336 let terminated = self.double_quoted_string();
337 let suffix_start = self.len_consumed();
339 self.eat_literal_suffix();
341 let kind = Str { terminated };
342 Literal { kind, suffix_start }
346 Token::new(token_kind, self.len_consumed())
349 fn line_comment(&mut self) -> TokenKind {
350 debug_assert!(self.prev() == '/' && self.nth_char(0) == '/');
353 match self.nth_char(0) {
355 '\r' if self.nth_char(1) == '\n' => break,
356 EOF_CHAR if self.is_eof() => break,
365 fn block_comment(&mut self) -> TokenKind {
366 debug_assert!(self.prev() == '/' && self.nth_char(0) == '*');
368 let mut depth = 1usize;
369 while let Some(c) = self.bump() {
371 '/' if self.nth_char(0) == '*' => {
375 '*' if self.nth_char(0) == '/' => {
386 BlockComment { terminated: depth == 0 }
389 fn whitespace(&mut self) -> TokenKind {
390 debug_assert!(character_properties::is_whitespace(self.prev()));
391 while character_properties::is_whitespace(self.nth_char(0)) {
397 fn raw_ident(&mut self) -> TokenKind {
400 && self.nth_char(0) == '#'
401 && character_properties::is_id_start(self.nth_char(1))
405 while character_properties::is_id_continue(self.nth_char(0)) {
411 fn ident(&mut self) -> TokenKind {
412 debug_assert!(character_properties::is_id_start(self.prev()));
413 while character_properties::is_id_continue(self.nth_char(0)) {
419 fn number(&mut self, first_digit: char) -> LiteralKind {
420 debug_assert!('0' <= self.prev() && self.prev() <= '9');
421 let mut base = Base::Decimal;
422 if first_digit == '0' {
423 let has_digits = match self.nth_char(0) {
427 self.eat_decimal_digits()
432 self.eat_decimal_digits()
435 base = Base::Hexadecimal;
437 self.eat_hexadecimal_digits()
439 '0'..='9' | '_' | '.' | 'e' | 'E' => {
440 self.eat_decimal_digits();
444 _ => return Int { base, empty_int: false },
447 return Int { base, empty_int: true };
450 self.eat_decimal_digits();
453 match self.nth_char(0) {
454 // Don't be greedy if this is actually an
455 // integer literal followed by field/method access or a range pattern
456 // (`0..2` and `12.foo()`)
457 '.' if self.nth_char(1) != '.'
458 && !character_properties::is_id_start(self.nth_char(1)) =>
460 // might have stuff after the ., and if it does, it needs to start
463 let mut empty_exponent = false;
464 if self.nth_char(0).is_digit(10) {
465 self.eat_decimal_digits();
466 match self.nth_char(0) {
469 empty_exponent = self.float_exponent().is_err()
474 Float { base, empty_exponent }
478 let empty_exponent = self.float_exponent().is_err();
479 Float { base, empty_exponent }
481 _ => Int { base, empty_int: false },
485 fn lifetime_or_char(&mut self) -> TokenKind {
486 debug_assert!(self.prev() == '\'');
487 let mut starts_with_number = false;
488 if (character_properties::is_id_start(self.nth_char(0))
489 || self.nth_char(0).is_digit(10) && {
490 starts_with_number = true;
493 && self.nth_char(1) != '\''
496 while character_properties::is_id_continue(self.nth_char(0)) {
500 return if self.nth_char(0) == '\'' {
502 let kind = Char { terminated: true };
503 Literal { kind, suffix_start: self.len_consumed() }
505 Lifetime { starts_with_number }
508 let terminated = self.single_quoted_string();
509 let suffix_start = self.len_consumed();
511 self.eat_literal_suffix();
513 let kind = Char { terminated };
514 return Literal { kind, suffix_start };
517 fn single_quoted_string(&mut self) -> bool {
518 debug_assert!(self.prev() == '\'');
519 // parse `'''` as a single char literal
520 if self.nth_char(0) == '\'' && self.nth_char(1) == '\'' {
523 let mut first = true;
525 match self.nth_char(0) {
526 '/' if !first => break,
527 '\n' if self.nth_char(1) != '\'' => break,
528 '\r' if self.nth_char(1) == '\n' => break,
529 EOF_CHAR if self.is_eof() => break,
547 fn double_quoted_string(&mut self) -> bool {
548 debug_assert!(self.prev() == '"');
550 match self.nth_char(0) {
555 EOF_CHAR if self.is_eof() => return false,
556 '\\' if self.nth_char(1) == '\\' || self.nth_char(1) == '"' => {
565 fn raw_double_quoted_string(&mut self) -> (usize, bool, bool) {
566 debug_assert!(self.prev() == 'r');
568 let mut acc: usize = 0;
571 Some('#') => acc += 1,
572 Some('"') => break acc,
573 None | Some(_) => return (acc, false, false),
581 let mut acc = n_hashes;
582 while self.nth_char(0) == '#' && acc > 0 {
587 return (n_hashes, true, true);
591 None => return (n_hashes, true, false),
596 fn eat_decimal_digits(&mut self) -> bool {
597 let mut has_digits = false;
599 match self.nth_char(0) {
613 fn eat_hexadecimal_digits(&mut self) -> bool {
614 let mut has_digits = false;
616 match self.nth_char(0) {
620 '0'..='9' | 'a'..='f' | 'A'..='F' => {
630 fn float_exponent(&mut self) -> Result<(), ()> {
631 debug_assert!(self.prev() == 'e' || self.prev() == 'E');
632 if self.nth_char(0) == '-' || self.nth_char(0) == '+' {
635 if self.eat_decimal_digits() { Ok(()) } else { Err(()) }
638 fn eat_literal_suffix(&mut self) {
639 if !character_properties::is_id_start(self.nth_char(0)) {
644 while character_properties::is_id_continue(self.nth_char(0)) {
649 fn eat_assign(&mut self) -> bool {
650 if self.nth_char(0) == '=' {
659 pub mod character_properties {
660 // this is Pattern_White_Space
661 #[cfg(feature = "unicode-xid")]
662 pub fn is_whitespace(c: char) -> bool {
664 '\u{0009}' | '\u{000A}' | '\u{000B}' | '\u{000C}' | '\u{000D}' | '\u{0020}'
665 | '\u{0085}' | '\u{200E}' | '\u{200F}' | '\u{2028}' | '\u{2029}' => true,
670 #[cfg(not(feature = "unicode-xid"))]
671 pub fn is_whitespace(c: char) -> bool {
672 core::unicode::property::Pattern_White_Space(c)
675 // this is XID_Start OR '_' (which formally is not a XID_Start)
676 #[cfg(feature = "unicode-xid")]
677 pub fn is_id_start(c: char) -> bool {
678 ('a' <= c && c <= 'z')
679 || ('A' <= c && c <= 'Z')
681 || (c > '\x7f' && unicode_xid::UnicodeXID::is_xid_start(c))
684 #[cfg(not(feature = "unicode-xid"))]
685 pub fn is_id_start(c: char) -> bool {
686 ('a' <= c && c <= 'z')
687 || ('A' <= c && c <= 'Z')
689 || (c > '\x7f' && c.is_xid_start())
692 // this is XID_Continue
693 #[cfg(feature = "unicode-xid")]
694 pub fn is_id_continue(c: char) -> bool {
695 ('a' <= c && c <= 'z')
696 || ('A' <= c && c <= 'Z')
697 || ('0' <= c && c <= '9')
699 || (c > '\x7f' && unicode_xid::UnicodeXID::is_xid_continue(c))
702 #[cfg(not(feature = "unicode-xid"))]
703 pub fn is_id_continue(c: char) -> bool {
704 ('a' <= c && c <= 'z')
705 || ('A' <= c && c <= 'Z')
706 || ('0' <= c && c <= '9')
708 || (c > '\x7f' && c.is_xid_continue())