1 use crate::ast::{self, Ident};
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 std::mem::replace;
16 use rustc_data_structures::sync::Lrc;
23 #[derive(Clone, Debug)]
24 pub struct UnmatchedBrace {
25 pub expected_delim: token::DelimToken,
26 pub found_delim: token::DelimToken,
28 pub unclosed_span: Option<Span>,
29 pub candidate_span: Option<Span>,
32 pub struct StringReader<'a> {
33 crate sess: &'a ParseSess,
34 /// The absolute offset within the source_map of the next character to read
35 crate next_pos: BytePos,
36 /// The absolute offset within the source_map of the current character
38 /// The current character (which has been read from self.pos)
39 crate ch: Option<char>,
40 crate source_file: Lrc<syntax_pos::SourceFile>,
41 /// Stop reading src at this index.
42 crate end_src_index: usize,
46 peek_span_src_raw: Span,
47 fatal_errs: Vec<DiagnosticBuilder<'a>>,
48 // cache a direct reference to the source text, so that we don't have to
49 // retrieve it via `self.source_file.src.as_ref().unwrap()` all the time.
51 override_span: Option<Span>,
54 impl<'a> StringReader<'a> {
55 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
56 self.mk_sp_and_raw(lo, hi).0
59 fn mk_sp_and_raw(&self, lo: BytePos, hi: BytePos) -> (Span, Span) {
60 let raw = Span::new(lo, hi, NO_EXPANSION);
61 let real = self.override_span.unwrap_or(raw);
66 fn mk_ident(&self, string: &str) -> Ident {
67 let mut ident = Ident::from_str(string);
68 if let Some(span) = self.override_span {
75 fn unwrap_or_abort(&mut self, res: Result<Token, ()>) -> Token {
79 self.emit_fatal_errors();
85 fn next_token(&mut self) -> Token where Self: Sized {
86 let res = self.try_next_token();
87 self.unwrap_or_abort(res)
90 /// Returns the next token. EFFECT: advances the string_reader.
91 pub fn try_next_token(&mut self) -> Result<Token, ()> {
92 assert!(self.fatal_errs.is_empty());
94 kind: replace(&mut self.peek_tok, token::Whitespace),
97 self.advance_token()?;
101 /// Immutably extract string if found at current position with given delimiters
102 fn peek_delimited(&self, from_ch: char, to_ch: char) -> Option<String> {
103 let mut pos = self.pos;
104 let mut idx = self.src_index(pos);
105 let mut ch = char_at(&self.src, idx);
109 pos = pos + Pos::from_usize(ch.len_utf8());
111 idx = self.src_index(pos);
112 while idx < self.end_src_index {
113 ch = char_at(&self.src, idx);
115 return Some(self.src[self.src_index(start_pos)..self.src_index(pos)].to_string());
117 pos = pos + Pos::from_usize(ch.len_utf8());
118 idx = self.src_index(pos);
123 fn try_real_token(&mut self) -> Result<Token, ()> {
124 let mut t = self.try_next_token()?;
127 token::Whitespace | token::Comment | token::Shebang(_) => {
128 t = self.try_next_token()?;
137 pub fn real_token(&mut self) -> Token {
138 let res = self.try_real_token();
139 self.unwrap_or_abort(res)
143 fn is_eof(&self) -> bool {
147 fn fail_unterminated_raw_string(&self, pos: BytePos, hash_count: u16) {
148 let mut err = self.struct_span_fatal(pos, pos, "unterminated raw string");
149 err.span_label(self.mk_sp(pos, pos), "unterminated raw string");
152 err.note(&format!("this raw string should be terminated with `\"{}`",
153 "#".repeat(hash_count as usize)));
160 fn fatal(&self, m: &str) -> FatalError {
161 self.fatal_span(self.peek_span, m)
164 crate fn emit_fatal_errors(&mut self) {
165 for err in &mut self.fatal_errs {
169 self.fatal_errs.clear();
172 pub fn buffer_fatal_errors(&mut self) -> Vec<Diagnostic> {
173 let mut buffer = Vec::new();
175 for err in self.fatal_errs.drain(..) {
176 err.buffer(&mut buffer);
182 pub fn peek(&self) -> Token {
183 // FIXME(pcwalton): Bad copy!
185 kind: self.peek_tok.clone(),
186 span: self.peek_span,
190 /// For comments.rs, which hackily pokes into next_pos and ch
191 fn new_raw(sess: &'a ParseSess,
192 source_file: Lrc<syntax_pos::SourceFile>,
193 override_span: Option<Span>) -> Self {
194 let mut sr = StringReader::new_raw_internal(sess, source_file, override_span);
200 fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc<syntax_pos::SourceFile>,
201 override_span: Option<Span>) -> Self
203 if source_file.src.is_none() {
204 sess.span_diagnostic.bug(&format!("Cannot lex source_file without source: {}",
208 let src = (*source_file.src.as_ref().unwrap()).clone();
212 next_pos: source_file.start_pos,
213 pos: source_file.start_pos,
216 end_src_index: src.len(),
217 // dummy values; not read
218 peek_tok: token::Eof,
219 peek_span: syntax_pos::DUMMY_SP,
220 peek_span_src_raw: syntax_pos::DUMMY_SP,
222 fatal_errs: Vec::new(),
227 pub fn new_or_buffered_errs(sess: &'a ParseSess,
228 source_file: Lrc<syntax_pos::SourceFile>,
229 override_span: Option<Span>) -> Result<Self, Vec<Diagnostic>> {
230 let mut sr = StringReader::new_raw(sess, source_file, override_span);
231 if sr.advance_token().is_err() {
232 Err(sr.buffer_fatal_errors())
238 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
239 let begin = sess.source_map().lookup_byte_offset(span.lo());
240 let end = sess.source_map().lookup_byte_offset(span.hi());
242 // Make the range zero-length if the span is invalid.
243 if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
244 span = span.shrink_to_lo();
247 let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
249 // Seek the lexer to the right byte range.
250 sr.next_pos = span.lo();
251 sr.end_src_index = sr.src_index(span.hi());
255 if sr.advance_token().is_err() {
256 sr.emit_fatal_errors();
264 fn ch_is(&self, c: char) -> bool {
268 /// Report a fatal lexical error with a given span.
269 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
270 self.sess.span_diagnostic.span_fatal(sp, m)
273 /// Report a lexical error with a given span.
274 fn err_span(&self, sp: Span, m: &str) {
275 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
279 /// Report a fatal error spanning [`from_pos`, `to_pos`).
280 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
281 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
284 /// Report a lexical error spanning [`from_pos`, `to_pos`).
285 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
286 self.err_span(self.mk_sp(from_pos, to_pos), m)
289 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
290 /// escaped character to the error message
291 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
292 let mut m = m.to_string();
294 push_escaped_char(&mut m, c);
296 self.fatal_span_(from_pos, to_pos, &m[..])
299 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
300 -> DiagnosticBuilder<'a>
302 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
305 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
306 -> DiagnosticBuilder<'a>
308 let mut m = m.to_string();
310 push_escaped_char(&mut m, c);
312 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
315 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
316 /// escaped character to the error message
317 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
318 let mut m = m.to_string();
320 push_escaped_char(&mut m, c);
321 self.err_span_(from_pos, to_pos, &m[..]);
324 /// Advance peek_tok and peek_span to refer to the next token, and
325 /// possibly update the interner.
326 fn advance_token(&mut self) -> Result<(), ()> {
327 match self.scan_whitespace_or_comment() {
329 self.peek_span_src_raw = comment.span;
330 self.peek_span = comment.span;
331 self.peek_tok = comment.kind;
335 self.peek_tok = token::Eof;
336 let (real, raw) = self.mk_sp_and_raw(
337 self.source_file.end_pos,
338 self.source_file.end_pos,
340 self.peek_span = real;
341 self.peek_span_src_raw = raw;
343 let start_bytepos = self.pos;
344 self.peek_tok = self.next_token_inner()?;
345 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
346 self.peek_span = real;
347 self.peek_span_src_raw = raw;
356 fn src_index(&self, pos: BytePos) -> usize {
357 (pos - self.source_file.start_pos).to_usize()
360 /// Calls `f` with a string slice of the source text spanning from `start`
361 /// up to but excluding `self.pos`, meaning the slice does not include
362 /// the character `self.ch`.
363 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
364 where F: FnOnce(&str) -> T
366 self.with_str_from_to(start, self.pos, f)
369 /// Creates a Name from a given offset to the current offset.
370 fn name_from(&self, start: BytePos) -> ast::Name {
371 debug!("taking an ident from {:?} to {:?}", start, self.pos);
372 self.with_str_from(start, Symbol::intern)
375 /// As name_from, with an explicit endpoint.
376 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
377 debug!("taking an ident from {:?} to {:?}", start, end);
378 self.with_str_from_to(start, end, Symbol::intern)
381 /// Calls `f` with a string slice of the source text spanning from `start`
382 /// up to but excluding `end`.
383 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
384 where F: FnOnce(&str) -> T
386 f(&self.src[self.src_index(start)..self.src_index(end)])
389 /// Converts CRLF to LF in the given string, raising an error on bare CR.
390 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
391 let mut chars = s.char_indices().peekable();
392 while let Some((i, ch)) = chars.next() {
394 if let Some((lf_idx, '\n')) = chars.peek() {
395 return translate_crlf_(self, start, s, *lf_idx, chars, errmsg).into();
397 let pos = start + BytePos(i as u32);
398 let end_pos = start + BytePos((i + ch.len_utf8()) as u32);
399 self.err_span_(pos, end_pos, errmsg);
404 fn translate_crlf_(rdr: &StringReader<'_>,
408 mut chars: iter::Peekable<impl Iterator<Item = (usize, char)>>,
411 let mut buf = String::with_capacity(s.len());
413 buf.push_str(&s[.. j - 1]);
414 while let Some((i, ch)) = chars.next() {
417 buf.push_str(&s[j..i]);
419 let next = i + ch.len_utf8();
421 if chars.peek().map(|(_, ch)| *ch) != Some('\n') {
422 let pos = start + BytePos(i as u32);
423 let end_pos = start + BytePos(next as u32);
424 rdr.err_span_(pos, end_pos, errmsg);
429 buf.push_str(&s[j..]);
435 /// Advance the StringReader by one character.
436 crate fn bump(&mut self) {
437 let next_src_index = self.src_index(self.next_pos);
438 if next_src_index < self.end_src_index {
439 let next_ch = char_at(&self.src, next_src_index);
440 let next_ch_len = next_ch.len_utf8();
442 self.ch = Some(next_ch);
443 self.pos = self.next_pos;
444 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
447 self.pos = self.next_pos;
451 fn nextch(&self) -> Option<char> {
452 let next_src_index = self.src_index(self.next_pos);
453 if next_src_index < self.end_src_index {
454 Some(char_at(&self.src, next_src_index))
461 fn nextch_is(&self, c: char) -> bool {
462 self.nextch() == Some(c)
465 fn nextnextch(&self) -> Option<char> {
466 let next_src_index = self.src_index(self.next_pos);
467 if next_src_index < self.end_src_index {
468 let next_next_src_index =
469 next_src_index + char_at(&self.src, next_src_index).len_utf8();
470 if next_next_src_index < self.end_src_index {
471 return Some(char_at(&self.src, next_next_src_index));
478 fn nextnextch_is(&self, c: char) -> bool {
479 self.nextnextch() == Some(c)
482 /// Eats <XID_start><XID_continue>*, if possible.
483 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
484 if !ident_start(self.ch) {
488 let start = self.pos;
491 while ident_continue(self.ch) {
495 self.with_str_from(start, |string| {
497 self.sess.span_diagnostic
498 .struct_span_warn(self.mk_sp(start, self.pos),
499 "underscore literal suffix is not allowed")
500 .warn("this was previously accepted by the compiler but is \
501 being phased out; it will become a hard error in \
503 .note("for more information, see issue #42326 \
504 <https://github.com/rust-lang/rust/issues/42326>")
508 Some(Symbol::intern(string))
513 /// PRECONDITION: self.ch is not whitespace
514 /// Eats any kind of comment.
515 fn scan_comment(&mut self) -> Option<Token> {
516 if let Some(c) = self.ch {
517 if c.is_whitespace() {
518 let msg = "called consume_any_line_comment, but there was whitespace";
519 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
524 match self.nextch() {
529 // line comments starting with "///" or "//!" are doc-comments
530 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
531 let start_bpos = self.pos - BytePos(2);
533 while !self.is_eof() {
534 match self.ch.unwrap() {
537 if self.nextch_is('\n') {
540 } else if doc_comment {
541 self.err_span_(self.pos,
543 "bare CR not allowed in doc-comment");
551 let kind = if doc_comment {
552 self.with_str_from(start_bpos, |string| {
553 token::DocComment(Symbol::intern(string))
558 Some(Token { kind, span: self.mk_sp(start_bpos, self.pos) })
563 self.scan_block_comment()
567 } else if self.ch_is('#') {
568 if self.nextch_is('!') {
570 // Parse an inner attribute.
571 if self.nextnextch_is('[') {
575 let is_beginning_of_file = self.pos == self.source_file.start_pos;
576 if is_beginning_of_file {
577 debug!("Skipping a shebang");
578 let start = self.pos;
579 while !self.ch_is('\n') && !self.is_eof() {
583 kind: token::Shebang(self.name_from(start)),
584 span: self.mk_sp(start, self.pos),
594 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
596 fn scan_whitespace_or_comment(&mut self) -> Option<Token> {
597 match self.ch.unwrap_or('\0') {
598 // # to handle shebang at start of file -- this is the entry point
599 // for skipping over all "junk"
601 let c = self.scan_comment();
602 debug!("scanning a comment {:?}", c);
605 c if is_pattern_whitespace(Some(c)) => {
606 let start_bpos = self.pos;
607 while is_pattern_whitespace(self.ch) {
611 kind: token::Whitespace,
612 span: self.mk_sp(start_bpos, self.pos),
614 debug!("scanning whitespace: {:?}", c);
621 /// Might return a sugared-doc-attr
622 fn scan_block_comment(&mut self) -> Option<Token> {
623 // block comments starting with "/**" or "/*!" are doc-comments
624 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
625 let start_bpos = self.pos - BytePos(2);
627 let mut level: isize = 1;
628 let mut has_cr = false;
631 let msg = if is_doc_comment {
632 "unterminated block doc-comment"
634 "unterminated block comment"
636 let last_bpos = self.pos;
637 self.fatal_span_(start_bpos, last_bpos, msg).raise();
639 let n = self.ch.unwrap();
641 '/' if self.nextch_is('*') => {
645 '*' if self.nextch_is('/') => {
657 self.with_str_from(start_bpos, |string| {
658 // but comments with only "*"s between two "/"s are not
659 let kind = if is_block_doc_comment(string) {
660 let string = if has_cr {
661 self.translate_crlf(start_bpos,
663 "bare CR not allowed in block doc-comment")
667 token::DocComment(Symbol::intern(&string[..]))
674 span: self.mk_sp(start_bpos, self.pos),
679 /// Scan through any digits (base `scan_radix`) or underscores,
680 /// and return how many digits there were.
682 /// `real_radix` represents the true radix of the number we're
683 /// interested in, and errors will be emitted for any digits
684 /// between `real_radix` and `scan_radix`.
685 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
686 assert!(real_radix <= scan_radix);
692 debug!("skipping a _");
696 match c.and_then(|cc| cc.to_digit(scan_radix)) {
698 debug!("{:?} in scan_digits", c);
699 // check that the hypothetical digit is actually
700 // in range for the true radix
701 if c.unwrap().to_digit(real_radix).is_none() {
702 self.err_span_(self.pos,
704 &format!("invalid digit for a base {} literal", real_radix));
714 /// Lex a LIT_INTEGER or a LIT_FLOAT
715 fn scan_number(&mut self, c: char) -> (token::LitKind, Symbol) {
717 let start_bpos = self.pos;
720 let num_digits = if c == '0' {
721 match self.ch.unwrap_or('\0') {
725 self.scan_digits(2, 10)
730 self.scan_digits(8, 10)
735 self.scan_digits(16, 16)
737 '0'..='9' | '_' | '.' | 'e' | 'E' => {
738 self.scan_digits(10, 10) + 1
742 return (token::Integer, sym::integer(0));
745 } else if c.is_digit(10) {
746 self.scan_digits(10, 10) + 1
752 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
754 return (token::Integer, Symbol::intern("0"));
757 // might be a float, but don't be greedy if this is actually an
758 // integer literal followed by field/method access or a range pattern
759 // (`0..2` and `12.foo()`)
760 if self.ch_is('.') && !self.nextch_is('.') &&
761 !ident_start(self.nextch()) {
762 // might have stuff after the ., and if it does, it needs to start
765 if self.ch.unwrap_or('\0').is_digit(10) {
766 self.scan_digits(10, 10);
767 self.scan_float_exponent();
770 self.check_float_base(start_bpos, pos, base);
772 (token::Float, self.name_from(start_bpos))
774 // it might be a float if it has an exponent
775 if self.ch_is('e') || self.ch_is('E') {
776 self.scan_float_exponent();
778 self.check_float_base(start_bpos, pos, base);
779 return (token::Float, self.name_from(start_bpos));
781 // but we certainly have an integer!
782 (token::Integer, self.name_from(start_bpos))
786 /// Scan over a float exponent.
787 fn scan_float_exponent(&mut self) {
788 if self.ch_is('e') || self.ch_is('E') {
791 if self.ch_is('-') || self.ch_is('+') {
795 if self.scan_digits(10, 10) == 0 {
796 let mut err = self.struct_span_fatal(
797 self.pos, self.next_pos,
798 "expected at least one digit in exponent"
800 if let Some(ch) = self.ch {
801 // check for e.g., Unicode minus '−' (Issue #49746)
802 if unicode_chars::check_for_substitution(self, ch, &mut err) {
804 self.scan_digits(10, 10);
812 /// Checks that a base is valid for a floating literal, emitting a nice
813 /// error if it isn't.
814 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
817 self.err_span_(start_bpos,
819 "hexadecimal float literal is not supported")
822 self.err_span_(start_bpos,
824 "octal float literal is not supported")
827 self.err_span_(start_bpos,
829 "binary float literal is not supported")
835 fn binop(&mut self, op: token::BinOpToken) -> TokenKind {
845 /// Returns the next token from the string, advances the input past that
846 /// token, and updates the interner
847 fn next_token_inner(&mut self) -> Result<TokenKind, ()> {
851 let (is_ident_start, is_raw_ident) =
852 match (c.unwrap(), self.nextch(), self.nextnextch()) {
853 // r# followed by an identifier starter is a raw identifier.
854 // This is an exception to the r# case below.
855 ('r', Some('#'), x) if ident_start(x) => (true, true),
856 // r as in r" or r#" is part of a raw string literal.
857 // b as in b' is part of a byte literal.
858 // They are not identifiers, and are handled further down.
859 ('r', Some('"'), _) |
860 ('r', Some('#'), _) |
861 ('b', Some('"'), _) |
862 ('b', Some('\''), _) |
863 ('b', Some('r'), Some('"')) |
864 ('b', Some('r'), Some('#')) => (false, false),
869 let raw_start = self.pos;
871 // Consume the 'r#' characters.
876 let start = self.pos;
879 while ident_continue(self.ch) {
883 return Ok(self.with_str_from(start, |string| {
884 // FIXME: perform NFKC normalization here. (Issue #2253)
885 let ident = self.mk_ident(string);
888 let span = self.mk_sp(raw_start, self.pos);
889 if !ident.can_be_raw() {
890 self.err_span(span, &format!("`{}` cannot be a raw identifier", ident));
892 self.sess.raw_identifier_spans.borrow_mut().push(span);
895 token::Ident(ident, is_raw_ident)
901 let (kind, symbol) = self.scan_number(c.unwrap());
902 let suffix = self.scan_optional_raw_name();
903 debug!("next_token_inner: scanned number {:?}, {:?}, {:?}", kind, symbol, suffix);
904 return Ok(TokenKind::lit(kind, symbol, suffix));
907 match c.expect("next_token_inner called at EOF") {
924 } else if self.ch_is('=') {
936 Ok(token::OpenDelim(token::Paren))
940 Ok(token::CloseDelim(token::Paren))
944 Ok(token::OpenDelim(token::Brace))
948 Ok(token::CloseDelim(token::Brace))
952 Ok(token::OpenDelim(token::Bracket))
956 Ok(token::CloseDelim(token::Bracket))
989 // Multi-byte tokens.
995 } else if self.ch_is('>') {
1004 if self.ch_is('=') {
1013 match self.ch.unwrap_or('\x00') {
1019 Ok(self.binop(token::Shl))
1032 match self.ch.unwrap_or('\x00') {
1038 Ok(self.binop(token::Shr))
1046 // Either a character constant 'a' OR a lifetime name 'abc
1047 let start_with_quote = self.pos;
1049 let start = self.pos;
1051 // If the character is an ident start not followed by another single
1052 // quote, then this is a lifetime name:
1053 let starts_with_number = self.ch.unwrap_or('\x00').is_numeric();
1054 if (ident_start(self.ch) || starts_with_number) && !self.nextch_is('\'') {
1056 while ident_continue(self.ch) {
1059 // lifetimes shouldn't end with a single quote
1060 // if we find one, then this is an invalid character literal
1061 if self.ch_is('\'') {
1062 let symbol = self.name_from(start);
1064 self.validate_char_escape(start_with_quote);
1065 return Ok(TokenKind::lit(token::Char, symbol, None));
1068 // Include the leading `'` in the real identifier, for macro
1069 // expansion purposes. See #12512 for the gory details of why
1070 // this is necessary.
1071 let ident = self.with_str_from(start_with_quote, |lifetime_name| {
1072 self.mk_ident(lifetime_name)
1075 if starts_with_number {
1076 // this is a recovered lifetime written `'1`, error but accept it
1080 "lifetimes cannot start with a number",
1084 return Ok(token::Lifetime(ident));
1086 let msg = "unterminated character literal";
1087 let symbol = self.scan_single_quoted_string(start_with_quote, msg);
1088 self.validate_char_escape(start_with_quote);
1089 let suffix = self.scan_optional_raw_name();
1090 Ok(TokenKind::lit(token::Char, symbol, suffix))
1094 let (kind, symbol) = match self.ch {
1096 let start_with_quote = self.pos;
1098 let msg = "unterminated byte constant";
1099 let symbol = self.scan_single_quoted_string(start_with_quote, msg);
1100 self.validate_byte_escape(start_with_quote);
1101 (token::Byte, symbol)
1104 let start_with_quote = self.pos;
1105 let msg = "unterminated double quote byte string";
1106 let symbol = self.scan_double_quoted_string(msg);
1107 self.validate_byte_str_escape(start_with_quote);
1108 (token::ByteStr, symbol)
1110 Some('r') => self.scan_raw_byte_string(),
1111 _ => unreachable!(), // Should have been a token::Ident above.
1113 let suffix = self.scan_optional_raw_name();
1115 Ok(TokenKind::lit(kind, symbol, suffix))
1118 let start_with_quote = self.pos;
1119 let msg = "unterminated double quote string";
1120 let symbol = self.scan_double_quoted_string(msg);
1121 self.validate_str_escape(start_with_quote);
1122 let suffix = self.scan_optional_raw_name();
1123 Ok(TokenKind::lit(token::Str, symbol, suffix))
1126 let start_bpos = self.pos;
1128 let mut hash_count: u16 = 0;
1129 while self.ch_is('#') {
1130 if hash_count == 65535 {
1131 let bpos = self.next_pos;
1132 self.fatal_span_(start_bpos,
1134 "too many `#` symbols: raw strings may be \
1135 delimited by up to 65535 `#` symbols").raise();
1142 self.fail_unterminated_raw_string(start_bpos, hash_count);
1143 } else if !self.ch_is('"') {
1144 let last_bpos = self.pos;
1145 let curr_char = self.ch.unwrap();
1146 self.fatal_span_char(start_bpos,
1148 "found invalid character; only `#` is allowed \
1149 in raw string delimitation",
1153 let content_start_bpos = self.pos;
1154 let mut content_end_bpos;
1155 let mut valid = true;
1158 self.fail_unterminated_raw_string(start_bpos, hash_count);
1160 // if self.ch_is('"') {
1161 // content_end_bpos = self.pos;
1162 // for _ in 0..hash_count {
1164 // if !self.ch_is('#') {
1166 let c = self.ch.unwrap();
1169 content_end_bpos = self.pos;
1170 for _ in 0..hash_count {
1172 if !self.ch_is('#') {
1179 if !self.nextch_is('\n') {
1180 let last_bpos = self.pos;
1181 self.err_span_(start_bpos,
1183 "bare CR not allowed in raw string, use \\r \
1194 let symbol = if valid {
1195 self.name_from_to(content_start_bpos, content_end_bpos)
1197 Symbol::intern("??")
1199 let suffix = self.scan_optional_raw_name();
1201 Ok(TokenKind::lit(token::StrRaw(hash_count), symbol, suffix))
1204 if self.nextch_is('>') {
1209 Ok(self.binop(token::Minus))
1213 if self.nextch_is('&') {
1218 Ok(self.binop(token::And))
1222 match self.nextch() {
1229 Ok(self.binop(token::Or))
1234 Ok(self.binop(token::Plus))
1237 Ok(self.binop(token::Star))
1240 Ok(self.binop(token::Slash))
1243 Ok(self.binop(token::Caret))
1246 Ok(self.binop(token::Percent))
1249 let last_bpos = self.pos;
1250 let bpos = self.next_pos;
1251 let mut err = self.struct_fatal_span_char(last_bpos,
1253 "unknown start of token",
1255 unicode_chars::check_for_substitution(self, c, &mut err);
1256 self.fatal_errs.push(err);
1263 fn read_to_eol(&mut self) -> String {
1264 let mut val = String::new();
1265 while !self.ch_is('\n') && !self.is_eof() {
1266 val.push(self.ch.unwrap());
1270 if self.ch_is('\n') {
1277 fn read_one_line_comment(&mut self) -> String {
1278 let val = self.read_to_eol();
1279 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1280 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1284 fn consume_non_eol_whitespace(&mut self) {
1285 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1290 fn peeking_at_comment(&self) -> bool {
1291 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1292 // consider shebangs comments, but not inner attributes
1293 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1296 fn scan_single_quoted_string(&mut self,
1297 start_with_quote: BytePos,
1298 unterminated_msg: &str) -> ast::Name {
1299 // assumes that first `'` is consumed
1300 let start = self.pos;
1301 // lex `'''` as a single char, for recovery
1302 if self.ch_is('\'') && self.nextch_is('\'') {
1305 let mut first = true;
1307 if self.ch_is('\'') {
1310 if self.ch_is('\\') && (self.nextch_is('\'') || self.nextch_is('\\')) {
1314 // Only attempt to infer single line string literals. If we encounter
1315 // a slash, bail out in order to avoid nonsensical suggestion when
1316 // involving comments.
1318 || (self.ch_is('/') && !first)
1319 || (self.ch_is('\n') && !self.nextch_is('\'')) {
1321 self.fatal_span_(start_with_quote, self.pos, unterminated_msg.into())
1330 let id = self.name_from(start);
1335 fn scan_double_quoted_string(&mut self, unterminated_msg: &str) -> ast::Name {
1336 debug_assert!(self.ch_is('\"'));
1337 let start_with_quote = self.pos;
1339 let start = self.pos;
1340 while !self.ch_is('"') {
1343 self.fatal_span_(start_with_quote, pos, unterminated_msg).raise();
1345 if self.ch_is('\\') && (self.nextch_is('\\') || self.nextch_is('"')) {
1350 let id = self.name_from(start);
1355 fn scan_raw_byte_string(&mut self) -> (token::LitKind, Symbol) {
1356 let start_bpos = self.pos;
1358 let mut hash_count = 0;
1359 while self.ch_is('#') {
1360 if hash_count == 65535 {
1361 let bpos = self.next_pos;
1362 self.fatal_span_(start_bpos,
1364 "too many `#` symbols: raw byte strings may be \
1365 delimited by up to 65535 `#` symbols").raise();
1372 self.fail_unterminated_raw_string(start_bpos, hash_count);
1373 } else if !self.ch_is('"') {
1375 let ch = self.ch.unwrap();
1376 self.fatal_span_char(start_bpos,
1378 "found invalid character; only `#` is allowed in raw \
1379 string delimitation",
1383 let content_start_bpos = self.pos;
1384 let mut content_end_bpos;
1388 self.fail_unterminated_raw_string(start_bpos, hash_count);
1391 content_end_bpos = self.pos;
1392 for _ in 0..hash_count {
1394 if !self.ch_is('#') {
1403 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1412 (token::ByteStrRaw(hash_count), self.name_from_to(content_start_bpos, content_end_bpos))
1415 fn validate_char_escape(&self, start_with_quote: BytePos) {
1416 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1417 if let Err((off, err)) = unescape::unescape_char(lit) {
1418 emit_unescape_error(
1419 &self.sess.span_diagnostic,
1421 self.mk_sp(start_with_quote, self.pos),
1422 unescape::Mode::Char,
1430 fn validate_byte_escape(&self, start_with_quote: BytePos) {
1431 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1432 if let Err((off, err)) = unescape::unescape_byte(lit) {
1433 emit_unescape_error(
1434 &self.sess.span_diagnostic,
1436 self.mk_sp(start_with_quote, self.pos),
1437 unescape::Mode::Byte,
1445 fn validate_str_escape(&self, start_with_quote: BytePos) {
1446 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1447 unescape::unescape_str(lit, &mut |range, c| {
1448 if let Err(err) = c {
1449 emit_unescape_error(
1450 &self.sess.span_diagnostic,
1452 self.mk_sp(start_with_quote, self.pos),
1453 unescape::Mode::Str,
1462 fn validate_byte_str_escape(&self, start_with_quote: BytePos) {
1463 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1464 unescape::unescape_byte_str(lit, &mut |range, c| {
1465 if let Err(err) = c {
1466 emit_unescape_error(
1467 &self.sess.span_diagnostic,
1469 self.mk_sp(start_with_quote, self.pos),
1470 unescape::Mode::ByteStr,
1480 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1481 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1483 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1484 c.map_or(false, Pattern_White_Space)
1488 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1489 c.map_or(false, |c| lo <= c && c <= hi)
1493 fn is_dec_digit(c: Option<char>) -> bool {
1494 in_range(c, '0', '9')
1497 fn is_doc_comment(s: &str) -> bool {
1498 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1499 s.starts_with("//!");
1500 debug!("is {:?} a doc comment? {}", s, res);
1504 fn is_block_doc_comment(s: &str) -> bool {
1505 // Prevent `/**/` from being parsed as a doc comment
1506 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1507 s.starts_with("/*!")) && s.len() >= 5;
1508 debug!("is {:?} a doc comment? {}", s, res);
1512 /// Determine whether `c` is a valid start for an ident.
1513 fn ident_start(c: Option<char>) -> bool {
1516 None => return false,
1519 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1522 fn ident_continue(c: Option<char>) -> bool {
1525 None => return false,
1528 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1529 (c > '\x7f' && c.is_xid_continue())
1533 fn char_at(s: &str, byte: usize) -> char {
1534 s[byte..].chars().next().unwrap()
1541 use crate::ast::{Ident, CrateConfig};
1542 use crate::symbol::Symbol;
1543 use crate::source_map::{SourceMap, FilePathMapping};
1544 use crate::feature_gate::UnstableFeatures;
1545 use crate::parse::token;
1546 use crate::diagnostics::plugin::ErrorMap;
1547 use crate::with_default_globals;
1549 use std::path::PathBuf;
1550 use syntax_pos::{BytePos, Span, NO_EXPANSION, edition::Edition};
1551 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
1552 use rustc_data_structures::sync::Lock;
1554 fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
1555 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1561 span_diagnostic: errors::Handler::with_emitter(true, None, Box::new(emitter)),
1562 unstable_features: UnstableFeatures::from_environment(),
1563 config: CrateConfig::default(),
1564 included_mod_stack: Lock::new(Vec::new()),
1566 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1567 raw_identifier_spans: Lock::new(Vec::new()),
1568 registered_diagnostics: Lock::new(ErrorMap::new()),
1569 buffered_lints: Lock::new(vec![]),
1570 edition: Edition::from_session(),
1571 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
1575 // open a string reader for the given string
1576 fn setup<'a>(sm: &SourceMap,
1577 sess: &'a ParseSess,
1579 -> StringReader<'a> {
1580 let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
1581 let mut sr = StringReader::new_raw(sess, sf, None);
1582 if sr.advance_token().is_err() {
1583 sr.emit_fatal_errors();
1591 with_default_globals(|| {
1592 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1593 let sh = mk_sess(sm.clone());
1594 let mut string_reader = setup(&sm,
1596 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1598 let id = Ident::from_str("fn");
1599 assert_eq!(string_reader.next_token().kind, token::Comment);
1600 assert_eq!(string_reader.next_token().kind, token::Whitespace);
1601 let tok1 = string_reader.next_token();
1603 kind: token::Ident(id, false),
1604 span: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1606 assert_eq!(tok1.kind, tok2.kind);
1607 assert_eq!(tok1.span, tok2.span);
1608 assert_eq!(string_reader.next_token().kind, token::Whitespace);
1609 // the 'main' id is already read:
1610 assert_eq!(string_reader.pos.clone(), BytePos(28));
1611 // read another token:
1612 let tok3 = string_reader.next_token();
1614 kind: mk_ident("main"),
1615 span: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1617 assert_eq!(tok3.kind, tok4.kind);
1618 assert_eq!(tok3.span, tok4.span);
1619 // the lparen is already read:
1620 assert_eq!(string_reader.pos.clone(), BytePos(29))
1624 // check that the given reader produces the desired stream
1625 // of tokens (stop checking after exhausting the expected vec)
1626 fn check_tokenization(mut string_reader: StringReader<'_>, expected: Vec<TokenKind>) {
1627 for expected_tok in &expected {
1628 assert_eq!(&string_reader.next_token().kind, expected_tok);
1632 // make the identifier by looking up the string in the interner
1633 fn mk_ident(id: &str) -> TokenKind {
1634 TokenKind::from_ast_ident(Ident::from_str(id))
1637 fn mk_lit(kind: token::LitKind, symbol: &str, suffix: Option<&str>) -> TokenKind {
1638 TokenKind::lit(kind, Symbol::intern(symbol), suffix.map(Symbol::intern))
1642 fn doublecolonparsing() {
1643 with_default_globals(|| {
1644 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1645 let sh = mk_sess(sm.clone());
1646 check_tokenization(setup(&sm, &sh, "a b".to_string()),
1647 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
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::ModSep, 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::Whitespace, 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::ModSep, token::Whitespace, mk_ident("b")]);
1683 with_default_globals(|| {
1684 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1685 let sh = mk_sess(sm.clone());
1686 assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().kind,
1687 mk_lit(token::Char, "a", None));
1692 fn character_space() {
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, "' '".to_string()).next_token().kind,
1697 mk_lit(token::Char, " ", None));
1702 fn character_escaped() {
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, "'\\n'".to_string()).next_token().kind,
1707 mk_lit(token::Char, "\\n", None));
1712 fn lifetime_name() {
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, "'abc".to_string()).next_token().kind,
1717 token::Lifetime(Ident::from_str("'abc")));
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, "r###\"\"#a\\b\x00c\"\"###".to_string()).next_token().kind,
1727 mk_lit(token::StrRaw(3), "\"#a\\b\x00c\"", None));
1732 fn literal_suffixes() {
1733 with_default_globals(|| {
1734 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1735 let sh = mk_sess(sm.clone());
1737 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1738 assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token().kind,
1739 mk_lit(token::$tok_type, $tok_contents, Some("suffix")));
1740 // with a whitespace separator:
1741 assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token().kind,
1742 mk_lit(token::$tok_type, $tok_contents, None));
1746 test!("'a'", Char, "a");
1747 test!("b'a'", Byte, "a");
1748 test!("\"a\"", Str, "a");
1749 test!("b\"a\"", ByteStr, "a");
1750 test!("1234", Integer, "1234");
1751 test!("0b101", Integer, "0b101");
1752 test!("0xABC", Integer, "0xABC");
1753 test!("1.0", Float, "1.0");
1754 test!("1.0e10", Float, "1.0e10");
1756 assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token().kind,
1757 mk_lit(token::Integer, "2", Some("us")));
1758 assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token().kind,
1759 mk_lit(token::StrRaw(3), "raw", Some("suffix")));
1760 assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token().kind,
1761 mk_lit(token::ByteStrRaw(3), "raw", Some("suffix")));
1766 fn line_doc_comments() {
1767 assert!(is_doc_comment("///"));
1768 assert!(is_doc_comment("/// blah"));
1769 assert!(!is_doc_comment("////"));
1773 fn nested_block_comments() {
1774 with_default_globals(|| {
1775 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1776 let sh = mk_sess(sm.clone());
1777 let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
1778 match lexer.next_token().kind {
1779 token::Comment => {}
1780 _ => panic!("expected a comment!"),
1782 assert_eq!(lexer.next_token().kind, mk_lit(token::Char, "a", None));
1787 fn crlf_comments() {
1788 with_default_globals(|| {
1789 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1790 let sh = mk_sess(sm.clone());
1791 let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
1792 let comment = lexer.next_token();
1793 assert_eq!(comment.kind, token::Comment);
1794 assert_eq!((comment.span.lo(), comment.span.hi()), (BytePos(0), BytePos(7)));
1795 assert_eq!(lexer.next_token().kind, token::Whitespace);
1796 assert_eq!(lexer.next_token().kind,
1797 token::DocComment(Symbol::intern("/// test")));