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