2 use crate::parse::ParseSess;
3 use crate::parse::token::{self, Token, TokenKind};
4 use crate::symbol::{sym, Symbol};
5 use crate::parse::unescape;
6 use crate::parse::unescape_error_reporting::{emit_unescape_error, push_escaped_char};
8 use errors::{FatalError, Diagnostic, DiagnosticBuilder};
9 use syntax_pos::{BytePos, Pos, Span, NO_EXPANSION};
10 use core::unicode::property::Pattern_White_Space;
15 use rustc_data_structures::sync::Lrc;
22 #[derive(Clone, Debug)]
23 pub struct UnmatchedBrace {
24 pub expected_delim: token::DelimToken,
25 pub found_delim: token::DelimToken,
27 pub unclosed_span: Option<Span>,
28 pub candidate_span: Option<Span>,
31 pub struct StringReader<'a> {
32 crate sess: &'a ParseSess,
33 /// The absolute offset within the source_map of the next character to read
34 crate next_pos: BytePos,
35 /// The absolute offset within the source_map of the current character
37 /// The current character (which has been read from self.pos)
38 crate ch: Option<char>,
39 crate source_file: Lrc<syntax_pos::SourceFile>,
40 /// Stop reading src at this index.
41 crate end_src_index: usize,
44 peek_span_src_raw: Span,
45 fatal_errs: Vec<DiagnosticBuilder<'a>>,
46 // cache a direct reference to the source text, so that we don't have to
47 // retrieve it via `self.source_file.src.as_ref().unwrap()` all the time.
49 override_span: Option<Span>,
52 impl<'a> StringReader<'a> {
53 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
54 self.mk_sp_and_raw(lo, hi).0
57 fn mk_sp_and_raw(&self, lo: BytePos, hi: BytePos) -> (Span, Span) {
58 let raw = Span::new(lo, hi, NO_EXPANSION);
59 let real = self.override_span.unwrap_or(raw);
64 fn unwrap_or_abort(&mut self, res: Result<Token, ()>) -> Token {
68 self.emit_fatal_errors();
74 fn next_token(&mut self) -> Token where Self: Sized {
75 let res = self.try_next_token();
76 self.unwrap_or_abort(res)
79 /// Returns the next token. EFFECT: advances the string_reader.
80 pub fn try_next_token(&mut self) -> Result<Token, ()> {
81 assert!(self.fatal_errs.is_empty());
82 let ret_val = self.peek_token.take();
83 self.advance_token()?;
87 /// Immutably extract string if found at current position with given delimiters
88 fn peek_delimited(&self, from_ch: char, to_ch: char) -> Option<String> {
89 let mut pos = self.pos;
90 let mut idx = self.src_index(pos);
91 let mut ch = char_at(&self.src, idx);
95 pos = pos + Pos::from_usize(ch.len_utf8());
97 idx = self.src_index(pos);
98 while idx < self.end_src_index {
99 ch = char_at(&self.src, idx);
101 return Some(self.src[self.src_index(start_pos)..self.src_index(pos)].to_string());
103 pos = pos + Pos::from_usize(ch.len_utf8());
104 idx = self.src_index(pos);
109 fn try_real_token(&mut self) -> Result<Token, ()> {
110 let mut t = self.try_next_token()?;
113 token::Whitespace | token::Comment | token::Shebang(_) => {
114 t = self.try_next_token()?;
123 pub fn real_token(&mut self) -> Token {
124 let res = self.try_real_token();
125 self.unwrap_or_abort(res)
129 fn is_eof(&self) -> bool {
133 fn fail_unterminated_raw_string(&self, pos: BytePos, hash_count: u16) -> ! {
134 let mut err = self.struct_span_fatal(pos, pos, "unterminated raw string");
135 err.span_label(self.mk_sp(pos, pos), "unterminated raw string");
138 err.note(&format!("this raw string should be terminated with `\"{}`",
139 "#".repeat(hash_count as usize)));
146 fn fatal(&self, m: &str) -> FatalError {
147 self.fatal_span(self.peek_token.span, m)
150 crate fn emit_fatal_errors(&mut self) {
151 for err in &mut self.fatal_errs {
155 self.fatal_errs.clear();
158 pub fn buffer_fatal_errors(&mut self) -> Vec<Diagnostic> {
159 let mut buffer = Vec::new();
161 for err in self.fatal_errs.drain(..) {
162 err.buffer(&mut buffer);
168 pub fn peek(&self) -> &Token {
172 /// For comments.rs, which hackily pokes into next_pos and ch
173 fn new_raw(sess: &'a ParseSess,
174 source_file: Lrc<syntax_pos::SourceFile>,
175 override_span: Option<Span>) -> Self {
176 let mut sr = StringReader::new_raw_internal(sess, source_file, override_span);
182 fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc<syntax_pos::SourceFile>,
183 override_span: Option<Span>) -> Self
185 if source_file.src.is_none() {
186 sess.span_diagnostic.bug(&format!("Cannot lex source_file without source: {}",
190 let src = (*source_file.src.as_ref().unwrap()).clone();
194 next_pos: source_file.start_pos,
195 pos: source_file.start_pos,
198 end_src_index: src.len(),
199 peek_token: Token::dummy(),
200 peek_span_src_raw: syntax_pos::DUMMY_SP,
202 fatal_errs: Vec::new(),
207 pub fn new_or_buffered_errs(sess: &'a ParseSess,
208 source_file: Lrc<syntax_pos::SourceFile>,
209 override_span: Option<Span>) -> Result<Self, Vec<Diagnostic>> {
210 let mut sr = StringReader::new_raw(sess, source_file, override_span);
211 if sr.advance_token().is_err() {
212 Err(sr.buffer_fatal_errors())
218 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
219 let begin = sess.source_map().lookup_byte_offset(span.lo());
220 let end = sess.source_map().lookup_byte_offset(span.hi());
222 // Make the range zero-length if the span is invalid.
223 if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
224 span = span.shrink_to_lo();
227 let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
229 // Seek the lexer to the right byte range.
230 sr.next_pos = span.lo();
231 sr.end_src_index = sr.src_index(span.hi());
235 if sr.advance_token().is_err() {
236 sr.emit_fatal_errors();
244 fn ch_is(&self, c: char) -> bool {
248 /// Report a fatal lexical error with a given span.
249 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
250 self.sess.span_diagnostic.span_fatal(sp, m)
253 /// Report a lexical error with a given span.
254 fn err_span(&self, sp: Span, m: &str) {
255 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
259 /// Report a fatal error spanning [`from_pos`, `to_pos`).
260 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
261 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
264 /// Report a lexical error spanning [`from_pos`, `to_pos`).
265 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
266 self.err_span(self.mk_sp(from_pos, to_pos), m)
269 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
270 /// escaped character to the error message
271 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
272 let mut m = m.to_string();
274 push_escaped_char(&mut m, c);
276 self.fatal_span_(from_pos, to_pos, &m[..])
279 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
280 -> DiagnosticBuilder<'a>
282 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
285 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
286 -> DiagnosticBuilder<'a>
288 let mut m = m.to_string();
290 push_escaped_char(&mut m, c);
292 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
295 /// Advance peek_token to refer to the next token, and
296 /// possibly update the interner.
297 fn advance_token(&mut self) -> Result<(), ()> {
298 match self.scan_whitespace_or_comment() {
300 self.peek_span_src_raw = comment.span;
301 self.peek_token = comment;
304 let (kind, start_pos, end_pos) = if self.is_eof() {
305 (token::Eof, self.source_file.end_pos, self.source_file.end_pos)
307 let start_pos = self.pos;
308 (self.next_token_inner()?, start_pos, self.pos)
310 let (real, raw) = self.mk_sp_and_raw(start_pos, end_pos);
311 self.peek_token = Token::new(kind, real);
312 self.peek_span_src_raw = raw;
320 fn src_index(&self, pos: BytePos) -> usize {
321 (pos - self.source_file.start_pos).to_usize()
324 /// Calls `f` with a string slice of the source text spanning from `start`
325 /// up to but excluding `self.pos`, meaning the slice does not include
326 /// the character `self.ch`.
327 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
328 where F: FnOnce(&str) -> T
330 self.with_str_from_to(start, self.pos, f)
333 /// Creates a Name from a given offset to the current offset.
334 fn name_from(&self, start: BytePos) -> ast::Name {
335 debug!("taking an ident from {:?} to {:?}", start, self.pos);
336 self.with_str_from(start, Symbol::intern)
339 /// As name_from, with an explicit endpoint.
340 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
341 debug!("taking an ident from {:?} to {:?}", start, end);
342 self.with_str_from_to(start, end, Symbol::intern)
345 /// Calls `f` with a string slice of the source text spanning from `start`
346 /// up to but excluding `end`.
347 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
348 where F: FnOnce(&str) -> T
350 f(&self.src[self.src_index(start)..self.src_index(end)])
353 /// Converts CRLF to LF in the given string, raising an error on bare CR.
354 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
355 let mut chars = s.char_indices().peekable();
356 while let Some((i, ch)) = chars.next() {
358 if let Some((lf_idx, '\n')) = chars.peek() {
359 return translate_crlf_(self, start, s, *lf_idx, chars, errmsg).into();
361 let pos = start + BytePos(i as u32);
362 let end_pos = start + BytePos((i + ch.len_utf8()) as u32);
363 self.err_span_(pos, end_pos, errmsg);
368 fn translate_crlf_(rdr: &StringReader<'_>,
372 mut chars: iter::Peekable<impl Iterator<Item = (usize, char)>>,
375 let mut buf = String::with_capacity(s.len());
377 buf.push_str(&s[.. j - 1]);
378 while let Some((i, ch)) = chars.next() {
381 buf.push_str(&s[j..i]);
383 let next = i + ch.len_utf8();
385 if chars.peek().map(|(_, ch)| *ch) != Some('\n') {
386 let pos = start + BytePos(i as u32);
387 let end_pos = start + BytePos(next as u32);
388 rdr.err_span_(pos, end_pos, errmsg);
393 buf.push_str(&s[j..]);
399 /// Advance the StringReader by one character.
400 crate fn bump(&mut self) {
401 let next_src_index = self.src_index(self.next_pos);
402 if next_src_index < self.end_src_index {
403 let next_ch = char_at(&self.src, next_src_index);
404 let next_ch_len = next_ch.len_utf8();
406 self.ch = Some(next_ch);
407 self.pos = self.next_pos;
408 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
411 self.pos = self.next_pos;
415 fn nextch(&self) -> Option<char> {
416 let next_src_index = self.src_index(self.next_pos);
417 if next_src_index < self.end_src_index {
418 Some(char_at(&self.src, next_src_index))
425 fn nextch_is(&self, c: char) -> bool {
426 self.nextch() == Some(c)
429 fn nextnextch(&self) -> Option<char> {
430 let next_src_index = self.src_index(self.next_pos);
431 if next_src_index < self.end_src_index {
432 let next_next_src_index =
433 next_src_index + char_at(&self.src, next_src_index).len_utf8();
434 if next_next_src_index < self.end_src_index {
435 return Some(char_at(&self.src, next_next_src_index));
442 fn nextnextch_is(&self, c: char) -> bool {
443 self.nextnextch() == Some(c)
446 /// Eats <XID_start><XID_continue>*, if possible.
447 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
448 if !ident_start(self.ch) {
452 let start = self.pos;
455 while ident_continue(self.ch) {
459 self.with_str_from(start, |string| {
461 self.sess.span_diagnostic
462 .struct_span_warn(self.mk_sp(start, self.pos),
463 "underscore literal suffix is not allowed")
464 .warn("this was previously accepted by the compiler but is \
465 being phased out; it will become a hard error in \
467 .note("for more information, see issue #42326 \
468 <https://github.com/rust-lang/rust/issues/42326>")
472 Some(Symbol::intern(string))
477 /// PRECONDITION: self.ch is not whitespace
478 /// Eats any kind of comment.
479 fn scan_comment(&mut self) -> Option<Token> {
480 if let Some(c) = self.ch {
481 if c.is_whitespace() {
482 let msg = "called consume_any_line_comment, but there was whitespace";
483 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
488 match self.nextch() {
493 // line comments starting with "///" or "//!" are doc-comments
494 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
495 let start_bpos = self.pos - BytePos(2);
497 while !self.is_eof() {
498 match self.ch.unwrap() {
501 if self.nextch_is('\n') {
504 } else if doc_comment {
505 self.err_span_(self.pos,
507 "bare CR not allowed in doc-comment");
515 let kind = if doc_comment {
516 self.with_str_from(start_bpos, |string| {
517 token::DocComment(Symbol::intern(string))
522 Some(Token::new(kind, self.mk_sp(start_bpos, self.pos)))
527 self.scan_block_comment()
531 } else if self.ch_is('#') {
532 if self.nextch_is('!') {
534 // Parse an inner attribute.
535 if self.nextnextch_is('[') {
539 let is_beginning_of_file = self.pos == self.source_file.start_pos;
540 if is_beginning_of_file {
541 debug!("Skipping a shebang");
542 let start = self.pos;
543 while !self.ch_is('\n') && !self.is_eof() {
546 return Some(Token::new(
547 token::Shebang(self.name_from(start)),
548 self.mk_sp(start, self.pos),
558 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
560 fn scan_whitespace_or_comment(&mut self) -> Option<Token> {
561 match self.ch.unwrap_or('\0') {
562 // # to handle shebang at start of file -- this is the entry point
563 // for skipping over all "junk"
565 let c = self.scan_comment();
566 debug!("scanning a comment {:?}", c);
569 c if is_pattern_whitespace(Some(c)) => {
570 let start_bpos = self.pos;
571 while is_pattern_whitespace(self.ch) {
574 let c = Some(Token::new(token::Whitespace, self.mk_sp(start_bpos, self.pos)));
575 debug!("scanning whitespace: {:?}", c);
582 /// Might return a sugared-doc-attr
583 fn scan_block_comment(&mut self) -> Option<Token> {
584 // block comments starting with "/**" or "/*!" are doc-comments
585 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
586 let start_bpos = self.pos - BytePos(2);
588 let mut level: isize = 1;
589 let mut has_cr = false;
592 let msg = if is_doc_comment {
593 "unterminated block doc-comment"
595 "unterminated block comment"
597 let last_bpos = self.pos;
598 self.fatal_span_(start_bpos, last_bpos, msg).raise();
600 let n = self.ch.unwrap();
602 '/' if self.nextch_is('*') => {
606 '*' if self.nextch_is('/') => {
618 self.with_str_from(start_bpos, |string| {
619 // but comments with only "*"s between two "/"s are not
620 let kind = if is_block_doc_comment(string) {
621 let string = if has_cr {
622 self.translate_crlf(start_bpos,
624 "bare CR not allowed in block doc-comment")
628 token::DocComment(Symbol::intern(&string[..]))
633 Some(Token::new(kind, self.mk_sp(start_bpos, self.pos)))
637 /// Scan through any digits (base `scan_radix`) or underscores,
638 /// and return how many digits there were.
640 /// `real_radix` represents the true radix of the number we're
641 /// interested in, and errors will be emitted for any digits
642 /// between `real_radix` and `scan_radix`.
643 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
644 assert!(real_radix <= scan_radix);
650 debug!("skipping a _");
654 match c.and_then(|cc| cc.to_digit(scan_radix)) {
656 debug!("{:?} in scan_digits", c);
657 // check that the hypothetical digit is actually
658 // in range for the true radix
659 if c.unwrap().to_digit(real_radix).is_none() {
660 self.err_span_(self.pos,
662 &format!("invalid digit for a base {} literal", real_radix));
672 /// Lex a LIT_INTEGER or a LIT_FLOAT
673 fn scan_number(&mut self, c: char) -> (token::LitKind, Symbol) {
675 let start_bpos = self.pos;
678 let num_digits = if c == '0' {
679 match self.ch.unwrap_or('\0') {
683 self.scan_digits(2, 10)
688 self.scan_digits(8, 10)
693 self.scan_digits(16, 16)
695 '0'..='9' | '_' | '.' | 'e' | 'E' => {
696 self.scan_digits(10, 10) + 1
700 return (token::Integer, sym::integer(0));
703 } else if c.is_digit(10) {
704 self.scan_digits(10, 10) + 1
710 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
712 return (token::Integer, Symbol::intern("0"));
715 // might be a float, but don't be greedy if this is actually an
716 // integer literal followed by field/method access or a range pattern
717 // (`0..2` and `12.foo()`)
718 if self.ch_is('.') && !self.nextch_is('.') &&
719 !ident_start(self.nextch()) {
720 // might have stuff after the ., and if it does, it needs to start
723 if self.ch.unwrap_or('\0').is_digit(10) {
724 self.scan_digits(10, 10);
725 self.scan_float_exponent();
728 self.check_float_base(start_bpos, pos, base);
730 (token::Float, self.name_from(start_bpos))
732 // it might be a float if it has an exponent
733 if self.ch_is('e') || self.ch_is('E') {
734 self.scan_float_exponent();
736 self.check_float_base(start_bpos, pos, base);
737 return (token::Float, self.name_from(start_bpos));
739 // but we certainly have an integer!
740 (token::Integer, self.name_from(start_bpos))
744 /// Scan over a float exponent.
745 fn scan_float_exponent(&mut self) {
746 if self.ch_is('e') || self.ch_is('E') {
749 if self.ch_is('-') || self.ch_is('+') {
753 if self.scan_digits(10, 10) == 0 {
754 let mut err = self.struct_span_fatal(
755 self.pos, self.next_pos,
756 "expected at least one digit in exponent"
758 if let Some(ch) = self.ch {
759 // check for e.g., Unicode minus '−' (Issue #49746)
760 if unicode_chars::check_for_substitution(self, ch, &mut err) {
762 self.scan_digits(10, 10);
770 /// Checks that a base is valid for a floating literal, emitting a nice
771 /// error if it isn't.
772 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
775 self.err_span_(start_bpos,
777 "hexadecimal float literal is not supported")
780 self.err_span_(start_bpos,
782 "octal float literal is not supported")
785 self.err_span_(start_bpos,
787 "binary float literal is not supported")
793 fn binop(&mut self, op: token::BinOpToken) -> TokenKind {
803 /// Returns the next token from the string, advances the input past that
804 /// token, and updates the interner
805 fn next_token_inner(&mut self) -> Result<TokenKind, ()> {
809 let (is_ident_start, is_raw_ident) =
810 match (c.unwrap(), self.nextch(), self.nextnextch()) {
811 // r# followed by an identifier starter is a raw identifier.
812 // This is an exception to the r# case below.
813 ('r', Some('#'), x) if ident_start(x) => (true, true),
814 // r as in r" or r#" is part of a raw string literal.
815 // b as in b' is part of a byte literal.
816 // They are not identifiers, and are handled further down.
817 ('r', Some('"'), _) |
818 ('r', Some('#'), _) |
819 ('b', Some('"'), _) |
820 ('b', Some('\''), _) |
821 ('b', Some('r'), Some('"')) |
822 ('b', Some('r'), Some('#')) => (false, false),
827 let raw_start = self.pos;
829 // Consume the 'r#' characters.
834 let start = self.pos;
837 while ident_continue(self.ch) {
841 return Ok(self.with_str_from(start, |string| {
842 // FIXME: perform NFKC normalization here. (Issue #2253)
843 let name = ast::Name::intern(string);
846 let span = self.mk_sp(raw_start, self.pos);
847 if !name.can_be_raw() {
848 self.err_span(span, &format!("`{}` cannot be a raw identifier", name));
850 self.sess.raw_identifier_spans.borrow_mut().push(span);
853 token::Ident(name, is_raw_ident)
859 let (kind, symbol) = self.scan_number(c.unwrap());
860 let suffix = self.scan_optional_raw_name();
861 debug!("next_token_inner: scanned number {:?}, {:?}, {:?}", kind, symbol, suffix);
862 return Ok(TokenKind::lit(kind, symbol, suffix));
865 match c.expect("next_token_inner called at EOF") {
882 } else if self.ch_is('=') {
894 Ok(token::OpenDelim(token::Paren))
898 Ok(token::CloseDelim(token::Paren))
902 Ok(token::OpenDelim(token::Brace))
906 Ok(token::CloseDelim(token::Brace))
910 Ok(token::OpenDelim(token::Bracket))
914 Ok(token::CloseDelim(token::Bracket))
947 // Multi-byte tokens.
953 } else if self.ch_is('>') {
971 match self.ch.unwrap_or('\x00') {
977 Ok(self.binop(token::Shl))
990 match self.ch.unwrap_or('\x00') {
996 Ok(self.binop(token::Shr))
1004 // Either a character constant 'a' OR a lifetime name 'abc
1005 let start_with_quote = self.pos;
1007 let start = self.pos;
1009 // If the character is an ident start not followed by another single
1010 // quote, then this is a lifetime name:
1011 let starts_with_number = self.ch.unwrap_or('\x00').is_numeric();
1012 if (ident_start(self.ch) || starts_with_number) && !self.nextch_is('\'') {
1014 while ident_continue(self.ch) {
1017 // lifetimes shouldn't end with a single quote
1018 // if we find one, then this is an invalid character literal
1019 if self.ch_is('\'') {
1020 let symbol = self.name_from(start);
1022 self.validate_char_escape(start_with_quote);
1023 return Ok(TokenKind::lit(token::Char, symbol, None));
1026 if starts_with_number {
1027 // this is a recovered lifetime written `'1`, error but accept it
1031 "lifetimes cannot start with a number",
1035 // Include the leading `'` in the real identifier, for macro
1036 // expansion purposes. See #12512 for the gory details of why
1037 // this is necessary.
1038 return Ok(token::Lifetime(self.name_from(start_with_quote)));
1040 let msg = "unterminated character literal";
1041 let symbol = self.scan_single_quoted_string(start_with_quote, msg);
1042 self.validate_char_escape(start_with_quote);
1043 let suffix = self.scan_optional_raw_name();
1044 Ok(TokenKind::lit(token::Char, symbol, suffix))
1048 let (kind, symbol) = match self.ch {
1050 let start_with_quote = self.pos;
1052 let msg = "unterminated byte constant";
1053 let symbol = self.scan_single_quoted_string(start_with_quote, msg);
1054 self.validate_byte_escape(start_with_quote);
1055 (token::Byte, symbol)
1058 let start_with_quote = self.pos;
1059 let msg = "unterminated double quote byte string";
1060 let symbol = self.scan_double_quoted_string(msg);
1061 self.validate_byte_str_escape(start_with_quote);
1062 (token::ByteStr, symbol)
1065 let (start, end, hash_count) = self.scan_raw_string();
1066 let symbol = self.name_from_to(start, end);
1067 self.validate_raw_byte_str_escape(start, end);
1069 (token::ByteStrRaw(hash_count), symbol)
1071 _ => unreachable!(), // Should have been a token::Ident above.
1073 let suffix = self.scan_optional_raw_name();
1075 Ok(TokenKind::lit(kind, symbol, suffix))
1078 let start_with_quote = self.pos;
1079 let msg = "unterminated double quote string";
1080 let symbol = self.scan_double_quoted_string(msg);
1081 self.validate_str_escape(start_with_quote);
1082 let suffix = self.scan_optional_raw_name();
1083 Ok(TokenKind::lit(token::Str, symbol, suffix))
1086 let (start, end, hash_count) = self.scan_raw_string();
1087 let symbol = self.name_from_to(start, end);
1088 self.validate_raw_str_escape(start, end);
1089 let suffix = self.scan_optional_raw_name();
1091 Ok(TokenKind::lit(token::StrRaw(hash_count), symbol, suffix))
1094 if self.nextch_is('>') {
1099 Ok(self.binop(token::Minus))
1103 if self.nextch_is('&') {
1108 Ok(self.binop(token::And))
1112 match self.nextch() {
1119 Ok(self.binop(token::Or))
1124 Ok(self.binop(token::Plus))
1127 Ok(self.binop(token::Star))
1130 Ok(self.binop(token::Slash))
1133 Ok(self.binop(token::Caret))
1136 Ok(self.binop(token::Percent))
1139 let last_bpos = self.pos;
1140 let bpos = self.next_pos;
1141 let mut err = self.struct_fatal_span_char(last_bpos,
1143 "unknown start of token",
1145 unicode_chars::check_for_substitution(self, c, &mut err);
1146 self.fatal_errs.push(err);
1153 fn read_to_eol(&mut self) -> String {
1154 let mut val = String::new();
1155 while !self.ch_is('\n') && !self.is_eof() {
1156 val.push(self.ch.unwrap());
1160 if self.ch_is('\n') {
1167 fn read_one_line_comment(&mut self) -> String {
1168 let val = self.read_to_eol();
1169 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1170 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1174 fn consume_non_eol_whitespace(&mut self) {
1175 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1180 fn peeking_at_comment(&self) -> bool {
1181 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1182 // consider shebangs comments, but not inner attributes
1183 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1186 fn scan_single_quoted_string(&mut self,
1187 start_with_quote: BytePos,
1188 unterminated_msg: &str) -> ast::Name {
1189 // assumes that first `'` is consumed
1190 let start = self.pos;
1191 // lex `'''` as a single char, for recovery
1192 if self.ch_is('\'') && self.nextch_is('\'') {
1195 let mut first = true;
1197 if self.ch_is('\'') {
1200 if self.ch_is('\\') && (self.nextch_is('\'') || self.nextch_is('\\')) {
1204 // Only attempt to infer single line string literals. If we encounter
1205 // a slash, bail out in order to avoid nonsensical suggestion when
1206 // involving comments.
1208 || (self.ch_is('/') && !first)
1209 || (self.ch_is('\n') && !self.nextch_is('\'')) {
1211 self.fatal_span_(start_with_quote, self.pos, unterminated_msg.into())
1220 let id = self.name_from(start);
1225 fn scan_double_quoted_string(&mut self, unterminated_msg: &str) -> ast::Name {
1226 debug_assert!(self.ch_is('\"'));
1227 let start_with_quote = self.pos;
1229 let start = self.pos;
1230 while !self.ch_is('"') {
1233 self.fatal_span_(start_with_quote, pos, unterminated_msg).raise();
1235 if self.ch_is('\\') && (self.nextch_is('\\') || self.nextch_is('"')) {
1240 let id = self.name_from(start);
1245 /// Scans a raw (byte) string, returning byte position range for `"<literal>"`
1246 /// (including quotes) along with `#` character count in `(b)r##..."<literal>"##...`;
1247 fn scan_raw_string(&mut self) -> (BytePos, BytePos, u16) {
1248 let start_bpos = self.pos;
1250 let mut hash_count: u16 = 0;
1251 while self.ch_is('#') {
1252 if hash_count == 65535 {
1253 let bpos = self.next_pos;
1254 self.fatal_span_(start_bpos,
1256 "too many `#` symbols: raw strings may be \
1257 delimited by up to 65535 `#` symbols").raise();
1264 self.fail_unterminated_raw_string(start_bpos, hash_count);
1265 } else if !self.ch_is('"') {
1266 let last_bpos = self.pos;
1267 let curr_char = self.ch.unwrap();
1268 self.fatal_span_char(start_bpos,
1270 "found invalid character; only `#` is allowed \
1271 in raw string delimitation",
1275 let content_start_bpos = self.pos;
1276 let mut content_end_bpos;
1280 self.fail_unterminated_raw_string(start_bpos, hash_count);
1283 content_end_bpos = self.pos;
1284 for _ in 0..hash_count {
1286 if !self.ch_is('#') {
1299 (content_start_bpos, content_end_bpos, hash_count)
1302 fn validate_char_escape(&self, start_with_quote: BytePos) {
1303 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1304 if let Err((off, err)) = unescape::unescape_char(lit) {
1305 emit_unescape_error(
1306 &self.sess.span_diagnostic,
1308 self.mk_sp(start_with_quote, self.pos),
1309 unescape::Mode::Char,
1317 fn validate_byte_escape(&self, start_with_quote: BytePos) {
1318 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1319 if let Err((off, err)) = unescape::unescape_byte(lit) {
1320 emit_unescape_error(
1321 &self.sess.span_diagnostic,
1323 self.mk_sp(start_with_quote, self.pos),
1324 unescape::Mode::Byte,
1332 fn validate_str_escape(&self, start_with_quote: BytePos) {
1333 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1334 unescape::unescape_str(lit, &mut |range, c| {
1335 if let Err(err) = c {
1336 emit_unescape_error(
1337 &self.sess.span_diagnostic,
1339 self.mk_sp(start_with_quote, self.pos),
1340 unescape::Mode::Str,
1349 fn validate_raw_str_escape(&self, content_start: BytePos, content_end: BytePos) {
1350 self.with_str_from_to(content_start, content_end, |lit: &str| {
1351 unescape::unescape_raw_str(lit, unescape::Mode::Str, &mut |range, c| {
1352 if let Err(err) = c {
1353 emit_unescape_error(
1354 &self.sess.span_diagnostic,
1356 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
1357 unescape::Mode::Str,
1366 fn validate_raw_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) {
1367 self.with_str_from_to(content_start, content_end, |lit: &str| {
1368 unescape::unescape_raw_str(lit, unescape::Mode::ByteStr, &mut |range, c| {
1369 if let Err(err) = c {
1370 emit_unescape_error(
1371 &self.sess.span_diagnostic,
1373 self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)),
1374 unescape::Mode::ByteStr,
1383 fn validate_byte_str_escape(&self, start_with_quote: BytePos) {
1384 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1385 unescape::unescape_byte_str(lit, &mut |range, c| {
1386 if let Err(err) = c {
1387 emit_unescape_error(
1388 &self.sess.span_diagnostic,
1390 self.mk_sp(start_with_quote, self.pos),
1391 unescape::Mode::ByteStr,
1401 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1402 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1404 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1405 c.map_or(false, Pattern_White_Space)
1409 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1410 c.map_or(false, |c| lo <= c && c <= hi)
1414 fn is_dec_digit(c: Option<char>) -> bool {
1415 in_range(c, '0', '9')
1418 fn is_doc_comment(s: &str) -> bool {
1419 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1420 s.starts_with("//!");
1421 debug!("is {:?} a doc comment? {}", s, res);
1425 fn is_block_doc_comment(s: &str) -> bool {
1426 // Prevent `/**/` from being parsed as a doc comment
1427 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1428 s.starts_with("/*!")) && s.len() >= 5;
1429 debug!("is {:?} a doc comment? {}", s, res);
1433 /// Determine whether `c` is a valid start for an ident.
1434 fn ident_start(c: Option<char>) -> bool {
1437 None => return false,
1440 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1443 fn ident_continue(c: Option<char>) -> bool {
1446 None => return false,
1449 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1450 (c > '\x7f' && c.is_xid_continue())
1454 fn char_at(s: &str, byte: usize) -> char {
1455 s[byte..].chars().next().unwrap()
1462 use crate::ast::{Ident, CrateConfig};
1463 use crate::symbol::Symbol;
1464 use crate::source_map::{SourceMap, FilePathMapping};
1465 use crate::feature_gate::UnstableFeatures;
1466 use crate::parse::token;
1467 use crate::diagnostics::plugin::ErrorMap;
1468 use crate::with_default_globals;
1470 use std::path::PathBuf;
1471 use syntax_pos::{BytePos, Span, NO_EXPANSION, edition::Edition};
1472 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
1473 use rustc_data_structures::sync::Lock;
1475 fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
1476 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1482 span_diagnostic: errors::Handler::with_emitter(true, None, Box::new(emitter)),
1483 unstable_features: UnstableFeatures::from_environment(),
1484 config: CrateConfig::default(),
1485 included_mod_stack: Lock::new(Vec::new()),
1487 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1488 raw_identifier_spans: Lock::new(Vec::new()),
1489 registered_diagnostics: Lock::new(ErrorMap::new()),
1490 buffered_lints: Lock::new(vec![]),
1491 edition: Edition::from_session(),
1492 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
1496 // open a string reader for the given string
1497 fn setup<'a>(sm: &SourceMap,
1498 sess: &'a ParseSess,
1500 -> StringReader<'a> {
1501 let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
1502 let mut sr = StringReader::new_raw(sess, sf, None);
1503 if sr.advance_token().is_err() {
1504 sr.emit_fatal_errors();
1512 with_default_globals(|| {
1513 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1514 let sh = mk_sess(sm.clone());
1515 let mut string_reader = setup(&sm,
1517 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1519 assert_eq!(string_reader.next_token(), token::Comment);
1520 assert_eq!(string_reader.next_token(), token::Whitespace);
1521 let tok1 = string_reader.next_token();
1522 let tok2 = Token::new(
1523 token::Ident(Symbol::intern("fn"), false),
1524 Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1526 assert_eq!(tok1.kind, tok2.kind);
1527 assert_eq!(tok1.span, tok2.span);
1528 assert_eq!(string_reader.next_token(), token::Whitespace);
1529 // the 'main' id is already read:
1530 assert_eq!(string_reader.pos.clone(), BytePos(28));
1531 // read another token:
1532 let tok3 = string_reader.next_token();
1533 let tok4 = Token::new(
1535 Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1537 assert_eq!(tok3.kind, tok4.kind);
1538 assert_eq!(tok3.span, tok4.span);
1539 // the lparen is already read:
1540 assert_eq!(string_reader.pos.clone(), BytePos(29))
1544 // check that the given reader produces the desired stream
1545 // of tokens (stop checking after exhausting the expected vec)
1546 fn check_tokenization(mut string_reader: StringReader<'_>, expected: Vec<TokenKind>) {
1547 for expected_tok in &expected {
1548 assert_eq!(&string_reader.next_token(), expected_tok);
1552 // make the identifier by looking up the string in the interner
1553 fn mk_ident(id: &str) -> TokenKind {
1554 TokenKind::from_ast_ident(Ident::from_str(id))
1557 fn mk_lit(kind: token::LitKind, symbol: &str, suffix: Option<&str>) -> TokenKind {
1558 TokenKind::lit(kind, Symbol::intern(symbol), suffix.map(Symbol::intern))
1562 fn doublecolonparsing() {
1563 with_default_globals(|| {
1564 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1565 let sh = mk_sess(sm.clone());
1566 check_tokenization(setup(&sm, &sh, "a b".to_string()),
1567 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1573 with_default_globals(|| {
1574 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1575 let sh = mk_sess(sm.clone());
1576 check_tokenization(setup(&sm, &sh, "a::b".to_string()),
1577 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1583 with_default_globals(|| {
1584 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1585 let sh = mk_sess(sm.clone());
1586 check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
1587 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
1593 with_default_globals(|| {
1594 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1595 let sh = mk_sess(sm.clone());
1596 check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
1597 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
1603 with_default_globals(|| {
1604 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1605 let sh = mk_sess(sm.clone());
1606 assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token(),
1607 mk_lit(token::Char, "a", None));
1612 fn character_space() {
1613 with_default_globals(|| {
1614 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1615 let sh = mk_sess(sm.clone());
1616 assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token(),
1617 mk_lit(token::Char, " ", None));
1622 fn character_escaped() {
1623 with_default_globals(|| {
1624 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1625 let sh = mk_sess(sm.clone());
1626 assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token(),
1627 mk_lit(token::Char, "\\n", None));
1632 fn lifetime_name() {
1633 with_default_globals(|| {
1634 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1635 let sh = mk_sess(sm.clone());
1636 assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token(),
1637 token::Lifetime(Symbol::intern("'abc")));
1643 with_default_globals(|| {
1644 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1645 let sh = mk_sess(sm.clone());
1646 assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string()).next_token(),
1647 mk_lit(token::StrRaw(3), "\"#a\\b\x00c\"", None));
1652 fn literal_suffixes() {
1653 with_default_globals(|| {
1654 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1655 let sh = mk_sess(sm.clone());
1657 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1658 assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token(),
1659 mk_lit(token::$tok_type, $tok_contents, Some("suffix")));
1660 // with a whitespace separator:
1661 assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token(),
1662 mk_lit(token::$tok_type, $tok_contents, None));
1666 test!("'a'", Char, "a");
1667 test!("b'a'", Byte, "a");
1668 test!("\"a\"", Str, "a");
1669 test!("b\"a\"", ByteStr, "a");
1670 test!("1234", Integer, "1234");
1671 test!("0b101", Integer, "0b101");
1672 test!("0xABC", Integer, "0xABC");
1673 test!("1.0", Float, "1.0");
1674 test!("1.0e10", Float, "1.0e10");
1676 assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token(),
1677 mk_lit(token::Integer, "2", Some("us")));
1678 assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token(),
1679 mk_lit(token::StrRaw(3), "raw", Some("suffix")));
1680 assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token(),
1681 mk_lit(token::ByteStrRaw(3), "raw", Some("suffix")));
1686 fn line_doc_comments() {
1687 assert!(is_doc_comment("///"));
1688 assert!(is_doc_comment("/// blah"));
1689 assert!(!is_doc_comment("////"));
1693 fn nested_block_comments() {
1694 with_default_globals(|| {
1695 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1696 let sh = mk_sess(sm.clone());
1697 let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
1698 assert_eq!(lexer.next_token(), token::Comment);
1699 assert_eq!(lexer.next_token(), mk_lit(token::Char, "a", None));
1704 fn crlf_comments() {
1705 with_default_globals(|| {
1706 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1707 let sh = mk_sess(sm.clone());
1708 let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
1709 let comment = lexer.next_token();
1710 assert_eq!(comment.kind, token::Comment);
1711 assert_eq!((comment.span.lo(), comment.span.hi()), (BytePos(0), BytePos(7)));
1712 assert_eq!(lexer.next_token(), token::Whitespace);
1713 assert_eq!(lexer.next_token(), token::DocComment(Symbol::intern("/// test")));