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