1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use ast::{self, Ident};
12 use syntax_pos::{self, BytePos, CharPos, Pos, Span, NO_EXPANSION};
13 use codemap::{CodeMap, FilePathMapping};
14 use errors::{FatalError, DiagnosticBuilder};
15 use parse::{token, ParseSess};
17 use symbol::{Symbol, keywords};
18 use std_unicode::property::Pattern_White_Space;
22 use std::mem::replace;
29 #[derive(Clone, PartialEq, Eq, Debug)]
30 pub struct TokenAndSpan {
31 pub tok: token::Token,
35 impl Default for TokenAndSpan {
36 fn default() -> Self {
37 TokenAndSpan { tok: token::Underscore, sp: syntax_pos::DUMMY_SP }
41 pub struct StringReader<'a> {
42 pub sess: &'a ParseSess,
43 /// The absolute offset within the codemap of the next character to read
44 pub next_pos: BytePos,
45 /// The absolute offset within the codemap of the current character
47 /// The column of the next character to read
49 /// The current character (which has been read from self.pos)
51 pub filemap: Rc<syntax_pos::FileMap>,
52 /// If Some, stop reading the source at this position (inclusive).
53 pub terminator: Option<BytePos>,
54 /// Whether to record new-lines and multibyte chars in filemap.
55 /// This is only necessary the first time a filemap is lexed.
56 /// If part of a filemap is being re-lexed, this should be set to false.
57 pub save_new_lines_and_multibyte: bool,
59 pub peek_tok: token::Token,
61 pub fatal_errs: Vec<DiagnosticBuilder<'a>>,
62 // cache a direct reference to the source text, so that we don't have to
63 // retrieve it via `self.filemap.src.as_ref().unwrap()` all the time.
64 source_text: Rc<String>,
65 /// Stack of open delimiters and their spans. Used for error message.
68 open_braces: Vec<(token::DelimToken, Span)>,
71 fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
72 Span { lo: lo, hi: hi, ctxt: NO_EXPANSION }
75 impl<'a> StringReader<'a> {
76 fn next_token(&mut self) -> TokenAndSpan {
77 let res = self.try_next_token();
78 self.unwrap_or_abort(res)
80 fn unwrap_or_abort(&mut self, res: Result<TokenAndSpan, ()>) -> TokenAndSpan {
84 self.emit_fatal_errors();
89 fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> {
90 let mut t = self.try_next_token()?;
93 token::Whitespace | token::Comment | token::Shebang(_) => {
94 t = self.try_next_token()?;
99 self.token = t.tok.clone();
103 pub fn real_token(&mut self) -> TokenAndSpan {
104 let res = self.try_real_token();
105 self.unwrap_or_abort(res)
107 fn is_eof(&self) -> bool {
108 if self.ch.is_none() {
112 match self.terminator {
113 Some(t) => self.next_pos > t,
117 /// Return the next token. EFFECT: advances the string_reader.
118 pub fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> {
119 assert!(self.fatal_errs.is_empty());
120 let ret_val = TokenAndSpan {
121 tok: replace(&mut self.peek_tok, token::Underscore),
124 self.advance_token()?;
127 fn fatal(&self, m: &str) -> FatalError {
128 self.fatal_span(self.peek_span, m)
130 pub fn emit_fatal_errors(&mut self) {
131 for err in &mut self.fatal_errs {
134 self.fatal_errs.clear();
136 pub fn peek(&self) -> TokenAndSpan {
137 // FIXME(pcwalton): Bad copy!
139 tok: self.peek_tok.clone(),
145 impl<'a> StringReader<'a> {
146 /// For comments.rs, which hackily pokes into next_pos and ch
147 pub fn new_raw(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self {
148 let mut sr = StringReader::new_raw_internal(sess, filemap);
153 fn new_raw_internal(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self {
154 if filemap.src.is_none() {
155 sess.span_diagnostic.bug(&format!("Cannot lex filemap without source: {}",
159 let source_text = (*filemap.src.as_ref().unwrap()).clone();
163 next_pos: filemap.start_pos,
164 pos: filemap.start_pos,
169 save_new_lines_and_multibyte: true,
170 // dummy values; not read
171 peek_tok: token::Eof,
172 peek_span: syntax_pos::DUMMY_SP,
173 source_text: source_text,
174 fatal_errs: Vec::new(),
176 span: syntax_pos::DUMMY_SP,
177 open_braces: Vec::new(),
181 pub fn new(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self {
182 let mut sr = StringReader::new_raw(sess, filemap);
183 if sr.advance_token().is_err() {
184 sr.emit_fatal_errors();
190 pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
191 let begin = sess.codemap().lookup_byte_offset(span.lo);
192 let end = sess.codemap().lookup_byte_offset(span.hi);
194 // Make the range zero-length if the span is invalid.
195 if span.lo > span.hi || begin.fm.start_pos != end.fm.start_pos {
199 let mut sr = StringReader::new_raw_internal(sess, begin.fm);
201 // Seek the lexer to the right byte range.
202 sr.save_new_lines_and_multibyte = false;
203 sr.next_pos = span.lo;
204 sr.terminator = Some(span.hi);
208 if sr.advance_token().is_err() {
209 sr.emit_fatal_errors();
215 pub fn ch_is(&self, c: char) -> bool {
219 /// Report a fatal lexical error with a given span.
220 pub fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
221 self.sess.span_diagnostic.span_fatal(sp, m)
224 /// Report a lexical error with a given span.
225 pub fn err_span(&self, sp: Span, m: &str) {
226 self.sess.span_diagnostic.span_err(sp, m)
230 /// Report a fatal error spanning [`from_pos`, `to_pos`).
231 fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
232 self.fatal_span(mk_sp(from_pos, to_pos), m)
235 /// Report a lexical error spanning [`from_pos`, `to_pos`).
236 fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
237 self.err_span(mk_sp(from_pos, to_pos), m)
240 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
241 /// escaped character to the error message
242 fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
243 let mut m = m.to_string();
245 for c in c.escape_default() {
248 self.fatal_span_(from_pos, to_pos, &m[..])
250 fn struct_fatal_span_char(&self,
255 -> DiagnosticBuilder<'a> {
256 let mut m = m.to_string();
258 for c in c.escape_default() {
261 self.sess.span_diagnostic.struct_span_fatal(mk_sp(from_pos, to_pos), &m[..])
264 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
265 /// escaped character to the error message
266 fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
267 let mut m = m.to_string();
269 for c in c.escape_default() {
272 self.err_span_(from_pos, to_pos, &m[..]);
274 fn struct_err_span_char(&self,
279 -> DiagnosticBuilder<'a> {
280 let mut m = m.to_string();
282 for c in c.escape_default() {
285 self.sess.span_diagnostic.struct_span_err(mk_sp(from_pos, to_pos), &m[..])
288 /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
289 /// offending string to the error message
290 fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> FatalError {
292 let from = self.byte_offset(from_pos).to_usize();
293 let to = self.byte_offset(to_pos).to_usize();
294 m.push_str(&self.source_text[from..to]);
295 self.fatal_span_(from_pos, to_pos, &m[..])
298 /// Advance peek_tok and peek_span to refer to the next token, and
299 /// possibly update the interner.
300 fn advance_token(&mut self) -> Result<(), ()> {
301 match self.scan_whitespace_or_comment() {
303 self.peek_span = comment.sp;
304 self.peek_tok = comment.tok;
308 self.peek_tok = token::Eof;
309 self.peek_span = mk_sp(self.filemap.end_pos, self.filemap.end_pos);
311 let start_bytepos = self.pos;
312 self.peek_tok = self.next_token_inner()?;
313 self.peek_span = mk_sp(start_bytepos, self.pos);
320 fn byte_offset(&self, pos: BytePos) -> BytePos {
321 (pos - self.filemap.start_pos)
324 /// Calls `f` with a string slice of the source text spanning from `start`
325 /// up to but excluding `self.pos`, meaning the slice does not include
326 /// the character `self.ch`.
327 pub fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
328 where F: FnOnce(&str) -> T
330 self.with_str_from_to(start, self.pos, f)
333 /// Create a Name from a given offset to the current offset, each
334 /// adjusted 1 towards each other (assumes that on either side there is a
335 /// single-byte delimiter).
336 pub fn name_from(&self, start: BytePos) -> ast::Name {
337 debug!("taking an ident from {:?} to {:?}", start, self.pos);
338 self.with_str_from(start, Symbol::intern)
341 /// As name_from, with an explicit endpoint.
342 pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
343 debug!("taking an ident from {:?} to {:?}", start, end);
344 self.with_str_from_to(start, end, Symbol::intern)
347 /// Calls `f` with a string slice of the source text spanning from `start`
348 /// up to but excluding `end`.
349 fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
350 where F: FnOnce(&str) -> T
352 f(&self.source_text[self.byte_offset(start).to_usize()..self.byte_offset(end).to_usize()])
355 /// Converts CRLF to LF in the given string, raising an error on bare CR.
356 fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
359 let ch = char_at(s, i);
360 let next = i + ch.len_utf8();
362 if next < s.len() && char_at(s, next) == '\n' {
363 return translate_crlf_(self, start, s, errmsg, i).into();
365 let pos = start + BytePos(i as u32);
366 let end_pos = start + BytePos(next as u32);
367 self.err_span_(pos, end_pos, errmsg);
373 fn translate_crlf_(rdr: &StringReader,
379 let mut buf = String::with_capacity(s.len());
382 let ch = char_at(s, i);
383 let next = i + ch.len_utf8();
386 buf.push_str(&s[j..i]);
389 if next >= s.len() || char_at(s, next) != '\n' {
390 let pos = start + BytePos(i as u32);
391 let end_pos = start + BytePos(next as u32);
392 rdr.err_span_(pos, end_pos, errmsg);
398 buf.push_str(&s[j..]);
405 /// Advance the StringReader by one character. If a newline is
406 /// discovered, add it to the FileMap's list of line start offsets.
407 pub fn bump(&mut self) {
408 let new_pos = self.next_pos;
409 let new_byte_offset = self.byte_offset(new_pos).to_usize();
410 let end = self.terminator.map_or(self.source_text.len(), |t| {
411 self.byte_offset(t).to_usize()
413 if new_byte_offset < end {
414 let old_ch_is_newline = self.ch.unwrap() == '\n';
415 let new_ch = char_at(&self.source_text, new_byte_offset);
416 let new_ch_len = new_ch.len_utf8();
418 self.ch = Some(new_ch);
420 self.next_pos = new_pos + Pos::from_usize(new_ch_len);
421 if old_ch_is_newline {
422 if self.save_new_lines_and_multibyte {
423 self.filemap.next_line(self.pos);
425 self.col = CharPos(0);
427 self.col = self.col + CharPos(1);
430 if self.save_new_lines_and_multibyte {
431 self.filemap.record_multibyte_char(self.pos, new_ch_len);
440 pub fn nextch(&self) -> Option<char> {
441 let offset = self.byte_offset(self.next_pos).to_usize();
442 if offset < self.source_text.len() {
443 Some(char_at(&self.source_text, offset))
449 pub fn nextch_is(&self, c: char) -> bool {
450 self.nextch() == Some(c)
453 pub fn nextnextch(&self) -> Option<char> {
454 let offset = self.byte_offset(self.next_pos).to_usize();
455 let s = &self.source_text[..];
456 if offset >= s.len() {
459 let next = offset + char_at(s, offset).len_utf8();
461 Some(char_at(s, next))
467 pub fn nextnextch_is(&self, c: char) -> bool {
468 self.nextnextch() == Some(c)
471 /// Eats <XID_start><XID_continue>*, if possible.
472 fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
473 if !ident_start(self.ch) {
476 let start = self.pos;
477 while ident_continue(self.ch) {
481 self.with_str_from(start, |string| {
483 self.sess.span_diagnostic
484 .struct_span_warn(mk_sp(start, self.pos),
485 "underscore literal suffix is not allowed")
486 .warn("this was previously accepted by the compiler but is \
487 being phased out; it will become a hard error in \
489 .note("for more information, see issue #42326 \
490 <https://github.com/rust-lang/rust/issues/42326>")
494 Some(Symbol::intern(string))
499 /// PRECONDITION: self.ch is not whitespace
500 /// Eats any kind of comment.
501 fn scan_comment(&mut self) -> Option<TokenAndSpan> {
502 if let Some(c) = self.ch {
503 if c.is_whitespace() {
504 let msg = "called consume_any_line_comment, but there was whitespace";
505 self.sess.span_diagnostic.span_err(mk_sp(self.pos, self.pos), msg);
510 match self.nextch() {
515 // line comments starting with "///" or "//!" are doc-comments
516 let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
517 let start_bpos = self.pos - BytePos(2);
519 while !self.is_eof() {
520 match self.ch.unwrap() {
523 if self.nextch_is('\n') {
526 } else if doc_comment {
527 self.err_span_(self.pos,
529 "bare CR not allowed in doc-comment");
538 self.with_str_from(start_bpos, |string| {
539 // comments with only more "/"s are not doc comments
540 let tok = if is_doc_comment(string) {
541 token::DocComment(Symbol::intern(string))
548 sp: mk_sp(start_bpos, self.pos),
554 sp: mk_sp(start_bpos, self.pos),
561 self.scan_block_comment()
565 } else if self.ch_is('#') {
566 if self.nextch_is('!') {
568 // Parse an inner attribute.
569 if self.nextnextch_is('[') {
573 // I guess this is the only way to figure out if
574 // we're at the beginning of the file...
575 let cmap = CodeMap::new(FilePathMapping::empty());
576 cmap.files.borrow_mut().push(self.filemap.clone());
577 let loc = cmap.lookup_char_pos_adj(self.pos);
578 debug!("Skipping a shebang");
579 if loc.line == 1 && loc.col == CharPos(0) {
580 // FIXME: Add shebang "token", return it
581 let start = self.pos;
582 while !self.ch_is('\n') && !self.is_eof() {
585 return Some(TokenAndSpan {
586 tok: token::Shebang(self.name_from(start)),
587 sp: mk_sp(start, self.pos),
597 /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
599 fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
600 match self.ch.unwrap_or('\0') {
601 // # to handle shebang at start of file -- this is the entry point
602 // for skipping over all "junk"
604 let c = self.scan_comment();
605 debug!("scanning a comment {:?}", c);
608 c if is_pattern_whitespace(Some(c)) => {
609 let start_bpos = self.pos;
610 while is_pattern_whitespace(self.ch) {
613 let c = Some(TokenAndSpan {
614 tok: token::Whitespace,
615 sp: mk_sp(start_bpos, self.pos),
617 debug!("scanning whitespace: {:?}", c);
624 /// Might return a sugared-doc-attr
625 fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
626 // block comments starting with "/**" or "/*!" are doc-comments
627 let is_doc_comment = self.ch_is('*') || self.ch_is('!');
628 let start_bpos = self.pos - BytePos(2);
630 let mut level: isize = 1;
631 let mut has_cr = false;
634 let msg = if is_doc_comment {
635 "unterminated block doc-comment"
637 "unterminated block comment"
639 let last_bpos = self.pos;
640 panic!(self.fatal_span_(start_bpos, last_bpos, msg));
642 let n = self.ch.unwrap();
644 '/' if self.nextch_is('*') => {
648 '*' if self.nextch_is('/') => {
660 self.with_str_from(start_bpos, |string| {
661 // but comments with only "*"s between two "/"s are not
662 let tok = if is_block_doc_comment(string) {
663 let string = if has_cr {
664 self.translate_crlf(start_bpos,
666 "bare CR not allowed in block doc-comment")
670 token::DocComment(Symbol::intern(&string[..]))
677 sp: mk_sp(start_bpos, self.pos),
682 /// Scan through any digits (base `scan_radix`) or underscores,
683 /// and return how many digits there were.
685 /// `real_radix` represents the true radix of the number we're
686 /// interested in, and errors will be emitted for any digits
687 /// between `real_radix` and `scan_radix`.
688 fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
689 assert!(real_radix <= scan_radix);
694 debug!("skipping a _");
698 match c.and_then(|cc| cc.to_digit(scan_radix)) {
700 debug!("{:?} in scan_digits", c);
701 // check that the hypothetical digit is actually
702 // in range for the true radix
703 if c.unwrap().to_digit(real_radix).is_none() {
704 self.err_span_(self.pos,
706 &format!("invalid digit for a base {} literal", real_radix));
716 /// Lex a LIT_INTEGER or a LIT_FLOAT
717 fn scan_number(&mut self, c: char) -> token::Lit {
720 let start_bpos = self.pos;
725 match self.ch.unwrap_or('\0') {
729 num_digits = self.scan_digits(2, 10);
734 num_digits = self.scan_digits(8, 10);
739 num_digits = self.scan_digits(16, 16);
741 '0'...'9' | '_' | '.' | 'e' | 'E' => {
742 num_digits = self.scan_digits(10, 10) + 1;
746 return token::Integer(self.name_from(start_bpos));
749 } else if c.is_digit(10) {
750 num_digits = self.scan_digits(10, 10) + 1;
756 self.err_span_(start_bpos,
758 "no valid digits found for number");
759 return token::Integer(Symbol::intern("0"));
762 // might be a float, but don't be greedy if this is actually an
763 // integer literal followed by field/method access or a range pattern
764 // (`0..2` and `12.foo()`)
765 if self.ch_is('.') && !self.nextch_is('.') &&
766 !ident_start(self.nextch()) {
767 // might have stuff after the ., and if it does, it needs to start
770 if self.ch.unwrap_or('\0').is_digit(10) {
771 self.scan_digits(10, 10);
772 self.scan_float_exponent();
775 self.check_float_base(start_bpos, pos, base);
776 token::Float(self.name_from(start_bpos))
778 // it might be a float if it has an exponent
779 if self.ch_is('e') || self.ch_is('E') {
780 self.scan_float_exponent();
782 self.check_float_base(start_bpos, pos, base);
783 return token::Float(self.name_from(start_bpos));
785 // but we certainly have an integer!
786 token::Integer(self.name_from(start_bpos))
790 /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
791 /// error if too many or too few digits are encountered.
792 fn scan_hex_digits(&mut self, n_digits: usize, delim: char, below_0x7f_only: bool) -> bool {
793 debug!("scanning {} digits until {:?}", n_digits, delim);
794 let start_bpos = self.pos;
795 let mut accum_int = 0;
797 let mut valid = true;
798 for _ in 0..n_digits {
800 let last_bpos = self.pos;
801 panic!(self.fatal_span_(start_bpos,
803 "unterminated numeric character escape"));
805 if self.ch_is(delim) {
806 let last_bpos = self.pos;
807 self.err_span_(start_bpos,
809 "numeric character escape is too short");
813 let c = self.ch.unwrap_or('\x00');
815 accum_int += c.to_digit(16).unwrap_or_else(|| {
816 self.err_span_char(self.pos,
818 "invalid character in numeric character escape",
827 if below_0x7f_only && accum_int >= 0x80 {
828 self.err_span_(start_bpos,
830 "this form of character escape may only be used with characters in \
831 the range [\\x00-\\x7f]");
835 match char::from_u32(accum_int) {
838 let last_bpos = self.pos;
839 self.err_span_(start_bpos, last_bpos, "invalid numeric character escape");
845 /// Scan for a single (possibly escaped) byte or char
846 /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
847 /// `start` is the position of `first_source_char`, which is already consumed.
849 /// Returns true if there was a valid char/byte, false otherwise.
850 fn scan_char_or_byte(&mut self,
852 first_source_char: char,
856 match first_source_char {
858 // '\X' for some X must be a character constant:
859 let escaped = self.ch;
860 let escaped_pos = self.pos;
863 None => {} // EOF here is an error that will be checked later.
866 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
867 'x' => self.scan_byte_escape(delim, !ascii_only),
869 let valid = if self.ch_is('{') {
870 self.scan_unicode_escape(delim) && !ascii_only
872 let span = mk_sp(start, self.pos);
873 self.sess.span_diagnostic
874 .struct_span_err(span, "incorrect unicode escape sequence")
876 "format of unicode escape sequences is \
882 self.err_span_(start,
884 "unicode escape sequences cannot be used as a \
885 byte or in a byte string");
890 '\n' if delim == '"' => {
891 self.consume_whitespace();
894 '\r' if delim == '"' && self.ch_is('\n') => {
895 self.consume_whitespace();
900 let mut err = self.struct_err_span_char(escaped_pos,
903 "unknown byte escape"
910 err.span_help(mk_sp(escaped_pos, pos),
911 "this is an isolated carriage return; consider \
912 checking your editor and version control \
915 if (e == '{' || e == '}') && !ascii_only {
916 err.span_help(mk_sp(escaped_pos, pos),
917 "if used in a formatting string, curly braces \
918 are escaped with `{{` and `}}`");
927 '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
929 self.err_span_char(start,
932 "byte constant must be escaped"
934 "character constant must be escaped"
940 if self.ch_is('\n') {
944 self.err_span_(start,
946 "bare CR not allowed in string, use \\r instead");
951 if ascii_only && first_source_char > '\x7F' {
953 self.err_span_(start,
955 "byte constant must be ASCII. Use a \\xHH escape for a \
964 /// Scan over a \u{...} escape
966 /// At this point, we have already seen the \ and the u, the { is the current character. We
967 /// will read at least one digit, and up to 6, and pass over the }.
968 fn scan_unicode_escape(&mut self, delim: char) -> bool {
969 self.bump(); // past the {
970 let start_bpos = self.pos;
972 let mut accum_int = 0;
973 let mut valid = true;
975 while !self.ch_is('}') && count <= 6 {
976 let c = match self.ch {
979 panic!(self.fatal_span_(start_bpos,
981 "unterminated unicode escape (found EOF)"));
985 accum_int += c.to_digit(16).unwrap_or_else(|| {
987 panic!(self.fatal_span_(self.pos,
989 "unterminated unicode escape (needed a `}`)"));
991 self.err_span_char(self.pos,
993 "invalid character in unicode escape",
1004 self.err_span_(start_bpos,
1006 "overlong unicode escape (can have at most 6 hex digits)");
1010 if valid && (char::from_u32(accum_int).is_none() || count == 0) {
1011 self.err_span_(start_bpos,
1013 "invalid unicode character escape");
1017 self.bump(); // past the ending }
1021 /// Scan over a float exponent.
1022 fn scan_float_exponent(&mut self) {
1023 if self.ch_is('e') || self.ch_is('E') {
1025 if self.ch_is('-') || self.ch_is('+') {
1028 if self.scan_digits(10, 10) == 0 {
1029 self.err_span_(self.pos,
1031 "expected at least one digit in exponent")
1036 /// Check that a base is valid for a floating literal, emitting a nice
1037 /// error if it isn't.
1038 fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
1041 self.err_span_(start_bpos,
1043 "hexadecimal float literal is not supported")
1046 self.err_span_(start_bpos,
1048 "octal float literal is not supported")
1051 self.err_span_(start_bpos,
1053 "binary float literal is not supported")
1059 fn binop(&mut self, op: token::BinOpToken) -> token::Token {
1061 if self.ch_is('=') {
1069 /// Return the next token from the string, advances the input past that
1070 /// token, and updates the interner
1071 fn next_token_inner(&mut self) -> Result<token::Token, ()> {
1073 if ident_start(c) &&
1074 match (c.unwrap(), self.nextch(), self.nextnextch()) {
1075 // Note: r as in r" or r#" is part of a raw string literal,
1076 // b as in b' is part of a byte literal.
1077 // They are not identifiers, and are handled further down.
1078 ('r', Some('"'), _) |
1079 ('r', Some('#'), _) |
1080 ('b', Some('"'), _) |
1081 ('b', Some('\''), _) |
1082 ('b', Some('r'), Some('"')) |
1083 ('b', Some('r'), Some('#')) => false,
1086 let start = self.pos;
1087 while ident_continue(self.ch) {
1091 return Ok(self.with_str_from(start, |string| {
1095 // FIXME: perform NFKC normalization here. (Issue #2253)
1096 token::Ident(Ident::from_str(string))
1101 if is_dec_digit(c) {
1102 let num = self.scan_number(c.unwrap());
1103 let suffix = self.scan_optional_raw_name();
1104 debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
1105 return Ok(token::Literal(num, suffix));
1108 match c.expect("next_token_inner called at EOF") {
1120 if self.ch_is('.') {
1122 if self.ch_is('.') {
1124 Ok(token::DotDotDot)
1134 Ok(token::OpenDelim(token::Paren))
1138 Ok(token::CloseDelim(token::Paren))
1142 Ok(token::OpenDelim(token::Brace))
1146 Ok(token::CloseDelim(token::Brace))
1150 Ok(token::OpenDelim(token::Bracket))
1154 Ok(token::CloseDelim(token::Bracket))
1174 if self.ch_is(':') {
1187 // Multi-byte tokens.
1190 if self.ch_is('=') {
1193 } else if self.ch_is('>') {
1202 if self.ch_is('=') {
1211 match self.ch.unwrap_or('\x00') {
1217 Ok(self.binop(token::Shl))
1221 match self.ch.unwrap_or('\x00') {
1234 match self.ch.unwrap_or('\x00') {
1240 Ok(self.binop(token::Shr))
1248 // Either a character constant 'a' OR a lifetime name 'abc
1249 let start_with_quote = self.pos;
1251 let start = self.pos;
1253 // the eof will be picked up by the final `'` check below
1254 let c2 = self.ch.unwrap_or('\x00');
1257 // If the character is an ident start not followed by another single
1258 // quote, then this is a lifetime name:
1259 if ident_start(Some(c2)) && !self.ch_is('\'') {
1260 while ident_continue(self.ch) {
1263 // lifetimes shouldn't end with a single quote
1264 // if we find one, then this is an invalid character literal
1265 if self.ch_is('\'') {
1266 panic!(self.fatal_span_verbose(
1267 start_with_quote, self.next_pos,
1268 String::from("character literal may only contain one codepoint")));
1272 // Include the leading `'` in the real identifier, for macro
1273 // expansion purposes. See #12512 for the gory details of why
1274 // this is necessary.
1275 let ident = self.with_str_from(start, |lifetime_name| {
1276 Ident::from_str(&format!("'{}", lifetime_name))
1279 // Conjure up a "keyword checking ident" to make sure that
1280 // the lifetime name is not a keyword.
1281 let keyword_checking_ident = self.with_str_from(start, |lifetime_name| {
1282 Ident::from_str(lifetime_name)
1284 let keyword_checking_token = &token::Ident(keyword_checking_ident);
1285 let last_bpos = self.pos;
1286 if keyword_checking_token.is_any_keyword() &&
1287 !keyword_checking_token.is_keyword(keywords::Static) {
1288 self.err_span_(start, last_bpos, "lifetimes cannot use keyword names");
1291 return Ok(token::Lifetime(ident));
1294 let valid = self.scan_char_or_byte(start,
1300 if !self.ch_is('\'') {
1301 panic!(self.fatal_span_verbose(
1302 start_with_quote, self.pos,
1303 String::from("character literal may only contain one codepoint")));
1307 self.name_from(start)
1311 self.bump(); // advance ch past token
1312 let suffix = self.scan_optional_raw_name();
1313 Ok(token::Literal(token::Char(id), suffix))
1317 let lit = match self.ch {
1318 Some('\'') => self.scan_byte(),
1319 Some('"') => self.scan_byte_string(),
1320 Some('r') => self.scan_raw_byte_string(),
1321 _ => unreachable!(), // Should have been a token::Ident above.
1323 let suffix = self.scan_optional_raw_name();
1324 Ok(token::Literal(lit, suffix))
1327 let start_bpos = self.pos;
1328 let mut valid = true;
1330 while !self.ch_is('"') {
1332 let last_bpos = self.pos;
1333 panic!(self.fatal_span_(start_bpos,
1335 "unterminated double quote string"));
1338 let ch_start = self.pos;
1339 let ch = self.ch.unwrap();
1341 valid &= self.scan_char_or_byte(ch_start,
1347 // adjust for the ASCII " at the start of the literal
1349 self.name_from(start_bpos + BytePos(1))
1351 Symbol::intern("??")
1354 let suffix = self.scan_optional_raw_name();
1355 Ok(token::Literal(token::Str_(id), suffix))
1358 let start_bpos = self.pos;
1360 let mut hash_count = 0;
1361 while self.ch_is('#') {
1367 let last_bpos = self.pos;
1368 panic!(self.fatal_span_(start_bpos, last_bpos, "unterminated raw string"));
1369 } else if !self.ch_is('"') {
1370 let last_bpos = self.pos;
1371 let curr_char = self.ch.unwrap();
1372 panic!(self.fatal_span_char(start_bpos,
1374 "found invalid character; only `#` is allowed \
1375 in raw string delimitation",
1379 let content_start_bpos = self.pos;
1380 let mut content_end_bpos;
1381 let mut valid = true;
1384 let last_bpos = self.pos;
1385 panic!(self.fatal_span_(start_bpos, last_bpos, "unterminated raw string"));
1387 // if self.ch_is('"') {
1388 // content_end_bpos = self.pos;
1389 // for _ in 0..hash_count {
1391 // if !self.ch_is('#') {
1393 let c = self.ch.unwrap();
1396 content_end_bpos = self.pos;
1397 for _ in 0..hash_count {
1399 if !self.ch_is('#') {
1406 if !self.nextch_is('\n') {
1407 let last_bpos = self.pos;
1408 self.err_span_(start_bpos,
1410 "bare CR not allowed in raw string, use \\r \
1421 self.name_from_to(content_start_bpos, content_end_bpos)
1423 Symbol::intern("??")
1425 let suffix = self.scan_optional_raw_name();
1426 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1429 if self.nextch_is('>') {
1434 Ok(self.binop(token::Minus))
1438 if self.nextch_is('&') {
1443 Ok(self.binop(token::And))
1447 match self.nextch() {
1454 Ok(self.binop(token::Or))
1459 Ok(self.binop(token::Plus))
1462 Ok(self.binop(token::Star))
1465 Ok(self.binop(token::Slash))
1468 Ok(self.binop(token::Caret))
1471 Ok(self.binop(token::Percent))
1474 let last_bpos = self.pos;
1475 let bpos = self.next_pos;
1476 let mut err = self.struct_fatal_span_char(last_bpos,
1478 "unknown start of token",
1480 unicode_chars::check_for_substitution(self, c, &mut err);
1481 self.fatal_errs.push(err);
1487 fn consume_whitespace(&mut self) {
1488 while is_pattern_whitespace(self.ch) && !self.is_eof() {
1493 fn read_to_eol(&mut self) -> String {
1494 let mut val = String::new();
1495 while !self.ch_is('\n') && !self.is_eof() {
1496 val.push(self.ch.unwrap());
1499 if self.ch_is('\n') {
1505 fn read_one_line_comment(&mut self) -> String {
1506 let val = self.read_to_eol();
1507 assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1508 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1512 fn consume_non_eol_whitespace(&mut self) {
1513 while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1518 fn peeking_at_comment(&self) -> bool {
1519 (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1520 // consider shebangs comments, but not inner attributes
1521 (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1524 fn scan_byte(&mut self) -> token::Lit {
1526 let start = self.pos;
1528 // the eof will be picked up by the final `'` check below
1529 let c2 = self.ch.unwrap_or('\x00');
1532 let valid = self.scan_char_or_byte(start,
1537 if !self.ch_is('\'') {
1538 // Byte offsetting here is okay because the
1539 // character before position `start` are an
1540 // ascii single quote and ascii 'b'.
1542 panic!(self.fatal_span_verbose(start - BytePos(2),
1544 "unterminated byte constant".to_string()));
1548 self.name_from(start)
1552 self.bump(); // advance ch past token
1556 fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1557 self.scan_hex_digits(2, delim, below_0x7f_only)
1560 fn scan_byte_string(&mut self) -> token::Lit {
1562 let start = self.pos;
1563 let mut valid = true;
1565 while !self.ch_is('"') {
1568 panic!(self.fatal_span_(start, pos, "unterminated double quote byte string"));
1571 let ch_start = self.pos;
1572 let ch = self.ch.unwrap();
1574 valid &= self.scan_char_or_byte(ch_start,
1581 self.name_from(start)
1583 Symbol::intern("??")
1589 fn scan_raw_byte_string(&mut self) -> token::Lit {
1590 let start_bpos = self.pos;
1592 let mut hash_count = 0;
1593 while self.ch_is('#') {
1600 panic!(self.fatal_span_(start_bpos, pos, "unterminated raw string"));
1601 } else if !self.ch_is('"') {
1603 let ch = self.ch.unwrap();
1604 panic!(self.fatal_span_char(start_bpos,
1606 "found invalid character; only `#` is allowed in raw \
1607 string delimitation",
1611 let content_start_bpos = self.pos;
1612 let mut content_end_bpos;
1617 panic!(self.fatal_span_(start_bpos, pos, "unterminated raw string"))
1620 content_end_bpos = self.pos;
1621 for _ in 0..hash_count {
1623 if !self.ch_is('#') {
1632 self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1639 token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos),
1644 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1645 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1646 pub fn is_pattern_whitespace(c: Option<char>) -> bool {
1647 c.map_or(false, Pattern_White_Space)
1650 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1652 Some(c) => lo <= c && c <= hi,
1657 fn is_dec_digit(c: Option<char>) -> bool {
1658 in_range(c, '0', '9')
1661 pub fn is_doc_comment(s: &str) -> bool {
1662 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1663 s.starts_with("//!");
1664 debug!("is {:?} a doc comment? {}", s, res);
1668 pub fn is_block_doc_comment(s: &str) -> bool {
1669 // Prevent `/**/` from being parsed as a doc comment
1670 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1671 s.starts_with("/*!")) && s.len() >= 5;
1672 debug!("is {:?} a doc comment? {}", s, res);
1676 fn ident_start(c: Option<char>) -> bool {
1679 None => return false,
1682 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1685 fn ident_continue(c: Option<char>) -> bool {
1688 None => return false,
1691 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1692 (c > '\x7f' && c.is_xid_continue())
1699 use ast::{Ident, CrateConfig};
1701 use syntax_pos::{BytePos, Span, NO_EXPANSION};
1702 use codemap::CodeMap;
1704 use feature_gate::UnstableFeatures;
1706 use std::cell::RefCell;
1707 use std::collections::HashSet;
1711 fn mk_sess(cm: Rc<CodeMap>) -> ParseSess {
1712 let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()), Some(cm.clone()));
1714 span_diagnostic: errors::Handler::with_emitter(true, false, Box::new(emitter)),
1715 unstable_features: UnstableFeatures::from_environment(),
1716 config: CrateConfig::new(),
1717 included_mod_stack: RefCell::new(Vec::new()),
1719 missing_fragment_specifiers: RefCell::new(HashSet::new()),
1723 // open a string reader for the given string
1724 fn setup<'a>(cm: &CodeMap,
1725 sess: &'a ParseSess,
1727 -> StringReader<'a> {
1728 let fm = cm.new_filemap("zebra.rs".to_string(), teststr);
1729 StringReader::new(sess, fm)
1734 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1735 let sh = mk_sess(cm.clone());
1736 let mut string_reader = setup(&cm,
1738 "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1740 let id = Ident::from_str("fn");
1741 assert_eq!(string_reader.next_token().tok, token::Comment);
1742 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1743 let tok1 = string_reader.next_token();
1744 let tok2 = TokenAndSpan {
1745 tok: token::Ident(id),
1752 assert_eq!(tok1, tok2);
1753 assert_eq!(string_reader.next_token().tok, token::Whitespace);
1754 // the 'main' id is already read:
1755 assert_eq!(string_reader.pos.clone(), BytePos(28));
1756 // read another token:
1757 let tok3 = string_reader.next_token();
1758 let tok4 = TokenAndSpan {
1759 tok: token::Ident(Ident::from_str("main")),
1766 assert_eq!(tok3, tok4);
1767 // the lparen is already read:
1768 assert_eq!(string_reader.pos.clone(), BytePos(29))
1771 // check that the given reader produces the desired stream
1772 // of tokens (stop checking after exhausting the expected vec)
1773 fn check_tokenization(mut string_reader: StringReader, expected: Vec<token::Token>) {
1774 for expected_tok in &expected {
1775 assert_eq!(&string_reader.next_token().tok, expected_tok);
1779 // make the identifier by looking up the string in the interner
1780 fn mk_ident(id: &str) -> token::Token {
1781 token::Ident(Ident::from_str(id))
1785 fn doublecolonparsing() {
1786 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1787 let sh = mk_sess(cm.clone());
1788 check_tokenization(setup(&cm, &sh, "a b".to_string()),
1789 vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1794 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1795 let sh = mk_sess(cm.clone());
1796 check_tokenization(setup(&cm, &sh, "a::b".to_string()),
1797 vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1802 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1803 let sh = mk_sess(cm.clone());
1804 check_tokenization(setup(&cm, &sh, "a ::b".to_string()),
1805 vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
1810 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1811 let sh = mk_sess(cm.clone());
1812 check_tokenization(setup(&cm, &sh, "a:: b".to_string()),
1813 vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
1818 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1819 let sh = mk_sess(cm.clone());
1820 assert_eq!(setup(&cm, &sh, "'a'".to_string()).next_token().tok,
1821 token::Literal(token::Char(Symbol::intern("a")), None));
1825 fn character_space() {
1826 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1827 let sh = mk_sess(cm.clone());
1828 assert_eq!(setup(&cm, &sh, "' '".to_string()).next_token().tok,
1829 token::Literal(token::Char(Symbol::intern(" ")), None));
1833 fn character_escaped() {
1834 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1835 let sh = mk_sess(cm.clone());
1836 assert_eq!(setup(&cm, &sh, "'\\n'".to_string()).next_token().tok,
1837 token::Literal(token::Char(Symbol::intern("\\n")), None));
1841 fn lifetime_name() {
1842 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1843 let sh = mk_sess(cm.clone());
1844 assert_eq!(setup(&cm, &sh, "'abc".to_string()).next_token().tok,
1845 token::Lifetime(Ident::from_str("'abc")));
1850 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1851 let sh = mk_sess(cm.clone());
1852 assert_eq!(setup(&cm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
1855 token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
1859 fn literal_suffixes() {
1860 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1861 let sh = mk_sess(cm.clone());
1863 ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1864 assert_eq!(setup(&cm, &sh, format!("{}suffix", $input)).next_token().tok,
1865 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
1866 Some(Symbol::intern("suffix"))));
1867 // with a whitespace separator:
1868 assert_eq!(setup(&cm, &sh, format!("{} suffix", $input)).next_token().tok,
1869 token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
1874 test!("'a'", Char, "a");
1875 test!("b'a'", Byte, "a");
1876 test!("\"a\"", Str_, "a");
1877 test!("b\"a\"", ByteStr, "a");
1878 test!("1234", Integer, "1234");
1879 test!("0b101", Integer, "0b101");
1880 test!("0xABC", Integer, "0xABC");
1881 test!("1.0", Float, "1.0");
1882 test!("1.0e10", Float, "1.0e10");
1884 assert_eq!(setup(&cm, &sh, "2us".to_string()).next_token().tok,
1885 token::Literal(token::Integer(Symbol::intern("2")),
1886 Some(Symbol::intern("us"))));
1887 assert_eq!(setup(&cm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
1888 token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
1889 Some(Symbol::intern("suffix"))));
1890 assert_eq!(setup(&cm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
1891 token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
1892 Some(Symbol::intern("suffix"))));
1896 fn line_doc_comments() {
1897 assert!(is_doc_comment("///"));
1898 assert!(is_doc_comment("/// blah"));
1899 assert!(!is_doc_comment("////"));
1903 fn nested_block_comments() {
1904 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1905 let sh = mk_sess(cm.clone());
1906 let mut lexer = setup(&cm, &sh, "/* /* */ */'a'".to_string());
1907 match lexer.next_token().tok {
1908 token::Comment => {}
1909 _ => panic!("expected a comment!"),
1911 assert_eq!(lexer.next_token().tok,
1912 token::Literal(token::Char(Symbol::intern("a")), None));
1916 fn crlf_comments() {
1917 let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1918 let sh = mk_sess(cm.clone());
1919 let mut lexer = setup(&cm, &sh, "// test\r\n/// test\r\n".to_string());
1920 let comment = lexer.next_token();
1921 assert_eq!(comment.tok, token::Comment);
1922 assert_eq!((comment.sp.lo, comment.sp.hi), (BytePos(0), BytePos(7)));
1923 assert_eq!(lexer.next_token().tok, token::Whitespace);
1924 assert_eq!(lexer.next_token().tok,
1925 token::DocComment(Symbol::intern("/// test")));