1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use ast::{self, Ident};
12 use syntax_pos::{self, BytePos, CharPos, Pos, Span, NO_EXPANSION};
13 use source_map::{SourceMap, FilePathMapping};
14 use errors::{Applicability, FatalError, DiagnosticBuilder};
15 use parse::{token, ParseSess};
17 use symbol::{Symbol, keywords};
18 use core::unicode::property::Pattern_White_Space;
22 use std::mem::replace;
23 use rustc_data_structures::sync::Lrc;
29 #[derive(Clone, Debug)]
30 pub struct TokenAndSpan {
31 pub tok: token::Token,
35 impl Default for TokenAndSpan {
36 fn default() -> Self {
38 tok: token::Whitespace,
39 sp: syntax_pos::DUMMY_SP,
44 pub struct StringReader<'a> {
45 pub sess: &'a ParseSess,
46 /// The absolute offset within the source_map of the next character to read
47 pub 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)
52 pub source_file: Lrc<syntax_pos::SourceFile>,
53 /// Stop reading src at this index.
54 pub 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.
63 /// Stack of open delimiters and their spans. Used for error message.
66 /// The raw source span which *does not* take `override_span` into account
68 open_braces: Vec<(token::DelimToken, Span)>,
69 /// The type and spans for all braces
71 /// Used only for error recovery when arriving to EOF with mismatched braces.
72 matching_delim_spans: Vec<(token::DelimToken, Span, Span)>,
73 crate override_span: Option<Span>,
74 last_unclosed_found_span: Option<Span>,
77 impl<'a> StringReader<'a> {
78 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
79 self.mk_sp_and_raw(lo, hi).0
82 fn mk_sp_and_raw(&self, lo: BytePos, hi: BytePos) -> (Span, Span) {
83 let raw = Span::new(lo, hi, NO_EXPANSION);
84 let real = self.override_span.unwrap_or(raw);
89 fn mk_ident(&self, string: &str) -> Ident {
90 let mut ident = Ident::from_str(string);
91 if let Some(span) = self.override_span {
98 fn unwrap_or_abort(&mut self, res: Result<TokenAndSpan, ()>) -> TokenAndSpan {
102 self.emit_fatal_errors();
108 fn next_token(&mut self) -> TokenAndSpan where Self: Sized {
109 let res = self.try_next_token();
110 self.unwrap_or_abort(res)
113 /// Return the next token. EFFECT: advances the string_reader.
114 pub fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> {
115 assert!(self.fatal_errs.is_empty());
116 let ret_val = TokenAndSpan {
117 tok: replace(&mut self.peek_tok, token::Whitespace),
120 self.advance_token()?;
121 self.span_src_raw = self.peek_span_src_raw;
126 fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> {
127 let mut t = self.try_next_token()?;
130 token::Whitespace | token::Comment | token::Shebang(_) => {
131 t = self.try_next_token()?;
137 self.token = t.tok.clone();
143 pub fn real_token(&mut self) -> TokenAndSpan {
144 let res = self.try_real_token();
145 self.unwrap_or_abort(res)
149 fn is_eof(&self) -> bool {
153 fn fail_unterminated_raw_string(&self, pos: BytePos, hash_count: u16) {
154 let mut err = self.struct_span_fatal(pos, pos, "unterminated raw string");
155 err.span_label(self.mk_sp(pos, pos), "unterminated raw string");
158 err.note(&format!("this raw string should be terminated with `\"{}`",
159 "#".repeat(hash_count as usize)));
166 fn fatal(&self, m: &str) -> FatalError {
167 self.fatal_span(self.peek_span, m)
170 pub fn emit_fatal_errors(&mut self) {
171 for err in &mut self.fatal_errs {
175 self.fatal_errs.clear();
178 pub fn peek(&self) -> TokenAndSpan {
179 // FIXME(pcwalton): Bad copy!
181 tok: self.peek_tok.clone(),
186 /// For comments.rs, which hackily pokes into next_pos and ch
187 fn new_raw(sess: &'a ParseSess,
188 source_file: Lrc<syntax_pos::SourceFile>,
189 override_span: Option<Span>) -> Self {
190 let mut sr = StringReader::new_raw_internal(sess, source_file, override_span);
196 fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc<syntax_pos::SourceFile>,
197 override_span: Option<Span>) -> Self
199 if source_file.src.is_none() {
200 sess.span_diagnostic.bug(&format!("Cannot lex source_file without source: {}",
204 let src = (*source_file.src.as_ref().unwrap()).clone();
208 next_pos: source_file.start_pos,
209 pos: source_file.start_pos,
212 end_src_index: src.len(),
213 // dummy values; not read
214 peek_tok: token::Eof,
215 peek_span: syntax_pos::DUMMY_SP,
216 peek_span_src_raw: syntax_pos::DUMMY_SP,
218 fatal_errs: Vec::new(),
220 span: syntax_pos::DUMMY_SP,
221 span_src_raw: syntax_pos::DUMMY_SP,
222 open_braces: Vec::new(),
223 matching_delim_spans: Vec::new(),
225 last_unclosed_found_span: None,
229 pub fn new(sess: &'a ParseSess,
230 source_file: Lrc<syntax_pos::SourceFile>,
231 override_span: Option<Span>) -> Self {
232 let mut sr = StringReader::new_raw(sess, source_file, override_span);
233 if sr.advance_token().is_err() {
234 sr.emit_fatal_errors();
241 pub fn new_without_err(sess: &'a ParseSess,
242 source_file: Lrc<syntax_pos::SourceFile>,
243 override_span: Option<Span>,
244 prepend_error_text: &str) -> Result<Self, ()> {
245 let mut sr = StringReader::new_raw(sess, source_file, override_span);
246 if sr.advance_token().is_err() {
247 eprintln!("{}", prepend_error_text);
248 sr.emit_fatal_errors();
254 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
255 let begin = sess.source_map().lookup_byte_offset(span.lo());
256 let end = sess.source_map().lookup_byte_offset(span.hi());
258 // Make the range zero-length if the span is invalid.
259 if span.lo() > span.hi() || begin.fm.start_pos != end.fm.start_pos {
260 span = span.shrink_to_lo();
263 let mut sr = StringReader::new_raw_internal(sess, begin.fm, None);
265 // Seek the lexer to the right byte range.
266 sr.next_pos = span.lo();
267 sr.end_src_index = sr.src_index(span.hi());
271 if sr.advance_token().is_err() {
272 sr.emit_fatal_errors();
280 fn ch_is(&self, c: char) -> bool {
284 /// Report a fatal lexical error with a given span.
285 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
286 self.sess.span_diagnostic.span_fatal(sp, m)
289 /// Report a lexical error with a given span.
290 fn err_span(&self, sp: Span, m: &str) {
291 self.sess.span_diagnostic.span_err(sp, m)
295 /// Report a fatal error spanning [`from_pos`, `to_pos`).
296 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
297 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
300 /// Report a lexical error spanning [`from_pos`, `to_pos`).
301 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
302 self.err_span(self.mk_sp(from_pos, to_pos), m)
305 /// Pushes a character to a message string for error reporting
306 fn push_escaped_char_for_msg(m: &mut String, c: char) {
308 '\u{20}'..='\u{7e}' => {
309 // Don't escape \, ' or " for user-facing messages
313 m.extend(c.escape_default());
318 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
319 /// escaped character to the error message
320 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
321 let mut m = m.to_string();
323 Self::push_escaped_char_for_msg(&mut m, c);
325 self.fatal_span_(from_pos, to_pos, &m[..])
328 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
329 -> DiagnosticBuilder<'a>
331 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
334 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
335 -> DiagnosticBuilder<'a>
337 let mut m = m.to_string();
339 Self::push_escaped_char_for_msg(&mut m, c);
341 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
344 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
345 /// escaped character to the error message
346 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
347 let mut m = m.to_string();
349 Self::push_escaped_char_for_msg(&mut m, c);
350 self.err_span_(from_pos, to_pos, &m[..]);
353 fn struct_err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
354 -> DiagnosticBuilder<'a>
356 let mut m = m.to_string();
358 Self::push_escaped_char_for_msg(&mut m, c);
360 self.sess.span_diagnostic.struct_span_err(self.mk_sp(from_pos, to_pos), &m[..])
363 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
364 /// offending string to the error message
365 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> FatalError {
367 m.push_str(&self.src[self.src_index(from_pos)..self.src_index(to_pos)]);
369 self.fatal_span_(from_pos, to_pos, &m[..])
372 /// Advance peek_tok and peek_span to refer to the next token, and
373 /// possibly update the interner.
374 fn advance_token(&mut self) -> Result<(), ()> {
375 match self.scan_whitespace_or_comment() {
377 self.peek_span_src_raw = comment.sp;
378 self.peek_span = comment.sp;
379 self.peek_tok = comment.tok;
383 self.peek_tok = token::Eof;
384 let (real, raw) = self.mk_sp_and_raw(
385 self.source_file.end_pos,
386 self.source_file.end_pos,
388 self.peek_span = real;
389 self.peek_span_src_raw = raw;
391 let start_bytepos = self.pos;
392 self.peek_tok = self.next_token_inner()?;
393 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
394 self.peek_span = real;
395 self.peek_span_src_raw = raw;
404 fn src_index(&self, pos: BytePos) -> usize {
405 (pos - self.source_file.start_pos).to_usize()
408 /// Calls `f` with a string slice of the source text spanning from `start`
409 /// up to but excluding `self.pos`, meaning the slice does not include
410 /// the character `self.ch`.
411 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
412 where F: FnOnce(&str) -> T
414 self.with_str_from_to(start, self.pos, f)
417 /// Create a Name from a given offset to the current offset, each
418 /// adjusted 1 towards each other (assumes that on either side there is a
419 /// single-byte delimiter).
420 fn name_from(&self, start: BytePos) -> ast::Name {
421 debug!("taking an ident from {:?} to {:?}", start, self.pos);
422 self.with_str_from(start, Symbol::intern)
425 /// As name_from, with an explicit endpoint.
426 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
427 debug!("taking an ident from {:?} to {:?}", start, end);
428 self.with_str_from_to(start, end, Symbol::intern)
431 /// Calls `f` with a string slice of the source text spanning from `start`
432 /// up to but excluding `end`.
433 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
434 where F: FnOnce(&str) -> T
436 f(&self.src[self.src_index(start)..self.src_index(end)])
439 /// Converts CRLF to LF in the given string, raising an error on bare CR.
440 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
443 let ch = char_at(s, i);
444 let next = i + ch.len_utf8();
446 if next < s.len() && char_at(s, next) == '\n' {
447 return translate_crlf_(self, start, s, errmsg, i).into();
449 let pos = start + BytePos(i as u32);
450 let end_pos = start + BytePos(next as u32);
451 self.err_span_(pos, end_pos, errmsg);
457 fn translate_crlf_(rdr: &StringReader,
463 let mut buf = String::with_capacity(s.len());
466 let ch = char_at(s, i);
467 let next = i + ch.len_utf8();
470 buf.push_str(&s[j..i]);
473 if next >= s.len() || char_at(s, next) != '\n' {
474 let pos = start + BytePos(i as u32);
475 let end_pos = start + BytePos(next as u32);
476 rdr.err_span_(pos, end_pos, errmsg);
482 buf.push_str(&s[j..]);
488 /// Advance the StringReader by one character. If a newline is
489 /// discovered, add it to the SourceFile's list of line start offsets.
490 crate fn bump(&mut self) {
491 let next_src_index = self.src_index(self.next_pos);
492 if next_src_index < self.end_src_index {
493 let next_ch = char_at(&self.src, next_src_index);
494 let next_ch_len = next_ch.len_utf8();
496 self.ch = Some(next_ch);
497 self.pos = self.next_pos;
498 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
501 self.pos = self.next_pos;
505 fn nextch(&self) -> Option<char> {
506 let next_src_index = self.src_index(self.next_pos);
507 if next_src_index < self.end_src_index {
508 Some(char_at(&self.src, next_src_index))
515 fn nextch_is(&self, c: char) -> bool {
516 self.nextch() == Some(c)
519 fn nextnextch(&self) -> Option<char> {
520 let next_src_index = self.src_index(self.next_pos);
521 if next_src_index < self.end_src_index {
522 let next_next_src_index =
523 next_src_index + char_at(&self.src, next_src_index).len_utf8();
524 if next_next_src_index < self.end_src_index {
525 return Some(char_at(&self.src, next_next_src_index));
532 fn nextnextch_is(&self, c: char) -> bool {
533 self.nextnextch() == Some(c)
536 /// Eats <XID_start><XID_continue>*, if possible.
537 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
538 if !ident_start(self.ch) {
542 let start = self.pos;
545 while ident_continue(self.ch) {
549 self.with_str_from(start, |string| {
551 self.sess.span_diagnostic
552 .struct_span_warn(self.mk_sp(start, self.pos),
553 "underscore literal suffix is not allowed")
554 .warn("this was previously accepted by the compiler but is \
555 being phased out; it will become a hard error in \
557 .note("for more information, see issue #42326 \
558 <https://github.com/rust-lang/rust/issues/42326>")
562 Some(Symbol::intern(string))
567 /// PRECONDITION: self.ch is not whitespace
568 /// Eats any kind of comment.
569 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
570 if let Some(c) = self.ch {
571 if c.is_whitespace() {
572 let msg = "called consume_any_line_comment, but there was whitespace";
573 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
578 match self.nextch() {
583 // line comments starting with "///" or "//!" are doc-comments
584 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
585 let start_bpos = self.pos - BytePos(2);
587 while !self.is_eof() {
588 match self.ch.unwrap() {
591 if self.nextch_is('\n') {
594 } else if doc_comment {
595 self.err_span_(self.pos,
597 "bare CR not allowed in doc-comment");
606 self.with_str_from(start_bpos, |string| {
607 // comments with only more "/"s are not doc comments
608 let tok = if is_doc_comment(string) {
609 token::DocComment(Symbol::intern(string))
616 sp: self.mk_sp(start_bpos, self.pos),
622 sp: self.mk_sp(start_bpos, self.pos),
629 self.scan_block_comment()
633 } else if self.ch_is('#') {
634 if self.nextch_is('!') {
636 // Parse an inner attribute.
637 if self.nextnextch_is('[') {
641 // I guess this is the only way to figure out if
642 // we're at the beginning of the file...
643 let cmap = SourceMap::new(FilePathMapping::empty());
644 cmap.files.borrow_mut().file_maps.push(self.source_file.clone());
645 let loc = cmap.lookup_char_pos_adj(self.pos);
646 debug!("Skipping a shebang");
647 if loc.line == 1 && loc.col == CharPos(0) {
648 // FIXME: Add shebang "token", return it
649 let start = self.pos;
650 while !self.ch_is('\n') && !self.is_eof() {
653 return Some(TokenAndSpan {
654 tok: token::Shebang(self.name_from(start)),
655 sp: self.mk_sp(start, self.pos),
665 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
667 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
668 match self.ch.unwrap_or('\0') {
669 // # to handle shebang at start of file -- this is the entry point
670 // for skipping over all "junk"
672 let c = self.scan_comment();
673 debug!("scanning a comment {:?}", c);
676 c if is_pattern_whitespace(Some(c)) => {
677 let start_bpos = self.pos;
678 while is_pattern_whitespace(self.ch) {
681 let c = Some(TokenAndSpan {
682 tok: token::Whitespace,
683 sp: self.mk_sp(start_bpos, self.pos),
685 debug!("scanning whitespace: {:?}", c);
692 /// Might return a sugared-doc-attr
693 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
694 // block comments starting with "/**" or "/*!" are doc-comments
695 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
696 let start_bpos = self.pos - BytePos(2);
698 let mut level: isize = 1;
699 let mut has_cr = false;
702 let msg = if is_doc_comment {
703 "unterminated block doc-comment"
705 "unterminated block comment"
707 let last_bpos = self.pos;
708 self.fatal_span_(start_bpos, last_bpos, msg).raise();
710 let n = self.ch.unwrap();
712 '/' if self.nextch_is('*') => {
716 '*' if self.nextch_is('/') => {
728 self.with_str_from(start_bpos, |string| {
729 // but comments with only "*"s between two "/"s are not
730 let tok = if is_block_doc_comment(string) {
731 let string = if has_cr {
732 self.translate_crlf(start_bpos,
734 "bare CR not allowed in block doc-comment")
738 token::DocComment(Symbol::intern(&string[..]))
745 sp: self.mk_sp(start_bpos, self.pos),
750 /// Scan through any digits (base `scan_radix`) or underscores,
751 /// and return how many digits there were.
753 /// `real_radix` represents the true radix of the number we're
754 /// interested in, and errors will be emitted for any digits
755 /// between `real_radix` and `scan_radix`.
756 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
757 assert!(real_radix <= scan_radix);
763 debug!("skipping a _");
767 match c.and_then(|cc| cc.to_digit(scan_radix)) {
769 debug!("{:?} in scan_digits", c);
770 // check that the hypothetical digit is actually
771 // in range for the true radix
772 if c.unwrap().to_digit(real_radix).is_none() {
773 self.err_span_(self.pos,
775 &format!("invalid digit for a base {} literal", real_radix));
785 /// Lex a LIT_INTEGER or a LIT_FLOAT
786 fn scan_number(&mut self, c: char) -> token::Lit {
788 let start_bpos = self.pos;
791 let num_digits = if c == '0' {
792 match self.ch.unwrap_or('\0') {
796 self.scan_digits(2, 10)
801 self.scan_digits(8, 10)
806 self.scan_digits(16, 16)
808 '0'..='9' | '_' | '.' | 'e' | 'E' => {
809 self.scan_digits(10, 10) + 1
813 return token::Integer(self.name_from(start_bpos));
816 } else if c.is_digit(10) {
817 self.scan_digits(10, 10) + 1
823 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
825 return token::Integer(Symbol::intern("0"));
828 // might be a float, but don't be greedy if this is actually an
829 // integer literal followed by field/method access or a range pattern
830 // (`0..2` and `12.foo()`)
831 if self.ch_is('.') && !self.nextch_is('.') &&
832 !ident_start(self.nextch()) {
833 // might have stuff after the ., and if it does, it needs to start
836 if self.ch.unwrap_or('\0').is_digit(10) {
837 self.scan_digits(10, 10);
838 self.scan_float_exponent();
841 self.check_float_base(start_bpos, pos, base);
843 token::Float(self.name_from(start_bpos))
845 // it might be a float if it has an exponent
846 if self.ch_is('e') || self.ch_is('E') {
847 self.scan_float_exponent();
849 self.check_float_base(start_bpos, pos, base);
850 return token::Float(self.name_from(start_bpos));
852 // but we certainly have an integer!
853 token::Integer(self.name_from(start_bpos))
857 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
858 /// error if too many or too few digits are encountered.
859 fn scan_hex_digits(&mut self, n_digits: usize, delim: char, below_0x7f_only: bool) -> bool {
860 debug!("scanning {} digits until {:?}", n_digits, delim);
861 let start_bpos = self.pos;
862 let mut accum_int = 0;
864 let mut valid = true;
865 for _ in 0..n_digits {
867 let last_bpos = self.pos;
868 self.fatal_span_(start_bpos,
870 "unterminated numeric character escape").raise();
872 if self.ch_is(delim) {
873 let last_bpos = self.pos;
874 self.err_span_(start_bpos,
876 "numeric character escape is too short");
880 let c = self.ch.unwrap_or('\x00');
882 accum_int += c.to_digit(16).unwrap_or_else(|| {
883 self.err_span_char(self.pos,
885 "invalid character in numeric character escape",
894 if below_0x7f_only && accum_int >= 0x80 {
895 self.err_span_(start_bpos,
897 "this form of character escape may only be used with characters in \
898 the range [\\x00-\\x7f]");
902 match char::from_u32(accum_int) {
905 let last_bpos = self.pos;
906 self.err_span_(start_bpos, last_bpos, "invalid numeric character escape");
912 /// Scan for a single (possibly escaped) byte or char
913 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
914 /// `start` is the position of `first_source_char`, which is already consumed.
916 /// Returns true if there was a valid char/byte, false otherwise.
917 fn scan_char_or_byte(&mut self,
919 first_source_char: char,
924 match first_source_char {
926 // '\X' for some X must be a character constant:
927 let escaped = self.ch;
928 let escaped_pos = self.pos;
931 None => {} // EOF here is an error that will be checked later.
934 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
935 'x' => self.scan_byte_escape(delim, !ascii_only),
937 let valid = if self.ch_is('{') {
938 self.scan_unicode_escape(delim) && !ascii_only
940 let span = self.mk_sp(start, self.pos);
941 self.sess.span_diagnostic
942 .struct_span_err(span, "incorrect unicode escape sequence")
944 "format of unicode escape sequences is \
950 self.err_span_(start,
952 "unicode escape sequences cannot be used as a \
953 byte or in a byte string");
958 '\n' if delim == '"' => {
959 self.consume_whitespace();
962 '\r' if delim == '"' && self.ch_is('\n') => {
963 self.consume_whitespace();
968 let mut err = self.struct_err_span_char(escaped_pos,
971 "unknown byte escape"
978 err.span_help(self.mk_sp(escaped_pos, pos),
979 "this is an isolated carriage return; consider \
980 checking your editor and version control \
983 if (e == '{' || e == '}') && !ascii_only {
984 err.span_help(self.mk_sp(escaped_pos, pos),
985 "if used in a formatting string, curly braces \
986 are escaped with `{{` and `}}`");
995 '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
997 self.err_span_char(start,
1000 "byte constant must be escaped"
1002 "character constant must be escaped"
1008 if self.ch_is('\n') {
1012 self.err_span_(start,
1014 "bare CR not allowed in string, use \\r instead");
1019 if ascii_only && first_source_char > '\x7F' {
1021 self.err_span_(start,
1023 "byte constant must be ASCII. Use a \\xHH escape for a \
1032 /// Scan over a `\u{...}` escape
1034 /// At this point, we have already seen the `\` and the `u`, the `{` is the current character.
1035 /// We will read a hex number (with `_` separators), with 1 to 6 actual digits,
1036 /// and pass over the `}`.
1037 fn scan_unicode_escape(&mut self, delim: char) -> bool {
1038 self.bump(); // past the {
1039 let start_bpos = self.pos;
1040 let mut valid = true;
1042 if let Some('_') = self.ch {
1043 // disallow leading `_`
1044 self.err_span_(self.pos,
1046 "invalid start of unicode escape");
1050 let count = self.scan_digits(16, 16);
1053 self.err_span_(start_bpos,
1055 "overlong unicode escape (must have at most 6 hex digits)");
1062 if valid && count == 0 {
1063 self.err_span_(start_bpos,
1065 "empty unicode escape (must have at least 1 hex digit)");
1068 self.bump(); // past the ending `}`
1073 self.err_span_(self.pos,
1075 "unterminated unicode escape (needed a `}`)");
1079 self.err_span_char(start_bpos,
1081 "invalid character in unicode escape",
1087 self.fatal_span_(start_bpos,
1089 "unterminated unicode escape (found EOF)").raise();
1098 /// Scan over a float exponent.
1099 fn scan_float_exponent(&mut self) {
1100 if self.ch_is('e') || self.ch_is('E') {
1103 if self.ch_is('-') || self.ch_is('+') {
1107 if self.scan_digits(10, 10) == 0 {
1108 let mut err = self.struct_span_fatal(
1109 self.pos, self.next_pos,
1110 "expected at least one digit in exponent"
1112 if let Some(ch) = self.ch {
1113 // check for e.g. Unicode minus '−' (Issue #49746)
1114 if unicode_chars::check_for_substitution(self, ch, &mut err) {
1116 self.scan_digits(10, 10);
1124 /// Check that a base is valid for a floating literal, emitting a nice
1125 /// error if it isn't.
1126 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
1129 self.err_span_(start_bpos,
1131 "hexadecimal float literal is not supported")
1134 self.err_span_(start_bpos,
1136 "octal float literal is not supported")
1139 self.err_span_(start_bpos,
1141 "binary float literal is not supported")
1147 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
1149 if self.ch_is('=') {
1157 /// Return the next token from the string, advances the input past that
1158 /// token, and updates the interner
1159 fn next_token_inner(&mut self) -> Result<token::Token, ()> {
1163 let (is_ident_start, is_raw_ident) =
1164 match (c.unwrap(), self.nextch(), self.nextnextch()) {
1165 // r# followed by an identifier starter is a raw identifier.
1166 // This is an exception to the r# case below.
1167 ('r', Some('#'), x) if ident_start(x) => (true, true),
1168 // r as in r" or r#" is part of a raw string literal.
1169 // b as in b' is part of a byte literal.
1170 // They are not identifiers, and are handled further down.
1171 ('r', Some('"'), _) |
1172 ('r', Some('#'), _) |
1173 ('b', Some('"'), _) |
1174 ('b', Some('\''), _) |
1175 ('b', Some('r'), Some('"')) |
1176 ('b', Some('r'), Some('#')) => (false, false),
1181 let raw_start = self.pos;
1183 // Consume the 'r#' characters.
1188 let start = self.pos;
1191 while ident_continue(self.ch) {
1195 return Ok(self.with_str_from(start, |string| {
1196 // FIXME: perform NFKC normalization here. (Issue #2253)
1197 let ident = self.mk_ident(string);
1199 if is_raw_ident && (ident.is_path_segment_keyword() ||
1200 ident.name == keywords::Underscore.name()) {
1201 self.fatal_span_(raw_start, self.pos,
1202 &format!("`r#{}` is not currently supported.", ident.name)
1207 let span = self.mk_sp(raw_start, self.pos);
1208 self.sess.raw_identifier_spans.borrow_mut().push(span);
1211 token::Ident(ident, is_raw_ident)
1216 if is_dec_digit(c) {
1217 let num = self.scan_number(c.unwrap());
1218 let suffix = self.scan_optional_raw_name();
1219 debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
1220 return Ok(token::Literal(num, suffix));
1223 match c.expect("next_token_inner called at EOF") {
1235 if self.ch_is('.') {
1237 if self.ch_is('.') {
1239 Ok(token::DotDotDot)
1240 } else if self.ch_is('=') {
1252 Ok(token::OpenDelim(token::Paren))
1256 Ok(token::CloseDelim(token::Paren))
1260 Ok(token::OpenDelim(token::Brace))
1264 Ok(token::CloseDelim(token::Brace))
1268 Ok(token::OpenDelim(token::Bracket))
1272 Ok(token::CloseDelim(token::Bracket))
1292 if self.ch_is(':') {
1305 // Multi-byte tokens.
1308 if self.ch_is('=') {
1311 } else if self.ch_is('>') {
1320 if self.ch_is('=') {
1329 match self.ch.unwrap_or('\x00') {
1335 Ok(self.binop(token::Shl))
1348 match self.ch.unwrap_or('\x00') {
1354 Ok(self.binop(token::Shr))
1362 // Either a character constant 'a' OR a lifetime name 'abc
1363 let start_with_quote = self.pos;
1365 let start = self.pos;
1367 // the eof will be picked up by the final `'` check below
1368 let c2 = self.ch.unwrap_or('\x00');
1371 // If the character is an ident start not followed by another single
1372 // quote, then this is a lifetime name:
1373 if ident_start(Some(c2)) && !self.ch_is('\'') {
1374 while ident_continue(self.ch) {
1377 // lifetimes shouldn't end with a single quote
1378 // if we find one, then this is an invalid character literal
1379 if self.ch_is('\'') {
1380 self.fatal_span_verbose(start_with_quote, self.next_pos,
1381 String::from("character literal may only contain one codepoint"))
1386 // Include the leading `'` in the real identifier, for macro
1387 // expansion purposes. See #12512 for the gory details of why
1388 // this is necessary.
1389 let ident = self.with_str_from(start, |lifetime_name| {
1390 self.mk_ident(&format!("'{}", lifetime_name))
1393 return Ok(token::Lifetime(ident));
1396 let valid = self.scan_char_or_byte(start, c2, /* ascii_only */ false, '\'');
1398 if !self.ch_is('\'') {
1403 if self.ch_is('\'') {
1404 let start = self.src_index(start);
1405 let end = self.src_index(self.pos);
1407 let span = self.mk_sp(start_with_quote, self.pos);
1408 self.sess.span_diagnostic
1409 .struct_span_err(span,
1410 "character literal may only contain one codepoint")
1411 .span_suggestion_with_applicability(
1413 "if you meant to write a `str` literal, use double quotes",
1414 format!("\"{}\"", &self.src[start..end]),
1415 Applicability::MachineApplicable
1417 return Ok(token::Literal(token::Str_(Symbol::intern("??")), None))
1419 if self.ch_is('\n') || self.is_eof() || self.ch_is('/') {
1420 // Only attempt to infer single line string literals. If we encounter
1421 // a slash, bail out in order to avoid nonsensical suggestion when
1422 // involving comments.
1427 self.fatal_span_verbose(start_with_quote, pos,
1428 String::from("character literal may only contain one codepoint")).raise();
1432 self.name_from(start)
1437 self.bump(); // advance ch past token
1438 let suffix = self.scan_optional_raw_name();
1440 Ok(token::Literal(token::Char(id), suffix))
1444 let lit = match self.ch {
1445 Some('\'') => self.scan_byte(),
1446 Some('"') => self.scan_byte_string(),
1447 Some('r') => self.scan_raw_byte_string(),
1448 _ => unreachable!(), // Should have been a token::Ident above.
1450 let suffix = self.scan_optional_raw_name();
1452 Ok(token::Literal(lit, suffix))
1455 let start_bpos = self.pos;
1456 let mut valid = true;
1459 while !self.ch_is('"') {
1461 let last_bpos = self.pos;
1462 self.fatal_span_(start_bpos,
1464 "unterminated double quote string").raise();
1467 let ch_start = self.pos;
1468 let ch = self.ch.unwrap();
1470 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only */ false, '"');
1472 // adjust for the ASCII " at the start of the literal
1474 self.name_from(start_bpos + BytePos(1))
1476 Symbol::intern("??")
1479 let suffix = self.scan_optional_raw_name();
1481 Ok(token::Literal(token::Str_(id), suffix))
1484 let start_bpos = self.pos;
1486 let mut hash_count: u16 = 0;
1487 while self.ch_is('#') {
1488 if hash_count == 65535 {
1489 let bpos = self.next_pos;
1490 self.fatal_span_(start_bpos,
1492 "too many `#` symbols: raw strings may be \
1493 delimited by up to 65535 `#` symbols").raise();
1500 self.fail_unterminated_raw_string(start_bpos, hash_count);
1501 } else if !self.ch_is('"') {
1502 let last_bpos = self.pos;
1503 let curr_char = self.ch.unwrap();
1504 self.fatal_span_char(start_bpos,
1506 "found invalid character; only `#` is allowed \
1507 in raw string delimitation",
1511 let content_start_bpos = self.pos;
1512 let mut content_end_bpos;
1513 let mut valid = true;
1516 self.fail_unterminated_raw_string(start_bpos, hash_count);
1518 // if self.ch_is('"') {
1519 // content_end_bpos = self.pos;
1520 // for _ in 0..hash_count {
1522 // if !self.ch_is('#') {
1524 let c = self.ch.unwrap();
1527 content_end_bpos = self.pos;
1528 for _ in 0..hash_count {
1530 if !self.ch_is('#') {
1537 if !self.nextch_is('\n') {
1538 let last_bpos = self.pos;
1539 self.err_span_(start_bpos,
1541 "bare CR not allowed in raw string, use \\r \
1553 self.name_from_to(content_start_bpos, content_end_bpos)
1555 Symbol::intern("??")
1557 let suffix = self.scan_optional_raw_name();
1559 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1562 if self.nextch_is('>') {
1567 Ok(self.binop(token::Minus))
1571 if self.nextch_is('&') {
1576 Ok(self.binop(token::And))
1580 match self.nextch() {
1587 Ok(self.binop(token::Or))
1592 Ok(self.binop(token::Plus))
1595 Ok(self.binop(token::Star))
1598 Ok(self.binop(token::Slash))
1601 Ok(self.binop(token::Caret))
1604 Ok(self.binop(token::Percent))
1607 let last_bpos = self.pos;
1608 let bpos = self.next_pos;
1609 let mut err = self.struct_fatal_span_char(last_bpos,
1611 "unknown start of token",
1613 unicode_chars::check_for_substitution(self, c, &mut err);
1614 self.fatal_errs.push(err);
1621 fn consume_whitespace(&mut self) {
1622 while is_pattern_whitespace(self.ch) && !self.is_eof() {
1627 fn read_to_eol(&mut self) -> String {
1628 let mut val = String::new();
1629 while !self.ch_is('\n') && !self.is_eof() {
1630 val.push(self.ch.unwrap());
1634 if self.ch_is('\n') {
1641 fn read_one_line_comment(&mut self) -> String {
1642 let val = self.read_to_eol();
1643 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1644 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1648 fn consume_non_eol_whitespace(&mut self) {
1649 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1654 fn peeking_at_comment(&self) -> bool {
1655 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1656 // consider shebangs comments, but not inner attributes
1657 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1660 fn scan_byte(&mut self) -> token::Lit {
1662 let start = self.pos;
1664 // the eof will be picked up by the final `'` check below
1665 let c2 = self.ch.unwrap_or('\x00');
1668 let valid = self.scan_char_or_byte(start,
1673 if !self.ch_is('\'') {
1674 // Byte offsetting here is okay because the
1675 // character before position `start` are an
1676 // ascii single quote and ascii 'b'.
1678 self.fatal_span_verbose(start - BytePos(2),
1680 "unterminated byte constant".to_string()).raise();
1684 self.name_from(start)
1688 self.bump(); // advance ch past token
1694 fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1695 self.scan_hex_digits(2, delim, below_0x7f_only)
1698 fn scan_byte_string(&mut self) -> token::Lit {
1700 let start = self.pos;
1701 let mut valid = true;
1703 while !self.ch_is('"') {
1706 self.fatal_span_(start, pos, "unterminated double quote byte string").raise();
1709 let ch_start = self.pos;
1710 let ch = self.ch.unwrap();
1712 valid &= self.scan_char_or_byte(ch_start,
1720 self.name_from(start)
1722 Symbol::intern("??")
1729 fn scan_raw_byte_string(&mut self) -> token::Lit {
1730 let start_bpos = self.pos;
1732 let mut hash_count = 0;
1733 while self.ch_is('#') {
1734 if hash_count == 65535 {
1735 let bpos = self.next_pos;
1736 self.fatal_span_(start_bpos,
1738 "too many `#` symbols: raw byte strings may be \
1739 delimited by up to 65535 `#` symbols").raise();
1746 self.fail_unterminated_raw_string(start_bpos, hash_count);
1747 } else if !self.ch_is('"') {
1749 let ch = self.ch.unwrap();
1750 self.fatal_span_char(start_bpos,
1752 "found invalid character; only `#` is allowed in raw \
1753 string delimitation",
1757 let content_start_bpos = self.pos;
1758 let mut content_end_bpos;
1762 self.fail_unterminated_raw_string(start_bpos, hash_count);
1765 content_end_bpos = self.pos;
1766 for _ in 0..hash_count {
1768 if !self.ch_is('#') {
1777 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1786 token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), hash_count)
1790 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1791 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1793 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1794 c.map_or(false, Pattern_White_Space)
1798 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1799 c.map_or(false, |c| lo <= c && c <= hi)
1803 fn is_dec_digit(c: Option<char>) -> bool {
1804 in_range(c, '0', '9')
1807 fn is_doc_comment(s: &str) -> bool {
1808 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1809 s.starts_with("//!");
1810 debug!("is {:?} a doc comment? {}", s, res);
1814 fn is_block_doc_comment(s: &str) -> bool {
1815 // Prevent `/**/` from being parsed as a doc comment
1816 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1817 s.starts_with("/*!")) && s.len() >= 5;
1818 debug!("is {:?} a doc comment? {}", s, res);
1822 fn ident_start(c: Option<char>) -> bool {
1825 None => return false,
1828 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1831 fn ident_continue(c: Option<char>) -> bool {
1834 None => return false,
1837 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1838 (c > '\x7f' && c.is_xid_continue())
1845 use ast::{Ident, CrateConfig};
1847 use syntax_pos::{BytePos, Span, NO_EXPANSION};
1848 use source_map::SourceMap;
1850 use feature_gate::UnstableFeatures;
1853 use std::path::PathBuf;
1854 use diagnostics::plugin::ErrorMap;
1855 use rustc_data_structures::fx::FxHashSet;
1856 use rustc_data_structures::sync::Lock;
1858 fn mk_sess(cm: Lrc<SourceMap>) -> ParseSess {
1859 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1864 span_diagnostic: errors::Handler::with_emitter(true, false, Box::new(emitter)),
1865 unstable_features: UnstableFeatures::from_environment(),
1866 config: CrateConfig::default(),
1867 included_mod_stack: Lock::new(Vec::new()),
1869 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1870 raw_identifier_spans: Lock::new(Vec::new()),
1871 registered_diagnostics: Lock::new(ErrorMap::new()),
1872 non_modrs_mods: Lock::new(vec![]),
1873 buffered_lints: Lock::new(vec![]),
1877 // open a string reader for the given string
1878 fn setup<'a>(cm: &SourceMap,
1879 sess: &'a ParseSess,
1881 -> StringReader<'a> {
1882 let fm = cm.new_source_file(PathBuf::from("zebra.rs").into(), teststr);
1883 StringReader::new(sess, fm, None)
1889 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1890 let sh = mk_sess(cm.clone());
1891 let mut string_reader = setup(&cm,
1893 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1895 let id = Ident::from_str("fn");
1896 assert_eq!(string_reader.next_token().tok, token::Comment);
1897 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1898 let tok1 = string_reader.next_token();
1899 let tok2 = TokenAndSpan {
1900 tok: token::Ident(id, false),
1901 sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1903 assert_eq!(tok1.tok, tok2.tok);
1904 assert_eq!(tok1.sp, tok2.sp);
1905 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1906 // the 'main' id is already read:
1907 assert_eq!(string_reader.pos.clone(), BytePos(28));
1908 // read another token:
1909 let tok3 = string_reader.next_token();
1910 let tok4 = TokenAndSpan {
1911 tok: mk_ident("main"),
1912 sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1914 assert_eq!(tok3.tok, tok4.tok);
1915 assert_eq!(tok3.sp, tok4.sp);
1916 // the lparen is already read:
1917 assert_eq!(string_reader.pos.clone(), BytePos(29))
1921 // check that the given reader produces the desired stream
1922 // of tokens (stop checking after exhausting the expected vec)
1923 fn check_tokenization(mut string_reader: StringReader, expected: Vec<token::Token>) {
1924 for expected_tok in &expected {
1925 assert_eq!(&string_reader.next_token().tok, expected_tok);
1929 // make the identifier by looking up the string in the interner
1930 fn mk_ident(id: &str) -> token::Token {
1931 token::Token::from_ast_ident(Ident::from_str(id))
1935 fn doublecolonparsing() {
1937 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1938 let sh = mk_sess(cm.clone());
1939 check_tokenization(setup(&cm, &sh, "a b".to_string()),
1940 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1947 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1948 let sh = mk_sess(cm.clone());
1949 check_tokenization(setup(&cm, &sh, "a::b".to_string()),
1950 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1957 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1958 let sh = mk_sess(cm.clone());
1959 check_tokenization(setup(&cm, &sh, "a ::b".to_string()),
1960 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
1967 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1968 let sh = mk_sess(cm.clone());
1969 check_tokenization(setup(&cm, &sh, "a:: b".to_string()),
1970 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
1977 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1978 let sh = mk_sess(cm.clone());
1979 assert_eq!(setup(&cm, &sh, "'a'".to_string()).next_token().tok,
1980 token::Literal(token::Char(Symbol::intern("a")), None));
1985 fn character_space() {
1987 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1988 let sh = mk_sess(cm.clone());
1989 assert_eq!(setup(&cm, &sh, "' '".to_string()).next_token().tok,
1990 token::Literal(token::Char(Symbol::intern(" ")), None));
1995 fn character_escaped() {
1997 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1998 let sh = mk_sess(cm.clone());
1999 assert_eq!(setup(&cm, &sh, "'\\n'".to_string()).next_token().tok,
2000 token::Literal(token::Char(Symbol::intern("\\n")), None));
2005 fn lifetime_name() {
2007 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2008 let sh = mk_sess(cm.clone());
2009 assert_eq!(setup(&cm, &sh, "'abc".to_string()).next_token().tok,
2010 token::Lifetime(Ident::from_str("'abc")));
2017 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2018 let sh = mk_sess(cm.clone());
2019 assert_eq!(setup(&cm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
2022 token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
2027 fn literal_suffixes() {
2029 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2030 let sh = mk_sess(cm.clone());
2032 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
2033 assert_eq!(setup(&cm, &sh, format!("{}suffix", $input)).next_token().tok,
2034 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2035 Some(Symbol::intern("suffix"))));
2036 // with a whitespace separator:
2037 assert_eq!(setup(&cm, &sh, format!("{} suffix", $input)).next_token().tok,
2038 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2043 test!("'a'", Char, "a");
2044 test!("b'a'", Byte, "a");
2045 test!("\"a\"", Str_, "a");
2046 test!("b\"a\"", ByteStr, "a");
2047 test!("1234", Integer, "1234");
2048 test!("0b101", Integer, "0b101");
2049 test!("0xABC", Integer, "0xABC");
2050 test!("1.0", Float, "1.0");
2051 test!("1.0e10", Float, "1.0e10");
2053 assert_eq!(setup(&cm, &sh, "2us".to_string()).next_token().tok,
2054 token::Literal(token::Integer(Symbol::intern("2")),
2055 Some(Symbol::intern("us"))));
2056 assert_eq!(setup(&cm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
2057 token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
2058 Some(Symbol::intern("suffix"))));
2059 assert_eq!(setup(&cm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
2060 token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
2061 Some(Symbol::intern("suffix"))));
2066 fn line_doc_comments() {
2067 assert!(is_doc_comment("///"));
2068 assert!(is_doc_comment("/// blah"));
2069 assert!(!is_doc_comment("////"));
2073 fn nested_block_comments() {
2075 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2076 let sh = mk_sess(cm.clone());
2077 let mut lexer = setup(&cm, &sh, "/* /* */ */'a'".to_string());
2078 match lexer.next_token().tok {
2079 token::Comment => {}
2080 _ => panic!("expected a comment!"),
2082 assert_eq!(lexer.next_token().tok,
2083 token::Literal(token::Char(Symbol::intern("a")), None));
2088 fn crlf_comments() {
2090 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2091 let sh = mk_sess(cm.clone());
2092 let mut lexer = setup(&cm, &sh, "// test\r\n/// test\r\n".to_string());
2093 let comment = lexer.next_token();
2094 assert_eq!(comment.tok, token::Comment);
2095 assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
2096 assert_eq!(lexer.next_token().tok, token::Whitespace);
2097 assert_eq!(lexer.next_token().tok,
2098 token::DocComment(Symbol::intern("/// test")));