1 use crate::ast::{self, Ident};
2 use crate::source_map::{SourceMap, FilePathMapping};
3 use crate::parse::{token, ParseSess};
4 use crate::symbol::Symbol;
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 /// Immutably extract string if found at current position with given delimiters
129 pub fn peek_delimited(&self, from_ch: char, to_ch: char) -> Option<String> {
130 let mut pos = self.pos;
131 let mut idx = self.src_index(pos);
132 let mut ch = char_at(&self.src, idx);
136 pos = pos + Pos::from_usize(ch.len_utf8());
138 idx = self.src_index(pos);
139 while idx < self.end_src_index {
140 ch = char_at(&self.src, idx);
142 return Some(self.src[self.src_index(start_pos)..self.src_index(pos)].to_string());
144 pos = pos + Pos::from_usize(ch.len_utf8());
145 idx = self.src_index(pos);
150 fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> {
151 let mut t = self.try_next_token()?;
154 token::Whitespace | token::Comment | token::Shebang(_) => {
155 t = self.try_next_token()?;
161 self.token = t.tok.clone();
167 pub fn real_token(&mut self) -> TokenAndSpan {
168 let res = self.try_real_token();
169 self.unwrap_or_abort(res)
173 fn is_eof(&self) -> bool {
177 fn fail_unterminated_raw_string(&self, pos: BytePos, hash_count: u16) {
178 let mut err = self.struct_span_fatal(pos, pos, "unterminated raw string");
179 err.span_label(self.mk_sp(pos, pos), "unterminated raw string");
182 err.note(&format!("this raw string should be terminated with `\"{}`",
183 "#".repeat(hash_count as usize)));
190 fn fatal(&self, m: &str) -> FatalError {
191 self.fatal_span(self.peek_span, m)
194 pub fn emit_fatal_errors(&mut self) {
195 for err in &mut self.fatal_errs {
199 self.fatal_errs.clear();
202 pub fn buffer_fatal_errors(&mut self) -> Vec<Diagnostic> {
203 let mut buffer = Vec::new();
205 for err in self.fatal_errs.drain(..) {
206 err.buffer(&mut buffer);
212 pub fn peek(&self) -> TokenAndSpan {
213 // FIXME(pcwalton): Bad copy!
215 tok: self.peek_tok.clone(),
220 /// For comments.rs, which hackily pokes into next_pos and ch
221 fn new_raw(sess: &'a ParseSess,
222 source_file: Lrc<syntax_pos::SourceFile>,
223 override_span: Option<Span>) -> Self {
224 let mut sr = StringReader::new_raw_internal(sess, source_file, override_span);
230 fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc<syntax_pos::SourceFile>,
231 override_span: Option<Span>) -> Self
233 if source_file.src.is_none() {
234 sess.span_diagnostic.bug(&format!("Cannot lex source_file without source: {}",
238 let src = (*source_file.src.as_ref().unwrap()).clone();
242 next_pos: source_file.start_pos,
243 pos: source_file.start_pos,
246 end_src_index: src.len(),
247 // dummy values; not read
248 peek_tok: token::Eof,
249 peek_span: syntax_pos::DUMMY_SP,
250 peek_span_src_raw: syntax_pos::DUMMY_SP,
252 fatal_errs: Vec::new(),
254 span: syntax_pos::DUMMY_SP,
255 span_src_raw: syntax_pos::DUMMY_SP,
256 open_braces: Vec::new(),
257 unmatched_braces: Vec::new(),
258 matching_delim_spans: Vec::new(),
260 last_unclosed_found_span: None,
264 pub fn new(sess: &'a ParseSess,
265 source_file: Lrc<syntax_pos::SourceFile>,
266 override_span: Option<Span>) -> Self {
267 let mut sr = StringReader::new_raw(sess, source_file, override_span);
268 if sr.advance_token().is_err() {
269 sr.emit_fatal_errors();
276 pub fn new_or_buffered_errs(sess: &'a ParseSess,
277 source_file: Lrc<syntax_pos::SourceFile>,
278 override_span: Option<Span>) -> Result<Self, Vec<Diagnostic>> {
279 let mut sr = StringReader::new_raw(sess, source_file, override_span);
280 if sr.advance_token().is_err() {
281 Err(sr.buffer_fatal_errors())
287 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
288 let begin = sess.source_map().lookup_byte_offset(span.lo());
289 let end = sess.source_map().lookup_byte_offset(span.hi());
291 // Make the range zero-length if the span is invalid.
292 if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
293 span = span.shrink_to_lo();
296 let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
298 // Seek the lexer to the right byte range.
299 sr.next_pos = span.lo();
300 sr.end_src_index = sr.src_index(span.hi());
304 if sr.advance_token().is_err() {
305 sr.emit_fatal_errors();
313 fn ch_is(&self, c: char) -> bool {
317 /// Report a fatal lexical error with a given span.
318 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
319 self.sess.span_diagnostic.span_fatal(sp, m)
322 /// Report a lexical error with a given span.
323 fn err_span(&self, sp: Span, m: &str) {
324 self.sess.span_diagnostic.struct_span_err(sp, m).emit();
328 /// Report a fatal error spanning [`from_pos`, `to_pos`).
329 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
330 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
333 /// Report a lexical error spanning [`from_pos`, `to_pos`).
334 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
335 self.err_span(self.mk_sp(from_pos, to_pos), m)
338 /// Pushes a character to a message string for error reporting
339 fn push_escaped_char_for_msg(m: &mut String, c: char) {
341 '\u{20}'..='\u{7e}' => {
342 // Don't escape \, ' or " for user-facing messages
346 m.extend(c.escape_default());
351 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
352 /// escaped character to the error message
353 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
354 let mut m = m.to_string();
356 Self::push_escaped_char_for_msg(&mut m, c);
358 self.fatal_span_(from_pos, to_pos, &m[..])
361 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
362 -> DiagnosticBuilder<'a>
364 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
367 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
368 -> DiagnosticBuilder<'a>
370 let mut m = m.to_string();
372 Self::push_escaped_char_for_msg(&mut m, c);
374 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
377 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
378 /// escaped character to the error message
379 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
380 let mut m = m.to_string();
382 Self::push_escaped_char_for_msg(&mut m, c);
383 self.err_span_(from_pos, to_pos, &m[..]);
386 fn struct_err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
387 -> DiagnosticBuilder<'a>
389 let mut m = m.to_string();
391 Self::push_escaped_char_for_msg(&mut m, c);
393 self.sess.span_diagnostic.struct_span_err(self.mk_sp(from_pos, to_pos), &m[..])
396 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
397 /// offending string to the error message
398 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> FatalError {
400 m.push_str(&self.src[self.src_index(from_pos)..self.src_index(to_pos)]);
402 self.fatal_span_(from_pos, to_pos, &m[..])
405 /// Advance peek_tok and peek_span to refer to the next token, and
406 /// possibly update the interner.
407 fn advance_token(&mut self) -> Result<(), ()> {
408 match self.scan_whitespace_or_comment() {
410 self.peek_span_src_raw = comment.sp;
411 self.peek_span = comment.sp;
412 self.peek_tok = comment.tok;
416 self.peek_tok = token::Eof;
417 let (real, raw) = self.mk_sp_and_raw(
418 self.source_file.end_pos,
419 self.source_file.end_pos,
421 self.peek_span = real;
422 self.peek_span_src_raw = raw;
424 let start_bytepos = self.pos;
425 self.peek_tok = self.next_token_inner()?;
426 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
427 self.peek_span = real;
428 self.peek_span_src_raw = raw;
437 fn src_index(&self, pos: BytePos) -> usize {
438 (pos - self.source_file.start_pos).to_usize()
441 /// Calls `f` with a string slice of the source text spanning from `start`
442 /// up to but excluding `self.pos`, meaning the slice does not include
443 /// the character `self.ch`.
444 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
445 where F: FnOnce(&str) -> T
447 self.with_str_from_to(start, self.pos, f)
450 /// Creates a Name from a given offset to the current offset, each
451 /// adjusted 1 towards each other (assumes that on either side there is a
452 /// single-byte delimiter).
453 fn name_from(&self, start: BytePos) -> ast::Name {
454 debug!("taking an ident from {:?} to {:?}", start, self.pos);
455 self.with_str_from(start, Symbol::intern)
458 /// As name_from, with an explicit endpoint.
459 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
460 debug!("taking an ident from {:?} to {:?}", start, end);
461 self.with_str_from_to(start, end, Symbol::intern)
464 /// Calls `f` with a string slice of the source text spanning from `start`
465 /// up to but excluding `end`.
466 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
467 where F: FnOnce(&str) -> T
469 f(&self.src[self.src_index(start)..self.src_index(end)])
472 /// Converts CRLF to LF in the given string, raising an error on bare CR.
473 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
474 let mut chars = s.char_indices().peekable();
475 while let Some((i, ch)) = chars.next() {
477 if let Some((lf_idx, '\n')) = chars.peek() {
478 return translate_crlf_(self, start, s, *lf_idx, chars, errmsg).into();
480 let pos = start + BytePos(i as u32);
481 let end_pos = start + BytePos((i + ch.len_utf8()) as u32);
482 self.err_span_(pos, end_pos, errmsg);
487 fn translate_crlf_(rdr: &StringReader<'_>,
491 mut chars: iter::Peekable<impl Iterator<Item = (usize, char)>>,
494 let mut buf = String::with_capacity(s.len());
496 buf.push_str(&s[.. j - 1]);
497 while let Some((i, ch)) = chars.next() {
500 buf.push_str(&s[j..i]);
502 let next = i + ch.len_utf8();
504 if chars.peek().map(|(_, ch)| *ch) != Some('\n') {
505 let pos = start + BytePos(i as u32);
506 let end_pos = start + BytePos(next as u32);
507 rdr.err_span_(pos, end_pos, errmsg);
512 buf.push_str(&s[j..]);
518 /// Advance the StringReader by one character.
519 crate fn bump(&mut self) {
520 let next_src_index = self.src_index(self.next_pos);
521 if next_src_index < self.end_src_index {
522 let next_ch = char_at(&self.src, next_src_index);
523 let next_ch_len = next_ch.len_utf8();
525 self.ch = Some(next_ch);
526 self.pos = self.next_pos;
527 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
530 self.pos = self.next_pos;
534 fn nextch(&self) -> Option<char> {
535 let next_src_index = self.src_index(self.next_pos);
536 if next_src_index < self.end_src_index {
537 Some(char_at(&self.src, next_src_index))
544 fn nextch_is(&self, c: char) -> bool {
545 self.nextch() == Some(c)
548 fn nextnextch(&self) -> Option<char> {
549 let next_src_index = self.src_index(self.next_pos);
550 if next_src_index < self.end_src_index {
551 let next_next_src_index =
552 next_src_index + char_at(&self.src, next_src_index).len_utf8();
553 if next_next_src_index < self.end_src_index {
554 return Some(char_at(&self.src, next_next_src_index));
561 fn nextnextch_is(&self, c: char) -> bool {
562 self.nextnextch() == Some(c)
565 /// Eats <XID_start><XID_continue>*, if possible.
566 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
567 if !ident_start(self.ch) {
571 let start = self.pos;
574 while ident_continue(self.ch) {
578 self.with_str_from(start, |string| {
580 self.sess.span_diagnostic
581 .struct_span_warn(self.mk_sp(start, self.pos),
582 "underscore literal suffix is not allowed")
583 .warn("this was previously accepted by the compiler but is \
584 being phased out; it will become a hard error in \
586 .note("for more information, see issue #42326 \
587 <https://github.com/rust-lang/rust/issues/42326>")
591 Some(Symbol::intern(string))
596 /// PRECONDITION: self.ch is not whitespace
597 /// Eats any kind of comment.
598 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
599 if let Some(c) = self.ch {
600 if c.is_whitespace() {
601 let msg = "called consume_any_line_comment, but there was whitespace";
602 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
607 match self.nextch() {
612 // line comments starting with "///" or "//!" are doc-comments
613 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
614 let start_bpos = self.pos - BytePos(2);
616 while !self.is_eof() {
617 match self.ch.unwrap() {
620 if self.nextch_is('\n') {
623 } else if doc_comment {
624 self.err_span_(self.pos,
626 "bare CR not allowed in doc-comment");
635 self.with_str_from(start_bpos, |string| {
636 // comments with only more "/"s are not doc comments
637 let tok = if is_doc_comment(string) {
638 token::DocComment(Symbol::intern(string))
645 sp: self.mk_sp(start_bpos, self.pos),
651 sp: self.mk_sp(start_bpos, self.pos),
658 self.scan_block_comment()
662 } else if self.ch_is('#') {
663 if self.nextch_is('!') {
665 // Parse an inner attribute.
666 if self.nextnextch_is('[') {
670 // I guess this is the only way to figure out if
671 // we're at the beginning of the file...
672 let smap = SourceMap::new(FilePathMapping::empty());
673 smap.files.borrow_mut().source_files.push(self.source_file.clone());
674 let loc = smap.lookup_char_pos_adj(self.pos);
675 debug!("Skipping a shebang");
676 if loc.line == 1 && loc.col == CharPos(0) {
677 // FIXME: Add shebang "token", return it
678 let start = self.pos;
679 while !self.ch_is('\n') && !self.is_eof() {
682 return Some(TokenAndSpan {
683 tok: token::Shebang(self.name_from(start)),
684 sp: self.mk_sp(start, self.pos),
694 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
696 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
697 match self.ch.unwrap_or('\0') {
698 // # to handle shebang at start of file -- this is the entry point
699 // for skipping over all "junk"
701 let c = self.scan_comment();
702 debug!("scanning a comment {:?}", c);
705 c if is_pattern_whitespace(Some(c)) => {
706 let start_bpos = self.pos;
707 while is_pattern_whitespace(self.ch) {
710 let c = Some(TokenAndSpan {
711 tok: token::Whitespace,
712 sp: self.mk_sp(start_bpos, self.pos),
714 debug!("scanning whitespace: {:?}", c);
721 /// Might return a sugared-doc-attr
722 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
723 // block comments starting with "/**" or "/*!" are doc-comments
724 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
725 let start_bpos = self.pos - BytePos(2);
727 let mut level: isize = 1;
728 let mut has_cr = false;
731 let msg = if is_doc_comment {
732 "unterminated block doc-comment"
734 "unterminated block comment"
736 let last_bpos = self.pos;
737 self.fatal_span_(start_bpos, last_bpos, msg).raise();
739 let n = self.ch.unwrap();
741 '/' if self.nextch_is('*') => {
745 '*' if self.nextch_is('/') => {
757 self.with_str_from(start_bpos, |string| {
758 // but comments with only "*"s between two "/"s are not
759 let tok = if is_block_doc_comment(string) {
760 let string = if has_cr {
761 self.translate_crlf(start_bpos,
763 "bare CR not allowed in block doc-comment")
767 token::DocComment(Symbol::intern(&string[..]))
774 sp: self.mk_sp(start_bpos, self.pos),
779 /// Scan through any digits (base `scan_radix`) or underscores,
780 /// and return how many digits there were.
782 /// `real_radix` represents the true radix of the number we're
783 /// interested in, and errors will be emitted for any digits
784 /// between `real_radix` and `scan_radix`.
785 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
786 assert!(real_radix <= scan_radix);
792 debug!("skipping a _");
796 match c.and_then(|cc| cc.to_digit(scan_radix)) {
798 debug!("{:?} in scan_digits", c);
799 // check that the hypothetical digit is actually
800 // in range for the true radix
801 if c.unwrap().to_digit(real_radix).is_none() {
802 self.err_span_(self.pos,
804 &format!("invalid digit for a base {} literal", real_radix));
814 /// Lex a LIT_INTEGER or a LIT_FLOAT
815 fn scan_number(&mut self, c: char) -> token::Lit {
817 let start_bpos = self.pos;
820 let num_digits = if c == '0' {
821 match self.ch.unwrap_or('\0') {
825 self.scan_digits(2, 10)
830 self.scan_digits(8, 10)
835 self.scan_digits(16, 16)
837 '0'..='9' | '_' | '.' | 'e' | 'E' => {
838 self.scan_digits(10, 10) + 1
842 return token::Integer(self.name_from(start_bpos));
845 } else if c.is_digit(10) {
846 self.scan_digits(10, 10) + 1
852 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
854 return token::Integer(Symbol::intern("0"));
857 // might be a float, but don't be greedy if this is actually an
858 // integer literal followed by field/method access or a range pattern
859 // (`0..2` and `12.foo()`)
860 if self.ch_is('.') && !self.nextch_is('.') &&
861 !ident_start(self.nextch()) {
862 // might have stuff after the ., and if it does, it needs to start
865 if self.ch.unwrap_or('\0').is_digit(10) {
866 self.scan_digits(10, 10);
867 self.scan_float_exponent();
870 self.check_float_base(start_bpos, pos, base);
872 token::Float(self.name_from(start_bpos))
874 // it might be a float if it has an exponent
875 if self.ch_is('e') || self.ch_is('E') {
876 self.scan_float_exponent();
878 self.check_float_base(start_bpos, pos, base);
879 return token::Float(self.name_from(start_bpos));
881 // but we certainly have an integer!
882 token::Integer(self.name_from(start_bpos))
886 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
887 /// error if too many or too few digits are encountered.
888 fn scan_hex_digits(&mut self, n_digits: usize, delim: char, below_0x7f_only: bool) -> bool {
889 debug!("scanning {} digits until {:?}", n_digits, delim);
890 let start_bpos = self.pos;
891 let mut accum_int = 0;
893 let mut valid = true;
894 for _ in 0..n_digits {
896 let last_bpos = self.pos;
897 self.fatal_span_(start_bpos,
899 "unterminated numeric character escape").raise();
901 if self.ch_is(delim) {
902 let last_bpos = self.pos;
903 self.err_span_(start_bpos,
905 "numeric character escape is too short");
909 let c = self.ch.unwrap_or('\x00');
911 accum_int += c.to_digit(16).unwrap_or_else(|| {
912 self.err_span_char(self.pos,
914 "invalid character in numeric character escape",
923 if below_0x7f_only && accum_int >= 0x80 {
924 self.err_span_(start_bpos,
926 "this form of character escape may only be used with characters in \
927 the range [\\x00-\\x7f]");
931 match char::from_u32(accum_int) {
934 let last_bpos = self.pos;
935 self.err_span_(start_bpos, last_bpos, "invalid numeric character escape");
941 /// Scan for a single (possibly escaped) byte or char
942 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
943 /// `start` is the position of `first_source_char`, which is already consumed.
945 /// Returns `true` if there was a valid char/byte.
946 fn scan_char_or_byte(&mut self,
948 first_source_char: char,
953 match first_source_char {
955 // '\X' for some X must be a character constant:
956 let escaped = self.ch;
957 let escaped_pos = self.pos;
960 None => {} // EOF here is an error that will be checked later.
963 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
964 'x' => self.scan_byte_escape(delim, !ascii_only),
966 let valid = if self.ch_is('{') {
967 self.scan_unicode_escape(delim) && !ascii_only
969 let span = self.mk_sp(start, self.pos);
970 let mut suggestion = "\\u{".to_owned();
971 let msg = "incorrect unicode escape sequence";
972 let mut err = self.sess.span_diagnostic.struct_span_err(
977 while let (Some(ch), true) = (self.ch, i < 6) {
987 suggestion.push('}');
989 self.mk_sp(start, self.pos),
990 "format of unicode escape sequences uses braces",
992 Applicability::MaybeIncorrect,
995 err.span_label(span, msg);
997 "format of unicode escape sequences is `\\u{...}`",
1004 self.err_span_(start,
1006 "unicode escape sequences cannot be used as a \
1007 byte or in a byte string");
1012 '\n' if delim == '"' => {
1013 self.consume_whitespace();
1016 '\r' if delim == '"' && self.ch_is('\n') => {
1017 self.consume_whitespace();
1022 let msg = if ascii_only {
1023 "unknown byte escape"
1025 "unknown character escape"
1027 let mut err = self.struct_err_span_char(escaped_pos, pos, msg, c);
1028 err.span_label(self.mk_sp(escaped_pos, pos), msg);
1031 "this is an isolated carriage return; consider checking \
1032 your editor and version control settings",
1035 if (e == '{' || e == '}') && !ascii_only {
1037 "if used in a formatting string, curly braces are escaped \
1038 with `{{` and `}}`",
1048 '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
1050 self.err_span_char(start,
1053 "byte constant must be escaped"
1055 "character constant must be escaped"
1061 if self.ch_is('\n') {
1065 self.err_span_(start,
1067 "bare CR not allowed in string, use \\r instead");
1072 if ascii_only && first_source_char > '\x7F' {
1074 self.err_span_(start,
1076 "byte constant must be ASCII. Use a \\xHH escape for a \
1085 /// Scan over a `\u{...}` escape
1087 /// At this point, we have already seen the `\` and the `u`, the `{` is the current character.
1088 /// We will read a hex number (with `_` separators), with 1 to 6 actual digits,
1089 /// and pass over the `}`.
1090 fn scan_unicode_escape(&mut self, delim: char) -> bool {
1091 self.bump(); // past the {
1092 let start_bpos = self.pos;
1093 let mut valid = true;
1095 if let Some('_') = self.ch {
1096 // disallow leading `_`
1097 self.err_span_(self.pos,
1099 "invalid start of unicode escape");
1103 let count = self.scan_digits(16, 16);
1106 self.err_span_(start_bpos,
1108 "overlong unicode escape (must have at most 6 hex digits)");
1115 if valid && count == 0 {
1116 self.err_span_(start_bpos,
1118 "empty unicode escape (must have at least 1 hex digit)");
1121 self.bump(); // past the ending `}`
1126 self.err_span_(self.pos,
1128 "unterminated unicode escape (needed a `}`)");
1132 self.err_span_char(start_bpos,
1134 "invalid character in unicode escape",
1140 self.fatal_span_(start_bpos,
1142 "unterminated unicode escape (found EOF)").raise();
1151 /// Scan over a float exponent.
1152 fn scan_float_exponent(&mut self) {
1153 if self.ch_is('e') || self.ch_is('E') {
1156 if self.ch_is('-') || self.ch_is('+') {
1160 if self.scan_digits(10, 10) == 0 {
1161 let mut err = self.struct_span_fatal(
1162 self.pos, self.next_pos,
1163 "expected at least one digit in exponent"
1165 if let Some(ch) = self.ch {
1166 // check for e.g., Unicode minus '−' (Issue #49746)
1167 if unicode_chars::check_for_substitution(self, ch, &mut err) {
1169 self.scan_digits(10, 10);
1177 /// Checks that a base is valid for a floating literal, emitting a nice
1178 /// error if it isn't.
1179 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
1182 self.err_span_(start_bpos,
1184 "hexadecimal float literal is not supported")
1187 self.err_span_(start_bpos,
1189 "octal float literal is not supported")
1192 self.err_span_(start_bpos,
1194 "binary float literal is not supported")
1200 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
1202 if self.ch_is('=') {
1210 /// Returns the next token from the string, advances the input past that
1211 /// token, and updates the interner
1212 fn next_token_inner(&mut self) -> Result<token::Token, ()> {
1216 let (is_ident_start, is_raw_ident) =
1217 match (c.unwrap(), self.nextch(), self.nextnextch()) {
1218 // r# followed by an identifier starter is a raw identifier.
1219 // This is an exception to the r# case below.
1220 ('r', Some('#'), x) if ident_start(x) => (true, true),
1221 // r as in r" or r#" is part of a raw string literal.
1222 // b as in b' is part of a byte literal.
1223 // They are not identifiers, and are handled further down.
1224 ('r', Some('"'), _) |
1225 ('r', Some('#'), _) |
1226 ('b', Some('"'), _) |
1227 ('b', Some('\''), _) |
1228 ('b', Some('r'), Some('"')) |
1229 ('b', Some('r'), Some('#')) => (false, false),
1234 let raw_start = self.pos;
1236 // Consume the 'r#' characters.
1241 let start = self.pos;
1244 while ident_continue(self.ch) {
1248 return Ok(self.with_str_from(start, |string| {
1249 // FIXME: perform NFKC normalization here. (Issue #2253)
1250 let ident = self.mk_ident(string);
1253 let span = self.mk_sp(raw_start, self.pos);
1254 if !ident.can_be_raw() {
1255 self.err_span(span, &format!("`{}` cannot be a raw identifier", ident));
1257 self.sess.raw_identifier_spans.borrow_mut().push(span);
1260 token::Ident(ident, is_raw_ident)
1265 if is_dec_digit(c) {
1266 let num = self.scan_number(c.unwrap());
1267 let suffix = self.scan_optional_raw_name();
1268 debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
1269 return Ok(token::Literal(num, suffix));
1272 match c.expect("next_token_inner called at EOF") {
1284 if self.ch_is('.') {
1286 if self.ch_is('.') {
1288 Ok(token::DotDotDot)
1289 } else if self.ch_is('=') {
1301 Ok(token::OpenDelim(token::Paren))
1305 Ok(token::CloseDelim(token::Paren))
1309 Ok(token::OpenDelim(token::Brace))
1313 Ok(token::CloseDelim(token::Brace))
1317 Ok(token::OpenDelim(token::Bracket))
1321 Ok(token::CloseDelim(token::Bracket))
1341 if self.ch_is(':') {
1354 // Multi-byte tokens.
1357 if self.ch_is('=') {
1360 } else if self.ch_is('>') {
1369 if self.ch_is('=') {
1378 match self.ch.unwrap_or('\x00') {
1384 Ok(self.binop(token::Shl))
1397 match self.ch.unwrap_or('\x00') {
1403 Ok(self.binop(token::Shr))
1411 // Either a character constant 'a' OR a lifetime name 'abc
1412 let start_with_quote = self.pos;
1414 let start = self.pos;
1416 // the eof will be picked up by the final `'` check below
1417 let c2 = self.ch.unwrap_or('\x00');
1420 // If the character is an ident start not followed by another single
1421 // quote, then this is a lifetime name:
1422 if (ident_start(Some(c2)) || c2.is_numeric()) && !self.ch_is('\'') {
1423 while ident_continue(self.ch) {
1426 // lifetimes shouldn't end with a single quote
1427 // if we find one, then this is an invalid character literal
1428 if self.ch_is('\'') {
1432 "character literal may only contain one codepoint");
1434 return Ok(token::Literal(token::Err(Symbol::intern("??")), None))
1438 // Include the leading `'` in the real identifier, for macro
1439 // expansion purposes. See #12512 for the gory details of why
1440 // this is necessary.
1441 let ident = self.with_str_from(start, |lifetime_name| {
1442 self.mk_ident(&format!("'{}", lifetime_name))
1445 if c2.is_numeric() {
1446 // this is a recovered lifetime written `'1`, error but accept it
1450 "lifetimes cannot start with a number",
1454 return Ok(token::Lifetime(ident));
1457 let valid = self.scan_char_or_byte(start, c2, /* ascii_only */ false, '\'');
1459 if !self.ch_is('\'') {
1464 if self.ch_is('\'') {
1465 let start = self.src_index(start);
1466 let end = self.src_index(self.pos);
1468 let span = self.mk_sp(start_with_quote, self.pos);
1469 self.sess.span_diagnostic
1470 .struct_span_err(span,
1471 "character literal may only contain one codepoint")
1474 "if you meant to write a `str` literal, use double quotes",
1475 format!("\"{}\"", &self.src[start..end]),
1476 Applicability::MachineApplicable
1478 return Ok(token::Literal(token::Err(Symbol::intern("??")), None))
1480 if self.ch_is('\n') || self.is_eof() || self.ch_is('/') {
1481 // Only attempt to infer single line string literals. If we encounter
1482 // a slash, bail out in order to avoid nonsensical suggestion when
1483 // involving comments.
1488 self.fatal_span_verbose(start_with_quote, pos,
1489 String::from("character literal may only contain one codepoint")).raise();
1493 self.name_from(start)
1498 self.bump(); // advance ch past token
1499 let suffix = self.scan_optional_raw_name();
1501 Ok(token::Literal(token::Char(id), suffix))
1505 let lit = match self.ch {
1506 Some('\'') => self.scan_byte(),
1507 Some('"') => self.scan_byte_string(),
1508 Some('r') => self.scan_raw_byte_string(),
1509 _ => unreachable!(), // Should have been a token::Ident above.
1511 let suffix = self.scan_optional_raw_name();
1513 Ok(token::Literal(lit, suffix))
1516 let start_bpos = self.pos;
1517 let mut valid = true;
1520 while !self.ch_is('"') {
1522 let last_bpos = self.pos;
1523 self.fatal_span_(start_bpos,
1525 "unterminated double quote string").raise();
1528 let ch_start = self.pos;
1529 let ch = self.ch.unwrap();
1531 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only */ false, '"');
1533 // adjust for the ASCII " at the start of the literal
1535 self.name_from(start_bpos + BytePos(1))
1537 Symbol::intern("??")
1540 let suffix = self.scan_optional_raw_name();
1542 Ok(token::Literal(token::Str_(id), suffix))
1545 let start_bpos = self.pos;
1547 let mut hash_count: u16 = 0;
1548 while self.ch_is('#') {
1549 if hash_count == 65535 {
1550 let bpos = self.next_pos;
1551 self.fatal_span_(start_bpos,
1553 "too many `#` symbols: raw strings may be \
1554 delimited by up to 65535 `#` symbols").raise();
1561 self.fail_unterminated_raw_string(start_bpos, hash_count);
1562 } else if !self.ch_is('"') {
1563 let last_bpos = self.pos;
1564 let curr_char = self.ch.unwrap();
1565 self.fatal_span_char(start_bpos,
1567 "found invalid character; only `#` is allowed \
1568 in raw string delimitation",
1572 let content_start_bpos = self.pos;
1573 let mut content_end_bpos;
1574 let mut valid = true;
1577 self.fail_unterminated_raw_string(start_bpos, hash_count);
1579 // if self.ch_is('"') {
1580 // content_end_bpos = self.pos;
1581 // for _ in 0..hash_count {
1583 // if !self.ch_is('#') {
1585 let c = self.ch.unwrap();
1588 content_end_bpos = self.pos;
1589 for _ in 0..hash_count {
1591 if !self.ch_is('#') {
1598 if !self.nextch_is('\n') {
1599 let last_bpos = self.pos;
1600 self.err_span_(start_bpos,
1602 "bare CR not allowed in raw string, use \\r \
1614 self.name_from_to(content_start_bpos, content_end_bpos)
1616 Symbol::intern("??")
1618 let suffix = self.scan_optional_raw_name();
1620 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1623 if self.nextch_is('>') {
1628 Ok(self.binop(token::Minus))
1632 if self.nextch_is('&') {
1637 Ok(self.binop(token::And))
1641 match self.nextch() {
1648 Ok(self.binop(token::Or))
1653 Ok(self.binop(token::Plus))
1656 Ok(self.binop(token::Star))
1659 Ok(self.binop(token::Slash))
1662 Ok(self.binop(token::Caret))
1665 Ok(self.binop(token::Percent))
1668 let last_bpos = self.pos;
1669 let bpos = self.next_pos;
1670 let mut err = self.struct_fatal_span_char(last_bpos,
1672 "unknown start of token",
1674 unicode_chars::check_for_substitution(self, c, &mut err);
1675 self.fatal_errs.push(err);
1682 fn consume_whitespace(&mut self) {
1683 while is_pattern_whitespace(self.ch) && !self.is_eof() {
1688 fn read_to_eol(&mut self) -> String {
1689 let mut val = String::new();
1690 while !self.ch_is('\n') && !self.is_eof() {
1691 val.push(self.ch.unwrap());
1695 if self.ch_is('\n') {
1702 fn read_one_line_comment(&mut self) -> String {
1703 let val = self.read_to_eol();
1704 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1705 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1709 fn consume_non_eol_whitespace(&mut self) {
1710 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1715 fn peeking_at_comment(&self) -> bool {
1716 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1717 // consider shebangs comments, but not inner attributes
1718 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1721 fn scan_byte(&mut self) -> token::Lit {
1723 let start = self.pos;
1725 // the eof will be picked up by the final `'` check below
1726 let c2 = self.ch.unwrap_or('\x00');
1729 let valid = self.scan_char_or_byte(start,
1734 if !self.ch_is('\'') {
1735 // Byte offsetting here is okay because the
1736 // character before position `start` are an
1737 // ascii single quote and ascii 'b'.
1739 self.fatal_span_verbose(start - BytePos(2),
1741 "unterminated byte constant".to_string()).raise();
1745 self.name_from(start)
1749 self.bump(); // advance ch past token
1755 fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1756 self.scan_hex_digits(2, delim, below_0x7f_only)
1759 fn scan_byte_string(&mut self) -> token::Lit {
1761 let start = self.pos;
1762 let mut valid = true;
1764 while !self.ch_is('"') {
1767 self.fatal_span_(start, pos, "unterminated double quote byte string").raise();
1770 let ch_start = self.pos;
1771 let ch = self.ch.unwrap();
1773 valid &= self.scan_char_or_byte(ch_start,
1781 self.name_from(start)
1783 Symbol::intern("??")
1790 fn scan_raw_byte_string(&mut self) -> token::Lit {
1791 let start_bpos = self.pos;
1793 let mut hash_count = 0;
1794 while self.ch_is('#') {
1795 if hash_count == 65535 {
1796 let bpos = self.next_pos;
1797 self.fatal_span_(start_bpos,
1799 "too many `#` symbols: raw byte strings may be \
1800 delimited by up to 65535 `#` symbols").raise();
1807 self.fail_unterminated_raw_string(start_bpos, hash_count);
1808 } else if !self.ch_is('"') {
1810 let ch = self.ch.unwrap();
1811 self.fatal_span_char(start_bpos,
1813 "found invalid character; only `#` is allowed in raw \
1814 string delimitation",
1818 let content_start_bpos = self.pos;
1819 let mut content_end_bpos;
1823 self.fail_unterminated_raw_string(start_bpos, hash_count);
1826 content_end_bpos = self.pos;
1827 for _ in 0..hash_count {
1829 if !self.ch_is('#') {
1838 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1847 token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), hash_count)
1851 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1852 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1854 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1855 c.map_or(false, Pattern_White_Space)
1859 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1860 c.map_or(false, |c| lo <= c && c <= hi)
1864 fn is_dec_digit(c: Option<char>) -> bool {
1865 in_range(c, '0', '9')
1868 fn is_doc_comment(s: &str) -> bool {
1869 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1870 s.starts_with("//!");
1871 debug!("is {:?} a doc comment? {}", s, res);
1875 fn is_block_doc_comment(s: &str) -> bool {
1876 // Prevent `/**/` from being parsed as a doc comment
1877 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1878 s.starts_with("/*!")) && s.len() >= 5;
1879 debug!("is {:?} a doc comment? {}", s, res);
1883 /// Determine whether `c` is a valid start for an ident.
1884 fn ident_start(c: Option<char>) -> bool {
1887 None => return false,
1890 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1893 fn ident_continue(c: Option<char>) -> bool {
1896 None => return false,
1899 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1900 (c > '\x7f' && c.is_xid_continue())
1904 fn char_at(s: &str, byte: usize) -> char {
1905 s[byte..].chars().next().unwrap()
1912 use crate::ast::{Ident, CrateConfig};
1913 use crate::symbol::Symbol;
1914 use crate::source_map::SourceMap;
1915 use crate::feature_gate::UnstableFeatures;
1916 use crate::parse::token;
1917 use crate::diagnostics::plugin::ErrorMap;
1918 use crate::with_globals;
1920 use std::path::PathBuf;
1921 use syntax_pos::{BytePos, Span, NO_EXPANSION};
1922 use rustc_data_structures::fx::FxHashSet;
1923 use rustc_data_structures::sync::Lock;
1925 fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
1926 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1931 span_diagnostic: errors::Handler::with_emitter(true, None, Box::new(emitter)),
1932 unstable_features: UnstableFeatures::from_environment(),
1933 config: CrateConfig::default(),
1934 included_mod_stack: Lock::new(Vec::new()),
1936 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1937 raw_identifier_spans: Lock::new(Vec::new()),
1938 registered_diagnostics: Lock::new(ErrorMap::new()),
1939 buffered_lints: Lock::new(vec![]),
1943 // open a string reader for the given string
1944 fn setup<'a>(sm: &SourceMap,
1945 sess: &'a ParseSess,
1947 -> StringReader<'a> {
1948 let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
1949 StringReader::new(sess, sf, None)
1955 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1956 let sh = mk_sess(sm.clone());
1957 let mut string_reader = setup(&sm,
1959 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1961 let id = Ident::from_str("fn");
1962 assert_eq!(string_reader.next_token().tok, token::Comment);
1963 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1964 let tok1 = string_reader.next_token();
1965 let tok2 = TokenAndSpan {
1966 tok: token::Ident(id, false),
1967 sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1969 assert_eq!(tok1.tok, tok2.tok);
1970 assert_eq!(tok1.sp, tok2.sp);
1971 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1972 // the 'main' id is already read:
1973 assert_eq!(string_reader.pos.clone(), BytePos(28));
1974 // read another token:
1975 let tok3 = string_reader.next_token();
1976 let tok4 = TokenAndSpan {
1977 tok: mk_ident("main"),
1978 sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1980 assert_eq!(tok3.tok, tok4.tok);
1981 assert_eq!(tok3.sp, tok4.sp);
1982 // the lparen is already read:
1983 assert_eq!(string_reader.pos.clone(), BytePos(29))
1987 // check that the given reader produces the desired stream
1988 // of tokens (stop checking after exhausting the expected vec)
1989 fn check_tokenization(mut string_reader: StringReader<'_>, expected: Vec<token::Token>) {
1990 for expected_tok in &expected {
1991 assert_eq!(&string_reader.next_token().tok, expected_tok);
1995 // make the identifier by looking up the string in the interner
1996 fn mk_ident(id: &str) -> token::Token {
1997 token::Token::from_ast_ident(Ident::from_str(id))
2001 fn doublecolonparsing() {
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::Whitespace, mk_ident("b")]);
2013 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2014 let sh = mk_sess(sm.clone());
2015 check_tokenization(setup(&sm, &sh, "a::b".to_string()),
2016 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
2023 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2024 let sh = mk_sess(sm.clone());
2025 check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
2026 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
2033 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2034 let sh = mk_sess(sm.clone());
2035 check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
2036 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
2043 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2044 let sh = mk_sess(sm.clone());
2045 assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok,
2046 token::Literal(token::Char(Symbol::intern("a")), None));
2051 fn character_space() {
2053 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2054 let sh = mk_sess(sm.clone());
2055 assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok,
2056 token::Literal(token::Char(Symbol::intern(" ")), None));
2061 fn character_escaped() {
2063 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2064 let sh = mk_sess(sm.clone());
2065 assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok,
2066 token::Literal(token::Char(Symbol::intern("\\n")), None));
2071 fn lifetime_name() {
2073 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2074 let sh = mk_sess(sm.clone());
2075 assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok,
2076 token::Lifetime(Ident::from_str("'abc")));
2083 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2084 let sh = mk_sess(sm.clone());
2085 assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
2088 token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
2093 fn literal_suffixes() {
2095 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2096 let sh = mk_sess(sm.clone());
2098 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
2099 assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token().tok,
2100 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2101 Some(Symbol::intern("suffix"))));
2102 // with a whitespace separator:
2103 assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token().tok,
2104 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2109 test!("'a'", Char, "a");
2110 test!("b'a'", Byte, "a");
2111 test!("\"a\"", Str_, "a");
2112 test!("b\"a\"", ByteStr, "a");
2113 test!("1234", Integer, "1234");
2114 test!("0b101", Integer, "0b101");
2115 test!("0xABC", Integer, "0xABC");
2116 test!("1.0", Float, "1.0");
2117 test!("1.0e10", Float, "1.0e10");
2119 assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token().tok,
2120 token::Literal(token::Integer(Symbol::intern("2")),
2121 Some(Symbol::intern("us"))));
2122 assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
2123 token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
2124 Some(Symbol::intern("suffix"))));
2125 assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
2126 token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
2127 Some(Symbol::intern("suffix"))));
2132 fn line_doc_comments() {
2133 assert!(is_doc_comment("///"));
2134 assert!(is_doc_comment("/// blah"));
2135 assert!(!is_doc_comment("////"));
2139 fn nested_block_comments() {
2141 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2142 let sh = mk_sess(sm.clone());
2143 let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
2144 match lexer.next_token().tok {
2145 token::Comment => {}
2146 _ => panic!("expected a comment!"),
2148 assert_eq!(lexer.next_token().tok,
2149 token::Literal(token::Char(Symbol::intern("a")), None));
2154 fn crlf_comments() {
2156 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2157 let sh = mk_sess(sm.clone());
2158 let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
2159 let comment = lexer.next_token();
2160 assert_eq!(comment.tok, token::Comment);
2161 assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
2162 assert_eq!(lexer.next_token().tok, token::Whitespace);
2163 assert_eq!(lexer.next_token().tok,
2164 token::DocComment(Symbol::intern("/// test")));