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.
67 /// The raw source span which *does not* take `override_span` into account
69 /// Stack of open delimiters and their spans. Used for error message.
70 open_braces: Vec<(token::DelimToken, Span)>,
71 crate unmatched_braces: Vec<UnmatchedBrace>,
72 /// The type and spans for all braces
74 /// Used only for error recovery when arriving to EOF with mismatched braces.
75 matching_delim_spans: Vec<(token::DelimToken, Span, Span)>,
76 crate override_span: Option<Span>,
77 last_unclosed_found_span: Option<Span>,
80 impl<'a> StringReader<'a> {
81 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
82 self.mk_sp_and_raw(lo, hi).0
85 fn mk_sp_and_raw(&self, lo: BytePos, hi: BytePos) -> (Span, Span) {
86 let raw = Span::new(lo, hi, NO_EXPANSION);
87 let real = self.override_span.unwrap_or(raw);
92 fn mk_ident(&self, string: &str) -> Ident {
93 let mut ident = Ident::from_str(string);
94 if let Some(span) = self.override_span {
101 fn unwrap_or_abort(&mut self, res: Result<TokenAndSpan, ()>) -> TokenAndSpan {
105 self.emit_fatal_errors();
111 fn next_token(&mut self) -> TokenAndSpan where Self: Sized {
112 let res = self.try_next_token();
113 self.unwrap_or_abort(res)
116 /// Returns the next token. EFFECT: advances the string_reader.
117 pub fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> {
118 assert!(self.fatal_errs.is_empty());
119 let ret_val = TokenAndSpan {
120 tok: replace(&mut self.peek_tok, token::Whitespace),
123 self.advance_token()?;
124 self.span_src_raw = self.peek_span_src_raw;
129 /// Immutably extract string if found at current position with given delimiters
130 fn peek_delimited(&self, from_ch: char, to_ch: char) -> Option<String> {
131 let mut pos = self.pos;
132 let mut idx = self.src_index(pos);
133 let mut ch = char_at(&self.src, idx);
137 pos = pos + Pos::from_usize(ch.len_utf8());
139 idx = self.src_index(pos);
140 while idx < self.end_src_index {
141 ch = char_at(&self.src, idx);
143 return Some(self.src[self.src_index(start_pos)..self.src_index(pos)].to_string());
145 pos = pos + Pos::from_usize(ch.len_utf8());
146 idx = self.src_index(pos);
151 fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> {
152 let mut t = self.try_next_token()?;
155 token::Whitespace | token::Comment | token::Shebang(_) => {
156 t = self.try_next_token()?;
162 self.token = t.tok.clone();
168 pub fn real_token(&mut self) -> TokenAndSpan {
169 let res = self.try_real_token();
170 self.unwrap_or_abort(res)
174 fn is_eof(&self) -> bool {
178 fn fail_unterminated_raw_string(&self, pos: BytePos, hash_count: u16) {
179 let mut err = self.struct_span_fatal(pos, pos, "unterminated raw string");
180 err.span_label(self.mk_sp(pos, pos), "unterminated raw string");
183 err.note(&format!("this raw string should be terminated with `\"{}`",
184 "#".repeat(hash_count as usize)));
191 fn fatal(&self, m: &str) -> FatalError {
192 self.fatal_span(self.peek_span, m)
195 crate fn emit_fatal_errors(&mut self) {
196 for err in &mut self.fatal_errs {
200 self.fatal_errs.clear();
203 pub fn buffer_fatal_errors(&mut self) -> Vec<Diagnostic> {
204 let mut buffer = Vec::new();
206 for err in self.fatal_errs.drain(..) {
207 err.buffer(&mut buffer);
213 pub fn peek(&self) -> TokenAndSpan {
214 // FIXME(pcwalton): Bad copy!
216 tok: self.peek_tok.clone(),
221 /// For comments.rs, which hackily pokes into next_pos and ch
222 fn new_raw(sess: &'a ParseSess,
223 source_file: Lrc<syntax_pos::SourceFile>,
224 override_span: Option<Span>) -> Self {
225 let mut sr = StringReader::new_raw_internal(sess, source_file, override_span);
231 fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc<syntax_pos::SourceFile>,
232 override_span: Option<Span>) -> Self
234 if source_file.src.is_none() {
235 sess.span_diagnostic.bug(&format!("Cannot lex source_file without source: {}",
239 let src = (*source_file.src.as_ref().unwrap()).clone();
243 next_pos: source_file.start_pos,
244 pos: source_file.start_pos,
247 end_src_index: src.len(),
248 // dummy values; not read
249 peek_tok: token::Eof,
250 peek_span: syntax_pos::DUMMY_SP,
251 peek_span_src_raw: syntax_pos::DUMMY_SP,
253 fatal_errs: Vec::new(),
255 span: syntax_pos::DUMMY_SP,
256 span_src_raw: syntax_pos::DUMMY_SP,
257 open_braces: Vec::new(),
258 unmatched_braces: Vec::new(),
259 matching_delim_spans: Vec::new(),
261 last_unclosed_found_span: None,
265 pub fn new_or_buffered_errs(sess: &'a ParseSess,
266 source_file: Lrc<syntax_pos::SourceFile>,
267 override_span: Option<Span>) -> Result<Self, Vec<Diagnostic>> {
268 let mut sr = StringReader::new_raw(sess, source_file, override_span);
269 if sr.advance_token().is_err() {
270 Err(sr.buffer_fatal_errors())
276 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
277 let begin = sess.source_map().lookup_byte_offset(span.lo());
278 let end = sess.source_map().lookup_byte_offset(span.hi());
280 // Make the range zero-length if the span is invalid.
281 if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
282 span = span.shrink_to_lo();
285 let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
287 // Seek the lexer to the right byte range.
288 sr.next_pos = span.lo();
289 sr.end_src_index = sr.src_index(span.hi());
293 if sr.advance_token().is_err() {
294 sr.emit_fatal_errors();
302 fn ch_is(&self, c: char) -> bool {
306 /// Report a fatal lexical error with a given span.
307 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
308 self.sess.span_diagnostic.span_fatal(sp, m)
311 /// Report a lexical error with a given span.
312 fn err_span(&self, sp: Span, m: &str) {
313 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
317 /// Report a fatal error spanning [`from_pos`, `to_pos`).
318 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
319 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
322 /// Report a lexical error spanning [`from_pos`, `to_pos`).
323 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
324 self.err_span(self.mk_sp(from_pos, to_pos), m)
327 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
328 /// escaped character to the error message
329 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
330 let mut m = m.to_string();
332 push_escaped_char(&mut m, c);
334 self.fatal_span_(from_pos, to_pos, &m[..])
337 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
338 -> DiagnosticBuilder<'a>
340 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
343 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
344 -> DiagnosticBuilder<'a>
346 let mut m = m.to_string();
348 push_escaped_char(&mut m, c);
350 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
353 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
354 /// escaped character to the error message
355 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
356 let mut m = m.to_string();
358 push_escaped_char(&mut m, c);
359 self.err_span_(from_pos, to_pos, &m[..]);
362 /// Advance peek_tok and peek_span to refer to the next token, and
363 /// possibly update the interner.
364 fn advance_token(&mut self) -> Result<(), ()> {
365 match self.scan_whitespace_or_comment() {
367 self.peek_span_src_raw = comment.sp;
368 self.peek_span = comment.sp;
369 self.peek_tok = comment.tok;
373 self.peek_tok = token::Eof;
374 let (real, raw) = self.mk_sp_and_raw(
375 self.source_file.end_pos,
376 self.source_file.end_pos,
378 self.peek_span = real;
379 self.peek_span_src_raw = raw;
381 let start_bytepos = self.pos;
382 self.peek_tok = self.next_token_inner()?;
383 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
384 self.peek_span = real;
385 self.peek_span_src_raw = raw;
394 fn src_index(&self, pos: BytePos) -> usize {
395 (pos - self.source_file.start_pos).to_usize()
398 /// Calls `f` with a string slice of the source text spanning from `start`
399 /// up to but excluding `self.pos`, meaning the slice does not include
400 /// the character `self.ch`.
401 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
402 where F: FnOnce(&str) -> T
404 self.with_str_from_to(start, self.pos, f)
407 /// Creates a Name from a given offset to the current offset.
408 fn name_from(&self, start: BytePos) -> ast::Name {
409 debug!("taking an ident from {:?} to {:?}", start, self.pos);
410 self.with_str_from(start, Symbol::intern)
413 /// As name_from, with an explicit endpoint.
414 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
415 debug!("taking an ident from {:?} to {:?}", start, end);
416 self.with_str_from_to(start, end, Symbol::intern)
419 /// Calls `f` with a string slice of the source text spanning from `start`
420 /// up to but excluding `end`.
421 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
422 where F: FnOnce(&str) -> T
424 f(&self.src[self.src_index(start)..self.src_index(end)])
427 /// Converts CRLF to LF in the given string, raising an error on bare CR.
428 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
429 let mut chars = s.char_indices().peekable();
430 while let Some((i, ch)) = chars.next() {
432 if let Some((lf_idx, '\n')) = chars.peek() {
433 return translate_crlf_(self, start, s, *lf_idx, chars, errmsg).into();
435 let pos = start + BytePos(i as u32);
436 let end_pos = start + BytePos((i + ch.len_utf8()) as u32);
437 self.err_span_(pos, end_pos, errmsg);
442 fn translate_crlf_(rdr: &StringReader<'_>,
446 mut chars: iter::Peekable<impl Iterator<Item = (usize, char)>>,
449 let mut buf = String::with_capacity(s.len());
451 buf.push_str(&s[.. j - 1]);
452 while let Some((i, ch)) = chars.next() {
455 buf.push_str(&s[j..i]);
457 let next = i + ch.len_utf8();
459 if chars.peek().map(|(_, ch)| *ch) != Some('\n') {
460 let pos = start + BytePos(i as u32);
461 let end_pos = start + BytePos(next as u32);
462 rdr.err_span_(pos, end_pos, errmsg);
467 buf.push_str(&s[j..]);
473 /// Advance the StringReader by one character.
474 crate fn bump(&mut self) {
475 let next_src_index = self.src_index(self.next_pos);
476 if next_src_index < self.end_src_index {
477 let next_ch = char_at(&self.src, next_src_index);
478 let next_ch_len = next_ch.len_utf8();
480 self.ch = Some(next_ch);
481 self.pos = self.next_pos;
482 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
485 self.pos = self.next_pos;
489 fn nextch(&self) -> Option<char> {
490 let next_src_index = self.src_index(self.next_pos);
491 if next_src_index < self.end_src_index {
492 Some(char_at(&self.src, next_src_index))
499 fn nextch_is(&self, c: char) -> bool {
500 self.nextch() == Some(c)
503 fn nextnextch(&self) -> Option<char> {
504 let next_src_index = self.src_index(self.next_pos);
505 if next_src_index < self.end_src_index {
506 let next_next_src_index =
507 next_src_index + char_at(&self.src, next_src_index).len_utf8();
508 if next_next_src_index < self.end_src_index {
509 return Some(char_at(&self.src, next_next_src_index));
516 fn nextnextch_is(&self, c: char) -> bool {
517 self.nextnextch() == Some(c)
520 /// Eats <XID_start><XID_continue>*, if possible.
521 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
522 if !ident_start(self.ch) {
526 let start = self.pos;
529 while ident_continue(self.ch) {
533 self.with_str_from(start, |string| {
535 self.sess.span_diagnostic
536 .struct_span_warn(self.mk_sp(start, self.pos),
537 "underscore literal suffix is not allowed")
538 .warn("this was previously accepted by the compiler but is \
539 being phased out; it will become a hard error in \
541 .note("for more information, see issue #42326 \
542 <https://github.com/rust-lang/rust/issues/42326>")
546 Some(Symbol::intern(string))
551 /// PRECONDITION: self.ch is not whitespace
552 /// Eats any kind of comment.
553 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
554 if let Some(c) = self.ch {
555 if c.is_whitespace() {
556 let msg = "called consume_any_line_comment, but there was whitespace";
557 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
562 match self.nextch() {
567 // line comments starting with "///" or "//!" are doc-comments
568 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
569 let start_bpos = self.pos - BytePos(2);
571 while !self.is_eof() {
572 match self.ch.unwrap() {
575 if self.nextch_is('\n') {
578 } else if doc_comment {
579 self.err_span_(self.pos,
581 "bare CR not allowed in doc-comment");
589 let tok = if doc_comment {
590 self.with_str_from(start_bpos, |string| {
591 token::DocComment(Symbol::intern(string))
596 Some(TokenAndSpan { tok, sp: self.mk_sp(start_bpos, self.pos) })
601 self.scan_block_comment()
605 } else if self.ch_is('#') {
606 if self.nextch_is('!') {
608 // Parse an inner attribute.
609 if self.nextnextch_is('[') {
613 let is_beginning_of_file = self.pos == self.source_file.start_pos;
614 if is_beginning_of_file {
615 debug!("Skipping a shebang");
616 let start = self.pos;
617 while !self.ch_is('\n') && !self.is_eof() {
620 return Some(TokenAndSpan {
621 tok: token::Shebang(self.name_from(start)),
622 sp: self.mk_sp(start, self.pos),
632 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
634 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
635 match self.ch.unwrap_or('\0') {
636 // # to handle shebang at start of file -- this is the entry point
637 // for skipping over all "junk"
639 let c = self.scan_comment();
640 debug!("scanning a comment {:?}", c);
643 c if is_pattern_whitespace(Some(c)) => {
644 let start_bpos = self.pos;
645 while is_pattern_whitespace(self.ch) {
648 let c = Some(TokenAndSpan {
649 tok: token::Whitespace,
650 sp: self.mk_sp(start_bpos, self.pos),
652 debug!("scanning whitespace: {:?}", c);
659 /// Might return a sugared-doc-attr
660 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
661 // block comments starting with "/**" or "/*!" are doc-comments
662 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
663 let start_bpos = self.pos - BytePos(2);
665 let mut level: isize = 1;
666 let mut has_cr = false;
669 let msg = if is_doc_comment {
670 "unterminated block doc-comment"
672 "unterminated block comment"
674 let last_bpos = self.pos;
675 self.fatal_span_(start_bpos, last_bpos, msg).raise();
677 let n = self.ch.unwrap();
679 '/' if self.nextch_is('*') => {
683 '*' if self.nextch_is('/') => {
695 self.with_str_from(start_bpos, |string| {
696 // but comments with only "*"s between two "/"s are not
697 let tok = if is_block_doc_comment(string) {
698 let string = if has_cr {
699 self.translate_crlf(start_bpos,
701 "bare CR not allowed in block doc-comment")
705 token::DocComment(Symbol::intern(&string[..]))
712 sp: self.mk_sp(start_bpos, self.pos),
717 /// Scan through any digits (base `scan_radix`) or underscores,
718 /// and return how many digits there were.
720 /// `real_radix` represents the true radix of the number we're
721 /// interested in, and errors will be emitted for any digits
722 /// between `real_radix` and `scan_radix`.
723 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
724 assert!(real_radix <= scan_radix);
730 debug!("skipping a _");
734 match c.and_then(|cc| cc.to_digit(scan_radix)) {
736 debug!("{:?} in scan_digits", c);
737 // check that the hypothetical digit is actually
738 // in range for the true radix
739 if c.unwrap().to_digit(real_radix).is_none() {
740 self.err_span_(self.pos,
742 &format!("invalid digit for a base {} literal", real_radix));
752 /// Lex a LIT_INTEGER or a LIT_FLOAT
753 fn scan_number(&mut self, c: char) -> token::Lit {
755 let start_bpos = self.pos;
758 let num_digits = if c == '0' {
759 match self.ch.unwrap_or('\0') {
763 self.scan_digits(2, 10)
768 self.scan_digits(8, 10)
773 self.scan_digits(16, 16)
775 '0'..='9' | '_' | '.' | 'e' | 'E' => {
776 self.scan_digits(10, 10) + 1
780 return token::Integer(self.name_from(start_bpos));
783 } else if c.is_digit(10) {
784 self.scan_digits(10, 10) + 1
790 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
792 return token::Integer(Symbol::intern("0"));
795 // might be a float, but don't be greedy if this is actually an
796 // integer literal followed by field/method access or a range pattern
797 // (`0..2` and `12.foo()`)
798 if self.ch_is('.') && !self.nextch_is('.') &&
799 !ident_start(self.nextch()) {
800 // might have stuff after the ., and if it does, it needs to start
803 if self.ch.unwrap_or('\0').is_digit(10) {
804 self.scan_digits(10, 10);
805 self.scan_float_exponent();
808 self.check_float_base(start_bpos, pos, base);
810 token::Float(self.name_from(start_bpos))
812 // it might be a float if it has an exponent
813 if self.ch_is('e') || self.ch_is('E') {
814 self.scan_float_exponent();
816 self.check_float_base(start_bpos, pos, base);
817 return token::Float(self.name_from(start_bpos));
819 // but we certainly have an integer!
820 token::Integer(self.name_from(start_bpos))
824 /// Scan over a float exponent.
825 fn scan_float_exponent(&mut self) {
826 if self.ch_is('e') || self.ch_is('E') {
829 if self.ch_is('-') || self.ch_is('+') {
833 if self.scan_digits(10, 10) == 0 {
834 let mut err = self.struct_span_fatal(
835 self.pos, self.next_pos,
836 "expected at least one digit in exponent"
838 if let Some(ch) = self.ch {
839 // check for e.g., Unicode minus '−' (Issue #49746)
840 if unicode_chars::check_for_substitution(self, ch, &mut err) {
842 self.scan_digits(10, 10);
850 /// Checks that a base is valid for a floating literal, emitting a nice
851 /// error if it isn't.
852 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
855 self.err_span_(start_bpos,
857 "hexadecimal float literal is not supported")
860 self.err_span_(start_bpos,
862 "octal float literal is not supported")
865 self.err_span_(start_bpos,
867 "binary float literal is not supported")
873 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
883 /// Returns the next token from the string, advances the input past that
884 /// token, and updates the interner
885 fn next_token_inner(&mut self) -> Result<token::Token, ()> {
889 let (is_ident_start, is_raw_ident) =
890 match (c.unwrap(), self.nextch(), self.nextnextch()) {
891 // r# followed by an identifier starter is a raw identifier.
892 // This is an exception to the r# case below.
893 ('r', Some('#'), x) if ident_start(x) => (true, true),
894 // r as in r" or r#" is part of a raw string literal.
895 // b as in b' is part of a byte literal.
896 // They are not identifiers, and are handled further down.
897 ('r', Some('"'), _) |
898 ('r', Some('#'), _) |
899 ('b', Some('"'), _) |
900 ('b', Some('\''), _) |
901 ('b', Some('r'), Some('"')) |
902 ('b', Some('r'), Some('#')) => (false, false),
907 let raw_start = self.pos;
909 // Consume the 'r#' characters.
914 let start = self.pos;
917 while ident_continue(self.ch) {
921 return Ok(self.with_str_from(start, |string| {
922 // FIXME: perform NFKC normalization here. (Issue #2253)
923 let ident = self.mk_ident(string);
926 let span = self.mk_sp(raw_start, self.pos);
927 if !ident.can_be_raw() {
928 self.err_span(span, &format!("`{}` cannot be a raw identifier", ident));
930 self.sess.raw_identifier_spans.borrow_mut().push(span);
933 token::Ident(ident, is_raw_ident)
939 let num = self.scan_number(c.unwrap());
940 let suffix = self.scan_optional_raw_name();
941 debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
942 return Ok(token::Literal(num, suffix));
945 match c.expect("next_token_inner called at EOF") {
962 } else if self.ch_is('=') {
974 Ok(token::OpenDelim(token::Paren))
978 Ok(token::CloseDelim(token::Paren))
982 Ok(token::OpenDelim(token::Brace))
986 Ok(token::CloseDelim(token::Brace))
990 Ok(token::OpenDelim(token::Bracket))
994 Ok(token::CloseDelim(token::Bracket))
1014 if self.ch_is(':') {
1027 // Multi-byte tokens.
1030 if self.ch_is('=') {
1033 } else if self.ch_is('>') {
1042 if self.ch_is('=') {
1051 match self.ch.unwrap_or('\x00') {
1057 Ok(self.binop(token::Shl))
1070 match self.ch.unwrap_or('\x00') {
1076 Ok(self.binop(token::Shr))
1084 // Either a character constant 'a' OR a lifetime name 'abc
1085 let start_with_quote = self.pos;
1087 let start = self.pos;
1089 // If the character is an ident start not followed by another single
1090 // quote, then this is a lifetime name:
1091 let starts_with_number = self.ch.unwrap_or('\x00').is_numeric();
1092 if (ident_start(self.ch) || starts_with_number) && !self.nextch_is('\'') {
1094 while ident_continue(self.ch) {
1097 // lifetimes shouldn't end with a single quote
1098 // if we find one, then this is an invalid character literal
1099 if self.ch_is('\'') {
1100 let id = self.name_from(start);
1102 self.validate_char_escape(start_with_quote);
1103 return Ok(token::Literal(token::Char(id), None))
1106 // Include the leading `'` in the real identifier, for macro
1107 // expansion purposes. See #12512 for the gory details of why
1108 // this is necessary.
1109 let ident = self.with_str_from(start_with_quote, |lifetime_name| {
1110 self.mk_ident(lifetime_name)
1113 if starts_with_number {
1114 // this is a recovered lifetime written `'1`, error but accept it
1118 "lifetimes cannot start with a number",
1122 return Ok(token::Lifetime(ident));
1124 let msg = "unterminated character literal";
1125 let id = self.scan_single_quoted_string(start_with_quote, msg);
1126 self.validate_char_escape(start_with_quote);
1127 let suffix = self.scan_optional_raw_name();
1128 Ok(token::Literal(token::Char(id), suffix))
1132 let lit = match self.ch {
1134 let start_with_quote = self.pos;
1136 let msg = "unterminated byte constant";
1137 let id = self.scan_single_quoted_string(start_with_quote, msg);
1138 self.validate_byte_escape(start_with_quote);
1142 let start_with_quote = self.pos;
1143 let msg = "unterminated double quote byte string";
1144 let id = self.scan_double_quoted_string(msg);
1145 self.validate_byte_str_escape(start_with_quote);
1148 Some('r') => self.scan_raw_byte_string(),
1149 _ => unreachable!(), // Should have been a token::Ident above.
1151 let suffix = self.scan_optional_raw_name();
1153 Ok(token::Literal(lit, suffix))
1156 let start_with_quote = self.pos;
1157 let msg = "unterminated double quote string";
1158 let id = self.scan_double_quoted_string(msg);
1159 self.validate_str_escape(start_with_quote);
1160 let suffix = self.scan_optional_raw_name();
1161 Ok(token::Literal(token::Str_(id), suffix))
1164 let start_bpos = self.pos;
1166 let mut hash_count: u16 = 0;
1167 while self.ch_is('#') {
1168 if hash_count == 65535 {
1169 let bpos = self.next_pos;
1170 self.fatal_span_(start_bpos,
1172 "too many `#` symbols: raw strings may be \
1173 delimited by up to 65535 `#` symbols").raise();
1180 self.fail_unterminated_raw_string(start_bpos, hash_count);
1181 } else if !self.ch_is('"') {
1182 let last_bpos = self.pos;
1183 let curr_char = self.ch.unwrap();
1184 self.fatal_span_char(start_bpos,
1186 "found invalid character; only `#` is allowed \
1187 in raw string delimitation",
1191 let content_start_bpos = self.pos;
1192 let mut content_end_bpos;
1193 let mut valid = true;
1196 self.fail_unterminated_raw_string(start_bpos, hash_count);
1198 // if self.ch_is('"') {
1199 // content_end_bpos = self.pos;
1200 // for _ in 0..hash_count {
1202 // if !self.ch_is('#') {
1204 let c = self.ch.unwrap();
1207 content_end_bpos = self.pos;
1208 for _ in 0..hash_count {
1210 if !self.ch_is('#') {
1217 if !self.nextch_is('\n') {
1218 let last_bpos = self.pos;
1219 self.err_span_(start_bpos,
1221 "bare CR not allowed in raw string, use \\r \
1233 self.name_from_to(content_start_bpos, content_end_bpos)
1235 Symbol::intern("??")
1237 let suffix = self.scan_optional_raw_name();
1239 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1242 if self.nextch_is('>') {
1247 Ok(self.binop(token::Minus))
1251 if self.nextch_is('&') {
1256 Ok(self.binop(token::And))
1260 match self.nextch() {
1267 Ok(self.binop(token::Or))
1272 Ok(self.binop(token::Plus))
1275 Ok(self.binop(token::Star))
1278 Ok(self.binop(token::Slash))
1281 Ok(self.binop(token::Caret))
1284 Ok(self.binop(token::Percent))
1287 let last_bpos = self.pos;
1288 let bpos = self.next_pos;
1289 let mut err = self.struct_fatal_span_char(last_bpos,
1291 "unknown start of token",
1293 unicode_chars::check_for_substitution(self, c, &mut err);
1294 self.fatal_errs.push(err);
1301 fn read_to_eol(&mut self) -> String {
1302 let mut val = String::new();
1303 while !self.ch_is('\n') && !self.is_eof() {
1304 val.push(self.ch.unwrap());
1308 if self.ch_is('\n') {
1315 fn read_one_line_comment(&mut self) -> String {
1316 let val = self.read_to_eol();
1317 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1318 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1322 fn consume_non_eol_whitespace(&mut self) {
1323 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1328 fn peeking_at_comment(&self) -> bool {
1329 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1330 // consider shebangs comments, but not inner attributes
1331 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1334 fn scan_single_quoted_string(&mut self,
1335 start_with_quote: BytePos,
1336 unterminated_msg: &str) -> ast::Name {
1337 // assumes that first `'` is consumed
1338 let start = self.pos;
1339 // lex `'''` as a single char, for recovery
1340 if self.ch_is('\'') && self.nextch_is('\'') {
1343 let mut first = true;
1345 if self.ch_is('\'') {
1348 if self.ch_is('\\') && (self.nextch_is('\'') || self.nextch_is('\\')) {
1352 // Only attempt to infer single line string literals. If we encounter
1353 // a slash, bail out in order to avoid nonsensical suggestion when
1354 // involving comments.
1356 || (self.ch_is('/') && !first)
1357 || (self.ch_is('\n') && !self.nextch_is('\'')) {
1359 self.fatal_span_(start_with_quote, self.pos, unterminated_msg.into())
1368 let id = self.name_from(start);
1373 fn scan_double_quoted_string(&mut self, unterminated_msg: &str) -> ast::Name {
1374 debug_assert!(self.ch_is('\"'));
1375 let start_with_quote = self.pos;
1377 let start = self.pos;
1378 while !self.ch_is('"') {
1381 self.fatal_span_(start_with_quote, pos, unterminated_msg).raise();
1383 if self.ch_is('\\') && (self.nextch_is('\\') || self.nextch_is('"')) {
1388 let id = self.name_from(start);
1393 fn scan_raw_byte_string(&mut self) -> token::Lit {
1394 let start_bpos = self.pos;
1396 let mut hash_count = 0;
1397 while self.ch_is('#') {
1398 if hash_count == 65535 {
1399 let bpos = self.next_pos;
1400 self.fatal_span_(start_bpos,
1402 "too many `#` symbols: raw byte strings may be \
1403 delimited by up to 65535 `#` symbols").raise();
1410 self.fail_unterminated_raw_string(start_bpos, hash_count);
1411 } else if !self.ch_is('"') {
1413 let ch = self.ch.unwrap();
1414 self.fatal_span_char(start_bpos,
1416 "found invalid character; only `#` is allowed in raw \
1417 string delimitation",
1421 let content_start_bpos = self.pos;
1422 let mut content_end_bpos;
1426 self.fail_unterminated_raw_string(start_bpos, hash_count);
1429 content_end_bpos = self.pos;
1430 for _ in 0..hash_count {
1432 if !self.ch_is('#') {
1441 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1450 token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), hash_count)
1453 fn validate_char_escape(&self, start_with_quote: BytePos) {
1454 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1455 if let Err((off, err)) = unescape::unescape_char(lit) {
1456 emit_unescape_error(
1457 &self.sess.span_diagnostic,
1459 self.mk_sp(start_with_quote, self.pos),
1460 unescape::Mode::Char,
1468 fn validate_byte_escape(&self, start_with_quote: BytePos) {
1469 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1470 if let Err((off, err)) = unescape::unescape_byte(lit) {
1471 emit_unescape_error(
1472 &self.sess.span_diagnostic,
1474 self.mk_sp(start_with_quote, self.pos),
1475 unescape::Mode::Byte,
1483 fn validate_str_escape(&self, start_with_quote: BytePos) {
1484 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1485 unescape::unescape_str(lit, &mut |range, c| {
1486 if let Err(err) = c {
1487 emit_unescape_error(
1488 &self.sess.span_diagnostic,
1490 self.mk_sp(start_with_quote, self.pos),
1491 unescape::Mode::Str,
1500 fn validate_byte_str_escape(&self, start_with_quote: BytePos) {
1501 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1502 unescape::unescape_byte_str(lit, &mut |range, c| {
1503 if let Err(err) = c {
1504 emit_unescape_error(
1505 &self.sess.span_diagnostic,
1507 self.mk_sp(start_with_quote, self.pos),
1508 unescape::Mode::ByteStr,
1518 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1519 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1521 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1522 c.map_or(false, Pattern_White_Space)
1526 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1527 c.map_or(false, |c| lo <= c && c <= hi)
1531 fn is_dec_digit(c: Option<char>) -> bool {
1532 in_range(c, '0', '9')
1535 fn is_doc_comment(s: &str) -> bool {
1536 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1537 s.starts_with("//!");
1538 debug!("is {:?} a doc comment? {}", s, res);
1542 fn is_block_doc_comment(s: &str) -> bool {
1543 // Prevent `/**/` from being parsed as a doc comment
1544 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1545 s.starts_with("/*!")) && s.len() >= 5;
1546 debug!("is {:?} a doc comment? {}", s, res);
1550 /// Determine whether `c` is a valid start for an ident.
1551 fn ident_start(c: Option<char>) -> bool {
1554 None => return false,
1557 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1560 fn ident_continue(c: Option<char>) -> bool {
1563 None => return false,
1566 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1567 (c > '\x7f' && c.is_xid_continue())
1571 fn char_at(s: &str, byte: usize) -> char {
1572 s[byte..].chars().next().unwrap()
1579 use crate::ast::{Ident, CrateConfig};
1580 use crate::symbol::Symbol;
1581 use crate::source_map::{SourceMap, FilePathMapping};
1582 use crate::feature_gate::UnstableFeatures;
1583 use crate::parse::token;
1584 use crate::diagnostics::plugin::ErrorMap;
1585 use crate::with_globals;
1587 use std::path::PathBuf;
1588 use syntax_pos::{BytePos, Span, NO_EXPANSION};
1589 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
1590 use rustc_data_structures::sync::Lock;
1592 fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
1593 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1599 span_diagnostic: errors::Handler::with_emitter(true, None, Box::new(emitter)),
1600 unstable_features: UnstableFeatures::from_environment(),
1601 config: CrateConfig::default(),
1602 included_mod_stack: Lock::new(Vec::new()),
1604 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1605 raw_identifier_spans: Lock::new(Vec::new()),
1606 registered_diagnostics: Lock::new(ErrorMap::new()),
1607 buffered_lints: Lock::new(vec![]),
1608 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
1612 // open a string reader for the given string
1613 fn setup<'a>(sm: &SourceMap,
1614 sess: &'a ParseSess,
1616 -> StringReader<'a> {
1617 let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
1618 let mut sr = StringReader::new_raw(sess, sf, None);
1619 if sr.advance_token().is_err() {
1620 sr.emit_fatal_errors();
1629 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1630 let sh = mk_sess(sm.clone());
1631 let mut string_reader = setup(&sm,
1633 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1635 let id = Ident::from_str("fn");
1636 assert_eq!(string_reader.next_token().tok, token::Comment);
1637 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1638 let tok1 = string_reader.next_token();
1639 let tok2 = TokenAndSpan {
1640 tok: token::Ident(id, false),
1641 sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1643 assert_eq!(tok1.tok, tok2.tok);
1644 assert_eq!(tok1.sp, tok2.sp);
1645 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1646 // the 'main' id is already read:
1647 assert_eq!(string_reader.pos.clone(), BytePos(28));
1648 // read another token:
1649 let tok3 = string_reader.next_token();
1650 let tok4 = TokenAndSpan {
1651 tok: mk_ident("main"),
1652 sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1654 assert_eq!(tok3.tok, tok4.tok);
1655 assert_eq!(tok3.sp, tok4.sp);
1656 // the lparen is already read:
1657 assert_eq!(string_reader.pos.clone(), BytePos(29))
1661 // check that the given reader produces the desired stream
1662 // of tokens (stop checking after exhausting the expected vec)
1663 fn check_tokenization(mut string_reader: StringReader<'_>, expected: Vec<token::Token>) {
1664 for expected_tok in &expected {
1665 assert_eq!(&string_reader.next_token().tok, expected_tok);
1669 // make the identifier by looking up the string in the interner
1670 fn mk_ident(id: &str) -> token::Token {
1671 token::Token::from_ast_ident(Ident::from_str(id))
1675 fn doublecolonparsing() {
1677 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1678 let sh = mk_sess(sm.clone());
1679 check_tokenization(setup(&sm, &sh, "a b".to_string()),
1680 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1687 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1688 let sh = mk_sess(sm.clone());
1689 check_tokenization(setup(&sm, &sh, "a::b".to_string()),
1690 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1697 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1698 let sh = mk_sess(sm.clone());
1699 check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
1700 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
1707 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1708 let sh = mk_sess(sm.clone());
1709 check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
1710 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
1717 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1718 let sh = mk_sess(sm.clone());
1719 assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok,
1720 token::Literal(token::Char(Symbol::intern("a")), None));
1725 fn character_space() {
1727 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1728 let sh = mk_sess(sm.clone());
1729 assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok,
1730 token::Literal(token::Char(Symbol::intern(" ")), None));
1735 fn character_escaped() {
1737 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1738 let sh = mk_sess(sm.clone());
1739 assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok,
1740 token::Literal(token::Char(Symbol::intern("\\n")), None));
1745 fn lifetime_name() {
1747 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1748 let sh = mk_sess(sm.clone());
1749 assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok,
1750 token::Lifetime(Ident::from_str("'abc")));
1757 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1758 let sh = mk_sess(sm.clone());
1759 assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
1762 token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
1767 fn literal_suffixes() {
1769 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1770 let sh = mk_sess(sm.clone());
1772 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1773 assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token().tok,
1774 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
1775 Some(Symbol::intern("suffix"))));
1776 // with a whitespace separator:
1777 assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token().tok,
1778 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
1783 test!("'a'", Char, "a");
1784 test!("b'a'", Byte, "a");
1785 test!("\"a\"", Str_, "a");
1786 test!("b\"a\"", ByteStr, "a");
1787 test!("1234", Integer, "1234");
1788 test!("0b101", Integer, "0b101");
1789 test!("0xABC", Integer, "0xABC");
1790 test!("1.0", Float, "1.0");
1791 test!("1.0e10", Float, "1.0e10");
1793 assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token().tok,
1794 token::Literal(token::Integer(Symbol::intern("2")),
1795 Some(Symbol::intern("us"))));
1796 assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
1797 token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
1798 Some(Symbol::intern("suffix"))));
1799 assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
1800 token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
1801 Some(Symbol::intern("suffix"))));
1806 fn line_doc_comments() {
1807 assert!(is_doc_comment("///"));
1808 assert!(is_doc_comment("/// blah"));
1809 assert!(!is_doc_comment("////"));
1813 fn nested_block_comments() {
1815 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1816 let sh = mk_sess(sm.clone());
1817 let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
1818 match lexer.next_token().tok {
1819 token::Comment => {}
1820 _ => panic!("expected a comment!"),
1822 assert_eq!(lexer.next_token().tok,
1823 token::Literal(token::Char(Symbol::intern("a")), None));
1828 fn crlf_comments() {
1830 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1831 let sh = mk_sess(sm.clone());
1832 let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
1833 let comment = lexer.next_token();
1834 assert_eq!(comment.tok, token::Comment);
1835 assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
1836 assert_eq!(lexer.next_token().tok, token::Whitespace);
1837 assert_eq!(lexer.next_token().tok,
1838 token::DocComment(Symbol::intern("/// test")));