]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/lexer/mod.rs
Auto merge of #102565 - jyn514:refactor-build-manifest, r=Mark-Simulacrum
[rust.git] / compiler / rustc_parse / src / lexer / mod.rs
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::{
7     error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult, StashKey,
8 };
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,
14 };
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};
19
20 mod tokentrees;
21 mod unescape_error_reporting;
22 mod unicode_chars;
23
24 use unescape_error_reporting::{emit_unescape_error, escaped_char};
25
26 // This type is used a lot. Make sure it doesn't unintentionally get bigger.
27 //
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);
32
33 #[derive(Clone, Debug)]
34 pub struct UnmatchedBrace {
35     pub expected_delim: Delimiter,
36     pub found_delim: Option<Delimiter>,
37     pub found_span: Span,
38     pub unclosed_span: Option<Span>,
39     pub candidate_span: Option<Span>,
40 }
41
42 pub(crate) fn parse_token_trees<'a>(
43     sess: &'a ParseSess,
44     mut src: &'a str,
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);
52     }
53
54     let cursor = Cursor::new(src);
55     let string_reader =
56         StringReader { sess, start_pos, pos: start_pos, src, cursor, override_span };
57     tokentrees::TokenTreesReader::parse_all_token_trees(string_reader)
58 }
59
60 struct StringReader<'a> {
61     sess: &'a ParseSess,
62     /// Initial position, read-only.
63     start_pos: BytePos,
64     /// The absolute offset within the source_map of the current character.
65     pos: BytePos,
66     /// Source text to tokenize.
67     src: &'a str,
68     /// Cursor for getting lexer tokens.
69     cursor: Cursor<'a>,
70     override_span: Option<Span>,
71 }
72
73 impl<'a> StringReader<'a> {
74     fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
75         self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
76     }
77
78     /// Returns the next token, paired with a bool indicating if the token was
79     /// preceded by whitespace.
80     fn next_token(&mut self) -> (Token, bool) {
81         let mut preceded_by_whitespace = false;
82
83         // Skip trivial (whitespace & comments) tokens
84         loop {
85             let token = self.cursor.advance_token();
86             let start = self.pos;
87             self.pos = self.pos + BytePos(token.len);
88
89             debug!("next_token: {:?}({:?})", token.kind, self.str_from(start));
90
91             // Now "cook" the token, converting the simple `rustc_lexer::TokenKind` enum into a
92             // rich `rustc_ast::TokenKind`. This turns strings into interned symbols and runs
93             // additional validation.
94             let kind = match token.kind {
95                 rustc_lexer::TokenKind::LineComment { doc_style } => {
96                     // Skip non-doc comments
97                     let Some(doc_style) = doc_style else {
98                         self.lint_unicode_text_flow(start);
99                         preceded_by_whitespace = true;
100                         continue;
101                     };
102
103                     // Opening delimiter of the length 3 is not included into the symbol.
104                     let content_start = start + BytePos(3);
105                     let content = self.str_from(content_start);
106                     self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style)
107                 }
108                 rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => {
109                     if !terminated {
110                         self.report_unterminated_block_comment(start, doc_style);
111                     }
112
113                     // Skip non-doc comments
114                     let Some(doc_style) = doc_style else {
115                         self.lint_unicode_text_flow(start);
116                         preceded_by_whitespace = true;
117                         continue;
118                     };
119
120                     // Opening delimiter of the length 3 and closing delimiter of the length 2
121                     // are not included into the symbol.
122                     let content_start = start + BytePos(3);
123                     let content_end = self.pos - BytePos(if terminated { 2 } else { 0 });
124                     let content = self.str_from_to(content_start, content_end);
125                     self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style)
126                 }
127                 rustc_lexer::TokenKind::Whitespace => {
128                     preceded_by_whitespace = true;
129                     continue;
130                 }
131                 rustc_lexer::TokenKind::Ident => {
132                     let sym = nfc_normalize(self.str_from(start));
133                     let span = self.mk_sp(start, self.pos);
134                     self.sess.symbol_gallery.insert(sym, span);
135                     token::Ident(sym, false)
136                 }
137                 rustc_lexer::TokenKind::RawIdent => {
138                     let sym = nfc_normalize(self.str_from(start + BytePos(2)));
139                     let span = self.mk_sp(start, self.pos);
140                     self.sess.symbol_gallery.insert(sym, span);
141                     if !sym.can_be_raw() {
142                         self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
143                     }
144                     self.sess.raw_identifier_spans.borrow_mut().push(span);
145                     token::Ident(sym, true)
146                 }
147                 rustc_lexer::TokenKind::UnknownPrefix => {
148                     self.report_unknown_prefix(start);
149                     let sym = nfc_normalize(self.str_from(start));
150                     let span = self.mk_sp(start, self.pos);
151                     self.sess.symbol_gallery.insert(sym, span);
152                     token::Ident(sym, false)
153                 }
154                 rustc_lexer::TokenKind::InvalidIdent
155                     // Do not recover an identifier with emoji if the codepoint is a confusable
156                     // with a recoverable substitution token, like `➖`.
157                     if !UNICODE_ARRAY
158                         .iter()
159                         .any(|&(c, _, _)| {
160                             let sym = self.str_from(start);
161                             sym.chars().count() == 1 && c == sym.chars().next().unwrap()
162                         }) =>
163                 {
164                     let sym = nfc_normalize(self.str_from(start));
165                     let span = self.mk_sp(start, self.pos);
166                     self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default()
167                         .push(span);
168                     token::Ident(sym, false)
169                 }
170                 rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
171                     let suffix_start = start + BytePos(suffix_start);
172                     let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
173                     let suffix = if suffix_start < self.pos {
174                         let string = self.str_from(suffix_start);
175                         if string == "_" {
176                             self.sess
177                                 .span_diagnostic
178                                 .struct_span_err(
179                                     self.mk_sp(suffix_start, self.pos),
180                                     "underscore literal suffix is not allowed",
181                                 )
182                                 .emit();
183                             None
184                         } else {
185                             Some(Symbol::intern(string))
186                         }
187                     } else {
188                         None
189                     };
190                     token::Literal(token::Lit { kind, symbol, suffix })
191                 }
192                 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
193                     // Include the leading `'` in the real identifier, for macro
194                     // expansion purposes. See #12512 for the gory details of why
195                     // this is necessary.
196                     let lifetime_name = self.str_from(start);
197                     if starts_with_number {
198                         let span = self.mk_sp(start, self.pos);
199                         let mut diag = self.sess.struct_err("lifetimes cannot start with a number");
200                         diag.set_span(span);
201                         diag.stash(span, StashKey::LifetimeIsChar);
202                     }
203                     let ident = Symbol::intern(lifetime_name);
204                     token::Lifetime(ident)
205                 }
206                 rustc_lexer::TokenKind::Semi => token::Semi,
207                 rustc_lexer::TokenKind::Comma => token::Comma,
208                 rustc_lexer::TokenKind::Dot => token::Dot,
209                 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(Delimiter::Parenthesis),
210                 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(Delimiter::Parenthesis),
211                 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(Delimiter::Brace),
212                 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(Delimiter::Brace),
213                 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(Delimiter::Bracket),
214                 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(Delimiter::Bracket),
215                 rustc_lexer::TokenKind::At => token::At,
216                 rustc_lexer::TokenKind::Pound => token::Pound,
217                 rustc_lexer::TokenKind::Tilde => token::Tilde,
218                 rustc_lexer::TokenKind::Question => token::Question,
219                 rustc_lexer::TokenKind::Colon => token::Colon,
220                 rustc_lexer::TokenKind::Dollar => token::Dollar,
221                 rustc_lexer::TokenKind::Eq => token::Eq,
222                 rustc_lexer::TokenKind::Bang => token::Not,
223                 rustc_lexer::TokenKind::Lt => token::Lt,
224                 rustc_lexer::TokenKind::Gt => token::Gt,
225                 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
226                 rustc_lexer::TokenKind::And => token::BinOp(token::And),
227                 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
228                 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
229                 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
230                 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
231                 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
232                 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
233
234                 rustc_lexer::TokenKind::Unknown | rustc_lexer::TokenKind::InvalidIdent => {
235                     let c = self.str_from(start).chars().next().unwrap();
236                     let mut err =
237                         self.struct_err_span_char(start, self.pos, "unknown start of token", c);
238                     // FIXME: the lexer could be used to turn the ASCII version of unicode
239                     // homoglyphs, instead of keeping a table in `check_for_substitution`into the
240                     // token. Ideally, this should be inside `rustc_lexer`. However, we should
241                     // first remove compound tokens like `<<` from `rustc_lexer`, and then add
242                     // fancier error recovery to it, as there will be less overall work to do this
243                     // way.
244                     let token = unicode_chars::check_for_substitution(self, start, c, &mut err);
245                     if c == '\x00' {
246                         err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used");
247                     }
248                     err.emit();
249                     if let Some(token) = token {
250                         token
251                     } else {
252                         preceded_by_whitespace = true;
253                         continue;
254                     }
255                 }
256                 rustc_lexer::TokenKind::Eof => token::Eof,
257             };
258             let span = self.mk_sp(start, self.pos);
259             return (Token::new(kind, span), preceded_by_whitespace);
260         }
261     }
262
263     /// Report a fatal lexical error with a given span.
264     fn fatal_span(&self, sp: Span, m: &str) -> ! {
265         self.sess.span_diagnostic.span_fatal(sp, m)
266     }
267
268     /// Report a lexical error with a given span.
269     fn err_span(&self, sp: Span, m: &str) {
270         self.sess.span_diagnostic.struct_span_err(sp, m).emit();
271     }
272
273     /// Report a fatal error spanning [`from_pos`, `to_pos`).
274     fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
275         self.fatal_span(self.mk_sp(from_pos, to_pos), m)
276     }
277
278     /// Report a lexical error spanning [`from_pos`, `to_pos`).
279     fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
280         self.err_span(self.mk_sp(from_pos, to_pos), m)
281     }
282
283     fn struct_fatal_span_char(
284         &self,
285         from_pos: BytePos,
286         to_pos: BytePos,
287         m: &str,
288         c: char,
289     ) -> DiagnosticBuilder<'a, !> {
290         self.sess
291             .span_diagnostic
292             .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
293     }
294
295     fn struct_err_span_char(
296         &self,
297         from_pos: BytePos,
298         to_pos: BytePos,
299         m: &str,
300         c: char,
301     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
302         self.sess
303             .span_diagnostic
304             .struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
305     }
306
307     /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly
308     /// complain about it.
309     fn lint_unicode_text_flow(&self, start: BytePos) {
310         // Opening delimiter of the length 2 is not included into the comment text.
311         let content_start = start + BytePos(2);
312         let content = self.str_from(content_start);
313         if contains_text_flow_control_chars(content) {
314             let span = self.mk_sp(start, self.pos);
315             self.sess.buffer_lint_with_diagnostic(
316                 &TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
317                 span,
318                 ast::CRATE_NODE_ID,
319                 "unicode codepoint changing visible direction of text present in comment",
320                 BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()),
321             );
322         }
323     }
324
325     fn cook_doc_comment(
326         &self,
327         content_start: BytePos,
328         content: &str,
329         comment_kind: CommentKind,
330         doc_style: DocStyle,
331     ) -> TokenKind {
332         if content.contains('\r') {
333             for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') {
334                 self.err_span_(
335                     content_start + BytePos(idx as u32),
336                     content_start + BytePos(idx as u32 + 1),
337                     match comment_kind {
338                         CommentKind::Line => "bare CR not allowed in doc-comment",
339                         CommentKind::Block => "bare CR not allowed in block doc-comment",
340                     },
341                 );
342             }
343         }
344
345         let attr_style = match doc_style {
346             DocStyle::Outer => AttrStyle::Outer,
347             DocStyle::Inner => AttrStyle::Inner,
348         };
349
350         token::DocComment(comment_kind, attr_style, Symbol::intern(content))
351     }
352
353     fn cook_lexer_literal(
354         &self,
355         start: BytePos,
356         suffix_start: BytePos,
357         kind: rustc_lexer::LiteralKind,
358     ) -> (token::LitKind, Symbol) {
359         // prefix means `"` or `br"` or `r###"`, ...
360         let (lit_kind, mode, prefix_len, postfix_len) = match kind {
361             rustc_lexer::LiteralKind::Char { terminated } => {
362                 if !terminated {
363                     self.sess.span_diagnostic.span_fatal_with_code(
364                         self.mk_sp(start, suffix_start),
365                         "unterminated character literal",
366                         error_code!(E0762),
367                     )
368                 }
369                 (token::Char, Mode::Char, 1, 1) // ' '
370             }
371             rustc_lexer::LiteralKind::Byte { terminated } => {
372                 if !terminated {
373                     self.sess.span_diagnostic.span_fatal_with_code(
374                         self.mk_sp(start + BytePos(1), suffix_start),
375                         "unterminated byte constant",
376                         error_code!(E0763),
377                     )
378                 }
379                 (token::Byte, Mode::Byte, 2, 1) // b' '
380             }
381             rustc_lexer::LiteralKind::Str { terminated } => {
382                 if !terminated {
383                     self.sess.span_diagnostic.span_fatal_with_code(
384                         self.mk_sp(start, suffix_start),
385                         "unterminated double quote string",
386                         error_code!(E0765),
387                     )
388                 }
389                 (token::Str, Mode::Str, 1, 1) // " "
390             }
391             rustc_lexer::LiteralKind::ByteStr { terminated } => {
392                 if !terminated {
393                     self.sess.span_diagnostic.span_fatal_with_code(
394                         self.mk_sp(start + BytePos(1), suffix_start),
395                         "unterminated double quote byte string",
396                         error_code!(E0766),
397                     )
398                 }
399                 (token::ByteStr, Mode::ByteStr, 2, 1) // b" "
400             }
401             rustc_lexer::LiteralKind::RawStr { n_hashes } => {
402                 if let Some(n_hashes) = n_hashes {
403                     let n = u32::from(n_hashes);
404                     (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "##
405                 } else {
406                     self.report_raw_str_error(start, 1);
407                 }
408             }
409             rustc_lexer::LiteralKind::RawByteStr { n_hashes } => {
410                 if let Some(n_hashes) = n_hashes {
411                     let n = u32::from(n_hashes);
412                     (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "##
413                 } else {
414                     self.report_raw_str_error(start, 2);
415                 }
416             }
417             rustc_lexer::LiteralKind::Int { base, empty_int } => {
418                 return if empty_int {
419                     self.sess
420                         .span_diagnostic
421                         .struct_span_err_with_code(
422                             self.mk_sp(start, suffix_start),
423                             "no valid digits found for number",
424                             error_code!(E0768),
425                         )
426                         .emit();
427                     (token::Integer, sym::integer(0))
428                 } else {
429                     self.validate_int_literal(base, start, suffix_start);
430                     (token::Integer, self.symbol_from_to(start, suffix_start))
431                 };
432             }
433             rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
434                 if empty_exponent {
435                     self.err_span_(start, self.pos, "expected at least one digit in exponent");
436                 }
437
438                 match base {
439                     Base::Hexadecimal => self.err_span_(
440                         start,
441                         suffix_start,
442                         "hexadecimal float literal is not supported",
443                     ),
444                     Base::Octal => {
445                         self.err_span_(start, suffix_start, "octal float literal is not supported")
446                     }
447                     Base::Binary => {
448                         self.err_span_(start, suffix_start, "binary float literal is not supported")
449                     }
450                     _ => (),
451                 }
452
453                 let id = self.symbol_from_to(start, suffix_start);
454                 return (token::Float, id);
455             }
456         };
457         let content_start = start + BytePos(prefix_len);
458         let content_end = suffix_start - BytePos(postfix_len);
459         let id = self.symbol_from_to(content_start, content_end);
460         self.validate_literal_escape(mode, content_start, content_end, prefix_len, postfix_len);
461         (lit_kind, id)
462     }
463
464     #[inline]
465     fn src_index(&self, pos: BytePos) -> usize {
466         (pos - self.start_pos).to_usize()
467     }
468
469     /// Slice of the source text from `start` up to but excluding `self.pos`,
470     /// meaning the slice does not include the character `self.ch`.
471     fn str_from(&self, start: BytePos) -> &str {
472         self.str_from_to(start, self.pos)
473     }
474
475     /// As symbol_from, with an explicit endpoint.
476     fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
477         debug!("taking an ident from {:?} to {:?}", start, end);
478         Symbol::intern(self.str_from_to(start, end))
479     }
480
481     /// Slice of the source text spanning from `start` up to but excluding `end`.
482     fn str_from_to(&self, start: BytePos, end: BytePos) -> &str {
483         &self.src[self.src_index(start)..self.src_index(end)]
484     }
485
486     fn report_raw_str_error(&self, start: BytePos, prefix_len: u32) -> ! {
487         match rustc_lexer::validate_raw_str(self.str_from(start), prefix_len) {
488             Err(RawStrError::InvalidStarter { bad_char }) => {
489                 self.report_non_started_raw_string(start, bad_char)
490             }
491             Err(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self
492                 .report_unterminated_raw_string(start, expected, possible_terminator_offset, found),
493             Err(RawStrError::TooManyDelimiters { found }) => {
494                 self.report_too_many_hashes(start, found)
495             }
496             Ok(()) => panic!("no error found for supposedly invalid raw string literal"),
497         }
498     }
499
500     fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
501         self.struct_fatal_span_char(
502             start,
503             self.pos,
504             "found invalid character; only `#` is allowed in raw string delimitation",
505             bad_char,
506         )
507         .emit()
508     }
509
510     fn report_unterminated_raw_string(
511         &self,
512         start: BytePos,
513         n_hashes: u32,
514         possible_offset: Option<u32>,
515         found_terminators: u32,
516     ) -> ! {
517         let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
518             self.mk_sp(start, start),
519             "unterminated raw string",
520             error_code!(E0748),
521         );
522
523         err.span_label(self.mk_sp(start, start), "unterminated raw string");
524
525         if n_hashes > 0 {
526             err.note(&format!(
527                 "this raw string should be terminated with `\"{}`",
528                 "#".repeat(n_hashes as usize)
529             ));
530         }
531
532         if let Some(possible_offset) = possible_offset {
533             let lo = start + BytePos(possible_offset as u32);
534             let hi = lo + BytePos(found_terminators as u32);
535             let span = self.mk_sp(lo, hi);
536             err.span_suggestion(
537                 span,
538                 "consider terminating the string here",
539                 "#".repeat(n_hashes as usize),
540                 Applicability::MaybeIncorrect,
541             );
542         }
543
544         err.emit()
545     }
546
547     fn report_unterminated_block_comment(&self, start: BytePos, doc_style: Option<DocStyle>) {
548         let msg = match doc_style {
549             Some(_) => "unterminated block doc-comment",
550             None => "unterminated block comment",
551         };
552         let last_bpos = self.pos;
553         let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
554             self.mk_sp(start, last_bpos),
555             msg,
556             error_code!(E0758),
557         );
558         let mut nested_block_comment_open_idxs = vec![];
559         let mut last_nested_block_comment_idxs = None;
560         let mut content_chars = self.str_from(start).char_indices().peekable();
561
562         while let Some((idx, current_char)) = content_chars.next() {
563             match content_chars.peek() {
564                 Some((_, '*')) if current_char == '/' => {
565                     nested_block_comment_open_idxs.push(idx);
566                 }
567                 Some((_, '/')) if current_char == '*' => {
568                     last_nested_block_comment_idxs =
569                         nested_block_comment_open_idxs.pop().map(|open_idx| (open_idx, idx));
570                 }
571                 _ => {}
572             };
573         }
574
575         if let Some((nested_open_idx, nested_close_idx)) = last_nested_block_comment_idxs {
576             err.span_label(self.mk_sp(start, start + BytePos(2)), msg)
577                 .span_label(
578                     self.mk_sp(
579                         start + BytePos(nested_open_idx as u32),
580                         start + BytePos(nested_open_idx as u32 + 2),
581                     ),
582                     "...as last nested comment starts here, maybe you want to close this instead?",
583                 )
584                 .span_label(
585                     self.mk_sp(
586                         start + BytePos(nested_close_idx as u32),
587                         start + BytePos(nested_close_idx as u32 + 2),
588                     ),
589                     "...and last nested comment terminates here.",
590                 );
591         }
592
593         err.emit();
594     }
595
596     // RFC 3101 introduced the idea of (reserved) prefixes. As of Rust 2021,
597     // using a (unknown) prefix is an error. In earlier editions, however, they
598     // only result in a (allowed by default) lint, and are treated as regular
599     // identifier tokens.
600     fn report_unknown_prefix(&self, start: BytePos) {
601         let prefix_span = self.mk_sp(start, self.pos);
602         let prefix_str = self.str_from_to(start, self.pos);
603         let msg = format!("prefix `{}` is unknown", prefix_str);
604
605         let expn_data = prefix_span.ctxt().outer_expn_data();
606
607         if expn_data.edition >= Edition::Edition2021 {
608             // In Rust 2021, this is a hard error.
609             let mut err = self.sess.span_diagnostic.struct_span_err(prefix_span, &msg);
610             err.span_label(prefix_span, "unknown prefix");
611             if prefix_str == "rb" {
612                 err.span_suggestion_verbose(
613                     prefix_span,
614                     "use `br` for a raw byte string",
615                     "br",
616                     Applicability::MaybeIncorrect,
617                 );
618             } else if expn_data.is_root() {
619                 err.span_suggestion_verbose(
620                     prefix_span.shrink_to_hi(),
621                     "consider inserting whitespace here",
622                     " ",
623                     Applicability::MaybeIncorrect,
624                 );
625             }
626             err.note("prefixed identifiers and literals are reserved since Rust 2021");
627             err.emit();
628         } else {
629             // Before Rust 2021, only emit a lint for migration.
630             self.sess.buffer_lint_with_diagnostic(
631                 &RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
632                 prefix_span,
633                 ast::CRATE_NODE_ID,
634                 &msg,
635                 BuiltinLintDiagnostics::ReservedPrefix(prefix_span),
636             );
637         }
638     }
639
640     fn report_too_many_hashes(&self, start: BytePos, found: u32) -> ! {
641         self.fatal_span_(
642             start,
643             self.pos,
644             &format!(
645                 "too many `#` symbols: raw strings may be delimited \
646                 by up to 255 `#` symbols, but found {}",
647                 found
648             ),
649         )
650     }
651
652     fn validate_literal_escape(
653         &self,
654         mode: Mode,
655         content_start: BytePos,
656         content_end: BytePos,
657         prefix_len: u32,
658         postfix_len: u32,
659     ) {
660         let lit_content = self.str_from_to(content_start, content_end);
661         unescape::unescape_literal(lit_content, mode, &mut |range, result| {
662             // Here we only check for errors. The actual unescaping is done later.
663             if let Err(err) = result {
664                 let span_with_quotes = self
665                     .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len));
666                 let (start, end) = (range.start as u32, range.end as u32);
667                 let lo = content_start + BytePos(start);
668                 let hi = lo + BytePos(end - start);
669                 let span = self.mk_sp(lo, hi);
670                 emit_unescape_error(
671                     &self.sess.span_diagnostic,
672                     lit_content,
673                     span_with_quotes,
674                     span,
675                     mode,
676                     range,
677                     err,
678                 );
679             }
680         });
681     }
682
683     fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) {
684         let base = match base {
685             Base::Binary => 2,
686             Base::Octal => 8,
687             _ => return,
688         };
689         let s = self.str_from_to(content_start + BytePos(2), content_end);
690         for (idx, c) in s.char_indices() {
691             let idx = idx as u32;
692             if c != '_' && c.to_digit(base).is_none() {
693                 let lo = content_start + BytePos(2 + idx);
694                 let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32);
695                 self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base));
696             }
697         }
698     }
699 }
700
701 pub fn nfc_normalize(string: &str) -> Symbol {
702     use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization};
703     match is_nfc_quick(string.chars()) {
704         IsNormalized::Yes => Symbol::intern(string),
705         _ => {
706             let normalized_str: String = string.chars().nfc().collect();
707             Symbol::intern(&normalized_str)
708         }
709     }
710 }