1 use syntax::token::{self, Token, TokenKind};
2 use syntax::sess::ParseSess;
3 use syntax::symbol::{sym, Symbol};
4 use syntax::util::comments;
6 use errors::{FatalError, DiagnosticBuilder};
7 use syntax_pos::{BytePos, Pos, Span};
9 use rustc_lexer::unescape;
12 use std::convert::TryInto;
13 use rustc_data_structures::sync::Lrc;
18 mod unescape_error_reporting;
19 use unescape_error_reporting::{emit_unescape_error, push_escaped_char};
21 #[derive(Clone, Debug)]
22 pub struct UnmatchedBrace {
23 pub expected_delim: token::DelimToken,
24 pub found_delim: Option<token::DelimToken>,
26 pub unclosed_span: Option<Span>,
27 pub candidate_span: Option<Span>,
30 pub struct StringReader<'a> {
32 /// Initial position, read-only.
34 /// The absolute offset within the source_map of the current character.
35 // FIXME(#64197): `pub` is needed by tests for now.
37 /// Stop reading src at this index.
39 /// Source text to tokenize.
41 override_span: Option<Span>,
44 impl<'a> StringReader<'a> {
45 pub fn new(sess: &'a ParseSess,
46 source_file: Lrc<syntax_pos::SourceFile>,
47 override_span: Option<Span>) -> Self {
48 if source_file.src.is_none() {
49 sess.span_diagnostic.bug(&format!("cannot lex `source_file` without source: {}",
53 let src = (*source_file.src.as_ref().unwrap()).clone();
57 start_pos: source_file.start_pos,
58 pos: source_file.start_pos,
59 end_src_index: src.len(),
65 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
66 let begin = sess.source_map().lookup_byte_offset(span.lo());
67 let end = sess.source_map().lookup_byte_offset(span.hi());
69 // Make the range zero-length if the span is invalid.
70 if begin.sf.start_pos != end.sf.start_pos {
71 span = span.shrink_to_lo();
74 let mut sr = StringReader::new(sess, begin.sf, None);
76 // Seek the lexer to the right byte range.
77 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();
142 /// Report a fatal error spanning [`from_pos`, `to_pos`).
143 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
144 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
147 /// Report a lexical error spanning [`from_pos`, `to_pos`).
148 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
149 self.err_span(self.mk_sp(from_pos, to_pos), m)
152 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
153 -> DiagnosticBuilder<'a>
155 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
158 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
159 -> DiagnosticBuilder<'a>
161 let mut m = m.to_string();
163 push_escaped_char(&mut m, c);
165 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
168 /// Turns simple `rustc_lexer::TokenKind` enum into a rich
169 /// `libsyntax::TokenKind`. This turns strings into interned
170 /// symbols and runs additional validation.
173 token: rustc_lexer::TokenKind,
177 rustc_lexer::TokenKind::LineComment => {
178 let string = self.str_from(start);
179 // comments with only more "/"s are not doc comments
180 let tok = if comments::is_line_doc_comment(string) {
181 self.forbid_bare_cr(start, string, "bare CR not allowed in doc-comment");
182 token::DocComment(Symbol::intern(string))
189 rustc_lexer::TokenKind::BlockComment { terminated } => {
190 let string = self.str_from(start);
191 // block comments starting with "/**" or "/*!" are doc-comments
192 // but comments with only "*"s between two "/"s are not
193 let is_doc_comment = comments::is_block_doc_comment(string);
196 let msg = if is_doc_comment {
197 "unterminated block doc-comment"
199 "unterminated block comment"
201 let last_bpos = self.pos;
202 self.fatal_span_(start, last_bpos, msg).raise();
205 let tok = if is_doc_comment {
206 self.forbid_bare_cr(start,
208 "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 // FIXME: perform NFKC normalization here. (Issue #2253)
224 let sym = self.symbol_from(ident_start);
226 let span = self.mk_sp(start, self.pos);
227 if !sym.can_be_raw() {
228 self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
230 self.sess.raw_identifier_spans.borrow_mut().push(span);
232 token::Ident(sym, is_raw_ident)
234 rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
235 let suffix_start = start + BytePos(suffix_start as u32);
236 let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
237 let suffix = if suffix_start < self.pos {
238 let string = self.str_from(suffix_start);
240 self.sess.span_diagnostic
241 .struct_span_warn(self.mk_sp(suffix_start, self.pos),
242 "underscore literal suffix is not allowed")
243 .warn("this was previously accepted by the compiler but is \
244 being phased out; it will become a hard error in \
246 .note("for more information, see issue #42326 \
247 <https://github.com/rust-lang/rust/issues/42326>")
251 Some(Symbol::intern(string))
256 token::Literal(token::Lit { kind, symbol, suffix })
258 rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
259 // Include the leading `'` in the real identifier, for macro
260 // expansion purposes. See #12512 for the gory details of why
261 // this is necessary.
262 let lifetime_name = self.str_from(start);
263 if starts_with_number {
267 "lifetimes cannot start with a number",
270 let ident = Symbol::intern(lifetime_name);
271 token::Lifetime(ident)
273 rustc_lexer::TokenKind::Semi => token::Semi,
274 rustc_lexer::TokenKind::Comma => token::Comma,
275 rustc_lexer::TokenKind::Dot => token::Dot,
276 rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren),
277 rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren),
278 rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace),
279 rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace),
280 rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(token::Bracket),
281 rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(token::Bracket),
282 rustc_lexer::TokenKind::At => token::At,
283 rustc_lexer::TokenKind::Pound => token::Pound,
284 rustc_lexer::TokenKind::Tilde => token::Tilde,
285 rustc_lexer::TokenKind::Question => token::Question,
286 rustc_lexer::TokenKind::Colon => token::Colon,
287 rustc_lexer::TokenKind::Dollar => token::Dollar,
288 rustc_lexer::TokenKind::Eq => token::Eq,
289 rustc_lexer::TokenKind::Not => token::Not,
290 rustc_lexer::TokenKind::Lt => token::Lt,
291 rustc_lexer::TokenKind::Gt => token::Gt,
292 rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
293 rustc_lexer::TokenKind::And => token::BinOp(token::And),
294 rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
295 rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
296 rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
297 rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
298 rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
299 rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
301 rustc_lexer::TokenKind::Unknown => {
302 let c = self.str_from(start).chars().next().unwrap();
303 let mut err = self.struct_fatal_span_char(start,
305 "unknown start of token",
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,
330 "unterminated character literal".into())
333 let content_start = start + BytePos(1);
334 let content_end = suffix_start - BytePos(1);
335 self.validate_char_escape(content_start, content_end);
336 let id = self.symbol_from_to(content_start, content_end);
339 rustc_lexer::LiteralKind::Byte { terminated } => {
341 self.fatal_span_(start + BytePos(1), suffix_start,
342 "unterminated byte constant".into())
345 let content_start = start + BytePos(2);
346 let content_end = suffix_start - BytePos(1);
347 self.validate_byte_escape(content_start, content_end);
348 let id = self.symbol_from_to(content_start, content_end);
351 rustc_lexer::LiteralKind::Str { terminated } => {
353 self.fatal_span_(start, suffix_start,
354 "unterminated double quote string".into())
357 let content_start = start + BytePos(1);
358 let content_end = suffix_start - BytePos(1);
359 self.validate_str_escape(content_start, content_end);
360 let id = self.symbol_from_to(content_start, content_end);
363 rustc_lexer::LiteralKind::ByteStr { terminated } => {
365 self.fatal_span_(start + BytePos(1), suffix_start,
366 "unterminated double quote byte string".into())
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(
418 "expected at least one digit in exponent"
424 Base::Hexadecimal => {
425 self.err_span_(start, suffix_start,
426 "hexadecimal float literal is not supported")
429 self.err_span_(start, suffix_start,
430 "octal float literal is not supported")
433 self.err_span_(start, suffix_start,
434 "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
454 self.str_from_to(start, self.pos)
457 /// Creates a Symbol from a given offset to the current offset.
458 fn symbol_from(&self, start: BytePos) -> Symbol {
459 debug!("taking an ident from {:?} to {:?}", start, self.pos);
460 Symbol::intern(self.str_from(start))
463 /// As symbol_from, with an explicit endpoint.
464 fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
465 debug!("taking an ident from {:?} to {:?}", start, end);
466 Symbol::intern(self.str_from_to(start, end))
469 /// Slice of the source text spanning from `start` up to but excluding `end`.
470 fn str_from_to(&self, start: BytePos, end: BytePos) -> &str
472 &self.src[self.src_index(start)..self.src_index(end)]
475 fn forbid_bare_cr(&self, start: BytePos, s: &str, errmsg: &str) {
478 idx = match s[idx..].find('\r') {
480 Some(it) => idx + it + 1
482 self.err_span_(start + BytePos(idx as u32 - 1),
483 start + BytePos(idx as u32),
488 fn report_non_started_raw_string(&self, start: BytePos) -> ! {
489 let bad_char = self.str_from(start).chars().last().unwrap();
491 .struct_fatal_span_char(
494 "found invalid character; only `#` is allowed \
495 in raw string delimitation",
502 fn report_unterminated_raw_string(&self, start: BytePos, n_hashes: usize) -> ! {
503 let mut err = self.struct_span_fatal(
505 "unterminated raw string",
508 self.mk_sp(start, start),
509 "unterminated raw string",
513 err.note(&format!("this raw string should be terminated with `\"{}`",
514 "#".repeat(n_hashes as usize)));
521 fn restrict_n_hashes(&self, start: BytePos, n_hashes: usize) -> u16 {
522 match n_hashes.try_into() {
523 Ok(n_hashes) => n_hashes,
525 self.fatal_span_(start,
527 "too many `#` symbols: raw strings may be \
528 delimited by up to 65535 `#` symbols").raise();
533 fn validate_char_escape(&self, content_start: BytePos, content_end: BytePos) {
534 let lit = self.str_from_to(content_start, content_end);
535 if let Err((off, err)) = unescape::unescape_char(lit) {
537 &self.sess.span_diagnostic,
539 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
540 unescape::Mode::Char,
547 fn validate_byte_escape(&self, content_start: BytePos, content_end: BytePos) {
548 let lit = self.str_from_to(content_start, content_end);
549 if let Err((off, err)) = unescape::unescape_byte(lit) {
551 &self.sess.span_diagnostic,
553 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
554 unescape::Mode::Byte,
561 fn validate_str_escape(&self, content_start: BytePos, content_end: BytePos) {
562 let lit = self.str_from_to(content_start, content_end);
563 unescape::unescape_str(lit, &mut |range, c| {
564 if let Err(err) = c {
566 &self.sess.span_diagnostic,
568 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
577 fn validate_raw_str_escape(&self, content_start: BytePos, content_end: BytePos) {
578 let lit = self.str_from_to(content_start, content_end);
579 unescape::unescape_raw_str(lit, &mut |range, c| {
580 if let Err(err) = c {
582 &self.sess.span_diagnostic,
584 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
593 fn validate_raw_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) {
594 let lit = self.str_from_to(content_start, content_end);
595 unescape::unescape_raw_byte_str(lit, &mut |range, c| {
596 if let Err(err) = c {
598 &self.sess.span_diagnostic,
600 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
601 unescape::Mode::ByteStr,
609 fn validate_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) {
610 let lit = self.str_from_to(content_start, content_end);
611 unescape::unescape_byte_str(lit, &mut |range, c| {
612 if let Err(err) = c {
614 &self.sess.span_diagnostic,
616 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
617 unescape::Mode::ByteStr,
625 fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) {
626 let base = match base {
631 let s = self.str_from_to(content_start + BytePos(2), content_end);
632 for (idx, c) in s.char_indices() {
633 let idx = idx as u32;
634 if c != '_' && c.to_digit(base).is_none() {
635 let lo = content_start + BytePos(2 + idx);
636 let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32);
637 self.err_span_(lo, hi,
638 &format!("invalid digit for a base {} literal", base));