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.
12 use codemap::{BytePos, CharPos, CodeMap, Pos, Span};
14 use diagnostic::SpanHandler;
15 use ext::tt::transcribe::tt_next_token;
17 use parse::token::{str_to_ident};
19 use std::borrow::IntoCow;
22 use std::mem::replace;
26 use std::string::CowString;
28 pub use ext::tt::transcribe::{TtReader, new_tt_reader, new_tt_reader_with_doc_flag};
33 fn is_eof(&self) -> bool;
34 fn next_token(&mut self) -> TokenAndSpan;
35 /// Report a fatal error with the current span.
36 fn fatal(&self, &str) -> !;
37 /// Report a non-fatal error with the current span.
39 fn peek(&self) -> TokenAndSpan;
40 /// Get a token the parser cares about.
41 fn real_token(&mut self) -> TokenAndSpan {
42 let mut t = self.next_token();
45 token::Whitespace | token::Comment | token::Shebang(_) => {
46 t = self.next_token();
55 #[derive(Clone, PartialEq, Eq, Debug)]
56 pub struct TokenAndSpan {
57 pub tok: token::Token,
61 pub struct StringReader<'a> {
62 pub span_diagnostic: &'a SpanHandler,
63 /// The absolute offset within the codemap of the next character to read
65 /// The absolute offset within the codemap of the last character read(curr)
66 pub last_pos: BytePos,
67 /// The column of the next character to read
69 /// The last character to be read
70 pub curr: Option<char>,
71 pub filemap: Rc<codemap::FileMap>,
73 pub peek_tok: token::Token,
76 // FIXME (Issue #16472): This field should go away after ToToken impls
77 // are revised to go directly to token-trees.
78 /// Is \x00<name>,<ctxt>\x00 is interpreted as encoded ast::Ident?
79 read_embedded_ident: bool,
82 impl<'a> Reader for StringReader<'a> {
83 fn is_eof(&self) -> bool { self.curr.is_none() }
84 /// Return the next token. EFFECT: advances the string_reader.
85 fn next_token(&mut self) -> TokenAndSpan {
86 let ret_val = TokenAndSpan {
87 tok: replace(&mut self.peek_tok, token::Underscore),
93 fn fatal(&self, m: &str) -> ! {
94 self.fatal_span(self.peek_span, m)
96 fn err(&self, m: &str) {
97 self.err_span(self.peek_span, m)
99 fn peek(&self) -> TokenAndSpan {
100 // FIXME(pcwalton): Bad copy!
102 tok: self.peek_tok.clone(),
108 impl<'a> Reader for TtReader<'a> {
109 fn is_eof(&self) -> bool {
110 self.cur_tok == token::Eof
112 fn next_token(&mut self) -> TokenAndSpan {
113 let r = tt_next_token(self);
114 debug!("TtReader: r={:?}", r);
117 fn fatal(&self, m: &str) -> ! {
118 self.sp_diag.span_fatal(self.cur_span, m);
120 fn err(&self, m: &str) {
121 self.sp_diag.span_err(self.cur_span, m);
123 fn peek(&self) -> TokenAndSpan {
125 tok: self.cur_tok.clone(),
131 // FIXME (Issue #16472): This function should go away after
132 // ToToken impls are revised to go directly to token-trees.
133 pub fn make_reader_with_embedded_idents<'b>(span_diagnostic: &'b SpanHandler,
134 filemap: Rc<codemap::FileMap>)
135 -> StringReader<'b> {
136 let mut sr = StringReader::new_raw(span_diagnostic, filemap);
137 sr.read_embedded_ident = true;
142 impl<'a> StringReader<'a> {
143 /// For comments.rs, which hackily pokes into pos and curr
144 pub fn new_raw<'b>(span_diagnostic: &'b SpanHandler,
145 filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
146 let mut sr = StringReader {
147 span_diagnostic: span_diagnostic,
148 pos: filemap.start_pos,
149 last_pos: filemap.start_pos,
153 /* dummy values; not read */
154 peek_tok: token::Eof,
155 peek_span: codemap::DUMMY_SP,
156 read_embedded_ident: false,
162 pub fn new<'b>(span_diagnostic: &'b SpanHandler,
163 filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
164 let mut sr = StringReader::new_raw(span_diagnostic, filemap);
169 pub fn curr_is(&self, c: char) -> bool {
173 /// Report a fatal lexical error with a given span.
174 pub fn fatal_span(&self, sp: Span, m: &str) -> ! {
175 self.span_diagnostic.span_fatal(sp, m)
178 /// Report a lexical error with a given span.
179 pub fn err_span(&self, sp: Span, m: &str) {
180 self.span_diagnostic.span_err(sp, m)
183 /// Report a fatal error spanning [`from_pos`, `to_pos`).
184 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
185 self.fatal_span(codemap::mk_sp(from_pos, to_pos), m)
188 /// Report a lexical error spanning [`from_pos`, `to_pos`).
189 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
190 self.err_span(codemap::mk_sp(from_pos, to_pos), m)
193 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
194 /// escaped character to the error message
195 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> ! {
196 let mut m = m.to_string();
198 for c in c.escape_default() { m.push(c) }
199 self.fatal_span_(from_pos, to_pos, &m[]);
202 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
203 /// escaped character to the error message
204 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
205 let mut m = m.to_string();
207 for c in c.escape_default() { m.push(c) }
208 self.err_span_(from_pos, to_pos, &m[]);
211 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
212 /// offending string to the error message
213 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> ! {
215 let from = self.byte_offset(from_pos).to_usize();
216 let to = self.byte_offset(to_pos).to_usize();
217 m.push_str(&self.filemap.src[from..to]);
218 self.fatal_span_(from_pos, to_pos, &m[]);
221 /// Advance peek_tok and peek_span to refer to the next token, and
222 /// possibly update the interner.
223 fn advance_token(&mut self) {
224 match self.scan_whitespace_or_comment() {
226 self.peek_span = comment.sp;
227 self.peek_tok = comment.tok;
231 self.peek_tok = token::Eof;
233 let start_bytepos = self.last_pos;
234 self.peek_tok = self.next_token_inner();
235 self.peek_span = codemap::mk_sp(start_bytepos,
242 fn byte_offset(&self, pos: BytePos) -> BytePos {
243 (pos - self.filemap.start_pos)
246 /// Calls `f` with a string slice of the source text spanning from `start`
247 /// up to but excluding `self.last_pos`, meaning the slice does not include
248 /// the character `self.curr`.
249 pub fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T where
250 F: FnOnce(&str) -> T,
252 self.with_str_from_to(start, self.last_pos, f)
255 /// Create a Name from a given offset to the current offset, each
256 /// adjusted 1 towards each other (assumes that on either side there is a
257 /// single-byte delimiter).
258 pub fn name_from(&self, start: BytePos) -> ast::Name {
259 debug!("taking an ident from {:?} to {:?}", start, self.last_pos);
260 self.with_str_from(start, token::intern)
263 /// As name_from, with an explicit endpoint.
264 pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
265 debug!("taking an ident from {:?} to {:?}", start, end);
266 self.with_str_from_to(start, end, token::intern)
269 /// Calls `f` with a string slice of the source text spanning from `start`
270 /// up to but excluding `end`.
271 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T where
272 F: FnOnce(&str) -> T,
275 self.byte_offset(start).to_usize()..
276 self.byte_offset(end).to_usize()])
279 /// Converts CRLF to LF in the given string, raising an error on bare CR.
280 fn translate_crlf<'b>(&self, start: BytePos,
281 s: &'b str, errmsg: &'b str) -> CowString<'b> {
284 let str::CharRange { ch, next } = s.char_range_at(i);
286 if next < s.len() && s.char_at(next) == '\n' {
287 return translate_crlf_(self, start, s, errmsg, i).into_cow();
289 let pos = start + BytePos(i as u32);
290 let end_pos = start + BytePos(next as u32);
291 self.err_span_(pos, end_pos, errmsg);
297 fn translate_crlf_(rdr: &StringReader, start: BytePos,
298 s: &str, errmsg: &str, mut i: usize) -> String {
299 let mut buf = String::with_capacity(s.len());
302 let str::CharRange { ch, next } = s.char_range_at(i);
304 if j < i { buf.push_str(&s[j..i]); }
306 if next >= s.len() || s.char_at(next) != '\n' {
307 let pos = start + BytePos(i as u32);
308 let end_pos = start + BytePos(next as u32);
309 rdr.err_span_(pos, end_pos, errmsg);
314 if j < s.len() { buf.push_str(&s[j..]); }
320 /// Advance the StringReader by one character. If a newline is
321 /// discovered, add it to the FileMap's list of line start offsets.
322 pub fn bump(&mut self) {
323 self.last_pos = self.pos;
324 let current_byte_offset = self.byte_offset(self.pos).to_usize();
325 if current_byte_offset < self.filemap.src.len() {
326 assert!(self.curr.is_some());
327 let last_char = self.curr.unwrap();
328 let next = self.filemap
330 .char_range_at(current_byte_offset);
331 let byte_offset_diff = next.next - current_byte_offset;
332 self.pos = self.pos + Pos::from_usize(byte_offset_diff);
333 self.curr = Some(next.ch);
334 self.col = self.col + CharPos(1);
335 if last_char == '\n' {
336 self.filemap.next_line(self.last_pos);
337 self.col = CharPos(0);
340 if byte_offset_diff > 1 {
341 self.filemap.record_multibyte_char(self.last_pos, byte_offset_diff);
348 pub fn nextch(&self) -> Option<char> {
349 let offset = self.byte_offset(self.pos).to_usize();
350 if offset < self.filemap.src.len() {
351 Some(self.filemap.src.char_at(offset))
357 pub fn nextch_is(&self, c: char) -> bool {
358 self.nextch() == Some(c)
361 pub fn nextnextch(&self) -> Option<char> {
362 let offset = self.byte_offset(self.pos).to_usize();
363 let s = &*self.filemap.src;
364 if offset >= s.len() { return None }
365 let str::CharRange { next, .. } = s.char_range_at(offset);
367 Some(s.char_at(next))
373 pub fn nextnextch_is(&self, c: char) -> bool {
374 self.nextnextch() == Some(c)
377 /// Eats <XID_start><XID_continue>*, if possible.
378 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
379 if !ident_start(self.curr) {
382 let start = self.last_pos;
383 while ident_continue(self.curr) {
387 self.with_str_from(start, |string| {
391 Some(token::intern(string))
396 /// PRECONDITION: self.curr is not whitespace
397 /// Eats any kind of comment.
398 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
401 if c.is_whitespace() {
402 self.span_diagnostic.span_err(codemap::mk_sp(self.last_pos, self.last_pos),
403 "called consume_any_line_comment, but there was whitespace");
409 if self.curr_is('/') {
410 match self.nextch() {
414 // line comments starting with "///" or "//!" are doc-comments
415 if self.curr_is('/') || self.curr_is('!') {
416 let start_bpos = self.pos - BytePos(3);
417 while !self.is_eof() {
418 match self.curr.unwrap() {
421 if self.nextch_is('\n') {
425 self.err_span_(self.last_pos, self.pos,
426 "bare CR not allowed in doc-comment");
433 return self.with_str_from(start_bpos, |string| {
434 // but comments with only more "/"s are not
435 let tok = if is_doc_comment(string) {
436 token::DocComment(token::intern(string))
441 return Some(TokenAndSpan{
443 sp: codemap::mk_sp(start_bpos, self.last_pos)
447 let start_bpos = self.last_pos - BytePos(2);
448 while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
449 return Some(TokenAndSpan {
451 sp: codemap::mk_sp(start_bpos, self.last_pos)
456 self.bump(); self.bump();
457 self.scan_block_comment()
461 } else if self.curr_is('#') {
462 if self.nextch_is('!') {
464 // Parse an inner attribute.
465 if self.nextnextch_is('[') {
469 // I guess this is the only way to figure out if
470 // we're at the beginning of the file...
471 let cmap = CodeMap::new();
472 cmap.files.borrow_mut().push(self.filemap.clone());
473 let loc = cmap.lookup_char_pos_adj(self.last_pos);
474 debug!("Skipping a shebang");
475 if loc.line == 1 && loc.col == CharPos(0) {
476 // FIXME: Add shebang "token", return it
477 let start = self.last_pos;
478 while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
479 return Some(TokenAndSpan {
480 tok: token::Shebang(self.name_from(start)),
481 sp: codemap::mk_sp(start, self.last_pos)
491 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
493 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
494 match self.curr.unwrap_or('\0') {
495 // # to handle shebang at start of file -- this is the entry point
496 // for skipping over all "junk"
498 let c = self.scan_comment();
499 debug!("scanning a comment {:?}", c);
502 c if is_whitespace(Some(c)) => {
503 let start_bpos = self.last_pos;
504 while is_whitespace(self.curr) { self.bump(); }
505 let c = Some(TokenAndSpan {
506 tok: token::Whitespace,
507 sp: codemap::mk_sp(start_bpos, self.last_pos)
509 debug!("scanning whitespace: {:?}", c);
516 /// Might return a sugared-doc-attr
517 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
518 // block comments starting with "/**" or "/*!" are doc-comments
519 let is_doc_comment = self.curr_is('*') || self.curr_is('!');
520 let start_bpos = self.last_pos - BytePos(2);
522 let mut level: isize = 1;
523 let mut has_cr = false;
526 let msg = if is_doc_comment {
527 "unterminated block doc-comment"
529 "unterminated block comment"
531 let last_bpos = self.last_pos;
532 self.fatal_span_(start_bpos, last_bpos, msg);
534 let n = self.curr.unwrap();
536 '/' if self.nextch_is('*') => {
540 '*' if self.nextch_is('/') => {
552 self.with_str_from(start_bpos, |string| {
553 // but comments with only "*"s between two "/"s are not
554 let tok = if is_block_doc_comment(string) {
555 let string = if has_cr {
556 self.translate_crlf(start_bpos, string,
557 "bare CR not allowed in block doc-comment")
558 } else { string.into_cow() };
559 token::DocComment(token::intern(&string[]))
566 sp: codemap::mk_sp(start_bpos, self.last_pos)
571 // FIXME (Issue #16472): The scan_embedded_hygienic_ident function
572 // should go away after we revise the syntax::ext::quote::ToToken
573 // impls to go directly to token-trees instead of thing -> string
574 // -> token-trees. (The function is currently used to resolve
575 // Issues #15750 and #15962.)
577 // Since this function is only used for certain internal macros,
578 // and the functionality it provides is not exposed to end user
579 // programs, pnkfelix deliberately chose to write it in a way that
580 // favors rustc debugging effectiveness over runtime efficiency.
582 /// Scan through input of form \x00name_NNNNNN,ctxt_CCCCCCC\x00
583 /// whence: `NNNNNN` is a string of characters forming an integer
584 /// (the name) and `CCCCCCC` is a string of characters forming an
585 /// integer (the ctxt), separate by a comma and delimited by a
588 fn scan_embedded_hygienic_ident(&mut self) -> ast::Ident {
589 fn bump_expecting_char<'a,D:fmt::Debug>(r: &mut StringReader<'a>,
594 Some(r_c) if r_c == c => r.bump(),
595 Some(r_c) => panic!("expected {:?}, hit {:?}, {}", described_c, r_c, whence),
596 None => panic!("expected {:?}, hit EOF, {}", described_c, whence),
600 let whence = "while scanning embedded hygienic ident";
602 // skip over the leading `\x00`
603 bump_expecting_char(self, '\x00', "nul-byte", whence);
605 // skip over the "name_"
606 for c in "name_".chars() {
607 bump_expecting_char(self, c, c, whence);
610 let start_bpos = self.last_pos;
613 // find the integer representing the name
614 self.scan_digits(base);
615 let encoded_name : u32 = self.with_str_from(start_bpos, |s| {
616 num::from_str_radix(s, 10).ok().unwrap_or_else(|| {
617 panic!("expected digits representing a name, got {:?}, {}, range [{:?},{:?}]",
618 s, whence, start_bpos, self.last_pos);
623 bump_expecting_char(self, ',', "comma", whence);
625 // skip over the "ctxt_"
626 for c in "ctxt_".chars() {
627 bump_expecting_char(self, c, c, whence);
630 // find the integer representing the ctxt
631 let start_bpos = self.last_pos;
632 self.scan_digits(base);
633 let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| {
634 num::from_str_radix(s, 10).ok().unwrap_or_else(|| {
635 panic!("expected digits representing a ctxt, got {:?}, {}", s, whence);
639 // skip over the `\x00`
640 bump_expecting_char(self, '\x00', "nul-byte", whence);
642 ast::Ident { name: ast::Name(encoded_name),
643 ctxt: encoded_ctxt, }
646 /// Scan through any digits (base `radix`) or underscores, and return how
647 /// many digits there were.
648 fn scan_digits(&mut self, radix: u32) -> usize {
652 if c == Some('_') { debug!("skipping a _"); self.bump(); continue; }
653 match c.and_then(|cc| cc.to_digit(radix)) {
655 debug!("{:?} in scan_digits", c);
664 /// Lex a LIT_INTEGER or a LIT_FLOAT
665 fn scan_number(&mut self, c: char) -> token::Lit {
668 let start_bpos = self.last_pos;
673 match self.curr.unwrap_or('\0') {
674 'b' => { self.bump(); base = 2; num_digits = self.scan_digits(2); }
675 'o' => { self.bump(); base = 8; num_digits = self.scan_digits(8); }
676 'x' => { self.bump(); base = 16; num_digits = self.scan_digits(16); }
677 '0'...'9' | '_' | '.' => {
678 num_digits = self.scan_digits(10) + 1;
682 return token::Integer(self.name_from(start_bpos));
685 } else if c.is_digit(10) {
686 num_digits = self.scan_digits(10) + 1;
692 self.err_span_(start_bpos, self.last_pos, "no valid digits found for number");
693 return token::Integer(token::intern("0"));
696 // might be a float, but don't be greedy if this is actually an
697 // integer literal followed by field/method access or a range pattern
698 // (`0..2` and `12.foo()`)
699 if self.curr_is('.') && !self.nextch_is('.') && !self.nextch().unwrap_or('\0')
701 // might have stuff after the ., and if it does, it needs to start
704 if self.curr.unwrap_or('\0').is_digit(10) {
705 self.scan_digits(10);
706 self.scan_float_exponent();
708 let last_pos = self.last_pos;
709 self.check_float_base(start_bpos, last_pos, base);
710 return token::Float(self.name_from(start_bpos));
712 // it might be a float if it has an exponent
713 if self.curr_is('e') || self.curr_is('E') {
714 self.scan_float_exponent();
715 let last_pos = self.last_pos;
716 self.check_float_base(start_bpos, last_pos, base);
717 return token::Float(self.name_from(start_bpos));
719 // but we certainly have an integer!
720 return token::Integer(self.name_from(start_bpos));
724 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
725 /// error if too many or too few digits are encountered.
726 fn scan_hex_digits(&mut self,
729 below_0x7f_only: bool)
731 debug!("scanning {} digits until {:?}", n_digits, delim);
732 let start_bpos = self.last_pos;
733 let mut accum_int = 0;
735 for _ in 0..n_digits {
737 let last_bpos = self.last_pos;
738 self.fatal_span_(start_bpos, last_bpos, "unterminated numeric character escape");
740 if self.curr_is(delim) {
741 let last_bpos = self.last_pos;
742 self.err_span_(start_bpos, last_bpos, "numeric character escape is too short");
745 let c = self.curr.unwrap_or('\x00');
747 accum_int += c.to_digit(16).unwrap_or_else(|| {
748 self.err_span_char(self.last_pos, self.pos,
749 "illegal character in numeric character escape", c);
755 if below_0x7f_only && accum_int >= 0x80 {
756 self.err_span_(start_bpos,
758 "this form of character escape may only be used \
759 with characters in the range [\\x00-\\x7f]");
762 match char::from_u32(accum_int) {
765 let last_bpos = self.last_pos;
766 self.err_span_(start_bpos, last_bpos, "illegal numeric character escape");
772 fn old_escape_warning(&mut self, sp: Span) {
774 .span_warn(sp, "\\U00ABCD12 and \\uABCD escapes are deprecated");
776 .span_help(sp, "use \\u{ABCD12} escapes instead");
779 /// Scan for a single (possibly escaped) byte or char
780 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
781 /// `start` is the position of `first_source_char`, which is already consumed.
783 /// Returns true if there was a valid char/byte, false otherwise.
784 fn scan_char_or_byte(&mut self, start: BytePos, first_source_char: char,
785 ascii_only: bool, delim: char) -> bool {
786 match first_source_char {
788 // '\X' for some X must be a character constant:
789 let escaped = self.curr;
790 let escaped_pos = self.last_pos;
793 None => {}, // EOF here is an error that will be checked later.
796 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
797 'x' => self.scan_byte_escape(delim, !ascii_only),
798 'u' if !ascii_only => {
799 if self.curr == Some('{') {
800 self.scan_unicode_escape(delim)
802 let res = self.scan_hex_digits(4, delim, false);
803 let sp = codemap::mk_sp(escaped_pos, self.last_pos);
804 self.old_escape_warning(sp);
808 'U' if !ascii_only => {
809 let res = self.scan_hex_digits(8, delim, false);
810 let sp = codemap::mk_sp(escaped_pos, self.last_pos);
811 self.old_escape_warning(sp);
814 '\n' if delim == '"' => {
815 self.consume_whitespace();
818 '\r' if delim == '"' && self.curr_is('\n') => {
819 self.consume_whitespace();
823 let last_pos = self.last_pos;
825 escaped_pos, last_pos,
826 if ascii_only { "unknown byte escape" }
827 else { "unknown character escape" },
830 let sp = codemap::mk_sp(escaped_pos, last_pos);
831 self.span_diagnostic.span_help(
833 "this is an isolated carriage return; consider checking \
834 your editor and version control settings")
842 '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
843 let last_pos = self.last_pos;
846 if ascii_only { "byte constant must be escaped" }
847 else { "character constant must be escaped" },
852 if self.curr_is('\n') {
856 self.err_span_(start, self.last_pos,
857 "bare CR not allowed in string, use \\r instead");
861 _ => if ascii_only && first_source_char > '\x7F' {
862 let last_pos = self.last_pos;
865 "byte constant must be ASCII. \
866 Use a \\xHH escape for a non-ASCII byte", first_source_char);
873 /// Scan over a \u{...} escape
875 /// At this point, we have already seen the \ and the u, the { is the current character. We
876 /// will read at least one digit, and up to 6, and pass over the }.
877 fn scan_unicode_escape(&mut self, delim: char) -> bool {
878 self.bump(); // past the {
879 let start_bpos = self.last_pos;
881 let mut accum_int = 0;
883 while !self.curr_is('}') && count <= 6 {
884 let c = match self.curr {
887 self.fatal_span_(start_bpos, self.last_pos,
888 "unterminated unicode escape (found EOF)");
892 accum_int += c.to_digit(16).unwrap_or_else(|| {
894 self.fatal_span_(self.last_pos, self.pos,
895 "unterminated unicode escape (needed a `}`)");
897 self.fatal_span_char(self.last_pos, self.pos,
898 "illegal character in unicode escape", c);
906 self.fatal_span_(start_bpos, self.last_pos,
907 "overlong unicode escape (can have at most 6 hex digits)");
910 self.bump(); // past the ending }
912 let mut valid = count >= 1 && count <= 6;
913 if char::from_u32(accum_int).is_none() {
918 self.fatal_span_(start_bpos, self.last_pos, "illegal unicode character escape");
923 /// Scan over a float exponent.
924 fn scan_float_exponent(&mut self) {
925 if self.curr_is('e') || self.curr_is('E') {
927 if self.curr_is('-') || self.curr_is('+') {
930 if self.scan_digits(10) == 0 {
931 self.err_span_(self.last_pos, self.pos, "expected at least one digit in exponent")
936 /// Check that a base is valid for a floating literal, emitting a nice
937 /// error if it isn't.
938 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
940 16 => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \
942 8 => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"),
943 2 => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"),
948 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
950 if self.curr_is('=') {
952 return token::BinOpEq(op);
954 return token::BinOp(op);
958 /// Return the next token from the string, advances the input past that
959 /// token, and updates the interner
960 fn next_token_inner(&mut self) -> token::Token {
962 if ident_start(c) && match (c.unwrap(), self.nextch(), self.nextnextch()) {
963 // Note: r as in r" or r#" is part of a raw string literal,
964 // b as in b' is part of a byte literal.
965 // They are not identifiers, and are handled further down.
966 ('r', Some('"'), _) | ('r', Some('#'), _) |
967 ('b', Some('"'), _) | ('b', Some('\''), _) |
968 ('b', Some('r'), Some('"')) | ('b', Some('r'), Some('#')) => false,
971 let start = self.last_pos;
972 while ident_continue(self.curr) {
976 return self.with_str_from(start, |string| {
980 // FIXME: perform NFKC normalization here. (Issue #2253)
981 if self.curr_is(':') && self.nextch_is(':') {
982 token::Ident(str_to_ident(string), token::ModName)
984 token::Ident(str_to_ident(string), token::Plain)
991 let num = self.scan_number(c.unwrap());
992 let suffix = self.scan_optional_raw_name();
993 debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
994 return token::Literal(num, suffix)
997 if self.read_embedded_ident {
998 match (c.unwrap(), self.nextch(), self.nextnextch()) {
999 ('\x00', Some('n'), Some('a')) => {
1000 let ast_ident = self.scan_embedded_hygienic_ident();
1001 return if self.curr_is(':') && self.nextch_is(':') {
1002 token::Ident(ast_ident, token::ModName)
1004 token::Ident(ast_ident, token::Plain)
1011 match c.expect("next_token_inner called at EOF") {
1013 ';' => { self.bump(); return token::Semi; }
1014 ',' => { self.bump(); return token::Comma; }
1017 return if self.curr_is('.') {
1019 if self.curr_is('.') {
1029 '(' => { self.bump(); return token::OpenDelim(token::Paren); }
1030 ')' => { self.bump(); return token::CloseDelim(token::Paren); }
1031 '{' => { self.bump(); return token::OpenDelim(token::Brace); }
1032 '}' => { self.bump(); return token::CloseDelim(token::Brace); }
1033 '[' => { self.bump(); return token::OpenDelim(token::Bracket); }
1034 ']' => { self.bump(); return token::CloseDelim(token::Bracket); }
1035 '@' => { self.bump(); return token::At; }
1036 '#' => { self.bump(); return token::Pound; }
1037 '~' => { self.bump(); return token::Tilde; }
1038 '?' => { self.bump(); return token::Question; }
1041 if self.curr_is(':') {
1043 return token::ModSep;
1045 return token::Colon;
1049 '$' => { self.bump(); return token::Dollar; }
1051 // Multi-byte tokens.
1054 if self.curr_is('=') {
1057 } else if self.curr_is('>') {
1059 return token::FatArrow;
1066 if self.curr_is('=') {
1069 } else { return token::Not; }
1073 match self.curr.unwrap_or('\x00') {
1074 '=' => { self.bump(); return token::Le; }
1075 '<' => { return self.binop(token::Shl); }
1078 match self.curr.unwrap_or('\x00') {
1079 _ => { return token::LArrow; }
1082 _ => { return token::Lt; }
1087 match self.curr.unwrap_or('\x00') {
1088 '=' => { self.bump(); return token::Ge; }
1089 '>' => { return self.binop(token::Shr); }
1090 _ => { return token::Gt; }
1094 // Either a character constant 'a' OR a lifetime name 'abc
1096 let start = self.last_pos;
1098 // the eof will be picked up by the final `'` check below
1099 let c2 = self.curr.unwrap_or('\x00');
1102 // If the character is an ident start not followed by another single
1103 // quote, then this is a lifetime name:
1104 if ident_start(Some(c2)) && !self.curr_is('\'') {
1105 while ident_continue(self.curr) {
1109 // Include the leading `'` in the real identifier, for macro
1110 // expansion purposes. See #12512 for the gory details of why
1111 // this is necessary.
1112 let ident = self.with_str_from(start, |lifetime_name| {
1113 str_to_ident(&format!("'{}", lifetime_name)[])
1116 // Conjure up a "keyword checking ident" to make sure that
1117 // the lifetime name is not a keyword.
1118 let keyword_checking_ident =
1119 self.with_str_from(start, |lifetime_name| {
1120 str_to_ident(lifetime_name)
1122 let keyword_checking_token =
1123 &token::Ident(keyword_checking_ident, token::Plain);
1124 let last_bpos = self.last_pos;
1125 if keyword_checking_token.is_keyword(token::keywords::SelfValue) {
1126 self.err_span_(start,
1128 "invalid lifetime name: 'self \
1129 is no longer a special lifetime");
1130 } else if keyword_checking_token.is_any_keyword() &&
1131 !keyword_checking_token.is_keyword(token::keywords::Static)
1133 self.err_span_(start,
1135 "invalid lifetime name");
1137 return token::Lifetime(ident);
1140 // Otherwise it is a character constant:
1141 let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ false, '\'');
1142 if !self.curr_is('\'') {
1143 let last_bpos = self.last_pos;
1144 self.fatal_span_verbose(
1145 // Byte offsetting here is okay because the
1146 // character before position `start` is an
1147 // ascii single quote.
1148 start - BytePos(1), last_bpos,
1149 "unterminated character constant".to_string());
1151 let id = if valid { self.name_from(start) } else { token::intern("0") };
1152 self.bump(); // advance curr past token
1153 let suffix = self.scan_optional_raw_name();
1154 return token::Literal(token::Char(id), suffix);
1158 let lit = match self.curr {
1159 Some('\'') => self.scan_byte(),
1160 Some('"') => self.scan_byte_string(),
1161 Some('r') => self.scan_raw_byte_string(),
1162 _ => unreachable!() // Should have been a token::Ident above.
1164 let suffix = self.scan_optional_raw_name();
1165 return token::Literal(lit, suffix);
1168 let start_bpos = self.last_pos;
1169 let mut valid = true;
1171 while !self.curr_is('"') {
1173 let last_bpos = self.last_pos;
1174 self.fatal_span_(start_bpos, last_bpos, "unterminated double quote string");
1177 let ch_start = self.last_pos;
1178 let ch = self.curr.unwrap();
1180 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ false, '"');
1182 // adjust for the ASCII " at the start of the literal
1183 let id = if valid { self.name_from(start_bpos + BytePos(1)) }
1184 else { token::intern("??") };
1186 let suffix = self.scan_optional_raw_name();
1187 return token::Literal(token::Str_(id), suffix);
1190 let start_bpos = self.last_pos;
1192 let mut hash_count = 0;
1193 while self.curr_is('#') {
1199 let last_bpos = self.last_pos;
1200 self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
1201 } else if !self.curr_is('"') {
1202 let last_bpos = self.last_pos;
1203 let curr_char = self.curr.unwrap();
1204 self.fatal_span_char(start_bpos, last_bpos,
1205 "only `#` is allowed in raw string delimitation; \
1206 found illegal character",
1210 let content_start_bpos = self.last_pos;
1211 let mut content_end_bpos;
1212 let mut valid = true;
1215 let last_bpos = self.last_pos;
1216 self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
1218 //if self.curr_is('"') {
1219 //content_end_bpos = self.last_pos;
1220 //for _ in 0..hash_count {
1222 //if !self.curr_is('#') {
1224 let c = self.curr.unwrap();
1227 content_end_bpos = self.last_pos;
1228 for _ in 0..hash_count {
1230 if !self.curr_is('#') {
1237 if !self.nextch_is('\n') {
1238 let last_bpos = self.last_pos;
1239 self.err_span_(start_bpos, last_bpos, "bare CR not allowed in raw \
1240 string, use \\r instead");
1250 self.name_from_to(content_start_bpos, content_end_bpos)
1254 let suffix = self.scan_optional_raw_name();
1255 return token::Literal(token::StrRaw(id, hash_count), suffix);
1258 if self.nextch_is('>') {
1261 return token::RArrow;
1262 } else { return self.binop(token::Minus); }
1265 if self.nextch_is('&') {
1268 return token::AndAnd;
1269 } else { return self.binop(token::And); }
1272 match self.nextch() {
1273 Some('|') => { self.bump(); self.bump(); return token::OrOr; }
1274 _ => { return self.binop(token::Or); }
1277 '+' => { return self.binop(token::Plus); }
1278 '*' => { return self.binop(token::Star); }
1279 '/' => { return self.binop(token::Slash); }
1280 '^' => { return self.binop(token::Caret); }
1281 '%' => { return self.binop(token::Percent); }
1283 let last_bpos = self.last_pos;
1284 let bpos = self.pos;
1285 self.fatal_span_char(last_bpos, bpos, "unknown start of token", c);
1290 fn consume_whitespace(&mut self) {
1291 while is_whitespace(self.curr) && !self.is_eof() { self.bump(); }
1294 fn read_to_eol(&mut self) -> String {
1295 let mut val = String::new();
1296 while !self.curr_is('\n') && !self.is_eof() {
1297 val.push(self.curr.unwrap());
1300 if self.curr_is('\n') { self.bump(); }
1304 fn read_one_line_comment(&mut self) -> String {
1305 let val = self.read_to_eol();
1306 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/')
1307 || (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1311 fn consume_non_eol_whitespace(&mut self) {
1312 while is_whitespace(self.curr) && !self.curr_is('\n') && !self.is_eof() {
1317 fn peeking_at_comment(&self) -> bool {
1318 (self.curr_is('/') && self.nextch_is('/'))
1319 || (self.curr_is('/') && self.nextch_is('*'))
1320 // consider shebangs comments, but not inner attributes
1321 || (self.curr_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1324 fn scan_byte(&mut self) -> token::Lit {
1326 let start = self.last_pos;
1328 // the eof will be picked up by the final `'` check below
1329 let c2 = self.curr.unwrap_or('\x00');
1332 let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ true, '\'');
1333 if !self.curr_is('\'') {
1334 // Byte offsetting here is okay because the
1335 // character before position `start` are an
1336 // ascii single quote and ascii 'b'.
1337 let last_pos = self.last_pos;
1338 self.fatal_span_verbose(
1339 start - BytePos(2), last_pos,
1340 "unterminated byte constant".to_string());
1343 let id = if valid { self.name_from(start) } else { token::intern("??") };
1344 self.bump(); // advance curr past token
1345 return token::Byte(id);
1348 fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1349 self.scan_hex_digits(2, delim, below_0x7f_only)
1352 fn scan_byte_string(&mut self) -> token::Lit {
1354 let start = self.last_pos;
1355 let mut valid = true;
1357 while !self.curr_is('"') {
1359 let last_pos = self.last_pos;
1360 self.fatal_span_(start, last_pos,
1361 "unterminated double quote byte string");
1364 let ch_start = self.last_pos;
1365 let ch = self.curr.unwrap();
1367 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ true, '"');
1369 let id = if valid { self.name_from(start) } else { token::intern("??") };
1371 return token::Binary(id);
1374 fn scan_raw_byte_string(&mut self) -> token::Lit {
1375 let start_bpos = self.last_pos;
1377 let mut hash_count = 0;
1378 while self.curr_is('#') {
1384 let last_pos = self.last_pos;
1385 self.fatal_span_(start_bpos, last_pos, "unterminated raw string");
1386 } else if !self.curr_is('"') {
1387 let last_pos = self.last_pos;
1388 let ch = self.curr.unwrap();
1389 self.fatal_span_char(start_bpos, last_pos,
1390 "only `#` is allowed in raw string delimitation; \
1391 found illegal character",
1395 let content_start_bpos = self.last_pos;
1396 let mut content_end_bpos;
1400 let last_pos = self.last_pos;
1401 self.fatal_span_(start_bpos, last_pos, "unterminated raw string")
1404 content_end_bpos = self.last_pos;
1405 for _ in 0..hash_count {
1407 if !self.curr_is('#') {
1413 Some(c) => if c > '\x7F' {
1414 let last_pos = self.last_pos;
1416 last_pos, last_pos, "raw byte string must be ASCII", c);
1422 return token::BinaryRaw(self.name_from_to(content_start_bpos,
1428 pub fn is_whitespace(c: Option<char>) -> bool {
1429 match c.unwrap_or('\x00') { // None can be null for now... it's not whitespace
1430 ' ' | '\n' | '\t' | '\r' => true,
1435 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1437 Some(c) => lo <= c && c <= hi,
1442 fn is_dec_digit(c: Option<char>) -> bool { return in_range(c, '0', '9'); }
1444 pub fn is_doc_comment(s: &str) -> bool {
1445 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/')
1446 || s.starts_with("//!");
1447 debug!("is {:?} a doc comment? {}", s, res);
1451 pub fn is_block_doc_comment(s: &str) -> bool {
1452 let res = (s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*')
1453 || s.starts_with("/*!");
1454 debug!("is {:?} a doc comment? {}", s, res);
1458 fn ident_start(c: Option<char>) -> bool {
1459 let c = match c { Some(c) => c, None => return false };
1461 (c >= 'a' && c <= 'z')
1462 || (c >= 'A' && c <= 'Z')
1464 || (c > '\x7f' && c.is_xid_start())
1467 fn ident_continue(c: Option<char>) -> bool {
1468 let c = match c { Some(c) => c, None => return false };
1470 (c >= 'a' && c <= 'z')
1471 || (c >= 'A' && c <= 'Z')
1472 || (c >= '0' && c <= '9')
1474 || (c > '\x7f' && c.is_xid_continue())
1481 use codemap::{BytePos, CodeMap, Span, NO_EXPANSION};
1484 use parse::token::{str_to_ident};
1485 use std::old_io::util;
1487 fn mk_sh() -> diagnostic::SpanHandler {
1488 let emitter = diagnostic::EmitterWriter::new(box util::NullWriter, None);
1489 let handler = diagnostic::mk_handler(true, box emitter);
1490 diagnostic::mk_span_handler(handler, CodeMap::new())
1493 // open a string reader for the given string
1494 fn setup<'a>(span_handler: &'a diagnostic::SpanHandler,
1495 teststr: String) -> StringReader<'a> {
1496 let fm = span_handler.cm.new_filemap("zebra.rs".to_string(), teststr);
1497 StringReader::new(span_handler, fm)
1501 let span_handler = mk_sh();
1502 let mut string_reader = setup(&span_handler,
1503 "/* my source file */ \
1504 fn main() { println!(\"zebra\"); }\n".to_string());
1505 let id = str_to_ident("fn");
1506 assert_eq!(string_reader.next_token().tok, token::Comment);
1507 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1508 let tok1 = string_reader.next_token();
1509 let tok2 = TokenAndSpan{
1510 tok:token::Ident(id, token::Plain),
1511 sp:Span {lo:BytePos(21),hi:BytePos(23),expn_id: NO_EXPANSION}};
1512 assert_eq!(tok1,tok2);
1513 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1514 // the 'main' id is already read:
1515 assert_eq!(string_reader.last_pos.clone(), BytePos(28));
1516 // read another token:
1517 let tok3 = string_reader.next_token();
1518 let tok4 = TokenAndSpan{
1519 tok:token::Ident(str_to_ident("main"), token::Plain),
1520 sp:Span {lo:BytePos(24),hi:BytePos(28),expn_id: NO_EXPANSION}};
1521 assert_eq!(tok3,tok4);
1522 // the lparen is already read:
1523 assert_eq!(string_reader.last_pos.clone(), BytePos(29))
1526 // check that the given reader produces the desired stream
1527 // of tokens (stop checking after exhausting the expected vec)
1528 fn check_tokenization (mut string_reader: StringReader, expected: Vec<token::Token> ) {
1529 for expected_tok in &expected {
1530 assert_eq!(&string_reader.next_token().tok, expected_tok);
1534 // make the identifier by looking up the string in the interner
1535 fn mk_ident(id: &str, style: token::IdentStyle) -> token::Token {
1536 token::Ident(str_to_ident(id), style)
1539 #[test] fn doublecolonparsing () {
1540 check_tokenization(setup(&mk_sh(), "a b".to_string()),
1541 vec![mk_ident("a", token::Plain),
1543 mk_ident("b", token::Plain)]);
1546 #[test] fn dcparsing_2 () {
1547 check_tokenization(setup(&mk_sh(), "a::b".to_string()),
1548 vec![mk_ident("a",token::ModName),
1550 mk_ident("b", token::Plain)]);
1553 #[test] fn dcparsing_3 () {
1554 check_tokenization(setup(&mk_sh(), "a ::b".to_string()),
1555 vec![mk_ident("a", token::Plain),
1558 mk_ident("b", token::Plain)]);
1561 #[test] fn dcparsing_4 () {
1562 check_tokenization(setup(&mk_sh(), "a:: b".to_string()),
1563 vec![mk_ident("a",token::ModName),
1566 mk_ident("b", token::Plain)]);
1569 #[test] fn character_a() {
1570 assert_eq!(setup(&mk_sh(), "'a'".to_string()).next_token().tok,
1571 token::Literal(token::Char(token::intern("a")), None));
1574 #[test] fn character_space() {
1575 assert_eq!(setup(&mk_sh(), "' '".to_string()).next_token().tok,
1576 token::Literal(token::Char(token::intern(" ")), None));
1579 #[test] fn character_escaped() {
1580 assert_eq!(setup(&mk_sh(), "'\\n'".to_string()).next_token().tok,
1581 token::Literal(token::Char(token::intern("\\n")), None));
1584 #[test] fn lifetime_name() {
1585 assert_eq!(setup(&mk_sh(), "'abc".to_string()).next_token().tok,
1586 token::Lifetime(token::str_to_ident("'abc")));
1589 #[test] fn raw_string() {
1590 assert_eq!(setup(&mk_sh(),
1591 "r###\"\"#a\\b\x00c\"\"###".to_string()).next_token()
1593 token::Literal(token::StrRaw(token::intern("\"#a\\b\x00c\""), 3), None));
1596 #[test] fn literal_suffixes() {
1598 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1599 assert_eq!(setup(&mk_sh(), format!("{}suffix", $input)).next_token().tok,
1600 token::Literal(token::$tok_type(token::intern($tok_contents)),
1601 Some(token::intern("suffix"))));
1602 // with a whitespace separator:
1603 assert_eq!(setup(&mk_sh(), format!("{} suffix", $input)).next_token().tok,
1604 token::Literal(token::$tok_type(token::intern($tok_contents)),
1609 test!("'a'", Char, "a");
1610 test!("b'a'", Byte, "a");
1611 test!("\"a\"", Str_, "a");
1612 test!("b\"a\"", Binary, "a");
1613 test!("1234", Integer, "1234");
1614 test!("0b101", Integer, "0b101");
1615 test!("0xABC", Integer, "0xABC");
1616 test!("1.0", Float, "1.0");
1617 test!("1.0e10", Float, "1.0e10");
1619 assert_eq!(setup(&mk_sh(), "2us".to_string()).next_token().tok,
1620 token::Literal(token::Integer(token::intern("2")),
1621 Some(token::intern("us"))));
1622 assert_eq!(setup(&mk_sh(), "r###\"raw\"###suffix".to_string()).next_token().tok,
1623 token::Literal(token::StrRaw(token::intern("raw"), 3),
1624 Some(token::intern("suffix"))));
1625 assert_eq!(setup(&mk_sh(), "br###\"raw\"###suffix".to_string()).next_token().tok,
1626 token::Literal(token::BinaryRaw(token::intern("raw"), 3),
1627 Some(token::intern("suffix"))));
1630 #[test] fn line_doc_comments() {
1631 assert!(is_doc_comment("///"));
1632 assert!(is_doc_comment("/// blah"));
1633 assert!(!is_doc_comment("////"));
1636 #[test] fn nested_block_comments() {
1638 let mut lexer = setup(&sh, "/* /* */ */'a'".to_string());
1639 match lexer.next_token().tok {
1640 token::Comment => { },
1641 _ => panic!("expected a comment!")
1643 assert_eq!(lexer.next_token().tok, token::Literal(token::Char(token::intern("a")), None));