]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/lexer/mod.rs
Register new snapshots
[rust.git] / src / libsyntax / parse / lexer / mod.rs
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.
4 //
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.
10
11 use ast;
12 use codemap::{BytePos, CharPos, CodeMap, Pos, Span};
13 use codemap;
14 use diagnostic::SpanHandler;
15 use ext::tt::transcribe::tt_next_token;
16 use parse::token;
17 use parse::token::{str_to_ident};
18
19 use std::char;
20 use std::fmt;
21 use std::mem::replace;
22 use std::num;
23 use std::rc::Rc;
24 use std::str;
25
26 pub use ext::tt::transcribe::{TtReader, new_tt_reader};
27
28 pub mod comments;
29
30 pub trait 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.
36     fn err(&self, &str);
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();
41         loop {
42             match t.tok {
43                 token::Whitespace | token::Comment | token::Shebang(_) => {
44                     t = self.next_token();
45                 },
46                 _ => break
47             }
48         }
49         t
50     }
51 }
52
53 #[deriving(Clone, PartialEq, Eq, Show)]
54 pub struct TokenAndSpan {
55     pub tok: token::Token,
56     pub sp: Span,
57 }
58
59 pub struct StringReader<'a> {
60     pub span_diagnostic: &'a SpanHandler,
61     /// The absolute offset within the codemap of the next character to read
62     pub pos: BytePos,
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
66     pub col: CharPos,
67     /// The last character to be read
68     pub curr: Option<char>,
69     pub filemap: Rc<codemap::FileMap>,
70     /* cached: */
71     pub peek_tok: token::Token,
72     pub peek_span: Span,
73
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,
78 }
79
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),
86             sp: self.peek_span,
87         };
88         self.advance_token();
89         ret_val
90     }
91     fn fatal(&self, m: &str) -> ! {
92         self.fatal_span(self.peek_span, m)
93     }
94     fn err(&self, m: &str) {
95         self.err_span(self.peek_span, m)
96     }
97     fn peek(&self) -> TokenAndSpan {
98         // FIXME(pcwalton): Bad copy!
99         TokenAndSpan {
100             tok: self.peek_tok.clone(),
101             sp: self.peek_span,
102         }
103     }
104 }
105
106 impl<'a> Reader for TtReader<'a> {
107     fn is_eof(&self) -> bool {
108         self.cur_tok == token::Eof
109     }
110     fn next_token(&mut self) -> TokenAndSpan {
111         let r = tt_next_token(self);
112         debug!("TtReader: r={}", r);
113         r
114     }
115     fn fatal(&self, m: &str) -> ! {
116         self.sp_diag.span_fatal(self.cur_span, m);
117     }
118     fn err(&self, m: &str) {
119         self.sp_diag.span_err(self.cur_span, m);
120     }
121     fn peek(&self) -> TokenAndSpan {
122         TokenAndSpan {
123             tok: self.cur_tok.clone(),
124             sp: self.cur_span,
125         }
126     }
127 }
128
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;
136     sr.advance_token();
137     sr
138 }
139
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,
148             col: CharPos(0),
149             curr: Some('\n'),
150             filemap: filemap,
151             /* dummy values; not read */
152             peek_tok: token::Eof,
153             peek_span: codemap::DUMMY_SP,
154             read_embedded_ident: false,
155         };
156         sr.bump();
157         sr
158     }
159
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);
163         sr.advance_token();
164         sr
165     }
166
167     pub fn curr_is(&self, c: char) -> bool {
168         self.curr == Some(c)
169     }
170
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)
174     }
175
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)
179     }
180
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)
184     }
185
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)
189     }
190
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();
195         m.push_str(": ");
196         for c in c.escape_default() { m.push(c) }
197         self.fatal_span_(from_pos, to_pos, m.as_slice());
198     }
199
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();
204         m.push_str(": ");
205         for c in c.escape_default() { m.push(c) }
206         self.err_span_(from_pos, to_pos, m.as_slice());
207     }
208
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) -> ! {
212         m.push_str(": ");
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());
217     }
218
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() {
223             Some(comment) => {
224                 self.peek_span = comment.sp;
225                 self.peek_tok = comment.tok;
226             },
227             None => {
228                 if self.is_eof() {
229                     self.peek_tok = token::Eof;
230                 } else {
231                     let start_bytepos = self.last_pos;
232                     self.peek_tok = self.next_token_inner();
233                     self.peek_span = codemap::mk_sp(start_bytepos,
234                                                     self.last_pos);
235                 };
236             }
237         }
238     }
239
240     fn byte_offset(&self, pos: BytePos) -> BytePos {
241         (pos - self.filemap.start_pos)
242     }
243
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)
249     }
250
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)
257     }
258
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)
263     }
264
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()))
271     }
272
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> {
276         let mut i = 0u;
277         while i < s.len() {
278             let str::CharRange { ch, next } = s.char_range_at(i);
279             if ch == '\r' {
280                 if next < s.len() && s.char_at(next) == '\n' {
281                     return translate_crlf_(self, start, s, errmsg, i).into_cow();
282                 }
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);
286             }
287             i = next;
288         }
289         return s.into_cow();
290
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());
294             let mut j = 0;
295             while i < s.len() {
296                 let str::CharRange { ch, next } = s.char_range_at(i);
297                 if ch == '\r' {
298                     if j < i { buf.push_str(s.slice(j, i)); }
299                     j = next;
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);
304                     }
305                 }
306                 i = next;
307             }
308             if j < s.len() { buf.push_str(s.slice_from(j)); }
309             buf
310         }
311     }
312
313
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
323                           .src
324                           .as_slice()
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);
333             }
334
335             if byte_offset_diff > 1 {
336                 self.filemap.record_multibyte_char(self.last_pos, byte_offset_diff);
337             }
338         } else {
339             self.curr = None;
340         }
341     }
342
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))
347         } else {
348             None
349         }
350     }
351
352     pub fn nextch_is(&self, c: char) -> bool {
353         self.nextch() == Some(c)
354     }
355
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);
361         if next < s.len() {
362             Some(s.char_at(next))
363         } else {
364             None
365         }
366     }
367
368     pub fn nextnextch_is(&self, c: char) -> bool {
369         self.nextnextch() == Some(c)
370     }
371
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) {
375             return None
376         }
377         let start = self.last_pos;
378         while ident_continue(self.curr) {
379             self.bump();
380         }
381
382         self.with_str_from(start, |string| {
383             if string == "_" {
384                 None
385             } else {
386                 Some(token::intern(string))
387             }
388         })
389     }
390
391     /// PRECONDITION: self.curr is not whitespace
392     /// Eats any kind of comment.
393     fn scan_comment(&mut self) -> Option<TokenAndSpan> {
394         match self.curr {
395             Some(c) => {
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");
399                 }
400             },
401             None => { }
402         }
403
404         if self.curr_is('/') {
405             match self.nextch() {
406                 Some('/') => {
407                     self.bump();
408                     self.bump();
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() {
414                                 '\n' => break,
415                                 '\r' => {
416                                     if self.nextch_is('\n') {
417                                         // CRLF
418                                         break
419                                     } else {
420                                         self.err_span_(self.last_pos, self.pos,
421                                                        "bare CR not allowed in doc-comment");
422                                     }
423                                 }
424                                 _ => ()
425                             }
426                             self.bump();
427                         }
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))
432                             } else {
433                                 token::Comment
434                             };
435
436                             return Some(TokenAndSpan{
437                                 tok: tok,
438                                 sp: codemap::mk_sp(start_bpos, self.last_pos)
439                             });
440                         });
441                     } else {
442                         let start_bpos = self.last_pos - BytePos(2);
443                         while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
444                         return Some(TokenAndSpan {
445                             tok: token::Comment,
446                             sp: codemap::mk_sp(start_bpos, self.last_pos)
447                         });
448                     }
449                 }
450                 Some('*') => {
451                     self.bump(); self.bump();
452                     self.scan_block_comment()
453                 }
454                 _ => None
455             }
456         } else if self.curr_is('#') {
457             if self.nextch_is('!') {
458
459                 // Parse an inner attribute.
460                 if self.nextnextch_is('[') {
461                     return None;
462                 }
463
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)
477                     });
478                 }
479             }
480             None
481         } else {
482             None
483         }
484     }
485
486     /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
487     /// return None.
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"
492             '/' | '#' => {
493                 let c = self.scan_comment();
494                 debug!("scanning a comment {}", c);
495                 c
496             },
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)
503                 });
504                 debug!("scanning whitespace: {}", c);
505                 c
506             },
507             _ => None
508         }
509     }
510
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);
516
517         let mut level: int = 1;
518         let mut has_cr = false;
519         while level > 0 {
520             if self.is_eof() {
521                 let msg = if is_doc_comment {
522                     "unterminated block doc-comment"
523                 } else {
524                     "unterminated block comment"
525                 };
526                 let last_bpos = self.last_pos;
527                 self.fatal_span_(start_bpos, last_bpos, msg);
528             }
529             let n = self.curr.unwrap();
530             match n {
531                 '/' if self.nextch_is('*') => {
532                     level += 1;
533                     self.bump();
534                 }
535                 '*' if self.nextch_is('/') => {
536                     level -= 1;
537                     self.bump();
538                 }
539                 '\r' => {
540                     has_cr = true;
541                 }
542                 _ => ()
543             }
544             self.bump();
545         }
546
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()))
555             } else {
556                 token::Comment
557             };
558
559             Some(TokenAndSpan{
560                 tok: tok,
561                 sp: codemap::mk_sp(start_bpos, self.last_pos)
562             })
563         })
564     }
565
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.)
571     //
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.
576
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
581     /// `\x00` marker.
582     #[inline(never)]
583     fn scan_embedded_hygienic_ident(&mut self) -> ast::Ident {
584         fn bump_expecting_char<'a,D:fmt::Show>(r: &mut StringReader<'a>,
585                                                c: char,
586                                                described_c: D,
587                                                whence: &str) {
588             match r.curr {
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),
592             }
593         }
594
595         let whence = "while scanning embedded hygienic ident";
596
597         // skip over the leading `\x00`
598         bump_expecting_char(self, '\x00', "nul-byte", whence);
599
600         // skip over the "name_"
601         for c in "name_".chars() {
602             bump_expecting_char(self, c, c, whence);
603         }
604
605         let start_bpos = self.last_pos;
606         let base = 10;
607
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);
614             })
615         });
616
617         // skip over the `,`
618         bump_expecting_char(self, ',', "comma", whence);
619
620         // skip over the "ctxt_"
621         for c in "ctxt_".chars() {
622             bump_expecting_char(self, c, c, whence);
623         }
624
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);
631             })
632         });
633
634         // skip over the `\x00`
635         bump_expecting_char(self, '\x00', "nul-byte", whence);
636
637         ast::Ident { name: ast::Name(encoded_name),
638                      ctxt: encoded_ctxt, }
639     }
640
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 {
644         let mut len = 0u;
645         loop {
646             let c = self.curr;
647             if c == Some('_') { debug!("skipping a _"); self.bump(); continue; }
648             match c.and_then(|cc| cc.to_digit(radix)) {
649                 Some(_) => {
650                     debug!("{} in scan_digits", c);
651                     len += 1;
652                     self.bump();
653                 }
654                 _ => return len
655             }
656         };
657     }
658
659     /// Lex a LIT_INTEGER or a LIT_FLOAT
660     fn scan_number(&mut self, c: char) -> token::Lit {
661         let mut num_digits;
662         let mut base = 10;
663         let start_bpos = self.last_pos;
664
665         self.bump();
666
667         if c == '0' {
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;
674                 }
675                 _ => {
676                     // just a 0
677                     return token::Integer(self.name_from(start_bpos));
678                 }
679             }
680         } else if c.is_digit(10) {
681             num_digits = self.scan_digits(10) + 1;
682         } else {
683             num_digits = 0;
684         }
685
686         if num_digits == 0 {
687             self.err_span_(start_bpos, self.last_pos, "no valid digits found for number");
688             return token::Integer(token::intern("0"));
689         }
690
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')
695                                                              .is_xid_start() {
696             // might have stuff after the ., and if it does, it needs to start
697             // with a number
698             self.bump();
699             if self.curr.unwrap_or('\0').is_digit(10) {
700                 self.scan_digits(10);
701                 self.scan_float_exponent();
702             }
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));
706         } else {
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));
713             }
714             // but we certainly have an integer!
715             return token::Integer(self.name_from(start_bpos));
716         }
717     }
718
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,
722                        n_digits: uint,
723                        delim: char,
724                        below_0x7f_only: bool)
725                        -> bool {
726         debug!("scanning {} digits until {}", n_digits, delim);
727         let start_bpos = self.last_pos;
728         let mut accum_int = 0;
729
730         for _ in range(0, n_digits) {
731             if self.is_eof() {
732                 let last_bpos = self.last_pos;
733                 self.fatal_span_(start_bpos, last_bpos, "unterminated numeric character escape");
734             }
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");
738                 break;
739             }
740             let c = self.curr.unwrap_or('\x00');
741             accum_int *= 16;
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);
745                 0
746             }) as u32;
747             self.bump();
748         }
749
750         if below_0x7f_only && accum_int >= 0x80 {
751             self.err_span_(start_bpos,
752                            self.last_pos,
753                            "this form of character escape may only be used \
754                             with characters in the range [\\x00-\\x7f]");
755         }
756
757         match char::from_u32(accum_int) {
758             Some(_) => true,
759             None => {
760                 let last_bpos = self.last_pos;
761                 self.err_span_(start_bpos, last_bpos, "illegal numeric character escape");
762                 false
763             }
764         }
765     }
766
767     // SNAP 361baab
768     #[allow(unused)]
769     fn old_escape_warning(&mut self, sp: Span) {
770         self.span_diagnostic
771             .span_warn(sp, "\\U00ABCD12 and \\uABCD escapes are deprecated");
772         self.span_diagnostic
773             .span_help(sp, "use \\u{ABCD12} escapes instead");
774     }
775
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.
779     ///
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 {
784             '\\' => {
785                 // '\X' for some X must be a character constant:
786                 let escaped = self.curr;
787                 let escaped_pos = self.last_pos;
788                 self.bump();
789                 match escaped {
790                     None => {},  // EOF here is an error that will be checked later.
791                     Some(e) => {
792                         return match e {
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)
798                                 } else {
799                                     let res = self.scan_hex_digits(4u, delim, false);
800                                     // SNAP 361baab
801                                     //let sp = codemap::mk_sp(escaped_pos, self.last_pos);
802                                     //self.old_escape_warning(sp);
803                                     res
804                                 }
805                             }
806                             'U' if !ascii_only => {
807                                 let res = self.scan_hex_digits(8u, delim, false);
808                                 // SNAP 361baab
809                                 //let sp = codemap::mk_sp(escaped_pos, self.last_pos);
810                                 //self.old_escape_warning(sp);
811                                 res
812                             }
813                             '\n' if delim == '"' => {
814                                 self.consume_whitespace();
815                                 true
816                             },
817                             '\r' if delim == '"' && self.curr_is('\n') => {
818                                 self.consume_whitespace();
819                                 true
820                             }
821                             c => {
822                                 let last_pos = self.last_pos;
823                                 self.err_span_char(
824                                     escaped_pos, last_pos,
825                                     if ascii_only { "unknown byte escape" }
826                                     else { "unknown character escape" },
827                                     c);
828                                 if e == '\r' {
829                                     let sp = codemap::mk_sp(escaped_pos, last_pos);
830                                     self.span_diagnostic.span_help(
831                                         sp,
832                                         "this is an isolated carriage return; consider checking \
833                                          your editor and version control settings")
834                                 }
835                                 false
836                             }
837                         }
838                     }
839                 }
840             }
841             '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
842                 let last_pos = self.last_pos;
843                 self.err_span_char(
844                     start, last_pos,
845                     if ascii_only { "byte constant must be escaped" }
846                     else { "character constant must be escaped" },
847                     first_source_char);
848                 return false;
849             }
850             '\r' => {
851                 if self.curr_is('\n') {
852                     self.bump();
853                     return true;
854                 } else {
855                     self.err_span_(start, self.last_pos,
856                                    "bare CR not allowed in string, use \\r instead");
857                     return false;
858                 }
859             }
860             _ => if ascii_only && first_source_char > '\x7F' {
861                 let last_pos = self.last_pos;
862                 self.err_span_char(
863                     start, last_pos,
864                     "byte constant must be ASCII. \
865                      Use a \\xHH escape for a non-ASCII byte", first_source_char);
866                 return false;
867             }
868         }
869         true
870     }
871
872     /// Scan over a \u{...} escape
873     ///
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;
881
882         while !self.curr_is('}') && count <= 6 {
883             let c = match self.curr {
884                 Some(c) => c,
885                 None => {
886                     self.fatal_span_(start_bpos, self.last_pos,
887                                      "unterminated unicode escape (found EOF)");
888                 }
889             };
890             accum_int *= 16;
891             accum_int += c.to_digit(16).unwrap_or_else(|| {
892                 if c == delim {
893                     self.fatal_span_(self.last_pos, self.pos,
894                                      "unterminated unicode escape (needed a `}`)");
895                 } else {
896                     self.fatal_span_char(self.last_pos, self.pos,
897                                    "illegal character in unicode escape", c);
898                 }
899             }) as u32;
900             self.bump();
901             count += 1;
902         }
903
904         if count > 6 {
905             self.fatal_span_(start_bpos, self.last_pos,
906                           "overlong unicode escape (can have at most 6 hex digits)");
907         }
908
909         self.bump(); // past the ending }
910
911         let mut valid = count >= 1 && count <= 6;
912         if char::from_u32(accum_int).is_none() {
913             valid = false;
914         }
915
916         if !valid {
917             self.fatal_span_(start_bpos, self.last_pos, "illegal unicode character escape");
918         }
919         valid
920     }
921
922     /// Scan over a float exponent.
923     fn scan_float_exponent(&mut self) {
924         if self.curr_is('e') || self.curr_is('E') {
925             self.bump();
926             if self.curr_is('-') || self.curr_is('+') {
927                 self.bump();
928             }
929             if self.scan_digits(10) == 0 {
930                 self.err_span_(self.last_pos, self.pos, "expected at least one digit in exponent")
931             }
932         }
933     }
934
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) {
938         match base {
939             16u => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \
940                                  supported"),
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"),
943             _ => ()
944         }
945     }
946
947     fn binop(&mut self, op: token::BinOpToken) -> token::Token {
948         self.bump();
949         if self.curr_is('=') {
950             self.bump();
951             return token::BinOpEq(op);
952         } else {
953             return token::BinOp(op);
954         }
955     }
956
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 {
960         let c = self.curr;
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,
968            _ => true
969         } {
970             let start = self.last_pos;
971             while ident_continue(self.curr) {
972                 self.bump();
973             }
974
975             return self.with_str_from(start, |string| {
976                 if string == "_" {
977                     token::Underscore
978                 } else {
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)
982                     } else {
983                         token::Ident(str_to_ident(string), token::Plain)
984                     }
985                 }
986             });
987         }
988
989         if is_dec_digit(c) {
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)
994         }
995
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)
1002                     } else {
1003                         token::Ident(ast_ident, token::Plain)
1004                     };
1005                 }
1006                 _ => {}
1007             }
1008         }
1009
1010         match c.expect("next_token_inner called at EOF") {
1011           // One-byte tokens.
1012           ';' => { self.bump(); return token::Semi; }
1013           ',' => { self.bump(); return token::Comma; }
1014           '.' => {
1015               self.bump();
1016               return if self.curr_is('.') {
1017                   self.bump();
1018                   if self.curr_is('.') {
1019                       self.bump();
1020                       token::DotDotDot
1021                   } else {
1022                       token::DotDot
1023                   }
1024               } else {
1025                   token::Dot
1026               };
1027           }
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; }
1038           ':' => {
1039             self.bump();
1040             if self.curr_is(':') {
1041                 self.bump();
1042                 return token::ModSep;
1043             } else {
1044                 return token::Colon;
1045             }
1046           }
1047
1048           '$' => { self.bump(); return token::Dollar; }
1049
1050           // Multi-byte tokens.
1051           '=' => {
1052             self.bump();
1053             if self.curr_is('=') {
1054                 self.bump();
1055                 return token::EqEq;
1056             } else if self.curr_is('>') {
1057                 self.bump();
1058                 return token::FatArrow;
1059             } else {
1060                 return token::Eq;
1061             }
1062           }
1063           '!' => {
1064             self.bump();
1065             if self.curr_is('=') {
1066                 self.bump();
1067                 return token::Ne;
1068             } else { return token::Not; }
1069           }
1070           '<' => {
1071             self.bump();
1072             match self.curr.unwrap_or('\x00') {
1073               '=' => { self.bump(); return token::Le; }
1074               '<' => { return self.binop(token::Shl); }
1075               '-' => {
1076                 self.bump();
1077                 match self.curr.unwrap_or('\x00') {
1078                   _ => { return token::LArrow; }
1079                 }
1080               }
1081               _ => { return token::Lt; }
1082             }
1083           }
1084           '>' => {
1085             self.bump();
1086             match self.curr.unwrap_or('\x00') {
1087               '=' => { self.bump(); return token::Ge; }
1088               '>' => { return self.binop(token::Shr); }
1089               _ => { return token::Gt; }
1090             }
1091           }
1092           '\'' => {
1093             // Either a character constant 'a' OR a lifetime name 'abc
1094             self.bump();
1095             let start = self.last_pos;
1096
1097             // the eof will be picked up by the final `'` check below
1098             let c2 = self.curr.unwrap_or('\x00');
1099             self.bump();
1100
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) {
1105                     self.bump();
1106                 }
1107
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())
1113                 });
1114
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)
1120                     });
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,
1126                                    last_bpos,
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)
1131                 {
1132                     self.err_span_(start,
1133                                    last_bpos,
1134                                    "invalid lifetime name");
1135                 }
1136                 return token::Lifetime(ident);
1137             }
1138
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());
1149             }
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);
1154           }
1155           'b' => {
1156             self.bump();
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.
1162             };
1163             let suffix = self.scan_optional_raw_name();
1164             return token::Literal(lit, suffix);
1165           }
1166           '"' => {
1167             let start_bpos = self.last_pos;
1168             let mut valid = true;
1169             self.bump();
1170             while !self.curr_is('"') {
1171                 if self.is_eof() {
1172                     let last_bpos = self.last_pos;
1173                     self.fatal_span_(start_bpos, last_bpos, "unterminated double quote string");
1174                 }
1175
1176                 let ch_start = self.last_pos;
1177                 let ch = self.curr.unwrap();
1178                 self.bump();
1179                 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ false, '"');
1180             }
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("??") };
1184             self.bump();
1185             let suffix = self.scan_optional_raw_name();
1186             return token::Literal(token::Str_(id), suffix);
1187           }
1188           'r' => {
1189             let start_bpos = self.last_pos;
1190             self.bump();
1191             let mut hash_count = 0u;
1192             while self.curr_is('#') {
1193                 self.bump();
1194                 hash_count += 1;
1195             }
1196
1197             if self.is_eof() {
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",
1206                                 curr_char);
1207             }
1208             self.bump();
1209             let content_start_bpos = self.last_pos;
1210             let mut content_end_bpos;
1211             let mut valid = true;
1212             'outer: loop {
1213                 if self.is_eof() {
1214                     let last_bpos = self.last_pos;
1215                     self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
1216                 }
1217                 //if self.curr_is('"') {
1218                     //content_end_bpos = self.last_pos;
1219                     //for _ in range(0, hash_count) {
1220                         //self.bump();
1221                         //if !self.curr_is('#') {
1222                             //continue 'outer;
1223                 let c = self.curr.unwrap();
1224                 match c {
1225                     '"' => {
1226                         content_end_bpos = self.last_pos;
1227                         for _ in range(0, hash_count) {
1228                             self.bump();
1229                             if !self.curr_is('#') {
1230                                 continue 'outer;
1231                             }
1232                         }
1233                         break;
1234                     },
1235                     '\r' => {
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");
1240                             valid = false;
1241                         }
1242                     }
1243                     _ => ()
1244                 }
1245                 self.bump();
1246             }
1247             self.bump();
1248             let id = if valid {
1249                 self.name_from_to(content_start_bpos, content_end_bpos)
1250             } else {
1251                 token::intern("??")
1252             };
1253             let suffix = self.scan_optional_raw_name();
1254             return token::Literal(token::StrRaw(id, hash_count), suffix);
1255           }
1256           '-' => {
1257             if self.nextch_is('>') {
1258                 self.bump();
1259                 self.bump();
1260                 return token::RArrow;
1261             } else { return self.binop(token::Minus); }
1262           }
1263           '&' => {
1264             if self.nextch_is('&') {
1265                 self.bump();
1266                 self.bump();
1267                 return token::AndAnd;
1268             } else { return self.binop(token::And); }
1269           }
1270           '|' => {
1271             match self.nextch() {
1272               Some('|') => { self.bump(); self.bump(); return token::OrOr; }
1273               _ => { return self.binop(token::Or); }
1274             }
1275           }
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); }
1281           c => {
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);
1285           }
1286         }
1287     }
1288
1289     fn consume_whitespace(&mut self) {
1290         while is_whitespace(self.curr) && !self.is_eof() { self.bump(); }
1291     }
1292
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());
1297             self.bump();
1298         }
1299         if self.curr_is('\n') { self.bump(); }
1300         return val
1301     }
1302
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'!'));
1307         return val;
1308     }
1309
1310     fn consume_non_eol_whitespace(&mut self) {
1311         while is_whitespace(self.curr) && !self.curr_is('\n') && !self.is_eof() {
1312             self.bump();
1313         }
1314     }
1315
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('['))
1321     }
1322
1323     fn scan_byte(&mut self) -> token::Lit {
1324         self.bump();
1325         let start = self.last_pos;
1326
1327         // the eof will be picked up by the final `'` check below
1328         let c2 = self.curr.unwrap_or('\x00');
1329         self.bump();
1330
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());
1340         }
1341
1342         let id = if valid { self.name_from(start) } else { token::intern("??") };
1343         self.bump(); // advance curr past token
1344         return token::Byte(id);
1345     }
1346
1347     fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1348         self.scan_hex_digits(2, delim, below_0x7f_only)
1349     }
1350
1351     fn scan_byte_string(&mut self) -> token::Lit {
1352         self.bump();
1353         let start = self.last_pos;
1354         let mut valid = true;
1355
1356         while !self.curr_is('"') {
1357             if self.is_eof() {
1358                 let last_pos = self.last_pos;
1359                 self.fatal_span_(start, last_pos,
1360                                   "unterminated double quote byte string");
1361             }
1362
1363             let ch_start = self.last_pos;
1364             let ch = self.curr.unwrap();
1365             self.bump();
1366             valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ true, '"');
1367         }
1368         let id = if valid { self.name_from(start) } else { token::intern("??") };
1369         self.bump();
1370         return token::Binary(id);
1371     }
1372
1373     fn scan_raw_byte_string(&mut self) -> token::Lit {
1374         let start_bpos = self.last_pos;
1375         self.bump();
1376         let mut hash_count = 0u;
1377         while self.curr_is('#') {
1378             self.bump();
1379             hash_count += 1;
1380         }
1381
1382         if self.is_eof() {
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",
1391                             ch);
1392         }
1393         self.bump();
1394         let content_start_bpos = self.last_pos;
1395         let mut content_end_bpos;
1396         'outer: loop {
1397             match self.curr {
1398                 None => {
1399                     let last_pos = self.last_pos;
1400                     self.fatal_span_(start_bpos, last_pos, "unterminated raw string")
1401                 },
1402                 Some('"') => {
1403                     content_end_bpos = self.last_pos;
1404                     for _ in range(0, hash_count) {
1405                         self.bump();
1406                         if !self.curr_is('#') {
1407                             continue 'outer;
1408                         }
1409                     }
1410                     break;
1411                 },
1412                 Some(c) => if c > '\x7F' {
1413                     let last_pos = self.last_pos;
1414                     self.err_span_char(
1415                         last_pos, last_pos, "raw byte string must be ASCII", c);
1416                 }
1417             }
1418             self.bump();
1419         }
1420         self.bump();
1421         return token::BinaryRaw(self.name_from_to(content_start_bpos,
1422                                                   content_end_bpos),
1423                                 hash_count);
1424     }
1425 }
1426
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,
1430         _ => false
1431     }
1432 }
1433
1434 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1435     match c {
1436         Some(c) => lo <= c && c <= hi,
1437         _ => false
1438     }
1439 }
1440
1441 fn is_dec_digit(c: Option<char>) -> bool { return in_range(c, '0', '9'); }
1442
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);
1447     res
1448 }
1449
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);
1454     res
1455 }
1456
1457 fn ident_start(c: Option<char>) -> bool {
1458     let c = match c { Some(c) => c, None => return false };
1459
1460     (c >= 'a' && c <= 'z')
1461         || (c >= 'A' && c <= 'Z')
1462         || c == '_'
1463         || (c > '\x7f' && c.is_xid_start())
1464 }
1465
1466 fn ident_continue(c: Option<char>) -> bool {
1467     let c = match c { Some(c) => c, None => return false };
1468
1469     (c >= 'a' && c <= 'z')
1470         || (c >= 'A' && c <= 'Z')
1471         || (c >= '0' && c <= '9')
1472         || c == '_'
1473         || (c > '\x7f' && c.is_xid_continue())
1474 }
1475
1476 #[cfg(test)]
1477 mod test {
1478     use super::*;
1479
1480     use codemap::{BytePos, CodeMap, Span, NO_EXPANSION};
1481     use diagnostic;
1482     use parse::token;
1483     use parse::token::{str_to_ident};
1484     use std::io::util;
1485
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())
1490     }
1491
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)
1497     }
1498
1499     #[test] fn t1 () {
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))
1523     }
1524
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);
1530         }
1531     }
1532
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)
1536     }
1537
1538     #[test] fn doublecolonparsing () {
1539         check_tokenization(setup(&mk_sh(), "a b".to_string()),
1540                            vec![mk_ident("a", token::Plain),
1541                                 token::Whitespace,
1542                                 mk_ident("b", token::Plain)]);
1543     }
1544
1545     #[test] fn dcparsing_2 () {
1546         check_tokenization(setup(&mk_sh(), "a::b".to_string()),
1547                            vec![mk_ident("a",token::ModName),
1548                                 token::ModSep,
1549                                 mk_ident("b", token::Plain)]);
1550     }
1551
1552     #[test] fn dcparsing_3 () {
1553         check_tokenization(setup(&mk_sh(), "a ::b".to_string()),
1554                            vec![mk_ident("a", token::Plain),
1555                                 token::Whitespace,
1556                                 token::ModSep,
1557                                 mk_ident("b", token::Plain)]);
1558     }
1559
1560     #[test] fn dcparsing_4 () {
1561         check_tokenization(setup(&mk_sh(), "a:: b".to_string()),
1562                            vec![mk_ident("a",token::ModName),
1563                                 token::ModSep,
1564                                 token::Whitespace,
1565                                 mk_ident("b", token::Plain)]);
1566     }
1567
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));
1571     }
1572
1573     #[test] fn character_space() {
1574         assert_eq!(setup(&mk_sh(), "' '".to_string()).next_token().tok,
1575                    token::Literal(token::Char(token::intern(" ")), None));
1576     }
1577
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));
1581     }
1582
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")));
1586     }
1587
1588     #[test] fn raw_string() {
1589         assert_eq!(setup(&mk_sh(),
1590                          "r###\"\"#a\\b\x00c\"\"###".to_string()).next_token()
1591                                                                  .tok,
1592                    token::Literal(token::StrRaw(token::intern("\"#a\\b\x00c\""), 3), None));
1593     }
1594
1595     #[test] fn literal_suffixes() {
1596         macro_rules! test {
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)),
1604                                           None));
1605             }}
1606         }
1607
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");
1617
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"))));
1627     }
1628
1629     #[test] fn line_doc_comments() {
1630         assert!(is_doc_comment("///"));
1631         assert!(is_doc_comment("/// blah"));
1632         assert!(!is_doc_comment("////"));
1633     }
1634
1635     #[test] fn nested_block_comments() {
1636         let sh = mk_sh();
1637         let mut lexer = setup(&sh, "/* /* */ */'a'".to_string());
1638         match lexer.next_token().tok {
1639             token::Comment => { },
1640             _ => panic!("expected a comment!")
1641         }
1642         assert_eq!(lexer.next_token().tok, token::Literal(token::Char(token::intern("a")), None));
1643     }
1644
1645 }