1 use crate::ast::{self, Ident};
2 use crate::parse::ParseSess;
3 use crate::parse::token::{self, Token};
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 TokenAndSpan {
29 impl Default for TokenAndSpan {
30 fn default() -> Self {
32 tok: token::Whitespace,
33 sp: syntax_pos::DUMMY_SP,
38 #[derive(Clone, Debug)]
39 pub struct UnmatchedBrace {
40 pub expected_delim: token::DelimToken,
41 pub found_delim: token::DelimToken,
43 pub unclosed_span: Option<Span>,
44 pub candidate_span: Option<Span>,
47 pub struct StringReader<'a> {
48 crate sess: &'a ParseSess,
49 /// The absolute offset within the source_map of the next character to read
50 crate next_pos: BytePos,
51 /// The absolute offset within the source_map of the current character
53 /// The current character (which has been read from self.pos)
54 crate ch: Option<char>,
55 crate source_file: Lrc<syntax_pos::SourceFile>,
56 /// Stop reading src at this index.
57 crate end_src_index: usize,
61 peek_span_src_raw: Span,
62 fatal_errs: Vec<DiagnosticBuilder<'a>>,
63 // cache a direct reference to the source text, so that we don't have to
64 // retrieve it via `self.source_file.src.as_ref().unwrap()` all the time.
66 override_span: Option<Span>,
69 impl<'a> StringReader<'a> {
70 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
71 self.mk_sp_and_raw(lo, hi).0
74 fn mk_sp_and_raw(&self, lo: BytePos, hi: BytePos) -> (Span, Span) {
75 let raw = Span::new(lo, hi, NO_EXPANSION);
76 let real = self.override_span.unwrap_or(raw);
81 fn mk_ident(&self, string: &str) -> Ident {
82 let mut ident = Ident::from_str(string);
83 if let Some(span) = self.override_span {
90 fn unwrap_or_abort(&mut self, res: Result<TokenAndSpan, ()>) -> TokenAndSpan {
94 self.emit_fatal_errors();
100 fn next_token(&mut self) -> TokenAndSpan where Self: Sized {
101 let res = self.try_next_token();
102 self.unwrap_or_abort(res)
105 /// Returns the next token. EFFECT: advances the string_reader.
106 pub fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> {
107 assert!(self.fatal_errs.is_empty());
108 let ret_val = TokenAndSpan {
109 tok: replace(&mut self.peek_tok, token::Whitespace),
112 self.advance_token()?;
116 /// Immutably extract string if found at current position with given delimiters
117 fn peek_delimited(&self, from_ch: char, to_ch: char) -> Option<String> {
118 let mut pos = self.pos;
119 let mut idx = self.src_index(pos);
120 let mut ch = char_at(&self.src, idx);
124 pos = pos + Pos::from_usize(ch.len_utf8());
126 idx = self.src_index(pos);
127 while idx < self.end_src_index {
128 ch = char_at(&self.src, idx);
130 return Some(self.src[self.src_index(start_pos)..self.src_index(pos)].to_string());
132 pos = pos + Pos::from_usize(ch.len_utf8());
133 idx = self.src_index(pos);
138 fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> {
139 let mut t = self.try_next_token()?;
142 token::Whitespace | token::Comment | token::Shebang(_) => {
143 t = self.try_next_token()?;
152 pub fn real_token(&mut self) -> TokenAndSpan {
153 let res = self.try_real_token();
154 self.unwrap_or_abort(res)
158 fn is_eof(&self) -> bool {
162 fn fail_unterminated_raw_string(&self, pos: BytePos, hash_count: u16) {
163 let mut err = self.struct_span_fatal(pos, pos, "unterminated raw string");
164 err.span_label(self.mk_sp(pos, pos), "unterminated raw string");
167 err.note(&format!("this raw string should be terminated with `\"{}`",
168 "#".repeat(hash_count as usize)));
175 fn fatal(&self, m: &str) -> FatalError {
176 self.fatal_span(self.peek_span, m)
179 crate fn emit_fatal_errors(&mut self) {
180 for err in &mut self.fatal_errs {
184 self.fatal_errs.clear();
187 pub fn buffer_fatal_errors(&mut self) -> Vec<Diagnostic> {
188 let mut buffer = Vec::new();
190 for err in self.fatal_errs.drain(..) {
191 err.buffer(&mut buffer);
197 pub fn peek(&self) -> TokenAndSpan {
198 // FIXME(pcwalton): Bad copy!
200 tok: self.peek_tok.clone(),
205 /// For comments.rs, which hackily pokes into next_pos and ch
206 fn new_raw(sess: &'a ParseSess,
207 source_file: Lrc<syntax_pos::SourceFile>,
208 override_span: Option<Span>) -> Self {
209 let mut sr = StringReader::new_raw_internal(sess, source_file, override_span);
215 fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc<syntax_pos::SourceFile>,
216 override_span: Option<Span>) -> Self
218 if source_file.src.is_none() {
219 sess.span_diagnostic.bug(&format!("Cannot lex source_file without source: {}",
223 let src = (*source_file.src.as_ref().unwrap()).clone();
227 next_pos: source_file.start_pos,
228 pos: source_file.start_pos,
231 end_src_index: src.len(),
232 // dummy values; not read
233 peek_tok: token::Eof,
234 peek_span: syntax_pos::DUMMY_SP,
235 peek_span_src_raw: syntax_pos::DUMMY_SP,
237 fatal_errs: Vec::new(),
242 pub fn new_or_buffered_errs(sess: &'a ParseSess,
243 source_file: Lrc<syntax_pos::SourceFile>,
244 override_span: Option<Span>) -> Result<Self, Vec<Diagnostic>> {
245 let mut sr = StringReader::new_raw(sess, source_file, override_span);
246 if sr.advance_token().is_err() {
247 Err(sr.buffer_fatal_errors())
253 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
254 let begin = sess.source_map().lookup_byte_offset(span.lo());
255 let end = sess.source_map().lookup_byte_offset(span.hi());
257 // Make the range zero-length if the span is invalid.
258 if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
259 span = span.shrink_to_lo();
262 let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
264 // Seek the lexer to the right byte range.
265 sr.next_pos = span.lo();
266 sr.end_src_index = sr.src_index(span.hi());
270 if sr.advance_token().is_err() {
271 sr.emit_fatal_errors();
279 fn ch_is(&self, c: char) -> bool {
283 /// Report a fatal lexical error with a given span.
284 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
285 self.sess.span_diagnostic.span_fatal(sp, m)
288 /// Report a lexical error with a given span.
289 fn err_span(&self, sp: Span, m: &str) {
290 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
294 /// Report a fatal error spanning [`from_pos`, `to_pos`).
295 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
296 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
299 /// Report a lexical error spanning [`from_pos`, `to_pos`).
300 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
301 self.err_span(self.mk_sp(from_pos, to_pos), m)
304 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
305 /// escaped character to the error message
306 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
307 let mut m = m.to_string();
309 push_escaped_char(&mut m, c);
311 self.fatal_span_(from_pos, to_pos, &m[..])
314 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
315 -> DiagnosticBuilder<'a>
317 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
320 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
321 -> DiagnosticBuilder<'a>
323 let mut m = m.to_string();
325 push_escaped_char(&mut m, c);
327 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
330 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
331 /// escaped character to the error message
332 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
333 let mut m = m.to_string();
335 push_escaped_char(&mut m, c);
336 self.err_span_(from_pos, to_pos, &m[..]);
339 /// Advance peek_tok and peek_span to refer to the next token, and
340 /// possibly update the interner.
341 fn advance_token(&mut self) -> Result<(), ()> {
342 match self.scan_whitespace_or_comment() {
344 self.peek_span_src_raw = comment.sp;
345 self.peek_span = comment.sp;
346 self.peek_tok = comment.tok;
350 self.peek_tok = token::Eof;
351 let (real, raw) = self.mk_sp_and_raw(
352 self.source_file.end_pos,
353 self.source_file.end_pos,
355 self.peek_span = real;
356 self.peek_span_src_raw = raw;
358 let start_bytepos = self.pos;
359 self.peek_tok = self.next_token_inner()?;
360 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
361 self.peek_span = real;
362 self.peek_span_src_raw = raw;
371 fn src_index(&self, pos: BytePos) -> usize {
372 (pos - self.source_file.start_pos).to_usize()
375 /// Calls `f` with a string slice of the source text spanning from `start`
376 /// up to but excluding `self.pos`, meaning the slice does not include
377 /// the character `self.ch`.
378 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
379 where F: FnOnce(&str) -> T
381 self.with_str_from_to(start, self.pos, f)
384 /// Creates a Name from a given offset to the current offset.
385 fn name_from(&self, start: BytePos) -> ast::Name {
386 debug!("taking an ident from {:?} to {:?}", start, self.pos);
387 self.with_str_from(start, Symbol::intern)
390 /// As name_from, with an explicit endpoint.
391 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
392 debug!("taking an ident from {:?} to {:?}", start, end);
393 self.with_str_from_to(start, end, Symbol::intern)
396 /// Calls `f` with a string slice of the source text spanning from `start`
397 /// up to but excluding `end`.
398 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
399 where F: FnOnce(&str) -> T
401 f(&self.src[self.src_index(start)..self.src_index(end)])
404 /// Converts CRLF to LF in the given string, raising an error on bare CR.
405 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
406 let mut chars = s.char_indices().peekable();
407 while let Some((i, ch)) = chars.next() {
409 if let Some((lf_idx, '\n')) = chars.peek() {
410 return translate_crlf_(self, start, s, *lf_idx, chars, errmsg).into();
412 let pos = start + BytePos(i as u32);
413 let end_pos = start + BytePos((i + ch.len_utf8()) as u32);
414 self.err_span_(pos, end_pos, errmsg);
419 fn translate_crlf_(rdr: &StringReader<'_>,
423 mut chars: iter::Peekable<impl Iterator<Item = (usize, char)>>,
426 let mut buf = String::with_capacity(s.len());
428 buf.push_str(&s[.. j - 1]);
429 while let Some((i, ch)) = chars.next() {
432 buf.push_str(&s[j..i]);
434 let next = i + ch.len_utf8();
436 if chars.peek().map(|(_, ch)| *ch) != Some('\n') {
437 let pos = start + BytePos(i as u32);
438 let end_pos = start + BytePos(next as u32);
439 rdr.err_span_(pos, end_pos, errmsg);
444 buf.push_str(&s[j..]);
450 /// Advance the StringReader by one character.
451 crate fn bump(&mut self) {
452 let next_src_index = self.src_index(self.next_pos);
453 if next_src_index < self.end_src_index {
454 let next_ch = char_at(&self.src, next_src_index);
455 let next_ch_len = next_ch.len_utf8();
457 self.ch = Some(next_ch);
458 self.pos = self.next_pos;
459 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
462 self.pos = self.next_pos;
466 fn nextch(&self) -> Option<char> {
467 let next_src_index = self.src_index(self.next_pos);
468 if next_src_index < self.end_src_index {
469 Some(char_at(&self.src, next_src_index))
476 fn nextch_is(&self, c: char) -> bool {
477 self.nextch() == Some(c)
480 fn nextnextch(&self) -> Option<char> {
481 let next_src_index = self.src_index(self.next_pos);
482 if next_src_index < self.end_src_index {
483 let next_next_src_index =
484 next_src_index + char_at(&self.src, next_src_index).len_utf8();
485 if next_next_src_index < self.end_src_index {
486 return Some(char_at(&self.src, next_next_src_index));
493 fn nextnextch_is(&self, c: char) -> bool {
494 self.nextnextch() == Some(c)
497 /// Eats <XID_start><XID_continue>*, if possible.
498 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
499 if !ident_start(self.ch) {
503 let start = self.pos;
506 while ident_continue(self.ch) {
510 self.with_str_from(start, |string| {
512 self.sess.span_diagnostic
513 .struct_span_warn(self.mk_sp(start, self.pos),
514 "underscore literal suffix is not allowed")
515 .warn("this was previously accepted by the compiler but is \
516 being phased out; it will become a hard error in \
518 .note("for more information, see issue #42326 \
519 <https://github.com/rust-lang/rust/issues/42326>")
523 Some(Symbol::intern(string))
528 /// PRECONDITION: self.ch is not whitespace
529 /// Eats any kind of comment.
530 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
531 if let Some(c) = self.ch {
532 if c.is_whitespace() {
533 let msg = "called consume_any_line_comment, but there was whitespace";
534 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
539 match self.nextch() {
544 // line comments starting with "///" or "//!" are doc-comments
545 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
546 let start_bpos = self.pos - BytePos(2);
548 while !self.is_eof() {
549 match self.ch.unwrap() {
552 if self.nextch_is('\n') {
555 } else if doc_comment {
556 self.err_span_(self.pos,
558 "bare CR not allowed in doc-comment");
566 let tok = if doc_comment {
567 self.with_str_from(start_bpos, |string| {
568 token::DocComment(Symbol::intern(string))
573 Some(TokenAndSpan { tok, sp: self.mk_sp(start_bpos, self.pos) })
578 self.scan_block_comment()
582 } else if self.ch_is('#') {
583 if self.nextch_is('!') {
585 // Parse an inner attribute.
586 if self.nextnextch_is('[') {
590 let is_beginning_of_file = self.pos == self.source_file.start_pos;
591 if is_beginning_of_file {
592 debug!("Skipping a shebang");
593 let start = self.pos;
594 while !self.ch_is('\n') && !self.is_eof() {
597 return Some(TokenAndSpan {
598 tok: token::Shebang(self.name_from(start)),
599 sp: self.mk_sp(start, self.pos),
609 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
611 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
612 match self.ch.unwrap_or('\0') {
613 // # to handle shebang at start of file -- this is the entry point
614 // for skipping over all "junk"
616 let c = self.scan_comment();
617 debug!("scanning a comment {:?}", c);
620 c if is_pattern_whitespace(Some(c)) => {
621 let start_bpos = self.pos;
622 while is_pattern_whitespace(self.ch) {
625 let c = Some(TokenAndSpan {
626 tok: token::Whitespace,
627 sp: self.mk_sp(start_bpos, self.pos),
629 debug!("scanning whitespace: {:?}", c);
636 /// Might return a sugared-doc-attr
637 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
638 // block comments starting with "/**" or "/*!" are doc-comments
639 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
640 let start_bpos = self.pos - BytePos(2);
642 let mut level: isize = 1;
643 let mut has_cr = false;
646 let msg = if is_doc_comment {
647 "unterminated block doc-comment"
649 "unterminated block comment"
651 let last_bpos = self.pos;
652 self.fatal_span_(start_bpos, last_bpos, msg).raise();
654 let n = self.ch.unwrap();
656 '/' if self.nextch_is('*') => {
660 '*' if self.nextch_is('/') => {
672 self.with_str_from(start_bpos, |string| {
673 // but comments with only "*"s between two "/"s are not
674 let tok = if is_block_doc_comment(string) {
675 let string = if has_cr {
676 self.translate_crlf(start_bpos,
678 "bare CR not allowed in block doc-comment")
682 token::DocComment(Symbol::intern(&string[..]))
689 sp: self.mk_sp(start_bpos, self.pos),
694 /// Scan through any digits (base `scan_radix`) or underscores,
695 /// and return how many digits there were.
697 /// `real_radix` represents the true radix of the number we're
698 /// interested in, and errors will be emitted for any digits
699 /// between `real_radix` and `scan_radix`.
700 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
701 assert!(real_radix <= scan_radix);
707 debug!("skipping a _");
711 match c.and_then(|cc| cc.to_digit(scan_radix)) {
713 debug!("{:?} in scan_digits", c);
714 // check that the hypothetical digit is actually
715 // in range for the true radix
716 if c.unwrap().to_digit(real_radix).is_none() {
717 self.err_span_(self.pos,
719 &format!("invalid digit for a base {} literal", real_radix));
729 /// Lex a LIT_INTEGER or a LIT_FLOAT
730 fn scan_number(&mut self, c: char) -> (token::LitKind, Symbol) {
732 let start_bpos = self.pos;
735 let num_digits = if c == '0' {
736 match self.ch.unwrap_or('\0') {
740 self.scan_digits(2, 10)
745 self.scan_digits(8, 10)
750 self.scan_digits(16, 16)
752 '0'..='9' | '_' | '.' | 'e' | 'E' => {
753 self.scan_digits(10, 10) + 1
757 return (token::Integer, sym::integer(0));
760 } else if c.is_digit(10) {
761 self.scan_digits(10, 10) + 1
767 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
769 return (token::Integer, Symbol::intern("0"));
772 // might be a float, but don't be greedy if this is actually an
773 // integer literal followed by field/method access or a range pattern
774 // (`0..2` and `12.foo()`)
775 if self.ch_is('.') && !self.nextch_is('.') &&
776 !ident_start(self.nextch()) {
777 // might have stuff after the ., and if it does, it needs to start
780 if self.ch.unwrap_or('\0').is_digit(10) {
781 self.scan_digits(10, 10);
782 self.scan_float_exponent();
785 self.check_float_base(start_bpos, pos, base);
787 (token::Float, self.name_from(start_bpos))
789 // it might be a float if it has an exponent
790 if self.ch_is('e') || self.ch_is('E') {
791 self.scan_float_exponent();
793 self.check_float_base(start_bpos, pos, base);
794 return (token::Float, self.name_from(start_bpos));
796 // but we certainly have an integer!
797 (token::Integer, self.name_from(start_bpos))
801 /// Scan over a float exponent.
802 fn scan_float_exponent(&mut self) {
803 if self.ch_is('e') || self.ch_is('E') {
806 if self.ch_is('-') || self.ch_is('+') {
810 if self.scan_digits(10, 10) == 0 {
811 let mut err = self.struct_span_fatal(
812 self.pos, self.next_pos,
813 "expected at least one digit in exponent"
815 if let Some(ch) = self.ch {
816 // check for e.g., Unicode minus '−' (Issue #49746)
817 if unicode_chars::check_for_substitution(self, ch, &mut err) {
819 self.scan_digits(10, 10);
827 /// Checks that a base is valid for a floating literal, emitting a nice
828 /// error if it isn't.
829 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
832 self.err_span_(start_bpos,
834 "hexadecimal float literal is not supported")
837 self.err_span_(start_bpos,
839 "octal float literal is not supported")
842 self.err_span_(start_bpos,
844 "binary float literal is not supported")
850 fn binop(&mut self, op: token::BinOpToken) -> Token {
860 /// Returns the next token from the string, advances the input past that
861 /// token, and updates the interner
862 fn next_token_inner(&mut self) -> Result<Token, ()> {
866 let (is_ident_start, is_raw_ident) =
867 match (c.unwrap(), self.nextch(), self.nextnextch()) {
868 // r# followed by an identifier starter is a raw identifier.
869 // This is an exception to the r# case below.
870 ('r', Some('#'), x) if ident_start(x) => (true, true),
871 // r as in r" or r#" is part of a raw string literal.
872 // b as in b' is part of a byte literal.
873 // They are not identifiers, and are handled further down.
874 ('r', Some('"'), _) |
875 ('r', Some('#'), _) |
876 ('b', Some('"'), _) |
877 ('b', Some('\''), _) |
878 ('b', Some('r'), Some('"')) |
879 ('b', Some('r'), Some('#')) => (false, false),
884 let raw_start = self.pos;
886 // Consume the 'r#' characters.
891 let start = self.pos;
894 while ident_continue(self.ch) {
898 return Ok(self.with_str_from(start, |string| {
899 // FIXME: perform NFKC normalization here. (Issue #2253)
900 let ident = self.mk_ident(string);
903 let span = self.mk_sp(raw_start, self.pos);
904 if !ident.can_be_raw() {
905 self.err_span(span, &format!("`{}` cannot be a raw identifier", ident));
907 self.sess.raw_identifier_spans.borrow_mut().push(span);
910 token::Ident(ident, is_raw_ident)
916 let (kind, symbol) = self.scan_number(c.unwrap());
917 let suffix = self.scan_optional_raw_name();
918 debug!("next_token_inner: scanned number {:?}, {:?}, {:?}", kind, symbol, suffix);
919 return Ok(Token::lit(kind, symbol, suffix));
922 match c.expect("next_token_inner called at EOF") {
939 } else if self.ch_is('=') {
951 Ok(token::OpenDelim(token::Paren))
955 Ok(token::CloseDelim(token::Paren))
959 Ok(token::OpenDelim(token::Brace))
963 Ok(token::CloseDelim(token::Brace))
967 Ok(token::OpenDelim(token::Bracket))
971 Ok(token::CloseDelim(token::Bracket))
1004 // Multi-byte tokens.
1007 if self.ch_is('=') {
1010 } else if self.ch_is('>') {
1019 if self.ch_is('=') {
1028 match self.ch.unwrap_or('\x00') {
1034 Ok(self.binop(token::Shl))
1047 match self.ch.unwrap_or('\x00') {
1053 Ok(self.binop(token::Shr))
1061 // Either a character constant 'a' OR a lifetime name 'abc
1062 let start_with_quote = self.pos;
1064 let start = self.pos;
1066 // If the character is an ident start not followed by another single
1067 // quote, then this is a lifetime name:
1068 let starts_with_number = self.ch.unwrap_or('\x00').is_numeric();
1069 if (ident_start(self.ch) || starts_with_number) && !self.nextch_is('\'') {
1071 while ident_continue(self.ch) {
1074 // lifetimes shouldn't end with a single quote
1075 // if we find one, then this is an invalid character literal
1076 if self.ch_is('\'') {
1077 let symbol = self.name_from(start);
1079 self.validate_char_escape(start_with_quote);
1080 return Ok(Token::lit(token::Char, symbol, None));
1083 // Include the leading `'` in the real identifier, for macro
1084 // expansion purposes. See #12512 for the gory details of why
1085 // this is necessary.
1086 let ident = self.with_str_from(start_with_quote, |lifetime_name| {
1087 self.mk_ident(lifetime_name)
1090 if starts_with_number {
1091 // this is a recovered lifetime written `'1`, error but accept it
1095 "lifetimes cannot start with a number",
1099 return Ok(token::Lifetime(ident));
1101 let msg = "unterminated character literal";
1102 let symbol = self.scan_single_quoted_string(start_with_quote, msg);
1103 self.validate_char_escape(start_with_quote);
1104 let suffix = self.scan_optional_raw_name();
1105 Ok(Token::lit(token::Char, symbol, suffix))
1109 let (kind, symbol) = match self.ch {
1111 let start_with_quote = self.pos;
1113 let msg = "unterminated byte constant";
1114 let symbol = self.scan_single_quoted_string(start_with_quote, msg);
1115 self.validate_byte_escape(start_with_quote);
1116 (token::Byte, symbol)
1119 let start_with_quote = self.pos;
1120 let msg = "unterminated double quote byte string";
1121 let symbol = self.scan_double_quoted_string(msg);
1122 self.validate_byte_str_escape(start_with_quote);
1123 (token::ByteStr, symbol)
1125 Some('r') => self.scan_raw_byte_string(),
1126 _ => unreachable!(), // Should have been a token::Ident above.
1128 let suffix = self.scan_optional_raw_name();
1130 Ok(Token::lit(kind, symbol, suffix))
1133 let start_with_quote = self.pos;
1134 let msg = "unterminated double quote string";
1135 let symbol = self.scan_double_quoted_string(msg);
1136 self.validate_str_escape(start_with_quote);
1137 let suffix = self.scan_optional_raw_name();
1138 Ok(Token::lit(token::Str, symbol, suffix))
1141 let start_bpos = self.pos;
1143 let mut hash_count: u16 = 0;
1144 while self.ch_is('#') {
1145 if hash_count == 65535 {
1146 let bpos = self.next_pos;
1147 self.fatal_span_(start_bpos,
1149 "too many `#` symbols: raw strings may be \
1150 delimited by up to 65535 `#` symbols").raise();
1157 self.fail_unterminated_raw_string(start_bpos, hash_count);
1158 } else if !self.ch_is('"') {
1159 let last_bpos = self.pos;
1160 let curr_char = self.ch.unwrap();
1161 self.fatal_span_char(start_bpos,
1163 "found invalid character; only `#` is allowed \
1164 in raw string delimitation",
1168 let content_start_bpos = self.pos;
1169 let mut content_end_bpos;
1170 let mut valid = true;
1173 self.fail_unterminated_raw_string(start_bpos, hash_count);
1175 // if self.ch_is('"') {
1176 // content_end_bpos = self.pos;
1177 // for _ in 0..hash_count {
1179 // if !self.ch_is('#') {
1181 let c = self.ch.unwrap();
1184 content_end_bpos = self.pos;
1185 for _ in 0..hash_count {
1187 if !self.ch_is('#') {
1194 if !self.nextch_is('\n') {
1195 let last_bpos = self.pos;
1196 self.err_span_(start_bpos,
1198 "bare CR not allowed in raw string, use \\r \
1209 let symbol = if valid {
1210 self.name_from_to(content_start_bpos, content_end_bpos)
1212 Symbol::intern("??")
1214 let suffix = self.scan_optional_raw_name();
1216 Ok(Token::lit(token::StrRaw(hash_count), symbol, suffix))
1219 if self.nextch_is('>') {
1224 Ok(self.binop(token::Minus))
1228 if self.nextch_is('&') {
1233 Ok(self.binop(token::And))
1237 match self.nextch() {
1244 Ok(self.binop(token::Or))
1249 Ok(self.binop(token::Plus))
1252 Ok(self.binop(token::Star))
1255 Ok(self.binop(token::Slash))
1258 Ok(self.binop(token::Caret))
1261 Ok(self.binop(token::Percent))
1264 let last_bpos = self.pos;
1265 let bpos = self.next_pos;
1266 let mut err = self.struct_fatal_span_char(last_bpos,
1268 "unknown start of token",
1270 unicode_chars::check_for_substitution(self, c, &mut err);
1271 self.fatal_errs.push(err);
1278 fn read_to_eol(&mut self) -> String {
1279 let mut val = String::new();
1280 while !self.ch_is('\n') && !self.is_eof() {
1281 val.push(self.ch.unwrap());
1285 if self.ch_is('\n') {
1292 fn read_one_line_comment(&mut self) -> String {
1293 let val = self.read_to_eol();
1294 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1295 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1299 fn consume_non_eol_whitespace(&mut self) {
1300 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1305 fn peeking_at_comment(&self) -> bool {
1306 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1307 // consider shebangs comments, but not inner attributes
1308 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1311 fn scan_single_quoted_string(&mut self,
1312 start_with_quote: BytePos,
1313 unterminated_msg: &str) -> ast::Name {
1314 // assumes that first `'` is consumed
1315 let start = self.pos;
1316 // lex `'''` as a single char, for recovery
1317 if self.ch_is('\'') && self.nextch_is('\'') {
1320 let mut first = true;
1322 if self.ch_is('\'') {
1325 if self.ch_is('\\') && (self.nextch_is('\'') || self.nextch_is('\\')) {
1329 // Only attempt to infer single line string literals. If we encounter
1330 // a slash, bail out in order to avoid nonsensical suggestion when
1331 // involving comments.
1333 || (self.ch_is('/') && !first)
1334 || (self.ch_is('\n') && !self.nextch_is('\'')) {
1336 self.fatal_span_(start_with_quote, self.pos, unterminated_msg.into())
1345 let id = self.name_from(start);
1350 fn scan_double_quoted_string(&mut self, unterminated_msg: &str) -> ast::Name {
1351 debug_assert!(self.ch_is('\"'));
1352 let start_with_quote = self.pos;
1354 let start = self.pos;
1355 while !self.ch_is('"') {
1358 self.fatal_span_(start_with_quote, pos, unterminated_msg).raise();
1360 if self.ch_is('\\') && (self.nextch_is('\\') || self.nextch_is('"')) {
1365 let id = self.name_from(start);
1370 fn scan_raw_byte_string(&mut self) -> (token::LitKind, Symbol) {
1371 let start_bpos = self.pos;
1373 let mut hash_count = 0;
1374 while self.ch_is('#') {
1375 if hash_count == 65535 {
1376 let bpos = self.next_pos;
1377 self.fatal_span_(start_bpos,
1379 "too many `#` symbols: raw byte strings may be \
1380 delimited by up to 65535 `#` symbols").raise();
1387 self.fail_unterminated_raw_string(start_bpos, hash_count);
1388 } else if !self.ch_is('"') {
1390 let ch = self.ch.unwrap();
1391 self.fatal_span_char(start_bpos,
1393 "found invalid character; only `#` is allowed in raw \
1394 string delimitation",
1398 let content_start_bpos = self.pos;
1399 let mut content_end_bpos;
1403 self.fail_unterminated_raw_string(start_bpos, hash_count);
1406 content_end_bpos = self.pos;
1407 for _ in 0..hash_count {
1409 if !self.ch_is('#') {
1418 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1427 (token::ByteStrRaw(hash_count), self.name_from_to(content_start_bpos, content_end_bpos))
1430 fn validate_char_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_char(lit) {
1433 emit_unescape_error(
1434 &self.sess.span_diagnostic,
1436 self.mk_sp(start_with_quote, self.pos),
1437 unescape::Mode::Char,
1445 fn validate_byte_escape(&self, start_with_quote: BytePos) {
1446 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1447 if let Err((off, err)) = unescape::unescape_byte(lit) {
1448 emit_unescape_error(
1449 &self.sess.span_diagnostic,
1451 self.mk_sp(start_with_quote, self.pos),
1452 unescape::Mode::Byte,
1460 fn validate_str_escape(&self, start_with_quote: BytePos) {
1461 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1462 unescape::unescape_str(lit, &mut |range, c| {
1463 if let Err(err) = c {
1464 emit_unescape_error(
1465 &self.sess.span_diagnostic,
1467 self.mk_sp(start_with_quote, self.pos),
1468 unescape::Mode::Str,
1477 fn validate_byte_str_escape(&self, start_with_quote: BytePos) {
1478 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1479 unescape::unescape_byte_str(lit, &mut |range, c| {
1480 if let Err(err) = c {
1481 emit_unescape_error(
1482 &self.sess.span_diagnostic,
1484 self.mk_sp(start_with_quote, self.pos),
1485 unescape::Mode::ByteStr,
1495 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1496 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1498 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1499 c.map_or(false, Pattern_White_Space)
1503 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1504 c.map_or(false, |c| lo <= c && c <= hi)
1508 fn is_dec_digit(c: Option<char>) -> bool {
1509 in_range(c, '0', '9')
1512 fn is_doc_comment(s: &str) -> bool {
1513 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1514 s.starts_with("//!");
1515 debug!("is {:?} a doc comment? {}", s, res);
1519 fn is_block_doc_comment(s: &str) -> bool {
1520 // Prevent `/**/` from being parsed as a doc comment
1521 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1522 s.starts_with("/*!")) && s.len() >= 5;
1523 debug!("is {:?} a doc comment? {}", s, res);
1527 /// Determine whether `c` is a valid start for an ident.
1528 fn ident_start(c: Option<char>) -> bool {
1531 None => return false,
1534 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1537 fn ident_continue(c: Option<char>) -> bool {
1540 None => return false,
1543 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1544 (c > '\x7f' && c.is_xid_continue())
1548 fn char_at(s: &str, byte: usize) -> char {
1549 s[byte..].chars().next().unwrap()
1556 use crate::ast::{Ident, CrateConfig};
1557 use crate::symbol::Symbol;
1558 use crate::source_map::{SourceMap, FilePathMapping};
1559 use crate::feature_gate::UnstableFeatures;
1560 use crate::parse::token;
1561 use crate::diagnostics::plugin::ErrorMap;
1562 use crate::with_default_globals;
1564 use std::path::PathBuf;
1565 use syntax_pos::{BytePos, Span, NO_EXPANSION, edition::Edition};
1566 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
1567 use rustc_data_structures::sync::Lock;
1569 fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
1570 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1576 span_diagnostic: errors::Handler::with_emitter(true, None, Box::new(emitter)),
1577 unstable_features: UnstableFeatures::from_environment(),
1578 config: CrateConfig::default(),
1579 included_mod_stack: Lock::new(Vec::new()),
1581 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1582 raw_identifier_spans: Lock::new(Vec::new()),
1583 registered_diagnostics: Lock::new(ErrorMap::new()),
1584 buffered_lints: Lock::new(vec![]),
1585 edition: Edition::from_session(),
1586 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
1590 // open a string reader for the given string
1591 fn setup<'a>(sm: &SourceMap,
1592 sess: &'a ParseSess,
1594 -> StringReader<'a> {
1595 let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
1596 let mut sr = StringReader::new_raw(sess, sf, None);
1597 if sr.advance_token().is_err() {
1598 sr.emit_fatal_errors();
1606 with_default_globals(|| {
1607 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1608 let sh = mk_sess(sm.clone());
1609 let mut string_reader = setup(&sm,
1611 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1613 let id = Ident::from_str("fn");
1614 assert_eq!(string_reader.next_token().tok, token::Comment);
1615 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1616 let tok1 = string_reader.next_token();
1617 let tok2 = TokenAndSpan {
1618 tok: token::Ident(id, false),
1619 sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1621 assert_eq!(tok1.tok, tok2.tok);
1622 assert_eq!(tok1.sp, tok2.sp);
1623 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1624 // the 'main' id is already read:
1625 assert_eq!(string_reader.pos.clone(), BytePos(28));
1626 // read another token:
1627 let tok3 = string_reader.next_token();
1628 let tok4 = TokenAndSpan {
1629 tok: mk_ident("main"),
1630 sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1632 assert_eq!(tok3.tok, tok4.tok);
1633 assert_eq!(tok3.sp, tok4.sp);
1634 // the lparen is already read:
1635 assert_eq!(string_reader.pos.clone(), BytePos(29))
1639 // check that the given reader produces the desired stream
1640 // of tokens (stop checking after exhausting the expected vec)
1641 fn check_tokenization(mut string_reader: StringReader<'_>, expected: Vec<Token>) {
1642 for expected_tok in &expected {
1643 assert_eq!(&string_reader.next_token().tok, expected_tok);
1647 // make the identifier by looking up the string in the interner
1648 fn mk_ident(id: &str) -> Token {
1649 Token::from_ast_ident(Ident::from_str(id))
1652 fn mk_lit(kind: token::LitKind, symbol: &str, suffix: Option<&str>) -> Token {
1653 Token::lit(kind, Symbol::intern(symbol), suffix.map(Symbol::intern))
1657 fn doublecolonparsing() {
1658 with_default_globals(|| {
1659 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1660 let sh = mk_sess(sm.clone());
1661 check_tokenization(setup(&sm, &sh, "a b".to_string()),
1662 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1668 with_default_globals(|| {
1669 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1670 let sh = mk_sess(sm.clone());
1671 check_tokenization(setup(&sm, &sh, "a::b".to_string()),
1672 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1678 with_default_globals(|| {
1679 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1680 let sh = mk_sess(sm.clone());
1681 check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
1682 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
1688 with_default_globals(|| {
1689 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1690 let sh = mk_sess(sm.clone());
1691 check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
1692 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
1698 with_default_globals(|| {
1699 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1700 let sh = mk_sess(sm.clone());
1701 assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok,
1702 mk_lit(token::Char, "a", None));
1707 fn character_space() {
1708 with_default_globals(|| {
1709 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1710 let sh = mk_sess(sm.clone());
1711 assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok,
1712 mk_lit(token::Char, " ", None));
1717 fn character_escaped() {
1718 with_default_globals(|| {
1719 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1720 let sh = mk_sess(sm.clone());
1721 assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok,
1722 mk_lit(token::Char, "\\n", None));
1727 fn lifetime_name() {
1728 with_default_globals(|| {
1729 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1730 let sh = mk_sess(sm.clone());
1731 assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok,
1732 token::Lifetime(Ident::from_str("'abc")));
1738 with_default_globals(|| {
1739 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1740 let sh = mk_sess(sm.clone());
1741 assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string()).next_token().tok,
1742 mk_lit(token::StrRaw(3), "\"#a\\b\x00c\"", None));
1747 fn literal_suffixes() {
1748 with_default_globals(|| {
1749 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1750 let sh = mk_sess(sm.clone());
1752 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1753 assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token().tok,
1754 mk_lit(token::$tok_type, $tok_contents, Some("suffix")));
1755 // with a whitespace separator:
1756 assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token().tok,
1757 mk_lit(token::$tok_type, $tok_contents, None));
1761 test!("'a'", Char, "a");
1762 test!("b'a'", Byte, "a");
1763 test!("\"a\"", Str, "a");
1764 test!("b\"a\"", ByteStr, "a");
1765 test!("1234", Integer, "1234");
1766 test!("0b101", Integer, "0b101");
1767 test!("0xABC", Integer, "0xABC");
1768 test!("1.0", Float, "1.0");
1769 test!("1.0e10", Float, "1.0e10");
1771 assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token().tok,
1772 mk_lit(token::Integer, "2", Some("us")));
1773 assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
1774 mk_lit(token::StrRaw(3), "raw", Some("suffix")));
1775 assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
1776 mk_lit(token::ByteStrRaw(3), "raw", Some("suffix")));
1781 fn line_doc_comments() {
1782 assert!(is_doc_comment("///"));
1783 assert!(is_doc_comment("/// blah"));
1784 assert!(!is_doc_comment("////"));
1788 fn nested_block_comments() {
1789 with_default_globals(|| {
1790 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1791 let sh = mk_sess(sm.clone());
1792 let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
1793 match lexer.next_token().tok {
1794 token::Comment => {}
1795 _ => panic!("expected a comment!"),
1797 assert_eq!(lexer.next_token().tok, mk_lit(token::Char, "a", None));
1802 fn crlf_comments() {
1803 with_default_globals(|| {
1804 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1805 let sh = mk_sess(sm.clone());
1806 let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
1807 let comment = lexer.next_token();
1808 assert_eq!(comment.tok, token::Comment);
1809 assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
1810 assert_eq!(lexer.next_token().tok, token::Whitespace);
1811 assert_eq!(lexer.next_token().tok,
1812 token::DocComment(Symbol::intern("/// test")));