1 use crate::lexer::unicode_chars::UNICODE_ARRAY;
2 use rustc_ast::ast::{self, AttrStyle};
3 use rustc_ast::token::{self, CommentKind, Delimiter, Token, TokenKind};
4 use rustc_ast::tokenstream::TokenStream;
5 use rustc_ast::util::unicode::contains_text_flow_control_chars;
6 use rustc_errors::{error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult};
7 use rustc_lexer::unescape::{self, Mode};
8 use rustc_lexer::Cursor;
9 use rustc_lexer::{Base, DocStyle, RawStrError};
10 use rustc_session::lint::builtin::{
11 RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
13 use rustc_session::lint::BuiltinLintDiagnostics;
14 use rustc_session::parse::ParseSess;
15 use rustc_span::symbol::{sym, Symbol};
16 use rustc_span::{edition::Edition, BytePos, Pos, Span};
19 mod unescape_error_reporting;
22 use unescape_error_reporting::{emit_unescape_error, escaped_char};
24 // This type is used a lot. Make sure it doesn't unintentionally get bigger.
26 // This assertion is in this crate, rather than in `rustc_lexer`, because that
27 // crate cannot depend on `rustc_data_structures`.
28 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
29 rustc_data_structures::static_assert_size!(rustc_lexer::Token, 12);
31 #[derive(Clone, Debug)]
32 pub struct UnmatchedBrace {
33 pub expected_delim: Delimiter,
34 pub found_delim: Option<Delimiter>,
36 pub unclosed_span: Option<Span>,
37 pub candidate_span: Option<Span>,
40 pub(crate) fn parse_token_trees<'a>(
43 mut start_pos: BytePos,
44 override_span: Option<Span>,
45 ) -> (PResult<'a, TokenStream>, Vec<UnmatchedBrace>) {
46 // Skip `#!`, if present.
47 if let Some(shebang_len) = rustc_lexer::strip_shebang(src) {
48 src = &src[shebang_len..];
49 start_pos = start_pos + BytePos::from_usize(shebang_len);
52 let cursor = Cursor::new(src);
54 StringReader { sess, start_pos, pos: start_pos, src, cursor, override_span };
55 tokentrees::TokenTreesReader::parse_all_token_trees(string_reader)
58 struct StringReader<'a> {
60 /// Initial position, read-only.
62 /// The absolute offset within the source_map of the current character.
64 /// Source text to tokenize.
66 /// Cursor for getting lexer tokens.
68 override_span: Option<Span>,
71 impl<'a> StringReader<'a> {
72 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
73 self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
76 /// Returns the next token, paired with a bool indicating if the token was
77 /// preceded by whitespace.
78 fn next_token(&mut self) -> (Token, bool) {
79 let mut preceded_by_whitespace = false;
81 // Skip trivial (whitespace & comments) tokens
83 let token = self.cursor.advance_token();
85 self.pos = self.pos + BytePos(token.len);
87 debug!("next_token: {:?}({:?})", token.kind, self.str_from(start));
89 // Now "cook" the token, converting the simple `rustc_lexer::TokenKind` enum into a
90 // rich `rustc_ast::TokenKind`. This turns strings into interned symbols and runs
91 // additional validation.
92 let kind = match token.kind {
93 rustc_lexer::TokenKind::LineComment { doc_style } => {
94 // Skip non-doc comments
95 let Some(doc_style) = doc_style else {
96 self.lint_unicode_text_flow(start);
97 preceded_by_whitespace = true;
101 // Opening delimiter of the length 3 is not included into the symbol.
102 let content_start = start + BytePos(3);
103 let content = self.str_from(content_start);
104 self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style)
106 rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => {
108 self.report_unterminated_block_comment(start, doc_style);
111 // Skip non-doc comments
112 let Some(doc_style) = doc_style else {
113 self.lint_unicode_text_flow(start);
114 preceded_by_whitespace = true;
118 // Opening delimiter of the length 3 and closing delimiter of the length 2
119 // are not included into the symbol.
120 let content_start = start + BytePos(3);
121 let content_end = self.pos - BytePos(if terminated { 2 } else { 0 });
122 let content = self.str_from_to(content_start, content_end);
123 self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style)
125 rustc_lexer::TokenKind::Whitespace => {
126 preceded_by_whitespace = true;
129 rustc_lexer::TokenKind::Ident => {
130 let sym = nfc_normalize(self.str_from(start));
131 let span = self.mk_sp(start, self.pos);
132 self.sess.symbol_gallery.insert(sym, span);
133 token::Ident(sym, false)
135 rustc_lexer::TokenKind::RawIdent => {
136 let sym = nfc_normalize(self.str_from(start + BytePos(2)));
137 let span = self.mk_sp(start, self.pos);
138 self.sess.symbol_gallery.insert(sym, span);
139 if !sym.can_be_raw() {
140 self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
142 self.sess.raw_identifier_spans.borrow_mut().push(span);
143 token::Ident(sym, true)
145 rustc_lexer::TokenKind::UnknownPrefix => {
146 self.report_unknown_prefix(start);
147 let sym = nfc_normalize(self.str_from(start));
148 let span = self.mk_sp(start, self.pos);
149 self.sess.symbol_gallery.insert(sym, span);
150 token::Ident(sym, false)
152 rustc_lexer::TokenKind::InvalidIdent
153 // Do not recover an identifier with emoji if the codepoint is a confusable
154 // with a recoverable substitution token, like `➖`.
158 let sym = self.str_from(start);
159 sym.chars().count() == 1 && c == sym.chars().next().unwrap()
162 let sym = nfc_normalize(self.str_from(start));
163 let span = self.mk_sp(start, self.pos);
164 self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default()
166 token::Ident(sym, false)
168 rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
169 let suffix_start = start + BytePos(suffix_start);
170 let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
171 let suffix = if suffix_start < self.pos {
172 let string = self.str_from(suffix_start);
177 self.mk_sp(suffix_start, self.pos),
178 "underscore literal suffix is not allowed",
181 "this was previously accepted by the compiler but is \
182 being phased out; it will become a hard error in \
187 <https://github.com/rust-lang/rust/issues/42326> \
188 for more information",
193 Some(Symbol::intern(string))
198 token::Literal(token::Lit { kind, symbol, suffix })
200 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
201 // Include the leading `'` in the real identifier, for macro
202 // expansion purposes. See #12512 for the gory details of why
203 // this is necessary.
204 let lifetime_name = self.str_from(start);
205 if starts_with_number {
206 self.err_span_(start, self.pos, "lifetimes cannot start with a number");
208 let ident = Symbol::intern(lifetime_name);
209 token::Lifetime(ident)
211 rustc_lexer::TokenKind::Semi => token::Semi,
212 rustc_lexer::TokenKind::Comma => token::Comma,
213 rustc_lexer::TokenKind::Dot => token::Dot,
214 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(Delimiter::Parenthesis),
215 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(Delimiter::Parenthesis),
216 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(Delimiter::Brace),
217 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(Delimiter::Brace),
218 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(Delimiter::Bracket),
219 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(Delimiter::Bracket),
220 rustc_lexer::TokenKind::At => token::At,
221 rustc_lexer::TokenKind::Pound => token::Pound,
222 rustc_lexer::TokenKind::Tilde => token::Tilde,
223 rustc_lexer::TokenKind::Question => token::Question,
224 rustc_lexer::TokenKind::Colon => token::Colon,
225 rustc_lexer::TokenKind::Dollar => token::Dollar,
226 rustc_lexer::TokenKind::Eq => token::Eq,
227 rustc_lexer::TokenKind::Bang => token::Not,
228 rustc_lexer::TokenKind::Lt => token::Lt,
229 rustc_lexer::TokenKind::Gt => token::Gt,
230 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
231 rustc_lexer::TokenKind::And => token::BinOp(token::And),
232 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
233 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
234 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
235 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
236 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
237 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
239 rustc_lexer::TokenKind::Unknown | rustc_lexer::TokenKind::InvalidIdent => {
240 let c = self.str_from(start).chars().next().unwrap();
242 self.struct_err_span_char(start, self.pos, "unknown start of token", c);
243 // FIXME: the lexer could be used to turn the ASCII version of unicode
244 // homoglyphs, instead of keeping a table in `check_for_substitution`into the
245 // token. Ideally, this should be inside `rustc_lexer`. However, we should
246 // first remove compound tokens like `<<` from `rustc_lexer`, and then add
247 // fancier error recovery to it, as there will be less overall work to do this
249 let token = unicode_chars::check_for_substitution(self, start, c, &mut err);
251 err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used");
254 if let Some(token) = token {
257 preceded_by_whitespace = true;
261 rustc_lexer::TokenKind::Eof => token::Eof,
263 let span = self.mk_sp(start, self.pos);
264 return (Token::new(kind, span), preceded_by_whitespace);
268 /// Report a fatal lexical error with a given span.
269 fn fatal_span(&self, sp: Span, m: &str) -> ! {
270 self.sess.span_diagnostic.span_fatal(sp, m)
273 /// Report a lexical error with a given span.
274 fn err_span(&self, sp: Span, m: &str) {
275 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
278 /// Report a fatal error spanning [`from_pos`, `to_pos`).
279 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
280 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
283 /// Report a lexical error spanning [`from_pos`, `to_pos`).
284 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
285 self.err_span(self.mk_sp(from_pos, to_pos), m)
288 fn struct_fatal_span_char(
294 ) -> DiagnosticBuilder<'a, !> {
297 .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
300 fn struct_err_span_char(
306 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
309 .struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
312 /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly
313 /// complain about it.
314 fn lint_unicode_text_flow(&self, start: BytePos) {
315 // Opening delimiter of the length 2 is not included into the comment text.
316 let content_start = start + BytePos(2);
317 let content = self.str_from(content_start);
318 if contains_text_flow_control_chars(content) {
319 let span = self.mk_sp(start, self.pos);
320 self.sess.buffer_lint_with_diagnostic(
321 &TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
324 "unicode codepoint changing visible direction of text present in comment",
325 BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()),
332 content_start: BytePos,
334 comment_kind: CommentKind,
337 if content.contains('\r') {
338 for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') {
340 content_start + BytePos(idx as u32),
341 content_start + BytePos(idx as u32 + 1),
343 CommentKind::Line => "bare CR not allowed in doc-comment",
344 CommentKind::Block => "bare CR not allowed in block doc-comment",
350 let attr_style = match doc_style {
351 DocStyle::Outer => AttrStyle::Outer,
352 DocStyle::Inner => AttrStyle::Inner,
355 token::DocComment(comment_kind, attr_style, Symbol::intern(content))
358 fn cook_lexer_literal(
361 suffix_start: BytePos,
362 kind: rustc_lexer::LiteralKind,
363 ) -> (token::LitKind, Symbol) {
364 // prefix means `"` or `br"` or `r###"`, ...
365 let (lit_kind, mode, prefix_len, postfix_len) = match kind {
366 rustc_lexer::LiteralKind::Char { terminated } => {
368 self.sess.span_diagnostic.span_fatal_with_code(
369 self.mk_sp(start, suffix_start),
370 "unterminated character literal",
374 (token::Char, Mode::Char, 1, 1) // ' '
376 rustc_lexer::LiteralKind::Byte { terminated } => {
378 self.sess.span_diagnostic.span_fatal_with_code(
379 self.mk_sp(start + BytePos(1), suffix_start),
380 "unterminated byte constant",
384 (token::Byte, Mode::Byte, 2, 1) // b' '
386 rustc_lexer::LiteralKind::Str { terminated } => {
388 self.sess.span_diagnostic.span_fatal_with_code(
389 self.mk_sp(start, suffix_start),
390 "unterminated double quote string",
394 (token::Str, Mode::Str, 1, 1) // " "
396 rustc_lexer::LiteralKind::ByteStr { terminated } => {
398 self.sess.span_diagnostic.span_fatal_with_code(
399 self.mk_sp(start + BytePos(1), suffix_start),
400 "unterminated double quote byte string",
404 (token::ByteStr, Mode::ByteStr, 2, 1) // b" "
406 rustc_lexer::LiteralKind::RawStr { n_hashes } => {
407 if let Some(n_hashes) = n_hashes {
408 let n = u32::from(n_hashes);
409 (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "##
411 self.report_raw_str_error(start, 1);
414 rustc_lexer::LiteralKind::RawByteStr { n_hashes } => {
415 if let Some(n_hashes) = n_hashes {
416 let n = u32::from(n_hashes);
417 (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "##
419 self.report_raw_str_error(start, 2);
422 rustc_lexer::LiteralKind::Int { base, empty_int } => {
423 return if empty_int {
426 .struct_span_err_with_code(
427 self.mk_sp(start, suffix_start),
428 "no valid digits found for number",
432 (token::Integer, sym::integer(0))
434 self.validate_int_literal(base, start, suffix_start);
435 (token::Integer, self.symbol_from_to(start, suffix_start))
438 rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
440 self.err_span_(start, self.pos, "expected at least one digit in exponent");
444 Base::Hexadecimal => self.err_span_(
447 "hexadecimal float literal is not supported",
450 self.err_span_(start, suffix_start, "octal float literal is not supported")
453 self.err_span_(start, suffix_start, "binary float literal is not supported")
458 let id = self.symbol_from_to(start, suffix_start);
459 return (token::Float, id);
462 let content_start = start + BytePos(prefix_len);
463 let content_end = suffix_start - BytePos(postfix_len);
464 let id = self.symbol_from_to(content_start, content_end);
465 self.validate_literal_escape(mode, content_start, content_end, prefix_len, postfix_len);
470 fn src_index(&self, pos: BytePos) -> usize {
471 (pos - self.start_pos).to_usize()
474 /// Slice of the source text from `start` up to but excluding `self.pos`,
475 /// meaning the slice does not include the character `self.ch`.
476 fn str_from(&self, start: BytePos) -> &str {
477 self.str_from_to(start, self.pos)
480 /// As symbol_from, with an explicit endpoint.
481 fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
482 debug!("taking an ident from {:?} to {:?}", start, end);
483 Symbol::intern(self.str_from_to(start, end))
486 /// Slice of the source text spanning from `start` up to but excluding `end`.
487 fn str_from_to(&self, start: BytePos, end: BytePos) -> &str {
488 &self.src[self.src_index(start)..self.src_index(end)]
491 fn report_raw_str_error(&self, start: BytePos, prefix_len: u32) -> ! {
492 match rustc_lexer::validate_raw_str(self.str_from(start), prefix_len) {
493 Err(RawStrError::InvalidStarter { bad_char }) => {
494 self.report_non_started_raw_string(start, bad_char)
496 Err(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self
497 .report_unterminated_raw_string(start, expected, possible_terminator_offset, found),
498 Err(RawStrError::TooManyDelimiters { found }) => {
499 self.report_too_many_hashes(start, found)
501 Ok(()) => panic!("no error found for supposedly invalid raw string literal"),
505 fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
506 self.struct_fatal_span_char(
509 "found invalid character; only `#` is allowed in raw string delimitation",
515 fn report_unterminated_raw_string(
519 possible_offset: Option<u32>,
520 found_terminators: u32,
522 let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
523 self.mk_sp(start, start),
524 "unterminated raw string",
528 err.span_label(self.mk_sp(start, start), "unterminated raw string");
532 "this raw string should be terminated with `\"{}`",
533 "#".repeat(n_hashes as usize)
537 if let Some(possible_offset) = possible_offset {
538 let lo = start + BytePos(possible_offset as u32);
539 let hi = lo + BytePos(found_terminators as u32);
540 let span = self.mk_sp(lo, hi);
543 "consider terminating the string here",
544 "#".repeat(n_hashes as usize),
545 Applicability::MaybeIncorrect,
552 fn report_unterminated_block_comment(&self, start: BytePos, doc_style: Option<DocStyle>) {
553 let msg = match doc_style {
554 Some(_) => "unterminated block doc-comment",
555 None => "unterminated block comment",
557 let last_bpos = self.pos;
558 let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
559 self.mk_sp(start, last_bpos),
563 let mut nested_block_comment_open_idxs = vec![];
564 let mut last_nested_block_comment_idxs = None;
565 let mut content_chars = self.str_from(start).char_indices().peekable();
567 while let Some((idx, current_char)) = content_chars.next() {
568 match content_chars.peek() {
569 Some((_, '*')) if current_char == '/' => {
570 nested_block_comment_open_idxs.push(idx);
572 Some((_, '/')) if current_char == '*' => {
573 last_nested_block_comment_idxs =
574 nested_block_comment_open_idxs.pop().map(|open_idx| (open_idx, idx));
580 if let Some((nested_open_idx, nested_close_idx)) = last_nested_block_comment_idxs {
581 err.span_label(self.mk_sp(start, start + BytePos(2)), msg)
584 start + BytePos(nested_open_idx as u32),
585 start + BytePos(nested_open_idx as u32 + 2),
587 "...as last nested comment starts here, maybe you want to close this instead?",
591 start + BytePos(nested_close_idx as u32),
592 start + BytePos(nested_close_idx as u32 + 2),
594 "...and last nested comment terminates here.",
601 // RFC 3101 introduced the idea of (reserved) prefixes. As of Rust 2021,
602 // using a (unknown) prefix is an error. In earlier editions, however, they
603 // only result in a (allowed by default) lint, and are treated as regular
604 // identifier tokens.
605 fn report_unknown_prefix(&self, start: BytePos) {
606 let prefix_span = self.mk_sp(start, self.pos);
607 let prefix_str = self.str_from_to(start, self.pos);
608 let msg = format!("prefix `{}` is unknown", prefix_str);
610 let expn_data = prefix_span.ctxt().outer_expn_data();
612 if expn_data.edition >= Edition::Edition2021 {
613 // In Rust 2021, this is a hard error.
614 let mut err = self.sess.span_diagnostic.struct_span_err(prefix_span, &msg);
615 err.span_label(prefix_span, "unknown prefix");
616 if prefix_str == "rb" {
617 err.span_suggestion_verbose(
619 "use `br` for a raw byte string",
621 Applicability::MaybeIncorrect,
623 } else if expn_data.is_root() {
624 err.span_suggestion_verbose(
625 prefix_span.shrink_to_hi(),
626 "consider inserting whitespace here",
628 Applicability::MaybeIncorrect,
631 err.note("prefixed identifiers and literals are reserved since Rust 2021");
634 // Before Rust 2021, only emit a lint for migration.
635 self.sess.buffer_lint_with_diagnostic(
636 &RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
640 BuiltinLintDiagnostics::ReservedPrefix(prefix_span),
645 fn report_too_many_hashes(&self, start: BytePos, found: u32) -> ! {
650 "too many `#` symbols: raw strings may be delimited \
651 by up to 255 `#` symbols, but found {}",
657 fn validate_literal_escape(
660 content_start: BytePos,
661 content_end: BytePos,
665 let lit_content = self.str_from_to(content_start, content_end);
666 unescape::unescape_literal(lit_content, mode, &mut |range, result| {
667 // Here we only check for errors. The actual unescaping is done later.
668 if let Err(err) = result {
669 let span_with_quotes = self
670 .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len));
671 let (start, end) = (range.start as u32, range.end as u32);
672 let lo = content_start + BytePos(start);
673 let hi = lo + BytePos(end - start);
674 let span = self.mk_sp(lo, hi);
676 &self.sess.span_diagnostic,
688 fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) {
689 let base = match base {
694 let s = self.str_from_to(content_start + BytePos(2), content_end);
695 for (idx, c) in s.char_indices() {
696 let idx = idx as u32;
697 if c != '_' && c.to_digit(base).is_none() {
698 let lo = content_start + BytePos(2 + idx);
699 let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32);
700 self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base));
706 pub fn nfc_normalize(string: &str) -> Symbol {
707 use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization};
708 match is_nfc_quick(string.chars()) {
709 IsNormalized::Yes => Symbol::intern(string),
711 let normalized_str: String = string.chars().nfc().collect();
712 Symbol::intern(&normalized_str)