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