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