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};
21 mod unescape_error_reporting;
24 use unescape_error_reporting::{emit_unescape_error, escaped_char};
26 // This type is used a lot. Make sure it doesn't unintentionally get bigger.
28 // This assertion is in this crate, rather than in `rustc_lexer`, because that
29 // crate cannot depend on `rustc_data_structures`.
30 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
31 rustc_data_structures::static_assert_size!(rustc_lexer::Token, 12);
33 #[derive(Clone, Debug)]
34 pub struct UnmatchedBrace {
35 pub expected_delim: Delimiter,
36 pub found_delim: Option<Delimiter>,
38 pub unclosed_span: Option<Span>,
39 pub candidate_span: Option<Span>,
42 pub(crate) fn parse_token_trees<'a>(
45 mut start_pos: BytePos,
46 override_span: Option<Span>,
47 ) -> (PResult<'a, TokenStream>, Vec<UnmatchedBrace>) {
48 // Skip `#!`, if present.
49 if let Some(shebang_len) = rustc_lexer::strip_shebang(src) {
50 src = &src[shebang_len..];
51 start_pos = start_pos + BytePos::from_usize(shebang_len);
54 let cursor = Cursor::new(src);
55 let string_reader = StringReader {
62 nbsp_is_whitespace: false,
64 tokentrees::TokenTreesReader::parse_all_token_trees(string_reader)
67 struct StringReader<'a> {
69 /// Initial position, read-only.
71 /// The absolute offset within the source_map of the current character.
73 /// Source text to tokenize.
75 /// Cursor for getting lexer tokens.
77 override_span: Option<Span>,
78 /// When a "unknown start of token: \u{a0}" has already been emitted earlier
79 /// in this file, it's safe to treat further occurrences of the non-breaking
80 /// space character as whitespace.
81 nbsp_is_whitespace: bool,
84 impl<'a> StringReader<'a> {
85 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
86 self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
89 /// Returns the next token, paired with a bool indicating if the token was
90 /// preceded by whitespace.
91 fn next_token(&mut self) -> (Token, bool) {
92 let mut preceded_by_whitespace = false;
93 let mut swallow_next_invalid = 0;
94 // Skip trivial (whitespace & comments) tokens
96 let token = self.cursor.advance_token();
98 self.pos = self.pos + BytePos(token.len);
100 debug!("next_token: {:?}({:?})", token.kind, self.str_from(start));
102 // Now "cook" the token, converting the simple `rustc_lexer::TokenKind` enum into a
103 // rich `rustc_ast::TokenKind`. This turns strings into interned symbols and runs
104 // additional validation.
105 let kind = match token.kind {
106 rustc_lexer::TokenKind::LineComment { doc_style } => {
107 // Skip non-doc comments
108 let Some(doc_style) = doc_style else {
109 self.lint_unicode_text_flow(start);
110 preceded_by_whitespace = true;
114 // Opening delimiter of the length 3 is not included into the symbol.
115 let content_start = start + BytePos(3);
116 let content = self.str_from(content_start);
117 self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style)
119 rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => {
121 self.report_unterminated_block_comment(start, doc_style);
124 // Skip non-doc comments
125 let Some(doc_style) = doc_style else {
126 self.lint_unicode_text_flow(start);
127 preceded_by_whitespace = true;
131 // Opening delimiter of the length 3 and closing delimiter of the length 2
132 // are not included into the symbol.
133 let content_start = start + BytePos(3);
134 let content_end = self.pos - BytePos(if terminated { 2 } else { 0 });
135 let content = self.str_from_to(content_start, content_end);
136 self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style)
138 rustc_lexer::TokenKind::Whitespace => {
139 preceded_by_whitespace = true;
142 rustc_lexer::TokenKind::Ident => {
143 let sym = nfc_normalize(self.str_from(start));
144 let span = self.mk_sp(start, self.pos);
145 self.sess.symbol_gallery.insert(sym, span);
146 token::Ident(sym, false)
148 rustc_lexer::TokenKind::RawIdent => {
149 let sym = nfc_normalize(self.str_from(start + BytePos(2)));
150 let span = self.mk_sp(start, self.pos);
151 self.sess.symbol_gallery.insert(sym, span);
152 if !sym.can_be_raw() {
153 self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
155 self.sess.raw_identifier_spans.borrow_mut().push(span);
156 token::Ident(sym, true)
158 rustc_lexer::TokenKind::UnknownPrefix => {
159 self.report_unknown_prefix(start);
160 let sym = nfc_normalize(self.str_from(start));
161 let span = self.mk_sp(start, self.pos);
162 self.sess.symbol_gallery.insert(sym, span);
163 token::Ident(sym, false)
165 rustc_lexer::TokenKind::InvalidIdent
166 // Do not recover an identifier with emoji if the codepoint is a confusable
167 // with a recoverable substitution token, like `➖`.
171 let sym = self.str_from(start);
172 sym.chars().count() == 1 && c == sym.chars().next().unwrap()
175 let sym = nfc_normalize(self.str_from(start));
176 let span = self.mk_sp(start, self.pos);
177 self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default()
179 token::Ident(sym, false)
181 rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
182 let suffix_start = start + BytePos(suffix_start);
183 let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
184 let suffix = if suffix_start < self.pos {
185 let string = self.str_from(suffix_start);
190 self.mk_sp(suffix_start, self.pos),
191 "underscore literal suffix is not allowed",
196 Some(Symbol::intern(string))
201 token::Literal(token::Lit { kind, symbol, suffix })
203 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
204 // Include the leading `'` in the real identifier, for macro
205 // expansion purposes. See #12512 for the gory details of why
206 // this is necessary.
207 let lifetime_name = self.str_from(start);
208 if starts_with_number {
209 let span = self.mk_sp(start, self.pos);
210 let mut diag = self.sess.struct_err("lifetimes cannot start with a number");
212 diag.stash(span, StashKey::LifetimeIsChar);
214 let ident = Symbol::intern(lifetime_name);
215 token::Lifetime(ident)
217 rustc_lexer::TokenKind::Semi => token::Semi,
218 rustc_lexer::TokenKind::Comma => token::Comma,
219 rustc_lexer::TokenKind::Dot => token::Dot,
220 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(Delimiter::Parenthesis),
221 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(Delimiter::Parenthesis),
222 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(Delimiter::Brace),
223 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(Delimiter::Brace),
224 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(Delimiter::Bracket),
225 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(Delimiter::Bracket),
226 rustc_lexer::TokenKind::At => token::At,
227 rustc_lexer::TokenKind::Pound => token::Pound,
228 rustc_lexer::TokenKind::Tilde => token::Tilde,
229 rustc_lexer::TokenKind::Question => token::Question,
230 rustc_lexer::TokenKind::Colon => token::Colon,
231 rustc_lexer::TokenKind::Dollar => token::Dollar,
232 rustc_lexer::TokenKind::Eq => token::Eq,
233 rustc_lexer::TokenKind::Bang => token::Not,
234 rustc_lexer::TokenKind::Lt => token::Lt,
235 rustc_lexer::TokenKind::Gt => token::Gt,
236 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
237 rustc_lexer::TokenKind::And => token::BinOp(token::And),
238 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
239 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
240 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
241 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
242 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
243 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
245 rustc_lexer::TokenKind::Unknown | rustc_lexer::TokenKind::InvalidIdent => {
246 // Don't emit diagnostics for sequences of the same invalid token
247 if swallow_next_invalid > 0 {
248 swallow_next_invalid -= 1;
251 let mut it = self.str_from_to_end(start).chars();
252 let c = it.next().unwrap();
254 // If an error has already been reported on non-breaking
255 // space characters earlier in the file, treat all
256 // subsequent occurrences as whitespace.
257 if self.nbsp_is_whitespace {
258 preceded_by_whitespace = true;
261 self.nbsp_is_whitespace = true;
263 let repeats = it.take_while(|c1| *c1 == c).count();
265 self.struct_err_span_char(start, self.pos + Pos::from_usize(repeats * c.len_utf8()), "unknown start of token", c);
266 // FIXME: the lexer could be used to turn the ASCII version of unicode
267 // homoglyphs, instead of keeping a table in `check_for_substitution`into the
268 // token. Ideally, this should be inside `rustc_lexer`. However, we should
269 // first remove compound tokens like `<<` from `rustc_lexer`, and then add
270 // fancier error recovery to it, as there will be less overall work to do this
272 let token = unicode_chars::check_for_substitution(self, start, c, &mut err, repeats+1);
274 err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used");
278 err.note(format!("character appears once more"));
280 err.note(format!("character appears {repeats} more times"));
282 swallow_next_invalid = repeats;
285 if let Some(token) = token {
288 preceded_by_whitespace = true;
292 rustc_lexer::TokenKind::Eof => token::Eof,
294 let span = self.mk_sp(start, self.pos);
295 return (Token::new(kind, span), preceded_by_whitespace);
299 /// Report a fatal lexical error with a given span.
300 fn fatal_span(&self, sp: Span, m: &str) -> ! {
301 self.sess.span_diagnostic.span_fatal(sp, m)
304 /// Report a lexical error with a given span.
305 fn err_span(&self, sp: Span, m: &str) {
306 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
309 /// Report a fatal error spanning [`from_pos`, `to_pos`).
310 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
311 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
314 /// Report a lexical error spanning [`from_pos`, `to_pos`).
315 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
316 self.err_span(self.mk_sp(from_pos, to_pos), m)
319 fn struct_fatal_span_char(
325 ) -> DiagnosticBuilder<'a, !> {
328 .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
331 fn struct_err_span_char(
337 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
340 .struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
343 /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly
344 /// complain about it.
345 fn lint_unicode_text_flow(&self, start: BytePos) {
346 // Opening delimiter of the length 2 is not included into the comment text.
347 let content_start = start + BytePos(2);
348 let content = self.str_from(content_start);
349 if contains_text_flow_control_chars(content) {
350 let span = self.mk_sp(start, self.pos);
351 self.sess.buffer_lint_with_diagnostic(
352 &TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
355 "unicode codepoint changing visible direction of text present in comment",
356 BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()),
363 content_start: BytePos,
365 comment_kind: CommentKind,
368 if content.contains('\r') {
369 for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') {
371 content_start + BytePos(idx as u32),
372 content_start + BytePos(idx as u32 + 1),
374 CommentKind::Line => "bare CR not allowed in doc-comment",
375 CommentKind::Block => "bare CR not allowed in block doc-comment",
381 let attr_style = match doc_style {
382 DocStyle::Outer => AttrStyle::Outer,
383 DocStyle::Inner => AttrStyle::Inner,
386 token::DocComment(comment_kind, attr_style, Symbol::intern(content))
389 fn cook_lexer_literal(
393 kind: rustc_lexer::LiteralKind,
394 ) -> (token::LitKind, Symbol) {
396 rustc_lexer::LiteralKind::Char { terminated } => {
398 self.sess.span_diagnostic.span_fatal_with_code(
399 self.mk_sp(start, end),
400 "unterminated character literal",
404 self.cook_quoted(token::Char, Mode::Char, start, end, 1, 1) // ' '
406 rustc_lexer::LiteralKind::Byte { terminated } => {
408 self.sess.span_diagnostic.span_fatal_with_code(
409 self.mk_sp(start + BytePos(1), end),
410 "unterminated byte constant",
414 self.cook_quoted(token::Byte, Mode::Byte, start, end, 2, 1) // b' '
416 rustc_lexer::LiteralKind::Str { terminated } => {
418 self.sess.span_diagnostic.span_fatal_with_code(
419 self.mk_sp(start, end),
420 "unterminated double quote string",
424 self.cook_quoted(token::Str, Mode::Str, start, end, 1, 1) // " "
426 rustc_lexer::LiteralKind::ByteStr { terminated } => {
428 self.sess.span_diagnostic.span_fatal_with_code(
429 self.mk_sp(start + BytePos(1), end),
430 "unterminated double quote byte string",
434 self.cook_quoted(token::ByteStr, Mode::ByteStr, start, end, 2, 1) // b" "
436 rustc_lexer::LiteralKind::RawStr { n_hashes } => {
437 if let Some(n_hashes) = n_hashes {
438 let n = u32::from(n_hashes);
439 let kind = token::StrRaw(n_hashes);
440 self.cook_quoted(kind, Mode::RawStr, start, end, 2 + n, 1 + n) // r##" "##
442 self.report_raw_str_error(start, 1);
445 rustc_lexer::LiteralKind::RawByteStr { n_hashes } => {
446 if let Some(n_hashes) = n_hashes {
447 let n = u32::from(n_hashes);
448 let kind = token::ByteStrRaw(n_hashes);
449 self.cook_quoted(kind, Mode::RawByteStr, start, end, 3 + n, 1 + n) // br##" "##
451 self.report_raw_str_error(start, 2);
454 rustc_lexer::LiteralKind::Int { base, empty_int } => {
458 .struct_span_err_with_code(
459 self.mk_sp(start, end),
460 "no valid digits found for number",
464 (token::Integer, sym::integer(0))
466 if matches!(base, Base::Binary | Base::Octal) {
467 let base = base as u32;
468 let s = self.str_from_to(start + BytePos(2), end);
469 for (idx, c) in s.char_indices() {
470 if c != '_' && c.to_digit(base).is_none() {
472 start + BytePos::from_usize(2 + idx),
473 start + BytePos::from_usize(2 + idx + c.len_utf8()),
474 &format!("invalid digit for a base {} literal", base),
479 (token::Integer, self.symbol_from_to(start, end))
482 rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
484 self.err_span_(start, self.pos, "expected at least one digit in exponent");
487 Base::Hexadecimal => {
488 self.err_span_(start, end, "hexadecimal float literal is not supported")
491 self.err_span_(start, end, "octal float literal is not supported")
494 self.err_span_(start, end, "binary float literal is not supported")
498 (token::Float, self.symbol_from_to(start, end))
504 fn src_index(&self, pos: BytePos) -> usize {
505 (pos - self.start_pos).to_usize()
508 /// Slice of the source text from `start` up to but excluding `self.pos`,
509 /// meaning the slice does not include the character `self.ch`.
510 fn str_from(&self, start: BytePos) -> &'a str {
511 self.str_from_to(start, self.pos)
514 /// As symbol_from, with an explicit endpoint.
515 fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
516 debug!("taking an ident from {:?} to {:?}", start, end);
517 Symbol::intern(self.str_from_to(start, end))
520 /// Slice of the source text spanning from `start` up to but excluding `end`.
521 fn str_from_to(&self, start: BytePos, end: BytePos) -> &'a str {
522 &self.src[self.src_index(start)..self.src_index(end)]
525 /// Slice of the source text spanning from `start` until the end
526 fn str_from_to_end(&self, start: BytePos) -> &'a str {
527 &self.src[self.src_index(start)..]
530 fn report_raw_str_error(&self, start: BytePos, prefix_len: u32) -> ! {
531 match rustc_lexer::validate_raw_str(self.str_from(start), prefix_len) {
532 Err(RawStrError::InvalidStarter { bad_char }) => {
533 self.report_non_started_raw_string(start, bad_char)
535 Err(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self
536 .report_unterminated_raw_string(start, expected, possible_terminator_offset, found),
537 Err(RawStrError::TooManyDelimiters { found }) => {
538 self.report_too_many_hashes(start, found)
540 Ok(()) => panic!("no error found for supposedly invalid raw string literal"),
544 fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
545 self.struct_fatal_span_char(
548 "found invalid character; only `#` is allowed in raw string delimitation",
554 fn report_unterminated_raw_string(
558 possible_offset: Option<u32>,
559 found_terminators: u32,
561 let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
562 self.mk_sp(start, start),
563 "unterminated raw string",
567 err.span_label(self.mk_sp(start, start), "unterminated raw string");
571 "this raw string should be terminated with `\"{}`",
572 "#".repeat(n_hashes as usize)
576 if let Some(possible_offset) = possible_offset {
577 let lo = start + BytePos(possible_offset as u32);
578 let hi = lo + BytePos(found_terminators as u32);
579 let span = self.mk_sp(lo, hi);
582 "consider terminating the string here",
583 "#".repeat(n_hashes as usize),
584 Applicability::MaybeIncorrect,
591 fn report_unterminated_block_comment(&self, start: BytePos, doc_style: Option<DocStyle>) {
592 let msg = match doc_style {
593 Some(_) => "unterminated block doc-comment",
594 None => "unterminated block comment",
596 let last_bpos = self.pos;
597 let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
598 self.mk_sp(start, last_bpos),
602 let mut nested_block_comment_open_idxs = vec![];
603 let mut last_nested_block_comment_idxs = None;
604 let mut content_chars = self.str_from(start).char_indices().peekable();
606 while let Some((idx, current_char)) = content_chars.next() {
607 match content_chars.peek() {
608 Some((_, '*')) if current_char == '/' => {
609 nested_block_comment_open_idxs.push(idx);
611 Some((_, '/')) if current_char == '*' => {
612 last_nested_block_comment_idxs =
613 nested_block_comment_open_idxs.pop().map(|open_idx| (open_idx, idx));
619 if let Some((nested_open_idx, nested_close_idx)) = last_nested_block_comment_idxs {
620 err.span_label(self.mk_sp(start, start + BytePos(2)), msg)
623 start + BytePos(nested_open_idx as u32),
624 start + BytePos(nested_open_idx as u32 + 2),
626 "...as last nested comment starts here, maybe you want to close this instead?",
630 start + BytePos(nested_close_idx as u32),
631 start + BytePos(nested_close_idx as u32 + 2),
633 "...and last nested comment terminates here.",
640 // RFC 3101 introduced the idea of (reserved) prefixes. As of Rust 2021,
641 // using a (unknown) prefix is an error. In earlier editions, however, they
642 // only result in a (allowed by default) lint, and are treated as regular
643 // identifier tokens.
644 fn report_unknown_prefix(&self, start: BytePos) {
645 let prefix_span = self.mk_sp(start, self.pos);
646 let prefix_str = self.str_from_to(start, self.pos);
647 let msg = format!("prefix `{}` is unknown", prefix_str);
649 let expn_data = prefix_span.ctxt().outer_expn_data();
651 if expn_data.edition >= Edition::Edition2021 {
652 // In Rust 2021, this is a hard error.
653 let mut err = self.sess.span_diagnostic.struct_span_err(prefix_span, &msg);
654 err.span_label(prefix_span, "unknown prefix");
655 if prefix_str == "rb" {
656 err.span_suggestion_verbose(
658 "use `br` for a raw byte string",
660 Applicability::MaybeIncorrect,
662 } else if expn_data.is_root() {
663 err.span_suggestion_verbose(
664 prefix_span.shrink_to_hi(),
665 "consider inserting whitespace here",
667 Applicability::MaybeIncorrect,
670 err.note("prefixed identifiers and literals are reserved since Rust 2021");
673 // Before Rust 2021, only emit a lint for migration.
674 self.sess.buffer_lint_with_diagnostic(
675 &RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
679 BuiltinLintDiagnostics::ReservedPrefix(prefix_span),
684 fn report_too_many_hashes(&self, start: BytePos, found: u32) -> ! {
689 "too many `#` symbols: raw strings may be delimited \
690 by up to 255 `#` symbols, but found {}",
698 kind: token::LitKind,
704 ) -> (token::LitKind, Symbol) {
705 let mut has_fatal_err = false;
706 let content_start = start + BytePos(prefix_len);
707 let content_end = end - BytePos(postfix_len);
708 let lit_content = self.str_from_to(content_start, content_end);
709 unescape::unescape_literal(lit_content, mode, &mut |range, result| {
710 // Here we only check for errors. The actual unescaping is done later.
711 if let Err(err) = result {
712 let span_with_quotes = self.mk_sp(start, end);
713 let (start, end) = (range.start as u32, range.end as u32);
714 let lo = content_start + BytePos(start);
715 let hi = lo + BytePos(end - start);
716 let span = self.mk_sp(lo, hi);
718 has_fatal_err = true;
721 &self.sess.span_diagnostic,
732 // We normally exclude the quotes for the symbol, but for errors we
733 // include it because it results in clearer error messages.
735 (kind, Symbol::intern(lit_content))
737 (token::Err, self.symbol_from_to(start, end))
742 pub fn nfc_normalize(string: &str) -> Symbol {
743 use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization};
744 match is_nfc_quick(string.chars()) {
745 IsNormalized::Yes => Symbol::intern(string),
747 let normalized_str: String = string.chars().nfc().collect();
748 Symbol::intern(&normalized_str)