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::{Spacing, 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::{Base, DocStyle, RawStrError};
9 use rustc_session::lint::builtin::{
10 RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
12 use rustc_session::lint::BuiltinLintDiagnostics;
13 use rustc_session::parse::ParseSess;
14 use rustc_span::symbol::{sym, Symbol};
15 use rustc_span::{edition::Edition, BytePos, Pos, Span};
18 mod unescape_error_reporting;
21 use unescape_error_reporting::{emit_unescape_error, escaped_char};
23 // This type is used a lot. Make sure it doesn't unintentionally get bigger.
25 // This assertion is in this crate, rather than in `rustc_lexer`, because that
26 // crate cannot depend on `rustc_data_structures`.
27 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
28 rustc_data_structures::static_assert_size!(rustc_lexer::Token, 12);
30 #[derive(Clone, Debug)]
31 pub struct UnmatchedBrace {
32 pub expected_delim: Delimiter,
33 pub found_delim: Option<Delimiter>,
35 pub unclosed_span: Option<Span>,
36 pub candidate_span: Option<Span>,
39 pub(crate) fn parse_token_trees<'a>(
43 override_span: Option<Span>,
44 ) -> (PResult<'a, TokenStream>, Vec<UnmatchedBrace>) {
45 StringReader { sess, start_pos, pos: start_pos, src, override_span }.into_token_trees()
48 struct StringReader<'a> {
50 /// Initial position, read-only.
52 /// The absolute offset within the source_map of the current character.
54 /// Source text to tokenize.
56 override_span: Option<Span>,
59 impl<'a> StringReader<'a> {
60 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
61 self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
64 /// Returns the next token, and info about preceding whitespace, if any.
65 fn next_token(&mut self) -> (Spacing, Token) {
66 let mut spacing = Spacing::Joint;
68 // Skip `#!` at the start of the file
69 if self.pos == self.start_pos
70 && let Some(shebang_len) = rustc_lexer::strip_shebang(self.src)
72 self.pos = self.pos + BytePos::from_usize(shebang_len);
73 spacing = Spacing::Alone;
76 // Skip trivial (whitespace & comments) tokens
78 let start_src_index = self.src_index(self.pos);
79 let text: &str = &self.src[start_src_index..];
82 let span = self.mk_sp(self.pos, self.pos);
83 return (spacing, Token::new(token::Eof, span));
86 let token = rustc_lexer::first_token(text);
89 self.pos = self.pos + BytePos(token.len);
91 debug!("next_token: {:?}({:?})", token.kind, self.str_from(start));
93 match self.cook_lexer_token(token.kind, start) {
95 let span = self.mk_sp(start, self.pos);
96 return (spacing, Token::new(kind, span));
98 None => spacing = Spacing::Alone,
103 /// Report a fatal lexical error with a given span.
104 fn fatal_span(&self, sp: Span, m: &str) -> ! {
105 self.sess.span_diagnostic.span_fatal(sp, m)
108 /// Report a lexical error with a given span.
109 fn err_span(&self, sp: Span, m: &str) {
110 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
113 /// Report a fatal error spanning [`from_pos`, `to_pos`).
114 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
115 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
118 /// Report a lexical error spanning [`from_pos`, `to_pos`).
119 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
120 self.err_span(self.mk_sp(from_pos, to_pos), m)
123 fn struct_fatal_span_char(
129 ) -> DiagnosticBuilder<'a, !> {
132 .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
135 fn struct_err_span_char(
141 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
144 .struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
147 /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly
148 /// complain about it.
149 fn lint_unicode_text_flow(&self, start: BytePos) {
150 // Opening delimiter of the length 2 is not included into the comment text.
151 let content_start = start + BytePos(2);
152 let content = self.str_from(content_start);
153 if contains_text_flow_control_chars(content) {
154 let span = self.mk_sp(start, self.pos);
155 self.sess.buffer_lint_with_diagnostic(
156 &TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
159 "unicode codepoint changing visible direction of text present in comment",
160 BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()),
165 /// Turns simple `rustc_lexer::TokenKind` enum into a rich
166 /// `rustc_ast::TokenKind`. This turns strings into interned
167 /// symbols and runs additional validation.
168 fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> Option<TokenKind> {
170 rustc_lexer::TokenKind::LineComment { doc_style } => {
171 // Skip non-doc comments
172 let Some(doc_style) = doc_style else {
173 self.lint_unicode_text_flow(start);
177 // Opening delimiter of the length 3 is not included into the symbol.
178 let content_start = start + BytePos(3);
179 let content = self.str_from(content_start);
180 self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style)
182 rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => {
184 self.report_unterminated_block_comment(start, doc_style);
187 // Skip non-doc comments
188 let Some(doc_style) = doc_style else {
189 self.lint_unicode_text_flow(start);
193 // Opening delimiter of the length 3 and closing delimiter of the length 2
194 // are not included into the symbol.
195 let content_start = start + BytePos(3);
196 let content_end = self.pos - BytePos(if terminated { 2 } else { 0 });
197 let content = self.str_from_to(content_start, content_end);
198 self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style)
200 rustc_lexer::TokenKind::Whitespace => return None,
201 rustc_lexer::TokenKind::Ident
202 | rustc_lexer::TokenKind::RawIdent
203 | rustc_lexer::TokenKind::UnknownPrefix => {
204 let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent;
205 let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix;
206 let mut ident_start = start;
208 ident_start = ident_start + BytePos(2);
210 if is_unknown_prefix {
211 self.report_unknown_prefix(start);
213 let sym = nfc_normalize(self.str_from(ident_start));
214 let span = self.mk_sp(start, self.pos);
215 self.sess.symbol_gallery.insert(sym, span);
217 if !sym.can_be_raw() {
218 self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
220 self.sess.raw_identifier_spans.borrow_mut().push(span);
222 token::Ident(sym, is_raw_ident)
224 rustc_lexer::TokenKind::InvalidIdent
225 // Do not recover an identifier with emoji if the codepoint is a confusable
226 // with a recoverable substitution token, like `âž–`.
230 let sym = self.str_from(start);
231 sym.chars().count() == 1 && c == sym.chars().next().unwrap()
235 let sym = nfc_normalize(self.str_from(start));
236 let span = self.mk_sp(start, self.pos);
237 self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default().push(span);
238 token::Ident(sym, false)
240 rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
241 let suffix_start = start + BytePos(suffix_start);
242 let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
243 let suffix = if suffix_start < self.pos {
244 let string = self.str_from(suffix_start);
249 self.mk_sp(suffix_start, self.pos),
250 "underscore literal suffix is not allowed",
253 "this was previously accepted by the compiler but is \
254 being phased out; it will become a hard error in \
259 <https://github.com/rust-lang/rust/issues/42326> \
260 for more information",
265 Some(Symbol::intern(string))
270 token::Literal(token::Lit { kind, symbol, suffix })
272 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
273 // Include the leading `'` in the real identifier, for macro
274 // expansion purposes. See #12512 for the gory details of why
275 // this is necessary.
276 let lifetime_name = self.str_from(start);
277 if starts_with_number {
278 self.err_span_(start, self.pos, "lifetimes cannot start with a number");
280 let ident = Symbol::intern(lifetime_name);
281 token::Lifetime(ident)
283 rustc_lexer::TokenKind::Semi => token::Semi,
284 rustc_lexer::TokenKind::Comma => token::Comma,
285 rustc_lexer::TokenKind::Dot => token::Dot,
286 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(Delimiter::Parenthesis),
287 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(Delimiter::Parenthesis),
288 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(Delimiter::Brace),
289 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(Delimiter::Brace),
290 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(Delimiter::Bracket),
291 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(Delimiter::Bracket),
292 rustc_lexer::TokenKind::At => token::At,
293 rustc_lexer::TokenKind::Pound => token::Pound,
294 rustc_lexer::TokenKind::Tilde => token::Tilde,
295 rustc_lexer::TokenKind::Question => token::Question,
296 rustc_lexer::TokenKind::Colon => token::Colon,
297 rustc_lexer::TokenKind::Dollar => token::Dollar,
298 rustc_lexer::TokenKind::Eq => token::Eq,
299 rustc_lexer::TokenKind::Bang => token::Not,
300 rustc_lexer::TokenKind::Lt => token::Lt,
301 rustc_lexer::TokenKind::Gt => token::Gt,
302 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
303 rustc_lexer::TokenKind::And => token::BinOp(token::And),
304 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
305 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
306 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
307 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
308 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
309 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
311 rustc_lexer::TokenKind::Unknown | rustc_lexer::TokenKind::InvalidIdent => {
312 let c = self.str_from(start).chars().next().unwrap();
314 self.struct_err_span_char(start, self.pos, "unknown start of token", c);
315 // FIXME: the lexer could be used to turn the ASCII version of unicode homoglyphs,
316 // instead of keeping a table in `check_for_substitution`into the token. Ideally,
317 // this should be inside `rustc_lexer`. However, we should first remove compound
318 // tokens like `<<` from `rustc_lexer`, and then add fancier error recovery to it,
319 // as there will be less overall work to do this way.
320 let token = unicode_chars::check_for_substitution(self, start, c, &mut err);
322 err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used");
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)