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