1 use rustc_data_structures::sync::Lrc;
2 use rustc_errors::{error_code, DiagnosticBuilder, FatalError};
3 use rustc_lexer::unescape;
5 use rustc_session::parse::ParseSess;
6 use rustc_span::symbol::{sym, Symbol};
7 use rustc_span::{BytePos, Pos, Span};
8 use syntax::token::{self, Token, TokenKind};
9 use syntax::util::comments;
13 use std::convert::TryInto;
16 mod unescape_error_reporting;
18 use unescape_error_reporting::{emit_unescape_error, push_escaped_char};
20 #[derive(Clone, Debug)]
21 pub struct UnmatchedBrace {
22 pub expected_delim: token::DelimToken,
23 pub found_delim: Option<token::DelimToken>,
25 pub unclosed_span: Option<Span>,
26 pub candidate_span: Option<Span>,
29 pub struct StringReader<'a> {
31 /// Initial position, read-only.
33 /// The absolute offset within the source_map of the current character.
34 // FIXME(#64197): `pub` is needed by tests for now.
36 /// Stop reading src at this index.
38 /// Source text to tokenize.
40 override_span: Option<Span>,
43 impl<'a> StringReader<'a> {
46 source_file: Lrc<rustc_span::SourceFile>,
47 override_span: Option<Span>,
49 if source_file.src.is_none() {
51 .bug(&format!("cannot lex `source_file` without source: {}", source_file.name));
54 let src = (*source_file.src.as_ref().unwrap()).clone();
58 start_pos: source_file.start_pos,
59 pos: source_file.start_pos,
60 end_src_index: src.len(),
66 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
67 let begin = sess.source_map().lookup_byte_offset(span.lo());
68 let end = sess.source_map().lookup_byte_offset(span.hi());
70 // Make the range zero-length if the span is invalid.
71 if begin.sf.start_pos != end.sf.start_pos {
72 span = span.shrink_to_lo();
75 let mut sr = StringReader::new(sess, begin.sf, None);
77 // Seek the lexer to the right byte range.
78 sr.end_src_index = sr.src_index(span.hi());
83 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
84 self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
87 /// Returns the next token, including trivia like whitespace or comments.
89 /// `Err(())` means that some errors were encountered, which can be
90 /// retrieved using `buffer_fatal_errors`.
91 pub fn next_token(&mut self) -> Token {
92 let start_src_index = self.src_index(self.pos);
93 let text: &str = &self.src[start_src_index..self.end_src_index];
96 let span = self.mk_sp(self.pos, self.pos);
97 return Token::new(token::Eof, span);
101 let is_beginning_of_file = self.pos == self.start_pos;
102 if is_beginning_of_file {
103 if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
104 let start = self.pos;
105 self.pos = self.pos + BytePos::from_usize(shebang_len);
107 let sym = self.symbol_from(start + BytePos::from_usize("#!".len()));
108 let kind = token::Shebang(sym);
110 let span = self.mk_sp(start, self.pos);
111 return Token::new(kind, span);
116 let token = rustc_lexer::first_token(text);
118 let start = self.pos;
119 self.pos = self.pos + BytePos::from_usize(token.len);
121 debug!("try_next_token: {:?}({:?})", token.kind, self.str_from(start));
123 // This could use `?`, but that makes code significantly (10-20%) slower.
124 // https://github.com/rust-lang/rust/issues/37939
125 let kind = self.cook_lexer_token(token.kind, start);
127 let span = self.mk_sp(start, self.pos);
128 Token::new(kind, span)
131 /// Report a fatal lexical error with a given span.
132 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
133 self.sess.span_diagnostic.span_fatal(sp, m)
136 /// Report a lexical error with a given span.
137 fn err_span(&self, sp: Span, m: &str) {
138 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
141 /// Report a fatal error spanning [`from_pos`, `to_pos`).
142 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
143 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
146 /// Report a lexical error spanning [`from_pos`, `to_pos`).
147 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
148 self.err_span(self.mk_sp(from_pos, to_pos), m)
151 fn struct_span_fatal(
156 ) -> DiagnosticBuilder<'a> {
157 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
160 fn struct_fatal_span_char(
166 ) -> DiagnosticBuilder<'a> {
167 let mut m = m.to_string();
169 push_escaped_char(&mut m, c);
171 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
174 /// Turns simple `rustc_lexer::TokenKind` enum into a rich
175 /// `libsyntax::TokenKind`. This turns strings into interned
176 /// symbols and runs additional validation.
177 fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> TokenKind {
179 rustc_lexer::TokenKind::LineComment => {
180 let string = self.str_from(start);
181 // comments with only more "/"s are not doc comments
182 let tok = if comments::is_line_doc_comment(string) {
183 self.forbid_bare_cr(start, string, "bare CR not allowed in doc-comment");
184 token::DocComment(Symbol::intern(string))
191 rustc_lexer::TokenKind::BlockComment { terminated } => {
192 let string = self.str_from(start);
193 // block comments starting with "/**" or "/*!" are doc-comments
194 // but comments with only "*"s between two "/"s are not
195 let is_doc_comment = comments::is_block_doc_comment(string);
198 let msg = if is_doc_comment {
199 "unterminated block doc-comment"
201 "unterminated block comment"
203 let last_bpos = self.pos;
204 self.fatal_span_(start, last_bpos, msg).raise();
207 let tok = if is_doc_comment {
208 self.forbid_bare_cr(start, string, "bare CR not allowed in block doc-comment");
209 token::DocComment(Symbol::intern(string))
216 rustc_lexer::TokenKind::Whitespace => token::Whitespace,
217 rustc_lexer::TokenKind::Ident | rustc_lexer::TokenKind::RawIdent => {
218 let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent;
219 let mut ident_start = start;
221 ident_start = ident_start + BytePos(2);
223 let sym = nfc_normalize(self.str_from(ident_start));
225 let span = self.mk_sp(start, self.pos);
226 if !sym.can_be_raw() {
227 self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
229 self.sess.raw_identifier_spans.borrow_mut().push(span);
231 token::Ident(sym, is_raw_ident)
233 rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
234 let suffix_start = start + BytePos(suffix_start as u32);
235 let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
236 let suffix = if suffix_start < self.pos {
237 let string = self.str_from(suffix_start);
242 self.mk_sp(suffix_start, self.pos),
243 "underscore literal suffix is not allowed",
246 "this was previously accepted by the compiler but is \
247 being phased out; it will become a hard error in \
252 <https://github.com/rust-lang/rust/issues/42326> \
253 for more information",
258 Some(Symbol::intern(string))
263 token::Literal(token::Lit { kind, symbol, suffix })
265 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
266 // Include the leading `'` in the real identifier, for macro
267 // expansion purposes. See #12512 for the gory details of why
268 // this is necessary.
269 let lifetime_name = self.str_from(start);
270 if starts_with_number {
271 self.err_span_(start, self.pos, "lifetimes cannot start with a number");
273 let ident = Symbol::intern(lifetime_name);
274 token::Lifetime(ident)
276 rustc_lexer::TokenKind::Semi => token::Semi,
277 rustc_lexer::TokenKind::Comma => token::Comma,
278 rustc_lexer::TokenKind::Dot => token::Dot,
279 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren),
280 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren),
281 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace),
282 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace),
283 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(token::Bracket),
284 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(token::Bracket),
285 rustc_lexer::TokenKind::At => token::At,
286 rustc_lexer::TokenKind::Pound => token::Pound,
287 rustc_lexer::TokenKind::Tilde => token::Tilde,
288 rustc_lexer::TokenKind::Question => token::Question,
289 rustc_lexer::TokenKind::Colon => token::Colon,
290 rustc_lexer::TokenKind::Dollar => token::Dollar,
291 rustc_lexer::TokenKind::Eq => token::Eq,
292 rustc_lexer::TokenKind::Not => token::Not,
293 rustc_lexer::TokenKind::Lt => token::Lt,
294 rustc_lexer::TokenKind::Gt => token::Gt,
295 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
296 rustc_lexer::TokenKind::And => token::BinOp(token::And),
297 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
298 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
299 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
300 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
301 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
302 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
304 rustc_lexer::TokenKind::Unknown => {
305 let c = self.str_from(start).chars().next().unwrap();
307 self.struct_fatal_span_char(start, self.pos, "unknown start of token", c);
308 // FIXME: the lexer could be used to turn the ASCII version of unicode homoglyphs,
309 // instead of keeping a table in `check_for_substitution`into the token. Ideally,
310 // this should be inside `rustc_lexer`. However, we should first remove compound
311 // tokens like `<<` from `rustc_lexer`, and then add fancier error recovery to it,
312 // as there will be less overall work to do this way.
313 let token = unicode_chars::check_for_substitution(self, start, c, &mut err)
314 .unwrap_or_else(|| token::Unknown(self.symbol_from(start)));
321 fn cook_lexer_literal(
324 suffix_start: BytePos,
325 kind: rustc_lexer::LiteralKind,
326 ) -> (token::LitKind, Symbol) {
328 rustc_lexer::LiteralKind::Char { terminated } => {
330 self.fatal_span_(start, suffix_start, "unterminated character literal").raise()
332 let content_start = start + BytePos(1);
333 let content_end = suffix_start - BytePos(1);
334 self.validate_char_escape(content_start, content_end);
335 let id = self.symbol_from_to(content_start, content_end);
338 rustc_lexer::LiteralKind::Byte { terminated } => {
340 self.fatal_span_(start + BytePos(1), suffix_start, "unterminated byte constant")
343 let content_start = start + BytePos(2);
344 let content_end = suffix_start - BytePos(1);
345 self.validate_byte_escape(content_start, content_end);
346 let id = self.symbol_from_to(content_start, content_end);
349 rustc_lexer::LiteralKind::Str { terminated } => {
351 self.fatal_span_(start, suffix_start, "unterminated double quote string")
354 let content_start = start + BytePos(1);
355 let content_end = suffix_start - BytePos(1);
356 self.validate_str_escape(content_start, content_end);
357 let id = self.symbol_from_to(content_start, content_end);
360 rustc_lexer::LiteralKind::ByteStr { terminated } => {
365 "unterminated double quote byte string",
369 let content_start = start + BytePos(2);
370 let content_end = suffix_start - BytePos(1);
371 self.validate_byte_str_escape(content_start, content_end);
372 let id = self.symbol_from_to(content_start, content_end);
375 rustc_lexer::LiteralKind::RawStr { n_hashes, started, terminated } => {
377 self.report_non_started_raw_string(start);
380 self.report_unterminated_raw_string(start, n_hashes)
382 let n_hashes: u16 = self.restrict_n_hashes(start, n_hashes);
383 let n = u32::from(n_hashes);
384 let content_start = start + BytePos(2 + n);
385 let content_end = suffix_start - BytePos(1 + n);
386 self.validate_raw_str_escape(content_start, content_end);
387 let id = self.symbol_from_to(content_start, content_end);
388 (token::StrRaw(n_hashes), id)
390 rustc_lexer::LiteralKind::RawByteStr { n_hashes, started, terminated } => {
392 self.report_non_started_raw_string(start);
395 self.report_unterminated_raw_string(start, n_hashes)
397 let n_hashes: u16 = self.restrict_n_hashes(start, n_hashes);
398 let n = u32::from(n_hashes);
399 let content_start = start + BytePos(3 + n);
400 let content_end = suffix_start - BytePos(1 + n);
401 self.validate_raw_byte_str_escape(content_start, content_end);
402 let id = self.symbol_from_to(content_start, content_end);
403 (token::ByteStrRaw(n_hashes), id)
405 rustc_lexer::LiteralKind::Int { base, empty_int } => {
407 self.err_span_(start, suffix_start, "no valid digits found for number");
408 (token::Integer, sym::integer(0))
410 self.validate_int_literal(base, start, suffix_start);
411 (token::Integer, self.symbol_from_to(start, suffix_start))
414 rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
416 let mut err = self.struct_span_fatal(
419 "expected at least one digit in exponent",
425 Base::Hexadecimal => self.err_span_(
428 "hexadecimal float literal is not supported",
431 self.err_span_(start, suffix_start, "octal float literal is not supported")
434 self.err_span_(start, suffix_start, "binary float literal is not supported")
439 let id = self.symbol_from_to(start, suffix_start);
446 fn src_index(&self, pos: BytePos) -> usize {
447 (pos - self.start_pos).to_usize()
450 /// Slice of the source text from `start` up to but excluding `self.pos`,
451 /// meaning the slice does not include the character `self.ch`.
452 fn str_from(&self, start: BytePos) -> &str {
453 self.str_from_to(start, self.pos)
456 /// Creates a Symbol from a given offset to the current offset.
457 fn symbol_from(&self, start: BytePos) -> Symbol {
458 debug!("taking an ident from {:?} to {:?}", start, self.pos);
459 Symbol::intern(self.str_from(start))
462 /// As symbol_from, with an explicit endpoint.
463 fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
464 debug!("taking an ident from {:?} to {:?}", start, end);
465 Symbol::intern(self.str_from_to(start, end))
468 /// Slice of the source text spanning from `start` up to but excluding `end`.
469 fn str_from_to(&self, start: BytePos, end: BytePos) -> &str {
470 &self.src[self.src_index(start)..self.src_index(end)]
473 fn forbid_bare_cr(&self, start: BytePos, s: &str, errmsg: &str) {
476 idx = match s[idx..].find('\r') {
478 Some(it) => idx + it + 1,
480 self.err_span_(start + BytePos(idx as u32 - 1), start + BytePos(idx as u32), errmsg);
484 fn report_non_started_raw_string(&self, start: BytePos) -> ! {
485 let bad_char = self.str_from(start).chars().last().unwrap();
486 self.struct_fatal_span_char(
489 "found invalid character; only `#` is allowed \
490 in raw string delimitation",
497 fn report_unterminated_raw_string(&self, start: BytePos, n_hashes: usize) -> ! {
498 let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
499 self.mk_sp(start, start),
500 "unterminated raw string",
503 err.span_label(self.mk_sp(start, start), "unterminated raw string");
507 "this raw string should be terminated with `\"{}`",
508 "#".repeat(n_hashes as usize)
516 fn restrict_n_hashes(&self, start: BytePos, n_hashes: usize) -> u16 {
517 match n_hashes.try_into() {
518 Ok(n_hashes) => n_hashes,
523 "too many `#` symbols: raw strings may be \
524 delimited by up to 65535 `#` symbols",
531 fn validate_char_escape(&self, content_start: BytePos, content_end: BytePos) {
532 let lit = self.str_from_to(content_start, content_end);
533 if let Err((off, err)) = unescape::unescape_char(lit) {
535 &self.sess.span_diagnostic,
537 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
538 unescape::Mode::Char,
545 fn validate_byte_escape(&self, content_start: BytePos, content_end: BytePos) {
546 let lit = self.str_from_to(content_start, content_end);
547 if let Err((off, err)) = unescape::unescape_byte(lit) {
549 &self.sess.span_diagnostic,
551 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
552 unescape::Mode::Byte,
559 fn validate_str_escape(&self, content_start: BytePos, content_end: BytePos) {
560 let lit = self.str_from_to(content_start, content_end);
561 unescape::unescape_str(lit, &mut |range, c| {
562 if let Err(err) = c {
564 &self.sess.span_diagnostic,
566 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
575 fn validate_raw_str_escape(&self, content_start: BytePos, content_end: BytePos) {
576 let lit = self.str_from_to(content_start, content_end);
577 unescape::unescape_raw_str(lit, &mut |range, c| {
578 if let Err(err) = c {
580 &self.sess.span_diagnostic,
582 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
591 fn validate_raw_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) {
592 let lit = self.str_from_to(content_start, content_end);
593 unescape::unescape_raw_byte_str(lit, &mut |range, c| {
594 if let Err(err) = c {
596 &self.sess.span_diagnostic,
598 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
599 unescape::Mode::ByteStr,
607 fn validate_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) {
608 let lit = self.str_from_to(content_start, content_end);
609 unescape::unescape_byte_str(lit, &mut |range, c| {
610 if let Err(err) = c {
612 &self.sess.span_diagnostic,
614 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
615 unescape::Mode::ByteStr,
623 fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) {
624 let base = match base {
629 let s = self.str_from_to(content_start + BytePos(2), content_end);
630 for (idx, c) in s.char_indices() {
631 let idx = idx as u32;
632 if c != '_' && c.to_digit(base).is_none() {
633 let lo = content_start + BytePos(2 + idx);
634 let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32);
635 self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base));
641 pub fn nfc_normalize(string: &str) -> Symbol {
642 use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization};
643 match is_nfc_quick(string.chars()) {
644 IsNormalized::Yes => Symbol::intern(string),
646 let normalized_str: String = string.chars().nfc().collect();
647 Symbol::intern(&normalized_str)