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};
21 use std::mem::replace;
26 pub use ext::tt::transcribe::{TtReader, new_tt_reader};
31 fn is_eof(&self) -> bool;
32 fn next_token(&mut self) -> TokenAndSpan;
33 /// Report a fatal error with the current span.
34 fn fatal(&self, &str) -> !;
35 /// Report a non-fatal error with the current span.
37 fn peek(&self) -> TokenAndSpan;
38 /// Get a token the parser cares about.
39 fn real_token(&mut self) -> TokenAndSpan {
40 let mut t = self.next_token();
43 token::Whitespace | token::Comment | token::Shebang(_) => {
44 t = self.next_token();
53 #[deriving(Clone, PartialEq, Eq, Show)]
54 pub struct TokenAndSpan {
55 pub tok: token::Token,
59 pub struct StringReader<'a> {
60 pub span_diagnostic: &'a SpanHandler,
61 /// The absolute offset within the codemap of the next character to read
63 /// The absolute offset within the codemap of the last character read(curr)
64 pub last_pos: BytePos,
65 /// The column of the next character to read
67 /// The last character to be read
68 pub curr: Option<char>,
69 pub filemap: Rc<codemap::FileMap>,
71 pub peek_tok: token::Token,
74 // FIXME (Issue #16472): This field should go away after ToToken impls
75 // are revised to go directly to token-trees.
76 /// Is \x00<name>,<ctxt>\x00 is interpreted as encoded ast::Ident?
77 read_embedded_ident: bool,
80 impl<'a> Reader for StringReader<'a> {
81 fn is_eof(&self) -> bool { self.curr.is_none() }
82 /// Return the next token. EFFECT: advances the string_reader.
83 fn next_token(&mut self) -> TokenAndSpan {
84 let ret_val = TokenAndSpan {
85 tok: replace(&mut self.peek_tok, token::Underscore),
91 fn fatal(&self, m: &str) -> ! {
92 self.fatal_span(self.peek_span, m)
94 fn err(&self, m: &str) {
95 self.err_span(self.peek_span, m)
97 fn peek(&self) -> TokenAndSpan {
98 // FIXME(pcwalton): Bad copy!
100 tok: self.peek_tok.clone(),
106 impl<'a> Reader for TtReader<'a> {
107 fn is_eof(&self) -> bool {
108 self.cur_tok == token::Eof
110 fn next_token(&mut self) -> TokenAndSpan {
111 let r = tt_next_token(self);
112 debug!("TtReader: r={}", r);
115 fn fatal(&self, m: &str) -> ! {
116 self.sp_diag.span_fatal(self.cur_span, m);
118 fn err(&self, m: &str) {
119 self.sp_diag.span_err(self.cur_span, m);
121 fn peek(&self) -> TokenAndSpan {
123 tok: self.cur_tok.clone(),
129 // FIXME (Issue #16472): This function should go away after
130 // ToToken impls are revised to go directly to token-trees.
131 pub fn make_reader_with_embedded_idents<'b>(span_diagnostic: &'b SpanHandler,
132 filemap: Rc<codemap::FileMap>)
133 -> StringReader<'b> {
134 let mut sr = StringReader::new_raw(span_diagnostic, filemap);
135 sr.read_embedded_ident = true;
140 impl<'a> StringReader<'a> {
141 /// For comments.rs, which hackily pokes into pos and curr
142 pub fn new_raw<'b>(span_diagnostic: &'b SpanHandler,
143 filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
144 let mut sr = StringReader {
145 span_diagnostic: span_diagnostic,
146 pos: filemap.start_pos,
147 last_pos: filemap.start_pos,
151 /* dummy values; not read */
152 peek_tok: token::Eof,
153 peek_span: codemap::DUMMY_SP,
154 read_embedded_ident: false,
160 pub fn new<'b>(span_diagnostic: &'b SpanHandler,
161 filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
162 let mut sr = StringReader::new_raw(span_diagnostic, filemap);
167 pub fn curr_is(&self, c: char) -> bool {
171 /// Report a fatal lexical error with a given span.
172 pub fn fatal_span(&self, sp: Span, m: &str) -> ! {
173 self.span_diagnostic.span_fatal(sp, m)
176 /// Report a lexical error with a given span.
177 pub fn err_span(&self, sp: Span, m: &str) {
178 self.span_diagnostic.span_err(sp, m)
181 /// Report a fatal error spanning [`from_pos`, `to_pos`).
182 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
183 self.fatal_span(codemap::mk_sp(from_pos, to_pos), m)
186 /// Report a lexical error spanning [`from_pos`, `to_pos`).
187 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
188 self.err_span(codemap::mk_sp(from_pos, to_pos), m)
191 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
192 /// escaped character to the error message
193 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> ! {
194 let mut m = m.to_string();
196 for c in c.escape_default() { m.push(c) }
197 self.fatal_span_(from_pos, to_pos, m.as_slice());
200 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
201 /// escaped character to the error message
202 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
203 let mut m = m.to_string();
205 for c in c.escape_default() { m.push(c) }
206 self.err_span_(from_pos, to_pos, m.as_slice());
209 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
210 /// offending string to the error message
211 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> ! {
213 let from = self.byte_offset(from_pos).to_uint();
214 let to = self.byte_offset(to_pos).to_uint();
215 m.push_str(self.filemap.src.as_slice().slice(from, to));
216 self.fatal_span_(from_pos, to_pos, m.as_slice());
219 /// Advance peek_tok and peek_span to refer to the next token, and
220 /// possibly update the interner.
221 fn advance_token(&mut self) {
222 match self.scan_whitespace_or_comment() {
224 self.peek_span = comment.sp;
225 self.peek_tok = comment.tok;
229 self.peek_tok = token::Eof;
231 let start_bytepos = self.last_pos;
232 self.peek_tok = self.next_token_inner();
233 self.peek_span = codemap::mk_sp(start_bytepos,
240 fn byte_offset(&self, pos: BytePos) -> BytePos {
241 (pos - self.filemap.start_pos)
244 /// Calls `f` with a string slice of the source text spanning from `start`
245 /// up to but excluding `self.last_pos`, meaning the slice does not include
246 /// the character `self.curr`.
247 pub fn with_str_from<T>(&self, start: BytePos, f: |s: &str| -> T) -> T {
248 self.with_str_from_to(start, self.last_pos, f)
251 /// Create a Name from a given offset to the current offset, each
252 /// adjusted 1 towards each other (assumes that on either side there is a
253 /// single-byte delimiter).
254 pub fn name_from(&self, start: BytePos) -> ast::Name {
255 debug!("taking an ident from {} to {}", start, self.last_pos);
256 self.with_str_from(start, token::intern)
259 /// As name_from, with an explicit endpoint.
260 pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
261 debug!("taking an ident from {} to {}", start, end);
262 self.with_str_from_to(start, end, token::intern)
265 /// Calls `f` with a string slice of the source text spanning from `start`
266 /// up to but excluding `end`.
267 fn with_str_from_to<T>(&self, start: BytePos, end: BytePos, f: |s: &str| -> T) -> T {
268 f(self.filemap.src.as_slice().slice(
269 self.byte_offset(start).to_uint(),
270 self.byte_offset(end).to_uint()))
273 /// Converts CRLF to LF in the given string, raising an error on bare CR.
274 fn translate_crlf<'a>(&self, start: BytePos,
275 s: &'a str, errmsg: &'a str) -> str::CowString<'a> {
278 let str::CharRange { ch, next } = s.char_range_at(i);
280 if next < s.len() && s.char_at(next) == '\n' {
281 return translate_crlf_(self, start, s, errmsg, i).into_cow();
283 let pos = start + BytePos(i as u32);
284 let end_pos = start + BytePos(next as u32);
285 self.err_span_(pos, end_pos, errmsg);
291 fn translate_crlf_(rdr: &StringReader, start: BytePos,
292 s: &str, errmsg: &str, mut i: uint) -> String {
293 let mut buf = String::with_capacity(s.len());
296 let str::CharRange { ch, next } = s.char_range_at(i);
298 if j < i { buf.push_str(s.slice(j, i)); }
300 if next >= s.len() || s.char_at(next) != '\n' {
301 let pos = start + BytePos(i as u32);
302 let end_pos = start + BytePos(next as u32);
303 rdr.err_span_(pos, end_pos, errmsg);
308 if j < s.len() { buf.push_str(s.slice_from(j)); }
314 /// Advance the StringReader by one character. If a newline is
315 /// discovered, add it to the FileMap's list of line start offsets.
316 pub fn bump(&mut self) {
317 self.last_pos = self.pos;
318 let current_byte_offset = self.byte_offset(self.pos).to_uint();
319 if current_byte_offset < self.filemap.src.len() {
320 assert!(self.curr.is_some());
321 let last_char = self.curr.unwrap();
322 let next = self.filemap
325 .char_range_at(current_byte_offset);
326 let byte_offset_diff = next.next - current_byte_offset;
327 self.pos = self.pos + Pos::from_uint(byte_offset_diff);
328 self.curr = Some(next.ch);
329 self.col = self.col + CharPos(1u);
330 if last_char == '\n' {
331 self.filemap.next_line(self.last_pos);
332 self.col = CharPos(0u);
335 if byte_offset_diff > 1 {
336 self.filemap.record_multibyte_char(self.last_pos, byte_offset_diff);
343 pub fn nextch(&self) -> Option<char> {
344 let offset = self.byte_offset(self.pos).to_uint();
345 if offset < self.filemap.src.len() {
346 Some(self.filemap.src.as_slice().char_at(offset))
352 pub fn nextch_is(&self, c: char) -> bool {
353 self.nextch() == Some(c)
356 pub fn nextnextch(&self) -> Option<char> {
357 let offset = self.byte_offset(self.pos).to_uint();
358 let s = self.filemap.deref().src.as_slice();
359 if offset >= s.len() { return None }
360 let str::CharRange { next, .. } = s.char_range_at(offset);
362 Some(s.char_at(next))
368 pub fn nextnextch_is(&self, c: char) -> bool {
369 self.nextnextch() == Some(c)
372 /// Eats <XID_start><XID_continue>*, if possible.
373 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
374 if !ident_start(self.curr) {
377 let start = self.last_pos;
378 while ident_continue(self.curr) {
382 self.with_str_from(start, |string| {
386 Some(token::intern(string))
391 /// PRECONDITION: self.curr is not whitespace
392 /// Eats any kind of comment.
393 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
396 if c.is_whitespace() {
397 self.span_diagnostic.span_err(codemap::mk_sp(self.last_pos, self.last_pos),
398 "called consume_any_line_comment, but there was whitespace");
404 if self.curr_is('/') {
405 match self.nextch() {
409 // line comments starting with "///" or "//!" are doc-comments
410 if self.curr_is('/') || self.curr_is('!') {
411 let start_bpos = self.pos - BytePos(3);
412 while !self.is_eof() {
413 match self.curr.unwrap() {
416 if self.nextch_is('\n') {
420 self.err_span_(self.last_pos, self.pos,
421 "bare CR not allowed in doc-comment");
428 return self.with_str_from(start_bpos, |string| {
429 // but comments with only more "/"s are not
430 let tok = if is_doc_comment(string) {
431 token::DocComment(token::intern(string))
436 return Some(TokenAndSpan{
438 sp: codemap::mk_sp(start_bpos, self.last_pos)
442 let start_bpos = self.last_pos - BytePos(2);
443 while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
444 return Some(TokenAndSpan {
446 sp: codemap::mk_sp(start_bpos, self.last_pos)
451 self.bump(); self.bump();
452 self.scan_block_comment()
456 } else if self.curr_is('#') {
457 if self.nextch_is('!') {
459 // Parse an inner attribute.
460 if self.nextnextch_is('[') {
464 // I guess this is the only way to figure out if
465 // we're at the beginning of the file...
466 let cmap = CodeMap::new();
467 cmap.files.borrow_mut().push(self.filemap.clone());
468 let loc = cmap.lookup_char_pos_adj(self.last_pos);
469 debug!("Skipping a shebang");
470 if loc.line == 1u && loc.col == CharPos(0u) {
471 // FIXME: Add shebang "token", return it
472 let start = self.last_pos;
473 while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
474 return Some(TokenAndSpan {
475 tok: token::Shebang(self.name_from(start)),
476 sp: codemap::mk_sp(start, self.last_pos)
486 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
488 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
489 match self.curr.unwrap_or('\0') {
490 // # to handle shebang at start of file -- this is the entry point
491 // for skipping over all "junk"
493 let c = self.scan_comment();
494 debug!("scanning a comment {}", c);
497 c if is_whitespace(Some(c)) => {
498 let start_bpos = self.last_pos;
499 while is_whitespace(self.curr) { self.bump(); }
500 let c = Some(TokenAndSpan {
501 tok: token::Whitespace,
502 sp: codemap::mk_sp(start_bpos, self.last_pos)
504 debug!("scanning whitespace: {}", c);
511 /// Might return a sugared-doc-attr
512 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
513 // block comments starting with "/**" or "/*!" are doc-comments
514 let is_doc_comment = self.curr_is('*') || self.curr_is('!');
515 let start_bpos = self.last_pos - BytePos(2);
517 let mut level: int = 1;
518 let mut has_cr = false;
521 let msg = if is_doc_comment {
522 "unterminated block doc-comment"
524 "unterminated block comment"
526 let last_bpos = self.last_pos;
527 self.fatal_span_(start_bpos, last_bpos, msg);
529 let n = self.curr.unwrap();
531 '/' if self.nextch_is('*') => {
535 '*' if self.nextch_is('/') => {
547 self.with_str_from(start_bpos, |string| {
548 // but comments with only "*"s between two "/"s are not
549 let tok = if is_block_doc_comment(string) {
550 let string = if has_cr {
551 self.translate_crlf(start_bpos, string,
552 "bare CR not allowed in block doc-comment")
553 } else { string.into_cow() };
554 token::DocComment(token::intern(string.as_slice()))
561 sp: codemap::mk_sp(start_bpos, self.last_pos)
566 // FIXME (Issue #16472): The scan_embedded_hygienic_ident function
567 // should go away after we revise the syntax::ext::quote::ToToken
568 // impls to go directly to token-trees instead of thing -> string
569 // -> token-trees. (The function is currently used to resolve
570 // Issues #15750 and #15962.)
572 // Since this function is only used for certain internal macros,
573 // and the functionality it provides is not exposed to end user
574 // programs, pnkfelix deliberately chose to write it in a way that
575 // favors rustc debugging effectiveness over runtime efficiency.
577 /// Scan through input of form \x00name_NNNNNN,ctxt_CCCCCCC\x00
578 /// whence: `NNNNNN` is a string of characters forming an integer
579 /// (the name) and `CCCCCCC` is a string of characters forming an
580 /// integer (the ctxt), separate by a comma and delimited by a
583 fn scan_embedded_hygienic_ident(&mut self) -> ast::Ident {
584 fn bump_expecting_char<'a,D:fmt::Show>(r: &mut StringReader<'a>,
589 Some(r_c) if r_c == c => r.bump(),
590 Some(r_c) => panic!("expected {}, hit {}, {}", described_c, r_c, whence),
591 None => panic!("expected {}, hit EOF, {}", described_c, whence),
595 let whence = "while scanning embedded hygienic ident";
597 // skip over the leading `\x00`
598 bump_expecting_char(self, '\x00', "nul-byte", whence);
600 // skip over the "name_"
601 for c in "name_".chars() {
602 bump_expecting_char(self, c, c, whence);
605 let start_bpos = self.last_pos;
608 // find the integer representing the name
609 self.scan_digits(base);
610 let encoded_name : u32 = self.with_str_from(start_bpos, |s| {
611 num::from_str_radix(s, 10).unwrap_or_else(|| {
612 panic!("expected digits representing a name, got `{}`, {}, range [{},{}]",
613 s, whence, start_bpos, self.last_pos);
618 bump_expecting_char(self, ',', "comma", whence);
620 // skip over the "ctxt_"
621 for c in "ctxt_".chars() {
622 bump_expecting_char(self, c, c, whence);
625 // find the integer representing the ctxt
626 let start_bpos = self.last_pos;
627 self.scan_digits(base);
628 let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| {
629 num::from_str_radix(s, 10).unwrap_or_else(|| {
630 panic!("expected digits representing a ctxt, got `{}`, {}", s, whence);
634 // skip over the `\x00`
635 bump_expecting_char(self, '\x00', "nul-byte", whence);
637 ast::Ident { name: ast::Name(encoded_name),
638 ctxt: encoded_ctxt, }
641 /// Scan through any digits (base `radix`) or underscores, and return how
642 /// many digits there were.
643 fn scan_digits(&mut self, radix: uint) -> uint {
647 if c == Some('_') { debug!("skipping a _"); self.bump(); continue; }
648 match c.and_then(|cc| cc.to_digit(radix)) {
650 debug!("{} in scan_digits", c);
659 /// Lex a LIT_INTEGER or a LIT_FLOAT
660 fn scan_number(&mut self, c: char) -> token::Lit {
663 let start_bpos = self.last_pos;
668 match self.curr.unwrap_or('\0') {
669 'b' => { self.bump(); base = 2; num_digits = self.scan_digits(2); }
670 'o' => { self.bump(); base = 8; num_digits = self.scan_digits(8); }
671 'x' => { self.bump(); base = 16; num_digits = self.scan_digits(16); }
672 '0'...'9' | '_' | '.' => {
673 num_digits = self.scan_digits(10) + 1;
677 return token::Integer(self.name_from(start_bpos));
680 } else if c.is_digit(10) {
681 num_digits = self.scan_digits(10) + 1;
687 self.err_span_(start_bpos, self.last_pos, "no valid digits found for number");
688 return token::Integer(token::intern("0"));
691 // might be a float, but don't be greedy if this is actually an
692 // integer literal followed by field/method access or a range pattern
693 // (`0..2` and `12.foo()`)
694 if self.curr_is('.') && !self.nextch_is('.') && !self.nextch().unwrap_or('\0')
696 // might have stuff after the ., and if it does, it needs to start
699 if self.curr.unwrap_or('\0').is_digit(10) {
700 self.scan_digits(10);
701 self.scan_float_exponent();
703 let last_pos = self.last_pos;
704 self.check_float_base(start_bpos, last_pos, base);
705 return token::Float(self.name_from(start_bpos));
707 // it might be a float if it has an exponent
708 if self.curr_is('e') || self.curr_is('E') {
709 self.scan_float_exponent();
710 let last_pos = self.last_pos;
711 self.check_float_base(start_bpos, last_pos, base);
712 return token::Float(self.name_from(start_bpos));
714 // but we certainly have an integer!
715 return token::Integer(self.name_from(start_bpos));
719 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
720 /// error if too many or too few digits are encountered.
721 fn scan_hex_digits(&mut self,
724 below_0x7f_only: bool)
726 debug!("scanning {} digits until {}", n_digits, delim);
727 let start_bpos = self.last_pos;
728 let mut accum_int = 0;
730 for _ in range(0, n_digits) {
732 let last_bpos = self.last_pos;
733 self.fatal_span_(start_bpos, last_bpos, "unterminated numeric character escape");
735 if self.curr_is(delim) {
736 let last_bpos = self.last_pos;
737 self.err_span_(start_bpos, last_bpos, "numeric character escape is too short");
740 let c = self.curr.unwrap_or('\x00');
742 accum_int += c.to_digit(16).unwrap_or_else(|| {
743 self.err_span_char(self.last_pos, self.pos,
744 "illegal character in numeric character escape", c);
750 if below_0x7f_only && accum_int >= 0x80 {
751 self.err_span_(start_bpos,
753 "this form of character escape may only be used \
754 with characters in the range [\\x00-\\x7f]");
757 match char::from_u32(accum_int) {
760 let last_bpos = self.last_pos;
761 self.err_span_(start_bpos, last_bpos, "illegal numeric character escape");
769 fn old_escape_warning(&mut self, sp: Span) {
771 .span_warn(sp, "\\U00ABCD12 and \\uABCD escapes are deprecated");
773 .span_help(sp, "use \\u{ABCD12} escapes instead");
776 /// Scan for a single (possibly escaped) byte or char
777 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
778 /// `start` is the position of `first_source_char`, which is already consumed.
780 /// Returns true if there was a valid char/byte, false otherwise.
781 fn scan_char_or_byte(&mut self, start: BytePos, first_source_char: char,
782 ascii_only: bool, delim: char) -> bool {
783 match first_source_char {
785 // '\X' for some X must be a character constant:
786 let escaped = self.curr;
787 let escaped_pos = self.last_pos;
790 None => {}, // EOF here is an error that will be checked later.
793 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
794 'x' => self.scan_byte_escape(delim, !ascii_only),
795 'u' if !ascii_only => {
796 if self.curr == Some('{') {
797 self.scan_unicode_escape(delim)
799 let res = self.scan_hex_digits(4u, delim, false);
801 //let sp = codemap::mk_sp(escaped_pos, self.last_pos);
802 //self.old_escape_warning(sp);
806 'U' if !ascii_only => {
807 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).as_slice())
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));