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, Diagnostic, 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.
65 /// The raw source span which *does not* take `override_span` into account
67 /// Stack of open delimiters and their spans. Used for error message.
68 open_braces: Vec<(token::DelimToken, Span)>,
69 /// 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 buffer_fatal_errors(&mut self) -> Vec<Diagnostic> {
179 let mut buffer = Vec::new();
181 for err in self.fatal_errs.drain(..) {
182 err.buffer(&mut buffer);
188 pub fn peek(&self) -> TokenAndSpan {
189 // FIXME(pcwalton): Bad copy!
191 tok: self.peek_tok.clone(),
196 /// For comments.rs, which hackily pokes into next_pos and ch
197 fn new_raw(sess: &'a ParseSess,
198 source_file: Lrc<syntax_pos::SourceFile>,
199 override_span: Option<Span>) -> Self {
200 let mut sr = StringReader::new_raw_internal(sess, source_file, override_span);
206 fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc<syntax_pos::SourceFile>,
207 override_span: Option<Span>) -> Self
209 if source_file.src.is_none() {
210 sess.span_diagnostic.bug(&format!("Cannot lex source_file without source: {}",
214 let src = (*source_file.src.as_ref().unwrap()).clone();
218 next_pos: source_file.start_pos,
219 pos: source_file.start_pos,
222 end_src_index: src.len(),
223 // dummy values; not read
224 peek_tok: token::Eof,
225 peek_span: syntax_pos::DUMMY_SP,
226 peek_span_src_raw: syntax_pos::DUMMY_SP,
228 fatal_errs: Vec::new(),
230 span: syntax_pos::DUMMY_SP,
231 span_src_raw: syntax_pos::DUMMY_SP,
232 open_braces: Vec::new(),
233 matching_delim_spans: Vec::new(),
235 last_unclosed_found_span: None,
239 pub fn new(sess: &'a ParseSess,
240 source_file: Lrc<syntax_pos::SourceFile>,
241 override_span: Option<Span>) -> Self {
242 let mut sr = StringReader::new_raw(sess, source_file, override_span);
243 if sr.advance_token().is_err() {
244 sr.emit_fatal_errors();
251 pub fn new_without_err(sess: &'a ParseSess,
252 source_file: Lrc<syntax_pos::SourceFile>,
253 override_span: Option<Span>,
254 prepend_error_text: &str) -> Result<Self, ()> {
255 let mut sr = StringReader::new_raw(sess, source_file, override_span);
256 if sr.advance_token().is_err() {
257 eprintln!("{}", prepend_error_text);
258 sr.emit_fatal_errors();
264 pub fn new_or_buffered_errs(sess: &'a ParseSess,
265 source_file: Lrc<syntax_pos::SourceFile>,
266 override_span: Option<Span>) -> Result<Self, Vec<Diagnostic>> {
267 let mut sr = StringReader::new_raw(sess, source_file, override_span);
268 if sr.advance_token().is_err() {
269 Err(sr.buffer_fatal_errors())
275 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
276 let begin = sess.source_map().lookup_byte_offset(span.lo());
277 let end = sess.source_map().lookup_byte_offset(span.hi());
279 // Make the range zero-length if the span is invalid.
280 if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
281 span = span.shrink_to_lo();
284 let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
286 // Seek the lexer to the right byte range.
287 sr.next_pos = span.lo();
288 sr.end_src_index = sr.src_index(span.hi());
292 if sr.advance_token().is_err() {
293 sr.emit_fatal_errors();
301 fn ch_is(&self, c: char) -> bool {
305 /// Report a fatal lexical error with a given span.
306 fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
307 self.sess.span_diagnostic.span_fatal(sp, m)
310 /// Report a lexical error with a given span.
311 fn err_span(&self, sp: Span, m: &str) {
312 self.sess.span_diagnostic.span_err(sp, m)
316 /// Report a fatal error spanning [`from_pos`, `to_pos`).
317 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
318 self.fatal_span(self.mk_sp(from_pos, to_pos), m)
321 /// Report a lexical error spanning [`from_pos`, `to_pos`).
322 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
323 self.err_span(self.mk_sp(from_pos, to_pos), m)
326 /// Pushes a character to a message string for error reporting
327 fn push_escaped_char_for_msg(m: &mut String, c: char) {
329 '\u{20}'..='\u{7e}' => {
330 // Don't escape \, ' or " for user-facing messages
334 m.extend(c.escape_default());
339 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
340 /// escaped character to the error message
341 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
342 let mut m = m.to_string();
344 Self::push_escaped_char_for_msg(&mut m, c);
346 self.fatal_span_(from_pos, to_pos, &m[..])
349 fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str)
350 -> DiagnosticBuilder<'a>
352 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m)
355 fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
356 -> DiagnosticBuilder<'a>
358 let mut m = m.to_string();
360 Self::push_escaped_char_for_msg(&mut m, c);
362 self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
365 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
366 /// escaped character to the error message
367 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
368 let mut m = m.to_string();
370 Self::push_escaped_char_for_msg(&mut m, c);
371 self.err_span_(from_pos, to_pos, &m[..]);
374 fn struct_err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char)
375 -> DiagnosticBuilder<'a>
377 let mut m = m.to_string();
379 Self::push_escaped_char_for_msg(&mut m, c);
381 self.sess.span_diagnostic.struct_span_err(self.mk_sp(from_pos, to_pos), &m[..])
384 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
385 /// offending string to the error message
386 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> FatalError {
388 m.push_str(&self.src[self.src_index(from_pos)..self.src_index(to_pos)]);
390 self.fatal_span_(from_pos, to_pos, &m[..])
393 /// Advance peek_tok and peek_span to refer to the next token, and
394 /// possibly update the interner.
395 fn advance_token(&mut self) -> Result<(), ()> {
396 match self.scan_whitespace_or_comment() {
398 self.peek_span_src_raw = comment.sp;
399 self.peek_span = comment.sp;
400 self.peek_tok = comment.tok;
404 self.peek_tok = token::Eof;
405 let (real, raw) = self.mk_sp_and_raw(
406 self.source_file.end_pos,
407 self.source_file.end_pos,
409 self.peek_span = real;
410 self.peek_span_src_raw = raw;
412 let start_bytepos = self.pos;
413 self.peek_tok = self.next_token_inner()?;
414 let (real, raw) = self.mk_sp_and_raw(start_bytepos, self.pos);
415 self.peek_span = real;
416 self.peek_span_src_raw = raw;
425 fn src_index(&self, pos: BytePos) -> usize {
426 (pos - self.source_file.start_pos).to_usize()
429 /// Calls `f` with a string slice of the source text spanning from `start`
430 /// up to but excluding `self.pos`, meaning the slice does not include
431 /// the character `self.ch`.
432 fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
433 where F: FnOnce(&str) -> T
435 self.with_str_from_to(start, self.pos, f)
438 /// Create a Name from a given offset to the current offset, each
439 /// adjusted 1 towards each other (assumes that on either side there is a
440 /// single-byte delimiter).
441 fn name_from(&self, start: BytePos) -> ast::Name {
442 debug!("taking an ident from {:?} to {:?}", start, self.pos);
443 self.with_str_from(start, Symbol::intern)
446 /// As name_from, with an explicit endpoint.
447 fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
448 debug!("taking an ident from {:?} to {:?}", start, end);
449 self.with_str_from_to(start, end, Symbol::intern)
452 /// Calls `f` with a string slice of the source text spanning from `start`
453 /// up to but excluding `end`.
454 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
455 where F: FnOnce(&str) -> T
457 f(&self.src[self.src_index(start)..self.src_index(end)])
460 /// Converts CRLF to LF in the given string, raising an error on bare CR.
461 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
464 let ch = char_at(s, i);
465 let next = i + ch.len_utf8();
467 if next < s.len() && char_at(s, next) == '\n' {
468 return translate_crlf_(self, start, s, errmsg, i).into();
470 let pos = start + BytePos(i as u32);
471 let end_pos = start + BytePos(next as u32);
472 self.err_span_(pos, end_pos, errmsg);
478 fn translate_crlf_(rdr: &StringReader,
484 let mut buf = String::with_capacity(s.len());
487 let ch = char_at(s, i);
488 let next = i + ch.len_utf8();
491 buf.push_str(&s[j..i]);
494 if next >= s.len() || char_at(s, next) != '\n' {
495 let pos = start + BytePos(i as u32);
496 let end_pos = start + BytePos(next as u32);
497 rdr.err_span_(pos, end_pos, errmsg);
503 buf.push_str(&s[j..]);
509 /// Advance the StringReader by one character.
510 crate fn bump(&mut self) {
511 let next_src_index = self.src_index(self.next_pos);
512 if next_src_index < self.end_src_index {
513 let next_ch = char_at(&self.src, next_src_index);
514 let next_ch_len = next_ch.len_utf8();
516 self.ch = Some(next_ch);
517 self.pos = self.next_pos;
518 self.next_pos = self.next_pos + Pos::from_usize(next_ch_len);
521 self.pos = self.next_pos;
525 fn nextch(&self) -> Option<char> {
526 let next_src_index = self.src_index(self.next_pos);
527 if next_src_index < self.end_src_index {
528 Some(char_at(&self.src, next_src_index))
535 fn nextch_is(&self, c: char) -> bool {
536 self.nextch() == Some(c)
539 fn nextnextch(&self) -> Option<char> {
540 let next_src_index = self.src_index(self.next_pos);
541 if next_src_index < self.end_src_index {
542 let next_next_src_index =
543 next_src_index + char_at(&self.src, next_src_index).len_utf8();
544 if next_next_src_index < self.end_src_index {
545 return Some(char_at(&self.src, next_next_src_index));
552 fn nextnextch_is(&self, c: char) -> bool {
553 self.nextnextch() == Some(c)
556 /// Eats <XID_start><XID_continue>*, if possible.
557 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
558 if !ident_start(self.ch) {
562 let start = self.pos;
565 while ident_continue(self.ch) {
569 self.with_str_from(start, |string| {
571 self.sess.span_diagnostic
572 .struct_span_warn(self.mk_sp(start, self.pos),
573 "underscore literal suffix is not allowed")
574 .warn("this was previously accepted by the compiler but is \
575 being phased out; it will become a hard error in \
577 .note("for more information, see issue #42326 \
578 <https://github.com/rust-lang/rust/issues/42326>")
582 Some(Symbol::intern(string))
587 /// PRECONDITION: self.ch is not whitespace
588 /// Eats any kind of comment.
589 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
590 if let Some(c) = self.ch {
591 if c.is_whitespace() {
592 let msg = "called consume_any_line_comment, but there was whitespace";
593 self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg);
598 match self.nextch() {
603 // line comments starting with "///" or "//!" are doc-comments
604 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
605 let start_bpos = self.pos - BytePos(2);
607 while !self.is_eof() {
608 match self.ch.unwrap() {
611 if self.nextch_is('\n') {
614 } else if doc_comment {
615 self.err_span_(self.pos,
617 "bare CR not allowed in doc-comment");
626 self.with_str_from(start_bpos, |string| {
627 // comments with only more "/"s are not doc comments
628 let tok = if is_doc_comment(string) {
629 token::DocComment(Symbol::intern(string))
636 sp: self.mk_sp(start_bpos, self.pos),
642 sp: self.mk_sp(start_bpos, self.pos),
649 self.scan_block_comment()
653 } else if self.ch_is('#') {
654 if self.nextch_is('!') {
656 // Parse an inner attribute.
657 if self.nextnextch_is('[') {
661 // I guess this is the only way to figure out if
662 // we're at the beginning of the file...
663 let smap = SourceMap::new(FilePathMapping::empty());
664 smap.files.borrow_mut().source_files.push(self.source_file.clone());
665 let loc = smap.lookup_char_pos_adj(self.pos);
666 debug!("Skipping a shebang");
667 if loc.line == 1 && loc.col == CharPos(0) {
668 // FIXME: Add shebang "token", return it
669 let start = self.pos;
670 while !self.ch_is('\n') && !self.is_eof() {
673 return Some(TokenAndSpan {
674 tok: token::Shebang(self.name_from(start)),
675 sp: self.mk_sp(start, self.pos),
685 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
687 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
688 match self.ch.unwrap_or('\0') {
689 // # to handle shebang at start of file -- this is the entry point
690 // for skipping over all "junk"
692 let c = self.scan_comment();
693 debug!("scanning a comment {:?}", c);
696 c if is_pattern_whitespace(Some(c)) => {
697 let start_bpos = self.pos;
698 while is_pattern_whitespace(self.ch) {
701 let c = Some(TokenAndSpan {
702 tok: token::Whitespace,
703 sp: self.mk_sp(start_bpos, self.pos),
705 debug!("scanning whitespace: {:?}", c);
712 /// Might return a sugared-doc-attr
713 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
714 // block comments starting with "/**" or "/*!" are doc-comments
715 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
716 let start_bpos = self.pos - BytePos(2);
718 let mut level: isize = 1;
719 let mut has_cr = false;
722 let msg = if is_doc_comment {
723 "unterminated block doc-comment"
725 "unterminated block comment"
727 let last_bpos = self.pos;
728 self.fatal_span_(start_bpos, last_bpos, msg).raise();
730 let n = self.ch.unwrap();
732 '/' if self.nextch_is('*') => {
736 '*' if self.nextch_is('/') => {
748 self.with_str_from(start_bpos, |string| {
749 // but comments with only "*"s between two "/"s are not
750 let tok = if is_block_doc_comment(string) {
751 let string = if has_cr {
752 self.translate_crlf(start_bpos,
754 "bare CR not allowed in block doc-comment")
758 token::DocComment(Symbol::intern(&string[..]))
765 sp: self.mk_sp(start_bpos, self.pos),
770 /// Scan through any digits (base `scan_radix`) or underscores,
771 /// and return how many digits there were.
773 /// `real_radix` represents the true radix of the number we're
774 /// interested in, and errors will be emitted for any digits
775 /// between `real_radix` and `scan_radix`.
776 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
777 assert!(real_radix <= scan_radix);
783 debug!("skipping a _");
787 match c.and_then(|cc| cc.to_digit(scan_radix)) {
789 debug!("{:?} in scan_digits", c);
790 // check that the hypothetical digit is actually
791 // in range for the true radix
792 if c.unwrap().to_digit(real_radix).is_none() {
793 self.err_span_(self.pos,
795 &format!("invalid digit for a base {} literal", real_radix));
805 /// Lex a LIT_INTEGER or a LIT_FLOAT
806 fn scan_number(&mut self, c: char) -> token::Lit {
808 let start_bpos = self.pos;
811 let num_digits = if c == '0' {
812 match self.ch.unwrap_or('\0') {
816 self.scan_digits(2, 10)
821 self.scan_digits(8, 10)
826 self.scan_digits(16, 16)
828 '0'..='9' | '_' | '.' | 'e' | 'E' => {
829 self.scan_digits(10, 10) + 1
833 return token::Integer(self.name_from(start_bpos));
836 } else if c.is_digit(10) {
837 self.scan_digits(10, 10) + 1
843 self.err_span_(start_bpos, self.pos, "no valid digits found for number");
845 return token::Integer(Symbol::intern("0"));
848 // might be a float, but don't be greedy if this is actually an
849 // integer literal followed by field/method access or a range pattern
850 // (`0..2` and `12.foo()`)
851 if self.ch_is('.') && !self.nextch_is('.') &&
852 !ident_start(self.nextch()) {
853 // might have stuff after the ., and if it does, it needs to start
856 if self.ch.unwrap_or('\0').is_digit(10) {
857 self.scan_digits(10, 10);
858 self.scan_float_exponent();
861 self.check_float_base(start_bpos, pos, base);
863 token::Float(self.name_from(start_bpos))
865 // it might be a float if it has an exponent
866 if self.ch_is('e') || self.ch_is('E') {
867 self.scan_float_exponent();
869 self.check_float_base(start_bpos, pos, base);
870 return token::Float(self.name_from(start_bpos));
872 // but we certainly have an integer!
873 token::Integer(self.name_from(start_bpos))
877 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
878 /// error if too many or too few digits are encountered.
879 fn scan_hex_digits(&mut self, n_digits: usize, delim: char, below_0x7f_only: bool) -> bool {
880 debug!("scanning {} digits until {:?}", n_digits, delim);
881 let start_bpos = self.pos;
882 let mut accum_int = 0;
884 let mut valid = true;
885 for _ in 0..n_digits {
887 let last_bpos = self.pos;
888 self.fatal_span_(start_bpos,
890 "unterminated numeric character escape").raise();
892 if self.ch_is(delim) {
893 let last_bpos = self.pos;
894 self.err_span_(start_bpos,
896 "numeric character escape is too short");
900 let c = self.ch.unwrap_or('\x00');
902 accum_int += c.to_digit(16).unwrap_or_else(|| {
903 self.err_span_char(self.pos,
905 "invalid character in numeric character escape",
914 if below_0x7f_only && accum_int >= 0x80 {
915 self.err_span_(start_bpos,
917 "this form of character escape may only be used with characters in \
918 the range [\\x00-\\x7f]");
922 match char::from_u32(accum_int) {
925 let last_bpos = self.pos;
926 self.err_span_(start_bpos, last_bpos, "invalid numeric character escape");
932 /// Scan for a single (possibly escaped) byte or char
933 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
934 /// `start` is the position of `first_source_char`, which is already consumed.
936 /// Returns true if there was a valid char/byte, false otherwise.
937 fn scan_char_or_byte(&mut self,
939 first_source_char: char,
944 match first_source_char {
946 // '\X' for some X must be a character constant:
947 let escaped = self.ch;
948 let escaped_pos = self.pos;
951 None => {} // EOF here is an error that will be checked later.
954 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
955 'x' => self.scan_byte_escape(delim, !ascii_only),
957 let valid = if self.ch_is('{') {
958 self.scan_unicode_escape(delim) && !ascii_only
960 let span = self.mk_sp(start, self.pos);
961 self.sess.span_diagnostic
962 .struct_span_err(span, "incorrect unicode escape sequence")
964 "format of unicode escape sequences is \
970 self.err_span_(start,
972 "unicode escape sequences cannot be used as a \
973 byte or in a byte string");
978 '\n' if delim == '"' => {
979 self.consume_whitespace();
982 '\r' if delim == '"' && self.ch_is('\n') => {
983 self.consume_whitespace();
988 let mut err = self.struct_err_span_char(escaped_pos,
991 "unknown byte escape"
998 err.span_help(self.mk_sp(escaped_pos, pos),
999 "this is an isolated carriage return; consider \
1000 checking your editor and version control \
1003 if (e == '{' || e == '}') && !ascii_only {
1004 err.span_help(self.mk_sp(escaped_pos, pos),
1005 "if used in a formatting string, curly braces \
1006 are escaped with `{{` and `}}`");
1015 '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
1017 self.err_span_char(start,
1020 "byte constant must be escaped"
1022 "character constant must be escaped"
1028 if self.ch_is('\n') {
1032 self.err_span_(start,
1034 "bare CR not allowed in string, use \\r instead");
1039 if ascii_only && first_source_char > '\x7F' {
1041 self.err_span_(start,
1043 "byte constant must be ASCII. Use a \\xHH escape for a \
1052 /// Scan over a `\u{...}` escape
1054 /// At this point, we have already seen the `\` and the `u`, the `{` is the current character.
1055 /// We will read a hex number (with `_` separators), with 1 to 6 actual digits,
1056 /// and pass over the `}`.
1057 fn scan_unicode_escape(&mut self, delim: char) -> bool {
1058 self.bump(); // past the {
1059 let start_bpos = self.pos;
1060 let mut valid = true;
1062 if let Some('_') = self.ch {
1063 // disallow leading `_`
1064 self.err_span_(self.pos,
1066 "invalid start of unicode escape");
1070 let count = self.scan_digits(16, 16);
1073 self.err_span_(start_bpos,
1075 "overlong unicode escape (must have at most 6 hex digits)");
1082 if valid && count == 0 {
1083 self.err_span_(start_bpos,
1085 "empty unicode escape (must have at least 1 hex digit)");
1088 self.bump(); // past the ending `}`
1093 self.err_span_(self.pos,
1095 "unterminated unicode escape (needed a `}`)");
1099 self.err_span_char(start_bpos,
1101 "invalid character in unicode escape",
1107 self.fatal_span_(start_bpos,
1109 "unterminated unicode escape (found EOF)").raise();
1118 /// Scan over a float exponent.
1119 fn scan_float_exponent(&mut self) {
1120 if self.ch_is('e') || self.ch_is('E') {
1123 if self.ch_is('-') || self.ch_is('+') {
1127 if self.scan_digits(10, 10) == 0 {
1128 let mut err = self.struct_span_fatal(
1129 self.pos, self.next_pos,
1130 "expected at least one digit in exponent"
1132 if let Some(ch) = self.ch {
1133 // check for e.g. Unicode minus '−' (Issue #49746)
1134 if unicode_chars::check_for_substitution(self, ch, &mut err) {
1136 self.scan_digits(10, 10);
1144 /// Check that a base is valid for a floating literal, emitting a nice
1145 /// error if it isn't.
1146 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
1149 self.err_span_(start_bpos,
1151 "hexadecimal float literal is not supported")
1154 self.err_span_(start_bpos,
1156 "octal float literal is not supported")
1159 self.err_span_(start_bpos,
1161 "binary float literal is not supported")
1167 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
1169 if self.ch_is('=') {
1177 /// Return the next token from the string, advances the input past that
1178 /// token, and updates the interner
1179 fn next_token_inner(&mut self) -> Result<token::Token, ()> {
1183 let (is_ident_start, is_raw_ident) =
1184 match (c.unwrap(), self.nextch(), self.nextnextch()) {
1185 // r# followed by an identifier starter is a raw identifier.
1186 // This is an exception to the r# case below.
1187 ('r', Some('#'), x) if ident_start(x) => (true, true),
1188 // r as in r" or r#" is part of a raw string literal.
1189 // b as in b' is part of a byte literal.
1190 // They are not identifiers, and are handled further down.
1191 ('r', Some('"'), _) |
1192 ('r', Some('#'), _) |
1193 ('b', Some('"'), _) |
1194 ('b', Some('\''), _) |
1195 ('b', Some('r'), Some('"')) |
1196 ('b', Some('r'), Some('#')) => (false, false),
1201 let raw_start = self.pos;
1203 // Consume the 'r#' characters.
1208 let start = self.pos;
1211 while ident_continue(self.ch) {
1215 return Ok(self.with_str_from(start, |string| {
1216 // FIXME: perform NFKC normalization here. (Issue #2253)
1217 let ident = self.mk_ident(string);
1219 if is_raw_ident && (ident.is_path_segment_keyword() ||
1220 ident.name == keywords::Underscore.name()) {
1221 self.fatal_span_(raw_start, self.pos,
1222 &format!("`r#{}` is not currently supported.", ident.name)
1227 let span = self.mk_sp(raw_start, self.pos);
1228 self.sess.raw_identifier_spans.borrow_mut().push(span);
1231 token::Ident(ident, is_raw_ident)
1236 if is_dec_digit(c) {
1237 let num = self.scan_number(c.unwrap());
1238 let suffix = self.scan_optional_raw_name();
1239 debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
1240 return Ok(token::Literal(num, suffix));
1243 match c.expect("next_token_inner called at EOF") {
1255 if self.ch_is('.') {
1257 if self.ch_is('.') {
1259 Ok(token::DotDotDot)
1260 } else if self.ch_is('=') {
1272 Ok(token::OpenDelim(token::Paren))
1276 Ok(token::CloseDelim(token::Paren))
1280 Ok(token::OpenDelim(token::Brace))
1284 Ok(token::CloseDelim(token::Brace))
1288 Ok(token::OpenDelim(token::Bracket))
1292 Ok(token::CloseDelim(token::Bracket))
1312 if self.ch_is(':') {
1325 // Multi-byte tokens.
1328 if self.ch_is('=') {
1331 } else if self.ch_is('>') {
1340 if self.ch_is('=') {
1349 match self.ch.unwrap_or('\x00') {
1355 Ok(self.binop(token::Shl))
1368 match self.ch.unwrap_or('\x00') {
1374 Ok(self.binop(token::Shr))
1382 // Either a character constant 'a' OR a lifetime name 'abc
1383 let start_with_quote = self.pos;
1385 let start = self.pos;
1387 // the eof will be picked up by the final `'` check below
1388 let c2 = self.ch.unwrap_or('\x00');
1391 // If the character is an ident start not followed by another single
1392 // quote, then this is a lifetime name:
1393 if ident_start(Some(c2)) && !self.ch_is('\'') {
1394 while ident_continue(self.ch) {
1397 // lifetimes shouldn't end with a single quote
1398 // if we find one, then this is an invalid character literal
1399 if self.ch_is('\'') {
1400 self.fatal_span_verbose(start_with_quote, self.next_pos,
1401 String::from("character literal may only contain one codepoint"))
1406 // Include the leading `'` in the real identifier, for macro
1407 // expansion purposes. See #12512 for the gory details of why
1408 // this is necessary.
1409 let ident = self.with_str_from(start, |lifetime_name| {
1410 self.mk_ident(&format!("'{}", lifetime_name))
1413 return Ok(token::Lifetime(ident));
1416 let valid = self.scan_char_or_byte(start, c2, /* ascii_only */ false, '\'');
1418 if !self.ch_is('\'') {
1423 if self.ch_is('\'') {
1424 let start = self.src_index(start);
1425 let end = self.src_index(self.pos);
1427 let span = self.mk_sp(start_with_quote, self.pos);
1428 self.sess.span_diagnostic
1429 .struct_span_err(span,
1430 "character literal may only contain one codepoint")
1431 .span_suggestion_with_applicability(
1433 "if you meant to write a `str` literal, use double quotes",
1434 format!("\"{}\"", &self.src[start..end]),
1435 Applicability::MachineApplicable
1437 return Ok(token::Literal(token::Str_(Symbol::intern("??")), None))
1439 if self.ch_is('\n') || self.is_eof() || self.ch_is('/') {
1440 // Only attempt to infer single line string literals. If we encounter
1441 // a slash, bail out in order to avoid nonsensical suggestion when
1442 // involving comments.
1447 self.fatal_span_verbose(start_with_quote, pos,
1448 String::from("character literal may only contain one codepoint")).raise();
1452 self.name_from(start)
1457 self.bump(); // advance ch past token
1458 let suffix = self.scan_optional_raw_name();
1460 Ok(token::Literal(token::Char(id), suffix))
1464 let lit = match self.ch {
1465 Some('\'') => self.scan_byte(),
1466 Some('"') => self.scan_byte_string(),
1467 Some('r') => self.scan_raw_byte_string(),
1468 _ => unreachable!(), // Should have been a token::Ident above.
1470 let suffix = self.scan_optional_raw_name();
1472 Ok(token::Literal(lit, suffix))
1475 let start_bpos = self.pos;
1476 let mut valid = true;
1479 while !self.ch_is('"') {
1481 let last_bpos = self.pos;
1482 self.fatal_span_(start_bpos,
1484 "unterminated double quote string").raise();
1487 let ch_start = self.pos;
1488 let ch = self.ch.unwrap();
1490 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only */ false, '"');
1492 // adjust for the ASCII " at the start of the literal
1494 self.name_from(start_bpos + BytePos(1))
1496 Symbol::intern("??")
1499 let suffix = self.scan_optional_raw_name();
1501 Ok(token::Literal(token::Str_(id), suffix))
1504 let start_bpos = self.pos;
1506 let mut hash_count: u16 = 0;
1507 while self.ch_is('#') {
1508 if hash_count == 65535 {
1509 let bpos = self.next_pos;
1510 self.fatal_span_(start_bpos,
1512 "too many `#` symbols: raw strings may be \
1513 delimited by up to 65535 `#` symbols").raise();
1520 self.fail_unterminated_raw_string(start_bpos, hash_count);
1521 } else if !self.ch_is('"') {
1522 let last_bpos = self.pos;
1523 let curr_char = self.ch.unwrap();
1524 self.fatal_span_char(start_bpos,
1526 "found invalid character; only `#` is allowed \
1527 in raw string delimitation",
1531 let content_start_bpos = self.pos;
1532 let mut content_end_bpos;
1533 let mut valid = true;
1536 self.fail_unterminated_raw_string(start_bpos, hash_count);
1538 // if self.ch_is('"') {
1539 // content_end_bpos = self.pos;
1540 // for _ in 0..hash_count {
1542 // if !self.ch_is('#') {
1544 let c = self.ch.unwrap();
1547 content_end_bpos = self.pos;
1548 for _ in 0..hash_count {
1550 if !self.ch_is('#') {
1557 if !self.nextch_is('\n') {
1558 let last_bpos = self.pos;
1559 self.err_span_(start_bpos,
1561 "bare CR not allowed in raw string, use \\r \
1573 self.name_from_to(content_start_bpos, content_end_bpos)
1575 Symbol::intern("??")
1577 let suffix = self.scan_optional_raw_name();
1579 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1582 if self.nextch_is('>') {
1587 Ok(self.binop(token::Minus))
1591 if self.nextch_is('&') {
1596 Ok(self.binop(token::And))
1600 match self.nextch() {
1607 Ok(self.binop(token::Or))
1612 Ok(self.binop(token::Plus))
1615 Ok(self.binop(token::Star))
1618 Ok(self.binop(token::Slash))
1621 Ok(self.binop(token::Caret))
1624 Ok(self.binop(token::Percent))
1627 let last_bpos = self.pos;
1628 let bpos = self.next_pos;
1629 let mut err = self.struct_fatal_span_char(last_bpos,
1631 "unknown start of token",
1633 unicode_chars::check_for_substitution(self, c, &mut err);
1634 self.fatal_errs.push(err);
1641 fn consume_whitespace(&mut self) {
1642 while is_pattern_whitespace(self.ch) && !self.is_eof() {
1647 fn read_to_eol(&mut self) -> String {
1648 let mut val = String::new();
1649 while !self.ch_is('\n') && !self.is_eof() {
1650 val.push(self.ch.unwrap());
1654 if self.ch_is('\n') {
1661 fn read_one_line_comment(&mut self) -> String {
1662 let val = self.read_to_eol();
1663 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1664 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1668 fn consume_non_eol_whitespace(&mut self) {
1669 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1674 fn peeking_at_comment(&self) -> bool {
1675 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1676 // consider shebangs comments, but not inner attributes
1677 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1680 fn scan_byte(&mut self) -> token::Lit {
1682 let start = self.pos;
1684 // the eof will be picked up by the final `'` check below
1685 let c2 = self.ch.unwrap_or('\x00');
1688 let valid = self.scan_char_or_byte(start,
1693 if !self.ch_is('\'') {
1694 // Byte offsetting here is okay because the
1695 // character before position `start` are an
1696 // ascii single quote and ascii 'b'.
1698 self.fatal_span_verbose(start - BytePos(2),
1700 "unterminated byte constant".to_string()).raise();
1704 self.name_from(start)
1708 self.bump(); // advance ch past token
1714 fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1715 self.scan_hex_digits(2, delim, below_0x7f_only)
1718 fn scan_byte_string(&mut self) -> token::Lit {
1720 let start = self.pos;
1721 let mut valid = true;
1723 while !self.ch_is('"') {
1726 self.fatal_span_(start, pos, "unterminated double quote byte string").raise();
1729 let ch_start = self.pos;
1730 let ch = self.ch.unwrap();
1732 valid &= self.scan_char_or_byte(ch_start,
1740 self.name_from(start)
1742 Symbol::intern("??")
1749 fn scan_raw_byte_string(&mut self) -> token::Lit {
1750 let start_bpos = self.pos;
1752 let mut hash_count = 0;
1753 while self.ch_is('#') {
1754 if hash_count == 65535 {
1755 let bpos = self.next_pos;
1756 self.fatal_span_(start_bpos,
1758 "too many `#` symbols: raw byte strings may be \
1759 delimited by up to 65535 `#` symbols").raise();
1766 self.fail_unterminated_raw_string(start_bpos, hash_count);
1767 } else if !self.ch_is('"') {
1769 let ch = self.ch.unwrap();
1770 self.fatal_span_char(start_bpos,
1772 "found invalid character; only `#` is allowed in raw \
1773 string delimitation",
1777 let content_start_bpos = self.pos;
1778 let mut content_end_bpos;
1782 self.fail_unterminated_raw_string(start_bpos, hash_count);
1785 content_end_bpos = self.pos;
1786 for _ in 0..hash_count {
1788 if !self.ch_is('#') {
1797 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1806 token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), hash_count)
1810 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1811 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1813 crate fn is_pattern_whitespace(c: Option<char>) -> bool {
1814 c.map_or(false, Pattern_White_Space)
1818 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1819 c.map_or(false, |c| lo <= c && c <= hi)
1823 fn is_dec_digit(c: Option<char>) -> bool {
1824 in_range(c, '0', '9')
1827 fn is_doc_comment(s: &str) -> bool {
1828 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1829 s.starts_with("//!");
1830 debug!("is {:?} a doc comment? {}", s, res);
1834 fn is_block_doc_comment(s: &str) -> bool {
1835 // Prevent `/**/` from being parsed as a doc comment
1836 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1837 s.starts_with("/*!")) && s.len() >= 5;
1838 debug!("is {:?} a doc comment? {}", s, res);
1842 fn ident_start(c: Option<char>) -> bool {
1845 None => return false,
1848 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1851 fn ident_continue(c: Option<char>) -> bool {
1854 None => return false,
1857 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1858 (c > '\x7f' && c.is_xid_continue())
1865 use ast::{Ident, CrateConfig};
1867 use syntax_pos::{BytePos, Span, NO_EXPANSION};
1868 use source_map::SourceMap;
1870 use feature_gate::UnstableFeatures;
1873 use std::path::PathBuf;
1874 use diagnostics::plugin::ErrorMap;
1875 use rustc_data_structures::fx::FxHashSet;
1876 use rustc_data_structures::sync::Lock;
1878 fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
1879 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
1884 span_diagnostic: errors::Handler::with_emitter(true, false, Box::new(emitter)),
1885 unstable_features: UnstableFeatures::from_environment(),
1886 config: CrateConfig::default(),
1887 included_mod_stack: Lock::new(Vec::new()),
1889 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
1890 raw_identifier_spans: Lock::new(Vec::new()),
1891 registered_diagnostics: Lock::new(ErrorMap::new()),
1892 buffered_lints: Lock::new(vec![]),
1896 // open a string reader for the given string
1897 fn setup<'a>(sm: &SourceMap,
1898 sess: &'a ParseSess,
1900 -> StringReader<'a> {
1901 let sf = sm.new_source_file(PathBuf::from("zebra.rs").into(), teststr);
1902 StringReader::new(sess, sf, None)
1908 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1909 let sh = mk_sess(sm.clone());
1910 let mut string_reader = setup(&sm,
1912 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1914 let id = Ident::from_str("fn");
1915 assert_eq!(string_reader.next_token().tok, token::Comment);
1916 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1917 let tok1 = string_reader.next_token();
1918 let tok2 = TokenAndSpan {
1919 tok: token::Ident(id, false),
1920 sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
1922 assert_eq!(tok1.tok, tok2.tok);
1923 assert_eq!(tok1.sp, tok2.sp);
1924 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1925 // the 'main' id is already read:
1926 assert_eq!(string_reader.pos.clone(), BytePos(28));
1927 // read another token:
1928 let tok3 = string_reader.next_token();
1929 let tok4 = TokenAndSpan {
1930 tok: mk_ident("main"),
1931 sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
1933 assert_eq!(tok3.tok, tok4.tok);
1934 assert_eq!(tok3.sp, tok4.sp);
1935 // the lparen is already read:
1936 assert_eq!(string_reader.pos.clone(), BytePos(29))
1940 // check that the given reader produces the desired stream
1941 // of tokens (stop checking after exhausting the expected vec)
1942 fn check_tokenization(mut string_reader: StringReader, expected: Vec<token::Token>) {
1943 for expected_tok in &expected {
1944 assert_eq!(&string_reader.next_token().tok, expected_tok);
1948 // make the identifier by looking up the string in the interner
1949 fn mk_ident(id: &str) -> token::Token {
1950 token::Token::from_ast_ident(Ident::from_str(id))
1954 fn doublecolonparsing() {
1956 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1957 let sh = mk_sess(sm.clone());
1958 check_tokenization(setup(&sm, &sh, "a b".to_string()),
1959 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1966 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1967 let sh = mk_sess(sm.clone());
1968 check_tokenization(setup(&sm, &sh, "a::b".to_string()),
1969 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1976 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1977 let sh = mk_sess(sm.clone());
1978 check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
1979 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
1986 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1987 let sh = mk_sess(sm.clone());
1988 check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
1989 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
1996 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
1997 let sh = mk_sess(sm.clone());
1998 assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok,
1999 token::Literal(token::Char(Symbol::intern("a")), None));
2004 fn character_space() {
2006 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2007 let sh = mk_sess(sm.clone());
2008 assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok,
2009 token::Literal(token::Char(Symbol::intern(" ")), None));
2014 fn character_escaped() {
2016 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2017 let sh = mk_sess(sm.clone());
2018 assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok,
2019 token::Literal(token::Char(Symbol::intern("\\n")), None));
2024 fn lifetime_name() {
2026 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2027 let sh = mk_sess(sm.clone());
2028 assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok,
2029 token::Lifetime(Ident::from_str("'abc")));
2036 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2037 let sh = mk_sess(sm.clone());
2038 assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
2041 token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
2046 fn literal_suffixes() {
2048 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2049 let sh = mk_sess(sm.clone());
2051 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
2052 assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token().tok,
2053 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2054 Some(Symbol::intern("suffix"))));
2055 // with a whitespace separator:
2056 assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token().tok,
2057 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
2062 test!("'a'", Char, "a");
2063 test!("b'a'", Byte, "a");
2064 test!("\"a\"", Str_, "a");
2065 test!("b\"a\"", ByteStr, "a");
2066 test!("1234", Integer, "1234");
2067 test!("0b101", Integer, "0b101");
2068 test!("0xABC", Integer, "0xABC");
2069 test!("1.0", Float, "1.0");
2070 test!("1.0e10", Float, "1.0e10");
2072 assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token().tok,
2073 token::Literal(token::Integer(Symbol::intern("2")),
2074 Some(Symbol::intern("us"))));
2075 assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
2076 token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
2077 Some(Symbol::intern("suffix"))));
2078 assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
2079 token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
2080 Some(Symbol::intern("suffix"))));
2085 fn line_doc_comments() {
2086 assert!(is_doc_comment("///"));
2087 assert!(is_doc_comment("/// blah"));
2088 assert!(!is_doc_comment("////"));
2092 fn nested_block_comments() {
2094 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2095 let sh = mk_sess(sm.clone());
2096 let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
2097 match lexer.next_token().tok {
2098 token::Comment => {}
2099 _ => panic!("expected a comment!"),
2101 assert_eq!(lexer.next_token().tok,
2102 token::Literal(token::Char(Symbol::intern("a")), None));
2107 fn crlf_comments() {
2109 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
2110 let sh = mk_sess(sm.clone());
2111 let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
2112 let comment = lexer.next_token();
2113 assert_eq!(comment.tok, token::Comment);
2114 assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
2115 assert_eq!(lexer.next_token().tok, token::Whitespace);
2116 assert_eq!(lexer.next_token().tok,
2117 token::DocComment(Symbol::intern("/// test")));