1 use rustc_ast::token::{self, Token, TokenKind};
2 use rustc_ast::util::comments;
3 use rustc_data_structures::sync::Lrc;
4 use rustc_errors::{error_code, DiagnosticBuilder, FatalError};
5 use rustc_lexer::unescape;
7 use rustc_session::parse::ParseSess;
8 use rustc_span::symbol::{sym, Symbol};
9 use rustc_span::{BytePos, Pos, Span};
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 // 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.
52 sess.source_map().ensure_source_file_source_present(source_file.clone());
54 // FIXME(eddyb) use `Lrc<str>` or similar to avoid cloning the `String`.
55 let src = if let Some(src) = &source_file.src {
57 } else if let Some(src) = source_file.external_src.borrow().get_source() {
61 .bug(&format!("cannot lex `source_file` without source: {}", source_file.name));
66 start_pos: source_file.start_pos,
67 pos: source_file.start_pos,
68 end_src_index: src.len(),
74 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
75 let begin = sess.source_map().lookup_byte_offset(span.lo());
76 let end = sess.source_map().lookup_byte_offset(span.hi());
78 // Make the range zero-length if the span is invalid.
79 if begin.sf.start_pos != end.sf.start_pos {
80 span = span.shrink_to_lo();
83 let mut sr = StringReader::new(sess, begin.sf, None);
85 // Seek the lexer to the right byte range.
86 sr.end_src_index = sr.src_index(span.hi());
91 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
92 self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
95 /// Returns the next token, including trivia like whitespace or comments.
97 /// `Err(())` means that some errors were encountered, which can be
98 /// retrieved using `buffer_fatal_errors`.
99 pub fn next_token(&mut self) -> Token {
100 let start_src_index = self.src_index(self.pos);
101 let text: &str = &self.src[start_src_index..self.end_src_index];
104 let span = self.mk_sp(self.pos, self.pos);
105 return Token::new(token::Eof, span);
109 let is_beginning_of_file = self.pos == self.start_pos;
110 if is_beginning_of_file {
111 if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
112 let start = self.pos;
113 self.pos = self.pos + BytePos::from_usize(shebang_len);
115 let sym = self.symbol_from(start + BytePos::from_usize("#!".len()));
116 let kind = token::Shebang(sym);
118 let span = self.mk_sp(start, self.pos);
119 return Token::new(kind, span);
124 let token = rustc_lexer::first_token(text);
126 let start = self.pos;
127 self.pos = self.pos + BytePos::from_usize(token.len);
129 debug!("try_next_token: {:?}({:?})", token.kind, self.str_from(start));
131 // This could use `?`, but that makes code significantly (10-20%) slower.
132 // https://github.com/rust-lang/rust/issues/37939
133 let kind = self.cook_lexer_token(token.kind, start);
135 let span = self.mk_sp(start, self.pos);
136 Token::new(kind, span)
139 /// Report a fatal lexical error with a given span.
140 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
141 self.sess.span_diagnostic.span_fatal(sp, m)
144 /// Report a lexical error with a given span.
145 fn err_span(&self, sp: Span, m: &str) {
146 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
149 /// Report a fatal error spanning [`from_pos`, `to_pos`).
150 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
151 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
154 /// Report a lexical error spanning [`from_pos`, `to_pos`).
155 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
156 self.err_span(self.mk_sp(from_pos, to_pos), m)
159 fn struct_span_fatal(
164 ) -> DiagnosticBuilder<'a> {
165 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
168 fn struct_fatal_span_char(
174 ) -> DiagnosticBuilder<'a> {
175 let mut m = m.to_string();
177 push_escaped_char(&mut m, c);
179 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
182 /// Turns simple `rustc_lexer::TokenKind` enum into a rich
183 /// `librustc_ast::TokenKind`. This turns strings into interned
184 /// symbols and runs additional validation.
185 fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> TokenKind {
187 rustc_lexer::TokenKind::LineComment => {
188 let string = self.str_from(start);
189 // comments with only more "/"s are not doc comments
190 let tok = if comments::is_line_doc_comment(string) {
191 self.forbid_bare_cr(start, string, "bare CR not allowed in doc-comment");
192 token::DocComment(Symbol::intern(string))
199 rustc_lexer::TokenKind::BlockComment { terminated } => {
200 let string = self.str_from(start);
201 // block comments starting with "/**" or "/*!" are doc-comments
202 // but comments with only "*"s between two "/"s are not
203 let is_doc_comment = comments::is_block_doc_comment(string);
206 let msg = if is_doc_comment {
207 "unterminated block doc-comment"
209 "unterminated block comment"
211 let last_bpos = self.pos;
212 self.fatal_span_(start, last_bpos, msg).raise();
215 let tok = if is_doc_comment {
216 self.forbid_bare_cr(start, string, "bare CR not allowed in block doc-comment");
217 token::DocComment(Symbol::intern(string))
224 rustc_lexer::TokenKind::Whitespace => token::Whitespace,
225 rustc_lexer::TokenKind::Ident | rustc_lexer::TokenKind::RawIdent => {
226 let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent;
227 let mut ident_start = start;
229 ident_start = ident_start + BytePos(2);
231 let sym = nfc_normalize(self.str_from(ident_start));
233 let span = self.mk_sp(start, self.pos);
234 if !sym.can_be_raw() {
235 self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
237 self.sess.raw_identifier_spans.borrow_mut().push(span);
239 token::Ident(sym, is_raw_ident)
241 rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
242 let suffix_start = start + BytePos(suffix_start as u32);
243 let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
244 let suffix = if suffix_start < self.pos {
245 let string = self.str_from(suffix_start);
250 self.mk_sp(suffix_start, self.pos),
251 "underscore literal suffix is not allowed",
254 "this was previously accepted by the compiler but is \
255 being phased out; it will become a hard error in \
260 <https://github.com/rust-lang/rust/issues/42326> \
261 for more information",
266 Some(Symbol::intern(string))
271 token::Literal(token::Lit { kind, symbol, suffix })
273 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
274 // Include the leading `'` in the real identifier, for macro
275 // expansion purposes. See #12512 for the gory details of why
276 // this is necessary.
277 let lifetime_name = self.str_from(start);
278 if starts_with_number {
279 self.err_span_(start, self.pos, "lifetimes cannot start with a number");
281 let ident = Symbol::intern(lifetime_name);
282 token::Lifetime(ident)
284 rustc_lexer::TokenKind::Semi => token::Semi,
285 rustc_lexer::TokenKind::Comma => token::Comma,
286 rustc_lexer::TokenKind::Dot => token::Dot,
287 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren),
288 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren),
289 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace),
290 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace),
291 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(token::Bracket),
292 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(token::Bracket),
293 rustc_lexer::TokenKind::At => token::At,
294 rustc_lexer::TokenKind::Pound => token::Pound,
295 rustc_lexer::TokenKind::Tilde => token::Tilde,
296 rustc_lexer::TokenKind::Question => token::Question,
297 rustc_lexer::TokenKind::Colon => token::Colon,
298 rustc_lexer::TokenKind::Dollar => token::Dollar,
299 rustc_lexer::TokenKind::Eq => token::Eq,
300 rustc_lexer::TokenKind::Not => token::Not,
301 rustc_lexer::TokenKind::Lt => token::Lt,
302 rustc_lexer::TokenKind::Gt => token::Gt,
303 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
304 rustc_lexer::TokenKind::And => token::BinOp(token::And),
305 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
306 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
307 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
308 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
309 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
310 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
312 rustc_lexer::TokenKind::Unknown => {
313 let c = self.str_from(start).chars().next().unwrap();
315 self.struct_fatal_span_char(start, self.pos, "unknown start of token", c);
316 // FIXME: the lexer could be used to turn the ASCII version of unicode homoglyphs,
317 // instead of keeping a table in `check_for_substitution`into the token. Ideally,
318 // this should be inside `rustc_lexer`. However, we should first remove compound
319 // tokens like `<<` from `rustc_lexer`, and then add fancier error recovery to it,
320 // as there will be less overall work to do this way.
321 let token = unicode_chars::check_for_substitution(self, start, c, &mut err)
322 .unwrap_or_else(|| token::Unknown(self.symbol_from(start)));
329 fn cook_lexer_literal(
332 suffix_start: BytePos,
333 kind: rustc_lexer::LiteralKind,
334 ) -> (token::LitKind, Symbol) {
336 rustc_lexer::LiteralKind::Char { terminated } => {
338 self.fatal_span_(start, suffix_start, "unterminated character literal").raise()
340 let content_start = start + BytePos(1);
341 let content_end = suffix_start - BytePos(1);
342 self.validate_char_escape(content_start, content_end);
343 let id = self.symbol_from_to(content_start, content_end);
346 rustc_lexer::LiteralKind::Byte { terminated } => {
348 self.fatal_span_(start + BytePos(1), suffix_start, "unterminated byte constant")
351 let content_start = start + BytePos(2);
352 let content_end = suffix_start - BytePos(1);
353 self.validate_byte_escape(content_start, content_end);
354 let id = self.symbol_from_to(content_start, content_end);
357 rustc_lexer::LiteralKind::Str { terminated } => {
359 self.fatal_span_(start, suffix_start, "unterminated double quote string")
362 let content_start = start + BytePos(1);
363 let content_end = suffix_start - BytePos(1);
364 self.validate_str_escape(content_start, content_end);
365 let id = self.symbol_from_to(content_start, content_end);
368 rustc_lexer::LiteralKind::ByteStr { terminated } => {
373 "unterminated double quote byte string",
377 let content_start = start + BytePos(2);
378 let content_end = suffix_start - BytePos(1);
379 self.validate_byte_str_escape(content_start, content_end);
380 let id = self.symbol_from_to(content_start, content_end);
383 rustc_lexer::LiteralKind::RawStr { n_hashes, started, terminated } => {
385 self.report_non_started_raw_string(start);
388 self.report_unterminated_raw_string(start, n_hashes)
390 let n_hashes: u16 = self.restrict_n_hashes(start, n_hashes);
391 let n = u32::from(n_hashes);
392 let content_start = start + BytePos(2 + n);
393 let content_end = suffix_start - BytePos(1 + n);
394 self.validate_raw_str_escape(content_start, content_end);
395 let id = self.symbol_from_to(content_start, content_end);
396 (token::StrRaw(n_hashes), id)
398 rustc_lexer::LiteralKind::RawByteStr { n_hashes, started, terminated } => {
400 self.report_non_started_raw_string(start);
403 self.report_unterminated_raw_string(start, n_hashes)
405 let n_hashes: u16 = self.restrict_n_hashes(start, n_hashes);
406 let n = u32::from(n_hashes);
407 let content_start = start + BytePos(3 + n);
408 let content_end = suffix_start - BytePos(1 + n);
409 self.validate_raw_byte_str_escape(content_start, content_end);
410 let id = self.symbol_from_to(content_start, content_end);
411 (token::ByteStrRaw(n_hashes), id)
413 rustc_lexer::LiteralKind::Int { base, empty_int } => {
415 self.err_span_(start, suffix_start, "no valid digits found for number");
416 (token::Integer, sym::integer(0))
418 self.validate_int_literal(base, start, suffix_start);
419 (token::Integer, self.symbol_from_to(start, suffix_start))
422 rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
424 let mut err = self.struct_span_fatal(
427 "expected at least one digit in exponent",
433 Base::Hexadecimal => self.err_span_(
436 "hexadecimal float literal is not supported",
439 self.err_span_(start, suffix_start, "octal float literal is not supported")
442 self.err_span_(start, suffix_start, "binary float literal is not supported")
447 let id = self.symbol_from_to(start, suffix_start);
454 fn src_index(&self, pos: BytePos) -> usize {
455 (pos - self.start_pos).to_usize()
458 /// Slice of the source text from `start` up to but excluding `self.pos`,
459 /// meaning the slice does not include the character `self.ch`.
460 fn str_from(&self, start: BytePos) -> &str {
461 self.str_from_to(start, self.pos)
464 /// Creates a Symbol from a given offset to the current offset.
465 fn symbol_from(&self, start: BytePos) -> Symbol {
466 debug!("taking an ident from {:?} to {:?}", start, self.pos);
467 Symbol::intern(self.str_from(start))
470 /// As symbol_from, with an explicit endpoint.
471 fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
472 debug!("taking an ident from {:?} to {:?}", start, end);
473 Symbol::intern(self.str_from_to(start, end))
476 /// Slice of the source text spanning from `start` up to but excluding `end`.
477 fn str_from_to(&self, start: BytePos, end: BytePos) -> &str {
478 &self.src[self.src_index(start)..self.src_index(end)]
481 fn forbid_bare_cr(&self, start: BytePos, s: &str, errmsg: &str) {
484 idx = match s[idx..].find('\r') {
486 Some(it) => idx + it + 1,
488 self.err_span_(start + BytePos(idx as u32 - 1), start + BytePos(idx as u32), errmsg);
492 fn report_non_started_raw_string(&self, start: BytePos) -> ! {
493 let bad_char = self.str_from(start).chars().last().unwrap();
494 self.struct_fatal_span_char(
497 "found invalid character; only `#` is allowed \
498 in raw string delimitation",
505 fn report_unterminated_raw_string(&self, start: BytePos, n_hashes: usize) -> ! {
506 let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
507 self.mk_sp(start, start),
508 "unterminated raw string",
511 err.span_label(self.mk_sp(start, start), "unterminated raw string");
515 "this raw string should be terminated with `\"{}`",
516 "#".repeat(n_hashes as usize)
524 fn restrict_n_hashes(&self, start: BytePos, n_hashes: usize) -> u16 {
525 match n_hashes.try_into() {
526 Ok(n_hashes) => n_hashes,
531 "too many `#` symbols: raw strings may be \
532 delimited by up to 65535 `#` symbols",
539 fn validate_char_escape(&self, content_start: BytePos, content_end: BytePos) {
540 let lit = self.str_from_to(content_start, content_end);
541 if let Err((off, err)) = unescape::unescape_char(lit) {
543 &self.sess.span_diagnostic,
545 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
546 unescape::Mode::Char,
553 fn validate_byte_escape(&self, content_start: BytePos, content_end: BytePos) {
554 let lit = self.str_from_to(content_start, content_end);
555 if let Err((off, err)) = unescape::unescape_byte(lit) {
557 &self.sess.span_diagnostic,
559 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
560 unescape::Mode::Byte,
567 fn validate_str_escape(&self, content_start: BytePos, content_end: BytePos) {
568 let lit = self.str_from_to(content_start, content_end);
569 unescape::unescape_str(lit, &mut |range, c| {
570 if let Err(err) = c {
572 &self.sess.span_diagnostic,
574 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
583 fn validate_raw_str_escape(&self, content_start: BytePos, content_end: BytePos) {
584 let lit = self.str_from_to(content_start, content_end);
585 unescape::unescape_raw_str(lit, &mut |range, c| {
586 if let Err(err) = c {
588 &self.sess.span_diagnostic,
590 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
599 fn validate_raw_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) {
600 let lit = self.str_from_to(content_start, content_end);
601 unescape::unescape_raw_byte_str(lit, &mut |range, c| {
602 if let Err(err) = c {
604 &self.sess.span_diagnostic,
606 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
607 unescape::Mode::ByteStr,
615 fn validate_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) {
616 let lit = self.str_from_to(content_start, content_end);
617 unescape::unescape_byte_str(lit, &mut |range, c| {
618 if let Err(err) = c {
620 &self.sess.span_diagnostic,
622 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
623 unescape::Mode::ByteStr,
631 fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) {
632 let base = match base {
637 let s = self.str_from_to(content_start + BytePos(2), content_end);
638 for (idx, c) in s.char_indices() {
639 let idx = idx as u32;
640 if c != '_' && c.to_digit(base).is_none() {
641 let lo = content_start + BytePos(2 + idx);
642 let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32);
643 self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base));
649 pub fn nfc_normalize(string: &str) -> Symbol {
650 use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization};
651 match is_nfc_quick(string.chars()) {
652 IsNormalized::Yes => Symbol::intern(string),
654 let normalized_str: String = string.chars().nfc().collect();
655 Symbol::intern(&normalized_str)