]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_parse/src/lexer/mod.rs
New upstream version 1.57.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};
c295e0f8
XL
7use rustc_session::lint::builtin::{
8 TEXT_DIRECTION_CODEPOINT_IN_COMMENT, RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
9};
136023e0 10use rustc_session::lint::BuiltinLintDiagnostics;
74b04a01 11use rustc_session::parse::ParseSess;
dfeec247 12use rustc_span::symbol::{sym, Symbol};
136023e0 13use rustc_span::{edition::Edition, BytePos, Pos, Span};
1a4d82fc 14
3dfed10e 15use tracing::debug;
1a4d82fc 16
32a655c1 17mod tokentrees;
60c5eb7d 18mod unescape_error_reporting;
dfeec247 19mod unicode_chars;
ba9703b0 20
5869c6ff 21use unescape_error_reporting::{emit_unescape_error, escaped_char};
1a4d82fc 22
9fa01778
XL
23#[derive(Clone, Debug)]
24pub struct UnmatchedBrace {
25 pub expected_delim: token::DelimToken,
e74abb32 26 pub found_delim: Option<token::DelimToken>,
9fa01778
XL
27 pub found_span: Span,
28 pub unclosed_span: Option<Span>,
29 pub candidate_span: Option<Span>,
30}
31
1b1a35ee
XL
32crate 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
42struct StringReader<'a> {
416331ca
XL
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.
f9f354fc 47 pos: BytePos,
94b46f34 48 /// Stop reading src at this index.
416331ca
XL
49 end_src_index: usize,
50 /// Source text to tokenize.
1b1a35ee 51 src: &'a str,
48663c56 52 override_span: Option<Span>,
cc61c64b
XL
53}
54
32a655c1 55impl<'a> StringReader<'a> {
416331ca 56 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
e1599b0c 57 self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
8bb4bdeb
XL
58 }
59
1b1a35ee
XL
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
416331ca
XL
65 let start_src_index = self.src_index(self.pos);
66 let text: &str = &self.src[start_src_index..self.end_src_index];
1b1a35ee
XL
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 }
416331ca
XL
73 }
74
1b1a35ee
XL
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];
416331ca 79
1b1a35ee
XL
80 if text.is_empty() {
81 let span = self.mk_sp(self.pos, self.pos);
82 return (spacing, Token::new(token::Eof, span));
416331ca 83 }
416331ca 84
1b1a35ee 85 let token = rustc_lexer::first_token(text);
416331ca 86
1b1a35ee
XL
87 let start = self.pos;
88 self.pos = self.pos + BytePos::from_usize(token.len);
416331ca 89
1b1a35ee 90 debug!("next_token: {:?}({:?})", token.kind, self.str_from(start));
416331ca 91
1b1a35ee
XL
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 }
1a4d82fc
JJ
100 }
101
102 /// Report a fatal lexical error with a given span.
94b46f34 103 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
32a655c1 104 self.sess.span_diagnostic.span_fatal(sp, m)
1a4d82fc
JJ
105 }
106
107 /// Report a lexical error with a given span.
94b46f34 108 fn err_span(&self, sp: Span, m: &str) {
0731742a 109 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
1a4d82fc
JJ
110 }
111
112 /// Report a fatal error spanning [`from_pos`, `to_pos`).
92a42be0 113 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
041b39d2 114 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
1a4d82fc
JJ
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) {
041b39d2 119 self.err_span(self.mk_sp(from_pos, to_pos), m)
1a4d82fc
JJ
120 }
121
dfeec247
XL
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> {
5869c6ff
XL
129 self.sess
130 .span_diagnostic
131 .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
9cc50fc6 132 }
1a4d82fc 133
c295e0f8
XL
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
416331ca 156 /// Turns simple `rustc_lexer::TokenKind` enum into a rich
cdc7bbd5 157 /// `rustc_ast::TokenKind`. This turns strings into interned
416331ca 158 /// symbols and runs additional validation.
1b1a35ee
XL
159 fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> Option<TokenKind> {
160 Some(match token {
3dfed10e 161 rustc_lexer::TokenKind::LineComment { doc_style } => {
1b1a35ee 162 // Skip non-doc comments
c295e0f8
XL
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 };
3dfed10e 169
1b1a35ee
XL
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)
416331ca 174 }
3dfed10e 175 rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => {
416331ca 176 if !terminated {
3dfed10e
XL
177 let msg = match doc_style {
178 Some(_) => "unterminated block doc-comment",
179 None => "unterminated block comment",
416331ca
XL
180 };
181 let last_bpos = self.pos;
17df50a5
XL
182 self.sess.span_diagnostic.span_fatal_with_code(
183 self.mk_sp(start, last_bpos),
184 msg,
185 error_code!(E0758),
186 );
416331ca 187 }
1b1a35ee
XL
188
189 // Skip non-doc comments
c295e0f8
XL
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 };
1b1a35ee
XL
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)
9cc50fc6 203 }
1b1a35ee 204 rustc_lexer::TokenKind::Whitespace => return None,
136023e0
XL
205 rustc_lexer::TokenKind::Ident
206 | rustc_lexer::TokenKind::RawIdent
207 | rustc_lexer::TokenKind::UnknownPrefix => {
416331ca 208 let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent;
136023e0 209 let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix;
416331ca
XL
210 let mut ident_start = start;
211 if is_raw_ident {
212 ident_start = ident_start + BytePos(2);
213 }
136023e0
XL
214 if is_unknown_prefix {
215 self.report_unknown_prefix(start);
216 }
dfeec247 217 let sym = nfc_normalize(self.str_from(ident_start));
f9f354fc
XL
218 let span = self.mk_sp(start, self.pos);
219 self.sess.symbol_gallery.insert(sym, span);
416331ca 220 if is_raw_ident {
416331ca
XL
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 == "_" {
dfeec247
XL
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 \
416331ca 242 being phased out; it will become a hard error in \
dfeec247
XL
243 a future release!",
244 )
245 .note(
74b04a01
XL
246 "see issue #42326 \
247 <https://github.com/rust-lang/rust/issues/42326> \
248 for more information",
dfeec247 249 )
416331ca
XL
250 .emit();
251 None
252 } else {
253 Some(Symbol::intern(string))
254 }
1a4d82fc 255 } else {
416331ca 256 None
1a4d82fc 257 };
416331ca
XL
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 {
dfeec247 266 self.err_span_(start, self.pos, "lifetimes cannot start with a number");
416331ca
XL
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,
416331ca
XL
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,
416331ca
XL
284 rustc_lexer::TokenKind::Colon => token::Colon,
285 rustc_lexer::TokenKind::Dollar => token::Dollar,
416331ca 286 rustc_lexer::TokenKind::Eq => token::Eq,
3dfed10e 287 rustc_lexer::TokenKind::Bang => token::Not,
416331ca 288 rustc_lexer::TokenKind::Lt => token::Lt,
416331ca 289 rustc_lexer::TokenKind::Gt => token::Gt,
416331ca 290 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
416331ca 291 rustc_lexer::TokenKind::And => token::BinOp(token::And),
416331ca 292 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
416331ca 293 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
416331ca 294 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
416331ca 295 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
416331ca 296 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
416331ca 297 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
416331ca
XL
298
299 rustc_lexer::TokenKind::Unknown => {
300 let c = self.str_from(start).chars().next().unwrap();
dfeec247
XL
301 let mut err =
302 self.struct_fatal_span_char(start, self.pos, "unknown start of token", c);
416331ca
XL
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.
1b1a35ee 308 let token = unicode_chars::check_for_substitution(self, start, c, &mut err);
6a06907d
XL
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 }
416331ca 312 err.emit();
1b1a35ee 313 token?
1a4d82fc 314 }
1b1a35ee 315 })
416331ca 316 }
b7449926 317
3dfed10e
XL
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
416331ca
XL
346 fn cook_lexer_literal(
347 &self,
348 start: BytePos,
349 suffix_start: BytePos,
dfeec247 350 kind: rustc_lexer::LiteralKind,
416331ca 351 ) -> (token::LitKind, Symbol) {
f9f354fc
XL
352 // prefix means `"` or `br"` or `r###"`, ...
353 let (lit_kind, mode, prefix_len, postfix_len) = match kind {
416331ca
XL
354 rustc_lexer::LiteralKind::Char { terminated } => {
355 if !terminated {
17df50a5
XL
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 )
416331ca 361 }
f9f354fc 362 (token::Char, Mode::Char, 1, 1) // ' '
dfeec247 363 }
416331ca
XL
364 rustc_lexer::LiteralKind::Byte { terminated } => {
365 if !terminated {
17df50a5
XL
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 )
416331ca 371 }
f9f354fc 372 (token::Byte, Mode::Byte, 2, 1) // b' '
dfeec247 373 }
416331ca
XL
374 rustc_lexer::LiteralKind::Str { terminated } => {
375 if !terminated {
17df50a5
XL
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 )
416331ca 381 }
f9f354fc 382 (token::Str, Mode::Str, 1, 1) // " "
416331ca
XL
383 }
384 rustc_lexer::LiteralKind::ByteStr { terminated } => {
385 if !terminated {
17df50a5
XL
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 )
416331ca 391 }
f9f354fc 392 (token::ByteStr, Mode::ByteStr, 2, 1) // b" "
416331ca 393 }
f035d41b
XL
394 rustc_lexer::LiteralKind::RawStr { n_hashes, err } => {
395 self.report_raw_str_error(start, err);
416331ca 396 let n = u32::from(n_hashes);
f9f354fc 397 (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "##
416331ca 398 }
f035d41b
XL
399 rustc_lexer::LiteralKind::RawByteStr { n_hashes, err } => {
400 self.report_raw_str_error(start, err);
416331ca 401 let n = u32::from(n_hashes);
f9f354fc 402 (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "##
416331ca
XL
403 }
404 rustc_lexer::LiteralKind::Int { base, empty_int } => {
f9f354fc 405 return if empty_int {
f035d41b
XL
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();
416331ca
XL
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))
f9f354fc 418 };
dfeec247 419 }
416331ca
XL
420 rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
421 if empty_exponent {
f035d41b 422 self.err_span_(start, self.pos, "expected at least one digit in exponent");
416331ca
XL
423 }
424
425 match base {
dfeec247
XL
426 Base::Hexadecimal => self.err_span_(
427 start,
428 suffix_start,
429 "hexadecimal float literal is not supported",
430 ),
416331ca 431 Base::Octal => {
dfeec247 432 self.err_span_(start, suffix_start, "octal float literal is not supported")
416331ca
XL
433 }
434 Base::Binary => {
dfeec247 435 self.err_span_(start, suffix_start, "binary float literal is not supported")
416331ca 436 }
dfeec247 437 _ => (),
416331ca
XL
438 }
439
440 let id = self.symbol_from_to(start, suffix_start);
f9f354fc 441 return (token::Float, id);
dfeec247 442 }
f9f354fc
XL
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);
5869c6ff 447 self.validate_literal_escape(mode, content_start, content_end, prefix_len, postfix_len);
f035d41b 448 (lit_kind, id)
f9f354fc
XL
449 }
450
94b46f34
XL
451 #[inline]
452 fn src_index(&self, pos: BytePos) -> usize {
416331ca 453 (pos - self.start_pos).to_usize()
1a4d82fc
JJ
454 }
455
dc9dc135
XL
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`.
dfeec247 458 fn str_from(&self, start: BytePos) -> &str {
dc9dc135 459 self.str_from_to(start, self.pos)
1a4d82fc
JJ
460 }
461
dc9dc135
XL
462 /// As symbol_from, with an explicit endpoint.
463 fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
1a4d82fc 464 debug!("taking an ident from {:?} to {:?}", start, end);
dc9dc135 465 Symbol::intern(self.str_from_to(start, end))
1a4d82fc
JJ
466 }
467
dc9dc135 468 /// Slice of the source text spanning from `start` up to but excluding `end`.
dfeec247 469 fn str_from_to(&self, start: BytePos, end: BytePos) -> &str {
dc9dc135 470 &self.src[self.src_index(start)..self.src_index(end)]
1a4d82fc
JJ
471 }
472
f035d41b
XL
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)
ba9703b0 482 }
f035d41b 483 None => (),
ba9703b0
XL
484 }
485 }
486
f035d41b 487 fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
dfeec247
XL
488 self.struct_fatal_span_char(
489 start,
490 self.pos,
f035d41b 491 "found invalid character; only `#` is allowed in raw string delimitation",
dfeec247
XL
492 bad_char,
493 )
494 .emit();
416331ca 495 FatalError.raise()
1a4d82fc
JJ
496 }
497
ba9703b0
XL
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 ) -> ! {
74b04a01
XL
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 );
ba9703b0 510
dfeec247 511 err.span_label(self.mk_sp(start, start), "unterminated raw string");
1a4d82fc 512
416331ca 513 if n_hashes > 0 {
dfeec247
XL
514 err.note(&format!(
515 "this raw string should be terminated with `\"{}`",
ba9703b0 516 "#".repeat(n_hashes)
dfeec247 517 ));
48663c56 518 }
1a4d82fc 519
ba9703b0
XL
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
416331ca
XL
532 err.emit();
533 FatalError.raise()
1a4d82fc
JJ
534 }
535
136023e0
XL
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);
94222f64
XL
542 let prefix_str = self.str_from_to(start, self.pos);
543 let msg = format!("prefix `{}` is unknown", prefix_str);
136023e0
XL
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");
94222f64
XL
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() {
136023e0
XL
559 err.span_suggestion_verbose(
560 prefix_span.shrink_to_hi(),
561 "consider inserting whitespace here",
562 " ".into(),
94222f64 563 Applicability::MaybeIncorrect,
136023e0
XL
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
fc512014 580 /// Note: It was decided to not add a test case, because it would be too big.
29967ef6 581 /// <https://github.com/rust-lang/rust/pull/50296#issuecomment-392135180>
f035d41b 582 fn report_too_many_hashes(&self, start: BytePos, found: usize) -> ! {
ba9703b0
XL
583 self.fatal_span_(
584 start,
585 self.pos,
f035d41b
XL
586 &format!(
587 "too many `#` symbols: raw strings may be delimited \
588 by up to 65535 `#` symbols, but found {}",
589 found
590 ),
ba9703b0
XL
591 )
592 .raise();
1a4d82fc 593 }
48663c56 594
5869c6ff
XL
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 ) {
f9f354fc
XL
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 {
5869c6ff
XL
607 let span_with_quotes = self
608 .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len));
fc512014
XL
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);
dc9dc135
XL
613 emit_unescape_error(
614 &self.sess.span_diagnostic,
f9f354fc
XL
615 lit_content,
616 span_with_quotes,
fc512014 617 span,
f9f354fc 618 mode,
dc9dc135
XL
619 range,
620 err,
f9f354fc 621 );
dc9dc135 622 }
f9f354fc 623 });
48663c56 624 }
1a4d82fc 625
416331ca
XL
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);
dfeec247 638 self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base));
416331ca
XL
639 }
640 }
641 }
9cc50fc6 642}
dfeec247
XL
643
644pub 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}