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;
7 error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult, StashKey,
9 use rustc_lexer::unescape::{self, Mode};
10 use rustc_lexer::Cursor;
11 use rustc_lexer::{Base, DocStyle, RawStrError};
12 use rustc_session::lint::builtin::{
13 RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
15 use rustc_session::lint::BuiltinLintDiagnostics;
16 use rustc_session::parse::ParseSess;
17 use rustc_span::symbol::{sym, Symbol};
18 use rustc_span::{edition::Edition, BytePos, Pos, Span};
22 mod unescape_error_reporting;
25 use unescape_error_reporting::{emit_unescape_error, escaped_char};
27 // This type is used a lot. Make sure it doesn't unintentionally get bigger.
29 // This assertion is in this crate, rather than in `rustc_lexer`, because that
30 // crate cannot depend on `rustc_data_structures`.
31 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
32 rustc_data_structures::static_assert_size!(rustc_lexer::Token, 12);
34 #[derive(Clone, Debug)]
35 pub struct UnmatchedBrace {
36 pub expected_delim: Delimiter,
37 pub found_delim: Option<Delimiter>,
39 pub unclosed_span: Option<Span>,
40 pub candidate_span: Option<Span>,
43 pub(crate) fn parse_token_trees<'a>(
46 mut start_pos: BytePos,
47 override_span: Option<Span>,
48 ) -> (PResult<'a, TokenStream>, Vec<UnmatchedBrace>) {
49 // Skip `#!`, if present.
50 if let Some(shebang_len) = rustc_lexer::strip_shebang(src) {
51 src = &src[shebang_len..];
52 start_pos = start_pos + BytePos::from_usize(shebang_len);
55 let cursor = Cursor::new(src);
56 let string_reader = StringReader {
63 nbsp_is_whitespace: false,
65 tokentrees::TokenTreesReader::parse_all_token_trees(string_reader)
68 struct StringReader<'a> {
70 /// Initial position, read-only.
72 /// The absolute offset within the source_map of the current character.
74 /// Source text to tokenize.
76 /// Cursor for getting lexer tokens.
78 override_span: Option<Span>,
79 /// When a "unknown start of token: \u{a0}" has already been emitted earlier
80 /// in this file, it's safe to treat further occurrences of the non-breaking
81 /// space character as whitespace.
82 nbsp_is_whitespace: bool,
85 impl<'a> StringReader<'a> {
86 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
87 self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
90 /// Returns the next token, paired with a bool indicating if the token was
91 /// preceded by whitespace.
92 fn next_token(&mut self) -> (Token, bool) {
93 let mut preceded_by_whitespace = false;
94 let mut swallow_next_invalid = 0;
95 // Skip trivial (whitespace & comments) tokens
97 let token = self.cursor.advance_token();
99 self.pos = self.pos + BytePos(token.len);
101 debug!("next_token: {:?}({:?})", token.kind, self.str_from(start));
103 // Now "cook" the token, converting the simple `rustc_lexer::TokenKind` enum into a
104 // rich `rustc_ast::TokenKind`. This turns strings into interned symbols and runs
105 // additional validation.
106 let kind = match token.kind {
107 rustc_lexer::TokenKind::LineComment { doc_style } => {
108 // Skip non-doc comments
109 let Some(doc_style) = doc_style else {
110 self.lint_unicode_text_flow(start);
111 preceded_by_whitespace = true;
115 // Opening delimiter of the length 3 is not included into the symbol.
116 let content_start = start + BytePos(3);
117 let content = self.str_from(content_start);
118 self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style)
120 rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => {
122 self.report_unterminated_block_comment(start, doc_style);
125 // Skip non-doc comments
126 let Some(doc_style) = doc_style else {
127 self.lint_unicode_text_flow(start);
128 preceded_by_whitespace = true;
132 // Opening delimiter of the length 3 and closing delimiter of the length 2
133 // are not included into the symbol.
134 let content_start = start + BytePos(3);
135 let content_end = self.pos - BytePos(if terminated { 2 } else { 0 });
136 let content = self.str_from_to(content_start, content_end);
137 self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style)
139 rustc_lexer::TokenKind::Whitespace => {
140 preceded_by_whitespace = true;
143 rustc_lexer::TokenKind::Ident => {
144 let sym = nfc_normalize(self.str_from(start));
145 let span = self.mk_sp(start, self.pos);
146 self.sess.symbol_gallery.insert(sym, span);
147 token::Ident(sym, false)
149 rustc_lexer::TokenKind::RawIdent => {
150 let sym = nfc_normalize(self.str_from(start + BytePos(2)));
151 let span = self.mk_sp(start, self.pos);
152 self.sess.symbol_gallery.insert(sym, span);
153 if !sym.can_be_raw() {
154 self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
156 self.sess.raw_identifier_spans.borrow_mut().push(span);
157 token::Ident(sym, true)
159 rustc_lexer::TokenKind::UnknownPrefix => {
160 self.report_unknown_prefix(start);
161 let sym = nfc_normalize(self.str_from(start));
162 let span = self.mk_sp(start, self.pos);
163 self.sess.symbol_gallery.insert(sym, span);
164 token::Ident(sym, false)
166 rustc_lexer::TokenKind::InvalidIdent
167 // Do not recover an identifier with emoji if the codepoint is a confusable
168 // with a recoverable substitution token, like `➖`.
172 let sym = self.str_from(start);
173 sym.chars().count() == 1 && c == sym.chars().next().unwrap()
176 let sym = nfc_normalize(self.str_from(start));
177 let span = self.mk_sp(start, self.pos);
178 self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default()
180 token::Ident(sym, false)
182 rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
183 let suffix_start = start + BytePos(suffix_start);
184 let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
185 let suffix = if suffix_start < self.pos {
186 let string = self.str_from(suffix_start);
191 self.mk_sp(suffix_start, self.pos),
192 "underscore literal suffix is not allowed",
197 Some(Symbol::intern(string))
202 token::Literal(token::Lit { kind, symbol, suffix })
204 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
205 // Include the leading `'` in the real identifier, for macro
206 // expansion purposes. See #12512 for the gory details of why
207 // this is necessary.
208 let lifetime_name = self.str_from(start);
209 if starts_with_number {
210 let span = self.mk_sp(start, self.pos);
211 let mut diag = self.sess.struct_err("lifetimes cannot start with a number");
213 diag.stash(span, StashKey::LifetimeIsChar);
215 let ident = Symbol::intern(lifetime_name);
216 token::Lifetime(ident)
218 rustc_lexer::TokenKind::Semi => token::Semi,
219 rustc_lexer::TokenKind::Comma => token::Comma,
220 rustc_lexer::TokenKind::Dot => token::Dot,
221 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(Delimiter::Parenthesis),
222 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(Delimiter::Parenthesis),
223 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(Delimiter::Brace),
224 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(Delimiter::Brace),
225 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(Delimiter::Bracket),
226 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(Delimiter::Bracket),
227 rustc_lexer::TokenKind::At => token::At,
228 rustc_lexer::TokenKind::Pound => token::Pound,
229 rustc_lexer::TokenKind::Tilde => token::Tilde,
230 rustc_lexer::TokenKind::Question => token::Question,
231 rustc_lexer::TokenKind::Colon => token::Colon,
232 rustc_lexer::TokenKind::Dollar => token::Dollar,
233 rustc_lexer::TokenKind::Eq => token::Eq,
234 rustc_lexer::TokenKind::Bang => token::Not,
235 rustc_lexer::TokenKind::Lt => token::Lt,
236 rustc_lexer::TokenKind::Gt => token::Gt,
237 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
238 rustc_lexer::TokenKind::And => token::BinOp(token::And),
239 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
240 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
241 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
242 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
243 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
244 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
246 rustc_lexer::TokenKind::Unknown | rustc_lexer::TokenKind::InvalidIdent => {
247 // Don't emit diagnostics for sequences of the same invalid token
248 if swallow_next_invalid > 0 {
249 swallow_next_invalid -= 1;
252 let mut it = self.str_from_to_end(start).chars();
253 let c = it.next().unwrap();
255 // If an error has already been reported on non-breaking
256 // space characters earlier in the file, treat all
257 // subsequent occurrences as whitespace.
258 if self.nbsp_is_whitespace {
259 preceded_by_whitespace = true;
262 self.nbsp_is_whitespace = true;
264 let repeats = it.take_while(|c1| *c1 == c).count();
266 self.struct_err_span_char(start, self.pos + Pos::from_usize(repeats * c.len_utf8()), "unknown start of token", c);
267 // FIXME: the lexer could be used to turn the ASCII version of unicode
268 // homoglyphs, instead of keeping a table in `check_for_substitution`into the
269 // token. Ideally, this should be inside `rustc_lexer`. However, we should
270 // first remove compound tokens like `<<` from `rustc_lexer`, and then add
271 // fancier error recovery to it, as there will be less overall work to do this
273 let token = unicode_chars::check_for_substitution(self, start, c, &mut err, repeats+1);
275 err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used");
279 err.note(format!("character appears once more"));
281 err.note(format!("character appears {repeats} more times"));
283 swallow_next_invalid = repeats;
286 if let Some(token) = token {
289 preceded_by_whitespace = true;
293 rustc_lexer::TokenKind::Eof => token::Eof,
295 let span = self.mk_sp(start, self.pos);
296 return (Token::new(kind, span), preceded_by_whitespace);
300 /// Report a fatal lexical error with a given span.
301 fn fatal_span(&self, sp: Span, m: &str) -> ! {
302 self.sess.span_diagnostic.span_fatal(sp, m)
305 /// Report a lexical error with a given span.
306 fn err_span(&self, sp: Span, m: &str) {
307 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
310 /// Report a fatal error spanning [`from_pos`, `to_pos`).
311 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
312 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
315 /// Report a lexical error spanning [`from_pos`, `to_pos`).
316 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
317 self.err_span(self.mk_sp(from_pos, to_pos), m)
320 fn struct_fatal_span_char(
326 ) -> DiagnosticBuilder<'a, !> {
329 .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
332 fn struct_err_span_char(
338 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
341 .struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
344 /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly
345 /// complain about it.
346 fn lint_unicode_text_flow(&self, start: BytePos) {
347 // Opening delimiter of the length 2 is not included into the comment text.
348 let content_start = start + BytePos(2);
349 let content = self.str_from(content_start);
350 if contains_text_flow_control_chars(content) {
351 let span = self.mk_sp(start, self.pos);
352 self.sess.buffer_lint_with_diagnostic(
353 &TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
356 "unicode codepoint changing visible direction of text present in comment",
357 BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()),
364 content_start: BytePos,
366 comment_kind: CommentKind,
369 if content.contains('\r') {
370 for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') {
372 content_start + BytePos(idx as u32),
373 content_start + BytePos(idx as u32 + 1),
375 CommentKind::Line => "bare CR not allowed in doc-comment",
376 CommentKind::Block => "bare CR not allowed in block doc-comment",
382 let attr_style = match doc_style {
383 DocStyle::Outer => AttrStyle::Outer,
384 DocStyle::Inner => AttrStyle::Inner,
387 token::DocComment(comment_kind, attr_style, Symbol::intern(content))
390 fn cook_lexer_literal(
394 kind: rustc_lexer::LiteralKind,
395 ) -> (token::LitKind, Symbol) {
397 rustc_lexer::LiteralKind::Char { terminated } => {
399 self.sess.span_diagnostic.span_fatal_with_code(
400 self.mk_sp(start, end),
401 "unterminated character literal",
405 self.cook_quoted(token::Char, Mode::Char, start, end, 1, 1) // ' '
407 rustc_lexer::LiteralKind::Byte { terminated } => {
409 self.sess.span_diagnostic.span_fatal_with_code(
410 self.mk_sp(start + BytePos(1), end),
411 "unterminated byte constant",
415 self.cook_quoted(token::Byte, Mode::Byte, start, end, 2, 1) // b' '
417 rustc_lexer::LiteralKind::Str { terminated } => {
419 self.sess.span_diagnostic.span_fatal_with_code(
420 self.mk_sp(start, end),
421 "unterminated double quote string",
425 self.cook_quoted(token::Str, Mode::Str, start, end, 1, 1) // " "
427 rustc_lexer::LiteralKind::ByteStr { terminated } => {
429 self.sess.span_diagnostic.span_fatal_with_code(
430 self.mk_sp(start + BytePos(1), end),
431 "unterminated double quote byte string",
435 self.cook_quoted(token::ByteStr, Mode::ByteStr, start, end, 2, 1) // b" "
437 rustc_lexer::LiteralKind::RawStr { n_hashes } => {
438 if let Some(n_hashes) = n_hashes {
439 let n = u32::from(n_hashes);
440 let kind = token::StrRaw(n_hashes);
441 self.cook_quoted(kind, Mode::RawStr, start, end, 2 + n, 1 + n) // r##" "##
443 self.report_raw_str_error(start, 1);
446 rustc_lexer::LiteralKind::RawByteStr { n_hashes } => {
447 if let Some(n_hashes) = n_hashes {
448 let n = u32::from(n_hashes);
449 let kind = token::ByteStrRaw(n_hashes);
450 self.cook_quoted(kind, Mode::RawByteStr, start, end, 3 + n, 1 + n) // br##" "##
452 self.report_raw_str_error(start, 2);
455 rustc_lexer::LiteralKind::Int { base, empty_int } => {
459 .struct_span_err_with_code(
460 self.mk_sp(start, end),
461 "no valid digits found for number",
465 (token::Integer, sym::integer(0))
467 if matches!(base, Base::Binary | Base::Octal) {
468 let base = base as u32;
469 let s = self.str_from_to(start + BytePos(2), end);
470 for (idx, c) in s.char_indices() {
471 if c != '_' && c.to_digit(base).is_none() {
473 start + BytePos::from_usize(2 + idx),
474 start + BytePos::from_usize(2 + idx + c.len_utf8()),
475 &format!("invalid digit for a base {} literal", base),
480 (token::Integer, self.symbol_from_to(start, end))
483 rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
485 self.err_span_(start, self.pos, "expected at least one digit in exponent");
488 Base::Hexadecimal => {
489 self.err_span_(start, end, "hexadecimal float literal is not supported")
492 self.err_span_(start, end, "octal float literal is not supported")
495 self.err_span_(start, end, "binary float literal is not supported")
499 (token::Float, self.symbol_from_to(start, end))
505 fn src_index(&self, pos: BytePos) -> usize {
506 (pos - self.start_pos).to_usize()
509 /// Slice of the source text from `start` up to but excluding `self.pos`,
510 /// meaning the slice does not include the character `self.ch`.
511 fn str_from(&self, start: BytePos) -> &'a str {
512 self.str_from_to(start, self.pos)
515 /// As symbol_from, with an explicit endpoint.
516 fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
517 debug!("taking an ident from {:?} to {:?}", start, end);
518 Symbol::intern(self.str_from_to(start, end))
521 /// Slice of the source text spanning from `start` up to but excluding `end`.
522 fn str_from_to(&self, start: BytePos, end: BytePos) -> &'a str {
523 &self.src[self.src_index(start)..self.src_index(end)]
526 /// Slice of the source text spanning from `start` until the end
527 fn str_from_to_end(&self, start: BytePos) -> &'a str {
528 &self.src[self.src_index(start)..]
531 fn report_raw_str_error(&self, start: BytePos, prefix_len: u32) -> ! {
532 match rustc_lexer::validate_raw_str(self.str_from(start), prefix_len) {
533 Err(RawStrError::InvalidStarter { bad_char }) => {
534 self.report_non_started_raw_string(start, bad_char)
536 Err(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self
537 .report_unterminated_raw_string(start, expected, possible_terminator_offset, found),
538 Err(RawStrError::TooManyDelimiters { found }) => {
539 self.report_too_many_hashes(start, found)
541 Ok(()) => panic!("no error found for supposedly invalid raw string literal"),
545 fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
546 self.struct_fatal_span_char(
549 "found invalid character; only `#` is allowed in raw string delimitation",
555 fn report_unterminated_raw_string(
559 possible_offset: Option<u32>,
560 found_terminators: u32,
562 let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
563 self.mk_sp(start, start),
564 "unterminated raw string",
568 err.span_label(self.mk_sp(start, start), "unterminated raw string");
572 "this raw string should be terminated with `\"{}`",
573 "#".repeat(n_hashes as usize)
577 if let Some(possible_offset) = possible_offset {
578 let lo = start + BytePos(possible_offset as u32);
579 let hi = lo + BytePos(found_terminators as u32);
580 let span = self.mk_sp(lo, hi);
583 "consider terminating the string here",
584 "#".repeat(n_hashes as usize),
585 Applicability::MaybeIncorrect,
592 fn report_unterminated_block_comment(&self, start: BytePos, doc_style: Option<DocStyle>) {
593 let msg = match doc_style {
594 Some(_) => "unterminated block doc-comment",
595 None => "unterminated block comment",
597 let last_bpos = self.pos;
598 let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
599 self.mk_sp(start, last_bpos),
603 let mut nested_block_comment_open_idxs = vec![];
604 let mut last_nested_block_comment_idxs = None;
605 let mut content_chars = self.str_from(start).char_indices().peekable();
607 while let Some((idx, current_char)) = content_chars.next() {
608 match content_chars.peek() {
609 Some((_, '*')) if current_char == '/' => {
610 nested_block_comment_open_idxs.push(idx);
612 Some((_, '/')) if current_char == '*' => {
613 last_nested_block_comment_idxs =
614 nested_block_comment_open_idxs.pop().map(|open_idx| (open_idx, idx));
620 if let Some((nested_open_idx, nested_close_idx)) = last_nested_block_comment_idxs {
621 err.span_label(self.mk_sp(start, start + BytePos(2)), msg)
624 start + BytePos(nested_open_idx as u32),
625 start + BytePos(nested_open_idx as u32 + 2),
627 "...as last nested comment starts here, maybe you want to close this instead?",
631 start + BytePos(nested_close_idx as u32),
632 start + BytePos(nested_close_idx as u32 + 2),
634 "...and last nested comment terminates here.",
641 // RFC 3101 introduced the idea of (reserved) prefixes. As of Rust 2021,
642 // using a (unknown) prefix is an error. In earlier editions, however, they
643 // only result in a (allowed by default) lint, and are treated as regular
644 // identifier tokens.
645 fn report_unknown_prefix(&self, start: BytePos) {
646 let prefix_span = self.mk_sp(start, self.pos);
647 let prefix_str = self.str_from_to(start, self.pos);
648 let msg = format!("prefix `{}` is unknown", prefix_str);
650 let expn_data = prefix_span.ctxt().outer_expn_data();
652 if expn_data.edition >= Edition::Edition2021 {
653 // In Rust 2021, this is a hard error.
654 let mut err = self.sess.span_diagnostic.struct_span_err(prefix_span, &msg);
655 err.span_label(prefix_span, "unknown prefix");
656 if prefix_str == "rb" {
657 err.span_suggestion_verbose(
659 "use `br` for a raw byte string",
661 Applicability::MaybeIncorrect,
663 } else if expn_data.is_root() {
664 err.span_suggestion_verbose(
665 prefix_span.shrink_to_hi(),
666 "consider inserting whitespace here",
668 Applicability::MaybeIncorrect,
671 err.note("prefixed identifiers and literals are reserved since Rust 2021");
674 // Before Rust 2021, only emit a lint for migration.
675 self.sess.buffer_lint_with_diagnostic(
676 &RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
680 BuiltinLintDiagnostics::ReservedPrefix(prefix_span),
685 fn report_too_many_hashes(&self, start: BytePos, found: u32) -> ! {
690 "too many `#` symbols: raw strings may be delimited \
691 by up to 255 `#` symbols, but found {}",
699 kind: token::LitKind,
705 ) -> (token::LitKind, Symbol) {
706 let mut has_fatal_err = false;
707 let content_start = start + BytePos(prefix_len);
708 let content_end = end - BytePos(postfix_len);
709 let lit_content = self.str_from_to(content_start, content_end);
710 unescape::unescape_literal(lit_content, mode, &mut |range, result| {
711 // Here we only check for errors. The actual unescaping is done later.
712 if let Err(err) = result {
713 let span_with_quotes = self.mk_sp(start, end);
714 let (start, end) = (range.start as u32, range.end as u32);
715 let lo = content_start + BytePos(start);
716 let hi = lo + BytePos(end - start);
717 let span = self.mk_sp(lo, hi);
719 has_fatal_err = true;
722 &self.sess.span_diagnostic,
733 // We normally exclude the quotes for the symbol, but for errors we
734 // include it because it results in clearer error messages.
736 (kind, Symbol::intern(lit_content))
738 (token::Err, self.symbol_from_to(start, end))
743 pub fn nfc_normalize(string: &str) -> Symbol {
744 use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization};
745 match is_nfc_quick(string.chars()) {
746 IsNormalized::Yes => Symbol::intern(string),
748 let normalized_str: String = string.chars().nfc().collect();
749 Symbol::intern(&normalized_str)