1 use crate::ast::{self, Ident};
2 use crate::parse::{token, ParseSess};
3 use crate::symbol::Symbol;
5 use errors::{Applicability, FatalError, Diagnostic, DiagnosticBuilder};
6 use syntax_pos::{BytePos, Pos, Span, NO_EXPANSION};
7 use core::unicode::property::Pattern_White_Space;
12 use std::mem::replace;
13 use rustc_data_structures::sync::Lrc;
20 #[derive(Clone, Debug)]
21 pub struct TokenAndSpan {
22 pub tok: token::Token,
26 impl Default for TokenAndSpan {
27 fn default() -> Self {
29 tok: token::Whitespace,
30 sp: syntax_pos::DUMMY_SP,
35 #[derive(Clone, Debug)]
36 pub struct UnmatchedBrace {
37 pub expected_delim: token::DelimToken,
38 pub found_delim: token::DelimToken,
40 pub unclosed_span: Option<Span>,
41 pub candidate_span: Option<Span>,
44 pub struct StringReader<'a> {
45 crate sess: &'a ParseSess,
46 /// The absolute offset within the source_map of the next character to read
47 crate next_pos: BytePos,
48 /// The absolute offset within the source_map of the current character
50 /// The current character (which has been read from self.pos)
51 crate ch: Option<char>,
52 crate source_file: Lrc<syntax_pos::SourceFile>,
53 /// Stop reading src at this index.
54 crate end_src_index: usize,
56 peek_tok: token::Token,
58 peek_span_src_raw: Span,
59 fatal_errs: Vec<DiagnosticBuilder<'a>>,
60 // cache a direct reference to the source text, so that we don't have to
61 // retrieve it via `self.source_file.src.as_ref().unwrap()` all the time.
65 /// The raw source span which *does not* take `override_span` into account
67 /// Stack of open delimiters and their spans. Used for error message.
68 open_braces: Vec<(token::DelimToken, Span)>,
69 crate unmatched_braces: Vec<UnmatchedBrace>,
70 /// The type and spans for all braces
72 /// Used only for error recovery when arriving to EOF with mismatched braces.
73 matching_delim_spans: Vec<(token::DelimToken, Span, Span)>,
74 crate override_span: Option<Span>,
75 last_unclosed_found_span: Option<Span>,
78 impl<'a> StringReader<'a> {
79 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
80 self.mk_sp_and_raw(lo, hi).0
83 fn mk_sp_and_raw(&self, lo: BytePos, hi: BytePos) -> (Span, Span) {
84 let raw = Span::new(lo, hi, NO_EXPANSION);
85 let real = self.override_span.unwrap_or(raw);
90 fn mk_ident(&self, string: &str) -> Ident {
91 let mut ident = Ident::from_str(string);
92 if let Some(span) = self.override_span {
99 fn unwrap_or_abort(&mut self, res: Result<TokenAndSpan, ()>) -> TokenAndSpan {
103 self.emit_fatal_errors();
109 fn next_token(&mut self) -> TokenAndSpan where Self: Sized {
110 let res = self.try_next_token();
111 self.unwrap_or_abort(res)
114 /// Returns the next token. EFFECT: advances the string_reader.
115 pub fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> {
116 assert!(self.fatal_errs.is_empty());
117 let ret_val = TokenAndSpan {
118 tok: replace(&mut self.peek_tok, token::Whitespace),
121 self.advance_token()?;
122 self.span_src_raw = self.peek_span_src_raw;
127 /// Immutably extract string if found at current position with given delimiters
128 fn peek_delimited(&self, from_ch: char, to_ch: char) -> Option<String> {
129 let mut pos = self.pos;
130 let mut idx = self.src_index(pos);
131 let mut ch = char_at(&self.src, idx);
135 pos = pos + Pos::from_usize(ch.len_utf8());
137 idx = self.src_index(pos);
138 while idx < self.end_src_index {
139 ch = char_at(&self.src, idx);
141 return Some(self.src[self.src_index(start_pos)..self.src_index(pos)].to_string());
143 pos = pos + Pos::from_usize(ch.len_utf8());
144 idx = self.src_index(pos);
149 fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> {
150 let mut t = self.try_next_token()?;
153 token::Whitespace | token::Comment | token::Shebang(_) => {
154 t = self.try_next_token()?;
160 self.token = t.tok.clone();
166 pub fn real_token(&mut self) -> TokenAndSpan {
167 let res = self.try_real_token();
168 self.unwrap_or_abort(res)
172 fn is_eof(&self) -> bool {
176 fn fail_unterminated_raw_string(&self, pos: BytePos, hash_count: u16) {
177 let mut err = self.struct_span_fatal(pos, pos, "unterminated raw string");
178 err.span_label(self.mk_sp(pos, pos), "unterminated raw string");
181 err.note(&format!("this raw string should be terminated with `\"{}`",
182 "#".repeat(hash_count as usize)));
189 fn fatal(&self, m: &str) -> FatalError {
190 self.fatal_span(self.peek_span, m)
193 crate fn emit_fatal_errors(&mut self) {
194 for err in &mut self.fatal_errs {
198 self.fatal_errs.clear();
201 pub fn buffer_fatal_errors(&mut self) -> Vec<Diagnostic> {
202 let mut buffer = Vec::new();
204 for err in self.fatal_errs.drain(..) {
205 err.buffer(&mut buffer);
211 pub fn peek(&self) -> TokenAndSpan {
212 // FIXME(pcwalton): Bad copy!
214 tok: self.peek_tok.clone(),
219 /// For comments.rs, which hackily pokes into next_pos and ch
220 fn new_raw(sess: &'a ParseSess,
221 source_file: Lrc<syntax_pos::SourceFile>,
222 override_span: Option<Span>) -> Self {
223 let mut sr = StringReader::new_raw_internal(sess, source_file, override_span);
229 fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc<syntax_pos::SourceFile>,
230 override_span: Option<Span>) -> Self
232 if source_file.src.is_none() {
233 sess.span_diagnostic.bug(&format!("Cannot lex source_file without source: {}",
237 let src = (*source_file.src.as_ref().unwrap()).clone();
241 next_pos: source_file.start_pos,
242 pos: source_file.start_pos,
245 end_src_index: src.len(),
246 // dummy values; not read
247 peek_tok: token::Eof,
248 peek_span: syntax_pos::DUMMY_SP,
249 peek_span_src_raw: syntax_pos::DUMMY_SP,
251 fatal_errs: Vec::new(),
253 span: syntax_pos::DUMMY_SP,
254 span_src_raw: syntax_pos::DUMMY_SP,
255 open_braces: Vec::new(),
256 unmatched_braces: Vec::new(),
257 matching_delim_spans: Vec::new(),
259 last_unclosed_found_span: None,
263 pub fn new(sess: &'a ParseSess,
264 source_file: Lrc<syntax_pos::SourceFile>,
265 override_span: Option<Span>) -> Self {
266 let mut sr = StringReader::new_raw(sess, source_file, override_span);
267 if sr.advance_token().is_err() {
268 sr.emit_fatal_errors();
275 pub fn new_or_buffered_errs(sess: &'a ParseSess,
276 source_file: Lrc<syntax_pos::SourceFile>,
277 override_span: Option<Span>) -> Result<Self, Vec<Diagnostic>> {
278 let mut sr = StringReader::new_raw(sess, source_file, override_span);
279 if sr.advance_token().is_err() {
280 Err(sr.buffer_fatal_errors())
286 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
287 let begin = sess.source_map().lookup_byte_offset(span.lo());
288 let end = sess.source_map().lookup_byte_offset(span.hi());
290 // Make the range zero-length if the span is invalid.
291 if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
292 span = span.shrink_to_lo();
295 let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
297 // Seek the lexer to the right byte range.
298 sr.next_pos = span.lo();
299 sr.end_src_index = sr.src_index(span.hi());
303 if sr.advance_token().is_err() {
304 sr.emit_fatal_errors();
312 fn ch_is(&self, c: char) -> bool {
316 /// Report a fatal lexical error with a given span.
317 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
318 self.sess.span_diagnostic.span_fatal(sp, m)
321 /// Report a lexical error with a given span.
322 fn err_span(&self, sp: Span, m: &str) {
323 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
327 /// Report a fatal error spanning [`from_pos`, `to_pos`).
328 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
329 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
332 /// Report a lexical error spanning [`from_pos`, `to_pos`).
333 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
334 self.err_span(self.mk_sp(from_pos, to_pos), m)
337 /// Pushes a character to a message string for error reporting
338 fn push_escaped_char_for_msg(m: &mut String, c: char) {
340 '\u{20}'..='\u{7e}' => {
341 // Don't escape \, ' or " for user-facing messages
345 m.extend(c.escape_default());
350 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
351 /// escaped character to the error message
352 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
353 let mut m = m.to_string();
355 Self::push_escaped_char_for_msg(&mut m, c);
357 self.fatal_span_(from_pos, to_pos, &m[..])
360 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
361 -> DiagnosticBuilder<'a>
363 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
366 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
367 -> DiagnosticBuilder<'a>
369 let mut m = m.to_string();
371 Self::push_escaped_char_for_msg(&mut m, c);
373 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
376 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
377 /// escaped character to the error message
378 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
379 let mut m = m.to_string();
381 Self::push_escaped_char_for_msg(&mut m, c);
382 self.err_span_(from_pos, to_pos, &m[..]);
385 fn struct_err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
386 -> DiagnosticBuilder<'a>
388 let mut m = m.to_string();
390 Self::push_escaped_char_for_msg(&mut m, c);
392 self.sess.span_diagnostic.struct_span_err(self.mk_sp(from_pos, to_pos), &m[..])
395 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
396 /// offending string to the error message
397 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> FatalError {
399 m.push_str(&self.src[self.src_index(from_pos)..self.src_index(to_pos)]);
401 self.fatal_span_(from_pos, to_pos, &m[..])
404 /// Advance peek_tok and peek_span to refer to the next token, and
405 /// possibly update the interner.
406 fn advance_token(&mut self) -> Result<(), ()> {
407 match self.scan_whitespace_or_comment() {
409 self.peek_span_src_raw = comment.sp;
410 self.peek_span = comment.sp;
411 self.peek_tok = comment.tok;
415 self.peek_tok = token::Eof;
416 let (real, raw) = self.mk_sp_and_raw(
417 self.source_file.end_pos,
418 self.source_file.end_pos,
420 self.peek_span = real;
421 self.peek_span_src_raw = raw;
423 let start_bytepos = self.pos;
424 self.peek_tok = self.next_token_inner()?;
425 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
426 self.peek_span = real;
427 self.peek_span_src_raw = raw;
436 fn src_index(&self, pos: BytePos) -> usize {
437 (pos - self.source_file.start_pos).to_usize()
440 /// Calls `f` with a string slice of the source text spanning from `start`
441 /// up to but excluding `self.pos`, meaning the slice does not include
442 /// the character `self.ch`.
443 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
444 where F: FnOnce(&str) -> T
446 self.with_str_from_to(start, self.pos, f)
449 /// Creates a Name from a given offset to the current offset, each
450 /// adjusted 1 towards each other (assumes that on either side there is a
451 /// single-byte delimiter).
452 fn name_from(&self, start: BytePos) -> ast::Name {
453 debug!("taking an ident from {:?} to {:?}", start, self.pos);
454 self.with_str_from(start, Symbol::intern)
457 /// As name_from, with an explicit endpoint.
458 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
459 debug!("taking an ident from {:?} to {:?}", start, end);
460 self.with_str_from_to(start, end, Symbol::intern)
463 /// Calls `f` with a string slice of the source text spanning from `start`
464 /// up to but excluding `end`.
465 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
466 where F: FnOnce(&str) -> T
468 f(&self.src[self.src_index(start)..self.src_index(end)])
471 /// Converts CRLF to LF in the given string, raising an error on bare CR.
472 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
473 let mut chars = s.char_indices().peekable();
474 while let Some((i, ch)) = chars.next() {
476 if let Some((lf_idx, '\n')) = chars.peek() {
477 return translate_crlf_(self, start, s, *lf_idx, chars, errmsg).into();
479 let pos = start + BytePos(i as u32);
480 let end_pos = start + BytePos((i + ch.len_utf8()) as u32);
481 self.err_span_(pos, end_pos, errmsg);
486 fn translate_crlf_(rdr: &StringReader<'_>,
490 mut chars: iter::Peekable<impl Iterator<Item = (usize, char)>>,
493 let mut buf = String::with_capacity(s.len());
495 buf.push_str(&s[.. j - 1]);
496 while let Some((i, ch)) = chars.next() {
499 buf.push_str(&s[j..i]);
501 let next = i + ch.len_utf8();
503 if chars.peek().map(|(_, ch)| *ch) != Some('\n') {
504 let pos = start + BytePos(i as u32);
505 let end_pos = start + BytePos(next as u32);
506 rdr.err_span_(pos, end_pos, errmsg);
511 buf.push_str(&s[j..]);
517 /// Advance the StringReader by one character.
518 crate fn bump(&mut self) {
519 let next_src_index = self.src_index(self.next_pos);
520 if next_src_index < self.end_src_index {
521 let next_ch = char_at(&self.src, next_src_index);
522 let next_ch_len = next_ch.len_utf8();
524 self.ch = Some(next_ch);
525 self.pos = self.next_pos;
526 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
529 self.pos = self.next_pos;
533 fn nextch(&self) -> Option<char> {
534 let next_src_index = self.src_index(self.next_pos);
535 if next_src_index < self.end_src_index {
536 Some(char_at(&self.src, next_src_index))
543 fn nextch_is(&self, c: char) -> bool {
544 self.nextch() == Some(c)
547 fn nextnextch(&self) -> Option<char> {
548 let next_src_index = self.src_index(self.next_pos);
549 if next_src_index < self.end_src_index {
550 let next_next_src_index =
551 next_src_index + char_at(&self.src, next_src_index).len_utf8();
552 if next_next_src_index < self.end_src_index {
553 return Some(char_at(&self.src, next_next_src_index));
560 fn nextnextch_is(&self, c: char) -> bool {
561 self.nextnextch() == Some(c)
564 /// Eats <XID_start><XID_continue>*, if possible.
565 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
566 if !ident_start(self.ch) {
570 let start = self.pos;
573 while ident_continue(self.ch) {
577 self.with_str_from(start, |string| {
579 self.sess.span_diagnostic
580 .struct_span_warn(self.mk_sp(start, self.pos),
581 "underscore literal suffix is not allowed")
582 .warn("this was previously accepted by the compiler but is \
583 being phased out; it will become a hard error in \
585 .note("for more information, see issue #42326 \
586 <https://github.com/rust-lang/rust/issues/42326>")
590 Some(Symbol::intern(string))
595 /// PRECONDITION: self.ch is not whitespace
596 /// Eats any kind of comment.
597 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
598 if let Some(c) = self.ch {
599 if c.is_whitespace() {
600 let msg = "called consume_any_line_comment, but there was whitespace";
601 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
606 match self.nextch() {
611 // line comments starting with "///" or "//!" are doc-comments
612 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
613 let start_bpos = self.pos - BytePos(2);
615 while !self.is_eof() {
616 match self.ch.unwrap() {
619 if self.nextch_is('\n') {
622 } else if doc_comment {
623 self.err_span_(self.pos,
625 "bare CR not allowed in doc-comment");
633 let tok = if doc_comment {
634 self.with_str_from(start_bpos, |string| {
635 token::DocComment(Symbol::intern(string))
640 Some(TokenAndSpan { tok, sp: self.mk_sp(start_bpos, self.pos) })
645 self.scan_block_comment()
649 } else if self.ch_is('#') {
650 if self.nextch_is('!') {
652 // Parse an inner attribute.
653 if self.nextnextch_is('[') {
657 let is_beginning_of_file = self.pos == self.source_file.start_pos;
658 if is_beginning_of_file {
659 debug!("Skipping a shebang");
660 let start = self.pos;
661 while !self.ch_is('\n') && !self.is_eof() {
664 return Some(TokenAndSpan {
665 tok: token::Shebang(self.name_from(start)),
666 sp: self.mk_sp(start, self.pos),
676 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
678 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
679 match self.ch.unwrap_or('\0') {
680 // # to handle shebang at start of file -- this is the entry point
681 // for skipping over all "junk"
683 let c = self.scan_comment();
684 debug!("scanning a comment {:?}", c);
687 c if is_pattern_whitespace(Some(c)) => {
688 let start_bpos = self.pos;
689 while is_pattern_whitespace(self.ch) {
692 let c = Some(TokenAndSpan {
693 tok: token::Whitespace,
694 sp: self.mk_sp(start_bpos, self.pos),
696 debug!("scanning whitespace: {:?}", c);
703 /// Might return a sugared-doc-attr
704 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
705 // block comments starting with "/**" or "/*!" are doc-comments
706 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
707 let start_bpos = self.pos - BytePos(2);
709 let mut level: isize = 1;
710 let mut has_cr = false;
713 let msg = if is_doc_comment {
714 "unterminated block doc-comment"
716 "unterminated block comment"
718 let last_bpos = self.pos;
719 self.fatal_span_(start_bpos, last_bpos, msg).raise();
721 let n = self.ch.unwrap();
723 '/' if self.nextch_is('*') => {
727 '*' if self.nextch_is('/') => {
739 self.with_str_from(start_bpos, |string| {
740 // but comments with only "*"s between two "/"s are not
741 let tok = if is_block_doc_comment(string) {
742 let string = if has_cr {
743 self.translate_crlf(start_bpos,
745 "bare CR not allowed in block doc-comment")
749 token::DocComment(Symbol::intern(&string[..]))
756 sp: self.mk_sp(start_bpos, self.pos),
761 /// Scan through any digits (base `scan_radix`) or underscores,
762 /// and return how many digits there were.
764 /// `real_radix` represents the true radix of the number we're
765 /// interested in, and errors will be emitted for any digits
766 /// between `real_radix` and `scan_radix`.
767 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
768 assert!(real_radix <= scan_radix);
774 debug!("skipping a _");
778 match c.and_then(|cc| cc.to_digit(scan_radix)) {
780 debug!("{:?} in scan_digits", c);
781 // check that the hypothetical digit is actually
782 // in range for the true radix
783 if c.unwrap().to_digit(real_radix).is_none() {
784 self.err_span_(self.pos,
786 &format!("invalid digit for a base {} literal", real_radix));
796 /// Lex a LIT_INTEGER or a LIT_FLOAT
797 fn scan_number(&mut self, c: char) -> token::Lit {
799 let start_bpos = self.pos;
802 let num_digits = if c == '0' {
803 match self.ch.unwrap_or('\0') {
807 self.scan_digits(2, 10)
812 self.scan_digits(8, 10)
817 self.scan_digits(16, 16)
819 '0'..='9' | '_' | '.' | 'e' | 'E' => {
820 self.scan_digits(10, 10) + 1
824 return token::Integer(self.name_from(start_bpos));
827 } else if c.is_digit(10) {
828 self.scan_digits(10, 10) + 1
834 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
836 return token::Integer(Symbol::intern("0"));
839 // might be a float, but don't be greedy if this is actually an
840 // integer literal followed by field/method access or a range pattern
841 // (`0..2` and `12.foo()`)
842 if self.ch_is('.') && !self.nextch_is('.') &&
843 !ident_start(self.nextch()) {
844 // might have stuff after the ., and if it does, it needs to start
847 if self.ch.unwrap_or('\0').is_digit(10) {
848 self.scan_digits(10, 10);
849 self.scan_float_exponent();
852 self.check_float_base(start_bpos, pos, base);
854 token::Float(self.name_from(start_bpos))
856 // it might be a float if it has an exponent
857 if self.ch_is('e') || self.ch_is('E') {
858 self.scan_float_exponent();
860 self.check_float_base(start_bpos, pos, base);
861 return token::Float(self.name_from(start_bpos));
863 // but we certainly have an integer!
864 token::Integer(self.name_from(start_bpos))
868 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
869 /// error if too many or too few digits are encountered.
870 fn scan_hex_digits(&mut self, n_digits: usize, delim: char, below_0x7f_only: bool) -> bool {
871 debug!("scanning {} digits until {:?}", n_digits, delim);
872 let start_bpos = self.pos;
873 let mut accum_int = 0;
875 let mut valid = true;
876 for _ in 0..n_digits {
878 let last_bpos = self.pos;
879 self.fatal_span_(start_bpos,
881 "unterminated numeric character escape").raise();
883 if self.ch_is(delim) {
884 let last_bpos = self.pos;
885 self.err_span_(start_bpos,
887 "numeric character escape is too short");
891 let c = self.ch.unwrap_or('\x00');
893 accum_int += c.to_digit(16).unwrap_or_else(|| {
894 self.err_span_char(self.pos,
896 "invalid character in numeric character escape",
905 if below_0x7f_only && accum_int >= 0x80 {
906 self.err_span_(start_bpos,
908 "this form of character escape may only be used with characters in \
909 the range [\\x00-\\x7f]");
913 match char::from_u32(accum_int) {
916 let last_bpos = self.pos;
917 self.err_span_(start_bpos, last_bpos, "invalid numeric character escape");
923 /// Scan for a single (possibly escaped) byte or char
924 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
925 /// `start` is the position of `first_source_char`, which is already consumed.
927 /// Returns `true` if there was a valid char/byte.
928 fn scan_char_or_byte(&mut self,
930 first_source_char: char,
935 match first_source_char {
937 // '\X' for some X must be a character constant:
938 let escaped = self.ch;
939 let escaped_pos = self.pos;
942 None => {} // EOF here is an error that will be checked later.
945 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
946 'x' => self.scan_byte_escape(delim, !ascii_only),
948 let valid = if self.ch_is('{') {
949 self.scan_unicode_escape(delim) && !ascii_only
951 let span = self.mk_sp(start, self.pos);
952 let mut suggestion = "\\u{".to_owned();
953 let msg = "incorrect unicode escape sequence";
954 let mut err = self.sess.span_diagnostic.struct_span_err(
959 while let (Some(ch), true) = (self.ch, i < 6) {
969 suggestion.push('}');
971 self.mk_sp(start, self.pos),
972 "format of unicode escape sequences uses braces",
974 Applicability::MaybeIncorrect,
977 err.span_label(span, msg);
979 "format of unicode escape sequences is `\\u{...}`",
986 self.err_span_(start,
988 "unicode escape sequences cannot be used as a \
989 byte or in a byte string");
994 '\n' if delim == '"' => {
995 self.consume_whitespace();
998 '\r' if delim == '"' && self.ch_is('\n') => {
999 self.consume_whitespace();
1004 let msg = if ascii_only {
1005 "unknown byte escape"
1007 "unknown character escape"
1009 let mut err = self.struct_err_span_char(escaped_pos, pos, msg, c);
1010 err.span_label(self.mk_sp(escaped_pos, pos), msg);
1013 "this is an isolated carriage return; consider checking \
1014 your editor and version control settings",
1017 if (e == '{' || e == '}') && !ascii_only {
1019 "if used in a formatting string, curly braces are escaped \
1020 with `{{` and `}}`",
1030 '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
1032 self.err_span_char(start,
1035 "byte constant must be escaped"
1037 "character constant must be escaped"
1043 if self.ch_is('\n') {
1047 self.err_span_(start,
1049 "bare CR not allowed in string, use \\r instead");
1054 if ascii_only && first_source_char > '\x7F' {
1056 self.err_span_(start,
1058 "byte constant must be ASCII. Use a \\xHH escape for a \
1067 /// Scan over a `\u{...}` escape
1069 /// At this point, we have already seen the `\` and the `u`, the `{` is the current character.
1070 /// We will read a hex number (with `_` separators), with 1 to 6 actual digits,
1071 /// and pass over the `}`.
1072 fn scan_unicode_escape(&mut self, delim: char) -> bool {
1073 self.bump(); // past the {
1074 let start_bpos = self.pos;
1075 let mut valid = true;
1077 if let Some('_') = self.ch {
1078 // disallow leading `_`
1079 self.err_span_(self.pos,
1081 "invalid start of unicode escape");
1085 let count = self.scan_digits(16, 16);
1088 self.err_span_(start_bpos,
1090 "overlong unicode escape (must have at most 6 hex digits)");
1097 if valid && count == 0 {
1098 self.err_span_(start_bpos,
1100 "empty unicode escape (must have at least 1 hex digit)");
1103 self.bump(); // past the ending `}`
1108 self.err_span_(self.pos,
1110 "unterminated unicode escape (needed a `}`)");
1114 self.err_span_char(start_bpos,
1116 "invalid character in unicode escape",
1122 self.fatal_span_(start_bpos,
1124 "unterminated unicode escape (found EOF)").raise();
1133 /// Scan over a float exponent.
1134 fn scan_float_exponent(&mut self) {
1135 if self.ch_is('e') || self.ch_is('E') {
1138 if self.ch_is('-') || self.ch_is('+') {
1142 if self.scan_digits(10, 10) == 0 {
1143 let mut err = self.struct_span_fatal(
1144 self.pos, self.next_pos,
1145 "expected at least one digit in exponent"
1147 if let Some(ch) = self.ch {
1148 // check for e.g., Unicode minus '−' (Issue #49746)
1149 if unicode_chars::check_for_substitution(self, ch, &mut err) {
1151 self.scan_digits(10, 10);
1159 /// Checks that a base is valid for a floating literal, emitting a nice
1160 /// error if it isn't.
1161 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
1164 self.err_span_(start_bpos,
1166 "hexadecimal float literal is not supported")
1169 self.err_span_(start_bpos,
1171 "octal float literal is not supported")
1174 self.err_span_(start_bpos,
1176 "binary float literal is not supported")
1182 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
1184 if self.ch_is('=') {
1192 /// Returns the next token from the string, advances the input past that
1193 /// token, and updates the interner
1194 fn next_token_inner(&mut self) -> Result<token::Token, ()> {
1198 let (is_ident_start, is_raw_ident) =
1199 match (c.unwrap(), self.nextch(), self.nextnextch()) {
1200 // r# followed by an identifier starter is a raw identifier.
1201 // This is an exception to the r# case below.
1202 ('r', Some('#'), x) if ident_start(x) => (true, true),
1203 // r as in r" or r#" is part of a raw string literal.
1204 // b as in b' is part of a byte literal.
1205 // They are not identifiers, and are handled further down.
1206 ('r', Some('"'), _) |
1207 ('r', Some('#'), _) |
1208 ('b', Some('"'), _) |
1209 ('b', Some('\''), _) |
1210 ('b', Some('r'), Some('"')) |
1211 ('b', Some('r'), Some('#')) => (false, false),
1216 let raw_start = self.pos;
1218 // Consume the 'r#' characters.
1223 let start = self.pos;
1226 while ident_continue(self.ch) {
1230 return Ok(self.with_str_from(start, |string| {
1231 // FIXME: perform NFKC normalization here. (Issue #2253)
1232 let ident = self.mk_ident(string);
1235 let span = self.mk_sp(raw_start, self.pos);
1236 if !ident.can_be_raw() {
1237 self.err_span(span, &format!("`{}` cannot be a raw identifier", ident));
1239 self.sess.raw_identifier_spans.borrow_mut().push(span);
1242 token::Ident(ident, is_raw_ident)
1247 if is_dec_digit(c) {
1248 let num = self.scan_number(c.unwrap());
1249 let suffix = self.scan_optional_raw_name();
1250 debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
1251 return Ok(token::Literal(num, suffix));
1254 match c.expect("next_token_inner called at EOF") {
1266 if self.ch_is('.') {
1268 if self.ch_is('.') {
1270 Ok(token::DotDotDot)
1271 } else if self.ch_is('=') {
1283 Ok(token::OpenDelim(token::Paren))
1287 Ok(token::CloseDelim(token::Paren))
1291 Ok(token::OpenDelim(token::Brace))
1295 Ok(token::CloseDelim(token::Brace))
1299 Ok(token::OpenDelim(token::Bracket))
1303 Ok(token::CloseDelim(token::Bracket))
1323 if self.ch_is(':') {
1336 // Multi-byte tokens.
1339 if self.ch_is('=') {
1342 } else if self.ch_is('>') {
1351 if self.ch_is('=') {
1360 match self.ch.unwrap_or('\x00') {
1366 Ok(self.binop(token::Shl))
1379 match self.ch.unwrap_or('\x00') {
1385 Ok(self.binop(token::Shr))
1393 // Either a character constant 'a' OR a lifetime name 'abc
1394 let start_with_quote = self.pos;
1396 let start = self.pos;
1398 // the eof will be picked up by the final `'` check below
1399 let c2 = self.ch.unwrap_or('\x00');
1402 // If the character is an ident start not followed by another single
1403 // quote, then this is a lifetime name:
1404 if (ident_start(Some(c2)) || c2.is_numeric()) && !self.ch_is('\'') {
1405 while ident_continue(self.ch) {
1408 // lifetimes shouldn't end with a single quote
1409 // if we find one, then this is an invalid character literal
1410 if self.ch_is('\'') {
1414 "character literal may only contain one codepoint");
1416 return Ok(token::Literal(token::Err(Symbol::intern("??")), None))
1420 // Include the leading `'` in the real identifier, for macro
1421 // expansion purposes. See #12512 for the gory details of why
1422 // this is necessary.
1423 let ident = self.with_str_from(start, |lifetime_name| {
1424 self.mk_ident(&format!("'{}", lifetime_name))
1427 if c2.is_numeric() {
1428 // this is a recovered lifetime written `'1`, error but accept it
1432 "lifetimes cannot start with a number",
1436 return Ok(token::Lifetime(ident));
1439 let valid = self.scan_char_or_byte(start, c2, /* ascii_only */ false, '\'');
1441 if !self.ch_is('\'') {
1446 if self.ch_is('\'') {
1447 let start = self.src_index(start);
1448 let end = self.src_index(self.pos);
1450 let span = self.mk_sp(start_with_quote, self.pos);
1451 self.sess.span_diagnostic
1452 .struct_span_err(span,
1453 "character literal may only contain one codepoint")
1456 "if you meant to write a `str` literal, use double quotes",
1457 format!("\"{}\"", &self.src[start..end]),
1458 Applicability::MachineApplicable
1460 return Ok(token::Literal(token::Err(Symbol::intern("??")), None))
1462 if self.ch_is('\n') || self.is_eof() || self.ch_is('/') {
1463 // Only attempt to infer single line string literals. If we encounter
1464 // a slash, bail out in order to avoid nonsensical suggestion when
1465 // involving comments.
1470 self.fatal_span_verbose(start_with_quote, pos,
1471 String::from("character literal may only contain one codepoint")).raise();
1475 self.name_from(start)
1480 self.bump(); // advance ch past token
1481 let suffix = self.scan_optional_raw_name();
1483 Ok(token::Literal(token::Char(id), suffix))
1487 let lit = match self.ch {
1488 Some('\'') => self.scan_byte(),
1489 Some('"') => self.scan_byte_string(),
1490 Some('r') => self.scan_raw_byte_string(),
1491 _ => unreachable!(), // Should have been a token::Ident above.
1493 let suffix = self.scan_optional_raw_name();
1495 Ok(token::Literal(lit, suffix))
1498 let start_bpos = self.pos;
1499 let mut valid = true;
1502 while !self.ch_is('"') {
1504 let last_bpos = self.pos;
1505 self.fatal_span_(start_bpos,
1507 "unterminated double quote string").raise();
1510 let ch_start = self.pos;
1511 let ch = self.ch.unwrap();
1513 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only */ false, '"');
1515 // adjust for the ASCII " at the start of the literal
1517 self.name_from(start_bpos + BytePos(1))
1519 Symbol::intern("??")
1522 let suffix = self.scan_optional_raw_name();
1524 Ok(token::Literal(token::Str_(id), suffix))
1527 let start_bpos = self.pos;
1529 let mut hash_count: u16 = 0;
1530 while self.ch_is('#') {
1531 if hash_count == 65535 {
1532 let bpos = self.next_pos;
1533 self.fatal_span_(start_bpos,
1535 "too many `#` symbols: raw strings may be \
1536 delimited by up to 65535 `#` symbols").raise();
1543 self.fail_unterminated_raw_string(start_bpos, hash_count);
1544 } else if !self.ch_is('"') {
1545 let last_bpos = self.pos;
1546 let curr_char = self.ch.unwrap();
1547 self.fatal_span_char(start_bpos,
1549 "found invalid character; only `#` is allowed \
1550 in raw string delimitation",
1554 let content_start_bpos = self.pos;
1555 let mut content_end_bpos;
1556 let mut valid = true;
1559 self.fail_unterminated_raw_string(start_bpos, hash_count);
1561 // if self.ch_is('"') {
1562 // content_end_bpos = self.pos;
1563 // for _ in 0..hash_count {
1565 // if !self.ch_is('#') {
1567 let c = self.ch.unwrap();
1570 content_end_bpos = self.pos;
1571 for _ in 0..hash_count {
1573 if !self.ch_is('#') {
1580 if !self.nextch_is('\n') {
1581 let last_bpos = self.pos;
1582 self.err_span_(start_bpos,
1584 "bare CR not allowed in raw string, use \\r \
1596 self.name_from_to(content_start_bpos, content_end_bpos)
1598 Symbol::intern("??")
1600 let suffix = self.scan_optional_raw_name();
1602 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1605 if self.nextch_is('>') {
1610 Ok(self.binop(token::Minus))
1614 if self.nextch_is('&') {
1619 Ok(self.binop(token::And))
1623 match self.nextch() {
1630 Ok(self.binop(token::Or))
1635 Ok(self.binop(token::Plus))
1638 Ok(self.binop(token::Star))
1641 Ok(self.binop(token::Slash))
1644 Ok(self.binop(token::Caret))
1647 Ok(self.binop(token::Percent))
1650 let last_bpos = self.pos;
1651 let bpos = self.next_pos;
1652 let mut err = self.struct_fatal_span_char(last_bpos,
1654 "unknown start of token",
1656 unicode_chars::check_for_substitution(self, c, &mut err);
1657 self.fatal_errs.push(err);
1664 fn consume_whitespace(&mut self) {
1665 while is_pattern_whitespace(self.ch) && !self.is_eof() {
1670 fn read_to_eol(&mut self) -> String {
1671 let mut val = String::new();
1672 while !self.ch_is('\n') && !self.is_eof() {
1673 val.push(self.ch.unwrap());
1677 if self.ch_is('\n') {
1684 fn read_one_line_comment(&mut self) -> String {
1685 let val = self.read_to_eol();
1686 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1687 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1691 fn consume_non_eol_whitespace(&mut self) {
1692 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1697 fn peeking_at_comment(&self) -> bool {
1698 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1699 // consider shebangs comments, but not inner attributes
1700 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1703 fn scan_byte(&mut self) -> token::Lit {
1705 let start = self.pos;
1707 // the eof will be picked up by the final `'` check below
1708 let c2 = self.ch.unwrap_or('\x00');
1711 let valid = self.scan_char_or_byte(start,
1716 if !self.ch_is('\'') {
1717 // Byte offsetting here is okay because the
1718 // character before position `start` are an
1719 // ascii single quote and ascii 'b'.
1721 self.fatal_span_verbose(start - BytePos(2),
1723 "unterminated byte constant".to_string()).raise();
1727 self.name_from(start)
1731 self.bump(); // advance ch past token
1737 fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1738 self.scan_hex_digits(2, delim, below_0x7f_only)
1741 fn scan_byte_string(&mut self) -> token::Lit {
1743 let start = self.pos;
1744 let mut valid = true;
1746 while !self.ch_is('"') {
1749 self.fatal_span_(start, pos, "unterminated double quote byte string").raise();
1752 let ch_start = self.pos;
1753 let ch = self.ch.unwrap();
1755 valid &= self.scan_char_or_byte(ch_start,
1763 self.name_from(start)
1765 Symbol::intern("??")
1772 fn scan_raw_byte_string(&mut self) -> token::Lit {
1773 let start_bpos = self.pos;
1775 let mut hash_count = 0;
1776 while self.ch_is('#') {
1777 if hash_count == 65535 {
1778 let bpos = self.next_pos;
1779 self.fatal_span_(start_bpos,
1781 "too many `#` symbols: raw byte strings may be \
1782 delimited by up to 65535 `#` symbols").raise();
1789 self.fail_unterminated_raw_string(start_bpos, hash_count);
1790 } else if !self.ch_is('"') {
1792 let ch = self.ch.unwrap();
1793 self.fatal_span_char(start_bpos,
1795 "found invalid character; only `#` is allowed in raw \
1796 string delimitation",
1800 let content_start_bpos = self.pos;
1801 let mut content_end_bpos;
1805 self.fail_unterminated_raw_string(start_bpos, hash_count);
1808 content_end_bpos = self.pos;
1809 for _ in 0..hash_count {
1811 if !self.ch_is('#') {
1820 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1829 token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), hash_count)
1833 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1834 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1836 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1837 c.map_or(false, Pattern_White_Space)
1841 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1842 c.map_or(false, |c| lo <= c && c <= hi)
1846 fn is_dec_digit(c: Option<char>) -> bool {
1847 in_range(c, '0', '9')
1850 fn is_doc_comment(s: &str) -> bool {
1851 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1852 s.starts_with("//!");
1853 debug!("is {:?} a doc comment? {}", s, res);
1857 fn is_block_doc_comment(s: &str) -> bool {
1858 // Prevent `/**/` from being parsed as a doc comment
1859 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1860 s.starts_with("/*!")) && s.len() >= 5;
1861 debug!("is {:?} a doc comment? {}", s, res);
1865 /// Determine whether `c` is a valid start for an ident.
1866 fn ident_start(c: Option<char>) -> bool {
1869 None => return false,
1872 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1875 fn ident_continue(c: Option<char>) -> bool {
1878 None => return false,
1881 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1882 (c > '\x7f' && c.is_xid_continue())
1886 fn char_at(s: &str, byte: usize) -> char {
1887 s[byte..].chars().next().unwrap()
1894 use crate::ast::{Ident, CrateConfig};
1895 use crate::symbol::Symbol;
1896 use crate::source_map::{SourceMap, FilePathMapping};
1897 use crate::feature_gate::UnstableFeatures;
1898 use crate::parse::token;
1899 use crate::diagnostics::plugin::ErrorMap;
1900 use crate::with_globals;
1902 use std::path::PathBuf;
1903 use syntax_pos::{BytePos, Span, NO_EXPANSION};
1904 use rustc_data_structures::fx::FxHashSet;
1905 use rustc_data_structures::sync::Lock;
1907 fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
1908 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1914 span_diagnostic: errors::Handler::with_emitter(true, None, Box::new(emitter)),
1915 unstable_features: UnstableFeatures::from_environment(),
1916 config: CrateConfig::default(),
1917 included_mod_stack: Lock::new(Vec::new()),
1919 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1920 raw_identifier_spans: Lock::new(Vec::new()),
1921 registered_diagnostics: Lock::new(ErrorMap::new()),
1922 buffered_lints: Lock::new(vec![]),
1926 // open a string reader for the given string
1927 fn setup<'a>(sm: &SourceMap,
1928 sess: &'a ParseSess,
1930 -> StringReader<'a> {
1931 let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
1932 StringReader::new(sess, sf, None)
1938 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1939 let sh = mk_sess(sm.clone());
1940 let mut string_reader = setup(&sm,
1942 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1944 let id = Ident::from_str("fn");
1945 assert_eq!(string_reader.next_token().tok, token::Comment);
1946 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1947 let tok1 = string_reader.next_token();
1948 let tok2 = TokenAndSpan {
1949 tok: token::Ident(id, false),
1950 sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1952 assert_eq!(tok1.tok, tok2.tok);
1953 assert_eq!(tok1.sp, tok2.sp);
1954 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1955 // the 'main' id is already read:
1956 assert_eq!(string_reader.pos.clone(), BytePos(28));
1957 // read another token:
1958 let tok3 = string_reader.next_token();
1959 let tok4 = TokenAndSpan {
1960 tok: mk_ident("main"),
1961 sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1963 assert_eq!(tok3.tok, tok4.tok);
1964 assert_eq!(tok3.sp, tok4.sp);
1965 // the lparen is already read:
1966 assert_eq!(string_reader.pos.clone(), BytePos(29))
1970 // check that the given reader produces the desired stream
1971 // of tokens (stop checking after exhausting the expected vec)
1972 fn check_tokenization(mut string_reader: StringReader<'_>, expected: Vec<token::Token>) {
1973 for expected_tok in &expected {
1974 assert_eq!(&string_reader.next_token().tok, expected_tok);
1978 // make the identifier by looking up the string in the interner
1979 fn mk_ident(id: &str) -> token::Token {
1980 token::Token::from_ast_ident(Ident::from_str(id))
1984 fn doublecolonparsing() {
1986 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1987 let sh = mk_sess(sm.clone());
1988 check_tokenization(setup(&sm, &sh, "a b".to_string()),
1989 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1996 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1997 let sh = mk_sess(sm.clone());
1998 check_tokenization(setup(&sm, &sh, "a::b".to_string()),
1999 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
2006 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2007 let sh = mk_sess(sm.clone());
2008 check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
2009 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
2016 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2017 let sh = mk_sess(sm.clone());
2018 check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
2019 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
2026 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2027 let sh = mk_sess(sm.clone());
2028 assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok,
2029 token::Literal(token::Char(Symbol::intern("a")), None));
2034 fn character_space() {
2036 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2037 let sh = mk_sess(sm.clone());
2038 assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok,
2039 token::Literal(token::Char(Symbol::intern(" ")), None));
2044 fn character_escaped() {
2046 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2047 let sh = mk_sess(sm.clone());
2048 assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok,
2049 token::Literal(token::Char(Symbol::intern("\\n")), None));
2054 fn lifetime_name() {
2056 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2057 let sh = mk_sess(sm.clone());
2058 assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok,
2059 token::Lifetime(Ident::from_str("'abc")));
2066 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2067 let sh = mk_sess(sm.clone());
2068 assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
2071 token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
2076 fn literal_suffixes() {
2078 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2079 let sh = mk_sess(sm.clone());
2081 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
2082 assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token().tok,
2083 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2084 Some(Symbol::intern("suffix"))));
2085 // with a whitespace separator:
2086 assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token().tok,
2087 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2092 test!("'a'", Char, "a");
2093 test!("b'a'", Byte, "a");
2094 test!("\"a\"", Str_, "a");
2095 test!("b\"a\"", ByteStr, "a");
2096 test!("1234", Integer, "1234");
2097 test!("0b101", Integer, "0b101");
2098 test!("0xABC", Integer, "0xABC");
2099 test!("1.0", Float, "1.0");
2100 test!("1.0e10", Float, "1.0e10");
2102 assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token().tok,
2103 token::Literal(token::Integer(Symbol::intern("2")),
2104 Some(Symbol::intern("us"))));
2105 assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
2106 token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
2107 Some(Symbol::intern("suffix"))));
2108 assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
2109 token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
2110 Some(Symbol::intern("suffix"))));
2115 fn line_doc_comments() {
2116 assert!(is_doc_comment("///"));
2117 assert!(is_doc_comment("/// blah"));
2118 assert!(!is_doc_comment("////"));
2122 fn nested_block_comments() {
2124 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2125 let sh = mk_sess(sm.clone());
2126 let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
2127 match lexer.next_token().tok {
2128 token::Comment => {}
2129 _ => panic!("expected a comment!"),
2131 assert_eq!(lexer.next_token().tok,
2132 token::Literal(token::Char(Symbol::intern("a")), None));
2137 fn crlf_comments() {
2139 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2140 let sh = mk_sess(sm.clone());
2141 let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
2142 let comment = lexer.next_token();
2143 assert_eq!(comment.tok, token::Comment);
2144 assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
2145 assert_eq!(lexer.next_token().tok, token::Whitespace);
2146 assert_eq!(lexer.next_token().tok,
2147 token::DocComment(Symbol::intern("/// test")));