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