1 use crate::ast::{self, Ident};
2 use crate::parse::{token, ParseSess};
3 use crate::symbol::Symbol;
4 use crate::parse::unescape;
5 use crate::parse::unescape_error_reporting::{emit_unescape_error, push_escaped_char};
7 use errors::{FatalError, Diagnostic, DiagnosticBuilder};
8 use syntax_pos::{BytePos, Pos, Span, NO_EXPANSION};
9 use core::unicode::property::Pattern_White_Space;
14 use std::mem::replace;
15 use rustc_data_structures::sync::Lrc;
22 #[derive(Clone, Debug)]
23 pub struct TokenAndSpan {
24 pub tok: token::Token,
28 impl Default for TokenAndSpan {
29 fn default() -> Self {
31 tok: token::Whitespace,
32 sp: syntax_pos::DUMMY_SP,
37 #[derive(Clone, Debug)]
38 pub struct UnmatchedBrace {
39 pub expected_delim: token::DelimToken,
40 pub found_delim: token::DelimToken,
42 pub unclosed_span: Option<Span>,
43 pub candidate_span: Option<Span>,
46 pub struct StringReader<'a> {
47 crate sess: &'a ParseSess,
48 /// The absolute offset within the source_map of the next character to read
49 crate next_pos: BytePos,
50 /// The absolute offset within the source_map of the current character
52 /// The current character (which has been read from self.pos)
53 crate ch: Option<char>,
54 crate source_file: Lrc<syntax_pos::SourceFile>,
55 /// Stop reading src at this index.
56 crate end_src_index: usize,
58 peek_tok: token::Token,
60 peek_span_src_raw: Span,
61 fatal_errs: Vec<DiagnosticBuilder<'a>>,
62 // cache a direct reference to the source text, so that we don't have to
63 // retrieve it via `self.source_file.src.as_ref().unwrap()` all the time.
65 override_span: Option<Span>,
68 impl<'a> StringReader<'a> {
69 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
70 self.mk_sp_and_raw(lo, hi).0
73 fn mk_sp_and_raw(&self, lo: BytePos, hi: BytePos) -> (Span, Span) {
74 let raw = Span::new(lo, hi, NO_EXPANSION);
75 let real = self.override_span.unwrap_or(raw);
80 fn mk_ident(&self, string: &str) -> Ident {
81 let mut ident = Ident::from_str(string);
82 if let Some(span) = self.override_span {
89 fn unwrap_or_abort(&mut self, res: Result<TokenAndSpan, ()>) -> TokenAndSpan {
93 self.emit_fatal_errors();
99 fn next_token(&mut self) -> TokenAndSpan where Self: Sized {
100 let res = self.try_next_token();
101 self.unwrap_or_abort(res)
104 /// Returns the next token. EFFECT: advances the string_reader.
105 pub fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> {
106 assert!(self.fatal_errs.is_empty());
107 let ret_val = TokenAndSpan {
108 tok: replace(&mut self.peek_tok, token::Whitespace),
111 self.advance_token()?;
115 /// Immutably extract string if found at current position with given delimiters
116 fn peek_delimited(&self, from_ch: char, to_ch: char) -> Option<String> {
117 let mut pos = self.pos;
118 let mut idx = self.src_index(pos);
119 let mut ch = char_at(&self.src, idx);
123 pos = pos + Pos::from_usize(ch.len_utf8());
125 idx = self.src_index(pos);
126 while idx < self.end_src_index {
127 ch = char_at(&self.src, idx);
129 return Some(self.src[self.src_index(start_pos)..self.src_index(pos)].to_string());
131 pos = pos + Pos::from_usize(ch.len_utf8());
132 idx = self.src_index(pos);
137 fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> {
138 let mut t = self.try_next_token()?;
141 token::Whitespace | token::Comment | token::Shebang(_) => {
142 t = self.try_next_token()?;
151 pub fn real_token(&mut self) -> TokenAndSpan {
152 let res = self.try_real_token();
153 self.unwrap_or_abort(res)
157 fn is_eof(&self) -> bool {
161 fn fail_unterminated_raw_string(&self, pos: BytePos, hash_count: u16) {
162 let mut err = self.struct_span_fatal(pos, pos, "unterminated raw string");
163 err.span_label(self.mk_sp(pos, pos), "unterminated raw string");
166 err.note(&format!("this raw string should be terminated with `\"{}`",
167 "#".repeat(hash_count as usize)));
174 fn fatal(&self, m: &str) -> FatalError {
175 self.fatal_span(self.peek_span, m)
178 crate fn emit_fatal_errors(&mut self) {
179 for err in &mut self.fatal_errs {
183 self.fatal_errs.clear();
186 pub fn buffer_fatal_errors(&mut self) -> Vec<Diagnostic> {
187 let mut buffer = Vec::new();
189 for err in self.fatal_errs.drain(..) {
190 err.buffer(&mut buffer);
196 pub fn peek(&self) -> TokenAndSpan {
197 // FIXME(pcwalton): Bad copy!
199 tok: self.peek_tok.clone(),
204 /// For comments.rs, which hackily pokes into next_pos and ch
205 fn new_raw(sess: &'a ParseSess,
206 source_file: Lrc<syntax_pos::SourceFile>,
207 override_span: Option<Span>) -> Self {
208 let mut sr = StringReader::new_raw_internal(sess, source_file, override_span);
214 fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc<syntax_pos::SourceFile>,
215 override_span: Option<Span>) -> Self
217 if source_file.src.is_none() {
218 sess.span_diagnostic.bug(&format!("Cannot lex source_file without source: {}",
222 let src = (*source_file.src.as_ref().unwrap()).clone();
226 next_pos: source_file.start_pos,
227 pos: source_file.start_pos,
230 end_src_index: src.len(),
231 // dummy values; not read
232 peek_tok: token::Eof,
233 peek_span: syntax_pos::DUMMY_SP,
234 peek_span_src_raw: syntax_pos::DUMMY_SP,
236 fatal_errs: Vec::new(),
241 pub fn new_or_buffered_errs(sess: &'a ParseSess,
242 source_file: Lrc<syntax_pos::SourceFile>,
243 override_span: Option<Span>) -> Result<Self, Vec<Diagnostic>> {
244 let mut sr = StringReader::new_raw(sess, source_file, override_span);
245 if sr.advance_token().is_err() {
246 Err(sr.buffer_fatal_errors())
252 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
253 let begin = sess.source_map().lookup_byte_offset(span.lo());
254 let end = sess.source_map().lookup_byte_offset(span.hi());
256 // Make the range zero-length if the span is invalid.
257 if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
258 span = span.shrink_to_lo();
261 let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
263 // Seek the lexer to the right byte range.
264 sr.next_pos = span.lo();
265 sr.end_src_index = sr.src_index(span.hi());
269 if sr.advance_token().is_err() {
270 sr.emit_fatal_errors();
278 fn ch_is(&self, c: char) -> bool {
282 /// Report a fatal lexical error with a given span.
283 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
284 self.sess.span_diagnostic.span_fatal(sp, m)
287 /// Report a lexical error with a given span.
288 fn err_span(&self, sp: Span, m: &str) {
289 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
293 /// Report a fatal error spanning [`from_pos`, `to_pos`).
294 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
295 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
298 /// Report a lexical error spanning [`from_pos`, `to_pos`).
299 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
300 self.err_span(self.mk_sp(from_pos, to_pos), m)
303 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
304 /// escaped character to the error message
305 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
306 let mut m = m.to_string();
308 push_escaped_char(&mut m, c);
310 self.fatal_span_(from_pos, to_pos, &m[..])
313 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
314 -> DiagnosticBuilder<'a>
316 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
319 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
320 -> DiagnosticBuilder<'a>
322 let mut m = m.to_string();
324 push_escaped_char(&mut m, c);
326 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
329 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
330 /// escaped character to the error message
331 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
332 let mut m = m.to_string();
334 push_escaped_char(&mut m, c);
335 self.err_span_(from_pos, to_pos, &m[..]);
338 /// Advance peek_tok and peek_span to refer to the next token, and
339 /// possibly update the interner.
340 fn advance_token(&mut self) -> Result<(), ()> {
341 match self.scan_whitespace_or_comment() {
343 self.peek_span_src_raw = comment.sp;
344 self.peek_span = comment.sp;
345 self.peek_tok = comment.tok;
349 self.peek_tok = token::Eof;
350 let (real, raw) = self.mk_sp_and_raw(
351 self.source_file.end_pos,
352 self.source_file.end_pos,
354 self.peek_span = real;
355 self.peek_span_src_raw = raw;
357 let start_bytepos = self.pos;
358 self.peek_tok = self.next_token_inner()?;
359 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
360 self.peek_span = real;
361 self.peek_span_src_raw = raw;
370 fn src_index(&self, pos: BytePos) -> usize {
371 (pos - self.source_file.start_pos).to_usize()
374 /// Calls `f` with a string slice of the source text spanning from `start`
375 /// up to but excluding `self.pos`, meaning the slice does not include
376 /// the character `self.ch`.
377 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
378 where F: FnOnce(&str) -> T
380 self.with_str_from_to(start, self.pos, f)
383 /// Creates a Name from a given offset to the current offset.
384 fn name_from(&self, start: BytePos) -> ast::Name {
385 debug!("taking an ident from {:?} to {:?}", start, self.pos);
386 self.with_str_from(start, Symbol::intern)
389 /// As name_from, with an explicit endpoint.
390 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
391 debug!("taking an ident from {:?} to {:?}", start, end);
392 self.with_str_from_to(start, end, Symbol::intern)
395 /// Calls `f` with a string slice of the source text spanning from `start`
396 /// up to but excluding `end`.
397 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
398 where F: FnOnce(&str) -> T
400 f(&self.src[self.src_index(start)..self.src_index(end)])
403 /// Converts CRLF to LF in the given string, raising an error on bare CR.
404 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
405 let mut chars = s.char_indices().peekable();
406 while let Some((i, ch)) = chars.next() {
408 if let Some((lf_idx, '\n')) = chars.peek() {
409 return translate_crlf_(self, start, s, *lf_idx, chars, errmsg).into();
411 let pos = start + BytePos(i as u32);
412 let end_pos = start + BytePos((i + ch.len_utf8()) as u32);
413 self.err_span_(pos, end_pos, errmsg);
418 fn translate_crlf_(rdr: &StringReader<'_>,
422 mut chars: iter::Peekable<impl Iterator<Item = (usize, char)>>,
425 let mut buf = String::with_capacity(s.len());
427 buf.push_str(&s[.. j - 1]);
428 while let Some((i, ch)) = chars.next() {
431 buf.push_str(&s[j..i]);
433 let next = i + ch.len_utf8();
435 if chars.peek().map(|(_, ch)| *ch) != Some('\n') {
436 let pos = start + BytePos(i as u32);
437 let end_pos = start + BytePos(next as u32);
438 rdr.err_span_(pos, end_pos, errmsg);
443 buf.push_str(&s[j..]);
449 /// Advance the StringReader by one character.
450 crate fn bump(&mut self) {
451 let next_src_index = self.src_index(self.next_pos);
452 if next_src_index < self.end_src_index {
453 let next_ch = char_at(&self.src, next_src_index);
454 let next_ch_len = next_ch.len_utf8();
456 self.ch = Some(next_ch);
457 self.pos = self.next_pos;
458 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
461 self.pos = self.next_pos;
465 fn nextch(&self) -> Option<char> {
466 let next_src_index = self.src_index(self.next_pos);
467 if next_src_index < self.end_src_index {
468 Some(char_at(&self.src, next_src_index))
475 fn nextch_is(&self, c: char) -> bool {
476 self.nextch() == Some(c)
479 fn nextnextch(&self) -> Option<char> {
480 let next_src_index = self.src_index(self.next_pos);
481 if next_src_index < self.end_src_index {
482 let next_next_src_index =
483 next_src_index + char_at(&self.src, next_src_index).len_utf8();
484 if next_next_src_index < self.end_src_index {
485 return Some(char_at(&self.src, next_next_src_index));
492 fn nextnextch_is(&self, c: char) -> bool {
493 self.nextnextch() == Some(c)
496 /// Eats <XID_start><XID_continue>*, if possible.
497 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
498 if !ident_start(self.ch) {
502 let start = self.pos;
505 while ident_continue(self.ch) {
509 self.with_str_from(start, |string| {
511 self.sess.span_diagnostic
512 .struct_span_warn(self.mk_sp(start, self.pos),
513 "underscore literal suffix is not allowed")
514 .warn("this was previously accepted by the compiler but is \
515 being phased out; it will become a hard error in \
517 .note("for more information, see issue #42326 \
518 <https://github.com/rust-lang/rust/issues/42326>")
522 Some(Symbol::intern(string))
527 /// PRECONDITION: self.ch is not whitespace
528 /// Eats any kind of comment.
529 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
530 if let Some(c) = self.ch {
531 if c.is_whitespace() {
532 let msg = "called consume_any_line_comment, but there was whitespace";
533 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
538 match self.nextch() {
543 // line comments starting with "///" or "//!" are doc-comments
544 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
545 let start_bpos = self.pos - BytePos(2);
547 while !self.is_eof() {
548 match self.ch.unwrap() {
551 if self.nextch_is('\n') {
554 } else if doc_comment {
555 self.err_span_(self.pos,
557 "bare CR not allowed in doc-comment");
565 let tok = if doc_comment {
566 self.with_str_from(start_bpos, |string| {
567 token::DocComment(Symbol::intern(string))
572 Some(TokenAndSpan { tok, sp: self.mk_sp(start_bpos, self.pos) })
577 self.scan_block_comment()
581 } else if self.ch_is('#') {
582 if self.nextch_is('!') {
584 // Parse an inner attribute.
585 if self.nextnextch_is('[') {
589 let is_beginning_of_file = self.pos == self.source_file.start_pos;
590 if is_beginning_of_file {
591 debug!("Skipping a shebang");
592 let start = self.pos;
593 while !self.ch_is('\n') && !self.is_eof() {
596 return Some(TokenAndSpan {
597 tok: token::Shebang(self.name_from(start)),
598 sp: self.mk_sp(start, self.pos),
608 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
610 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
611 match self.ch.unwrap_or('\0') {
612 // # to handle shebang at start of file -- this is the entry point
613 // for skipping over all "junk"
615 let c = self.scan_comment();
616 debug!("scanning a comment {:?}", c);
619 c if is_pattern_whitespace(Some(c)) => {
620 let start_bpos = self.pos;
621 while is_pattern_whitespace(self.ch) {
624 let c = Some(TokenAndSpan {
625 tok: token::Whitespace,
626 sp: self.mk_sp(start_bpos, self.pos),
628 debug!("scanning whitespace: {:?}", c);
635 /// Might return a sugared-doc-attr
636 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
637 // block comments starting with "/**" or "/*!" are doc-comments
638 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
639 let start_bpos = self.pos - BytePos(2);
641 let mut level: isize = 1;
642 let mut has_cr = false;
645 let msg = if is_doc_comment {
646 "unterminated block doc-comment"
648 "unterminated block comment"
650 let last_bpos = self.pos;
651 self.fatal_span_(start_bpos, last_bpos, msg).raise();
653 let n = self.ch.unwrap();
655 '/' if self.nextch_is('*') => {
659 '*' if self.nextch_is('/') => {
671 self.with_str_from(start_bpos, |string| {
672 // but comments with only "*"s between two "/"s are not
673 let tok = if is_block_doc_comment(string) {
674 let string = if has_cr {
675 self.translate_crlf(start_bpos,
677 "bare CR not allowed in block doc-comment")
681 token::DocComment(Symbol::intern(&string[..]))
688 sp: self.mk_sp(start_bpos, self.pos),
693 /// Scan through any digits (base `scan_radix`) or underscores,
694 /// and return how many digits there were.
696 /// `real_radix` represents the true radix of the number we're
697 /// interested in, and errors will be emitted for any digits
698 /// between `real_radix` and `scan_radix`.
699 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
700 assert!(real_radix <= scan_radix);
706 debug!("skipping a _");
710 match c.and_then(|cc| cc.to_digit(scan_radix)) {
712 debug!("{:?} in scan_digits", c);
713 // check that the hypothetical digit is actually
714 // in range for the true radix
715 if c.unwrap().to_digit(real_radix).is_none() {
716 self.err_span_(self.pos,
718 &format!("invalid digit for a base {} literal", real_radix));
728 /// Lex a LIT_INTEGER or a LIT_FLOAT
729 fn scan_number(&mut self, c: char) -> token::Lit {
731 let start_bpos = self.pos;
734 let num_digits = if c == '0' {
735 match self.ch.unwrap_or('\0') {
739 self.scan_digits(2, 10)
744 self.scan_digits(8, 10)
749 self.scan_digits(16, 16)
751 '0'..='9' | '_' | '.' | 'e' | 'E' => {
752 self.scan_digits(10, 10) + 1
756 return token::Integer(self.name_from(start_bpos));
759 } else if c.is_digit(10) {
760 self.scan_digits(10, 10) + 1
766 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
768 return token::Integer(Symbol::intern("0"));
771 // might be a float, but don't be greedy if this is actually an
772 // integer literal followed by field/method access or a range pattern
773 // (`0..2` and `12.foo()`)
774 if self.ch_is('.') && !self.nextch_is('.') &&
775 !ident_start(self.nextch()) {
776 // might have stuff after the ., and if it does, it needs to start
779 if self.ch.unwrap_or('\0').is_digit(10) {
780 self.scan_digits(10, 10);
781 self.scan_float_exponent();
784 self.check_float_base(start_bpos, pos, base);
786 token::Float(self.name_from(start_bpos))
788 // it might be a float if it has an exponent
789 if self.ch_is('e') || self.ch_is('E') {
790 self.scan_float_exponent();
792 self.check_float_base(start_bpos, pos, base);
793 return token::Float(self.name_from(start_bpos));
795 // but we certainly have an integer!
796 token::Integer(self.name_from(start_bpos))
800 /// Scan over a float exponent.
801 fn scan_float_exponent(&mut self) {
802 if self.ch_is('e') || self.ch_is('E') {
805 if self.ch_is('-') || self.ch_is('+') {
809 if self.scan_digits(10, 10) == 0 {
810 let mut err = self.struct_span_fatal(
811 self.pos, self.next_pos,
812 "expected at least one digit in exponent"
814 if let Some(ch) = self.ch {
815 // check for e.g., Unicode minus '−' (Issue #49746)
816 if unicode_chars::check_for_substitution(self, ch, &mut err) {
818 self.scan_digits(10, 10);
826 /// Checks that a base is valid for a floating literal, emitting a nice
827 /// error if it isn't.
828 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
831 self.err_span_(start_bpos,
833 "hexadecimal float literal is not supported")
836 self.err_span_(start_bpos,
838 "octal float literal is not supported")
841 self.err_span_(start_bpos,
843 "binary float literal is not supported")
849 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
859 /// Returns the next token from the string, advances the input past that
860 /// token, and updates the interner
861 fn next_token_inner(&mut self) -> Result<token::Token, ()> {
865 let (is_ident_start, is_raw_ident) =
866 match (c.unwrap(), self.nextch(), self.nextnextch()) {
867 // r# followed by an identifier starter is a raw identifier.
868 // This is an exception to the r# case below.
869 ('r', Some('#'), x) if ident_start(x) => (true, true),
870 // r as in r" or r#" is part of a raw string literal.
871 // b as in b' is part of a byte literal.
872 // They are not identifiers, and are handled further down.
873 ('r', Some('"'), _) |
874 ('r', Some('#'), _) |
875 ('b', Some('"'), _) |
876 ('b', Some('\''), _) |
877 ('b', Some('r'), Some('"')) |
878 ('b', Some('r'), Some('#')) => (false, false),
883 let raw_start = self.pos;
885 // Consume the 'r#' characters.
890 let start = self.pos;
893 while ident_continue(self.ch) {
897 return Ok(self.with_str_from(start, |string| {
898 // FIXME: perform NFKC normalization here. (Issue #2253)
899 let ident = self.mk_ident(string);
902 let span = self.mk_sp(raw_start, self.pos);
903 if !ident.can_be_raw() {
904 self.err_span(span, &format!("`{}` cannot be a raw identifier", ident));
906 self.sess.raw_identifier_spans.borrow_mut().push(span);
909 token::Ident(ident, is_raw_ident)
915 let num = self.scan_number(c.unwrap());
916 let suffix = self.scan_optional_raw_name();
917 debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
918 return Ok(token::Literal(num, suffix));
921 match c.expect("next_token_inner called at EOF") {
938 } else if self.ch_is('=') {
950 Ok(token::OpenDelim(token::Paren))
954 Ok(token::CloseDelim(token::Paren))
958 Ok(token::OpenDelim(token::Brace))
962 Ok(token::CloseDelim(token::Brace))
966 Ok(token::OpenDelim(token::Bracket))
970 Ok(token::CloseDelim(token::Bracket))
1003 // Multi-byte tokens.
1006 if self.ch_is('=') {
1009 } else if self.ch_is('>') {
1018 if self.ch_is('=') {
1027 match self.ch.unwrap_or('\x00') {
1033 Ok(self.binop(token::Shl))
1046 match self.ch.unwrap_or('\x00') {
1052 Ok(self.binop(token::Shr))
1060 // Either a character constant 'a' OR a lifetime name 'abc
1061 let start_with_quote = self.pos;
1063 let start = self.pos;
1065 // If the character is an ident start not followed by another single
1066 // quote, then this is a lifetime name:
1067 let starts_with_number = self.ch.unwrap_or('\x00').is_numeric();
1068 if (ident_start(self.ch) || starts_with_number) && !self.nextch_is('\'') {
1070 while ident_continue(self.ch) {
1073 // lifetimes shouldn't end with a single quote
1074 // if we find one, then this is an invalid character literal
1075 if self.ch_is('\'') {
1076 let id = self.name_from(start);
1078 self.validate_char_escape(start_with_quote);
1079 return Ok(token::Literal(token::Char(id), None))
1082 // Include the leading `'` in the real identifier, for macro
1083 // expansion purposes. See #12512 for the gory details of why
1084 // this is necessary.
1085 let ident = self.with_str_from(start_with_quote, |lifetime_name| {
1086 self.mk_ident(lifetime_name)
1089 if starts_with_number {
1090 // this is a recovered lifetime written `'1`, error but accept it
1094 "lifetimes cannot start with a number",
1098 return Ok(token::Lifetime(ident));
1100 let msg = "unterminated character literal";
1101 let id = self.scan_single_quoted_string(start_with_quote, msg);
1102 self.validate_char_escape(start_with_quote);
1103 let suffix = self.scan_optional_raw_name();
1104 Ok(token::Literal(token::Char(id), suffix))
1108 let lit = match self.ch {
1110 let start_with_quote = self.pos;
1112 let msg = "unterminated byte constant";
1113 let id = self.scan_single_quoted_string(start_with_quote, msg);
1114 self.validate_byte_escape(start_with_quote);
1118 let start_with_quote = self.pos;
1119 let msg = "unterminated double quote byte string";
1120 let id = self.scan_double_quoted_string(msg);
1121 self.validate_byte_str_escape(start_with_quote);
1124 Some('r') => self.scan_raw_byte_string(),
1125 _ => unreachable!(), // Should have been a token::Ident above.
1127 let suffix = self.scan_optional_raw_name();
1129 Ok(token::Literal(lit, suffix))
1132 let start_with_quote = self.pos;
1133 let msg = "unterminated double quote string";
1134 let id = self.scan_double_quoted_string(msg);
1135 self.validate_str_escape(start_with_quote);
1136 let suffix = self.scan_optional_raw_name();
1137 Ok(token::Literal(token::Str_(id), suffix))
1140 let start_bpos = self.pos;
1142 let mut hash_count: u16 = 0;
1143 while self.ch_is('#') {
1144 if hash_count == 65535 {
1145 let bpos = self.next_pos;
1146 self.fatal_span_(start_bpos,
1148 "too many `#` symbols: raw strings may be \
1149 delimited by up to 65535 `#` symbols").raise();
1156 self.fail_unterminated_raw_string(start_bpos, hash_count);
1157 } else if !self.ch_is('"') {
1158 let last_bpos = self.pos;
1159 let curr_char = self.ch.unwrap();
1160 self.fatal_span_char(start_bpos,
1162 "found invalid character; only `#` is allowed \
1163 in raw string delimitation",
1167 let content_start_bpos = self.pos;
1168 let mut content_end_bpos;
1169 let mut valid = true;
1172 self.fail_unterminated_raw_string(start_bpos, hash_count);
1174 // if self.ch_is('"') {
1175 // content_end_bpos = self.pos;
1176 // for _ in 0..hash_count {
1178 // if !self.ch_is('#') {
1180 let c = self.ch.unwrap();
1183 content_end_bpos = self.pos;
1184 for _ in 0..hash_count {
1186 if !self.ch_is('#') {
1193 if !self.nextch_is('\n') {
1194 let last_bpos = self.pos;
1195 self.err_span_(start_bpos,
1197 "bare CR not allowed in raw string, use \\r \
1209 self.name_from_to(content_start_bpos, content_end_bpos)
1211 Symbol::intern("??")
1213 let suffix = self.scan_optional_raw_name();
1215 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1218 if self.nextch_is('>') {
1223 Ok(self.binop(token::Minus))
1227 if self.nextch_is('&') {
1232 Ok(self.binop(token::And))
1236 match self.nextch() {
1243 Ok(self.binop(token::Or))
1248 Ok(self.binop(token::Plus))
1251 Ok(self.binop(token::Star))
1254 Ok(self.binop(token::Slash))
1257 Ok(self.binop(token::Caret))
1260 Ok(self.binop(token::Percent))
1263 let last_bpos = self.pos;
1264 let bpos = self.next_pos;
1265 let mut err = self.struct_fatal_span_char(last_bpos,
1267 "unknown start of token",
1269 unicode_chars::check_for_substitution(self, c, &mut err);
1270 self.fatal_errs.push(err);
1277 fn read_to_eol(&mut self) -> String {
1278 let mut val = String::new();
1279 while !self.ch_is('\n') && !self.is_eof() {
1280 val.push(self.ch.unwrap());
1284 if self.ch_is('\n') {
1291 fn read_one_line_comment(&mut self) -> String {
1292 let val = self.read_to_eol();
1293 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1294 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1298 fn consume_non_eol_whitespace(&mut self) {
1299 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1304 fn peeking_at_comment(&self) -> bool {
1305 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1306 // consider shebangs comments, but not inner attributes
1307 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1310 fn scan_single_quoted_string(&mut self,
1311 start_with_quote: BytePos,
1312 unterminated_msg: &str) -> ast::Name {
1313 // assumes that first `'` is consumed
1314 let start = self.pos;
1315 // lex `'''` as a single char, for recovery
1316 if self.ch_is('\'') && self.nextch_is('\'') {
1319 let mut first = true;
1321 if self.ch_is('\'') {
1324 if self.ch_is('\\') && (self.nextch_is('\'') || self.nextch_is('\\')) {
1328 // Only attempt to infer single line string literals. If we encounter
1329 // a slash, bail out in order to avoid nonsensical suggestion when
1330 // involving comments.
1332 || (self.ch_is('/') && !first)
1333 || (self.ch_is('\n') && !self.nextch_is('\'')) {
1335 self.fatal_span_(start_with_quote, self.pos, unterminated_msg.into())
1344 let id = self.name_from(start);
1349 fn scan_double_quoted_string(&mut self, unterminated_msg: &str) -> ast::Name {
1350 debug_assert!(self.ch_is('\"'));
1351 let start_with_quote = self.pos;
1353 let start = self.pos;
1354 while !self.ch_is('"') {
1357 self.fatal_span_(start_with_quote, pos, unterminated_msg).raise();
1359 if self.ch_is('\\') && (self.nextch_is('\\') || self.nextch_is('"')) {
1364 let id = self.name_from(start);
1369 fn scan_raw_byte_string(&mut self) -> token::Lit {
1370 let start_bpos = self.pos;
1372 let mut hash_count = 0;
1373 while self.ch_is('#') {
1374 if hash_count == 65535 {
1375 let bpos = self.next_pos;
1376 self.fatal_span_(start_bpos,
1378 "too many `#` symbols: raw byte strings may be \
1379 delimited by up to 65535 `#` symbols").raise();
1386 self.fail_unterminated_raw_string(start_bpos, hash_count);
1387 } else if !self.ch_is('"') {
1389 let ch = self.ch.unwrap();
1390 self.fatal_span_char(start_bpos,
1392 "found invalid character; only `#` is allowed in raw \
1393 string delimitation",
1397 let content_start_bpos = self.pos;
1398 let mut content_end_bpos;
1402 self.fail_unterminated_raw_string(start_bpos, hash_count);
1405 content_end_bpos = self.pos;
1406 for _ in 0..hash_count {
1408 if !self.ch_is('#') {
1417 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1426 token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), hash_count)
1429 fn validate_char_escape(&self, start_with_quote: BytePos) {
1430 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1431 if let Err((off, err)) = unescape::unescape_char(lit) {
1432 emit_unescape_error(
1433 &self.sess.span_diagnostic,
1435 self.mk_sp(start_with_quote, self.pos),
1436 unescape::Mode::Char,
1444 fn validate_byte_escape(&self, start_with_quote: BytePos) {
1445 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1446 if let Err((off, err)) = unescape::unescape_byte(lit) {
1447 emit_unescape_error(
1448 &self.sess.span_diagnostic,
1450 self.mk_sp(start_with_quote, self.pos),
1451 unescape::Mode::Byte,
1459 fn validate_str_escape(&self, start_with_quote: BytePos) {
1460 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1461 unescape::unescape_str(lit, &mut |range, c| {
1462 if let Err(err) = c {
1463 emit_unescape_error(
1464 &self.sess.span_diagnostic,
1466 self.mk_sp(start_with_quote, self.pos),
1467 unescape::Mode::Str,
1476 fn validate_byte_str_escape(&self, start_with_quote: BytePos) {
1477 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1478 unescape::unescape_byte_str(lit, &mut |range, c| {
1479 if let Err(err) = c {
1480 emit_unescape_error(
1481 &self.sess.span_diagnostic,
1483 self.mk_sp(start_with_quote, self.pos),
1484 unescape::Mode::ByteStr,
1494 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1495 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1497 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1498 c.map_or(false, Pattern_White_Space)
1502 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1503 c.map_or(false, |c| lo <= c && c <= hi)
1507 fn is_dec_digit(c: Option<char>) -> bool {
1508 in_range(c, '0', '9')
1511 fn is_doc_comment(s: &str) -> bool {
1512 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1513 s.starts_with("//!");
1514 debug!("is {:?} a doc comment? {}", s, res);
1518 fn is_block_doc_comment(s: &str) -> bool {
1519 // Prevent `/**/` from being parsed as a doc comment
1520 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1521 s.starts_with("/*!")) && s.len() >= 5;
1522 debug!("is {:?} a doc comment? {}", s, res);
1526 /// Determine whether `c` is a valid start for an ident.
1527 fn ident_start(c: Option<char>) -> bool {
1530 None => return false,
1533 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1536 fn ident_continue(c: Option<char>) -> bool {
1539 None => return false,
1542 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1543 (c > '\x7f' && c.is_xid_continue())
1547 fn char_at(s: &str, byte: usize) -> char {
1548 s[byte..].chars().next().unwrap()
1555 use crate::ast::{Ident, CrateConfig};
1556 use crate::symbol::Symbol;
1557 use crate::source_map::{SourceMap, FilePathMapping};
1558 use crate::feature_gate::UnstableFeatures;
1559 use crate::parse::token;
1560 use crate::diagnostics::plugin::ErrorMap;
1561 use crate::with_default_globals;
1563 use std::path::PathBuf;
1564 use syntax_pos::{BytePos, Span, NO_EXPANSION, edition::Edition};
1565 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
1566 use rustc_data_structures::sync::Lock;
1568 fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
1569 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1575 span_diagnostic: errors::Handler::with_emitter(true, None, Box::new(emitter)),
1576 unstable_features: UnstableFeatures::from_environment(),
1577 config: CrateConfig::default(),
1578 included_mod_stack: Lock::new(Vec::new()),
1580 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1581 raw_identifier_spans: Lock::new(Vec::new()),
1582 registered_diagnostics: Lock::new(ErrorMap::new()),
1583 buffered_lints: Lock::new(vec![]),
1584 edition: Edition::from_session(),
1585 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
1589 // open a string reader for the given string
1590 fn setup<'a>(sm: &SourceMap,
1591 sess: &'a ParseSess,
1593 -> StringReader<'a> {
1594 let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
1595 let mut sr = StringReader::new_raw(sess, sf, None);
1596 if sr.advance_token().is_err() {
1597 sr.emit_fatal_errors();
1605 with_default_globals(|| {
1606 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1607 let sh = mk_sess(sm.clone());
1608 let mut string_reader = setup(&sm,
1610 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1612 let id = Ident::from_str("fn");
1613 assert_eq!(string_reader.next_token().tok, token::Comment);
1614 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1615 let tok1 = string_reader.next_token();
1616 let tok2 = TokenAndSpan {
1617 tok: token::Ident(id, false),
1618 sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1620 assert_eq!(tok1.tok, tok2.tok);
1621 assert_eq!(tok1.sp, tok2.sp);
1622 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1623 // the 'main' id is already read:
1624 assert_eq!(string_reader.pos.clone(), BytePos(28));
1625 // read another token:
1626 let tok3 = string_reader.next_token();
1627 let tok4 = TokenAndSpan {
1628 tok: mk_ident("main"),
1629 sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1631 assert_eq!(tok3.tok, tok4.tok);
1632 assert_eq!(tok3.sp, tok4.sp);
1633 // the lparen is already read:
1634 assert_eq!(string_reader.pos.clone(), BytePos(29))
1638 // check that the given reader produces the desired stream
1639 // of tokens (stop checking after exhausting the expected vec)
1640 fn check_tokenization(mut string_reader: StringReader<'_>, expected: Vec<token::Token>) {
1641 for expected_tok in &expected {
1642 assert_eq!(&string_reader.next_token().tok, expected_tok);
1646 // make the identifier by looking up the string in the interner
1647 fn mk_ident(id: &str) -> token::Token {
1648 token::Token::from_ast_ident(Ident::from_str(id))
1652 fn doublecolonparsing() {
1653 with_default_globals(|| {
1654 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1655 let sh = mk_sess(sm.clone());
1656 check_tokenization(setup(&sm, &sh, "a b".to_string()),
1657 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1663 with_default_globals(|| {
1664 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1665 let sh = mk_sess(sm.clone());
1666 check_tokenization(setup(&sm, &sh, "a::b".to_string()),
1667 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1673 with_default_globals(|| {
1674 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1675 let sh = mk_sess(sm.clone());
1676 check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
1677 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
1683 with_default_globals(|| {
1684 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1685 let sh = mk_sess(sm.clone());
1686 check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
1687 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
1693 with_default_globals(|| {
1694 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1695 let sh = mk_sess(sm.clone());
1696 assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok,
1697 token::Literal(token::Char(Symbol::intern("a")), None));
1702 fn character_space() {
1703 with_default_globals(|| {
1704 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1705 let sh = mk_sess(sm.clone());
1706 assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok,
1707 token::Literal(token::Char(Symbol::intern(" ")), None));
1712 fn character_escaped() {
1713 with_default_globals(|| {
1714 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1715 let sh = mk_sess(sm.clone());
1716 assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok,
1717 token::Literal(token::Char(Symbol::intern("\\n")), None));
1722 fn lifetime_name() {
1723 with_default_globals(|| {
1724 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1725 let sh = mk_sess(sm.clone());
1726 assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok,
1727 token::Lifetime(Ident::from_str("'abc")));
1733 with_default_globals(|| {
1734 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1735 let sh = mk_sess(sm.clone());
1736 assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
1739 token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
1744 fn literal_suffixes() {
1745 with_default_globals(|| {
1746 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1747 let sh = mk_sess(sm.clone());
1749 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1750 assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token().tok,
1751 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
1752 Some(Symbol::intern("suffix"))));
1753 // with a whitespace separator:
1754 assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token().tok,
1755 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
1760 test!("'a'", Char, "a");
1761 test!("b'a'", Byte, "a");
1762 test!("\"a\"", Str_, "a");
1763 test!("b\"a\"", ByteStr, "a");
1764 test!("1234", Integer, "1234");
1765 test!("0b101", Integer, "0b101");
1766 test!("0xABC", Integer, "0xABC");
1767 test!("1.0", Float, "1.0");
1768 test!("1.0e10", Float, "1.0e10");
1770 assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token().tok,
1771 token::Literal(token::Integer(Symbol::intern("2")),
1772 Some(Symbol::intern("us"))));
1773 assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
1774 token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
1775 Some(Symbol::intern("suffix"))));
1776 assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
1777 token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
1778 Some(Symbol::intern("suffix"))));
1783 fn line_doc_comments() {
1784 assert!(is_doc_comment("///"));
1785 assert!(is_doc_comment("/// blah"));
1786 assert!(!is_doc_comment("////"));
1790 fn nested_block_comments() {
1791 with_default_globals(|| {
1792 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1793 let sh = mk_sess(sm.clone());
1794 let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
1795 match lexer.next_token().tok {
1796 token::Comment => {}
1797 _ => panic!("expected a comment!"),
1799 assert_eq!(lexer.next_token().tok,
1800 token::Literal(token::Char(Symbol::intern("a")), None));
1805 fn crlf_comments() {
1806 with_default_globals(|| {
1807 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1808 let sh = mk_sess(sm.clone());
1809 let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
1810 let comment = lexer.next_token();
1811 assert_eq!(comment.tok, token::Comment);
1812 assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
1813 assert_eq!(lexer.next_token().tok, token::Whitespace);
1814 assert_eq!(lexer.next_token().tok,
1815 token::DocComment(Symbol::intern("/// test")));