1 use rustc_ast::ast::{self, AttrStyle};
2 use rustc_ast::token::{self, CommentKind, Token, TokenKind};
3 use rustc_ast::tokenstream::{Spacing, TokenStream};
4 use rustc_errors::{error_code, Applicability, DiagnosticBuilder, FatalError, PResult};
5 use rustc_lexer::unescape::{self, Mode};
6 use rustc_lexer::{Base, DocStyle, RawStrError};
7 use rustc_session::lint::builtin::{
8 RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
10 use rustc_session::lint::BuiltinLintDiagnostics;
11 use rustc_session::parse::ParseSess;
12 use rustc_span::symbol::{sym, Symbol};
13 use rustc_span::{edition::Edition, BytePos, Pos, Span};
18 mod unescape_error_reporting;
21 use unescape_error_reporting::{emit_unescape_error, escaped_char};
23 #[derive(Clone, Debug)]
24 pub struct UnmatchedBrace {
25 pub expected_delim: token::DelimToken,
26 pub found_delim: Option<token::DelimToken>,
28 pub unclosed_span: Option<Span>,
29 pub candidate_span: Option<Span>,
32 crate fn parse_token_trees<'a>(
36 override_span: Option<Span>,
37 ) -> (PResult<'a, TokenStream>, Vec<UnmatchedBrace>) {
38 StringReader { sess, start_pos, pos: start_pos, end_src_index: src.len(), src, override_span }
42 struct StringReader<'a> {
44 /// Initial position, read-only.
46 /// The absolute offset within the source_map of the current character.
48 /// Stop reading src at this index.
50 /// Source text to tokenize.
52 override_span: Option<Span>,
55 impl<'a> StringReader<'a> {
56 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
57 self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
60 /// Returns the next token, and info about preceding whitespace, if any.
61 fn next_token(&mut self) -> (Spacing, Token) {
62 let mut spacing = Spacing::Joint;
64 // Skip `#!` at the start of the file
65 let start_src_index = self.src_index(self.pos);
66 let text: &str = &self.src[start_src_index..self.end_src_index];
67 let is_beginning_of_file = self.pos == self.start_pos;
68 if is_beginning_of_file {
69 if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
70 self.pos = self.pos + BytePos::from_usize(shebang_len);
71 spacing = Spacing::Alone;
75 // Skip trivial (whitespace & comments) tokens
77 let start_src_index = self.src_index(self.pos);
78 let text: &str = &self.src[start_src_index..self.end_src_index];
81 let span = self.mk_sp(self.pos, self.pos);
82 return (spacing, Token::new(token::Eof, span));
85 let token = rustc_lexer::first_token(text);
88 self.pos = self.pos + BytePos::from_usize(token.len);
90 debug!("next_token: {:?}({:?})", token.kind, self.str_from(start));
92 match self.cook_lexer_token(token.kind, start) {
94 let span = self.mk_sp(start, self.pos);
95 return (spacing, Token::new(kind, span));
97 None => spacing = Spacing::Alone,
102 /// Report a fatal lexical error with a given span.
103 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
104 self.sess.span_diagnostic.span_fatal(sp, m)
107 /// Report a lexical error with a given span.
108 fn err_span(&self, sp: Span, m: &str) {
109 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
112 /// Report a fatal error spanning [`from_pos`, `to_pos`).
113 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
114 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
117 /// Report a lexical error spanning [`from_pos`, `to_pos`).
118 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
119 self.err_span(self.mk_sp(from_pos, to_pos), m)
122 fn struct_fatal_span_char(
128 ) -> DiagnosticBuilder<'a> {
131 .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
134 /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly
135 /// complain about it.
136 fn lint_unicode_text_flow(&self, start: BytePos) {
137 // Opening delimiter of the length 2 is not included into the comment text.
138 let content_start = start + BytePos(2);
139 let content = self.str_from(content_start);
140 let span = self.mk_sp(start, self.pos);
141 const UNICODE_TEXT_FLOW_CHARS: &[char] = &[
142 '\u{202A}', '\u{202B}', '\u{202D}', '\u{202E}', '\u{2066}', '\u{2067}', '\u{2068}',
143 '\u{202C}', '\u{2069}',
145 if content.contains(UNICODE_TEXT_FLOW_CHARS) {
146 self.sess.buffer_lint_with_diagnostic(
147 &TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
150 "unicode codepoint changing visible direction of text present in comment",
151 BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()),
156 /// Turns simple `rustc_lexer::TokenKind` enum into a rich
157 /// `rustc_ast::TokenKind`. This turns strings into interned
158 /// symbols and runs additional validation.
159 fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> Option<TokenKind> {
161 rustc_lexer::TokenKind::LineComment { doc_style } => {
162 // Skip non-doc comments
163 let doc_style = if let Some(doc_style) = doc_style {
166 self.lint_unicode_text_flow(start);
170 // Opening delimiter of the length 3 is not included into the symbol.
171 let content_start = start + BytePos(3);
172 let content = self.str_from(content_start);
173 self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style)
175 rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => {
177 let msg = match doc_style {
178 Some(_) => "unterminated block doc-comment",
179 None => "unterminated block comment",
181 let last_bpos = self.pos;
182 self.sess.span_diagnostic.span_fatal_with_code(
183 self.mk_sp(start, last_bpos),
189 // Skip non-doc comments
190 let doc_style = if let Some(doc_style) = doc_style {
193 self.lint_unicode_text_flow(start);
197 // Opening delimiter of the length 3 and closing delimiter of the length 2
198 // are not included into the symbol.
199 let content_start = start + BytePos(3);
200 let content_end = self.pos - BytePos(if terminated { 2 } else { 0 });
201 let content = self.str_from_to(content_start, content_end);
202 self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style)
204 rustc_lexer::TokenKind::Whitespace => return None,
205 rustc_lexer::TokenKind::Ident
206 | rustc_lexer::TokenKind::RawIdent
207 | rustc_lexer::TokenKind::UnknownPrefix => {
208 let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent;
209 let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix;
210 let mut ident_start = start;
212 ident_start = ident_start + BytePos(2);
214 if is_unknown_prefix {
215 self.report_unknown_prefix(start);
217 let sym = nfc_normalize(self.str_from(ident_start));
218 let span = self.mk_sp(start, self.pos);
219 self.sess.symbol_gallery.insert(sym, span);
221 if !sym.can_be_raw() {
222 self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
224 self.sess.raw_identifier_spans.borrow_mut().push(span);
226 token::Ident(sym, is_raw_ident)
228 rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
229 let suffix_start = start + BytePos(suffix_start as u32);
230 let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
231 let suffix = if suffix_start < self.pos {
232 let string = self.str_from(suffix_start);
237 self.mk_sp(suffix_start, self.pos),
238 "underscore literal suffix is not allowed",
241 "this was previously accepted by the compiler but is \
242 being phased out; it will become a hard error in \
247 <https://github.com/rust-lang/rust/issues/42326> \
248 for more information",
253 Some(Symbol::intern(string))
258 token::Literal(token::Lit { kind, symbol, suffix })
260 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
261 // Include the leading `'` in the real identifier, for macro
262 // expansion purposes. See #12512 for the gory details of why
263 // this is necessary.
264 let lifetime_name = self.str_from(start);
265 if starts_with_number {
266 self.err_span_(start, self.pos, "lifetimes cannot start with a number");
268 let ident = Symbol::intern(lifetime_name);
269 token::Lifetime(ident)
271 rustc_lexer::TokenKind::Semi => token::Semi,
272 rustc_lexer::TokenKind::Comma => token::Comma,
273 rustc_lexer::TokenKind::Dot => token::Dot,
274 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren),
275 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren),
276 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace),
277 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace),
278 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(token::Bracket),
279 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(token::Bracket),
280 rustc_lexer::TokenKind::At => token::At,
281 rustc_lexer::TokenKind::Pound => token::Pound,
282 rustc_lexer::TokenKind::Tilde => token::Tilde,
283 rustc_lexer::TokenKind::Question => token::Question,
284 rustc_lexer::TokenKind::Colon => token::Colon,
285 rustc_lexer::TokenKind::Dollar => token::Dollar,
286 rustc_lexer::TokenKind::Eq => token::Eq,
287 rustc_lexer::TokenKind::Bang => token::Not,
288 rustc_lexer::TokenKind::Lt => token::Lt,
289 rustc_lexer::TokenKind::Gt => token::Gt,
290 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
291 rustc_lexer::TokenKind::And => token::BinOp(token::And),
292 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
293 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
294 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
295 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
296 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
297 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
299 rustc_lexer::TokenKind::Unknown => {
300 let c = self.str_from(start).chars().next().unwrap();
302 self.struct_fatal_span_char(start, self.pos, "unknown start of token", c);
303 // FIXME: the lexer could be used to turn the ASCII version of unicode homoglyphs,
304 // instead of keeping a table in `check_for_substitution`into the token. Ideally,
305 // this should be inside `rustc_lexer`. However, we should first remove compound
306 // tokens like `<<` from `rustc_lexer`, and then add fancier error recovery to it,
307 // as there will be less overall work to do this way.
308 let token = unicode_chars::check_for_substitution(self, start, c, &mut err);
310 err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used");
320 content_start: BytePos,
322 comment_kind: CommentKind,
325 if content.contains('\r') {
326 for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') {
328 content_start + BytePos(idx as u32),
329 content_start + BytePos(idx as u32 + 1),
331 CommentKind::Line => "bare CR not allowed in doc-comment",
332 CommentKind::Block => "bare CR not allowed in block doc-comment",
338 let attr_style = match doc_style {
339 DocStyle::Outer => AttrStyle::Outer,
340 DocStyle::Inner => AttrStyle::Inner,
343 token::DocComment(comment_kind, attr_style, Symbol::intern(content))
346 fn cook_lexer_literal(
349 suffix_start: BytePos,
350 kind: rustc_lexer::LiteralKind,
351 ) -> (token::LitKind, Symbol) {
352 // prefix means `"` or `br"` or `r###"`, ...
353 let (lit_kind, mode, prefix_len, postfix_len) = match kind {
354 rustc_lexer::LiteralKind::Char { terminated } => {
356 self.sess.span_diagnostic.span_fatal_with_code(
357 self.mk_sp(start, suffix_start),
358 "unterminated character literal",
362 (token::Char, Mode::Char, 1, 1) // ' '
364 rustc_lexer::LiteralKind::Byte { terminated } => {
366 self.sess.span_diagnostic.span_fatal_with_code(
367 self.mk_sp(start + BytePos(1), suffix_start),
368 "unterminated byte constant",
372 (token::Byte, Mode::Byte, 2, 1) // b' '
374 rustc_lexer::LiteralKind::Str { terminated } => {
376 self.sess.span_diagnostic.span_fatal_with_code(
377 self.mk_sp(start, suffix_start),
378 "unterminated double quote string",
382 (token::Str, Mode::Str, 1, 1) // " "
384 rustc_lexer::LiteralKind::ByteStr { terminated } => {
386 self.sess.span_diagnostic.span_fatal_with_code(
387 self.mk_sp(start + BytePos(1), suffix_start),
388 "unterminated double quote byte string",
392 (token::ByteStr, Mode::ByteStr, 2, 1) // b" "
394 rustc_lexer::LiteralKind::RawStr { n_hashes, err } => {
395 self.report_raw_str_error(start, err);
396 let n = u32::from(n_hashes);
397 (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "##
399 rustc_lexer::LiteralKind::RawByteStr { n_hashes, err } => {
400 self.report_raw_str_error(start, err);
401 let n = u32::from(n_hashes);
402 (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "##
404 rustc_lexer::LiteralKind::Int { base, empty_int } => {
405 return if empty_int {
408 .struct_span_err_with_code(
409 self.mk_sp(start, suffix_start),
410 "no valid digits found for number",
414 (token::Integer, sym::integer(0))
416 self.validate_int_literal(base, start, suffix_start);
417 (token::Integer, self.symbol_from_to(start, suffix_start))
420 rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
422 self.err_span_(start, self.pos, "expected at least one digit in exponent");
426 Base::Hexadecimal => self.err_span_(
429 "hexadecimal float literal is not supported",
432 self.err_span_(start, suffix_start, "octal float literal is not supported")
435 self.err_span_(start, suffix_start, "binary float literal is not supported")
440 let id = self.symbol_from_to(start, suffix_start);
441 return (token::Float, id);
444 let content_start = start + BytePos(prefix_len);
445 let content_end = suffix_start - BytePos(postfix_len);
446 let id = self.symbol_from_to(content_start, content_end);
447 self.validate_literal_escape(mode, content_start, content_end, prefix_len, postfix_len);
452 fn src_index(&self, pos: BytePos) -> usize {
453 (pos - self.start_pos).to_usize()
456 /// Slice of the source text from `start` up to but excluding `self.pos`,
457 /// meaning the slice does not include the character `self.ch`.
458 fn str_from(&self, start: BytePos) -> &str {
459 self.str_from_to(start, self.pos)
462 /// As symbol_from, with an explicit endpoint.
463 fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
464 debug!("taking an ident from {:?} to {:?}", start, end);
465 Symbol::intern(self.str_from_to(start, end))
468 /// Slice of the source text spanning from `start` up to but excluding `end`.
469 fn str_from_to(&self, start: BytePos, end: BytePos) -> &str {
470 &self.src[self.src_index(start)..self.src_index(end)]
473 fn report_raw_str_error(&self, start: BytePos, opt_err: Option<RawStrError>) {
475 Some(RawStrError::InvalidStarter { bad_char }) => {
476 self.report_non_started_raw_string(start, bad_char)
478 Some(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self
479 .report_unterminated_raw_string(start, expected, possible_terminator_offset, found),
480 Some(RawStrError::TooManyDelimiters { found }) => {
481 self.report_too_many_hashes(start, found)
487 fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
488 self.struct_fatal_span_char(
491 "found invalid character; only `#` is allowed in raw string delimitation",
498 fn report_unterminated_raw_string(
502 possible_offset: Option<usize>,
503 found_terminators: usize,
505 let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
506 self.mk_sp(start, start),
507 "unterminated raw string",
511 err.span_label(self.mk_sp(start, start), "unterminated raw string");
515 "this raw string should be terminated with `\"{}`",
520 if let Some(possible_offset) = possible_offset {
521 let lo = start + BytePos(possible_offset as u32);
522 let hi = lo + BytePos(found_terminators as u32);
523 let span = self.mk_sp(lo, hi);
526 "consider terminating the string here",
527 "#".repeat(n_hashes),
528 Applicability::MaybeIncorrect,
536 // RFC 3101 introduced the idea of (reserved) prefixes. As of Rust 2021,
537 // using a (unknown) prefix is an error. In earlier editions, however, they
538 // only result in a (allowed by default) lint, and are treated as regular
539 // identifier tokens.
540 fn report_unknown_prefix(&self, start: BytePos) {
541 let prefix_span = self.mk_sp(start, self.pos);
542 let prefix_str = self.str_from_to(start, self.pos);
543 let msg = format!("prefix `{}` is unknown", prefix_str);
545 let expn_data = prefix_span.ctxt().outer_expn_data();
547 if expn_data.edition >= Edition::Edition2021 {
548 // In Rust 2021, this is a hard error.
549 let mut err = self.sess.span_diagnostic.struct_span_err(prefix_span, &msg);
550 err.span_label(prefix_span, "unknown prefix");
551 if prefix_str == "rb" {
552 err.span_suggestion_verbose(
554 "use `br` for a raw byte string",
556 Applicability::MaybeIncorrect,
558 } else if expn_data.is_root() {
559 err.span_suggestion_verbose(
560 prefix_span.shrink_to_hi(),
561 "consider inserting whitespace here",
563 Applicability::MaybeIncorrect,
566 err.note("prefixed identifiers and literals are reserved since Rust 2021");
569 // Before Rust 2021, only emit a lint for migration.
570 self.sess.buffer_lint_with_diagnostic(
571 &RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
575 BuiltinLintDiagnostics::ReservedPrefix(prefix_span),
580 /// Note: It was decided to not add a test case, because it would be too big.
581 /// <https://github.com/rust-lang/rust/pull/50296#issuecomment-392135180>
582 fn report_too_many_hashes(&self, start: BytePos, found: usize) -> ! {
587 "too many `#` symbols: raw strings may be delimited \
588 by up to 65535 `#` symbols, but found {}",
595 fn validate_literal_escape(
598 content_start: BytePos,
599 content_end: BytePos,
603 let lit_content = self.str_from_to(content_start, content_end);
604 unescape::unescape_literal(lit_content, mode, &mut |range, result| {
605 // Here we only check for errors. The actual unescaping is done later.
606 if let Err(err) = result {
607 let span_with_quotes = self
608 .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len));
609 let (start, end) = (range.start as u32, range.end as u32);
610 let lo = content_start + BytePos(start);
611 let hi = lo + BytePos(end - start);
612 let span = self.mk_sp(lo, hi);
614 &self.sess.span_diagnostic,
626 fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) {
627 let base = match base {
632 let s = self.str_from_to(content_start + BytePos(2), content_end);
633 for (idx, c) in s.char_indices() {
634 let idx = idx as u32;
635 if c != '_' && c.to_digit(base).is_none() {
636 let lo = content_start + BytePos(2 + idx);
637 let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32);
638 self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base));
644 pub fn nfc_normalize(string: &str) -> Symbol {
645 use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization};
646 match is_nfc_quick(string.chars()) {
647 IsNormalized::Yes => Symbol::intern(string),
649 let normalized_str: String = string.chars().nfc().collect();
650 Symbol::intern(&normalized_str)