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;
40 #[deriving(Clone, PartialEq, Eq, Show)]
41 pub struct TokenAndSpan {
42 pub tok: token::Token,
46 pub struct StringReader<'a> {
47 pub span_diagnostic: &'a SpanHandler,
48 /// The absolute offset within the codemap of the next character to read
50 /// The absolute offset within the codemap of the last character read(curr)
51 pub last_pos: BytePos,
52 /// The column of the next character to read
54 /// The last character to be read
55 pub curr: Option<char>,
56 pub filemap: Rc<codemap::FileMap>,
58 pub peek_tok: token::Token,
61 // FIXME (Issue #16472): This field should go away after ToToken impls
62 // are revised to go directly to token-trees.
63 /// Is \x00<name>,<ctxt>\x00 is interpreted as encoded ast::Ident?
64 read_embedded_ident: bool,
67 impl<'a> Reader for StringReader<'a> {
68 fn is_eof(&self) -> bool { self.curr.is_none() }
69 /// Return the next token. EFFECT: advances the string_reader.
70 fn next_token(&mut self) -> TokenAndSpan {
71 let ret_val = TokenAndSpan {
72 tok: replace(&mut self.peek_tok, token::UNDERSCORE),
78 fn fatal(&self, m: &str) -> ! {
79 self.fatal_span(self.peek_span, m)
81 fn err(&self, m: &str) {
82 self.err_span(self.peek_span, m)
84 fn peek(&self) -> TokenAndSpan {
85 // FIXME(pcwalton): Bad copy!
87 tok: self.peek_tok.clone(),
93 impl<'a> Reader for TtReader<'a> {
94 fn is_eof(&self) -> bool {
95 self.cur_tok == token::EOF
97 fn next_token(&mut self) -> TokenAndSpan {
98 let r = tt_next_token(self);
99 debug!("TtReader: r={}", r);
102 fn fatal(&self, m: &str) -> ! {
103 self.sp_diag.span_fatal(self.cur_span, m);
105 fn err(&self, m: &str) {
106 self.sp_diag.span_err(self.cur_span, m);
108 fn peek(&self) -> TokenAndSpan {
110 tok: self.cur_tok.clone(),
116 // FIXME (Issue #16472): This function should go away after
117 // ToToken impls are revised to go directly to token-trees.
118 pub fn make_reader_with_embedded_idents<'b>(span_diagnostic: &'b SpanHandler,
119 filemap: Rc<codemap::FileMap>)
120 -> StringReader<'b> {
121 let mut sr = StringReader::new_raw(span_diagnostic, filemap);
122 sr.read_embedded_ident = true;
127 impl<'a> StringReader<'a> {
128 /// For comments.rs, which hackily pokes into pos and curr
129 pub fn new_raw<'b>(span_diagnostic: &'b SpanHandler,
130 filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
131 let mut sr = StringReader {
132 span_diagnostic: span_diagnostic,
133 pos: filemap.start_pos,
134 last_pos: filemap.start_pos,
138 /* dummy values; not read */
139 peek_tok: token::EOF,
140 peek_span: codemap::DUMMY_SP,
141 read_embedded_ident: false,
147 pub fn new<'b>(span_diagnostic: &'b SpanHandler,
148 filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
149 let mut sr = StringReader::new_raw(span_diagnostic, filemap);
154 pub fn curr_is(&self, c: char) -> bool {
158 /// Report a fatal lexical error with a given span.
159 pub fn fatal_span(&self, sp: Span, m: &str) -> ! {
160 self.span_diagnostic.span_fatal(sp, m)
163 /// Report a lexical error with a given span.
164 pub fn err_span(&self, sp: Span, m: &str) {
165 self.span_diagnostic.span_err(sp, m)
168 /// Report a fatal error spanning [`from_pos`, `to_pos`).
169 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
170 self.fatal_span(codemap::mk_sp(from_pos, to_pos), m)
173 /// Report a lexical error spanning [`from_pos`, `to_pos`).
174 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
175 self.err_span(codemap::mk_sp(from_pos, to_pos), m)
178 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
179 /// escaped character to the error message
180 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> ! {
181 let mut m = m.to_string();
183 char::escape_default(c, |c| m.push_char(c));
184 self.fatal_span_(from_pos, to_pos, m.as_slice());
187 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
188 /// escaped character to the error message
189 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
190 let mut m = m.to_string();
192 char::escape_default(c, |c| m.push_char(c));
193 self.err_span_(from_pos, to_pos, m.as_slice());
196 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
197 /// offending string to the error message
198 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> ! {
200 let from = self.byte_offset(from_pos).to_uint();
201 let to = self.byte_offset(to_pos).to_uint();
202 m.push_str(self.filemap.src.as_slice().slice(from, to));
203 self.fatal_span_(from_pos, to_pos, m.as_slice());
206 /// Advance peek_tok and peek_span to refer to the next token, and
207 /// possibly update the interner.
208 fn advance_token(&mut self) {
209 match self.scan_whitespace_or_comment() {
211 self.peek_span = comment.sp;
212 self.peek_tok = comment.tok;
216 self.peek_tok = token::EOF;
218 let start_bytepos = self.last_pos;
219 self.peek_tok = self.next_token_inner();
220 self.peek_span = codemap::mk_sp(start_bytepos,
227 fn byte_offset(&self, pos: BytePos) -> BytePos {
228 (pos - self.filemap.start_pos)
231 /// Calls `f` with a string slice of the source text spanning from `start`
232 /// up to but excluding `self.last_pos`, meaning the slice does not include
233 /// the character `self.curr`.
234 pub fn with_str_from<T>(&self, start: BytePos, f: |s: &str| -> T) -> T {
235 self.with_str_from_to(start, self.last_pos, f)
238 /// Create a Name from a given offset to the current offset, each
239 /// adjusted 1 towards each other (assumes that on either side there is a
240 /// single-byte delimiter).
241 pub fn name_from(&self, start: BytePos) -> ast::Name {
242 debug!("taking an ident from {} to {}", start, self.last_pos);
243 self.with_str_from(start, token::intern)
246 /// As name_from, with an explicit endpoint.
247 pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
248 debug!("taking an ident from {} to {}", start, end);
249 self.with_str_from_to(start, end, token::intern)
252 /// Calls `f` with a string slice of the source text spanning from `start`
253 /// up to but excluding `end`.
254 fn with_str_from_to<T>(&self, start: BytePos, end: BytePos, f: |s: &str| -> T) -> T {
255 f(self.filemap.src.as_slice().slice(
256 self.byte_offset(start).to_uint(),
257 self.byte_offset(end).to_uint()))
260 /// Converts CRLF to LF in the given string, raising an error on bare CR.
261 fn translate_crlf<'a>(&self, start: BytePos,
262 s: &'a str, errmsg: &'a str) -> str::MaybeOwned<'a> {
265 let str::CharRange { ch, next } = s.char_range_at(i);
267 if next < s.len() && s.char_at(next) == '\n' {
268 return translate_crlf_(self, start, s, errmsg, i).into_maybe_owned();
270 let pos = start + BytePos(i as u32);
271 let end_pos = start + BytePos(next as u32);
272 self.err_span_(pos, end_pos, errmsg);
276 return s.into_maybe_owned();
278 fn translate_crlf_(rdr: &StringReader, start: BytePos,
279 s: &str, errmsg: &str, mut i: uint) -> String {
280 let mut buf = String::with_capacity(s.len());
283 let str::CharRange { ch, next } = s.char_range_at(i);
285 if j < i { buf.push_str(s.slice(j, i)); }
287 if next >= s.len() || s.char_at(next) != '\n' {
288 let pos = start + BytePos(i as u32);
289 let end_pos = start + BytePos(next as u32);
290 rdr.err_span_(pos, end_pos, errmsg);
295 if j < s.len() { buf.push_str(s.slice_from(j)); }
301 /// Advance the StringReader by one character. If a newline is
302 /// discovered, add it to the FileMap's list of line start offsets.
303 pub fn bump(&mut self) {
304 self.last_pos = self.pos;
305 let current_byte_offset = self.byte_offset(self.pos).to_uint();
306 if current_byte_offset < self.filemap.src.len() {
307 assert!(self.curr.is_some());
308 let last_char = self.curr.unwrap();
309 let next = self.filemap
312 .char_range_at(current_byte_offset);
313 let byte_offset_diff = next.next - current_byte_offset;
314 self.pos = self.pos + Pos::from_uint(byte_offset_diff);
315 self.curr = Some(next.ch);
316 self.col = self.col + CharPos(1u);
317 if last_char == '\n' {
318 self.filemap.next_line(self.last_pos);
319 self.col = CharPos(0u);
322 if byte_offset_diff > 1 {
323 self.filemap.record_multibyte_char(self.last_pos, byte_offset_diff);
330 pub fn nextch(&self) -> Option<char> {
331 let offset = self.byte_offset(self.pos).to_uint();
332 if offset < self.filemap.src.len() {
333 Some(self.filemap.src.as_slice().char_at(offset))
339 pub fn nextch_is(&self, c: char) -> bool {
340 self.nextch() == Some(c)
343 pub fn nextnextch(&self) -> Option<char> {
344 let offset = self.byte_offset(self.pos).to_uint();
345 let s = self.filemap.deref().src.as_slice();
346 if offset >= s.len() { return None }
347 let str::CharRange { next, .. } = s.char_range_at(offset);
349 Some(s.char_at(next))
355 pub fn nextnextch_is(&self, c: char) -> bool {
356 self.nextnextch() == Some(c)
359 /// PRECONDITION: self.curr is not whitespace
360 /// Eats any kind of comment.
361 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
364 if c.is_whitespace() {
365 self.span_diagnostic.span_err(codemap::mk_sp(self.last_pos, self.last_pos),
366 "called consume_any_line_comment, but there was whitespace");
372 if self.curr_is('/') {
373 match self.nextch() {
377 // line comments starting with "///" or "//!" are doc-comments
378 if self.curr_is('/') || self.curr_is('!') {
379 let start_bpos = self.pos - BytePos(3);
380 while !self.is_eof() {
381 match self.curr.unwrap() {
384 if self.nextch_is('\n') {
388 self.err_span_(self.last_pos, self.pos,
389 "bare CR not allowed in doc-comment");
396 return self.with_str_from(start_bpos, |string| {
397 // but comments with only more "/"s are not
398 let tok = if is_doc_comment(string) {
399 token::DOC_COMMENT(token::intern(string))
404 return Some(TokenAndSpan{
406 sp: codemap::mk_sp(start_bpos, self.last_pos)
410 let start_bpos = self.last_pos - BytePos(2);
411 while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
412 return Some(TokenAndSpan {
414 sp: codemap::mk_sp(start_bpos, self.last_pos)
419 self.bump(); self.bump();
420 self.scan_block_comment()
424 } else if self.curr_is('#') {
425 if self.nextch_is('!') {
427 // Parse an inner attribute.
428 if self.nextnextch_is('[') {
432 // I guess this is the only way to figure out if
433 // we're at the beginning of the file...
434 let cmap = CodeMap::new();
435 cmap.files.borrow_mut().push(self.filemap.clone());
436 let loc = cmap.lookup_char_pos_adj(self.last_pos);
437 debug!("Skipping a shebang");
438 if loc.line == 1u && loc.col == CharPos(0u) {
439 // FIXME: Add shebang "token", return it
440 let start = self.last_pos;
441 while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
442 return Some(TokenAndSpan {
443 tok: token::SHEBANG(self.name_from(start)),
444 sp: codemap::mk_sp(start, self.last_pos)
454 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
456 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
457 match self.curr.unwrap_or('\0') {
458 // # to handle shebang at start of file -- this is the entry point
459 // for skipping over all "junk"
461 let c = self.scan_comment();
462 debug!("scanning a comment {}", c);
465 c if is_whitespace(Some(c)) => {
466 let start_bpos = self.last_pos;
467 while is_whitespace(self.curr) { self.bump(); }
468 let c = Some(TokenAndSpan {
470 sp: codemap::mk_sp(start_bpos, self.last_pos)
472 debug!("scanning whitespace: {}", c);
479 /// Might return a sugared-doc-attr
480 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
481 // block comments starting with "/**" or "/*!" are doc-comments
482 let is_doc_comment = self.curr_is('*') || self.curr_is('!');
483 let start_bpos = self.last_pos - BytePos(2);
485 let mut level: int = 1;
486 let mut has_cr = false;
489 let msg = if is_doc_comment {
490 "unterminated block doc-comment"
492 "unterminated block comment"
494 let last_bpos = self.last_pos;
495 self.fatal_span_(start_bpos, last_bpos, msg);
497 let n = self.curr.unwrap();
499 '/' if self.nextch_is('*') => {
503 '*' if self.nextch_is('/') => {
515 self.with_str_from(start_bpos, |string| {
516 // but comments with only "*"s between two "/"s are not
517 let tok = if is_block_doc_comment(string) {
518 let string = if has_cr {
519 self.translate_crlf(start_bpos, string,
520 "bare CR not allowed in block doc-comment")
521 } else { string.into_maybe_owned() };
522 token::DOC_COMMENT(token::intern(string.as_slice()))
529 sp: codemap::mk_sp(start_bpos, self.last_pos)
534 // FIXME (Issue #16472): The scan_embedded_hygienic_ident function
535 // should go away after we revise the syntax::ext::quote::ToToken
536 // impls to go directly to token-trees instead of thing -> string
537 // -> token-trees. (The function is currently used to resolve
538 // Issues #15750 and #15962.)
540 // Since this function is only used for certain internal macros,
541 // and the functionality it provides is not exposed to end user
542 // programs, pnkfelix deliberately chose to write it in a way that
543 // favors rustc debugging effectiveness over runtime efficiency.
545 /// Scan through input of form \x00name_NNNNNN,ctxt_CCCCCCC\x00
546 /// whence: `NNNNNN` is a string of characters forming an integer
547 /// (the name) and `CCCCCCC` is a string of characters forming an
548 /// integer (the ctxt), separate by a comma and delimited by a
551 fn scan_embedded_hygienic_ident(&mut self) -> ast::Ident {
552 fn bump_expecting_char<'a,D:fmt::Show>(r: &mut StringReader<'a>,
557 Some(r_c) if r_c == c => r.bump(),
558 Some(r_c) => fail!("expected {}, hit {}, {}", described_c, r_c, whence),
559 None => fail!("expected {}, hit EOF, {}", described_c, whence),
563 let whence = "while scanning embedded hygienic ident";
565 // skip over the leading `\x00`
566 bump_expecting_char(self, '\x00', "nul-byte", whence);
568 // skip over the "name_"
569 for c in "name_".chars() {
570 bump_expecting_char(self, c, c, whence);
573 let start_bpos = self.last_pos;
576 // find the integer representing the name
577 self.scan_digits(base);
578 let encoded_name : u32 = self.with_str_from(start_bpos, |s| {
579 num::from_str_radix(s, 10).unwrap_or_else(|| {
580 fail!("expected digits representing a name, got `{}`, {}, range [{},{}]",
581 s, whence, start_bpos, self.last_pos);
586 bump_expecting_char(self, ',', "comma", whence);
588 // skip over the "ctxt_"
589 for c in "ctxt_".chars() {
590 bump_expecting_char(self, c, c, whence);
593 // find the integer representing the ctxt
594 let start_bpos = self.last_pos;
595 self.scan_digits(base);
596 let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| {
597 num::from_str_radix(s, 10).unwrap_or_else(|| {
598 fail!("expected digits representing a ctxt, got `{}`, {}", s, whence);
602 // skip over the `\x00`
603 bump_expecting_char(self, '\x00', "nul-byte", whence);
605 ast::Ident { name: ast::Name(encoded_name),
606 ctxt: encoded_ctxt, }
609 /// Scan through any digits (base `radix`) or underscores, and return how
610 /// many digits there were.
611 fn scan_digits(&mut self, radix: uint) -> uint {
615 if c == Some('_') { debug!("skipping a _"); self.bump(); continue; }
616 match c.and_then(|cc| char::to_digit(cc, radix)) {
618 debug!("{} in scan_digits", c);
627 /// Lex a LIT_INTEGER or a LIT_FLOAT
628 fn scan_number(&mut self, c: char) -> token::Token {
631 let start_bpos = self.last_pos;
636 match self.curr.unwrap_or('\0') {
637 'b' => { self.bump(); base = 2; num_digits = self.scan_digits(2); }
638 'o' => { self.bump(); base = 8; num_digits = self.scan_digits(8); }
639 'x' => { self.bump(); base = 16; num_digits = self.scan_digits(16); }
640 '0'...'9' | '_' | '.' => {
641 num_digits = self.scan_digits(10) + 1;
644 self.scan_int_suffix();
645 return token::LIT_INTEGER(self.name_from(start_bpos));
648 let last_pos = self.last_pos;
649 self.scan_float_suffix();
650 self.check_float_base(start_bpos, last_pos, base);
651 return token::LIT_FLOAT(self.name_from(start_bpos));
655 return token::LIT_INTEGER(self.name_from(start_bpos));
658 } else if c.is_digit_radix(10) {
659 num_digits = self.scan_digits(10) + 1;
665 self.err_span_(start_bpos, self.last_pos, "no valid digits found for number");
667 self.scan_int_suffix();
668 return token::LIT_INTEGER(token::intern("0"));
671 // might be a float, but don't be greedy if this is actually an
672 // integer literal followed by field/method access or a range pattern
673 // (`0..2` and `12.foo()`)
674 if self.curr_is('.') && !self.nextch_is('.') && !self.nextch().unwrap_or('\0')
676 // might have stuff after the ., and if it does, it needs to start
679 if self.curr.unwrap_or('\0').is_digit_radix(10) {
680 self.scan_digits(10);
681 self.scan_float_exponent();
682 self.scan_float_suffix();
684 let last_pos = self.last_pos;
685 self.check_float_base(start_bpos, last_pos, base);
686 return token::LIT_FLOAT(self.name_from(start_bpos));
687 } else if self.curr_is('f') {
688 // or it might be an integer literal suffixed as a float
689 self.scan_float_suffix();
690 let last_pos = self.last_pos;
691 self.check_float_base(start_bpos, last_pos, base);
692 return token::LIT_FLOAT(self.name_from(start_bpos));
694 // it might be a float if it has an exponent
695 if self.curr_is('e') || self.curr_is('E') {
696 self.scan_float_exponent();
697 self.scan_float_suffix();
698 let last_pos = self.last_pos;
699 self.check_float_base(start_bpos, last_pos, base);
700 return token::LIT_FLOAT(self.name_from(start_bpos));
702 // but we certainly have an integer!
703 self.scan_int_suffix();
704 return token::LIT_INTEGER(self.name_from(start_bpos));
708 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
709 /// error if too many or too few digits are encountered.
710 fn scan_hex_digits(&mut self, n_digits: uint, delim: char) -> bool {
711 debug!("scanning {} digits until {}", n_digits, delim);
712 let start_bpos = self.last_pos;
713 let mut accum_int = 0;
715 for _ in range(0, n_digits) {
717 let last_bpos = self.last_pos;
718 self.fatal_span_(start_bpos, last_bpos, "unterminated numeric character escape");
720 if self.curr_is(delim) {
721 let last_bpos = self.last_pos;
722 self.err_span_(start_bpos, last_bpos, "numeric character escape is too short");
725 let c = self.curr.unwrap_or('\x00');
727 accum_int += c.to_digit(16).unwrap_or_else(|| {
728 self.err_span_char(self.last_pos, self.pos,
729 "illegal character in numeric character escape", c);
735 match char::from_u32(accum_int) {
738 let last_bpos = self.last_pos;
739 self.err_span_(start_bpos, last_bpos, "illegal numeric character escape");
745 /// Scan for a single (possibly escaped) byte or char
746 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
747 /// `start` is the position of `first_source_char`, which is already consumed.
749 /// Returns true if there was a valid char/byte, false otherwise.
750 fn scan_char_or_byte(&mut self, start: BytePos, first_source_char: char,
751 ascii_only: bool, delim: char) -> bool {
752 match first_source_char {
754 // '\X' for some X must be a character constant:
755 let escaped = self.curr;
756 let escaped_pos = self.last_pos;
759 None => {}, // EOF here is an error that will be checked later.
762 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
763 'x' => self.scan_hex_digits(2u, delim),
764 'u' if !ascii_only => self.scan_hex_digits(4u, delim),
765 'U' if !ascii_only => self.scan_hex_digits(8u, delim),
766 '\n' if delim == '"' => {
767 self.consume_whitespace();
770 '\r' if delim == '"' && self.curr_is('\n') => {
771 self.consume_whitespace();
775 let last_pos = self.last_pos;
777 escaped_pos, last_pos,
778 if ascii_only { "unknown byte escape" }
779 else { "unknown character escape" },
787 '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
788 let last_pos = self.last_pos;
791 if ascii_only { "byte constant must be escaped" }
792 else { "character constant must be escaped" },
797 if self.curr_is('\n') {
801 self.err_span_(start, self.last_pos,
802 "bare CR not allowed in string, use \\r instead");
806 _ => if ascii_only && first_source_char > '\x7F' {
807 let last_pos = self.last_pos;
810 "byte constant must be ASCII. \
811 Use a \\xHH escape for a non-ASCII byte", first_source_char);
818 /// Scan over an int literal suffix.
819 fn scan_int_suffix(&mut self) {
821 Some('i') | Some('u') => {
824 if self.curr_is('8') {
826 } else if self.curr_is('1') {
827 if !self.nextch_is('6') {
828 self.err_span_(self.last_pos, self.pos,
829 "illegal int suffix");
831 self.bump(); self.bump();
833 } else if self.curr_is('3') {
834 if !self.nextch_is('2') {
835 self.err_span_(self.last_pos, self.pos,
836 "illegal int suffix");
838 self.bump(); self.bump();
840 } else if self.curr_is('6') {
841 if !self.nextch_is('4') {
842 self.err_span_(self.last_pos, self.pos,
843 "illegal int suffix");
845 self.bump(); self.bump();
853 /// Scan over a float literal suffix
854 fn scan_float_suffix(&mut self) {
855 if self.curr_is('f') {
856 if (self.nextch_is('3') && self.nextnextch_is('2'))
857 || (self.nextch_is('6') && self.nextnextch_is('4')) {
862 self.err_span_(self.last_pos, self.pos, "illegal float suffix");
867 /// Scan over a float exponent.
868 fn scan_float_exponent(&mut self) {
869 if self.curr_is('e') || self.curr_is('E') {
871 if self.curr_is('-') || self.curr_is('+') {
874 if self.scan_digits(10) == 0 {
875 self.err_span_(self.last_pos, self.pos, "expected at least one digit in exponent")
880 /// Check that a base is valid for a floating literal, emitting a nice
881 /// error if it isn't.
882 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: uint) {
884 16u => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \
886 8u => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"),
887 2u => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"),
892 fn binop(&mut self, op: token::BinOp) -> token::Token {
894 if self.curr_is('=') {
896 return token::BINOPEQ(op);
898 return token::BINOP(op);
902 /// Return the next token from the string, advances the input past that
903 /// token, and updates the interner
904 fn next_token_inner(&mut self) -> token::Token {
906 if ident_start(c) && match (c.unwrap(), self.nextch(), self.nextnextch()) {
907 // Note: r as in r" or r#" is part of a raw string literal,
908 // b as in b' is part of a byte literal.
909 // They are not identifiers, and are handled further down.
910 ('r', Some('"'), _) | ('r', Some('#'), _) |
911 ('b', Some('"'), _) | ('b', Some('\''), _) |
912 ('b', Some('r'), Some('"')) | ('b', Some('r'), Some('#')) => false,
915 let start = self.last_pos;
916 while ident_continue(self.curr) {
920 return self.with_str_from(start, |string| {
924 let is_mod_name = self.curr_is(':') && self.nextch_is(':');
926 // FIXME: perform NFKC normalization here. (Issue #2253)
927 token::IDENT(str_to_ident(string), is_mod_name)
933 return self.scan_number(c.unwrap());
936 if self.read_embedded_ident {
937 match (c.unwrap(), self.nextch(), self.nextnextch()) {
938 ('\x00', Some('n'), Some('a')) => {
939 let ast_ident = self.scan_embedded_hygienic_ident();
940 let is_mod_name = self.curr_is(':') && self.nextch_is(':');
941 return token::IDENT(ast_ident, is_mod_name);
947 match c.expect("next_token_inner called at EOF") {
949 ';' => { self.bump(); return token::SEMI; }
950 ',' => { self.bump(); return token::COMMA; }
953 return if self.curr_is('.') {
955 if self.curr_is('.') {
965 '(' => { self.bump(); return token::LPAREN; }
966 ')' => { self.bump(); return token::RPAREN; }
967 '{' => { self.bump(); return token::LBRACE; }
968 '}' => { self.bump(); return token::RBRACE; }
969 '[' => { self.bump(); return token::LBRACKET; }
970 ']' => { self.bump(); return token::RBRACKET; }
971 '@' => { self.bump(); return token::AT; }
972 '#' => { self.bump(); return token::POUND; }
973 '~' => { self.bump(); return token::TILDE; }
974 '?' => { self.bump(); return token::QUESTION; }
977 if self.curr_is(':') {
979 return token::MOD_SEP;
985 '$' => { self.bump(); return token::DOLLAR; }
987 // Multi-byte tokens.
990 if self.curr_is('=') {
993 } else if self.curr_is('>') {
995 return token::FAT_ARROW;
1002 if self.curr_is('=') {
1005 } else { return token::NOT; }
1009 match self.curr.unwrap_or('\x00') {
1010 '=' => { self.bump(); return token::LE; }
1011 '<' => { return self.binop(token::SHL); }
1014 match self.curr.unwrap_or('\x00') {
1015 _ => { return token::LARROW; }
1018 _ => { return token::LT; }
1023 match self.curr.unwrap_or('\x00') {
1024 '=' => { self.bump(); return token::GE; }
1025 '>' => { return self.binop(token::SHR); }
1026 _ => { return token::GT; }
1030 // Either a character constant 'a' OR a lifetime name 'abc
1032 let start = self.last_pos;
1034 // the eof will be picked up by the final `'` check below
1035 let c2 = self.curr.unwrap_or('\x00');
1038 // If the character is an ident start not followed by another single
1039 // quote, then this is a lifetime name:
1040 if ident_start(Some(c2)) && !self.curr_is('\'') {
1041 while ident_continue(self.curr) {
1045 // Include the leading `'` in the real identifier, for macro
1046 // expansion purposes. See #12512 for the gory details of why
1047 // this is necessary.
1048 let ident = self.with_str_from(start, |lifetime_name| {
1049 str_to_ident(format!("'{}", lifetime_name).as_slice())
1052 // Conjure up a "keyword checking ident" to make sure that
1053 // the lifetime name is not a keyword.
1054 let keyword_checking_ident =
1055 self.with_str_from(start, |lifetime_name| {
1056 str_to_ident(lifetime_name)
1058 let keyword_checking_token =
1059 &token::IDENT(keyword_checking_ident, false);
1060 let last_bpos = self.last_pos;
1061 if token::is_keyword(token::keywords::Self,
1062 keyword_checking_token) {
1063 self.err_span_(start,
1065 "invalid lifetime name: 'self \
1066 is no longer a special lifetime");
1067 } else if token::is_any_keyword(keyword_checking_token) &&
1068 !token::is_keyword(token::keywords::Static,
1069 keyword_checking_token) {
1070 self.err_span_(start,
1072 "invalid lifetime name");
1074 return token::LIFETIME(ident);
1077 // Otherwise it is a character constant:
1078 let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ false, '\'');
1079 if !self.curr_is('\'') {
1080 let last_bpos = self.last_pos;
1081 self.fatal_span_verbose(
1082 // Byte offsetting here is okay because the
1083 // character before position `start` is an
1084 // ascii single quote.
1085 start - BytePos(1), last_bpos,
1086 "unterminated character constant".to_string());
1088 let id = if valid { self.name_from(start) } else { token::intern("0") };
1089 self.bump(); // advance curr past token
1090 return token::LIT_CHAR(id);
1094 return match self.curr {
1095 Some('\'') => self.scan_byte(),
1096 Some('"') => self.scan_byte_string(),
1097 Some('r') => self.scan_raw_byte_string(),
1098 _ => unreachable!() // Should have been a token::IDENT above.
1103 let start_bpos = self.last_pos;
1104 let mut valid = true;
1106 while !self.curr_is('"') {
1108 let last_bpos = self.last_pos;
1109 self.fatal_span_(start_bpos, last_bpos, "unterminated double quote string");
1112 let ch_start = self.last_pos;
1113 let ch = self.curr.unwrap();
1115 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ false, '"');
1117 // adjust for the ASCII " at the start of the literal
1118 let id = if valid { self.name_from(start_bpos + BytePos(1)) }
1119 else { token::intern("??") };
1121 return token::LIT_STR(id);
1124 let start_bpos = self.last_pos;
1126 let mut hash_count = 0u;
1127 while self.curr_is('#') {
1133 let last_bpos = self.last_pos;
1134 self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
1135 } else if !self.curr_is('"') {
1136 let last_bpos = self.last_pos;
1137 let curr_char = self.curr.unwrap();
1138 self.fatal_span_char(start_bpos, last_bpos,
1139 "only `#` is allowed in raw string delimitation; \
1140 found illegal character",
1144 let content_start_bpos = self.last_pos;
1145 let mut content_end_bpos;
1146 let mut valid = true;
1149 let last_bpos = self.last_pos;
1150 self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
1152 //if self.curr_is('"') {
1153 //content_end_bpos = self.last_pos;
1154 //for _ in range(0, hash_count) {
1156 //if !self.curr_is('#') {
1158 let c = self.curr.unwrap();
1161 content_end_bpos = self.last_pos;
1162 for _ in range(0, hash_count) {
1164 if !self.curr_is('#') {
1171 if !self.nextch_is('\n') {
1172 let last_bpos = self.last_pos;
1173 self.err_span_(start_bpos, last_bpos, "bare CR not allowed in raw \
1174 string, use \\r instead");
1184 self.name_from_to(content_start_bpos, content_end_bpos)
1188 return token::LIT_STR_RAW(id, hash_count);
1191 if self.nextch_is('>') {
1194 return token::RARROW;
1195 } else { return self.binop(token::MINUS); }
1198 if self.nextch_is('&') {
1201 return token::ANDAND;
1202 } else { return self.binop(token::AND); }
1205 match self.nextch() {
1206 Some('|') => { self.bump(); self.bump(); return token::OROR; }
1207 _ => { return self.binop(token::OR); }
1210 '+' => { return self.binop(token::PLUS); }
1211 '*' => { return self.binop(token::STAR); }
1212 '/' => { return self.binop(token::SLASH); }
1213 '^' => { return self.binop(token::CARET); }
1214 '%' => { return self.binop(token::PERCENT); }
1216 let last_bpos = self.last_pos;
1217 let bpos = self.pos;
1218 self.fatal_span_char(last_bpos, bpos, "unknown start of token", c);
1223 fn consume_whitespace(&mut self) {
1224 while is_whitespace(self.curr) && !self.is_eof() { self.bump(); }
1227 fn read_to_eol(&mut self) -> String {
1228 let mut val = String::new();
1229 while !self.curr_is('\n') && !self.is_eof() {
1230 val.push_char(self.curr.unwrap());
1233 if self.curr_is('\n') { self.bump(); }
1237 fn read_one_line_comment(&mut self) -> String {
1238 let val = self.read_to_eol();
1239 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/')
1240 || (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1244 fn consume_non_eol_whitespace(&mut self) {
1245 while is_whitespace(self.curr) && !self.curr_is('\n') && !self.is_eof() {
1250 fn peeking_at_comment(&self) -> bool {
1251 (self.curr_is('/') && self.nextch_is('/'))
1252 || (self.curr_is('/') && self.nextch_is('*'))
1253 // consider shebangs comments, but not inner attributes
1254 || (self.curr_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1257 fn scan_byte(&mut self) -> token::Token {
1259 let start = self.last_pos;
1261 // the eof will be picked up by the final `'` check below
1262 let c2 = self.curr.unwrap_or('\x00');
1265 let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ true, '\'');
1266 if !self.curr_is('\'') {
1267 // Byte offsetting here is okay because the
1268 // character before position `start` are an
1269 // ascii single quote and ascii 'b'.
1270 let last_pos = self.last_pos;
1271 self.fatal_span_verbose(
1272 start - BytePos(2), last_pos,
1273 "unterminated byte constant".to_string());
1276 let id = if valid { self.name_from(start) } else { token::intern("??") };
1277 self.bump(); // advance curr past token
1278 return token::LIT_BYTE(id);
1281 fn scan_byte_string(&mut self) -> token::Token {
1283 let start = self.last_pos;
1284 let mut valid = true;
1286 while !self.curr_is('"') {
1288 let last_pos = self.last_pos;
1289 self.fatal_span_(start, last_pos,
1290 "unterminated double quote byte string");
1293 let ch_start = self.last_pos;
1294 let ch = self.curr.unwrap();
1296 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ true, '"');
1298 let id = if valid { self.name_from(start) } else { token::intern("??") };
1300 return token::LIT_BINARY(id);
1303 fn scan_raw_byte_string(&mut self) -> token::Token {
1304 let start_bpos = self.last_pos;
1306 let mut hash_count = 0u;
1307 while self.curr_is('#') {
1313 let last_pos = self.last_pos;
1314 self.fatal_span_(start_bpos, last_pos, "unterminated raw string");
1315 } else if !self.curr_is('"') {
1316 let last_pos = self.last_pos;
1317 let ch = self.curr.unwrap();
1318 self.fatal_span_char(start_bpos, last_pos,
1319 "only `#` is allowed in raw string delimitation; \
1320 found illegal character",
1324 let content_start_bpos = self.last_pos;
1325 let mut content_end_bpos;
1329 let last_pos = self.last_pos;
1330 self.fatal_span_(start_bpos, last_pos, "unterminated raw string")
1333 content_end_bpos = self.last_pos;
1334 for _ in range(0, hash_count) {
1336 if !self.curr_is('#') {
1342 Some(c) => if c > '\x7F' {
1343 let last_pos = self.last_pos;
1345 last_pos, last_pos, "raw byte string must be ASCII", c);
1351 return token::LIT_BINARY_RAW(self.name_from_to(content_start_bpos, content_end_bpos),
1356 pub fn is_whitespace(c: Option<char>) -> bool {
1357 match c.unwrap_or('\x00') { // None can be null for now... it's not whitespace
1358 ' ' | '\n' | '\t' | '\r' => true,
1363 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1365 Some(c) => lo <= c && c <= hi,
1370 fn is_dec_digit(c: Option<char>) -> bool { return in_range(c, '0', '9'); }
1372 pub fn is_doc_comment(s: &str) -> bool {
1373 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/')
1374 || s.starts_with("//!");
1375 debug!("is `{}` a doc comment? {}", s, res);
1379 pub fn is_block_doc_comment(s: &str) -> bool {
1380 let res = (s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*')
1381 || s.starts_with("/*!");
1382 debug!("is `{}` a doc comment? {}", s, res);
1386 fn ident_start(c: Option<char>) -> bool {
1387 let c = match c { Some(c) => c, None => return false };
1389 (c >= 'a' && c <= 'z')
1390 || (c >= 'A' && c <= 'Z')
1392 || (c > '\x7f' && char::is_XID_start(c))
1395 fn ident_continue(c: Option<char>) -> bool {
1396 let c = match c { Some(c) => c, None => return false };
1398 (c >= 'a' && c <= 'z')
1399 || (c >= 'A' && c <= 'Z')
1400 || (c >= '0' && c <= '9')
1402 || (c > '\x7f' && char::is_XID_continue(c))
1409 use codemap::{BytePos, CodeMap, Span, NO_EXPANSION};
1412 use parse::token::{str_to_ident};
1415 fn mk_sh() -> diagnostic::SpanHandler {
1416 let emitter = diagnostic::EmitterWriter::new(box util::NullWriter, None);
1417 let handler = diagnostic::mk_handler(box emitter);
1418 diagnostic::mk_span_handler(handler, CodeMap::new())
1421 // open a string reader for the given string
1422 fn setup<'a>(span_handler: &'a diagnostic::SpanHandler,
1423 teststr: String) -> StringReader<'a> {
1424 let fm = span_handler.cm.new_filemap("zebra.rs".to_string(), teststr);
1425 StringReader::new(span_handler, fm)
1429 let span_handler = mk_sh();
1430 let mut string_reader = setup(&span_handler,
1431 "/* my source file */ \
1432 fn main() { println!(\"zebra\"); }\n".to_string());
1433 let id = str_to_ident("fn");
1434 assert_eq!(string_reader.next_token().tok, token::COMMENT);
1435 assert_eq!(string_reader.next_token().tok, token::WS);
1436 let tok1 = string_reader.next_token();
1437 let tok2 = TokenAndSpan{
1438 tok:token::IDENT(id, false),
1439 sp:Span {lo:BytePos(21),hi:BytePos(23),expn_id: NO_EXPANSION}};
1440 assert_eq!(tok1,tok2);
1441 assert_eq!(string_reader.next_token().tok, token::WS);
1442 // the 'main' id is already read:
1443 assert_eq!(string_reader.last_pos.clone(), BytePos(28));
1444 // read another token:
1445 let tok3 = string_reader.next_token();
1446 let tok4 = TokenAndSpan{
1447 tok:token::IDENT(str_to_ident("main"), false),
1448 sp:Span {lo:BytePos(24),hi:BytePos(28),expn_id: NO_EXPANSION}};
1449 assert_eq!(tok3,tok4);
1450 // the lparen is already read:
1451 assert_eq!(string_reader.last_pos.clone(), BytePos(29))
1454 // check that the given reader produces the desired stream
1455 // of tokens (stop checking after exhausting the expected vec)
1456 fn check_tokenization (mut string_reader: StringReader, expected: Vec<token::Token> ) {
1457 for expected_tok in expected.iter() {
1458 assert_eq!(&string_reader.next_token().tok, expected_tok);
1462 // make the identifier by looking up the string in the interner
1463 fn mk_ident (id: &str, is_mod_name: bool) -> token::Token {
1464 token::IDENT (str_to_ident(id),is_mod_name)
1467 #[test] fn doublecolonparsing () {
1468 check_tokenization(setup(&mk_sh(), "a b".to_string()),
1469 vec!(mk_ident("a",false),
1471 mk_ident("b",false)));
1474 #[test] fn dcparsing_2 () {
1475 check_tokenization(setup(&mk_sh(), "a::b".to_string()),
1476 vec!(mk_ident("a",true),
1478 mk_ident("b",false)));
1481 #[test] fn dcparsing_3 () {
1482 check_tokenization(setup(&mk_sh(), "a ::b".to_string()),
1483 vec!(mk_ident("a",false),
1486 mk_ident("b",false)));
1489 #[test] fn dcparsing_4 () {
1490 check_tokenization(setup(&mk_sh(), "a:: b".to_string()),
1491 vec!(mk_ident("a",true),
1494 mk_ident("b",false)));
1497 #[test] fn character_a() {
1498 assert_eq!(setup(&mk_sh(), "'a'".to_string()).next_token().tok,
1499 token::LIT_CHAR(token::intern("a")));
1502 #[test] fn character_space() {
1503 assert_eq!(setup(&mk_sh(), "' '".to_string()).next_token().tok,
1504 token::LIT_CHAR(token::intern(" ")));
1507 #[test] fn character_escaped() {
1508 assert_eq!(setup(&mk_sh(), "'\\n'".to_string()).next_token().tok,
1509 token::LIT_CHAR(token::intern("\\n")));
1512 #[test] fn lifetime_name() {
1513 assert_eq!(setup(&mk_sh(), "'abc".to_string()).next_token().tok,
1514 token::LIFETIME(token::str_to_ident("'abc")));
1517 #[test] fn raw_string() {
1518 assert_eq!(setup(&mk_sh(),
1519 "r###\"\"#a\\b\x00c\"\"###".to_string()).next_token()
1521 token::LIT_STR_RAW(token::intern("\"#a\\b\x00c\""), 3));
1524 #[test] fn line_doc_comments() {
1525 assert!(is_doc_comment("///"));
1526 assert!(is_doc_comment("/// blah"));
1527 assert!(!is_doc_comment("////"));
1530 #[test] fn nested_block_comments() {
1532 let mut lexer = setup(&sh, "/* /* */ */'a'".to_string());
1533 match lexer.next_token().tok {
1534 token::COMMENT => { },
1535 _ => fail!("expected a comment!")
1537 assert_eq!(lexer.next_token().tok, token::LIT_CHAR(token::intern("a")));