1 //! Low-level Rust lexer.
3 //! The idea with `rustc_lexer` is to make a reusable library,
4 //! by separating out pure lexing and rustc-specific concerns, like spans,
5 //! error reporting, and interning. So, rustc_lexer operates directly on `&str`,
6 //! produces simple tokens which are a pair of type-tag and a bit of original text,
7 //! and does not report errors, instead storing them as flags on the token.
9 //! Tokens produced by this lexer are not yet ready for parsing the Rust syntax.
10 //! For that see [`rustc_parse::lexer`], which converts this basic token stream
11 //! into wide tokens used by actual parser.
13 //! The purpose of this crate is to convert raw sources into a labeled sequence
14 //! of well-known token types, so building an actual Rust token stream will
17 //! The main entity of this crate is the [`TokenKind`] enum which represents common
20 //! [`rustc_parse::lexer`]: ../rustc_parse/lexer/index.html
21 #![deny(rustc::untranslatable_diagnostic)]
22 #![deny(rustc::diagnostic_outside_of_impl)]
23 // We want to be able to build this crate with a stable compiler, so no
24 // `#![feature]` attributes should be added.
32 pub use crate::cursor::Cursor;
34 use self::LiteralKind::*;
35 use self::TokenKind::*;
36 use crate::cursor::EOF_CHAR;
37 use std::convert::TryFrom;
40 /// It doesn't contain information about data that has been parsed,
41 /// only the type of the token and its size.
49 fn new(kind: TokenKind, len: u32) -> Token {
54 /// Enum representing common lexeme types.
55 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
59 LineComment { doc_style: Option<DocStyle> },
61 /// `/* block comment */`
63 /// Block comments can be recursive, so a sequence like `/* /* */`
64 /// will not be considered terminated and will result in a parsing error.
65 BlockComment { doc_style: Option<DocStyle>, terminated: bool },
67 /// Any whitespace character sequence.
70 /// "ident" or "continue"
72 /// At this step, keywords are also considered identifiers.
75 /// Like the above, but containing invalid unicode codepoints.
81 /// An unknown prefix, like `foo#`, `foo'`, `foo"`.
83 /// Note that only the
84 /// prefix (`foo`) is included in the token, not the separator (which is
85 /// lexed as its own distinct token). In Rust 2021 and later, reserved
86 /// prefixes are reported as errors; in earlier editions, they result in a
87 /// (allowed by default) lint, and are treated as regular identifier
91 /// Examples: `"12_u8"`, `"1.0e-40"`, `b"123`.
93 /// See [LiteralKind] for more details.
94 Literal { kind: LiteralKind, suffix_start: u32 },
97 Lifetime { starts_with_number: bool },
155 /// Unknown token, not expected by the lexer, e.g. "№"
162 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
168 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
169 pub enum LiteralKind {
170 /// "12_u8", "0o100", "0b120i99"
171 Int { base: Base, empty_int: bool },
172 /// "12.34f32", "0b100.100"
173 Float { base: Base, empty_exponent: bool },
174 /// "'a'", "'\\'", "'''", "';"
175 Char { terminated: bool },
176 /// "b'a'", "b'\\'", "b'''", "b';"
177 Byte { terminated: bool },
179 Str { terminated: bool },
180 /// "b"abc"", "b"abc"
181 ByteStr { terminated: bool },
182 /// "r"abc"", "r#"abc"#", "r####"ab"###"c"####", "r#"a". `None` indicates
183 /// an invalid literal.
184 RawStr { n_hashes: Option<u8> },
185 /// "br"abc"", "br#"abc"#", "br####"ab"###"c"####", "br#"a". `None`
186 /// indicates an invalid literal.
187 RawByteStr { n_hashes: Option<u8> },
190 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
191 pub enum RawStrError {
192 /// Non `#` characters exist between `r` and `"`, e.g. `r##~"abcde"##`
193 InvalidStarter { bad_char: char },
194 /// The string was not terminated, e.g. `r###"abcde"##`.
195 /// `possible_terminator_offset` is the number of characters after `r` or
196 /// `br` where they may have intended to terminate it.
197 NoTerminator { expected: u32, found: u32, possible_terminator_offset: Option<u32> },
198 /// More than 255 `#`s exist.
199 TooManyDelimiters { found: u32 },
202 /// Base of numeric literal encoding according to its prefix.
203 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
205 /// Literal starts with "0b".
207 /// Literal starts with "0o".
209 /// Literal doesn't contain a prefix.
211 /// Literal starts with "0x".
215 /// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun",
216 /// but shebang isn't a part of rust syntax.
217 pub fn strip_shebang(input: &str) -> Option<usize> {
218 // Shebang must start with `#!` literally, without any preceding whitespace.
219 // For simplicity we consider any line starting with `#!` a shebang,
220 // regardless of restrictions put on shebangs by specific platforms.
221 if let Some(input_tail) = input.strip_prefix("#!") {
222 // Ok, this is a shebang but if the next non-whitespace token is `[`,
223 // then it may be valid Rust code, so consider it Rust code.
224 let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| {
227 TokenKind::Whitespace
228 | TokenKind::LineComment { doc_style: None }
229 | TokenKind::BlockComment { doc_style: None, .. }
232 if next_non_whitespace_token != Some(TokenKind::OpenBracket) {
233 // No other choice than to consider this a shebang.
234 return Some(2 + input_tail.lines().next().unwrap_or_default().len());
240 /// Validates a raw string literal. Used for getting more information about a
241 /// problem with a `RawStr`/`RawByteStr` with a `None` field.
243 pub fn validate_raw_str(input: &str, prefix_len: u32) -> Result<(), RawStrError> {
244 debug_assert!(!input.is_empty());
245 let mut cursor = Cursor::new(input);
246 // Move past the leading `r` or `br`.
247 for _ in 0..prefix_len {
248 cursor.bump().unwrap();
250 cursor.raw_double_quoted_string(prefix_len).map(|_| ())
253 /// Creates an iterator that produces tokens from the input string.
254 pub fn tokenize(input: &str) -> impl Iterator<Item = Token> + '_ {
255 let mut cursor = Cursor::new(input);
256 std::iter::from_fn(move || {
257 let token = cursor.advance_token();
258 if token.kind != TokenKind::Eof { Some(token) } else { None }
262 /// True if `c` is considered a whitespace according to Rust language definition.
263 /// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html)
264 /// for definitions of these classes.
265 pub fn is_whitespace(c: char) -> bool {
266 // This is Pattern_White_Space.
268 // Note that this set is stable (ie, it doesn't change with different
269 // Unicode versions), so it's ok to just hard-code the values.
273 // Usual ASCII suspects
276 | '\u{000B}' // vertical tab
277 | '\u{000C}' // form feed
279 | '\u{0020}' // space
281 // NEXT LINE from latin1
285 | '\u{200E}' // LEFT-TO-RIGHT MARK
286 | '\u{200F}' // RIGHT-TO-LEFT MARK
288 // Dedicated whitespace characters from Unicode
289 | '\u{2028}' // LINE SEPARATOR
290 | '\u{2029}' // PARAGRAPH SEPARATOR
294 /// True if `c` is valid as a first character of an identifier.
295 /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
296 /// a formal definition of valid identifier name.
297 pub fn is_id_start(c: char) -> bool {
298 // This is XID_Start OR '_' (which formally is not a XID_Start).
299 c == '_' || unicode_xid::UnicodeXID::is_xid_start(c)
302 /// True if `c` is valid as a non-first character of an identifier.
303 /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for
304 /// a formal definition of valid identifier name.
305 pub fn is_id_continue(c: char) -> bool {
306 unicode_xid::UnicodeXID::is_xid_continue(c)
309 /// The passed string is lexically an identifier.
310 pub fn is_ident(string: &str) -> bool {
311 let mut chars = string.chars();
312 if let Some(start) = chars.next() {
313 is_id_start(start) && chars.all(is_id_continue)
320 /// Parses a token from the input string.
321 pub fn advance_token(&mut self) -> Token {
322 let first_char = match self.bump() {
324 None => return Token::new(TokenKind::Eof, 0),
326 let token_kind = match first_char {
327 // Slash, comment or block comment.
328 '/' => match self.first() {
329 '/' => self.line_comment(),
330 '*' => self.block_comment(),
334 // Whitespace sequence.
335 c if is_whitespace(c) => self.whitespace(),
337 // Raw identifier, raw string literal or identifier.
338 'r' => match (self.first(), self.second()) {
339 ('#', c1) if is_id_start(c1) => self.raw_ident(),
340 ('#', _) | ('"', _) => {
341 let res = self.raw_double_quoted_string(1);
342 let suffix_start = self.pos_within_token();
344 self.eat_literal_suffix();
346 let kind = RawStr { n_hashes: res.ok() };
347 Literal { kind, suffix_start }
349 _ => self.ident_or_unknown_prefix(),
352 // Byte literal, byte string literal, raw byte string literal or identifier.
353 'b' => match (self.first(), self.second()) {
356 let terminated = self.single_quoted_string();
357 let suffix_start = self.pos_within_token();
359 self.eat_literal_suffix();
361 let kind = Byte { terminated };
362 Literal { kind, suffix_start }
366 let terminated = self.double_quoted_string();
367 let suffix_start = self.pos_within_token();
369 self.eat_literal_suffix();
371 let kind = ByteStr { terminated };
372 Literal { kind, suffix_start }
374 ('r', '"') | ('r', '#') => {
376 let res = self.raw_double_quoted_string(2);
377 let suffix_start = self.pos_within_token();
379 self.eat_literal_suffix();
381 let kind = RawByteStr { n_hashes: res.ok() };
382 Literal { kind, suffix_start }
384 _ => self.ident_or_unknown_prefix(),
387 // Identifier (this should be checked after other variant that can
388 // start as identifier).
389 c if is_id_start(c) => self.ident_or_unknown_prefix(),
393 let literal_kind = self.number(c);
394 let suffix_start = self.pos_within_token();
395 self.eat_literal_suffix();
396 TokenKind::Literal { kind: literal_kind, suffix_start }
399 // One-symbol tokens.
427 // Lifetime or character literal.
428 '\'' => self.lifetime_or_char(),
432 let terminated = self.double_quoted_string();
433 let suffix_start = self.pos_within_token();
435 self.eat_literal_suffix();
437 let kind = Str { terminated };
438 Literal { kind, suffix_start }
440 // Identifier starting with an emoji. Only lexed for graceful error recovery.
441 c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => {
442 self.fake_ident_or_unknown_prefix()
446 let res = Token::new(token_kind, self.pos_within_token());
447 self.reset_pos_within_token();
451 fn line_comment(&mut self) -> TokenKind {
452 debug_assert!(self.prev() == '/' && self.first() == '/');
455 let doc_style = match self.first() {
456 // `//!` is an inner line doc comment.
457 '!' => Some(DocStyle::Inner),
458 // `////` (more than 3 slashes) is not considered a doc comment.
459 '/' if self.second() != '/' => Some(DocStyle::Outer),
463 self.eat_while(|c| c != '\n');
464 LineComment { doc_style }
467 fn block_comment(&mut self) -> TokenKind {
468 debug_assert!(self.prev() == '/' && self.first() == '*');
471 let doc_style = match self.first() {
472 // `/*!` is an inner block doc comment.
473 '!' => Some(DocStyle::Inner),
474 // `/***` (more than 2 stars) is not considered a doc comment.
475 // `/**/` is not considered a doc comment.
476 '*' if !matches!(self.second(), '*' | '/') => Some(DocStyle::Outer),
480 let mut depth = 1usize;
481 while let Some(c) = self.bump() {
483 '/' if self.first() == '*' => {
487 '*' if self.first() == '/' => {
491 // This block comment is closed, so for a construction like "/* */ */"
492 // there will be a successfully parsed block comment "/* */"
493 // and " */" will be processed separately.
501 BlockComment { doc_style, terminated: depth == 0 }
504 fn whitespace(&mut self) -> TokenKind {
505 debug_assert!(is_whitespace(self.prev()));
506 self.eat_while(is_whitespace);
510 fn raw_ident(&mut self) -> TokenKind {
511 debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second()));
514 // Eat the identifier part of RawIdent.
515 self.eat_identifier();
519 fn ident_or_unknown_prefix(&mut self) -> TokenKind {
520 debug_assert!(is_id_start(self.prev()));
521 // Start is already eaten, eat the rest of identifier.
522 self.eat_while(is_id_continue);
523 // Known prefixes must have been handled earlier. So if
524 // we see a prefix here, it is definitely an unknown prefix.
526 '#' | '"' | '\'' => UnknownPrefix,
527 c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => {
528 self.fake_ident_or_unknown_prefix()
534 fn fake_ident_or_unknown_prefix(&mut self) -> TokenKind {
535 // Start is already eaten, eat the rest of identifier.
537 unicode_xid::UnicodeXID::is_xid_continue(c)
538 || (!c.is_ascii() && unic_emoji_char::is_emoji(c))
541 // Known prefixes must have been handled earlier. So if
542 // we see a prefix here, it is definitely an unknown prefix.
544 '#' | '"' | '\'' => UnknownPrefix,
549 fn number(&mut self, first_digit: char) -> LiteralKind {
550 debug_assert!('0' <= self.prev() && self.prev() <= '9');
551 let mut base = Base::Decimal;
552 if first_digit == '0' {
553 // Attempt to parse encoding base.
554 let has_digits = match self.first() {
558 self.eat_decimal_digits()
563 self.eat_decimal_digits()
566 base = Base::Hexadecimal;
568 self.eat_hexadecimal_digits()
570 // Not a base prefix.
571 '0'..='9' | '_' | '.' | 'e' | 'E' => {
572 self.eat_decimal_digits();
576 _ => return Int { base, empty_int: false },
578 // Base prefix was provided, but there were no digits
579 // after it, e.g. "0x".
581 return Int { base, empty_int: true };
584 // No base prefix, parse number in the usual way.
585 self.eat_decimal_digits();
589 // Don't be greedy if this is actually an
590 // integer literal followed by field/method access or a range pattern
591 // (`0..2` and `12.foo()`)
592 '.' if self.second() != '.' && !is_id_start(self.second()) => {
593 // might have stuff after the ., and if it does, it needs to start
596 let mut empty_exponent = false;
597 if self.first().is_digit(10) {
598 self.eat_decimal_digits();
602 empty_exponent = !self.eat_float_exponent();
607 Float { base, empty_exponent }
611 let empty_exponent = !self.eat_float_exponent();
612 Float { base, empty_exponent }
614 _ => Int { base, empty_int: false },
618 fn lifetime_or_char(&mut self) -> TokenKind {
619 debug_assert!(self.prev() == '\'');
621 let can_be_a_lifetime = if self.second() == '\'' {
622 // It's surely not a lifetime.
625 // If the first symbol is valid for identifier, it can be a lifetime.
626 // Also check if it's a number for a better error reporting (so '0 will
627 // be reported as invalid lifetime and not as unterminated char literal).
628 is_id_start(self.first()) || self.first().is_digit(10)
631 if !can_be_a_lifetime {
632 let terminated = self.single_quoted_string();
633 let suffix_start = self.pos_within_token();
635 self.eat_literal_suffix();
637 let kind = Char { terminated };
638 return Literal { kind, suffix_start };
641 // Either a lifetime or a character literal with
642 // length greater than 1.
644 let starts_with_number = self.first().is_digit(10);
646 // Skip the literal contents.
647 // First symbol can be a number (which isn't a valid identifier start),
648 // so skip it without any checks.
650 self.eat_while(is_id_continue);
652 // Check if after skipping literal contents we've met a closing
653 // single quote (which means that user attempted to create a
654 // string with single quotes).
655 if self.first() == '\'' {
657 let kind = Char { terminated: true };
658 Literal { kind, suffix_start: self.pos_within_token() }
660 Lifetime { starts_with_number }
664 fn single_quoted_string(&mut self) -> bool {
665 debug_assert!(self.prev() == '\'');
666 // Check if it's a one-symbol literal.
667 if self.second() == '\'' && self.first() != '\\' {
673 // Literal has more than one symbol.
675 // Parse until either quotes are terminated or error is detected.
678 // Quotes are terminated, finish parsing.
683 // Probably beginning of the comment, which we don't want to include
684 // to the error report.
686 // Newline without following '\'' means unclosed quote, stop parsing.
687 '\n' if self.second() != '\'' => break,
688 // End of file, stop parsing.
689 EOF_CHAR if self.is_eof() => break,
690 // Escaped slash is considered one character, so bump twice.
695 // Skip the character.
701 // String was not terminated.
705 /// Eats double-quoted string and returns true
706 /// if string is terminated.
707 fn double_quoted_string(&mut self) -> bool {
708 debug_assert!(self.prev() == '"');
709 while let Some(c) = self.bump() {
714 '\\' if self.first() == '\\' || self.first() == '"' => {
715 // Bump again to skip escaped character.
721 // End of file reached.
725 /// Eats the double-quoted string and returns `n_hashes` and an error if encountered.
726 fn raw_double_quoted_string(&mut self, prefix_len: u32) -> Result<u8, RawStrError> {
727 // Wrap the actual function to handle the error with too many hashes.
728 // This way, it eats the whole raw string.
729 let n_hashes = self.raw_string_unvalidated(prefix_len)?;
730 // Only up to 255 `#`s are allowed in raw strings
731 match u8::try_from(n_hashes) {
733 Err(_) => Err(RawStrError::TooManyDelimiters { found: n_hashes }),
737 fn raw_string_unvalidated(&mut self, prefix_len: u32) -> Result<u32, RawStrError> {
738 debug_assert!(self.prev() == 'r');
739 let start_pos = self.pos_within_token();
740 let mut possible_terminator_offset = None;
741 let mut max_hashes = 0;
743 // Count opening '#' symbols.
745 while self.first() == '#' {
749 let n_start_hashes = eaten;
751 // Check that string is started.
755 let c = c.unwrap_or(EOF_CHAR);
756 return Err(RawStrError::InvalidStarter { bad_char: c });
760 // Skip the string contents and on each '#' character met, check if this is
761 // a raw string termination.
763 self.eat_while(|c| c != '"');
766 return Err(RawStrError::NoTerminator {
767 expected: n_start_hashes,
769 possible_terminator_offset,
773 // Eat closing double quote.
776 // Check that amount of closing '#' symbols
777 // is equal to the amount of opening ones.
778 // Note that this will not consume extra trailing `#` characters:
779 // `r###"abcde"####` is lexed as a `RawStr { n_hashes: 3 }`
780 // followed by a `#` token.
781 let mut n_end_hashes = 0;
782 while self.first() == '#' && n_end_hashes < n_start_hashes {
787 if n_end_hashes == n_start_hashes {
788 return Ok(n_start_hashes);
789 } else if n_end_hashes > max_hashes {
790 // Keep track of possible terminators to give a hint about
791 // where there might be a missing terminator
792 possible_terminator_offset =
793 Some(self.pos_within_token() - start_pos - n_end_hashes + prefix_len);
794 max_hashes = n_end_hashes;
799 fn eat_decimal_digits(&mut self) -> bool {
800 let mut has_digits = false;
816 fn eat_hexadecimal_digits(&mut self) -> bool {
817 let mut has_digits = false;
823 '0'..='9' | 'a'..='f' | 'A'..='F' => {
833 /// Eats the float exponent. Returns true if at least one digit was met,
834 /// and returns false otherwise.
835 fn eat_float_exponent(&mut self) -> bool {
836 debug_assert!(self.prev() == 'e' || self.prev() == 'E');
837 if self.first() == '-' || self.first() == '+' {
840 self.eat_decimal_digits()
843 // Eats the suffix of the literal, e.g. "_u8".
844 fn eat_literal_suffix(&mut self) {
845 self.eat_identifier();
848 // Eats the identifier.
849 fn eat_identifier(&mut self) {
850 if !is_id_start(self.first()) {
855 self.eat_while(is_id_continue);