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(sess: &'a ParseSess,
266 source_file: Lrc<syntax_pos::SourceFile>,
267 override_span: Option<Span>) -> Self {
268 let mut sr = StringReader::new_raw(sess, source_file, override_span);
269 if sr.advance_token().is_err() {
270 sr.emit_fatal_errors();
277 pub fn new_or_buffered_errs(sess: &'a ParseSess,
278 source_file: Lrc<syntax_pos::SourceFile>,
279 override_span: Option<Span>) -> Result<Self, Vec<Diagnostic>> {
280 let mut sr = StringReader::new_raw(sess, source_file, override_span);
281 if sr.advance_token().is_err() {
282 Err(sr.buffer_fatal_errors())
288 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
289 let begin = sess.source_map().lookup_byte_offset(span.lo());
290 let end = sess.source_map().lookup_byte_offset(span.hi());
292 // Make the range zero-length if the span is invalid.
293 if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
294 span = span.shrink_to_lo();
297 let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
299 // Seek the lexer to the right byte range.
300 sr.next_pos = span.lo();
301 sr.end_src_index = sr.src_index(span.hi());
305 if sr.advance_token().is_err() {
306 sr.emit_fatal_errors();
314 fn ch_is(&self, c: char) -> bool {
318 /// Report a fatal lexical error with a given span.
319 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
320 self.sess.span_diagnostic.span_fatal(sp, m)
323 /// Report a lexical error with a given span.
324 fn err_span(&self, sp: Span, m: &str) {
325 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
329 /// Report a fatal error spanning [`from_pos`, `to_pos`).
330 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
331 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
334 /// Report a lexical error spanning [`from_pos`, `to_pos`).
335 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
336 self.err_span(self.mk_sp(from_pos, to_pos), m)
339 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
340 /// escaped character to the error message
341 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
342 let mut m = m.to_string();
344 push_escaped_char(&mut m, c);
346 self.fatal_span_(from_pos, to_pos, &m[..])
349 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
350 -> DiagnosticBuilder<'a>
352 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
355 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
356 -> DiagnosticBuilder<'a>
358 let mut m = m.to_string();
360 push_escaped_char(&mut m, c);
362 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
365 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
366 /// escaped character to the error message
367 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
368 let mut m = m.to_string();
370 push_escaped_char(&mut m, c);
371 self.err_span_(from_pos, to_pos, &m[..]);
374 /// Advance peek_tok and peek_span to refer to the next token, and
375 /// possibly update the interner.
376 fn advance_token(&mut self) -> Result<(), ()> {
377 match self.scan_whitespace_or_comment() {
379 self.peek_span_src_raw = comment.sp;
380 self.peek_span = comment.sp;
381 self.peek_tok = comment.tok;
385 self.peek_tok = token::Eof;
386 let (real, raw) = self.mk_sp_and_raw(
387 self.source_file.end_pos,
388 self.source_file.end_pos,
390 self.peek_span = real;
391 self.peek_span_src_raw = raw;
393 let start_bytepos = self.pos;
394 self.peek_tok = self.next_token_inner()?;
395 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
396 self.peek_span = real;
397 self.peek_span_src_raw = raw;
406 fn src_index(&self, pos: BytePos) -> usize {
407 (pos - self.source_file.start_pos).to_usize()
410 /// Calls `f` with a string slice of the source text spanning from `start`
411 /// up to but excluding `self.pos`, meaning the slice does not include
412 /// the character `self.ch`.
413 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
414 where F: FnOnce(&str) -> T
416 self.with_str_from_to(start, self.pos, f)
419 /// Creates a Name from a given offset to the current offset.
420 fn name_from(&self, start: BytePos) -> ast::Name {
421 debug!("taking an ident from {:?} to {:?}", start, self.pos);
422 self.with_str_from(start, Symbol::intern)
425 /// As name_from, with an explicit endpoint.
426 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
427 debug!("taking an ident from {:?} to {:?}", start, end);
428 self.with_str_from_to(start, end, Symbol::intern)
431 /// Calls `f` with a string slice of the source text spanning from `start`
432 /// up to but excluding `end`.
433 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
434 where F: FnOnce(&str) -> T
436 f(&self.src[self.src_index(start)..self.src_index(end)])
439 /// Converts CRLF to LF in the given string, raising an error on bare CR.
440 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
441 let mut chars = s.char_indices().peekable();
442 while let Some((i, ch)) = chars.next() {
444 if let Some((lf_idx, '\n')) = chars.peek() {
445 return translate_crlf_(self, start, s, *lf_idx, chars, errmsg).into();
447 let pos = start + BytePos(i as u32);
448 let end_pos = start + BytePos((i + ch.len_utf8()) as u32);
449 self.err_span_(pos, end_pos, errmsg);
454 fn translate_crlf_(rdr: &StringReader<'_>,
458 mut chars: iter::Peekable<impl Iterator<Item = (usize, char)>>,
461 let mut buf = String::with_capacity(s.len());
463 buf.push_str(&s[.. j - 1]);
464 while let Some((i, ch)) = chars.next() {
467 buf.push_str(&s[j..i]);
469 let next = i + ch.len_utf8();
471 if chars.peek().map(|(_, ch)| *ch) != Some('\n') {
472 let pos = start + BytePos(i as u32);
473 let end_pos = start + BytePos(next as u32);
474 rdr.err_span_(pos, end_pos, errmsg);
479 buf.push_str(&s[j..]);
485 /// Advance the StringReader by one character.
486 crate fn bump(&mut self) {
487 let next_src_index = self.src_index(self.next_pos);
488 if next_src_index < self.end_src_index {
489 let next_ch = char_at(&self.src, next_src_index);
490 let next_ch_len = next_ch.len_utf8();
492 self.ch = Some(next_ch);
493 self.pos = self.next_pos;
494 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
497 self.pos = self.next_pos;
501 fn nextch(&self) -> Option<char> {
502 let next_src_index = self.src_index(self.next_pos);
503 if next_src_index < self.end_src_index {
504 Some(char_at(&self.src, next_src_index))
511 fn nextch_is(&self, c: char) -> bool {
512 self.nextch() == Some(c)
515 fn nextnextch(&self) -> Option<char> {
516 let next_src_index = self.src_index(self.next_pos);
517 if next_src_index < self.end_src_index {
518 let next_next_src_index =
519 next_src_index + char_at(&self.src, next_src_index).len_utf8();
520 if next_next_src_index < self.end_src_index {
521 return Some(char_at(&self.src, next_next_src_index));
528 fn nextnextch_is(&self, c: char) -> bool {
529 self.nextnextch() == Some(c)
532 /// Eats <XID_start><XID_continue>*, if possible.
533 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
534 if !ident_start(self.ch) {
538 let start = self.pos;
541 while ident_continue(self.ch) {
545 self.with_str_from(start, |string| {
547 self.sess.span_diagnostic
548 .struct_span_warn(self.mk_sp(start, self.pos),
549 "underscore literal suffix is not allowed")
550 .warn("this was previously accepted by the compiler but is \
551 being phased out; it will become a hard error in \
553 .note("for more information, see issue #42326 \
554 <https://github.com/rust-lang/rust/issues/42326>")
558 Some(Symbol::intern(string))
563 /// PRECONDITION: self.ch is not whitespace
564 /// Eats any kind of comment.
565 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
566 if let Some(c) = self.ch {
567 if c.is_whitespace() {
568 let msg = "called consume_any_line_comment, but there was whitespace";
569 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
574 match self.nextch() {
579 // line comments starting with "///" or "//!" are doc-comments
580 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
581 let start_bpos = self.pos - BytePos(2);
583 while !self.is_eof() {
584 match self.ch.unwrap() {
587 if self.nextch_is('\n') {
590 } else if doc_comment {
591 self.err_span_(self.pos,
593 "bare CR not allowed in doc-comment");
601 let tok = if doc_comment {
602 self.with_str_from(start_bpos, |string| {
603 token::DocComment(Symbol::intern(string))
608 Some(TokenAndSpan { tok, sp: self.mk_sp(start_bpos, self.pos) })
613 self.scan_block_comment()
617 } else if self.ch_is('#') {
618 if self.nextch_is('!') {
620 // Parse an inner attribute.
621 if self.nextnextch_is('[') {
625 let is_beginning_of_file = self.pos == self.source_file.start_pos;
626 if is_beginning_of_file {
627 debug!("Skipping a shebang");
628 let start = self.pos;
629 while !self.ch_is('\n') && !self.is_eof() {
632 return Some(TokenAndSpan {
633 tok: token::Shebang(self.name_from(start)),
634 sp: self.mk_sp(start, self.pos),
644 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
646 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
647 match self.ch.unwrap_or('\0') {
648 // # to handle shebang at start of file -- this is the entry point
649 // for skipping over all "junk"
651 let c = self.scan_comment();
652 debug!("scanning a comment {:?}", c);
655 c if is_pattern_whitespace(Some(c)) => {
656 let start_bpos = self.pos;
657 while is_pattern_whitespace(self.ch) {
660 let c = Some(TokenAndSpan {
661 tok: token::Whitespace,
662 sp: self.mk_sp(start_bpos, self.pos),
664 debug!("scanning whitespace: {:?}", c);
671 /// Might return a sugared-doc-attr
672 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
673 // block comments starting with "/**" or "/*!" are doc-comments
674 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
675 let start_bpos = self.pos - BytePos(2);
677 let mut level: isize = 1;
678 let mut has_cr = false;
681 let msg = if is_doc_comment {
682 "unterminated block doc-comment"
684 "unterminated block comment"
686 let last_bpos = self.pos;
687 self.fatal_span_(start_bpos, last_bpos, msg).raise();
689 let n = self.ch.unwrap();
691 '/' if self.nextch_is('*') => {
695 '*' if self.nextch_is('/') => {
707 self.with_str_from(start_bpos, |string| {
708 // but comments with only "*"s between two "/"s are not
709 let tok = if is_block_doc_comment(string) {
710 let string = if has_cr {
711 self.translate_crlf(start_bpos,
713 "bare CR not allowed in block doc-comment")
717 token::DocComment(Symbol::intern(&string[..]))
724 sp: self.mk_sp(start_bpos, self.pos),
729 /// Scan through any digits (base `scan_radix`) or underscores,
730 /// and return how many digits there were.
732 /// `real_radix` represents the true radix of the number we're
733 /// interested in, and errors will be emitted for any digits
734 /// between `real_radix` and `scan_radix`.
735 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
736 assert!(real_radix <= scan_radix);
742 debug!("skipping a _");
746 match c.and_then(|cc| cc.to_digit(scan_radix)) {
748 debug!("{:?} in scan_digits", c);
749 // check that the hypothetical digit is actually
750 // in range for the true radix
751 if c.unwrap().to_digit(real_radix).is_none() {
752 self.err_span_(self.pos,
754 &format!("invalid digit for a base {} literal", real_radix));
764 /// Lex a LIT_INTEGER or a LIT_FLOAT
765 fn scan_number(&mut self, c: char) -> token::Lit {
767 let start_bpos = self.pos;
770 let num_digits = if c == '0' {
771 match self.ch.unwrap_or('\0') {
775 self.scan_digits(2, 10)
780 self.scan_digits(8, 10)
785 self.scan_digits(16, 16)
787 '0'..='9' | '_' | '.' | 'e' | 'E' => {
788 self.scan_digits(10, 10) + 1
792 return token::Integer(self.name_from(start_bpos));
795 } else if c.is_digit(10) {
796 self.scan_digits(10, 10) + 1
802 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
804 return token::Integer(Symbol::intern("0"));
807 // might be a float, but don't be greedy if this is actually an
808 // integer literal followed by field/method access or a range pattern
809 // (`0..2` and `12.foo()`)
810 if self.ch_is('.') && !self.nextch_is('.') &&
811 !ident_start(self.nextch()) {
812 // might have stuff after the ., and if it does, it needs to start
815 if self.ch.unwrap_or('\0').is_digit(10) {
816 self.scan_digits(10, 10);
817 self.scan_float_exponent();
820 self.check_float_base(start_bpos, pos, base);
822 token::Float(self.name_from(start_bpos))
824 // it might be a float if it has an exponent
825 if self.ch_is('e') || self.ch_is('E') {
826 self.scan_float_exponent();
828 self.check_float_base(start_bpos, pos, base);
829 return token::Float(self.name_from(start_bpos));
831 // but we certainly have an integer!
832 token::Integer(self.name_from(start_bpos))
836 /// Scan over a float exponent.
837 fn scan_float_exponent(&mut self) {
838 if self.ch_is('e') || self.ch_is('E') {
841 if self.ch_is('-') || self.ch_is('+') {
845 if self.scan_digits(10, 10) == 0 {
846 let mut err = self.struct_span_fatal(
847 self.pos, self.next_pos,
848 "expected at least one digit in exponent"
850 if let Some(ch) = self.ch {
851 // check for e.g., Unicode minus '−' (Issue #49746)
852 if unicode_chars::check_for_substitution(self, ch, &mut err) {
854 self.scan_digits(10, 10);
862 /// Checks that a base is valid for a floating literal, emitting a nice
863 /// error if it isn't.
864 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
867 self.err_span_(start_bpos,
869 "hexadecimal float literal is not supported")
872 self.err_span_(start_bpos,
874 "octal float literal is not supported")
877 self.err_span_(start_bpos,
879 "binary float literal is not supported")
885 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
895 /// Returns the next token from the string, advances the input past that
896 /// token, and updates the interner
897 fn next_token_inner(&mut self) -> Result<token::Token, ()> {
901 let (is_ident_start, is_raw_ident) =
902 match (c.unwrap(), self.nextch(), self.nextnextch()) {
903 // r# followed by an identifier starter is a raw identifier.
904 // This is an exception to the r# case below.
905 ('r', Some('#'), x) if ident_start(x) => (true, true),
906 // r as in r" or r#" is part of a raw string literal.
907 // b as in b' is part of a byte literal.
908 // They are not identifiers, and are handled further down.
909 ('r', Some('"'), _) |
910 ('r', Some('#'), _) |
911 ('b', Some('"'), _) |
912 ('b', Some('\''), _) |
913 ('b', Some('r'), Some('"')) |
914 ('b', Some('r'), Some('#')) => (false, false),
919 let raw_start = self.pos;
921 // Consume the 'r#' characters.
926 let start = self.pos;
929 while ident_continue(self.ch) {
933 return Ok(self.with_str_from(start, |string| {
934 // FIXME: perform NFKC normalization here. (Issue #2253)
935 let ident = self.mk_ident(string);
938 let span = self.mk_sp(raw_start, self.pos);
939 if !ident.can_be_raw() {
940 self.err_span(span, &format!("`{}` cannot be a raw identifier", ident));
942 self.sess.raw_identifier_spans.borrow_mut().push(span);
945 token::Ident(ident, is_raw_ident)
951 let num = self.scan_number(c.unwrap());
952 let suffix = self.scan_optional_raw_name();
953 debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
954 return Ok(token::Literal(num, suffix));
957 match c.expect("next_token_inner called at EOF") {
974 } else if self.ch_is('=') {
986 Ok(token::OpenDelim(token::Paren))
990 Ok(token::CloseDelim(token::Paren))
994 Ok(token::OpenDelim(token::Brace))
998 Ok(token::CloseDelim(token::Brace))
1002 Ok(token::OpenDelim(token::Bracket))
1006 Ok(token::CloseDelim(token::Bracket))
1026 if self.ch_is(':') {
1039 // Multi-byte tokens.
1042 if self.ch_is('=') {
1045 } else if self.ch_is('>') {
1054 if self.ch_is('=') {
1063 match self.ch.unwrap_or('\x00') {
1069 Ok(self.binop(token::Shl))
1082 match self.ch.unwrap_or('\x00') {
1088 Ok(self.binop(token::Shr))
1096 // Either a character constant 'a' OR a lifetime name 'abc
1097 let start_with_quote = self.pos;
1099 let start = self.pos;
1101 // If the character is an ident start not followed by another single
1102 // quote, then this is a lifetime name:
1103 let starts_with_number = self.ch.unwrap_or('\x00').is_numeric();
1104 if (ident_start(self.ch) || starts_with_number) && !self.nextch_is('\'') {
1106 while ident_continue(self.ch) {
1109 // lifetimes shouldn't end with a single quote
1110 // if we find one, then this is an invalid character literal
1111 if self.ch_is('\'') {
1112 let id = self.name_from(start);
1114 self.validate_char_escape(start_with_quote);
1115 return Ok(token::Literal(token::Char(id), None))
1118 // Include the leading `'` in the real identifier, for macro
1119 // expansion purposes. See #12512 for the gory details of why
1120 // this is necessary.
1121 let ident = self.with_str_from(start_with_quote, |lifetime_name| {
1122 self.mk_ident(lifetime_name)
1125 if starts_with_number {
1126 // this is a recovered lifetime written `'1`, error but accept it
1130 "lifetimes cannot start with a number",
1134 return Ok(token::Lifetime(ident));
1136 let msg = "unterminated character literal";
1137 let id = self.scan_single_quoted_string(start_with_quote, msg);
1138 self.validate_char_escape(start_with_quote);
1139 let suffix = self.scan_optional_raw_name();
1140 Ok(token::Literal(token::Char(id), suffix))
1144 let lit = match self.ch {
1146 let start_with_quote = self.pos;
1148 let msg = "unterminated byte constant";
1149 let id = self.scan_single_quoted_string(start_with_quote, msg);
1150 self.validate_byte_escape(start_with_quote);
1154 let start_with_quote = self.pos;
1155 let msg = "unterminated double quote byte string";
1156 let id = self.scan_double_quoted_string(msg);
1157 self.validate_byte_str_escape(start_with_quote);
1160 Some('r') => self.scan_raw_byte_string(),
1161 _ => unreachable!(), // Should have been a token::Ident above.
1163 let suffix = self.scan_optional_raw_name();
1165 Ok(token::Literal(lit, suffix))
1168 let start_with_quote = self.pos;
1169 let msg = "unterminated double quote string";
1170 let id = self.scan_double_quoted_string(msg);
1171 self.validate_str_escape(start_with_quote);
1172 let suffix = self.scan_optional_raw_name();
1173 Ok(token::Literal(token::Str_(id), suffix))
1176 let start_bpos = self.pos;
1178 let mut hash_count: u16 = 0;
1179 while self.ch_is('#') {
1180 if hash_count == 65535 {
1181 let bpos = self.next_pos;
1182 self.fatal_span_(start_bpos,
1184 "too many `#` symbols: raw strings may be \
1185 delimited by up to 65535 `#` symbols").raise();
1192 self.fail_unterminated_raw_string(start_bpos, hash_count);
1193 } else if !self.ch_is('"') {
1194 let last_bpos = self.pos;
1195 let curr_char = self.ch.unwrap();
1196 self.fatal_span_char(start_bpos,
1198 "found invalid character; only `#` is allowed \
1199 in raw string delimitation",
1203 let content_start_bpos = self.pos;
1204 let mut content_end_bpos;
1205 let mut valid = true;
1208 self.fail_unterminated_raw_string(start_bpos, hash_count);
1210 // if self.ch_is('"') {
1211 // content_end_bpos = self.pos;
1212 // for _ in 0..hash_count {
1214 // if !self.ch_is('#') {
1216 let c = self.ch.unwrap();
1219 content_end_bpos = self.pos;
1220 for _ in 0..hash_count {
1222 if !self.ch_is('#') {
1229 if !self.nextch_is('\n') {
1230 let last_bpos = self.pos;
1231 self.err_span_(start_bpos,
1233 "bare CR not allowed in raw string, use \\r \
1245 self.name_from_to(content_start_bpos, content_end_bpos)
1247 Symbol::intern("??")
1249 let suffix = self.scan_optional_raw_name();
1251 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1254 if self.nextch_is('>') {
1259 Ok(self.binop(token::Minus))
1263 if self.nextch_is('&') {
1268 Ok(self.binop(token::And))
1272 match self.nextch() {
1279 Ok(self.binop(token::Or))
1284 Ok(self.binop(token::Plus))
1287 Ok(self.binop(token::Star))
1290 Ok(self.binop(token::Slash))
1293 Ok(self.binop(token::Caret))
1296 Ok(self.binop(token::Percent))
1299 let last_bpos = self.pos;
1300 let bpos = self.next_pos;
1301 let mut err = self.struct_fatal_span_char(last_bpos,
1303 "unknown start of token",
1305 unicode_chars::check_for_substitution(self, c, &mut err);
1306 self.fatal_errs.push(err);
1313 fn read_to_eol(&mut self) -> String {
1314 let mut val = String::new();
1315 while !self.ch_is('\n') && !self.is_eof() {
1316 val.push(self.ch.unwrap());
1320 if self.ch_is('\n') {
1327 fn read_one_line_comment(&mut self) -> String {
1328 let val = self.read_to_eol();
1329 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1330 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1334 fn consume_non_eol_whitespace(&mut self) {
1335 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1340 fn peeking_at_comment(&self) -> bool {
1341 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1342 // consider shebangs comments, but not inner attributes
1343 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1346 fn scan_single_quoted_string(&mut self,
1347 start_with_quote: BytePos,
1348 unterminated_msg: &str) -> ast::Name {
1349 // assumes that first `'` is consumed
1350 let start = self.pos;
1351 // lex `'''` as a single char, for recovery
1352 if self.ch_is('\'') && self.nextch_is('\'') {
1355 let mut first = true;
1357 if self.ch_is('\'') {
1360 if self.ch_is('\\') && (self.nextch_is('\'') || self.nextch_is('\\')) {
1364 // Only attempt to infer single line string literals. If we encounter
1365 // a slash, bail out in order to avoid nonsensical suggestion when
1366 // involving comments.
1368 || (self.ch_is('/') && !first)
1369 || (self.ch_is('\n') && !self.nextch_is('\'')) {
1371 self.fatal_span_(start_with_quote, self.pos, unterminated_msg.into())
1380 let id = self.name_from(start);
1385 fn scan_double_quoted_string(&mut self, unterminated_msg: &str) -> ast::Name {
1386 debug_assert!(self.ch_is('\"'));
1387 let start_with_quote = self.pos;
1389 let start = self.pos;
1390 while !self.ch_is('"') {
1393 self.fatal_span_(start_with_quote, pos, unterminated_msg).raise();
1395 if self.ch_is('\\') && (self.nextch_is('\\') || self.nextch_is('"')) {
1400 let id = self.name_from(start);
1405 fn scan_raw_byte_string(&mut self) -> token::Lit {
1406 let start_bpos = self.pos;
1408 let mut hash_count = 0;
1409 while self.ch_is('#') {
1410 if hash_count == 65535 {
1411 let bpos = self.next_pos;
1412 self.fatal_span_(start_bpos,
1414 "too many `#` symbols: raw byte strings may be \
1415 delimited by up to 65535 `#` symbols").raise();
1422 self.fail_unterminated_raw_string(start_bpos, hash_count);
1423 } else if !self.ch_is('"') {
1425 let ch = self.ch.unwrap();
1426 self.fatal_span_char(start_bpos,
1428 "found invalid character; only `#` is allowed in raw \
1429 string delimitation",
1433 let content_start_bpos = self.pos;
1434 let mut content_end_bpos;
1438 self.fail_unterminated_raw_string(start_bpos, hash_count);
1441 content_end_bpos = self.pos;
1442 for _ in 0..hash_count {
1444 if !self.ch_is('#') {
1453 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1462 token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), hash_count)
1465 fn validate_char_escape(&self, start_with_quote: BytePos) {
1466 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1467 if let Err((off, err)) = unescape::unescape_char(lit) {
1468 emit_unescape_error(
1469 &self.sess.span_diagnostic,
1471 self.mk_sp(start_with_quote, self.pos),
1472 unescape::Mode::Char,
1480 fn validate_byte_escape(&self, start_with_quote: BytePos) {
1481 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1482 if let Err((off, err)) = unescape::unescape_byte(lit) {
1483 emit_unescape_error(
1484 &self.sess.span_diagnostic,
1486 self.mk_sp(start_with_quote, self.pos),
1487 unescape::Mode::Byte,
1495 fn validate_str_escape(&self, start_with_quote: BytePos) {
1496 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1497 unescape::unescape_str(lit, &mut |range, c| {
1498 if let Err(err) = c {
1499 emit_unescape_error(
1500 &self.sess.span_diagnostic,
1502 self.mk_sp(start_with_quote, self.pos),
1503 unescape::Mode::Str,
1512 fn validate_byte_str_escape(&self, start_with_quote: BytePos) {
1513 self.with_str_from_to(start_with_quote + BytePos(1), self.pos - BytePos(1), |lit| {
1514 unescape::unescape_byte_str(lit, &mut |range, c| {
1515 if let Err(err) = c {
1516 emit_unescape_error(
1517 &self.sess.span_diagnostic,
1519 self.mk_sp(start_with_quote, self.pos),
1520 unescape::Mode::ByteStr,
1530 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1531 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1533 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1534 c.map_or(false, Pattern_White_Space)
1538 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1539 c.map_or(false, |c| lo <= c && c <= hi)
1543 fn is_dec_digit(c: Option<char>) -> bool {
1544 in_range(c, '0', '9')
1547 fn is_doc_comment(s: &str) -> bool {
1548 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1549 s.starts_with("//!");
1550 debug!("is {:?} a doc comment? {}", s, res);
1554 fn is_block_doc_comment(s: &str) -> bool {
1555 // Prevent `/**/` from being parsed as a doc comment
1556 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1557 s.starts_with("/*!")) && s.len() >= 5;
1558 debug!("is {:?} a doc comment? {}", s, res);
1562 /// Determine whether `c` is a valid start for an ident.
1563 fn ident_start(c: Option<char>) -> bool {
1566 None => return false,
1569 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1572 fn ident_continue(c: Option<char>) -> bool {
1575 None => return false,
1578 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1579 (c > '\x7f' && c.is_xid_continue())
1583 fn char_at(s: &str, byte: usize) -> char {
1584 s[byte..].chars().next().unwrap()
1591 use crate::ast::{Ident, CrateConfig};
1592 use crate::symbol::Symbol;
1593 use crate::source_map::{SourceMap, FilePathMapping};
1594 use crate::feature_gate::UnstableFeatures;
1595 use crate::parse::token;
1596 use crate::diagnostics::plugin::ErrorMap;
1597 use crate::with_globals;
1599 use std::path::PathBuf;
1600 use syntax_pos::{BytePos, Span, NO_EXPANSION};
1601 use rustc_data_structures::fx::FxHashSet;
1602 use rustc_data_structures::sync::Lock;
1604 fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
1605 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1611 span_diagnostic: errors::Handler::with_emitter(true, None, Box::new(emitter)),
1612 unstable_features: UnstableFeatures::from_environment(),
1613 config: CrateConfig::default(),
1614 included_mod_stack: Lock::new(Vec::new()),
1616 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1617 raw_identifier_spans: Lock::new(Vec::new()),
1618 registered_diagnostics: Lock::new(ErrorMap::new()),
1619 buffered_lints: Lock::new(vec![]),
1623 // open a string reader for the given string
1624 fn setup<'a>(sm: &SourceMap,
1625 sess: &'a ParseSess,
1627 -> StringReader<'a> {
1628 let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
1629 StringReader::new(sess, sf, None)
1635 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1636 let sh = mk_sess(sm.clone());
1637 let mut string_reader = setup(&sm,
1639 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1641 let id = Ident::from_str("fn");
1642 assert_eq!(string_reader.next_token().tok, token::Comment);
1643 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1644 let tok1 = string_reader.next_token();
1645 let tok2 = TokenAndSpan {
1646 tok: token::Ident(id, false),
1647 sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1649 assert_eq!(tok1.tok, tok2.tok);
1650 assert_eq!(tok1.sp, tok2.sp);
1651 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1652 // the 'main' id is already read:
1653 assert_eq!(string_reader.pos.clone(), BytePos(28));
1654 // read another token:
1655 let tok3 = string_reader.next_token();
1656 let tok4 = TokenAndSpan {
1657 tok: mk_ident("main"),
1658 sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1660 assert_eq!(tok3.tok, tok4.tok);
1661 assert_eq!(tok3.sp, tok4.sp);
1662 // the lparen is already read:
1663 assert_eq!(string_reader.pos.clone(), BytePos(29))
1667 // check that the given reader produces the desired stream
1668 // of tokens (stop checking after exhausting the expected vec)
1669 fn check_tokenization(mut string_reader: StringReader<'_>, expected: Vec<token::Token>) {
1670 for expected_tok in &expected {
1671 assert_eq!(&string_reader.next_token().tok, expected_tok);
1675 // make the identifier by looking up the string in the interner
1676 fn mk_ident(id: &str) -> token::Token {
1677 token::Token::from_ast_ident(Ident::from_str(id))
1681 fn doublecolonparsing() {
1683 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1684 let sh = mk_sess(sm.clone());
1685 check_tokenization(setup(&sm, &sh, "a b".to_string()),
1686 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1693 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1694 let sh = mk_sess(sm.clone());
1695 check_tokenization(setup(&sm, &sh, "a::b".to_string()),
1696 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1703 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1704 let sh = mk_sess(sm.clone());
1705 check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
1706 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
1713 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1714 let sh = mk_sess(sm.clone());
1715 check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
1716 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
1723 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1724 let sh = mk_sess(sm.clone());
1725 assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok,
1726 token::Literal(token::Char(Symbol::intern("a")), None));
1731 fn character_space() {
1733 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1734 let sh = mk_sess(sm.clone());
1735 assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok,
1736 token::Literal(token::Char(Symbol::intern(" ")), None));
1741 fn character_escaped() {
1743 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1744 let sh = mk_sess(sm.clone());
1745 assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok,
1746 token::Literal(token::Char(Symbol::intern("\\n")), None));
1751 fn lifetime_name() {
1753 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1754 let sh = mk_sess(sm.clone());
1755 assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok,
1756 token::Lifetime(Ident::from_str("'abc")));
1763 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1764 let sh = mk_sess(sm.clone());
1765 assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
1768 token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
1773 fn literal_suffixes() {
1775 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1776 let sh = mk_sess(sm.clone());
1778 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1779 assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token().tok,
1780 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
1781 Some(Symbol::intern("suffix"))));
1782 // with a whitespace separator:
1783 assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token().tok,
1784 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
1789 test!("'a'", Char, "a");
1790 test!("b'a'", Byte, "a");
1791 test!("\"a\"", Str_, "a");
1792 test!("b\"a\"", ByteStr, "a");
1793 test!("1234", Integer, "1234");
1794 test!("0b101", Integer, "0b101");
1795 test!("0xABC", Integer, "0xABC");
1796 test!("1.0", Float, "1.0");
1797 test!("1.0e10", Float, "1.0e10");
1799 assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token().tok,
1800 token::Literal(token::Integer(Symbol::intern("2")),
1801 Some(Symbol::intern("us"))));
1802 assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
1803 token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
1804 Some(Symbol::intern("suffix"))));
1805 assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
1806 token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
1807 Some(Symbol::intern("suffix"))));
1812 fn line_doc_comments() {
1813 assert!(is_doc_comment("///"));
1814 assert!(is_doc_comment("/// blah"));
1815 assert!(!is_doc_comment("////"));
1819 fn nested_block_comments() {
1821 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1822 let sh = mk_sess(sm.clone());
1823 let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
1824 match lexer.next_token().tok {
1825 token::Comment => {}
1826 _ => panic!("expected a comment!"),
1828 assert_eq!(lexer.next_token().tok,
1829 token::Literal(token::Char(Symbol::intern("a")), None));
1834 fn crlf_comments() {
1836 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1837 let sh = mk_sess(sm.clone());
1838 let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
1839 let comment = lexer.next_token();
1840 assert_eq!(comment.tok, token::Comment);
1841 assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
1842 assert_eq!(lexer.next_token().tok, token::Whitespace);
1843 assert_eq!(lexer.next_token().tok,
1844 token::DocComment(Symbol::intern("/// test")));