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 retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
242 let begin = sess.source_map().lookup_byte_offset(span.lo());
243 let end = sess.source_map().lookup_byte_offset(span.hi());
245 // Make the range zero-length if the span is invalid.
246 if span.lo() > span.hi() || begin.fm.start_pos != end.fm.start_pos {
247 span = span.shrink_to_lo();
250 let mut sr = StringReader::new_raw_internal(sess, begin.fm, None);
252 // Seek the lexer to the right byte range.
253 sr.next_pos = span.lo();
254 sr.end_src_index = sr.src_index(span.hi());
258 if sr.advance_token().is_err() {
259 sr.emit_fatal_errors();
267 fn ch_is(&self, c: char) -> bool {
271 /// Report a fatal lexical error with a given span.
272 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
273 self.sess.span_diagnostic.span_fatal(sp, m)
276 /// Report a lexical error with a given span.
277 fn err_span(&self, sp: Span, m: &str) {
278 self.sess.span_diagnostic.span_err(sp, m)
282 /// Report a fatal error spanning [`from_pos`, `to_pos`).
283 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
284 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
287 /// Report a lexical error spanning [`from_pos`, `to_pos`).
288 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
289 self.err_span(self.mk_sp(from_pos, to_pos), m)
292 /// Pushes a character to a message string for error reporting
293 fn push_escaped_char_for_msg(m: &mut String, c: char) {
295 '\u{20}'..='\u{7e}' => {
296 // Don't escape \, ' or " for user-facing messages
300 m.extend(c.escape_default());
305 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
306 /// escaped character to the error message
307 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
308 let mut m = m.to_string();
310 Self::push_escaped_char_for_msg(&mut m, c);
312 self.fatal_span_(from_pos, to_pos, &m[..])
315 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
316 -> DiagnosticBuilder<'a>
318 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
321 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
322 -> DiagnosticBuilder<'a>
324 let mut m = m.to_string();
326 Self::push_escaped_char_for_msg(&mut m, c);
328 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
331 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
332 /// escaped character to the error message
333 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
334 let mut m = m.to_string();
336 Self::push_escaped_char_for_msg(&mut m, c);
337 self.err_span_(from_pos, to_pos, &m[..]);
340 fn struct_err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
341 -> DiagnosticBuilder<'a>
343 let mut m = m.to_string();
345 Self::push_escaped_char_for_msg(&mut m, c);
347 self.sess.span_diagnostic.struct_span_err(self.mk_sp(from_pos, to_pos), &m[..])
350 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
351 /// offending string to the error message
352 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> FatalError {
354 m.push_str(&self.src[self.src_index(from_pos)..self.src_index(to_pos)]);
356 self.fatal_span_(from_pos, to_pos, &m[..])
359 /// Advance peek_tok and peek_span to refer to the next token, and
360 /// possibly update the interner.
361 fn advance_token(&mut self) -> Result<(), ()> {
362 match self.scan_whitespace_or_comment() {
364 self.peek_span_src_raw = comment.sp;
365 self.peek_span = comment.sp;
366 self.peek_tok = comment.tok;
370 self.peek_tok = token::Eof;
371 let (real, raw) = self.mk_sp_and_raw(
372 self.source_file.end_pos,
373 self.source_file.end_pos,
375 self.peek_span = real;
376 self.peek_span_src_raw = raw;
378 let start_bytepos = self.pos;
379 self.peek_tok = self.next_token_inner()?;
380 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
381 self.peek_span = real;
382 self.peek_span_src_raw = raw;
391 fn src_index(&self, pos: BytePos) -> usize {
392 (pos - self.source_file.start_pos).to_usize()
395 /// Calls `f` with a string slice of the source text spanning from `start`
396 /// up to but excluding `self.pos`, meaning the slice does not include
397 /// the character `self.ch`.
398 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
399 where F: FnOnce(&str) -> T
401 self.with_str_from_to(start, self.pos, f)
404 /// Create a Name from a given offset to the current offset, each
405 /// adjusted 1 towards each other (assumes that on either side there is a
406 /// single-byte delimiter).
407 fn name_from(&self, start: BytePos) -> ast::Name {
408 debug!("taking an ident from {:?} to {:?}", start, self.pos);
409 self.with_str_from(start, Symbol::intern)
412 /// As name_from, with an explicit endpoint.
413 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
414 debug!("taking an ident from {:?} to {:?}", start, end);
415 self.with_str_from_to(start, end, Symbol::intern)
418 /// Calls `f` with a string slice of the source text spanning from `start`
419 /// up to but excluding `end`.
420 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
421 where F: FnOnce(&str) -> T
423 f(&self.src[self.src_index(start)..self.src_index(end)])
426 /// Converts CRLF to LF in the given string, raising an error on bare CR.
427 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
430 let ch = char_at(s, i);
431 let next = i + ch.len_utf8();
433 if next < s.len() && char_at(s, next) == '\n' {
434 return translate_crlf_(self, start, s, errmsg, i).into();
436 let pos = start + BytePos(i as u32);
437 let end_pos = start + BytePos(next as u32);
438 self.err_span_(pos, end_pos, errmsg);
444 fn translate_crlf_(rdr: &StringReader,
450 let mut buf = String::with_capacity(s.len());
453 let ch = char_at(s, i);
454 let next = i + ch.len_utf8();
457 buf.push_str(&s[j..i]);
460 if next >= s.len() || char_at(s, next) != '\n' {
461 let pos = start + BytePos(i as u32);
462 let end_pos = start + BytePos(next as u32);
463 rdr.err_span_(pos, end_pos, errmsg);
469 buf.push_str(&s[j..]);
475 /// Advance the StringReader by one character. If a newline is
476 /// discovered, add it to the SourceFile's list of line start offsets.
477 crate fn bump(&mut self) {
478 let next_src_index = self.src_index(self.next_pos);
479 if next_src_index < self.end_src_index {
480 let next_ch = char_at(&self.src, next_src_index);
481 let next_ch_len = next_ch.len_utf8();
483 self.ch = Some(next_ch);
484 self.pos = self.next_pos;
485 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
488 self.pos = self.next_pos;
492 fn nextch(&self) -> Option<char> {
493 let next_src_index = self.src_index(self.next_pos);
494 if next_src_index < self.end_src_index {
495 Some(char_at(&self.src, next_src_index))
502 fn nextch_is(&self, c: char) -> bool {
503 self.nextch() == Some(c)
506 fn nextnextch(&self) -> Option<char> {
507 let next_src_index = self.src_index(self.next_pos);
508 if next_src_index < self.end_src_index {
509 let next_next_src_index =
510 next_src_index + char_at(&self.src, next_src_index).len_utf8();
511 if next_next_src_index < self.end_src_index {
512 return Some(char_at(&self.src, next_next_src_index));
519 fn nextnextch_is(&self, c: char) -> bool {
520 self.nextnextch() == Some(c)
523 /// Eats <XID_start><XID_continue>*, if possible.
524 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
525 if !ident_start(self.ch) {
529 let start = self.pos;
532 while ident_continue(self.ch) {
536 self.with_str_from(start, |string| {
538 self.sess.span_diagnostic
539 .struct_span_warn(self.mk_sp(start, self.pos),
540 "underscore literal suffix is not allowed")
541 .warn("this was previously accepted by the compiler but is \
542 being phased out; it will become a hard error in \
544 .note("for more information, see issue #42326 \
545 <https://github.com/rust-lang/rust/issues/42326>")
549 Some(Symbol::intern(string))
554 /// PRECONDITION: self.ch is not whitespace
555 /// Eats any kind of comment.
556 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
557 if let Some(c) = self.ch {
558 if c.is_whitespace() {
559 let msg = "called consume_any_line_comment, but there was whitespace";
560 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
565 match self.nextch() {
570 // line comments starting with "///" or "//!" are doc-comments
571 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
572 let start_bpos = self.pos - BytePos(2);
574 while !self.is_eof() {
575 match self.ch.unwrap() {
578 if self.nextch_is('\n') {
581 } else if doc_comment {
582 self.err_span_(self.pos,
584 "bare CR not allowed in doc-comment");
593 self.with_str_from(start_bpos, |string| {
594 // comments with only more "/"s are not doc comments
595 let tok = if is_doc_comment(string) {
596 token::DocComment(Symbol::intern(string))
603 sp: self.mk_sp(start_bpos, self.pos),
609 sp: self.mk_sp(start_bpos, self.pos),
616 self.scan_block_comment()
620 } else if self.ch_is('#') {
621 if self.nextch_is('!') {
623 // Parse an inner attribute.
624 if self.nextnextch_is('[') {
628 // I guess this is the only way to figure out if
629 // we're at the beginning of the file...
630 let cmap = SourceMap::new(FilePathMapping::empty());
631 cmap.files.borrow_mut().file_maps.push(self.source_file.clone());
632 let loc = cmap.lookup_char_pos_adj(self.pos);
633 debug!("Skipping a shebang");
634 if loc.line == 1 && loc.col == CharPos(0) {
635 // FIXME: Add shebang "token", return it
636 let start = self.pos;
637 while !self.ch_is('\n') && !self.is_eof() {
640 return Some(TokenAndSpan {
641 tok: token::Shebang(self.name_from(start)),
642 sp: self.mk_sp(start, self.pos),
652 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
654 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
655 match self.ch.unwrap_or('\0') {
656 // # to handle shebang at start of file -- this is the entry point
657 // for skipping over all "junk"
659 let c = self.scan_comment();
660 debug!("scanning a comment {:?}", c);
663 c if is_pattern_whitespace(Some(c)) => {
664 let start_bpos = self.pos;
665 while is_pattern_whitespace(self.ch) {
668 let c = Some(TokenAndSpan {
669 tok: token::Whitespace,
670 sp: self.mk_sp(start_bpos, self.pos),
672 debug!("scanning whitespace: {:?}", c);
679 /// Might return a sugared-doc-attr
680 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
681 // block comments starting with "/**" or "/*!" are doc-comments
682 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
683 let start_bpos = self.pos - BytePos(2);
685 let mut level: isize = 1;
686 let mut has_cr = false;
689 let msg = if is_doc_comment {
690 "unterminated block doc-comment"
692 "unterminated block comment"
694 let last_bpos = self.pos;
695 self.fatal_span_(start_bpos, last_bpos, msg).raise();
697 let n = self.ch.unwrap();
699 '/' if self.nextch_is('*') => {
703 '*' if self.nextch_is('/') => {
715 self.with_str_from(start_bpos, |string| {
716 // but comments with only "*"s between two "/"s are not
717 let tok = if is_block_doc_comment(string) {
718 let string = if has_cr {
719 self.translate_crlf(start_bpos,
721 "bare CR not allowed in block doc-comment")
725 token::DocComment(Symbol::intern(&string[..]))
732 sp: self.mk_sp(start_bpos, self.pos),
737 /// Scan through any digits (base `scan_radix`) or underscores,
738 /// and return how many digits there were.
740 /// `real_radix` represents the true radix of the number we're
741 /// interested in, and errors will be emitted for any digits
742 /// between `real_radix` and `scan_radix`.
743 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
744 assert!(real_radix <= scan_radix);
750 debug!("skipping a _");
754 match c.and_then(|cc| cc.to_digit(scan_radix)) {
756 debug!("{:?} in scan_digits", c);
757 // check that the hypothetical digit is actually
758 // in range for the true radix
759 if c.unwrap().to_digit(real_radix).is_none() {
760 self.err_span_(self.pos,
762 &format!("invalid digit for a base {} literal", real_radix));
772 /// Lex a LIT_INTEGER or a LIT_FLOAT
773 fn scan_number(&mut self, c: char) -> token::Lit {
775 let start_bpos = self.pos;
778 let num_digits = if c == '0' {
779 match self.ch.unwrap_or('\0') {
783 self.scan_digits(2, 10)
788 self.scan_digits(8, 10)
793 self.scan_digits(16, 16)
795 '0'..='9' | '_' | '.' | 'e' | 'E' => {
796 self.scan_digits(10, 10) + 1
800 return token::Integer(self.name_from(start_bpos));
803 } else if c.is_digit(10) {
804 self.scan_digits(10, 10) + 1
810 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
812 return token::Integer(Symbol::intern("0"));
815 // might be a float, but don't be greedy if this is actually an
816 // integer literal followed by field/method access or a range pattern
817 // (`0..2` and `12.foo()`)
818 if self.ch_is('.') && !self.nextch_is('.') &&
819 !ident_start(self.nextch()) {
820 // might have stuff after the ., and if it does, it needs to start
823 if self.ch.unwrap_or('\0').is_digit(10) {
824 self.scan_digits(10, 10);
825 self.scan_float_exponent();
828 self.check_float_base(start_bpos, pos, base);
830 token::Float(self.name_from(start_bpos))
832 // it might be a float if it has an exponent
833 if self.ch_is('e') || self.ch_is('E') {
834 self.scan_float_exponent();
836 self.check_float_base(start_bpos, pos, base);
837 return token::Float(self.name_from(start_bpos));
839 // but we certainly have an integer!
840 token::Integer(self.name_from(start_bpos))
844 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
845 /// error if too many or too few digits are encountered.
846 fn scan_hex_digits(&mut self, n_digits: usize, delim: char, below_0x7f_only: bool) -> bool {
847 debug!("scanning {} digits until {:?}", n_digits, delim);
848 let start_bpos = self.pos;
849 let mut accum_int = 0;
851 let mut valid = true;
852 for _ in 0..n_digits {
854 let last_bpos = self.pos;
855 self.fatal_span_(start_bpos,
857 "unterminated numeric character escape").raise();
859 if self.ch_is(delim) {
860 let last_bpos = self.pos;
861 self.err_span_(start_bpos,
863 "numeric character escape is too short");
867 let c = self.ch.unwrap_or('\x00');
869 accum_int += c.to_digit(16).unwrap_or_else(|| {
870 self.err_span_char(self.pos,
872 "invalid character in numeric character escape",
881 if below_0x7f_only && accum_int >= 0x80 {
882 self.err_span_(start_bpos,
884 "this form of character escape may only be used with characters in \
885 the range [\\x00-\\x7f]");
889 match char::from_u32(accum_int) {
892 let last_bpos = self.pos;
893 self.err_span_(start_bpos, last_bpos, "invalid numeric character escape");
899 /// Scan for a single (possibly escaped) byte or char
900 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
901 /// `start` is the position of `first_source_char`, which is already consumed.
903 /// Returns true if there was a valid char/byte, false otherwise.
904 fn scan_char_or_byte(&mut self,
906 first_source_char: char,
911 match first_source_char {
913 // '\X' for some X must be a character constant:
914 let escaped = self.ch;
915 let escaped_pos = self.pos;
918 None => {} // EOF here is an error that will be checked later.
921 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
922 'x' => self.scan_byte_escape(delim, !ascii_only),
924 let valid = if self.ch_is('{') {
925 self.scan_unicode_escape(delim) && !ascii_only
927 let span = self.mk_sp(start, self.pos);
928 self.sess.span_diagnostic
929 .struct_span_err(span, "incorrect unicode escape sequence")
931 "format of unicode escape sequences is \
937 self.err_span_(start,
939 "unicode escape sequences cannot be used as a \
940 byte or in a byte string");
945 '\n' if delim == '"' => {
946 self.consume_whitespace();
949 '\r' if delim == '"' && self.ch_is('\n') => {
950 self.consume_whitespace();
955 let mut err = self.struct_err_span_char(escaped_pos,
958 "unknown byte escape"
965 err.span_help(self.mk_sp(escaped_pos, pos),
966 "this is an isolated carriage return; consider \
967 checking your editor and version control \
970 if (e == '{' || e == '}') && !ascii_only {
971 err.span_help(self.mk_sp(escaped_pos, pos),
972 "if used in a formatting string, curly braces \
973 are escaped with `{{` and `}}`");
982 '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
984 self.err_span_char(start,
987 "byte constant must be escaped"
989 "character constant must be escaped"
995 if self.ch_is('\n') {
999 self.err_span_(start,
1001 "bare CR not allowed in string, use \\r instead");
1006 if ascii_only && first_source_char > '\x7F' {
1008 self.err_span_(start,
1010 "byte constant must be ASCII. Use a \\xHH escape for a \
1019 /// Scan over a `\u{...}` escape
1021 /// At this point, we have already seen the `\` and the `u`, the `{` is the current character.
1022 /// We will read a hex number (with `_` separators), with 1 to 6 actual digits,
1023 /// and pass over the `}`.
1024 fn scan_unicode_escape(&mut self, delim: char) -> bool {
1025 self.bump(); // past the {
1026 let start_bpos = self.pos;
1027 let mut valid = true;
1029 if let Some('_') = self.ch {
1030 // disallow leading `_`
1031 self.err_span_(self.pos,
1033 "invalid start of unicode escape");
1037 let count = self.scan_digits(16, 16);
1040 self.err_span_(start_bpos,
1042 "overlong unicode escape (must have at most 6 hex digits)");
1049 if valid && count == 0 {
1050 self.err_span_(start_bpos,
1052 "empty unicode escape (must have at least 1 hex digit)");
1055 self.bump(); // past the ending `}`
1060 self.err_span_(self.pos,
1062 "unterminated unicode escape (needed a `}`)");
1066 self.err_span_char(start_bpos,
1068 "invalid character in unicode escape",
1074 self.fatal_span_(start_bpos,
1076 "unterminated unicode escape (found EOF)").raise();
1085 /// Scan over a float exponent.
1086 fn scan_float_exponent(&mut self) {
1087 if self.ch_is('e') || self.ch_is('E') {
1090 if self.ch_is('-') || self.ch_is('+') {
1094 if self.scan_digits(10, 10) == 0 {
1095 let mut err = self.struct_span_fatal(
1096 self.pos, self.next_pos,
1097 "expected at least one digit in exponent"
1099 if let Some(ch) = self.ch {
1100 // check for e.g. Unicode minus '−' (Issue #49746)
1101 if unicode_chars::check_for_substitution(self, ch, &mut err) {
1103 self.scan_digits(10, 10);
1111 /// Check that a base is valid for a floating literal, emitting a nice
1112 /// error if it isn't.
1113 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
1116 self.err_span_(start_bpos,
1118 "hexadecimal float literal is not supported")
1121 self.err_span_(start_bpos,
1123 "octal float literal is not supported")
1126 self.err_span_(start_bpos,
1128 "binary float literal is not supported")
1134 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
1136 if self.ch_is('=') {
1144 /// Return the next token from the string, advances the input past that
1145 /// token, and updates the interner
1146 fn next_token_inner(&mut self) -> Result<token::Token, ()> {
1150 let (is_ident_start, is_raw_ident) =
1151 match (c.unwrap(), self.nextch(), self.nextnextch()) {
1152 // r# followed by an identifier starter is a raw identifier.
1153 // This is an exception to the r# case below.
1154 ('r', Some('#'), x) if ident_start(x) => (true, true),
1155 // r as in r" or r#" is part of a raw string literal.
1156 // b as in b' is part of a byte literal.
1157 // They are not identifiers, and are handled further down.
1158 ('r', Some('"'), _) |
1159 ('r', Some('#'), _) |
1160 ('b', Some('"'), _) |
1161 ('b', Some('\''), _) |
1162 ('b', Some('r'), Some('"')) |
1163 ('b', Some('r'), Some('#')) => (false, false),
1168 let raw_start = self.pos;
1170 // Consume the 'r#' characters.
1175 let start = self.pos;
1178 while ident_continue(self.ch) {
1182 return Ok(self.with_str_from(start, |string| {
1183 // FIXME: perform NFKC normalization here. (Issue #2253)
1184 let ident = self.mk_ident(string);
1186 if is_raw_ident && (ident.is_path_segment_keyword() ||
1187 ident.name == keywords::Underscore.name()) {
1188 self.fatal_span_(raw_start, self.pos,
1189 &format!("`r#{}` is not currently supported.", ident.name)
1194 let span = self.mk_sp(raw_start, self.pos);
1195 self.sess.raw_identifier_spans.borrow_mut().push(span);
1198 token::Ident(ident, is_raw_ident)
1203 if is_dec_digit(c) {
1204 let num = self.scan_number(c.unwrap());
1205 let suffix = self.scan_optional_raw_name();
1206 debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
1207 return Ok(token::Literal(num, suffix));
1210 match c.expect("next_token_inner called at EOF") {
1222 if self.ch_is('.') {
1224 if self.ch_is('.') {
1226 Ok(token::DotDotDot)
1227 } else if self.ch_is('=') {
1239 Ok(token::OpenDelim(token::Paren))
1243 Ok(token::CloseDelim(token::Paren))
1247 Ok(token::OpenDelim(token::Brace))
1251 Ok(token::CloseDelim(token::Brace))
1255 Ok(token::OpenDelim(token::Bracket))
1259 Ok(token::CloseDelim(token::Bracket))
1279 if self.ch_is(':') {
1292 // Multi-byte tokens.
1295 if self.ch_is('=') {
1298 } else if self.ch_is('>') {
1307 if self.ch_is('=') {
1316 match self.ch.unwrap_or('\x00') {
1322 Ok(self.binop(token::Shl))
1335 match self.ch.unwrap_or('\x00') {
1341 Ok(self.binop(token::Shr))
1349 // Either a character constant 'a' OR a lifetime name 'abc
1350 let start_with_quote = self.pos;
1352 let start = self.pos;
1354 // the eof will be picked up by the final `'` check below
1355 let c2 = self.ch.unwrap_or('\x00');
1358 // If the character is an ident start not followed by another single
1359 // quote, then this is a lifetime name:
1360 if ident_start(Some(c2)) && !self.ch_is('\'') {
1361 while ident_continue(self.ch) {
1364 // lifetimes shouldn't end with a single quote
1365 // if we find one, then this is an invalid character literal
1366 if self.ch_is('\'') {
1367 self.fatal_span_verbose(start_with_quote, self.next_pos,
1368 String::from("character literal may only contain one codepoint"))
1373 // Include the leading `'` in the real identifier, for macro
1374 // expansion purposes. See #12512 for the gory details of why
1375 // this is necessary.
1376 let ident = self.with_str_from(start, |lifetime_name| {
1377 self.mk_ident(&format!("'{}", lifetime_name))
1380 return Ok(token::Lifetime(ident));
1383 let valid = self.scan_char_or_byte(start, c2, /* ascii_only */ false, '\'');
1385 if !self.ch_is('\'') {
1390 if self.ch_is('\'') {
1391 let start = self.src_index(start);
1392 let end = self.src_index(self.pos);
1394 let span = self.mk_sp(start_with_quote, self.pos);
1395 self.sess.span_diagnostic
1396 .struct_span_err(span,
1397 "character literal may only contain one codepoint")
1398 .span_suggestion_with_applicability(
1400 "if you meant to write a `str` literal, use double quotes",
1401 format!("\"{}\"", &self.src[start..end]),
1402 Applicability::MachineApplicable
1404 return Ok(token::Literal(token::Str_(Symbol::intern("??")), None))
1406 if self.ch_is('\n') || self.is_eof() || self.ch_is('/') {
1407 // Only attempt to infer single line string literals. If we encounter
1408 // a slash, bail out in order to avoid nonsensical suggestion when
1409 // involving comments.
1414 self.fatal_span_verbose(start_with_quote, pos,
1415 String::from("character literal may only contain one codepoint")).raise();
1419 self.name_from(start)
1424 self.bump(); // advance ch past token
1425 let suffix = self.scan_optional_raw_name();
1427 Ok(token::Literal(token::Char(id), suffix))
1431 let lit = match self.ch {
1432 Some('\'') => self.scan_byte(),
1433 Some('"') => self.scan_byte_string(),
1434 Some('r') => self.scan_raw_byte_string(),
1435 _ => unreachable!(), // Should have been a token::Ident above.
1437 let suffix = self.scan_optional_raw_name();
1439 Ok(token::Literal(lit, suffix))
1442 let start_bpos = self.pos;
1443 let mut valid = true;
1446 while !self.ch_is('"') {
1448 let last_bpos = self.pos;
1449 self.fatal_span_(start_bpos,
1451 "unterminated double quote string").raise();
1454 let ch_start = self.pos;
1455 let ch = self.ch.unwrap();
1457 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only */ false, '"');
1459 // adjust for the ASCII " at the start of the literal
1461 self.name_from(start_bpos + BytePos(1))
1463 Symbol::intern("??")
1466 let suffix = self.scan_optional_raw_name();
1468 Ok(token::Literal(token::Str_(id), suffix))
1471 let start_bpos = self.pos;
1473 let mut hash_count: u16 = 0;
1474 while self.ch_is('#') {
1475 if hash_count == 65535 {
1476 let bpos = self.next_pos;
1477 self.fatal_span_(start_bpos,
1479 "too many `#` symbols: raw strings may be \
1480 delimited by up to 65535 `#` symbols").raise();
1487 self.fail_unterminated_raw_string(start_bpos, hash_count);
1488 } else if !self.ch_is('"') {
1489 let last_bpos = self.pos;
1490 let curr_char = self.ch.unwrap();
1491 self.fatal_span_char(start_bpos,
1493 "found invalid character; only `#` is allowed \
1494 in raw string delimitation",
1498 let content_start_bpos = self.pos;
1499 let mut content_end_bpos;
1500 let mut valid = true;
1503 self.fail_unterminated_raw_string(start_bpos, hash_count);
1505 // if self.ch_is('"') {
1506 // content_end_bpos = self.pos;
1507 // for _ in 0..hash_count {
1509 // if !self.ch_is('#') {
1511 let c = self.ch.unwrap();
1514 content_end_bpos = self.pos;
1515 for _ in 0..hash_count {
1517 if !self.ch_is('#') {
1524 if !self.nextch_is('\n') {
1525 let last_bpos = self.pos;
1526 self.err_span_(start_bpos,
1528 "bare CR not allowed in raw string, use \\r \
1540 self.name_from_to(content_start_bpos, content_end_bpos)
1542 Symbol::intern("??")
1544 let suffix = self.scan_optional_raw_name();
1546 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1549 if self.nextch_is('>') {
1554 Ok(self.binop(token::Minus))
1558 if self.nextch_is('&') {
1563 Ok(self.binop(token::And))
1567 match self.nextch() {
1574 Ok(self.binop(token::Or))
1579 Ok(self.binop(token::Plus))
1582 Ok(self.binop(token::Star))
1585 Ok(self.binop(token::Slash))
1588 Ok(self.binop(token::Caret))
1591 Ok(self.binop(token::Percent))
1594 let last_bpos = self.pos;
1595 let bpos = self.next_pos;
1596 let mut err = self.struct_fatal_span_char(last_bpos,
1598 "unknown start of token",
1600 unicode_chars::check_for_substitution(self, c, &mut err);
1601 self.fatal_errs.push(err);
1608 fn consume_whitespace(&mut self) {
1609 while is_pattern_whitespace(self.ch) && !self.is_eof() {
1614 fn read_to_eol(&mut self) -> String {
1615 let mut val = String::new();
1616 while !self.ch_is('\n') && !self.is_eof() {
1617 val.push(self.ch.unwrap());
1621 if self.ch_is('\n') {
1628 fn read_one_line_comment(&mut self) -> String {
1629 let val = self.read_to_eol();
1630 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1631 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1635 fn consume_non_eol_whitespace(&mut self) {
1636 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1641 fn peeking_at_comment(&self) -> bool {
1642 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1643 // consider shebangs comments, but not inner attributes
1644 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1647 fn scan_byte(&mut self) -> token::Lit {
1649 let start = self.pos;
1651 // the eof will be picked up by the final `'` check below
1652 let c2 = self.ch.unwrap_or('\x00');
1655 let valid = self.scan_char_or_byte(start,
1660 if !self.ch_is('\'') {
1661 // Byte offsetting here is okay because the
1662 // character before position `start` are an
1663 // ascii single quote and ascii 'b'.
1665 self.fatal_span_verbose(start - BytePos(2),
1667 "unterminated byte constant".to_string()).raise();
1671 self.name_from(start)
1675 self.bump(); // advance ch past token
1681 fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1682 self.scan_hex_digits(2, delim, below_0x7f_only)
1685 fn scan_byte_string(&mut self) -> token::Lit {
1687 let start = self.pos;
1688 let mut valid = true;
1690 while !self.ch_is('"') {
1693 self.fatal_span_(start, pos, "unterminated double quote byte string").raise();
1696 let ch_start = self.pos;
1697 let ch = self.ch.unwrap();
1699 valid &= self.scan_char_or_byte(ch_start,
1707 self.name_from(start)
1709 Symbol::intern("??")
1716 fn scan_raw_byte_string(&mut self) -> token::Lit {
1717 let start_bpos = self.pos;
1719 let mut hash_count = 0;
1720 while self.ch_is('#') {
1721 if hash_count == 65535 {
1722 let bpos = self.next_pos;
1723 self.fatal_span_(start_bpos,
1725 "too many `#` symbols: raw byte strings may be \
1726 delimited by up to 65535 `#` symbols").raise();
1733 self.fail_unterminated_raw_string(start_bpos, hash_count);
1734 } else if !self.ch_is('"') {
1736 let ch = self.ch.unwrap();
1737 self.fatal_span_char(start_bpos,
1739 "found invalid character; only `#` is allowed in raw \
1740 string delimitation",
1744 let content_start_bpos = self.pos;
1745 let mut content_end_bpos;
1749 self.fail_unterminated_raw_string(start_bpos, hash_count);
1752 content_end_bpos = self.pos;
1753 for _ in 0..hash_count {
1755 if !self.ch_is('#') {
1764 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1773 token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), hash_count)
1777 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1778 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1780 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1781 c.map_or(false, Pattern_White_Space)
1785 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1786 c.map_or(false, |c| lo <= c && c <= hi)
1790 fn is_dec_digit(c: Option<char>) -> bool {
1791 in_range(c, '0', '9')
1794 fn is_doc_comment(s: &str) -> bool {
1795 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1796 s.starts_with("//!");
1797 debug!("is {:?} a doc comment? {}", s, res);
1801 fn is_block_doc_comment(s: &str) -> bool {
1802 // Prevent `/**/` from being parsed as a doc comment
1803 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1804 s.starts_with("/*!")) && s.len() >= 5;
1805 debug!("is {:?} a doc comment? {}", s, res);
1809 fn ident_start(c: Option<char>) -> bool {
1812 None => return false,
1815 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1818 fn ident_continue(c: Option<char>) -> bool {
1821 None => return false,
1824 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1825 (c > '\x7f' && c.is_xid_continue())
1832 use ast::{Ident, CrateConfig};
1834 use syntax_pos::{BytePos, Span, NO_EXPANSION};
1835 use source_map::SourceMap;
1837 use feature_gate::UnstableFeatures;
1840 use std::path::PathBuf;
1841 use diagnostics::plugin::ErrorMap;
1842 use rustc_data_structures::fx::FxHashSet;
1843 use rustc_data_structures::sync::Lock;
1845 fn mk_sess(cm: Lrc<SourceMap>) -> ParseSess {
1846 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1851 span_diagnostic: errors::Handler::with_emitter(true, false, Box::new(emitter)),
1852 unstable_features: UnstableFeatures::from_environment(),
1853 config: CrateConfig::default(),
1854 included_mod_stack: Lock::new(Vec::new()),
1856 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1857 raw_identifier_spans: Lock::new(Vec::new()),
1858 registered_diagnostics: Lock::new(ErrorMap::new()),
1859 non_modrs_mods: Lock::new(vec![]),
1860 buffered_lints: Lock::new(vec![]),
1864 // open a string reader for the given string
1865 fn setup<'a>(cm: &SourceMap,
1866 sess: &'a ParseSess,
1868 -> StringReader<'a> {
1869 let fm = cm.new_source_file(PathBuf::from("zebra.rs").into(), teststr);
1870 StringReader::new(sess, fm, None)
1876 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1877 let sh = mk_sess(cm.clone());
1878 let mut string_reader = setup(&cm,
1880 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1882 let id = Ident::from_str("fn");
1883 assert_eq!(string_reader.next_token().tok, token::Comment);
1884 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1885 let tok1 = string_reader.next_token();
1886 let tok2 = TokenAndSpan {
1887 tok: token::Ident(id, false),
1888 sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1890 assert_eq!(tok1.tok, tok2.tok);
1891 assert_eq!(tok1.sp, tok2.sp);
1892 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1893 // the 'main' id is already read:
1894 assert_eq!(string_reader.pos.clone(), BytePos(28));
1895 // read another token:
1896 let tok3 = string_reader.next_token();
1897 let tok4 = TokenAndSpan {
1898 tok: mk_ident("main"),
1899 sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1901 assert_eq!(tok3.tok, tok4.tok);
1902 assert_eq!(tok3.sp, tok4.sp);
1903 // the lparen is already read:
1904 assert_eq!(string_reader.pos.clone(), BytePos(29))
1908 // check that the given reader produces the desired stream
1909 // of tokens (stop checking after exhausting the expected vec)
1910 fn check_tokenization(mut string_reader: StringReader, expected: Vec<token::Token>) {
1911 for expected_tok in &expected {
1912 assert_eq!(&string_reader.next_token().tok, expected_tok);
1916 // make the identifier by looking up the string in the interner
1917 fn mk_ident(id: &str) -> token::Token {
1918 token::Token::from_ast_ident(Ident::from_str(id))
1922 fn doublecolonparsing() {
1924 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1925 let sh = mk_sess(cm.clone());
1926 check_tokenization(setup(&cm, &sh, "a b".to_string()),
1927 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1934 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1935 let sh = mk_sess(cm.clone());
1936 check_tokenization(setup(&cm, &sh, "a::b".to_string()),
1937 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1944 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1945 let sh = mk_sess(cm.clone());
1946 check_tokenization(setup(&cm, &sh, "a ::b".to_string()),
1947 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
1954 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1955 let sh = mk_sess(cm.clone());
1956 check_tokenization(setup(&cm, &sh, "a:: b".to_string()),
1957 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
1964 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1965 let sh = mk_sess(cm.clone());
1966 assert_eq!(setup(&cm, &sh, "'a'".to_string()).next_token().tok,
1967 token::Literal(token::Char(Symbol::intern("a")), None));
1972 fn character_space() {
1974 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1975 let sh = mk_sess(cm.clone());
1976 assert_eq!(setup(&cm, &sh, "' '".to_string()).next_token().tok,
1977 token::Literal(token::Char(Symbol::intern(" ")), None));
1982 fn character_escaped() {
1984 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1985 let sh = mk_sess(cm.clone());
1986 assert_eq!(setup(&cm, &sh, "'\\n'".to_string()).next_token().tok,
1987 token::Literal(token::Char(Symbol::intern("\\n")), None));
1992 fn lifetime_name() {
1994 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1995 let sh = mk_sess(cm.clone());
1996 assert_eq!(setup(&cm, &sh, "'abc".to_string()).next_token().tok,
1997 token::Lifetime(Ident::from_str("'abc")));
2004 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2005 let sh = mk_sess(cm.clone());
2006 assert_eq!(setup(&cm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
2009 token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
2014 fn literal_suffixes() {
2016 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2017 let sh = mk_sess(cm.clone());
2019 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
2020 assert_eq!(setup(&cm, &sh, format!("{}suffix", $input)).next_token().tok,
2021 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2022 Some(Symbol::intern("suffix"))));
2023 // with a whitespace separator:
2024 assert_eq!(setup(&cm, &sh, format!("{} suffix", $input)).next_token().tok,
2025 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2030 test!("'a'", Char, "a");
2031 test!("b'a'", Byte, "a");
2032 test!("\"a\"", Str_, "a");
2033 test!("b\"a\"", ByteStr, "a");
2034 test!("1234", Integer, "1234");
2035 test!("0b101", Integer, "0b101");
2036 test!("0xABC", Integer, "0xABC");
2037 test!("1.0", Float, "1.0");
2038 test!("1.0e10", Float, "1.0e10");
2040 assert_eq!(setup(&cm, &sh, "2us".to_string()).next_token().tok,
2041 token::Literal(token::Integer(Symbol::intern("2")),
2042 Some(Symbol::intern("us"))));
2043 assert_eq!(setup(&cm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
2044 token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
2045 Some(Symbol::intern("suffix"))));
2046 assert_eq!(setup(&cm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
2047 token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
2048 Some(Symbol::intern("suffix"))));
2053 fn line_doc_comments() {
2054 assert!(is_doc_comment("///"));
2055 assert!(is_doc_comment("/// blah"));
2056 assert!(!is_doc_comment("////"));
2060 fn nested_block_comments() {
2062 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2063 let sh = mk_sess(cm.clone());
2064 let mut lexer = setup(&cm, &sh, "/* /* */ */'a'".to_string());
2065 match lexer.next_token().tok {
2066 token::Comment => {}
2067 _ => panic!("expected a comment!"),
2069 assert_eq!(lexer.next_token().tok,
2070 token::Literal(token::Char(Symbol::intern("a")), None));
2075 fn crlf_comments() {
2077 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2078 let sh = mk_sess(cm.clone());
2079 let mut lexer = setup(&cm, &sh, "// test\r\n/// test\r\n".to_string());
2080 let comment = lexer.next_token();
2081 assert_eq!(comment.tok, token::Comment);
2082 assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
2083 assert_eq!(lexer.next_token().tok, token::Whitespace);
2084 assert_eq!(lexer.next_token().tok,
2085 token::DocComment(Symbol::intern("/// test")));