1 use crate::ast::{self, Ident};
2 use crate::source_map::{SourceMap, FilePathMapping};
3 use crate::parse::{token, ParseSess};
4 use crate::symbol::{Symbol, keywords};
6 use errors::{Applicability, FatalError, Diagnostic, DiagnosticBuilder};
7 use syntax_pos::{BytePos, CharPos, Pos, Span, NO_EXPANSION};
8 use core::unicode::property::Pattern_White_Space;
13 use std::mem::replace;
14 use rustc_data_structures::sync::Lrc;
21 #[derive(Clone, Debug)]
22 pub struct TokenAndSpan {
23 pub tok: token::Token,
27 impl Default for TokenAndSpan {
28 fn default() -> Self {
30 tok: token::Whitespace,
31 sp: syntax_pos::DUMMY_SP,
36 #[derive(Clone, Debug)]
37 pub struct UnmatchedBrace {
38 pub expected_delim: token::DelimToken,
39 pub found_delim: token::DelimToken,
41 pub unclosed_span: Option<Span>,
42 pub candidate_span: Option<Span>,
45 pub struct StringReader<'a> {
46 pub sess: &'a ParseSess,
47 /// The absolute offset within the source_map of the next character to read
48 pub next_pos: BytePos,
49 /// The absolute offset within the source_map of the current character
51 /// The current character (which has been read from self.pos)
53 pub source_file: Lrc<syntax_pos::SourceFile>,
54 /// Stop reading src at this index.
55 pub end_src_index: usize,
57 peek_tok: token::Token,
59 peek_span_src_raw: Span,
60 fatal_errs: Vec<DiagnosticBuilder<'a>>,
61 // cache a direct reference to the source text, so that we don't have to
62 // retrieve it via `self.source_file.src.as_ref().unwrap()` all the time.
66 /// The raw source span which *does not* take `override_span` into account
68 /// Stack of open delimiters and their spans. Used for error message.
69 open_braces: Vec<(token::DelimToken, Span)>,
70 crate unmatched_braces: Vec<UnmatchedBrace>,
71 /// The type and spans for all braces
73 /// Used only for error recovery when arriving to EOF with mismatched braces.
74 matching_delim_spans: Vec<(token::DelimToken, Span, Span)>,
75 crate override_span: Option<Span>,
76 last_unclosed_found_span: Option<Span>,
79 impl<'a> StringReader<'a> {
80 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
81 self.mk_sp_and_raw(lo, hi).0
84 fn mk_sp_and_raw(&self, lo: BytePos, hi: BytePos) -> (Span, Span) {
85 let raw = Span::new(lo, hi, NO_EXPANSION);
86 let real = self.override_span.unwrap_or(raw);
91 fn mk_ident(&self, string: &str) -> Ident {
92 let mut ident = Ident::from_str(string);
93 if let Some(span) = self.override_span {
100 fn unwrap_or_abort(&mut self, res: Result<TokenAndSpan, ()>) -> TokenAndSpan {
104 self.emit_fatal_errors();
110 fn next_token(&mut self) -> TokenAndSpan where Self: Sized {
111 let res = self.try_next_token();
112 self.unwrap_or_abort(res)
115 /// Returns the next token. EFFECT: advances the string_reader.
116 pub fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> {
117 assert!(self.fatal_errs.is_empty());
118 let ret_val = TokenAndSpan {
119 tok: replace(&mut self.peek_tok, token::Whitespace),
122 self.advance_token()?;
123 self.span_src_raw = self.peek_span_src_raw;
128 fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> {
129 let mut t = self.try_next_token()?;
132 token::Whitespace | token::Comment | token::Shebang(_) => {
133 t = self.try_next_token()?;
139 self.token = t.tok.clone();
145 pub fn real_token(&mut self) -> TokenAndSpan {
146 let res = self.try_real_token();
147 self.unwrap_or_abort(res)
151 fn is_eof(&self) -> bool {
155 fn fail_unterminated_raw_string(&self, pos: BytePos, hash_count: u16) {
156 let mut err = self.struct_span_fatal(pos, pos, "unterminated raw string");
157 err.span_label(self.mk_sp(pos, pos), "unterminated raw string");
160 err.note(&format!("this raw string should be terminated with `\"{}`",
161 "#".repeat(hash_count as usize)));
168 fn fatal(&self, m: &str) -> FatalError {
169 self.fatal_span(self.peek_span, m)
172 pub fn emit_fatal_errors(&mut self) {
173 for err in &mut self.fatal_errs {
177 self.fatal_errs.clear();
180 pub fn buffer_fatal_errors(&mut self) -> Vec<Diagnostic> {
181 let mut buffer = Vec::new();
183 for err in self.fatal_errs.drain(..) {
184 err.buffer(&mut buffer);
190 pub fn peek(&self) -> TokenAndSpan {
191 // FIXME(pcwalton): Bad copy!
193 tok: self.peek_tok.clone(),
198 /// For comments.rs, which hackily pokes into next_pos and ch
199 fn new_raw(sess: &'a ParseSess,
200 source_file: Lrc<syntax_pos::SourceFile>,
201 override_span: Option<Span>) -> Self {
202 let mut sr = StringReader::new_raw_internal(sess, source_file, override_span);
208 fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc<syntax_pos::SourceFile>,
209 override_span: Option<Span>) -> Self
211 if source_file.src.is_none() {
212 sess.span_diagnostic.bug(&format!("Cannot lex source_file without source: {}",
216 let src = (*source_file.src.as_ref().unwrap()).clone();
220 next_pos: source_file.start_pos,
221 pos: source_file.start_pos,
224 end_src_index: src.len(),
225 // dummy values; not read
226 peek_tok: token::Eof,
227 peek_span: syntax_pos::DUMMY_SP,
228 peek_span_src_raw: syntax_pos::DUMMY_SP,
230 fatal_errs: Vec::new(),
232 span: syntax_pos::DUMMY_SP,
233 span_src_raw: syntax_pos::DUMMY_SP,
234 open_braces: Vec::new(),
235 unmatched_braces: Vec::new(),
236 matching_delim_spans: Vec::new(),
238 last_unclosed_found_span: None,
242 pub fn new(sess: &'a ParseSess,
243 source_file: Lrc<syntax_pos::SourceFile>,
244 override_span: Option<Span>) -> Self {
245 let mut sr = StringReader::new_raw(sess, source_file, override_span);
246 if sr.advance_token().is_err() {
247 sr.emit_fatal_errors();
254 pub fn new_or_buffered_errs(sess: &'a ParseSess,
255 source_file: Lrc<syntax_pos::SourceFile>,
256 override_span: Option<Span>) -> Result<Self, Vec<Diagnostic>> {
257 let mut sr = StringReader::new_raw(sess, source_file, override_span);
258 if sr.advance_token().is_err() {
259 Err(sr.buffer_fatal_errors())
265 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
266 let begin = sess.source_map().lookup_byte_offset(span.lo());
267 let end = sess.source_map().lookup_byte_offset(span.hi());
269 // Make the range zero-length if the span is invalid.
270 if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
271 span = span.shrink_to_lo();
274 let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
276 // Seek the lexer to the right byte range.
277 sr.next_pos = span.lo();
278 sr.end_src_index = sr.src_index(span.hi());
282 if sr.advance_token().is_err() {
283 sr.emit_fatal_errors();
291 fn ch_is(&self, c: char) -> bool {
295 /// Report a fatal lexical error with a given span.
296 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
297 self.sess.span_diagnostic.span_fatal(sp, m)
300 /// Report a lexical error with a given span.
301 fn err_span(&self, sp: Span, m: &str) {
302 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
306 /// Report a fatal error spanning [`from_pos`, `to_pos`).
307 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
308 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
311 /// Report a lexical error spanning [`from_pos`, `to_pos`).
312 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
313 self.err_span(self.mk_sp(from_pos, to_pos), m)
316 /// Pushes a character to a message string for error reporting
317 fn push_escaped_char_for_msg(m: &mut String, c: char) {
319 '\u{20}'..='\u{7e}' => {
320 // Don't escape \, ' or " for user-facing messages
324 m.extend(c.escape_default());
329 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
330 /// escaped character to the error message
331 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
332 let mut m = m.to_string();
334 Self::push_escaped_char_for_msg(&mut m, c);
336 self.fatal_span_(from_pos, to_pos, &m[..])
339 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
340 -> DiagnosticBuilder<'a>
342 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
345 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
346 -> DiagnosticBuilder<'a>
348 let mut m = m.to_string();
350 Self::push_escaped_char_for_msg(&mut m, c);
352 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
355 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
356 /// escaped character to the error message
357 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
358 let mut m = m.to_string();
360 Self::push_escaped_char_for_msg(&mut m, c);
361 self.err_span_(from_pos, to_pos, &m[..]);
364 fn struct_err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
365 -> DiagnosticBuilder<'a>
367 let mut m = m.to_string();
369 Self::push_escaped_char_for_msg(&mut m, c);
371 self.sess.span_diagnostic.struct_span_err(self.mk_sp(from_pos, to_pos), &m[..])
374 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
375 /// offending string to the error message
376 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> FatalError {
378 m.push_str(&self.src[self.src_index(from_pos)..self.src_index(to_pos)]);
380 self.fatal_span_(from_pos, to_pos, &m[..])
383 /// Advance peek_tok and peek_span to refer to the next token, and
384 /// possibly update the interner.
385 fn advance_token(&mut self) -> Result<(), ()> {
386 match self.scan_whitespace_or_comment() {
388 self.peek_span_src_raw = comment.sp;
389 self.peek_span = comment.sp;
390 self.peek_tok = comment.tok;
394 self.peek_tok = token::Eof;
395 let (real, raw) = self.mk_sp_and_raw(
396 self.source_file.end_pos,
397 self.source_file.end_pos,
399 self.peek_span = real;
400 self.peek_span_src_raw = raw;
402 let start_bytepos = self.pos;
403 self.peek_tok = self.next_token_inner()?;
404 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
405 self.peek_span = real;
406 self.peek_span_src_raw = raw;
415 fn src_index(&self, pos: BytePos) -> usize {
416 (pos - self.source_file.start_pos).to_usize()
419 /// Calls `f` with a string slice of the source text spanning from `start`
420 /// up to but excluding `self.pos`, meaning the slice does not include
421 /// the character `self.ch`.
422 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
423 where F: FnOnce(&str) -> T
425 self.with_str_from_to(start, self.pos, f)
428 /// Creates a Name from a given offset to the current offset, each
429 /// adjusted 1 towards each other (assumes that on either side there is a
430 /// single-byte delimiter).
431 fn name_from(&self, start: BytePos) -> ast::Name {
432 debug!("taking an ident from {:?} to {:?}", start, self.pos);
433 self.with_str_from(start, Symbol::intern)
436 /// As name_from, with an explicit endpoint.
437 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
438 debug!("taking an ident from {:?} to {:?}", start, end);
439 self.with_str_from_to(start, end, Symbol::intern)
442 /// Calls `f` with a string slice of the source text spanning from `start`
443 /// up to but excluding `end`.
444 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
445 where F: FnOnce(&str) -> T
447 f(&self.src[self.src_index(start)..self.src_index(end)])
450 /// Converts CRLF to LF in the given string, raising an error on bare CR.
451 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
452 let mut chars = s.char_indices().peekable();
453 while let Some((i, ch)) = chars.next() {
455 if let Some((lf_idx, '\n')) = chars.peek() {
456 return translate_crlf_(self, start, s, *lf_idx, chars, errmsg).into();
458 let pos = start + BytePos(i as u32);
459 let end_pos = start + BytePos((i + ch.len_utf8()) as u32);
460 self.err_span_(pos, end_pos, errmsg);
465 fn translate_crlf_(rdr: &StringReader<'_>,
469 mut chars: iter::Peekable<impl Iterator<Item = (usize, char)>>,
472 let mut buf = String::with_capacity(s.len());
474 buf.push_str(&s[.. j - 1]);
475 while let Some((i, ch)) = chars.next() {
478 buf.push_str(&s[j..i]);
480 let next = i + ch.len_utf8();
482 if chars.peek().map(|(_, ch)| *ch) != Some('\n') {
483 let pos = start + BytePos(i as u32);
484 let end_pos = start + BytePos(next as u32);
485 rdr.err_span_(pos, end_pos, errmsg);
490 buf.push_str(&s[j..]);
496 /// Advance the StringReader by one character.
497 crate fn bump(&mut self) {
498 let next_src_index = self.src_index(self.next_pos);
499 if next_src_index < self.end_src_index {
500 let next_ch = char_at(&self.src, next_src_index);
501 let next_ch_len = next_ch.len_utf8();
503 self.ch = Some(next_ch);
504 self.pos = self.next_pos;
505 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
508 self.pos = self.next_pos;
512 fn nextch(&self) -> Option<char> {
513 let next_src_index = self.src_index(self.next_pos);
514 if next_src_index < self.end_src_index {
515 Some(char_at(&self.src, next_src_index))
522 fn nextch_is(&self, c: char) -> bool {
523 self.nextch() == Some(c)
526 fn nextnextch(&self) -> Option<char> {
527 let next_src_index = self.src_index(self.next_pos);
528 if next_src_index < self.end_src_index {
529 let next_next_src_index =
530 next_src_index + char_at(&self.src, next_src_index).len_utf8();
531 if next_next_src_index < self.end_src_index {
532 return Some(char_at(&self.src, next_next_src_index));
539 fn nextnextch_is(&self, c: char) -> bool {
540 self.nextnextch() == Some(c)
543 /// Eats <XID_start><XID_continue>*, if possible.
544 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
545 if !ident_start(self.ch) {
549 let start = self.pos;
552 while ident_continue(self.ch) {
556 self.with_str_from(start, |string| {
558 self.sess.span_diagnostic
559 .struct_span_warn(self.mk_sp(start, self.pos),
560 "underscore literal suffix is not allowed")
561 .warn("this was previously accepted by the compiler but is \
562 being phased out; it will become a hard error in \
564 .note("for more information, see issue #42326 \
565 <https://github.com/rust-lang/rust/issues/42326>")
569 Some(Symbol::intern(string))
574 /// PRECONDITION: self.ch is not whitespace
575 /// Eats any kind of comment.
576 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
577 if let Some(c) = self.ch {
578 if c.is_whitespace() {
579 let msg = "called consume_any_line_comment, but there was whitespace";
580 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
585 match self.nextch() {
590 // line comments starting with "///" or "//!" are doc-comments
591 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
592 let start_bpos = self.pos - BytePos(2);
594 while !self.is_eof() {
595 match self.ch.unwrap() {
598 if self.nextch_is('\n') {
601 } else if doc_comment {
602 self.err_span_(self.pos,
604 "bare CR not allowed in doc-comment");
613 self.with_str_from(start_bpos, |string| {
614 // comments with only more "/"s are not doc comments
615 let tok = if is_doc_comment(string) {
616 token::DocComment(Symbol::intern(string))
623 sp: self.mk_sp(start_bpos, self.pos),
629 sp: self.mk_sp(start_bpos, self.pos),
636 self.scan_block_comment()
640 } else if self.ch_is('#') {
641 if self.nextch_is('!') {
643 // Parse an inner attribute.
644 if self.nextnextch_is('[') {
648 // I guess this is the only way to figure out if
649 // we're at the beginning of the file...
650 let smap = SourceMap::new(FilePathMapping::empty());
651 smap.files.borrow_mut().source_files.push(self.source_file.clone());
652 let loc = smap.lookup_char_pos_adj(self.pos);
653 debug!("Skipping a shebang");
654 if loc.line == 1 && loc.col == CharPos(0) {
655 // FIXME: Add shebang "token", return it
656 let start = self.pos;
657 while !self.ch_is('\n') && !self.is_eof() {
660 return Some(TokenAndSpan {
661 tok: token::Shebang(self.name_from(start)),
662 sp: self.mk_sp(start, self.pos),
672 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
674 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
675 match self.ch.unwrap_or('\0') {
676 // # to handle shebang at start of file -- this is the entry point
677 // for skipping over all "junk"
679 let c = self.scan_comment();
680 debug!("scanning a comment {:?}", c);
683 c if is_pattern_whitespace(Some(c)) => {
684 let start_bpos = self.pos;
685 while is_pattern_whitespace(self.ch) {
688 let c = Some(TokenAndSpan {
689 tok: token::Whitespace,
690 sp: self.mk_sp(start_bpos, self.pos),
692 debug!("scanning whitespace: {:?}", c);
699 /// Might return a sugared-doc-attr
700 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
701 // block comments starting with "/**" or "/*!" are doc-comments
702 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
703 let start_bpos = self.pos - BytePos(2);
705 let mut level: isize = 1;
706 let mut has_cr = false;
709 let msg = if is_doc_comment {
710 "unterminated block doc-comment"
712 "unterminated block comment"
714 let last_bpos = self.pos;
715 self.fatal_span_(start_bpos, last_bpos, msg).raise();
717 let n = self.ch.unwrap();
719 '/' if self.nextch_is('*') => {
723 '*' if self.nextch_is('/') => {
735 self.with_str_from(start_bpos, |string| {
736 // but comments with only "*"s between two "/"s are not
737 let tok = if is_block_doc_comment(string) {
738 let string = if has_cr {
739 self.translate_crlf(start_bpos,
741 "bare CR not allowed in block doc-comment")
745 token::DocComment(Symbol::intern(&string[..]))
752 sp: self.mk_sp(start_bpos, self.pos),
757 /// Scan through any digits (base `scan_radix`) or underscores,
758 /// and return how many digits there were.
760 /// `real_radix` represents the true radix of the number we're
761 /// interested in, and errors will be emitted for any digits
762 /// between `real_radix` and `scan_radix`.
763 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
764 assert!(real_radix <= scan_radix);
770 debug!("skipping a _");
774 match c.and_then(|cc| cc.to_digit(scan_radix)) {
776 debug!("{:?} in scan_digits", c);
777 // check that the hypothetical digit is actually
778 // in range for the true radix
779 if c.unwrap().to_digit(real_radix).is_none() {
780 self.err_span_(self.pos,
782 &format!("invalid digit for a base {} literal", real_radix));
792 /// Lex a LIT_INTEGER or a LIT_FLOAT
793 fn scan_number(&mut self, c: char) -> token::Lit {
795 let start_bpos = self.pos;
798 let num_digits = if c == '0' {
799 match self.ch.unwrap_or('\0') {
803 self.scan_digits(2, 10)
808 self.scan_digits(8, 10)
813 self.scan_digits(16, 16)
815 '0'..='9' | '_' | '.' | 'e' | 'E' => {
816 self.scan_digits(10, 10) + 1
820 return token::Integer(self.name_from(start_bpos));
823 } else if c.is_digit(10) {
824 self.scan_digits(10, 10) + 1
830 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
832 return token::Integer(Symbol::intern("0"));
835 // might be a float, but don't be greedy if this is actually an
836 // integer literal followed by field/method access or a range pattern
837 // (`0..2` and `12.foo()`)
838 if self.ch_is('.') && !self.nextch_is('.') &&
839 !ident_start(self.nextch()) {
840 // might have stuff after the ., and if it does, it needs to start
843 if self.ch.unwrap_or('\0').is_digit(10) {
844 self.scan_digits(10, 10);
845 self.scan_float_exponent();
848 self.check_float_base(start_bpos, pos, base);
850 token::Float(self.name_from(start_bpos))
852 // it might be a float if it has an exponent
853 if self.ch_is('e') || self.ch_is('E') {
854 self.scan_float_exponent();
856 self.check_float_base(start_bpos, pos, base);
857 return token::Float(self.name_from(start_bpos));
859 // but we certainly have an integer!
860 token::Integer(self.name_from(start_bpos))
864 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
865 /// error if too many or too few digits are encountered.
866 fn scan_hex_digits(&mut self, n_digits: usize, delim: char, below_0x7f_only: bool) -> bool {
867 debug!("scanning {} digits until {:?}", n_digits, delim);
868 let start_bpos = self.pos;
869 let mut accum_int = 0;
871 let mut valid = true;
872 for _ in 0..n_digits {
874 let last_bpos = self.pos;
875 self.fatal_span_(start_bpos,
877 "unterminated numeric character escape").raise();
879 if self.ch_is(delim) {
880 let last_bpos = self.pos;
881 self.err_span_(start_bpos,
883 "numeric character escape is too short");
887 let c = self.ch.unwrap_or('\x00');
889 accum_int += c.to_digit(16).unwrap_or_else(|| {
890 self.err_span_char(self.pos,
892 "invalid character in numeric character escape",
901 if below_0x7f_only && accum_int >= 0x80 {
902 self.err_span_(start_bpos,
904 "this form of character escape may only be used with characters in \
905 the range [\\x00-\\x7f]");
909 match char::from_u32(accum_int) {
912 let last_bpos = self.pos;
913 self.err_span_(start_bpos, last_bpos, "invalid numeric character escape");
919 /// Scan for a single (possibly escaped) byte or char
920 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
921 /// `start` is the position of `first_source_char`, which is already consumed.
923 /// Returns `true` if there was a valid char/byte.
924 fn scan_char_or_byte(&mut self,
926 first_source_char: char,
931 match first_source_char {
933 // '\X' for some X must be a character constant:
934 let escaped = self.ch;
935 let escaped_pos = self.pos;
938 None => {} // EOF here is an error that will be checked later.
941 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
942 'x' => self.scan_byte_escape(delim, !ascii_only),
944 let valid = if self.ch_is('{') {
945 self.scan_unicode_escape(delim) && !ascii_only
947 let span = self.mk_sp(start, self.pos);
948 let mut suggestion = "\\u{".to_owned();
949 let mut err = self.sess.span_diagnostic.struct_span_err(
951 "incorrect unicode escape sequence",
954 while let (Some(ch), true) = (self.ch, i < 6) {
964 suggestion.push('}');
966 self.mk_sp(start, self.pos),
967 "format of unicode escape sequences uses braces",
969 Applicability::MaybeIncorrect,
974 "format of unicode escape sequences is `\\u{...}`",
981 self.err_span_(start,
983 "unicode escape sequences cannot be used as a \
984 byte or in a byte string");
989 '\n' if delim == '"' => {
990 self.consume_whitespace();
993 '\r' if delim == '"' && self.ch_is('\n') => {
994 self.consume_whitespace();
999 let mut err = self.struct_err_span_char(escaped_pos,
1002 "unknown byte escape"
1004 "unknown character \
1009 err.span_help(self.mk_sp(escaped_pos, pos),
1010 "this is an isolated carriage return; consider \
1011 checking your editor and version control \
1014 if (e == '{' || e == '}') && !ascii_only {
1015 err.span_help(self.mk_sp(escaped_pos, pos),
1016 "if used in a formatting string, curly braces \
1017 are escaped with `{{` and `}}`");
1026 '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
1028 self.err_span_char(start,
1031 "byte constant must be escaped"
1033 "character constant must be escaped"
1039 if self.ch_is('\n') {
1043 self.err_span_(start,
1045 "bare CR not allowed in string, use \\r instead");
1050 if ascii_only && first_source_char > '\x7F' {
1052 self.err_span_(start,
1054 "byte constant must be ASCII. Use a \\xHH escape for a \
1063 /// Scan over a `\u{...}` escape
1065 /// At this point, we have already seen the `\` and the `u`, the `{` is the current character.
1066 /// We will read a hex number (with `_` separators), with 1 to 6 actual digits,
1067 /// and pass over the `}`.
1068 fn scan_unicode_escape(&mut self, delim: char) -> bool {
1069 self.bump(); // past the {
1070 let start_bpos = self.pos;
1071 let mut valid = true;
1073 if let Some('_') = self.ch {
1074 // disallow leading `_`
1075 self.err_span_(self.pos,
1077 "invalid start of unicode escape");
1081 let count = self.scan_digits(16, 16);
1084 self.err_span_(start_bpos,
1086 "overlong unicode escape (must have at most 6 hex digits)");
1093 if valid && count == 0 {
1094 self.err_span_(start_bpos,
1096 "empty unicode escape (must have at least 1 hex digit)");
1099 self.bump(); // past the ending `}`
1104 self.err_span_(self.pos,
1106 "unterminated unicode escape (needed a `}`)");
1110 self.err_span_char(start_bpos,
1112 "invalid character in unicode escape",
1118 self.fatal_span_(start_bpos,
1120 "unterminated unicode escape (found EOF)").raise();
1129 /// Scan over a float exponent.
1130 fn scan_float_exponent(&mut self) {
1131 if self.ch_is('e') || self.ch_is('E') {
1134 if self.ch_is('-') || self.ch_is('+') {
1138 if self.scan_digits(10, 10) == 0 {
1139 let mut err = self.struct_span_fatal(
1140 self.pos, self.next_pos,
1141 "expected at least one digit in exponent"
1143 if let Some(ch) = self.ch {
1144 // check for e.g., Unicode minus '−' (Issue #49746)
1145 if unicode_chars::check_for_substitution(self, ch, &mut err) {
1147 self.scan_digits(10, 10);
1155 /// Checks that a base is valid for a floating literal, emitting a nice
1156 /// error if it isn't.
1157 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
1160 self.err_span_(start_bpos,
1162 "hexadecimal float literal is not supported")
1165 self.err_span_(start_bpos,
1167 "octal float literal is not supported")
1170 self.err_span_(start_bpos,
1172 "binary float literal is not supported")
1178 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
1180 if self.ch_is('=') {
1188 /// Returns the next token from the string, advances the input past that
1189 /// token, and updates the interner
1190 fn next_token_inner(&mut self) -> Result<token::Token, ()> {
1194 let (is_ident_start, is_raw_ident) =
1195 match (c.unwrap(), self.nextch(), self.nextnextch()) {
1196 // r# followed by an identifier starter is a raw identifier.
1197 // This is an exception to the r# case below.
1198 ('r', Some('#'), x) if ident_start(x) => (true, true),
1199 // r as in r" or r#" is part of a raw string literal.
1200 // b as in b' is part of a byte literal.
1201 // They are not identifiers, and are handled further down.
1202 ('r', Some('"'), _) |
1203 ('r', Some('#'), _) |
1204 ('b', Some('"'), _) |
1205 ('b', Some('\''), _) |
1206 ('b', Some('r'), Some('"')) |
1207 ('b', Some('r'), Some('#')) => (false, false),
1212 let raw_start = self.pos;
1214 // Consume the 'r#' characters.
1219 let start = self.pos;
1222 while ident_continue(self.ch) {
1226 return Ok(self.with_str_from(start, |string| {
1227 // FIXME: perform NFKC normalization here. (Issue #2253)
1228 let ident = self.mk_ident(string);
1230 if is_raw_ident && (ident.is_path_segment_keyword() ||
1231 ident.name == keywords::Underscore.name()) {
1232 self.fatal_span_(raw_start, self.pos,
1233 &format!("`r#{}` is not currently supported.", ident.name)
1238 let span = self.mk_sp(raw_start, self.pos);
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)) && !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('\'') {
1411 self.err_span_(start_with_quote, self.next_pos,
1412 "character literal may only contain one codepoint");
1414 return Ok(token::Literal(token::Err(Symbol::intern("??")), None))
1418 // Include the leading `'` in the real identifier, for macro
1419 // expansion purposes. See #12512 for the gory details of why
1420 // this is necessary.
1421 let ident = self.with_str_from(start, |lifetime_name| {
1422 self.mk_ident(&format!("'{}", lifetime_name))
1425 return Ok(token::Lifetime(ident));
1428 let valid = self.scan_char_or_byte(start, c2, /* ascii_only */ false, '\'');
1430 if !self.ch_is('\'') {
1435 if self.ch_is('\'') {
1436 let start = self.src_index(start);
1437 let end = self.src_index(self.pos);
1439 let span = self.mk_sp(start_with_quote, self.pos);
1440 self.sess.span_diagnostic
1441 .struct_span_err(span,
1442 "character literal may only contain one codepoint")
1445 "if you meant to write a `str` literal, use double quotes",
1446 format!("\"{}\"", &self.src[start..end]),
1447 Applicability::MachineApplicable
1449 return Ok(token::Literal(token::Err(Symbol::intern("??")), None))
1451 if self.ch_is('\n') || self.is_eof() || self.ch_is('/') {
1452 // Only attempt to infer single line string literals. If we encounter
1453 // a slash, bail out in order to avoid nonsensical suggestion when
1454 // involving comments.
1459 self.fatal_span_verbose(start_with_quote, pos,
1460 String::from("character literal may only contain one codepoint")).raise();
1464 self.name_from(start)
1469 self.bump(); // advance ch past token
1470 let suffix = self.scan_optional_raw_name();
1472 Ok(token::Literal(token::Char(id), suffix))
1476 let lit = match self.ch {
1477 Some('\'') => self.scan_byte(),
1478 Some('"') => self.scan_byte_string(),
1479 Some('r') => self.scan_raw_byte_string(),
1480 _ => unreachable!(), // Should have been a token::Ident above.
1482 let suffix = self.scan_optional_raw_name();
1484 Ok(token::Literal(lit, suffix))
1487 let start_bpos = self.pos;
1488 let mut valid = true;
1491 while !self.ch_is('"') {
1493 let last_bpos = self.pos;
1494 self.fatal_span_(start_bpos,
1496 "unterminated double quote string").raise();
1499 let ch_start = self.pos;
1500 let ch = self.ch.unwrap();
1502 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only */ false, '"');
1504 // adjust for the ASCII " at the start of the literal
1506 self.name_from(start_bpos + BytePos(1))
1508 Symbol::intern("??")
1511 let suffix = self.scan_optional_raw_name();
1513 Ok(token::Literal(token::Str_(id), suffix))
1516 let start_bpos = self.pos;
1518 let mut hash_count: u16 = 0;
1519 while self.ch_is('#') {
1520 if hash_count == 65535 {
1521 let bpos = self.next_pos;
1522 self.fatal_span_(start_bpos,
1524 "too many `#` symbols: raw strings may be \
1525 delimited by up to 65535 `#` symbols").raise();
1532 self.fail_unterminated_raw_string(start_bpos, hash_count);
1533 } else if !self.ch_is('"') {
1534 let last_bpos = self.pos;
1535 let curr_char = self.ch.unwrap();
1536 self.fatal_span_char(start_bpos,
1538 "found invalid character; only `#` is allowed \
1539 in raw string delimitation",
1543 let content_start_bpos = self.pos;
1544 let mut content_end_bpos;
1545 let mut valid = true;
1548 self.fail_unterminated_raw_string(start_bpos, hash_count);
1550 // if self.ch_is('"') {
1551 // content_end_bpos = self.pos;
1552 // for _ in 0..hash_count {
1554 // if !self.ch_is('#') {
1556 let c = self.ch.unwrap();
1559 content_end_bpos = self.pos;
1560 for _ in 0..hash_count {
1562 if !self.ch_is('#') {
1569 if !self.nextch_is('\n') {
1570 let last_bpos = self.pos;
1571 self.err_span_(start_bpos,
1573 "bare CR not allowed in raw string, use \\r \
1585 self.name_from_to(content_start_bpos, content_end_bpos)
1587 Symbol::intern("??")
1589 let suffix = self.scan_optional_raw_name();
1591 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1594 if self.nextch_is('>') {
1599 Ok(self.binop(token::Minus))
1603 if self.nextch_is('&') {
1608 Ok(self.binop(token::And))
1612 match self.nextch() {
1619 Ok(self.binop(token::Or))
1624 Ok(self.binop(token::Plus))
1627 Ok(self.binop(token::Star))
1630 Ok(self.binop(token::Slash))
1633 Ok(self.binop(token::Caret))
1636 Ok(self.binop(token::Percent))
1639 let last_bpos = self.pos;
1640 let bpos = self.next_pos;
1641 let mut err = self.struct_fatal_span_char(last_bpos,
1643 "unknown start of token",
1645 unicode_chars::check_for_substitution(self, c, &mut err);
1646 self.fatal_errs.push(err);
1653 fn consume_whitespace(&mut self) {
1654 while is_pattern_whitespace(self.ch) && !self.is_eof() {
1659 fn read_to_eol(&mut self) -> String {
1660 let mut val = String::new();
1661 while !self.ch_is('\n') && !self.is_eof() {
1662 val.push(self.ch.unwrap());
1666 if self.ch_is('\n') {
1673 fn read_one_line_comment(&mut self) -> String {
1674 let val = self.read_to_eol();
1675 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1676 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1680 fn consume_non_eol_whitespace(&mut self) {
1681 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1686 fn peeking_at_comment(&self) -> bool {
1687 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1688 // consider shebangs comments, but not inner attributes
1689 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1692 fn scan_byte(&mut self) -> token::Lit {
1694 let start = self.pos;
1696 // the eof will be picked up by the final `'` check below
1697 let c2 = self.ch.unwrap_or('\x00');
1700 let valid = self.scan_char_or_byte(start,
1705 if !self.ch_is('\'') {
1706 // Byte offsetting here is okay because the
1707 // character before position `start` are an
1708 // ascii single quote and ascii 'b'.
1710 self.fatal_span_verbose(start - BytePos(2),
1712 "unterminated byte constant".to_string()).raise();
1716 self.name_from(start)
1720 self.bump(); // advance ch past token
1726 fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1727 self.scan_hex_digits(2, delim, below_0x7f_only)
1730 fn scan_byte_string(&mut self) -> token::Lit {
1732 let start = self.pos;
1733 let mut valid = true;
1735 while !self.ch_is('"') {
1738 self.fatal_span_(start, pos, "unterminated double quote byte string").raise();
1741 let ch_start = self.pos;
1742 let ch = self.ch.unwrap();
1744 valid &= self.scan_char_or_byte(ch_start,
1752 self.name_from(start)
1754 Symbol::intern("??")
1761 fn scan_raw_byte_string(&mut self) -> token::Lit {
1762 let start_bpos = self.pos;
1764 let mut hash_count = 0;
1765 while self.ch_is('#') {
1766 if hash_count == 65535 {
1767 let bpos = self.next_pos;
1768 self.fatal_span_(start_bpos,
1770 "too many `#` symbols: raw byte strings may be \
1771 delimited by up to 65535 `#` symbols").raise();
1778 self.fail_unterminated_raw_string(start_bpos, hash_count);
1779 } else if !self.ch_is('"') {
1781 let ch = self.ch.unwrap();
1782 self.fatal_span_char(start_bpos,
1784 "found invalid character; only `#` is allowed in raw \
1785 string delimitation",
1789 let content_start_bpos = self.pos;
1790 let mut content_end_bpos;
1794 self.fail_unterminated_raw_string(start_bpos, hash_count);
1797 content_end_bpos = self.pos;
1798 for _ in 0..hash_count {
1800 if !self.ch_is('#') {
1809 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1818 token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), hash_count)
1822 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1823 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1825 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1826 c.map_or(false, Pattern_White_Space)
1830 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1831 c.map_or(false, |c| lo <= c && c <= hi)
1835 fn is_dec_digit(c: Option<char>) -> bool {
1836 in_range(c, '0', '9')
1839 fn is_doc_comment(s: &str) -> bool {
1840 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1841 s.starts_with("//!");
1842 debug!("is {:?} a doc comment? {}", s, res);
1846 fn is_block_doc_comment(s: &str) -> bool {
1847 // Prevent `/**/` from being parsed as a doc comment
1848 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1849 s.starts_with("/*!")) && s.len() >= 5;
1850 debug!("is {:?} a doc comment? {}", s, res);
1854 fn ident_start(c: Option<char>) -> bool {
1857 None => return false,
1860 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1863 fn ident_continue(c: Option<char>) -> bool {
1866 None => return false,
1869 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1870 (c > '\x7f' && c.is_xid_continue())
1874 fn char_at(s: &str, byte: usize) -> char {
1875 s[byte..].chars().next().unwrap()
1882 use crate::ast::{Ident, CrateConfig};
1883 use crate::symbol::Symbol;
1884 use crate::source_map::SourceMap;
1885 use crate::feature_gate::UnstableFeatures;
1886 use crate::parse::token;
1887 use crate::diagnostics::plugin::ErrorMap;
1888 use crate::with_globals;
1890 use std::path::PathBuf;
1891 use syntax_pos::{BytePos, Span, NO_EXPANSION};
1892 use rustc_data_structures::fx::FxHashSet;
1893 use rustc_data_structures::sync::Lock;
1895 fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
1896 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1901 span_diagnostic: errors::Handler::with_emitter(true, false, Box::new(emitter)),
1902 unstable_features: UnstableFeatures::from_environment(),
1903 config: CrateConfig::default(),
1904 included_mod_stack: Lock::new(Vec::new()),
1906 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1907 raw_identifier_spans: Lock::new(Vec::new()),
1908 registered_diagnostics: Lock::new(ErrorMap::new()),
1909 buffered_lints: Lock::new(vec![]),
1913 // open a string reader for the given string
1914 fn setup<'a>(sm: &SourceMap,
1915 sess: &'a ParseSess,
1917 -> StringReader<'a> {
1918 let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
1919 StringReader::new(sess, sf, None)
1925 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1926 let sh = mk_sess(sm.clone());
1927 let mut string_reader = setup(&sm,
1929 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1931 let id = Ident::from_str("fn");
1932 assert_eq!(string_reader.next_token().tok, token::Comment);
1933 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1934 let tok1 = string_reader.next_token();
1935 let tok2 = TokenAndSpan {
1936 tok: token::Ident(id, false),
1937 sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1939 assert_eq!(tok1.tok, tok2.tok);
1940 assert_eq!(tok1.sp, tok2.sp);
1941 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1942 // the 'main' id is already read:
1943 assert_eq!(string_reader.pos.clone(), BytePos(28));
1944 // read another token:
1945 let tok3 = string_reader.next_token();
1946 let tok4 = TokenAndSpan {
1947 tok: mk_ident("main"),
1948 sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1950 assert_eq!(tok3.tok, tok4.tok);
1951 assert_eq!(tok3.sp, tok4.sp);
1952 // the lparen is already read:
1953 assert_eq!(string_reader.pos.clone(), BytePos(29))
1957 // check that the given reader produces the desired stream
1958 // of tokens (stop checking after exhausting the expected vec)
1959 fn check_tokenization(mut string_reader: StringReader<'_>, expected: Vec<token::Token>) {
1960 for expected_tok in &expected {
1961 assert_eq!(&string_reader.next_token().tok, expected_tok);
1965 // make the identifier by looking up the string in the interner
1966 fn mk_ident(id: &str) -> token::Token {
1967 token::Token::from_ast_ident(Ident::from_str(id))
1971 fn doublecolonparsing() {
1973 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1974 let sh = mk_sess(sm.clone());
1975 check_tokenization(setup(&sm, &sh, "a b".to_string()),
1976 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1983 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1984 let sh = mk_sess(sm.clone());
1985 check_tokenization(setup(&sm, &sh, "a::b".to_string()),
1986 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1993 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1994 let sh = mk_sess(sm.clone());
1995 check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
1996 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
2003 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2004 let sh = mk_sess(sm.clone());
2005 check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
2006 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
2013 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2014 let sh = mk_sess(sm.clone());
2015 assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok,
2016 token::Literal(token::Char(Symbol::intern("a")), None));
2021 fn character_space() {
2023 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2024 let sh = mk_sess(sm.clone());
2025 assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok,
2026 token::Literal(token::Char(Symbol::intern(" ")), None));
2031 fn character_escaped() {
2033 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2034 let sh = mk_sess(sm.clone());
2035 assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok,
2036 token::Literal(token::Char(Symbol::intern("\\n")), None));
2041 fn lifetime_name() {
2043 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2044 let sh = mk_sess(sm.clone());
2045 assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok,
2046 token::Lifetime(Ident::from_str("'abc")));
2053 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2054 let sh = mk_sess(sm.clone());
2055 assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
2058 token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
2063 fn literal_suffixes() {
2065 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2066 let sh = mk_sess(sm.clone());
2068 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
2069 assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token().tok,
2070 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2071 Some(Symbol::intern("suffix"))));
2072 // with a whitespace separator:
2073 assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token().tok,
2074 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2079 test!("'a'", Char, "a");
2080 test!("b'a'", Byte, "a");
2081 test!("\"a\"", Str_, "a");
2082 test!("b\"a\"", ByteStr, "a");
2083 test!("1234", Integer, "1234");
2084 test!("0b101", Integer, "0b101");
2085 test!("0xABC", Integer, "0xABC");
2086 test!("1.0", Float, "1.0");
2087 test!("1.0e10", Float, "1.0e10");
2089 assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token().tok,
2090 token::Literal(token::Integer(Symbol::intern("2")),
2091 Some(Symbol::intern("us"))));
2092 assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
2093 token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
2094 Some(Symbol::intern("suffix"))));
2095 assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
2096 token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
2097 Some(Symbol::intern("suffix"))));
2102 fn line_doc_comments() {
2103 assert!(is_doc_comment("///"));
2104 assert!(is_doc_comment("/// blah"));
2105 assert!(!is_doc_comment("////"));
2109 fn nested_block_comments() {
2111 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2112 let sh = mk_sess(sm.clone());
2113 let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
2114 match lexer.next_token().tok {
2115 token::Comment => {}
2116 _ => panic!("expected a comment!"),
2118 assert_eq!(lexer.next_token().tok,
2119 token::Literal(token::Char(Symbol::intern("a")), None));
2124 fn crlf_comments() {
2126 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2127 let sh = mk_sess(sm.clone());
2128 let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
2129 let comment = lexer.next_token();
2130 assert_eq!(comment.tok, token::Comment);
2131 assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
2132 assert_eq!(lexer.next_token().tok, token::Whitespace);
2133 assert_eq!(lexer.next_token().tok,
2134 token::DocComment(Symbol::intern("/// test")));