1 use rustc_data_structures::sync::Lrc;
2 use rustc_errors::{DiagnosticBuilder, FatalError};
3 use rustc_lexer::unescape;
5 use rustc_span::symbol::{sym, Symbol};
6 use rustc_span::{BytePos, Pos, Span};
7 use syntax::sess::ParseSess;
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 \
251 "for more information, see issue #42326 \
252 <https://github.com/rust-lang/rust/issues/42326>",
257 Some(Symbol::intern(string))
262 token::Literal(token::Lit { kind, symbol, suffix })
264 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
265 // Include the leading `'` in the real identifier, for macro
266 // expansion purposes. See #12512 for the gory details of why
267 // this is necessary.
268 let lifetime_name = self.str_from(start);
269 if starts_with_number {
270 self.err_span_(start, self.pos, "lifetimes cannot start with a number");
272 let ident = Symbol::intern(lifetime_name);
273 token::Lifetime(ident)
275 rustc_lexer::TokenKind::Semi => token::Semi,
276 rustc_lexer::TokenKind::Comma => token::Comma,
277 rustc_lexer::TokenKind::Dot => token::Dot,
278 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren),
279 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren),
280 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace),
281 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace),
282 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(token::Bracket),
283 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(token::Bracket),
284 rustc_lexer::TokenKind::At => token::At,
285 rustc_lexer::TokenKind::Pound => token::Pound,
286 rustc_lexer::TokenKind::Tilde => token::Tilde,
287 rustc_lexer::TokenKind::Question => token::Question,
288 rustc_lexer::TokenKind::Colon => token::Colon,
289 rustc_lexer::TokenKind::Dollar => token::Dollar,
290 rustc_lexer::TokenKind::Eq => token::Eq,
291 rustc_lexer::TokenKind::Not => token::Not,
292 rustc_lexer::TokenKind::Lt => token::Lt,
293 rustc_lexer::TokenKind::Gt => token::Gt,
294 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
295 rustc_lexer::TokenKind::And => token::BinOp(token::And),
296 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
297 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
298 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
299 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
300 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
301 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
303 rustc_lexer::TokenKind::Unknown => {
304 let c = self.str_from(start).chars().next().unwrap();
306 self.struct_fatal_span_char(start, self.pos, "unknown start of token", c);
307 // FIXME: the lexer could be used to turn the ASCII version of unicode homoglyphs,
308 // instead of keeping a table in `check_for_substitution`into the token. Ideally,
309 // this should be inside `rustc_lexer`. However, we should first remove compound
310 // tokens like `<<` from `rustc_lexer`, and then add fancier error recovery to it,
311 // as there will be less overall work to do this way.
312 let token = unicode_chars::check_for_substitution(self, start, c, &mut err)
313 .unwrap_or_else(|| token::Unknown(self.symbol_from(start)));
320 fn cook_lexer_literal(
323 suffix_start: BytePos,
324 kind: rustc_lexer::LiteralKind,
325 ) -> (token::LitKind, Symbol) {
327 rustc_lexer::LiteralKind::Char { terminated } => {
329 self.fatal_span_(start, suffix_start, "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 } => {
343 "unterminated byte constant".into(),
347 let content_start = start + BytePos(2);
348 let content_end = suffix_start - BytePos(1);
349 self.validate_byte_escape(content_start, content_end);
350 let id = self.symbol_from_to(content_start, content_end);
353 rustc_lexer::LiteralKind::Str { terminated } => {
355 self.fatal_span_(start, suffix_start, "unterminated double quote string".into())
358 let content_start = start + BytePos(1);
359 let content_end = suffix_start - BytePos(1);
360 self.validate_str_escape(content_start, content_end);
361 let id = self.symbol_from_to(content_start, content_end);
364 rustc_lexer::LiteralKind::ByteStr { terminated } => {
369 "unterminated double quote byte string".into(),
373 let content_start = start + BytePos(2);
374 let content_end = suffix_start - BytePos(1);
375 self.validate_byte_str_escape(content_start, content_end);
376 let id = self.symbol_from_to(content_start, content_end);
379 rustc_lexer::LiteralKind::RawStr { n_hashes, started, terminated } => {
381 self.report_non_started_raw_string(start);
384 self.report_unterminated_raw_string(start, n_hashes)
386 let n_hashes: u16 = self.restrict_n_hashes(start, n_hashes);
387 let n = u32::from(n_hashes);
388 let content_start = start + BytePos(2 + n);
389 let content_end = suffix_start - BytePos(1 + n);
390 self.validate_raw_str_escape(content_start, content_end);
391 let id = self.symbol_from_to(content_start, content_end);
392 (token::StrRaw(n_hashes), id)
394 rustc_lexer::LiteralKind::RawByteStr { n_hashes, started, terminated } => {
396 self.report_non_started_raw_string(start);
399 self.report_unterminated_raw_string(start, n_hashes)
401 let n_hashes: u16 = self.restrict_n_hashes(start, n_hashes);
402 let n = u32::from(n_hashes);
403 let content_start = start + BytePos(3 + n);
404 let content_end = suffix_start - BytePos(1 + n);
405 self.validate_raw_byte_str_escape(content_start, content_end);
406 let id = self.symbol_from_to(content_start, content_end);
407 (token::ByteStrRaw(n_hashes), id)
409 rustc_lexer::LiteralKind::Int { base, empty_int } => {
411 self.err_span_(start, suffix_start, "no valid digits found for number");
412 (token::Integer, sym::integer(0))
414 self.validate_int_literal(base, start, suffix_start);
415 (token::Integer, self.symbol_from_to(start, suffix_start))
418 rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
420 let mut err = self.struct_span_fatal(
423 "expected at least one digit in exponent",
429 Base::Hexadecimal => self.err_span_(
432 "hexadecimal float literal is not supported",
435 self.err_span_(start, suffix_start, "octal float literal is not supported")
438 self.err_span_(start, suffix_start, "binary float literal is not supported")
443 let id = self.symbol_from_to(start, suffix_start);
450 fn src_index(&self, pos: BytePos) -> usize {
451 (pos - self.start_pos).to_usize()
454 /// Slice of the source text from `start` up to but excluding `self.pos`,
455 /// meaning the slice does not include the character `self.ch`.
456 fn str_from(&self, start: BytePos) -> &str {
457 self.str_from_to(start, self.pos)
460 /// Creates a Symbol from a given offset to the current offset.
461 fn symbol_from(&self, start: BytePos) -> Symbol {
462 debug!("taking an ident from {:?} to {:?}", start, self.pos);
463 Symbol::intern(self.str_from(start))
466 /// As symbol_from, with an explicit endpoint.
467 fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
468 debug!("taking an ident from {:?} to {:?}", start, end);
469 Symbol::intern(self.str_from_to(start, end))
472 /// Slice of the source text spanning from `start` up to but excluding `end`.
473 fn str_from_to(&self, start: BytePos, end: BytePos) -> &str {
474 &self.src[self.src_index(start)..self.src_index(end)]
477 fn forbid_bare_cr(&self, start: BytePos, s: &str, errmsg: &str) {
480 idx = match s[idx..].find('\r') {
482 Some(it) => idx + it + 1,
484 self.err_span_(start + BytePos(idx as u32 - 1), start + BytePos(idx as u32), errmsg);
488 fn report_non_started_raw_string(&self, start: BytePos) -> ! {
489 let bad_char = self.str_from(start).chars().last().unwrap();
490 self.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(start, start, "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)