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;
27 pub use ext::tt::transcribe::{TtReader, new_tt_reader};
32 fn is_eof(&self) -> bool;
33 fn next_token(&mut self) -> TokenAndSpan;
34 /// Report a fatal error with the current span.
35 fn fatal(&self, &str) -> !;
36 /// Report a non-fatal error with the current span.
38 fn peek(&self) -> TokenAndSpan;
39 /// Get a token the parser cares about.
40 fn real_token(&mut self) -> TokenAndSpan {
41 let mut t = self.next_token();
44 token::Whitespace | token::Comment | token::Shebang(_) => {
45 t = self.next_token();
54 #[deriving(Clone, PartialEq, Eq, Show)]
55 pub struct TokenAndSpan {
56 pub tok: token::Token,
60 pub struct StringReader<'a> {
61 pub span_diagnostic: &'a SpanHandler,
62 /// The absolute offset within the codemap of the next character to read
64 /// The absolute offset within the codemap of the last character read(curr)
65 pub last_pos: BytePos,
66 /// The column of the next character to read
68 /// The last character to be read
69 pub curr: Option<char>,
70 pub filemap: Rc<codemap::FileMap>,
72 pub peek_tok: token::Token,
75 // FIXME (Issue #16472): This field should go away after ToToken impls
76 // are revised to go directly to token-trees.
77 /// Is \x00<name>,<ctxt>\x00 is interpreted as encoded ast::Ident?
78 read_embedded_ident: bool,
81 impl<'a> Reader for StringReader<'a> {
82 fn is_eof(&self) -> bool { self.curr.is_none() }
83 /// Return the next token. EFFECT: advances the string_reader.
84 fn next_token(&mut self) -> TokenAndSpan {
85 let ret_val = TokenAndSpan {
86 tok: replace(&mut self.peek_tok, token::Underscore),
92 fn fatal(&self, m: &str) -> ! {
93 self.fatal_span(self.peek_span, m)
95 fn err(&self, m: &str) {
96 self.err_span(self.peek_span, m)
98 fn peek(&self) -> TokenAndSpan {
99 // FIXME(pcwalton): Bad copy!
101 tok: self.peek_tok.clone(),
107 impl<'a> Reader for TtReader<'a> {
108 fn is_eof(&self) -> bool {
109 self.cur_tok == token::Eof
111 fn next_token(&mut self) -> TokenAndSpan {
112 let r = tt_next_token(self);
113 debug!("TtReader: r={}", r);
116 fn fatal(&self, m: &str) -> ! {
117 self.sp_diag.span_fatal(self.cur_span, m);
119 fn err(&self, m: &str) {
120 self.sp_diag.span_err(self.cur_span, m);
122 fn peek(&self) -> TokenAndSpan {
124 tok: self.cur_tok.clone(),
130 // FIXME (Issue #16472): This function should go away after
131 // ToToken impls are revised to go directly to token-trees.
132 pub fn make_reader_with_embedded_idents<'b>(span_diagnostic: &'b SpanHandler,
133 filemap: Rc<codemap::FileMap>)
134 -> StringReader<'b> {
135 let mut sr = StringReader::new_raw(span_diagnostic, filemap);
136 sr.read_embedded_ident = true;
141 impl<'a> StringReader<'a> {
142 /// For comments.rs, which hackily pokes into pos and curr
143 pub fn new_raw<'b>(span_diagnostic: &'b SpanHandler,
144 filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
145 let mut sr = StringReader {
146 span_diagnostic: span_diagnostic,
147 pos: filemap.start_pos,
148 last_pos: filemap.start_pos,
152 /* dummy values; not read */
153 peek_tok: token::Eof,
154 peek_span: codemap::DUMMY_SP,
155 read_embedded_ident: false,
161 pub fn new<'b>(span_diagnostic: &'b SpanHandler,
162 filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
163 let mut sr = StringReader::new_raw(span_diagnostic, filemap);
168 pub fn curr_is(&self, c: char) -> bool {
172 /// Report a fatal lexical error with a given span.
173 pub fn fatal_span(&self, sp: Span, m: &str) -> ! {
174 self.span_diagnostic.span_fatal(sp, m)
177 /// Report a lexical error with a given span.
178 pub fn err_span(&self, sp: Span, m: &str) {
179 self.span_diagnostic.span_err(sp, m)
182 /// Report a fatal error spanning [`from_pos`, `to_pos`).
183 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
184 self.fatal_span(codemap::mk_sp(from_pos, to_pos), m)
187 /// Report a lexical error spanning [`from_pos`, `to_pos`).
188 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
189 self.err_span(codemap::mk_sp(from_pos, to_pos), m)
192 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
193 /// escaped character to the error message
194 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> ! {
195 let mut m = m.to_string();
197 for c in c.escape_default() { m.push(c) }
198 self.fatal_span_(from_pos, to_pos, m[]);
201 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
202 /// escaped character to the error message
203 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
204 let mut m = m.to_string();
206 for c in c.escape_default() { m.push(c) }
207 self.err_span_(from_pos, to_pos, m[]);
210 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
211 /// offending string to the error message
212 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> ! {
214 let from = self.byte_offset(from_pos).to_uint();
215 let to = self.byte_offset(to_pos).to_uint();
216 m.push_str(self.filemap.src[from..to]);
217 self.fatal_span_(from_pos, to_pos, m[]);
220 /// Advance peek_tok and peek_span to refer to the next token, and
221 /// possibly update the interner.
222 fn advance_token(&mut self) {
223 match self.scan_whitespace_or_comment() {
225 self.peek_span = comment.sp;
226 self.peek_tok = comment.tok;
230 self.peek_tok = token::Eof;
232 let start_bytepos = self.last_pos;
233 self.peek_tok = self.next_token_inner();
234 self.peek_span = codemap::mk_sp(start_bytepos,
241 fn byte_offset(&self, pos: BytePos) -> BytePos {
242 (pos - self.filemap.start_pos)
245 /// Calls `f` with a string slice of the source text spanning from `start`
246 /// up to but excluding `self.last_pos`, meaning the slice does not include
247 /// the character `self.curr`.
248 pub fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T where
249 F: FnOnce(&str) -> T,
251 self.with_str_from_to(start, self.last_pos, f)
254 /// Create a Name from a given offset to the current offset, each
255 /// adjusted 1 towards each other (assumes that on either side there is a
256 /// single-byte delimiter).
257 pub fn name_from(&self, start: BytePos) -> ast::Name {
258 debug!("taking an ident from {} to {}", start, self.last_pos);
259 self.with_str_from(start, token::intern)
262 /// As name_from, with an explicit endpoint.
263 pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
264 debug!("taking an ident from {} to {}", start, end);
265 self.with_str_from_to(start, end, token::intern)
268 /// Calls `f` with a string slice of the source text spanning from `start`
269 /// up to but excluding `end`.
270 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T where
271 F: FnOnce(&str) -> T,
273 f(self.filemap.src.slice(
274 self.byte_offset(start).to_uint(),
275 self.byte_offset(end).to_uint()))
278 /// Converts CRLF to LF in the given string, raising an error on bare CR.
279 fn translate_crlf<'b>(&self, start: BytePos,
280 s: &'b str, errmsg: &'b str) -> str::CowString<'b> {
283 let str::CharRange { ch, next } = s.char_range_at(i);
285 if next < s.len() && s.char_at(next) == '\n' {
286 return translate_crlf_(self, start, s, errmsg, i).into_cow();
288 let pos = start + BytePos(i as u32);
289 let end_pos = start + BytePos(next as u32);
290 self.err_span_(pos, end_pos, errmsg);
296 fn translate_crlf_(rdr: &StringReader, start: BytePos,
297 s: &str, errmsg: &str, mut i: uint) -> String {
298 let mut buf = String::with_capacity(s.len());
301 let str::CharRange { ch, next } = s.char_range_at(i);
303 if j < i { buf.push_str(s[j..i]); }
305 if next >= s.len() || s.char_at(next) != '\n' {
306 let pos = start + BytePos(i as u32);
307 let end_pos = start + BytePos(next as u32);
308 rdr.err_span_(pos, end_pos, errmsg);
313 if j < s.len() { buf.push_str(s[j..]); }
319 /// Advance the StringReader by one character. If a newline is
320 /// discovered, add it to the FileMap's list of line start offsets.
321 pub fn bump(&mut self) {
322 self.last_pos = self.pos;
323 let current_byte_offset = self.byte_offset(self.pos).to_uint();
324 if current_byte_offset < self.filemap.src.len() {
325 assert!(self.curr.is_some());
326 let last_char = self.curr.unwrap();
327 let next = self.filemap
329 .char_range_at(current_byte_offset);
330 let byte_offset_diff = next.next - current_byte_offset;
331 self.pos = self.pos + Pos::from_uint(byte_offset_diff);
332 self.curr = Some(next.ch);
333 self.col = self.col + CharPos(1u);
334 if last_char == '\n' {
335 self.filemap.next_line(self.last_pos);
336 self.col = CharPos(0u);
339 if byte_offset_diff > 1 {
340 self.filemap.record_multibyte_char(self.last_pos, byte_offset_diff);
347 pub fn nextch(&self) -> Option<char> {
348 let offset = self.byte_offset(self.pos).to_uint();
349 if offset < self.filemap.src.len() {
350 Some(self.filemap.src.char_at(offset))
356 pub fn nextch_is(&self, c: char) -> bool {
357 self.nextch() == Some(c)
360 pub fn nextnextch(&self) -> Option<char> {
361 let offset = self.byte_offset(self.pos).to_uint();
362 let s = self.filemap.src.as_slice();
363 if offset >= s.len() { return None }
364 let str::CharRange { next, .. } = s.char_range_at(offset);
366 Some(s.char_at(next))
372 pub fn nextnextch_is(&self, c: char) -> bool {
373 self.nextnextch() == Some(c)
376 /// Eats <XID_start><XID_continue>*, if possible.
377 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
378 if !ident_start(self.curr) {
381 let start = self.last_pos;
382 while ident_continue(self.curr) {
386 self.with_str_from(start, |string| {
390 Some(token::intern(string))
395 /// PRECONDITION: self.curr is not whitespace
396 /// Eats any kind of comment.
397 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
400 if c.is_whitespace() {
401 self.span_diagnostic.span_err(codemap::mk_sp(self.last_pos, self.last_pos),
402 "called consume_any_line_comment, but there was whitespace");
408 if self.curr_is('/') {
409 match self.nextch() {
413 // line comments starting with "///" or "//!" are doc-comments
414 if self.curr_is('/') || self.curr_is('!') {
415 let start_bpos = self.pos - BytePos(3);
416 while !self.is_eof() {
417 match self.curr.unwrap() {
420 if self.nextch_is('\n') {
424 self.err_span_(self.last_pos, self.pos,
425 "bare CR not allowed in doc-comment");
432 return self.with_str_from(start_bpos, |string| {
433 // but comments with only more "/"s are not
434 let tok = if is_doc_comment(string) {
435 token::DocComment(token::intern(string))
440 return Some(TokenAndSpan{
442 sp: codemap::mk_sp(start_bpos, self.last_pos)
446 let start_bpos = self.last_pos - BytePos(2);
447 while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
448 return Some(TokenAndSpan {
450 sp: codemap::mk_sp(start_bpos, self.last_pos)
455 self.bump(); self.bump();
456 self.scan_block_comment()
460 } else if self.curr_is('#') {
461 if self.nextch_is('!') {
463 // Parse an inner attribute.
464 if self.nextnextch_is('[') {
468 // I guess this is the only way to figure out if
469 // we're at the beginning of the file...
470 let cmap = CodeMap::new();
471 cmap.files.borrow_mut().push(self.filemap.clone());
472 let loc = cmap.lookup_char_pos_adj(self.last_pos);
473 debug!("Skipping a shebang");
474 if loc.line == 1u && loc.col == CharPos(0u) {
475 // FIXME: Add shebang "token", return it
476 let start = self.last_pos;
477 while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
478 return Some(TokenAndSpan {
479 tok: token::Shebang(self.name_from(start)),
480 sp: codemap::mk_sp(start, self.last_pos)
490 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
492 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
493 match self.curr.unwrap_or('\0') {
494 // # to handle shebang at start of file -- this is the entry point
495 // for skipping over all "junk"
497 let c = self.scan_comment();
498 debug!("scanning a comment {}", c);
501 c if is_whitespace(Some(c)) => {
502 let start_bpos = self.last_pos;
503 while is_whitespace(self.curr) { self.bump(); }
504 let c = Some(TokenAndSpan {
505 tok: token::Whitespace,
506 sp: codemap::mk_sp(start_bpos, self.last_pos)
508 debug!("scanning whitespace: {}", c);
515 /// Might return a sugared-doc-attr
516 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
517 // block comments starting with "/**" or "/*!" are doc-comments
518 let is_doc_comment = self.curr_is('*') || self.curr_is('!');
519 let start_bpos = self.last_pos - BytePos(2);
521 let mut level: int = 1;
522 let mut has_cr = false;
525 let msg = if is_doc_comment {
526 "unterminated block doc-comment"
528 "unterminated block comment"
530 let last_bpos = self.last_pos;
531 self.fatal_span_(start_bpos, last_bpos, msg);
533 let n = self.curr.unwrap();
535 '/' if self.nextch_is('*') => {
539 '*' if self.nextch_is('/') => {
551 self.with_str_from(start_bpos, |string| {
552 // but comments with only "*"s between two "/"s are not
553 let tok = if is_block_doc_comment(string) {
554 let string = if has_cr {
555 self.translate_crlf(start_bpos, string,
556 "bare CR not allowed in block doc-comment")
557 } else { string.into_cow() };
558 token::DocComment(token::intern(string[]))
565 sp: codemap::mk_sp(start_bpos, self.last_pos)
570 // FIXME (Issue #16472): The scan_embedded_hygienic_ident function
571 // should go away after we revise the syntax::ext::quote::ToToken
572 // impls to go directly to token-trees instead of thing -> string
573 // -> token-trees. (The function is currently used to resolve
574 // Issues #15750 and #15962.)
576 // Since this function is only used for certain internal macros,
577 // and the functionality it provides is not exposed to end user
578 // programs, pnkfelix deliberately chose to write it in a way that
579 // favors rustc debugging effectiveness over runtime efficiency.
581 /// Scan through input of form \x00name_NNNNNN,ctxt_CCCCCCC\x00
582 /// whence: `NNNNNN` is a string of characters forming an integer
583 /// (the name) and `CCCCCCC` is a string of characters forming an
584 /// integer (the ctxt), separate by a comma and delimited by a
587 fn scan_embedded_hygienic_ident(&mut self) -> ast::Ident {
588 fn bump_expecting_char<'a,D:fmt::Show>(r: &mut StringReader<'a>,
593 Some(r_c) if r_c == c => r.bump(),
594 Some(r_c) => panic!("expected {}, hit {}, {}", described_c, r_c, whence),
595 None => panic!("expected {}, hit EOF, {}", described_c, whence),
599 let whence = "while scanning embedded hygienic ident";
601 // skip over the leading `\x00`
602 bump_expecting_char(self, '\x00', "nul-byte", whence);
604 // skip over the "name_"
605 for c in "name_".chars() {
606 bump_expecting_char(self, c, c, whence);
609 let start_bpos = self.last_pos;
612 // find the integer representing the name
613 self.scan_digits(base);
614 let encoded_name : u32 = self.with_str_from(start_bpos, |s| {
615 num::from_str_radix(s, 10).unwrap_or_else(|| {
616 panic!("expected digits representing a name, got `{}`, {}, range [{},{}]",
617 s, whence, start_bpos, self.last_pos);
622 bump_expecting_char(self, ',', "comma", whence);
624 // skip over the "ctxt_"
625 for c in "ctxt_".chars() {
626 bump_expecting_char(self, c, c, whence);
629 // find the integer representing the ctxt
630 let start_bpos = self.last_pos;
631 self.scan_digits(base);
632 let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| {
633 num::from_str_radix(s, 10).unwrap_or_else(|| {
634 panic!("expected digits representing a ctxt, got `{}`, {}", s, whence);
638 // skip over the `\x00`
639 bump_expecting_char(self, '\x00', "nul-byte", whence);
641 ast::Ident { name: ast::Name(encoded_name),
642 ctxt: encoded_ctxt, }
645 /// Scan through any digits (base `radix`) or underscores, and return how
646 /// many digits there were.
647 fn scan_digits(&mut self, radix: uint) -> uint {
651 if c == Some('_') { debug!("skipping a _"); self.bump(); continue; }
652 match c.and_then(|cc| cc.to_digit(radix)) {
654 debug!("{} in scan_digits", c);
663 /// Lex a LIT_INTEGER or a LIT_FLOAT
664 fn scan_number(&mut self, c: char) -> token::Lit {
667 let start_bpos = self.last_pos;
672 match self.curr.unwrap_or('\0') {
673 'b' => { self.bump(); base = 2; num_digits = self.scan_digits(2); }
674 'o' => { self.bump(); base = 8; num_digits = self.scan_digits(8); }
675 'x' => { self.bump(); base = 16; num_digits = self.scan_digits(16); }
676 '0'...'9' | '_' | '.' => {
677 num_digits = self.scan_digits(10) + 1;
681 return token::Integer(self.name_from(start_bpos));
684 } else if c.is_digit(10) {
685 num_digits = self.scan_digits(10) + 1;
691 self.err_span_(start_bpos, self.last_pos, "no valid digits found for number");
692 return token::Integer(token::intern("0"));
695 // might be a float, but don't be greedy if this is actually an
696 // integer literal followed by field/method access or a range pattern
697 // (`0..2` and `12.foo()`)
698 if self.curr_is('.') && !self.nextch_is('.') && !self.nextch().unwrap_or('\0')
700 // might have stuff after the ., and if it does, it needs to start
703 if self.curr.unwrap_or('\0').is_digit(10) {
704 self.scan_digits(10);
705 self.scan_float_exponent();
707 let last_pos = self.last_pos;
708 self.check_float_base(start_bpos, last_pos, base);
709 return token::Float(self.name_from(start_bpos));
711 // it might be a float if it has an exponent
712 if self.curr_is('e') || self.curr_is('E') {
713 self.scan_float_exponent();
714 let last_pos = self.last_pos;
715 self.check_float_base(start_bpos, last_pos, base);
716 return token::Float(self.name_from(start_bpos));
718 // but we certainly have an integer!
719 return token::Integer(self.name_from(start_bpos));
723 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
724 /// error if too many or too few digits are encountered.
725 fn scan_hex_digits(&mut self,
728 below_0x7f_only: bool)
730 debug!("scanning {} digits until {}", n_digits, delim);
731 let start_bpos = self.last_pos;
732 let mut accum_int = 0;
734 for _ in range(0, n_digits) {
736 let last_bpos = self.last_pos;
737 self.fatal_span_(start_bpos, last_bpos, "unterminated numeric character escape");
739 if self.curr_is(delim) {
740 let last_bpos = self.last_pos;
741 self.err_span_(start_bpos, last_bpos, "numeric character escape is too short");
744 let c = self.curr.unwrap_or('\x00');
746 accum_int += c.to_digit(16).unwrap_or_else(|| {
747 self.err_span_char(self.last_pos, self.pos,
748 "illegal character in numeric character escape", c);
754 if below_0x7f_only && accum_int >= 0x80 {
755 self.err_span_(start_bpos,
757 "this form of character escape may only be used \
758 with characters in the range [\\x00-\\x7f]");
761 match char::from_u32(accum_int) {
764 let last_bpos = self.last_pos;
765 self.err_span_(start_bpos, last_bpos, "illegal numeric character escape");
771 fn old_escape_warning(&mut self, sp: Span) {
773 .span_warn(sp, "\\U00ABCD12 and \\uABCD escapes are deprecated");
775 .span_help(sp, "use \\u{ABCD12} escapes instead");
778 /// Scan for a single (possibly escaped) byte or char
779 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
780 /// `start` is the position of `first_source_char`, which is already consumed.
782 /// Returns true if there was a valid char/byte, false otherwise.
783 fn scan_char_or_byte(&mut self, start: BytePos, first_source_char: char,
784 ascii_only: bool, delim: char) -> bool {
785 match first_source_char {
787 // '\X' for some X must be a character constant:
788 let escaped = self.curr;
789 let escaped_pos = self.last_pos;
792 None => {}, // EOF here is an error that will be checked later.
795 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
796 'x' => self.scan_byte_escape(delim, !ascii_only),
797 'u' if !ascii_only => {
798 if self.curr == Some('{') {
799 self.scan_unicode_escape(delim)
801 let res = self.scan_hex_digits(4u, delim, false);
802 let sp = codemap::mk_sp(escaped_pos, self.last_pos);
803 self.old_escape_warning(sp);
807 'U' if !ascii_only => {
808 let res = self.scan_hex_digits(8u, delim, false);
809 let sp = codemap::mk_sp(escaped_pos, self.last_pos);
810 self.old_escape_warning(sp);
813 '\n' if delim == '"' => {
814 self.consume_whitespace();
817 '\r' if delim == '"' && self.curr_is('\n') => {
818 self.consume_whitespace();
822 let last_pos = self.last_pos;
824 escaped_pos, last_pos,
825 if ascii_only { "unknown byte escape" }
826 else { "unknown character escape" },
829 let sp = codemap::mk_sp(escaped_pos, last_pos);
830 self.span_diagnostic.span_help(
832 "this is an isolated carriage return; consider checking \
833 your editor and version control settings")
841 '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
842 let last_pos = self.last_pos;
845 if ascii_only { "byte constant must be escaped" }
846 else { "character constant must be escaped" },
851 if self.curr_is('\n') {
855 self.err_span_(start, self.last_pos,
856 "bare CR not allowed in string, use \\r instead");
860 _ => if ascii_only && first_source_char > '\x7F' {
861 let last_pos = self.last_pos;
864 "byte constant must be ASCII. \
865 Use a \\xHH escape for a non-ASCII byte", first_source_char);
872 /// Scan over a \u{...} escape
874 /// At this point, we have already seen the \ and the u, the { is the current character. We
875 /// will read at least one digit, and up to 6, and pass over the }.
876 fn scan_unicode_escape(&mut self, delim: char) -> bool {
877 self.bump(); // past the {
878 let start_bpos = self.last_pos;
879 let mut count: uint = 0;
880 let mut accum_int = 0;
882 while !self.curr_is('}') && count <= 6 {
883 let c = match self.curr {
886 self.fatal_span_(start_bpos, self.last_pos,
887 "unterminated unicode escape (found EOF)");
891 accum_int += c.to_digit(16).unwrap_or_else(|| {
893 self.fatal_span_(self.last_pos, self.pos,
894 "unterminated unicode escape (needed a `}`)");
896 self.fatal_span_char(self.last_pos, self.pos,
897 "illegal character in unicode escape", c);
905 self.fatal_span_(start_bpos, self.last_pos,
906 "overlong unicode escape (can have at most 6 hex digits)");
909 self.bump(); // past the ending }
911 let mut valid = count >= 1 && count <= 6;
912 if char::from_u32(accum_int).is_none() {
917 self.fatal_span_(start_bpos, self.last_pos, "illegal unicode character escape");
922 /// Scan over a float exponent.
923 fn scan_float_exponent(&mut self) {
924 if self.curr_is('e') || self.curr_is('E') {
926 if self.curr_is('-') || self.curr_is('+') {
929 if self.scan_digits(10) == 0 {
930 self.err_span_(self.last_pos, self.pos, "expected at least one digit in exponent")
935 /// Check that a base is valid for a floating literal, emitting a nice
936 /// error if it isn't.
937 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: uint) {
939 16u => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \
941 8u => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"),
942 2u => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"),
947 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
949 if self.curr_is('=') {
951 return token::BinOpEq(op);
953 return token::BinOp(op);
957 /// Return the next token from the string, advances the input past that
958 /// token, and updates the interner
959 fn next_token_inner(&mut self) -> token::Token {
961 if ident_start(c) && match (c.unwrap(), self.nextch(), self.nextnextch()) {
962 // Note: r as in r" or r#" is part of a raw string literal,
963 // b as in b' is part of a byte literal.
964 // They are not identifiers, and are handled further down.
965 ('r', Some('"'), _) | ('r', Some('#'), _) |
966 ('b', Some('"'), _) | ('b', Some('\''), _) |
967 ('b', Some('r'), Some('"')) | ('b', Some('r'), Some('#')) => false,
970 let start = self.last_pos;
971 while ident_continue(self.curr) {
975 return self.with_str_from(start, |string| {
979 // FIXME: perform NFKC normalization here. (Issue #2253)
980 if self.curr_is(':') && self.nextch_is(':') {
981 token::Ident(str_to_ident(string), token::ModName)
983 token::Ident(str_to_ident(string), token::Plain)
990 let num = self.scan_number(c.unwrap());
991 let suffix = self.scan_optional_raw_name();
992 debug!("next_token_inner: scanned number {}, {}", num, suffix);
993 return token::Literal(num, suffix)
996 if self.read_embedded_ident {
997 match (c.unwrap(), self.nextch(), self.nextnextch()) {
998 ('\x00', Some('n'), Some('a')) => {
999 let ast_ident = self.scan_embedded_hygienic_ident();
1000 return if self.curr_is(':') && self.nextch_is(':') {
1001 token::Ident(ast_ident, token::ModName)
1003 token::Ident(ast_ident, token::Plain)
1010 match c.expect("next_token_inner called at EOF") {
1012 ';' => { self.bump(); return token::Semi; }
1013 ',' => { self.bump(); return token::Comma; }
1016 return if self.curr_is('.') {
1018 if self.curr_is('.') {
1028 '(' => { self.bump(); return token::OpenDelim(token::Paren); }
1029 ')' => { self.bump(); return token::CloseDelim(token::Paren); }
1030 '{' => { self.bump(); return token::OpenDelim(token::Brace); }
1031 '}' => { self.bump(); return token::CloseDelim(token::Brace); }
1032 '[' => { self.bump(); return token::OpenDelim(token::Bracket); }
1033 ']' => { self.bump(); return token::CloseDelim(token::Bracket); }
1034 '@' => { self.bump(); return token::At; }
1035 '#' => { self.bump(); return token::Pound; }
1036 '~' => { self.bump(); return token::Tilde; }
1037 '?' => { self.bump(); return token::Question; }
1040 if self.curr_is(':') {
1042 return token::ModSep;
1044 return token::Colon;
1048 '$' => { self.bump(); return token::Dollar; }
1050 // Multi-byte tokens.
1053 if self.curr_is('=') {
1056 } else if self.curr_is('>') {
1058 return token::FatArrow;
1065 if self.curr_is('=') {
1068 } else { return token::Not; }
1072 match self.curr.unwrap_or('\x00') {
1073 '=' => { self.bump(); return token::Le; }
1074 '<' => { return self.binop(token::Shl); }
1077 match self.curr.unwrap_or('\x00') {
1078 _ => { return token::LArrow; }
1081 _ => { return token::Lt; }
1086 match self.curr.unwrap_or('\x00') {
1087 '=' => { self.bump(); return token::Ge; }
1088 '>' => { return self.binop(token::Shr); }
1089 _ => { return token::Gt; }
1093 // Either a character constant 'a' OR a lifetime name 'abc
1095 let start = self.last_pos;
1097 // the eof will be picked up by the final `'` check below
1098 let c2 = self.curr.unwrap_or('\x00');
1101 // If the character is an ident start not followed by another single
1102 // quote, then this is a lifetime name:
1103 if ident_start(Some(c2)) && !self.curr_is('\'') {
1104 while ident_continue(self.curr) {
1108 // Include the leading `'` in the real identifier, for macro
1109 // expansion purposes. See #12512 for the gory details of why
1110 // this is necessary.
1111 let ident = self.with_str_from(start, |lifetime_name| {
1112 str_to_ident(format!("'{}", lifetime_name)[])
1115 // Conjure up a "keyword checking ident" to make sure that
1116 // the lifetime name is not a keyword.
1117 let keyword_checking_ident =
1118 self.with_str_from(start, |lifetime_name| {
1119 str_to_ident(lifetime_name)
1121 let keyword_checking_token =
1122 &token::Ident(keyword_checking_ident, token::Plain);
1123 let last_bpos = self.last_pos;
1124 if keyword_checking_token.is_keyword(token::keywords::Self) {
1125 self.err_span_(start,
1127 "invalid lifetime name: 'self \
1128 is no longer a special lifetime");
1129 } else if keyword_checking_token.is_any_keyword() &&
1130 !keyword_checking_token.is_keyword(token::keywords::Static)
1132 self.err_span_(start,
1134 "invalid lifetime name");
1136 return token::Lifetime(ident);
1139 // Otherwise it is a character constant:
1140 let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ false, '\'');
1141 if !self.curr_is('\'') {
1142 let last_bpos = self.last_pos;
1143 self.fatal_span_verbose(
1144 // Byte offsetting here is okay because the
1145 // character before position `start` is an
1146 // ascii single quote.
1147 start - BytePos(1), last_bpos,
1148 "unterminated character constant".to_string());
1150 let id = if valid { self.name_from(start) } else { token::intern("0") };
1151 self.bump(); // advance curr past token
1152 let suffix = self.scan_optional_raw_name();
1153 return token::Literal(token::Char(id), suffix);
1157 let lit = match self.curr {
1158 Some('\'') => self.scan_byte(),
1159 Some('"') => self.scan_byte_string(),
1160 Some('r') => self.scan_raw_byte_string(),
1161 _ => unreachable!() // Should have been a token::Ident above.
1163 let suffix = self.scan_optional_raw_name();
1164 return token::Literal(lit, suffix);
1167 let start_bpos = self.last_pos;
1168 let mut valid = true;
1170 while !self.curr_is('"') {
1172 let last_bpos = self.last_pos;
1173 self.fatal_span_(start_bpos, last_bpos, "unterminated double quote string");
1176 let ch_start = self.last_pos;
1177 let ch = self.curr.unwrap();
1179 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ false, '"');
1181 // adjust for the ASCII " at the start of the literal
1182 let id = if valid { self.name_from(start_bpos + BytePos(1)) }
1183 else { token::intern("??") };
1185 let suffix = self.scan_optional_raw_name();
1186 return token::Literal(token::Str_(id), suffix);
1189 let start_bpos = self.last_pos;
1191 let mut hash_count = 0u;
1192 while self.curr_is('#') {
1198 let last_bpos = self.last_pos;
1199 self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
1200 } else if !self.curr_is('"') {
1201 let last_bpos = self.last_pos;
1202 let curr_char = self.curr.unwrap();
1203 self.fatal_span_char(start_bpos, last_bpos,
1204 "only `#` is allowed in raw string delimitation; \
1205 found illegal character",
1209 let content_start_bpos = self.last_pos;
1210 let mut content_end_bpos;
1211 let mut valid = true;
1214 let last_bpos = self.last_pos;
1215 self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
1217 //if self.curr_is('"') {
1218 //content_end_bpos = self.last_pos;
1219 //for _ in range(0, hash_count) {
1221 //if !self.curr_is('#') {
1223 let c = self.curr.unwrap();
1226 content_end_bpos = self.last_pos;
1227 for _ in range(0, hash_count) {
1229 if !self.curr_is('#') {
1236 if !self.nextch_is('\n') {
1237 let last_bpos = self.last_pos;
1238 self.err_span_(start_bpos, last_bpos, "bare CR not allowed in raw \
1239 string, use \\r instead");
1249 self.name_from_to(content_start_bpos, content_end_bpos)
1253 let suffix = self.scan_optional_raw_name();
1254 return token::Literal(token::StrRaw(id, hash_count), suffix);
1257 if self.nextch_is('>') {
1260 return token::RArrow;
1261 } else { return self.binop(token::Minus); }
1264 if self.nextch_is('&') {
1267 return token::AndAnd;
1268 } else { return self.binop(token::And); }
1271 match self.nextch() {
1272 Some('|') => { self.bump(); self.bump(); return token::OrOr; }
1273 _ => { return self.binop(token::Or); }
1276 '+' => { return self.binop(token::Plus); }
1277 '*' => { return self.binop(token::Star); }
1278 '/' => { return self.binop(token::Slash); }
1279 '^' => { return self.binop(token::Caret); }
1280 '%' => { return self.binop(token::Percent); }
1282 let last_bpos = self.last_pos;
1283 let bpos = self.pos;
1284 self.fatal_span_char(last_bpos, bpos, "unknown start of token", c);
1289 fn consume_whitespace(&mut self) {
1290 while is_whitespace(self.curr) && !self.is_eof() { self.bump(); }
1293 fn read_to_eol(&mut self) -> String {
1294 let mut val = String::new();
1295 while !self.curr_is('\n') && !self.is_eof() {
1296 val.push(self.curr.unwrap());
1299 if self.curr_is('\n') { self.bump(); }
1303 fn read_one_line_comment(&mut self) -> String {
1304 let val = self.read_to_eol();
1305 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/')
1306 || (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1310 fn consume_non_eol_whitespace(&mut self) {
1311 while is_whitespace(self.curr) && !self.curr_is('\n') && !self.is_eof() {
1316 fn peeking_at_comment(&self) -> bool {
1317 (self.curr_is('/') && self.nextch_is('/'))
1318 || (self.curr_is('/') && self.nextch_is('*'))
1319 // consider shebangs comments, but not inner attributes
1320 || (self.curr_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1323 fn scan_byte(&mut self) -> token::Lit {
1325 let start = self.last_pos;
1327 // the eof will be picked up by the final `'` check below
1328 let c2 = self.curr.unwrap_or('\x00');
1331 let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ true, '\'');
1332 if !self.curr_is('\'') {
1333 // Byte offsetting here is okay because the
1334 // character before position `start` are an
1335 // ascii single quote and ascii 'b'.
1336 let last_pos = self.last_pos;
1337 self.fatal_span_verbose(
1338 start - BytePos(2), last_pos,
1339 "unterminated byte constant".to_string());
1342 let id = if valid { self.name_from(start) } else { token::intern("??") };
1343 self.bump(); // advance curr past token
1344 return token::Byte(id);
1347 fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1348 self.scan_hex_digits(2, delim, below_0x7f_only)
1351 fn scan_byte_string(&mut self) -> token::Lit {
1353 let start = self.last_pos;
1354 let mut valid = true;
1356 while !self.curr_is('"') {
1358 let last_pos = self.last_pos;
1359 self.fatal_span_(start, last_pos,
1360 "unterminated double quote byte string");
1363 let ch_start = self.last_pos;
1364 let ch = self.curr.unwrap();
1366 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ true, '"');
1368 let id = if valid { self.name_from(start) } else { token::intern("??") };
1370 return token::Binary(id);
1373 fn scan_raw_byte_string(&mut self) -> token::Lit {
1374 let start_bpos = self.last_pos;
1376 let mut hash_count = 0u;
1377 while self.curr_is('#') {
1383 let last_pos = self.last_pos;
1384 self.fatal_span_(start_bpos, last_pos, "unterminated raw string");
1385 } else if !self.curr_is('"') {
1386 let last_pos = self.last_pos;
1387 let ch = self.curr.unwrap();
1388 self.fatal_span_char(start_bpos, last_pos,
1389 "only `#` is allowed in raw string delimitation; \
1390 found illegal character",
1394 let content_start_bpos = self.last_pos;
1395 let mut content_end_bpos;
1399 let last_pos = self.last_pos;
1400 self.fatal_span_(start_bpos, last_pos, "unterminated raw string")
1403 content_end_bpos = self.last_pos;
1404 for _ in range(0, hash_count) {
1406 if !self.curr_is('#') {
1412 Some(c) => if c > '\x7F' {
1413 let last_pos = self.last_pos;
1415 last_pos, last_pos, "raw byte string must be ASCII", c);
1421 return token::BinaryRaw(self.name_from_to(content_start_bpos,
1427 pub fn is_whitespace(c: Option<char>) -> bool {
1428 match c.unwrap_or('\x00') { // None can be null for now... it's not whitespace
1429 ' ' | '\n' | '\t' | '\r' => true,
1434 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1436 Some(c) => lo <= c && c <= hi,
1441 fn is_dec_digit(c: Option<char>) -> bool { return in_range(c, '0', '9'); }
1443 pub fn is_doc_comment(s: &str) -> bool {
1444 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/')
1445 || s.starts_with("//!");
1446 debug!("is `{}` a doc comment? {}", s, res);
1450 pub fn is_block_doc_comment(s: &str) -> bool {
1451 let res = (s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*')
1452 || s.starts_with("/*!");
1453 debug!("is `{}` a doc comment? {}", s, res);
1457 fn ident_start(c: Option<char>) -> bool {
1458 let c = match c { Some(c) => c, None => return false };
1460 (c >= 'a' && c <= 'z')
1461 || (c >= 'A' && c <= 'Z')
1463 || (c > '\x7f' && c.is_xid_start())
1466 fn ident_continue(c: Option<char>) -> bool {
1467 let c = match c { Some(c) => c, None => return false };
1469 (c >= 'a' && c <= 'z')
1470 || (c >= 'A' && c <= 'Z')
1471 || (c >= '0' && c <= '9')
1473 || (c > '\x7f' && c.is_xid_continue())
1480 use codemap::{BytePos, CodeMap, Span, NO_EXPANSION};
1483 use parse::token::{str_to_ident};
1486 fn mk_sh() -> diagnostic::SpanHandler {
1487 let emitter = diagnostic::EmitterWriter::new(box util::NullWriter, None);
1488 let handler = diagnostic::mk_handler(box emitter);
1489 diagnostic::mk_span_handler(handler, CodeMap::new())
1492 // open a string reader for the given string
1493 fn setup<'a>(span_handler: &'a diagnostic::SpanHandler,
1494 teststr: String) -> StringReader<'a> {
1495 let fm = span_handler.cm.new_filemap("zebra.rs".to_string(), teststr);
1496 StringReader::new(span_handler, fm)
1500 let span_handler = mk_sh();
1501 let mut string_reader = setup(&span_handler,
1502 "/* my source file */ \
1503 fn main() { println!(\"zebra\"); }\n".to_string());
1504 let id = str_to_ident("fn");
1505 assert_eq!(string_reader.next_token().tok, token::Comment);
1506 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1507 let tok1 = string_reader.next_token();
1508 let tok2 = TokenAndSpan{
1509 tok:token::Ident(id, token::Plain),
1510 sp:Span {lo:BytePos(21),hi:BytePos(23),expn_id: NO_EXPANSION}};
1511 assert_eq!(tok1,tok2);
1512 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1513 // the 'main' id is already read:
1514 assert_eq!(string_reader.last_pos.clone(), BytePos(28));
1515 // read another token:
1516 let tok3 = string_reader.next_token();
1517 let tok4 = TokenAndSpan{
1518 tok:token::Ident(str_to_ident("main"), token::Plain),
1519 sp:Span {lo:BytePos(24),hi:BytePos(28),expn_id: NO_EXPANSION}};
1520 assert_eq!(tok3,tok4);
1521 // the lparen is already read:
1522 assert_eq!(string_reader.last_pos.clone(), BytePos(29))
1525 // check that the given reader produces the desired stream
1526 // of tokens (stop checking after exhausting the expected vec)
1527 fn check_tokenization (mut string_reader: StringReader, expected: Vec<token::Token> ) {
1528 for expected_tok in expected.iter() {
1529 assert_eq!(&string_reader.next_token().tok, expected_tok);
1533 // make the identifier by looking up the string in the interner
1534 fn mk_ident(id: &str, style: token::IdentStyle) -> token::Token {
1535 token::Ident(str_to_ident(id), style)
1538 #[test] fn doublecolonparsing () {
1539 check_tokenization(setup(&mk_sh(), "a b".to_string()),
1540 vec![mk_ident("a", token::Plain),
1542 mk_ident("b", token::Plain)]);
1545 #[test] fn dcparsing_2 () {
1546 check_tokenization(setup(&mk_sh(), "a::b".to_string()),
1547 vec![mk_ident("a",token::ModName),
1549 mk_ident("b", token::Plain)]);
1552 #[test] fn dcparsing_3 () {
1553 check_tokenization(setup(&mk_sh(), "a ::b".to_string()),
1554 vec![mk_ident("a", token::Plain),
1557 mk_ident("b", token::Plain)]);
1560 #[test] fn dcparsing_4 () {
1561 check_tokenization(setup(&mk_sh(), "a:: b".to_string()),
1562 vec![mk_ident("a",token::ModName),
1565 mk_ident("b", token::Plain)]);
1568 #[test] fn character_a() {
1569 assert_eq!(setup(&mk_sh(), "'a'".to_string()).next_token().tok,
1570 token::Literal(token::Char(token::intern("a")), None));
1573 #[test] fn character_space() {
1574 assert_eq!(setup(&mk_sh(), "' '".to_string()).next_token().tok,
1575 token::Literal(token::Char(token::intern(" ")), None));
1578 #[test] fn character_escaped() {
1579 assert_eq!(setup(&mk_sh(), "'\\n'".to_string()).next_token().tok,
1580 token::Literal(token::Char(token::intern("\\n")), None));
1583 #[test] fn lifetime_name() {
1584 assert_eq!(setup(&mk_sh(), "'abc".to_string()).next_token().tok,
1585 token::Lifetime(token::str_to_ident("'abc")));
1588 #[test] fn raw_string() {
1589 assert_eq!(setup(&mk_sh(),
1590 "r###\"\"#a\\b\x00c\"\"###".to_string()).next_token()
1592 token::Literal(token::StrRaw(token::intern("\"#a\\b\x00c\""), 3), None));
1595 #[test] fn literal_suffixes() {
1597 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1598 assert_eq!(setup(&mk_sh(), format!("{}suffix", $input)).next_token().tok,
1599 token::Literal(token::$tok_type(token::intern($tok_contents)),
1600 Some(token::intern("suffix"))));
1601 // with a whitespace separator:
1602 assert_eq!(setup(&mk_sh(), format!("{} suffix", $input)).next_token().tok,
1603 token::Literal(token::$tok_type(token::intern($tok_contents)),
1608 test!("'a'", Char, "a");
1609 test!("b'a'", Byte, "a");
1610 test!("\"a\"", Str_, "a");
1611 test!("b\"a\"", Binary, "a");
1612 test!("1234", Integer, "1234");
1613 test!("0b101", Integer, "0b101");
1614 test!("0xABC", Integer, "0xABC");
1615 test!("1.0", Float, "1.0");
1616 test!("1.0e10", Float, "1.0e10");
1618 assert_eq!(setup(&mk_sh(), "2u".to_string()).next_token().tok,
1619 token::Literal(token::Integer(token::intern("2")),
1620 Some(token::intern("u"))));
1621 assert_eq!(setup(&mk_sh(), "r###\"raw\"###suffix".to_string()).next_token().tok,
1622 token::Literal(token::StrRaw(token::intern("raw"), 3),
1623 Some(token::intern("suffix"))));
1624 assert_eq!(setup(&mk_sh(), "br###\"raw\"###suffix".to_string()).next_token().tok,
1625 token::Literal(token::BinaryRaw(token::intern("raw"), 3),
1626 Some(token::intern("suffix"))));
1629 #[test] fn line_doc_comments() {
1630 assert!(is_doc_comment("///"));
1631 assert!(is_doc_comment("/// blah"));
1632 assert!(!is_doc_comment("////"));
1635 #[test] fn nested_block_comments() {
1637 let mut lexer = setup(&sh, "/* /* */ */'a'".to_string());
1638 match lexer.next_token().tok {
1639 token::Comment => { },
1640 _ => panic!("expected a comment!")
1642 assert_eq!(lexer.next_token().tok, token::Literal(token::Char(token::intern("a")), None));