1 use rustc_data_structures::sync::Lrc;
2 use rustc_errors::{FatalError, DiagnosticBuilder};
4 use rustc_lexer::unescape;
5 use syntax::token::{self, Token, TokenKind};
6 use syntax::sess::ParseSess;
7 use syntax::util::comments;
8 use syntax_pos::symbol::{sym, Symbol};
9 use syntax_pos::{BytePos, Pos, Span};
12 use std::convert::TryInto;
17 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> {
44 pub fn new(sess: &'a ParseSess,
45 source_file: Lrc<syntax_pos::SourceFile>,
46 override_span: Option<Span>) -> Self {
47 if source_file.src.is_none() {
48 sess.span_diagnostic.bug(&format!("cannot lex `source_file` without source: {}",
52 let src = (*source_file.src.as_ref().unwrap()).clone();
56 start_pos: source_file.start_pos,
57 pos: source_file.start_pos,
58 end_src_index: src.len(),
64 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
65 let begin = sess.source_map().lookup_byte_offset(span.lo());
66 let end = sess.source_map().lookup_byte_offset(span.hi());
68 // Make the range zero-length if the span is invalid.
69 if begin.sf.start_pos != end.sf.start_pos {
70 span = span.shrink_to_lo();
73 let mut sr = StringReader::new(sess, begin.sf, None);
75 // Seek the lexer to the right byte range.
76 sr.end_src_index = sr.src_index(span.hi());
82 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
83 self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
86 /// Returns the next token, including trivia like whitespace or comments.
88 /// `Err(())` means that some errors were encountered, which can be
89 /// retrieved using `buffer_fatal_errors`.
90 pub fn next_token(&mut self) -> Token {
91 let start_src_index = self.src_index(self.pos);
92 let text: &str = &self.src[start_src_index..self.end_src_index];
95 let span = self.mk_sp(self.pos, self.pos);
96 return Token::new(token::Eof, span);
100 let is_beginning_of_file = self.pos == self.start_pos;
101 if is_beginning_of_file {
102 if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
103 let start = self.pos;
104 self.pos = self.pos + BytePos::from_usize(shebang_len);
106 let sym = self.symbol_from(start + BytePos::from_usize("#!".len()));
107 let kind = token::Shebang(sym);
109 let span = self.mk_sp(start, self.pos);
110 return Token::new(kind, span);
115 let token = rustc_lexer::first_token(text);
117 let start = self.pos;
118 self.pos = self.pos + BytePos::from_usize(token.len);
120 debug!("try_next_token: {:?}({:?})", token.kind, self.str_from(start));
122 // This could use `?`, but that makes code significantly (10-20%) slower.
123 // https://github.com/rust-lang/rust/issues/37939
124 let kind = self.cook_lexer_token(token.kind, start);
126 let span = self.mk_sp(start, self.pos);
127 Token::new(kind, span)
130 /// Report a fatal lexical error with a given span.
131 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
132 self.sess.span_diagnostic.span_fatal(sp, m)
135 /// Report a lexical error with a given span.
136 fn err_span(&self, sp: Span, m: &str) {
137 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(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
152 -> DiagnosticBuilder<'a>
154 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
157 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
158 -> DiagnosticBuilder<'a>
160 let mut m = m.to_string();
162 push_escaped_char(&mut m, c);
164 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
167 /// Turns simple `rustc_lexer::TokenKind` enum into a rich
168 /// `libsyntax::TokenKind`. This turns strings into interned
169 /// symbols and runs additional validation.
172 token: rustc_lexer::TokenKind,
176 rustc_lexer::TokenKind::LineComment => {
177 let string = self.str_from(start);
178 // comments with only more "/"s are not doc comments
179 let tok = if comments::is_line_doc_comment(string) {
180 self.forbid_bare_cr(start, string, "bare CR not allowed in doc-comment");
181 token::DocComment(Symbol::intern(string))
188 rustc_lexer::TokenKind::BlockComment { terminated } => {
189 let string = self.str_from(start);
190 // block comments starting with "/**" or "/*!" are doc-comments
191 // but comments with only "*"s between two "/"s are not
192 let is_doc_comment = comments::is_block_doc_comment(string);
195 let msg = if is_doc_comment {
196 "unterminated block doc-comment"
198 "unterminated block comment"
200 let last_bpos = self.pos;
201 self.fatal_span_(start, last_bpos, msg).raise();
204 let tok = if is_doc_comment {
205 self.forbid_bare_cr(start,
207 "bare CR not allowed in block doc-comment");
208 token::DocComment(Symbol::intern(string))
215 rustc_lexer::TokenKind::Whitespace => token::Whitespace,
216 rustc_lexer::TokenKind::Ident | rustc_lexer::TokenKind::RawIdent => {
217 let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent;
218 let mut ident_start = start;
220 ident_start = ident_start + BytePos(2);
222 // FIXME: perform NFKC normalization here. (Issue #2253)
223 let sym = self.symbol_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);
239 self.sess.span_diagnostic
240 .struct_span_warn(self.mk_sp(suffix_start, self.pos),
241 "underscore literal suffix is not allowed")
242 .warn("this was previously accepted by the compiler but is \
243 being phased out; it will become a hard error in \
245 .note("for more information, see issue #42326 \
246 <https://github.com/rust-lang/rust/issues/42326>")
250 Some(Symbol::intern(string))
255 token::Literal(token::Lit { kind, symbol, suffix })
257 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
258 // Include the leading `'` in the real identifier, for macro
259 // expansion purposes. See #12512 for the gory details of why
260 // this is necessary.
261 let lifetime_name = self.str_from(start);
262 if starts_with_number {
266 "lifetimes cannot start with a number",
269 let ident = Symbol::intern(lifetime_name);
270 token::Lifetime(ident)
272 rustc_lexer::TokenKind::Semi => token::Semi,
273 rustc_lexer::TokenKind::Comma => token::Comma,
274 rustc_lexer::TokenKind::Dot => token::Dot,
275 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren),
276 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren),
277 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace),
278 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace),
279 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(token::Bracket),
280 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(token::Bracket),
281 rustc_lexer::TokenKind::At => token::At,
282 rustc_lexer::TokenKind::Pound => token::Pound,
283 rustc_lexer::TokenKind::Tilde => token::Tilde,
284 rustc_lexer::TokenKind::Question => token::Question,
285 rustc_lexer::TokenKind::Colon => token::Colon,
286 rustc_lexer::TokenKind::Dollar => token::Dollar,
287 rustc_lexer::TokenKind::Eq => token::Eq,
288 rustc_lexer::TokenKind::Not => token::Not,
289 rustc_lexer::TokenKind::Lt => token::Lt,
290 rustc_lexer::TokenKind::Gt => token::Gt,
291 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
292 rustc_lexer::TokenKind::And => token::BinOp(token::And),
293 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
294 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
295 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
296 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
297 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
298 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
300 rustc_lexer::TokenKind::Unknown => {
301 let c = self.str_from(start).chars().next().unwrap();
302 let mut err = self.struct_fatal_span_char(start,
304 "unknown start of token",
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)));
319 fn cook_lexer_literal(
322 suffix_start: BytePos,
323 kind: rustc_lexer::LiteralKind
324 ) -> (token::LitKind, Symbol) {
326 rustc_lexer::LiteralKind::Char { terminated } => {
328 self.fatal_span_(start, suffix_start,
329 "unterminated character literal".into())
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,
341 "unterminated byte constant".into())
344 let content_start = start + BytePos(2);
345 let content_end = suffix_start - BytePos(1);
346 self.validate_byte_escape(content_start, content_end);
347 let id = self.symbol_from_to(content_start, content_end);
350 rustc_lexer::LiteralKind::Str { terminated } => {
352 self.fatal_span_(start, suffix_start,
353 "unterminated double quote string".into())
356 let content_start = start + BytePos(1);
357 let content_end = suffix_start - BytePos(1);
358 self.validate_str_escape(content_start, content_end);
359 let id = self.symbol_from_to(content_start, content_end);
362 rustc_lexer::LiteralKind::ByteStr { terminated } => {
364 self.fatal_span_(start + BytePos(1), suffix_start,
365 "unterminated double quote byte string".into())
368 let content_start = start + BytePos(2);
369 let content_end = suffix_start - BytePos(1);
370 self.validate_byte_str_escape(content_start, content_end);
371 let id = self.symbol_from_to(content_start, content_end);
374 rustc_lexer::LiteralKind::RawStr { n_hashes, started, terminated } => {
376 self.report_non_started_raw_string(start);
379 self.report_unterminated_raw_string(start, n_hashes)
381 let n_hashes: u16 = self.restrict_n_hashes(start, n_hashes);
382 let n = u32::from(n_hashes);
383 let content_start = start + BytePos(2 + n);
384 let content_end = suffix_start - BytePos(1 + n);
385 self.validate_raw_str_escape(content_start, content_end);
386 let id = self.symbol_from_to(content_start, content_end);
387 (token::StrRaw(n_hashes), id)
389 rustc_lexer::LiteralKind::RawByteStr { n_hashes, started, terminated } => {
391 self.report_non_started_raw_string(start);
394 self.report_unterminated_raw_string(start, n_hashes)
396 let n_hashes: u16 = self.restrict_n_hashes(start, n_hashes);
397 let n = u32::from(n_hashes);
398 let content_start = start + BytePos(3 + n);
399 let content_end = suffix_start - BytePos(1 + n);
400 self.validate_raw_byte_str_escape(content_start, content_end);
401 let id = self.symbol_from_to(content_start, content_end);
402 (token::ByteStrRaw(n_hashes), id)
404 rustc_lexer::LiteralKind::Int { base, empty_int } => {
406 self.err_span_(start, suffix_start, "no valid digits found for number");
407 (token::Integer, sym::integer(0))
409 self.validate_int_literal(base, start, suffix_start);
410 (token::Integer, self.symbol_from_to(start, suffix_start))
413 rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
415 let mut err = self.struct_span_fatal(
417 "expected at least one digit in exponent"
423 Base::Hexadecimal => {
424 self.err_span_(start, suffix_start,
425 "hexadecimal float literal is not supported")
428 self.err_span_(start, suffix_start,
429 "octal float literal is not supported")
432 self.err_span_(start, suffix_start,
433 "binary float literal is not supported")
438 let id = self.symbol_from_to(start, suffix_start);
445 fn src_index(&self, pos: BytePos) -> usize {
446 (pos - self.start_pos).to_usize()
449 /// Slice of the source text from `start` up to but excluding `self.pos`,
450 /// meaning the slice does not include the character `self.ch`.
451 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
471 &self.src[self.src_index(start)..self.src_index(end)]
474 fn forbid_bare_cr(&self, start: BytePos, s: &str, errmsg: &str) {
477 idx = match s[idx..].find('\r') {
479 Some(it) => idx + it + 1
481 self.err_span_(start + BytePos(idx as u32 - 1),
482 start + BytePos(idx as u32),
487 fn report_non_started_raw_string(&self, start: BytePos) -> ! {
488 let bad_char = self.str_from(start).chars().last().unwrap();
490 .struct_fatal_span_char(
493 "found invalid character; only `#` is allowed \
494 in raw string delimitation",
501 fn report_unterminated_raw_string(&self, start: BytePos, n_hashes: usize) -> ! {
502 let mut err = self.struct_span_fatal(
504 "unterminated raw string",
507 self.mk_sp(start, start),
508 "unterminated raw string",
512 err.note(&format!("this raw string should be terminated with `\"{}`",
513 "#".repeat(n_hashes as usize)));
520 fn restrict_n_hashes(&self, start: BytePos, n_hashes: usize) -> u16 {
521 match n_hashes.try_into() {
522 Ok(n_hashes) => n_hashes,
524 self.fatal_span_(start,
526 "too many `#` symbols: raw strings may be \
527 delimited by up to 65535 `#` symbols").raise();
532 fn validate_char_escape(&self, content_start: BytePos, content_end: BytePos) {
533 let lit = self.str_from_to(content_start, content_end);
534 if let Err((off, err)) = unescape::unescape_char(lit) {
536 &self.sess.span_diagnostic,
538 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
539 unescape::Mode::Char,
546 fn validate_byte_escape(&self, content_start: BytePos, content_end: BytePos) {
547 let lit = self.str_from_to(content_start, content_end);
548 if let Err((off, err)) = unescape::unescape_byte(lit) {
550 &self.sess.span_diagnostic,
552 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
553 unescape::Mode::Byte,
560 fn validate_str_escape(&self, content_start: BytePos, content_end: BytePos) {
561 let lit = self.str_from_to(content_start, content_end);
562 unescape::unescape_str(lit, &mut |range, c| {
563 if let Err(err) = c {
565 &self.sess.span_diagnostic,
567 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
576 fn validate_raw_str_escape(&self, content_start: BytePos, content_end: BytePos) {
577 let lit = self.str_from_to(content_start, content_end);
578 unescape::unescape_raw_str(lit, &mut |range, c| {
579 if let Err(err) = c {
581 &self.sess.span_diagnostic,
583 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
592 fn validate_raw_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) {
593 let lit = self.str_from_to(content_start, content_end);
594 unescape::unescape_raw_byte_str(lit, &mut |range, c| {
595 if let Err(err) = c {
597 &self.sess.span_diagnostic,
599 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
600 unescape::Mode::ByteStr,
608 fn validate_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) {
609 let lit = self.str_from_to(content_start, content_end);
610 unescape::unescape_byte_str(lit, &mut |range, c| {
611 if let Err(err) = c {
613 &self.sess.span_diagnostic,
615 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
616 unescape::Mode::ByteStr,
624 fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) {
625 let base = match base {
630 let s = self.str_from_to(content_start + BytePos(2), content_end);
631 for (idx, c) in s.char_indices() {
632 let idx = idx as u32;
633 if c != '_' && c.to_digit(base).is_none() {
634 let lo = content_start + BytePos(2 + idx);
635 let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32);
636 self.err_span_(lo, hi,
637 &format!("invalid digit for a base {} literal", base));