]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/lexer/mod.rs
Auto merge of #106742 - compiler-errors:new-solver-make-it-not-ice, r=lcnr
[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         let mut swallow_next_invalid = 0;
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                     // Don't emit diagnostics for sequences of the same invalid token
236                     if swallow_next_invalid > 0 {
237                         swallow_next_invalid -= 1;
238                         continue;
239                     }
240                     let mut it = self.str_from_to_end(start).chars();
241                     let c = it.next().unwrap();
242                     let repeats = it.take_while(|c1| *c1 == c).count();
243                     let mut err =
244                         self.struct_err_span_char(start, self.pos + Pos::from_usize(repeats * c.len_utf8()), "unknown start of token", c);
245                     // FIXME: the lexer could be used to turn the ASCII version of unicode
246                     // homoglyphs, instead of keeping a table in `check_for_substitution`into the
247                     // token. Ideally, this should be inside `rustc_lexer`. However, we should
248                     // first remove compound tokens like `<<` from `rustc_lexer`, and then add
249                     // fancier error recovery to it, as there will be less overall work to do this
250                     // way.
251                     let token = unicode_chars::check_for_substitution(self, start, c, &mut err, repeats+1);
252                     if c == '\x00' {
253                         err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used");
254                     }
255                     if repeats > 0 {
256                         if repeats == 1 {
257                             err.note(format!("character appears once more"));
258                         } else {
259                             err.note(format!("character appears {repeats} more times"));
260                         }
261                         swallow_next_invalid = repeats;
262                     }
263                     err.emit();
264                     if let Some(token) = token {
265                         token
266                     } else {
267                         preceded_by_whitespace = true;
268                         continue;
269                     }
270                 }
271                 rustc_lexer::TokenKind::Eof => token::Eof,
272             };
273             let span = self.mk_sp(start, self.pos);
274             return (Token::new(kind, span), preceded_by_whitespace);
275         }
276     }
277
278     /// Report a fatal lexical error with a given span.
279     fn fatal_span(&self, sp: Span, m: &str) -> ! {
280         self.sess.span_diagnostic.span_fatal(sp, m)
281     }
282
283     /// Report a lexical error with a given span.
284     fn err_span(&self, sp: Span, m: &str) {
285         self.sess.span_diagnostic.struct_span_err(sp, m).emit();
286     }
287
288     /// Report a fatal error spanning [`from_pos`, `to_pos`).
289     fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
290         self.fatal_span(self.mk_sp(from_pos, to_pos), m)
291     }
292
293     /// Report a lexical error spanning [`from_pos`, `to_pos`).
294     fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
295         self.err_span(self.mk_sp(from_pos, to_pos), m)
296     }
297
298     fn struct_fatal_span_char(
299         &self,
300         from_pos: BytePos,
301         to_pos: BytePos,
302         m: &str,
303         c: char,
304     ) -> DiagnosticBuilder<'a, !> {
305         self.sess
306             .span_diagnostic
307             .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
308     }
309
310     fn struct_err_span_char(
311         &self,
312         from_pos: BytePos,
313         to_pos: BytePos,
314         m: &str,
315         c: char,
316     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
317         self.sess
318             .span_diagnostic
319             .struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
320     }
321
322     /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly
323     /// complain about it.
324     fn lint_unicode_text_flow(&self, start: BytePos) {
325         // Opening delimiter of the length 2 is not included into the comment text.
326         let content_start = start + BytePos(2);
327         let content = self.str_from(content_start);
328         if contains_text_flow_control_chars(content) {
329             let span = self.mk_sp(start, self.pos);
330             self.sess.buffer_lint_with_diagnostic(
331                 &TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
332                 span,
333                 ast::CRATE_NODE_ID,
334                 "unicode codepoint changing visible direction of text present in comment",
335                 BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()),
336             );
337         }
338     }
339
340     fn cook_doc_comment(
341         &self,
342         content_start: BytePos,
343         content: &str,
344         comment_kind: CommentKind,
345         doc_style: DocStyle,
346     ) -> TokenKind {
347         if content.contains('\r') {
348             for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') {
349                 self.err_span_(
350                     content_start + BytePos(idx as u32),
351                     content_start + BytePos(idx as u32 + 1),
352                     match comment_kind {
353                         CommentKind::Line => "bare CR not allowed in doc-comment",
354                         CommentKind::Block => "bare CR not allowed in block doc-comment",
355                     },
356                 );
357             }
358         }
359
360         let attr_style = match doc_style {
361             DocStyle::Outer => AttrStyle::Outer,
362             DocStyle::Inner => AttrStyle::Inner,
363         };
364
365         token::DocComment(comment_kind, attr_style, Symbol::intern(content))
366     }
367
368     fn cook_lexer_literal(
369         &self,
370         start: BytePos,
371         end: BytePos,
372         kind: rustc_lexer::LiteralKind,
373     ) -> (token::LitKind, Symbol) {
374         match kind {
375             rustc_lexer::LiteralKind::Char { terminated } => {
376                 if !terminated {
377                     self.sess.span_diagnostic.span_fatal_with_code(
378                         self.mk_sp(start, end),
379                         "unterminated character literal",
380                         error_code!(E0762),
381                     )
382                 }
383                 self.cook_quoted(token::Char, Mode::Char, start, end, 1, 1) // ' '
384             }
385             rustc_lexer::LiteralKind::Byte { terminated } => {
386                 if !terminated {
387                     self.sess.span_diagnostic.span_fatal_with_code(
388                         self.mk_sp(start + BytePos(1), end),
389                         "unterminated byte constant",
390                         error_code!(E0763),
391                     )
392                 }
393                 self.cook_quoted(token::Byte, Mode::Byte, start, end, 2, 1) // b' '
394             }
395             rustc_lexer::LiteralKind::Str { terminated } => {
396                 if !terminated {
397                     self.sess.span_diagnostic.span_fatal_with_code(
398                         self.mk_sp(start, end),
399                         "unterminated double quote string",
400                         error_code!(E0765),
401                     )
402                 }
403                 self.cook_quoted(token::Str, Mode::Str, start, end, 1, 1) // " "
404             }
405             rustc_lexer::LiteralKind::ByteStr { terminated } => {
406                 if !terminated {
407                     self.sess.span_diagnostic.span_fatal_with_code(
408                         self.mk_sp(start + BytePos(1), end),
409                         "unterminated double quote byte string",
410                         error_code!(E0766),
411                     )
412                 }
413                 self.cook_quoted(token::ByteStr, Mode::ByteStr, start, end, 2, 1) // b" "
414             }
415             rustc_lexer::LiteralKind::RawStr { n_hashes } => {
416                 if let Some(n_hashes) = n_hashes {
417                     let n = u32::from(n_hashes);
418                     let kind = token::StrRaw(n_hashes);
419                     self.cook_quoted(kind, Mode::RawStr, start, end, 2 + n, 1 + n) // r##" "##
420                 } else {
421                     self.report_raw_str_error(start, 1);
422                 }
423             }
424             rustc_lexer::LiteralKind::RawByteStr { n_hashes } => {
425                 if let Some(n_hashes) = n_hashes {
426                     let n = u32::from(n_hashes);
427                     let kind = token::ByteStrRaw(n_hashes);
428                     self.cook_quoted(kind, Mode::RawByteStr, start, end, 3 + n, 1 + n) // br##" "##
429                 } else {
430                     self.report_raw_str_error(start, 2);
431                 }
432             }
433             rustc_lexer::LiteralKind::Int { base, empty_int } => {
434                 if empty_int {
435                     self.sess
436                         .span_diagnostic
437                         .struct_span_err_with_code(
438                             self.mk_sp(start, end),
439                             "no valid digits found for number",
440                             error_code!(E0768),
441                         )
442                         .emit();
443                     (token::Integer, sym::integer(0))
444                 } else {
445                     if matches!(base, Base::Binary | Base::Octal) {
446                         let base = base as u32;
447                         let s = self.str_from_to(start + BytePos(2), end);
448                         for (idx, c) in s.char_indices() {
449                             if c != '_' && c.to_digit(base).is_none() {
450                                 self.err_span_(
451                                     start + BytePos::from_usize(2 + idx),
452                                     start + BytePos::from_usize(2 + idx + c.len_utf8()),
453                                     &format!("invalid digit for a base {} literal", base),
454                                 );
455                             }
456                         }
457                     }
458                     (token::Integer, self.symbol_from_to(start, end))
459                 }
460             }
461             rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
462                 if empty_exponent {
463                     self.err_span_(start, self.pos, "expected at least one digit in exponent");
464                 }
465                 match base {
466                     Base::Hexadecimal => {
467                         self.err_span_(start, end, "hexadecimal float literal is not supported")
468                     }
469                     Base::Octal => {
470                         self.err_span_(start, end, "octal float literal is not supported")
471                     }
472                     Base::Binary => {
473                         self.err_span_(start, end, "binary float literal is not supported")
474                     }
475                     _ => {}
476                 }
477                 (token::Float, self.symbol_from_to(start, end))
478             }
479         }
480     }
481
482     #[inline]
483     fn src_index(&self, pos: BytePos) -> usize {
484         (pos - self.start_pos).to_usize()
485     }
486
487     /// Slice of the source text from `start` up to but excluding `self.pos`,
488     /// meaning the slice does not include the character `self.ch`.
489     fn str_from(&self, start: BytePos) -> &str {
490         self.str_from_to(start, self.pos)
491     }
492
493     /// As symbol_from, with an explicit endpoint.
494     fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
495         debug!("taking an ident from {:?} to {:?}", start, end);
496         Symbol::intern(self.str_from_to(start, end))
497     }
498
499     /// Slice of the source text spanning from `start` up to but excluding `end`.
500     fn str_from_to(&self, start: BytePos, end: BytePos) -> &str {
501         &self.src[self.src_index(start)..self.src_index(end)]
502     }
503
504     /// Slice of the source text spanning from `start` until the end
505     fn str_from_to_end(&self, start: BytePos) -> &str {
506         &self.src[self.src_index(start)..]
507     }
508
509     fn report_raw_str_error(&self, start: BytePos, prefix_len: u32) -> ! {
510         match rustc_lexer::validate_raw_str(self.str_from(start), prefix_len) {
511             Err(RawStrError::InvalidStarter { bad_char }) => {
512                 self.report_non_started_raw_string(start, bad_char)
513             }
514             Err(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self
515                 .report_unterminated_raw_string(start, expected, possible_terminator_offset, found),
516             Err(RawStrError::TooManyDelimiters { found }) => {
517                 self.report_too_many_hashes(start, found)
518             }
519             Ok(()) => panic!("no error found for supposedly invalid raw string literal"),
520         }
521     }
522
523     fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
524         self.struct_fatal_span_char(
525             start,
526             self.pos,
527             "found invalid character; only `#` is allowed in raw string delimitation",
528             bad_char,
529         )
530         .emit()
531     }
532
533     fn report_unterminated_raw_string(
534         &self,
535         start: BytePos,
536         n_hashes: u32,
537         possible_offset: Option<u32>,
538         found_terminators: u32,
539     ) -> ! {
540         let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
541             self.mk_sp(start, start),
542             "unterminated raw string",
543             error_code!(E0748),
544         );
545
546         err.span_label(self.mk_sp(start, start), "unterminated raw string");
547
548         if n_hashes > 0 {
549             err.note(&format!(
550                 "this raw string should be terminated with `\"{}`",
551                 "#".repeat(n_hashes as usize)
552             ));
553         }
554
555         if let Some(possible_offset) = possible_offset {
556             let lo = start + BytePos(possible_offset as u32);
557             let hi = lo + BytePos(found_terminators as u32);
558             let span = self.mk_sp(lo, hi);
559             err.span_suggestion(
560                 span,
561                 "consider terminating the string here",
562                 "#".repeat(n_hashes as usize),
563                 Applicability::MaybeIncorrect,
564             );
565         }
566
567         err.emit()
568     }
569
570     fn report_unterminated_block_comment(&self, start: BytePos, doc_style: Option<DocStyle>) {
571         let msg = match doc_style {
572             Some(_) => "unterminated block doc-comment",
573             None => "unterminated block comment",
574         };
575         let last_bpos = self.pos;
576         let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
577             self.mk_sp(start, last_bpos),
578             msg,
579             error_code!(E0758),
580         );
581         let mut nested_block_comment_open_idxs = vec![];
582         let mut last_nested_block_comment_idxs = None;
583         let mut content_chars = self.str_from(start).char_indices().peekable();
584
585         while let Some((idx, current_char)) = content_chars.next() {
586             match content_chars.peek() {
587                 Some((_, '*')) if current_char == '/' => {
588                     nested_block_comment_open_idxs.push(idx);
589                 }
590                 Some((_, '/')) if current_char == '*' => {
591                     last_nested_block_comment_idxs =
592                         nested_block_comment_open_idxs.pop().map(|open_idx| (open_idx, idx));
593                 }
594                 _ => {}
595             };
596         }
597
598         if let Some((nested_open_idx, nested_close_idx)) = last_nested_block_comment_idxs {
599             err.span_label(self.mk_sp(start, start + BytePos(2)), msg)
600                 .span_label(
601                     self.mk_sp(
602                         start + BytePos(nested_open_idx as u32),
603                         start + BytePos(nested_open_idx as u32 + 2),
604                     ),
605                     "...as last nested comment starts here, maybe you want to close this instead?",
606                 )
607                 .span_label(
608                     self.mk_sp(
609                         start + BytePos(nested_close_idx as u32),
610                         start + BytePos(nested_close_idx as u32 + 2),
611                     ),
612                     "...and last nested comment terminates here.",
613                 );
614         }
615
616         err.emit();
617     }
618
619     // RFC 3101 introduced the idea of (reserved) prefixes. As of Rust 2021,
620     // using a (unknown) prefix is an error. In earlier editions, however, they
621     // only result in a (allowed by default) lint, and are treated as regular
622     // identifier tokens.
623     fn report_unknown_prefix(&self, start: BytePos) {
624         let prefix_span = self.mk_sp(start, self.pos);
625         let prefix_str = self.str_from_to(start, self.pos);
626         let msg = format!("prefix `{}` is unknown", prefix_str);
627
628         let expn_data = prefix_span.ctxt().outer_expn_data();
629
630         if expn_data.edition >= Edition::Edition2021 {
631             // In Rust 2021, this is a hard error.
632             let mut err = self.sess.span_diagnostic.struct_span_err(prefix_span, &msg);
633             err.span_label(prefix_span, "unknown prefix");
634             if prefix_str == "rb" {
635                 err.span_suggestion_verbose(
636                     prefix_span,
637                     "use `br` for a raw byte string",
638                     "br",
639                     Applicability::MaybeIncorrect,
640                 );
641             } else if expn_data.is_root() {
642                 err.span_suggestion_verbose(
643                     prefix_span.shrink_to_hi(),
644                     "consider inserting whitespace here",
645                     " ",
646                     Applicability::MaybeIncorrect,
647                 );
648             }
649             err.note("prefixed identifiers and literals are reserved since Rust 2021");
650             err.emit();
651         } else {
652             // Before Rust 2021, only emit a lint for migration.
653             self.sess.buffer_lint_with_diagnostic(
654                 &RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
655                 prefix_span,
656                 ast::CRATE_NODE_ID,
657                 &msg,
658                 BuiltinLintDiagnostics::ReservedPrefix(prefix_span),
659             );
660         }
661     }
662
663     fn report_too_many_hashes(&self, start: BytePos, found: u32) -> ! {
664         self.fatal_span_(
665             start,
666             self.pos,
667             &format!(
668                 "too many `#` symbols: raw strings may be delimited \
669                 by up to 255 `#` symbols, but found {}",
670                 found
671             ),
672         )
673     }
674
675     fn cook_quoted(
676         &self,
677         kind: token::LitKind,
678         mode: Mode,
679         start: BytePos,
680         end: BytePos,
681         prefix_len: u32,
682         postfix_len: u32,
683     ) -> (token::LitKind, Symbol) {
684         let mut has_fatal_err = false;
685         let content_start = start + BytePos(prefix_len);
686         let content_end = end - BytePos(postfix_len);
687         let lit_content = self.str_from_to(content_start, content_end);
688         unescape::unescape_literal(lit_content, mode, &mut |range, result| {
689             // Here we only check for errors. The actual unescaping is done later.
690             if let Err(err) = result {
691                 let span_with_quotes = self.mk_sp(start, end);
692                 let (start, end) = (range.start as u32, range.end as u32);
693                 let lo = content_start + BytePos(start);
694                 let hi = lo + BytePos(end - start);
695                 let span = self.mk_sp(lo, hi);
696                 if err.is_fatal() {
697                     has_fatal_err = true;
698                 }
699                 emit_unescape_error(
700                     &self.sess.span_diagnostic,
701                     lit_content,
702                     span_with_quotes,
703                     span,
704                     mode,
705                     range,
706                     err,
707                 );
708             }
709         });
710
711         // We normally exclude the quotes for the symbol, but for errors we
712         // include it because it results in clearer error messages.
713         if !has_fatal_err {
714             (kind, Symbol::intern(lit_content))
715         } else {
716             (token::Err, self.symbol_from_to(start, end))
717         }
718     }
719 }
720
721 pub fn nfc_normalize(string: &str) -> Symbol {
722     use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization};
723     match is_nfc_quick(string.chars()) {
724         IsNormalized::Yes => Symbol::intern(string),
725         _ => {
726             let normalized_str: String = string.chars().nfc().collect();
727             Symbol::intern(&normalized_str)
728         }
729     }
730 }