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