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