]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/lexer/mod.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[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::borrow::IntoCow;
20 use std::char;
21 use std::fmt;
22 use std::mem::replace;
23 use std::num;
24 use std::rc::Rc;
25 use std::str;
26 use std::string::CowString;
27
28 pub use ext::tt::transcribe::{TtReader, new_tt_reader, new_tt_reader_with_doc_flag};
29
30 pub mod comments;
31
32 pub trait Reader {
33     fn is_eof(&self) -> bool;
34     fn next_token(&mut self) -> TokenAndSpan;
35     /// Report a fatal error with the current span.
36     fn fatal(&self, &str) -> !;
37     /// Report a non-fatal error with the current span.
38     fn err(&self, &str);
39     fn peek(&self) -> TokenAndSpan;
40     /// Get a token the parser cares about.
41     fn real_token(&mut self) -> TokenAndSpan {
42         let mut t = self.next_token();
43         loop {
44             match t.tok {
45                 token::Whitespace | token::Comment | token::Shebang(_) => {
46                     t = self.next_token();
47                 },
48                 _ => break
49             }
50         }
51         t
52     }
53 }
54
55 #[derive(Clone, PartialEq, Eq, Debug)]
56 pub struct TokenAndSpan {
57     pub tok: token::Token,
58     pub sp: Span,
59 }
60
61 pub struct StringReader<'a> {
62     pub span_diagnostic: &'a SpanHandler,
63     /// The absolute offset within the codemap of the next character to read
64     pub pos: BytePos,
65     /// The absolute offset within the codemap of the last character read(curr)
66     pub last_pos: BytePos,
67     /// The column of the next character to read
68     pub col: CharPos,
69     /// The last character to be read
70     pub curr: Option<char>,
71     pub filemap: Rc<codemap::FileMap>,
72     /* cached: */
73     pub peek_tok: token::Token,
74     pub peek_span: Span,
75
76     // FIXME (Issue #16472): This field should go away after ToToken impls
77     // are revised to go directly to token-trees.
78     /// Is \x00<name>,<ctxt>\x00 is interpreted as encoded ast::Ident?
79     read_embedded_ident: bool,
80 }
81
82 impl<'a> Reader for StringReader<'a> {
83     fn is_eof(&self) -> bool { self.curr.is_none() }
84     /// Return the next token. EFFECT: advances the string_reader.
85     fn next_token(&mut self) -> TokenAndSpan {
86         let ret_val = TokenAndSpan {
87             tok: replace(&mut self.peek_tok, token::Underscore),
88             sp: self.peek_span,
89         };
90         self.advance_token();
91         ret_val
92     }
93     fn fatal(&self, m: &str) -> ! {
94         self.fatal_span(self.peek_span, m)
95     }
96     fn err(&self, m: &str) {
97         self.err_span(self.peek_span, m)
98     }
99     fn peek(&self) -> TokenAndSpan {
100         // FIXME(pcwalton): Bad copy!
101         TokenAndSpan {
102             tok: self.peek_tok.clone(),
103             sp: self.peek_span,
104         }
105     }
106 }
107
108 impl<'a> Reader for TtReader<'a> {
109     fn is_eof(&self) -> bool {
110         self.cur_tok == token::Eof
111     }
112     fn next_token(&mut self) -> TokenAndSpan {
113         let r = tt_next_token(self);
114         debug!("TtReader: r={:?}", r);
115         r
116     }
117     fn fatal(&self, m: &str) -> ! {
118         self.sp_diag.span_fatal(self.cur_span, m);
119     }
120     fn err(&self, m: &str) {
121         self.sp_diag.span_err(self.cur_span, m);
122     }
123     fn peek(&self) -> TokenAndSpan {
124         TokenAndSpan {
125             tok: self.cur_tok.clone(),
126             sp: self.cur_span,
127         }
128     }
129 }
130
131 // FIXME (Issue #16472): This function should go away after
132 // ToToken impls are revised to go directly to token-trees.
133 pub fn make_reader_with_embedded_idents<'b>(span_diagnostic: &'b SpanHandler,
134                                             filemap: Rc<codemap::FileMap>)
135                                             -> StringReader<'b> {
136     let mut sr = StringReader::new_raw(span_diagnostic, filemap);
137     sr.read_embedded_ident = true;
138     sr.advance_token();
139     sr
140 }
141
142 impl<'a> StringReader<'a> {
143     /// For comments.rs, which hackily pokes into pos and curr
144     pub fn new_raw<'b>(span_diagnostic: &'b SpanHandler,
145                    filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
146         let mut sr = StringReader {
147             span_diagnostic: span_diagnostic,
148             pos: filemap.start_pos,
149             last_pos: filemap.start_pos,
150             col: CharPos(0),
151             curr: Some('\n'),
152             filemap: filemap,
153             /* dummy values; not read */
154             peek_tok: token::Eof,
155             peek_span: codemap::DUMMY_SP,
156             read_embedded_ident: false,
157         };
158         sr.bump();
159         sr
160     }
161
162     pub fn new<'b>(span_diagnostic: &'b SpanHandler,
163                    filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
164         let mut sr = StringReader::new_raw(span_diagnostic, filemap);
165         sr.advance_token();
166         sr
167     }
168
169     pub fn curr_is(&self, c: char) -> bool {
170         self.curr == Some(c)
171     }
172
173     /// Report a fatal lexical error with a given span.
174     pub fn fatal_span(&self, sp: Span, m: &str) -> ! {
175         self.span_diagnostic.span_fatal(sp, m)
176     }
177
178     /// Report a lexical error with a given span.
179     pub fn err_span(&self, sp: Span, m: &str) {
180         self.span_diagnostic.span_err(sp, m)
181     }
182
183     /// Report a fatal error spanning [`from_pos`, `to_pos`).
184     fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
185         self.fatal_span(codemap::mk_sp(from_pos, to_pos), m)
186     }
187
188     /// Report a lexical error spanning [`from_pos`, `to_pos`).
189     fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
190         self.err_span(codemap::mk_sp(from_pos, to_pos), m)
191     }
192
193     /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
194     /// escaped character to the error message
195     fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> ! {
196         let mut m = m.to_string();
197         m.push_str(": ");
198         for c in c.escape_default() { m.push(c) }
199         self.fatal_span_(from_pos, to_pos, &m[]);
200     }
201
202     /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
203     /// escaped character to the error message
204     fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
205         let mut m = m.to_string();
206         m.push_str(": ");
207         for c in c.escape_default() { m.push(c) }
208         self.err_span_(from_pos, to_pos, &m[]);
209     }
210
211     /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
212     /// offending string to the error message
213     fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> ! {
214         m.push_str(": ");
215         let from = self.byte_offset(from_pos).to_usize();
216         let to = self.byte_offset(to_pos).to_usize();
217         m.push_str(&self.filemap.src[from..to]);
218         self.fatal_span_(from_pos, to_pos, &m[]);
219     }
220
221     /// Advance peek_tok and peek_span to refer to the next token, and
222     /// possibly update the interner.
223     fn advance_token(&mut self) {
224         match self.scan_whitespace_or_comment() {
225             Some(comment) => {
226                 self.peek_span = comment.sp;
227                 self.peek_tok = comment.tok;
228             },
229             None => {
230                 if self.is_eof() {
231                     self.peek_tok = token::Eof;
232                 } else {
233                     let start_bytepos = self.last_pos;
234                     self.peek_tok = self.next_token_inner();
235                     self.peek_span = codemap::mk_sp(start_bytepos,
236                                                     self.last_pos);
237                 };
238             }
239         }
240     }
241
242     fn byte_offset(&self, pos: BytePos) -> BytePos {
243         (pos - self.filemap.start_pos)
244     }
245
246     /// Calls `f` with a string slice of the source text spanning from `start`
247     /// up to but excluding `self.last_pos`, meaning the slice does not include
248     /// the character `self.curr`.
249     pub fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T where
250         F: FnOnce(&str) -> T,
251     {
252         self.with_str_from_to(start, self.last_pos, f)
253     }
254
255     /// Create a Name from a given offset to the current offset, each
256     /// adjusted 1 towards each other (assumes that on either side there is a
257     /// single-byte delimiter).
258     pub fn name_from(&self, start: BytePos) -> ast::Name {
259         debug!("taking an ident from {:?} to {:?}", start, self.last_pos);
260         self.with_str_from(start, token::intern)
261     }
262
263     /// As name_from, with an explicit endpoint.
264     pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
265         debug!("taking an ident from {:?} to {:?}", start, end);
266         self.with_str_from_to(start, end, token::intern)
267     }
268
269     /// Calls `f` with a string slice of the source text spanning from `start`
270     /// up to but excluding `end`.
271     fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T where
272         F: FnOnce(&str) -> T,
273     {
274         f(&self.filemap.src[
275                 self.byte_offset(start).to_usize()..
276                 self.byte_offset(end).to_usize()])
277     }
278
279     /// Converts CRLF to LF in the given string, raising an error on bare CR.
280     fn translate_crlf<'b>(&self, start: BytePos,
281                           s: &'b str, errmsg: &'b str) -> CowString<'b> {
282         let mut i = 0;
283         while i < s.len() {
284             let str::CharRange { ch, next } = s.char_range_at(i);
285             if ch == '\r' {
286                 if next < s.len() && s.char_at(next) == '\n' {
287                     return translate_crlf_(self, start, s, errmsg, i).into_cow();
288                 }
289                 let pos = start + BytePos(i as u32);
290                 let end_pos = start + BytePos(next as u32);
291                 self.err_span_(pos, end_pos, errmsg);
292             }
293             i = next;
294         }
295         return s.into_cow();
296
297         fn translate_crlf_(rdr: &StringReader, start: BytePos,
298                         s: &str, errmsg: &str, mut i: usize) -> String {
299             let mut buf = String::with_capacity(s.len());
300             let mut j = 0;
301             while i < s.len() {
302                 let str::CharRange { ch, next } = s.char_range_at(i);
303                 if ch == '\r' {
304                     if j < i { buf.push_str(&s[j..i]); }
305                     j = next;
306                     if next >= s.len() || s.char_at(next) != '\n' {
307                         let pos = start + BytePos(i as u32);
308                         let end_pos = start + BytePos(next as u32);
309                         rdr.err_span_(pos, end_pos, errmsg);
310                     }
311                 }
312                 i = next;
313             }
314             if j < s.len() { buf.push_str(&s[j..]); }
315             buf
316         }
317     }
318
319
320     /// Advance the StringReader by one character. If a newline is
321     /// discovered, add it to the FileMap's list of line start offsets.
322     pub fn bump(&mut self) {
323         self.last_pos = self.pos;
324         let current_byte_offset = self.byte_offset(self.pos).to_usize();
325         if current_byte_offset < self.filemap.src.len() {
326             assert!(self.curr.is_some());
327             let last_char = self.curr.unwrap();
328             let next = self.filemap
329                           .src
330                           .char_range_at(current_byte_offset);
331             let byte_offset_diff = next.next - current_byte_offset;
332             self.pos = self.pos + Pos::from_usize(byte_offset_diff);
333             self.curr = Some(next.ch);
334             self.col = self.col + CharPos(1);
335             if last_char == '\n' {
336                 self.filemap.next_line(self.last_pos);
337                 self.col = CharPos(0);
338             }
339
340             if byte_offset_diff > 1 {
341                 self.filemap.record_multibyte_char(self.last_pos, byte_offset_diff);
342             }
343         } else {
344             self.curr = None;
345         }
346     }
347
348     pub fn nextch(&self) -> Option<char> {
349         let offset = self.byte_offset(self.pos).to_usize();
350         if offset < self.filemap.src.len() {
351             Some(self.filemap.src.char_at(offset))
352         } else {
353             None
354         }
355     }
356
357     pub fn nextch_is(&self, c: char) -> bool {
358         self.nextch() == Some(c)
359     }
360
361     pub fn nextnextch(&self) -> Option<char> {
362         let offset = self.byte_offset(self.pos).to_usize();
363         let s = &*self.filemap.src;
364         if offset >= s.len() { return None }
365         let str::CharRange { next, .. } = s.char_range_at(offset);
366         if next < s.len() {
367             Some(s.char_at(next))
368         } else {
369             None
370         }
371     }
372
373     pub fn nextnextch_is(&self, c: char) -> bool {
374         self.nextnextch() == Some(c)
375     }
376
377     /// Eats <XID_start><XID_continue>*, if possible.
378     fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
379         if !ident_start(self.curr) {
380             return None
381         }
382         let start = self.last_pos;
383         while ident_continue(self.curr) {
384             self.bump();
385         }
386
387         self.with_str_from(start, |string| {
388             if string == "_" {
389                 None
390             } else {
391                 Some(token::intern(string))
392             }
393         })
394     }
395
396     /// PRECONDITION: self.curr is not whitespace
397     /// Eats any kind of comment.
398     fn scan_comment(&mut self) -> Option<TokenAndSpan> {
399         match self.curr {
400             Some(c) => {
401                 if c.is_whitespace() {
402                     self.span_diagnostic.span_err(codemap::mk_sp(self.last_pos, self.last_pos),
403                                     "called consume_any_line_comment, but there was whitespace");
404                 }
405             },
406             None => { }
407         }
408
409         if self.curr_is('/') {
410             match self.nextch() {
411                 Some('/') => {
412                     self.bump();
413                     self.bump();
414                     // line comments starting with "///" or "//!" are doc-comments
415                     if self.curr_is('/') || self.curr_is('!') {
416                         let start_bpos = self.pos - BytePos(3);
417                         while !self.is_eof() {
418                             match self.curr.unwrap() {
419                                 '\n' => break,
420                                 '\r' => {
421                                     if self.nextch_is('\n') {
422                                         // CRLF
423                                         break
424                                     } else {
425                                         self.err_span_(self.last_pos, self.pos,
426                                                        "bare CR not allowed in doc-comment");
427                                     }
428                                 }
429                                 _ => ()
430                             }
431                             self.bump();
432                         }
433                         return self.with_str_from(start_bpos, |string| {
434                             // but comments with only more "/"s are not
435                             let tok = if is_doc_comment(string) {
436                                 token::DocComment(token::intern(string))
437                             } else {
438                                 token::Comment
439                             };
440
441                             return Some(TokenAndSpan{
442                                 tok: tok,
443                                 sp: codemap::mk_sp(start_bpos, self.last_pos)
444                             });
445                         });
446                     } else {
447                         let start_bpos = self.last_pos - BytePos(2);
448                         while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
449                         return Some(TokenAndSpan {
450                             tok: token::Comment,
451                             sp: codemap::mk_sp(start_bpos, self.last_pos)
452                         });
453                     }
454                 }
455                 Some('*') => {
456                     self.bump(); self.bump();
457                     self.scan_block_comment()
458                 }
459                 _ => None
460             }
461         } else if self.curr_is('#') {
462             if self.nextch_is('!') {
463
464                 // Parse an inner attribute.
465                 if self.nextnextch_is('[') {
466                     return None;
467                 }
468
469                 // I guess this is the only way to figure out if
470                 // we're at the beginning of the file...
471                 let cmap = CodeMap::new();
472                 cmap.files.borrow_mut().push(self.filemap.clone());
473                 let loc = cmap.lookup_char_pos_adj(self.last_pos);
474                 debug!("Skipping a shebang");
475                 if loc.line == 1 && loc.col == CharPos(0) {
476                     // FIXME: Add shebang "token", return it
477                     let start = self.last_pos;
478                     while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
479                     return Some(TokenAndSpan {
480                         tok: token::Shebang(self.name_from(start)),
481                         sp: codemap::mk_sp(start, self.last_pos)
482                     });
483                 }
484             }
485             None
486         } else {
487             None
488         }
489     }
490
491     /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
492     /// return None.
493     fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
494         match self.curr.unwrap_or('\0') {
495             // # to handle shebang at start of file -- this is the entry point
496             // for skipping over all "junk"
497             '/' | '#' => {
498                 let c = self.scan_comment();
499                 debug!("scanning a comment {:?}", c);
500                 c
501             },
502             c if is_whitespace(Some(c)) => {
503                 let start_bpos = self.last_pos;
504                 while is_whitespace(self.curr) { self.bump(); }
505                 let c = Some(TokenAndSpan {
506                     tok: token::Whitespace,
507                     sp: codemap::mk_sp(start_bpos, self.last_pos)
508                 });
509                 debug!("scanning whitespace: {:?}", c);
510                 c
511             },
512             _ => None
513         }
514     }
515
516     /// Might return a sugared-doc-attr
517     fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
518         // block comments starting with "/**" or "/*!" are doc-comments
519         let is_doc_comment = self.curr_is('*') || self.curr_is('!');
520         let start_bpos = self.last_pos - BytePos(2);
521
522         let mut level: isize = 1;
523         let mut has_cr = false;
524         while level > 0 {
525             if self.is_eof() {
526                 let msg = if is_doc_comment {
527                     "unterminated block doc-comment"
528                 } else {
529                     "unterminated block comment"
530                 };
531                 let last_bpos = self.last_pos;
532                 self.fatal_span_(start_bpos, last_bpos, msg);
533             }
534             let n = self.curr.unwrap();
535             match n {
536                 '/' if self.nextch_is('*') => {
537                     level += 1;
538                     self.bump();
539                 }
540                 '*' if self.nextch_is('/') => {
541                     level -= 1;
542                     self.bump();
543                 }
544                 '\r' => {
545                     has_cr = true;
546                 }
547                 _ => ()
548             }
549             self.bump();
550         }
551
552         self.with_str_from(start_bpos, |string| {
553             // but comments with only "*"s between two "/"s are not
554             let tok = if is_block_doc_comment(string) {
555                 let string = if has_cr {
556                     self.translate_crlf(start_bpos, string,
557                                         "bare CR not allowed in block doc-comment")
558                 } else { string.into_cow() };
559                 token::DocComment(token::intern(&string[]))
560             } else {
561                 token::Comment
562             };
563
564             Some(TokenAndSpan{
565                 tok: tok,
566                 sp: codemap::mk_sp(start_bpos, self.last_pos)
567             })
568         })
569     }
570
571     // FIXME (Issue #16472): The scan_embedded_hygienic_ident function
572     // should go away after we revise the syntax::ext::quote::ToToken
573     // impls to go directly to token-trees instead of thing -> string
574     // -> token-trees.  (The function is currently used to resolve
575     // Issues #15750 and #15962.)
576     //
577     // Since this function is only used for certain internal macros,
578     // and the functionality it provides is not exposed to end user
579     // programs, pnkfelix deliberately chose to write it in a way that
580     // favors rustc debugging effectiveness over runtime efficiency.
581
582     /// Scan through input of form \x00name_NNNNNN,ctxt_CCCCCCC\x00
583     /// whence: `NNNNNN` is a string of characters forming an integer
584     /// (the name) and `CCCCCCC` is a string of characters forming an
585     /// integer (the ctxt), separate by a comma and delimited by a
586     /// `\x00` marker.
587     #[inline(never)]
588     fn scan_embedded_hygienic_ident(&mut self) -> ast::Ident {
589         fn bump_expecting_char<'a,D:fmt::Debug>(r: &mut StringReader<'a>,
590                                                 c: char,
591                                                 described_c: D,
592                                                 whence: &str) {
593             match r.curr {
594                 Some(r_c) if r_c == c => r.bump(),
595                 Some(r_c) => panic!("expected {:?}, hit {:?}, {}", described_c, r_c, whence),
596                 None      => panic!("expected {:?}, hit EOF, {}", described_c, whence),
597             }
598         }
599
600         let whence = "while scanning embedded hygienic ident";
601
602         // skip over the leading `\x00`
603         bump_expecting_char(self, '\x00', "nul-byte", whence);
604
605         // skip over the "name_"
606         for c in "name_".chars() {
607             bump_expecting_char(self, c, c, whence);
608         }
609
610         let start_bpos = self.last_pos;
611         let base = 10;
612
613         // find the integer representing the name
614         self.scan_digits(base);
615         let encoded_name : u32 = self.with_str_from(start_bpos, |s| {
616             num::from_str_radix(s, 10).ok().unwrap_or_else(|| {
617                 panic!("expected digits representing a name, got {:?}, {}, range [{:?},{:?}]",
618                       s, whence, start_bpos, self.last_pos);
619             })
620         });
621
622         // skip over the `,`
623         bump_expecting_char(self, ',', "comma", whence);
624
625         // skip over the "ctxt_"
626         for c in "ctxt_".chars() {
627             bump_expecting_char(self, c, c, whence);
628         }
629
630         // find the integer representing the ctxt
631         let start_bpos = self.last_pos;
632         self.scan_digits(base);
633         let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| {
634             num::from_str_radix(s, 10).ok().unwrap_or_else(|| {
635                 panic!("expected digits representing a ctxt, got {:?}, {}", s, whence);
636             })
637         });
638
639         // skip over the `\x00`
640         bump_expecting_char(self, '\x00', "nul-byte", whence);
641
642         ast::Ident { name: ast::Name(encoded_name),
643                      ctxt: encoded_ctxt, }
644     }
645
646     /// Scan through any digits (base `radix`) or underscores, and return how
647     /// many digits there were.
648     fn scan_digits(&mut self, radix: u32) -> usize {
649         let mut len = 0;
650         loop {
651             let c = self.curr;
652             if c == Some('_') { debug!("skipping a _"); self.bump(); continue; }
653             match c.and_then(|cc| cc.to_digit(radix)) {
654                 Some(_) => {
655                     debug!("{:?} in scan_digits", c);
656                     len += 1;
657                     self.bump();
658                 }
659                 _ => return len
660             }
661         };
662     }
663
664     /// Lex a LIT_INTEGER or a LIT_FLOAT
665     fn scan_number(&mut self, c: char) -> token::Lit {
666         let mut num_digits;
667         let mut base = 10;
668         let start_bpos = self.last_pos;
669
670         self.bump();
671
672         if c == '0' {
673             match self.curr.unwrap_or('\0') {
674                 'b' => { self.bump(); base = 2; num_digits = self.scan_digits(2); }
675                 'o' => { self.bump(); base = 8; num_digits = self.scan_digits(8); }
676                 'x' => { self.bump(); base = 16; num_digits = self.scan_digits(16); }
677                 '0'...'9' | '_' | '.' => {
678                     num_digits = self.scan_digits(10) + 1;
679                 }
680                 _ => {
681                     // just a 0
682                     return token::Integer(self.name_from(start_bpos));
683                 }
684             }
685         } else if c.is_digit(10) {
686             num_digits = self.scan_digits(10) + 1;
687         } else {
688             num_digits = 0;
689         }
690
691         if num_digits == 0 {
692             self.err_span_(start_bpos, self.last_pos, "no valid digits found for number");
693             return token::Integer(token::intern("0"));
694         }
695
696         // might be a float, but don't be greedy if this is actually an
697         // integer literal followed by field/method access or a range pattern
698         // (`0..2` and `12.foo()`)
699         if self.curr_is('.') && !self.nextch_is('.') && !self.nextch().unwrap_or('\0')
700                                                              .is_xid_start() {
701             // might have stuff after the ., and if it does, it needs to start
702             // with a number
703             self.bump();
704             if self.curr.unwrap_or('\0').is_digit(10) {
705                 self.scan_digits(10);
706                 self.scan_float_exponent();
707             }
708             let last_pos = self.last_pos;
709             self.check_float_base(start_bpos, last_pos, base);
710             return token::Float(self.name_from(start_bpos));
711         } else {
712             // it might be a float if it has an exponent
713             if self.curr_is('e') || self.curr_is('E') {
714                 self.scan_float_exponent();
715                 let last_pos = self.last_pos;
716                 self.check_float_base(start_bpos, last_pos, base);
717                 return token::Float(self.name_from(start_bpos));
718             }
719             // but we certainly have an integer!
720             return token::Integer(self.name_from(start_bpos));
721         }
722     }
723
724     /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
725     /// error if too many or too few digits are encountered.
726     fn scan_hex_digits(&mut self,
727                        n_digits: usize,
728                        delim: char,
729                        below_0x7f_only: bool)
730                        -> bool {
731         debug!("scanning {} digits until {:?}", n_digits, delim);
732         let start_bpos = self.last_pos;
733         let mut accum_int = 0;
734
735         for _ in 0..n_digits {
736             if self.is_eof() {
737                 let last_bpos = self.last_pos;
738                 self.fatal_span_(start_bpos, last_bpos, "unterminated numeric character escape");
739             }
740             if self.curr_is(delim) {
741                 let last_bpos = self.last_pos;
742                 self.err_span_(start_bpos, last_bpos, "numeric character escape is too short");
743                 break;
744             }
745             let c = self.curr.unwrap_or('\x00');
746             accum_int *= 16;
747             accum_int += c.to_digit(16).unwrap_or_else(|| {
748                 self.err_span_char(self.last_pos, self.pos,
749                               "illegal character in numeric character escape", c);
750                 0
751             }) as u32;
752             self.bump();
753         }
754
755         if below_0x7f_only && accum_int >= 0x80 {
756             self.err_span_(start_bpos,
757                            self.last_pos,
758                            "this form of character escape may only be used \
759                             with characters in the range [\\x00-\\x7f]");
760         }
761
762         match char::from_u32(accum_int) {
763             Some(_) => true,
764             None => {
765                 let last_bpos = self.last_pos;
766                 self.err_span_(start_bpos, last_bpos, "illegal numeric character escape");
767                 false
768             }
769         }
770     }
771
772     fn old_escape_warning(&mut self, sp: Span) {
773         self.span_diagnostic
774             .span_warn(sp, "\\U00ABCD12 and \\uABCD escapes are deprecated");
775         self.span_diagnostic
776             .span_help(sp, "use \\u{ABCD12} escapes instead");
777     }
778
779     /// Scan for a single (possibly escaped) byte or char
780     /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
781     /// `start` is the position of `first_source_char`, which is already consumed.
782     ///
783     /// Returns true if there was a valid char/byte, false otherwise.
784     fn scan_char_or_byte(&mut self, start: BytePos, first_source_char: char,
785                          ascii_only: bool, delim: char) -> bool {
786         match first_source_char {
787             '\\' => {
788                 // '\X' for some X must be a character constant:
789                 let escaped = self.curr;
790                 let escaped_pos = self.last_pos;
791                 self.bump();
792                 match escaped {
793                     None => {},  // EOF here is an error that will be checked later.
794                     Some(e) => {
795                         return match e {
796                             'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
797                             'x' => self.scan_byte_escape(delim, !ascii_only),
798                             'u' if !ascii_only => {
799                                 if self.curr == Some('{') {
800                                     self.scan_unicode_escape(delim)
801                                 } else {
802                                     let res = self.scan_hex_digits(4, delim, false);
803                                     let sp = codemap::mk_sp(escaped_pos, self.last_pos);
804                                     self.old_escape_warning(sp);
805                                     res
806                                 }
807                             }
808                             'U' if !ascii_only => {
809                                 let res = self.scan_hex_digits(8, delim, false);
810                                 let sp = codemap::mk_sp(escaped_pos, self.last_pos);
811                                 self.old_escape_warning(sp);
812                                 res
813                             }
814                             '\n' if delim == '"' => {
815                                 self.consume_whitespace();
816                                 true
817                             },
818                             '\r' if delim == '"' && self.curr_is('\n') => {
819                                 self.consume_whitespace();
820                                 true
821                             }
822                             c => {
823                                 let last_pos = self.last_pos;
824                                 self.err_span_char(
825                                     escaped_pos, last_pos,
826                                     if ascii_only { "unknown byte escape" }
827                                     else { "unknown character escape" },
828                                     c);
829                                 if e == '\r' {
830                                     let sp = codemap::mk_sp(escaped_pos, last_pos);
831                                     self.span_diagnostic.span_help(
832                                         sp,
833                                         "this is an isolated carriage return; consider checking \
834                                          your editor and version control settings")
835                                 }
836                                 false
837                             }
838                         }
839                     }
840                 }
841             }
842             '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
843                 let last_pos = self.last_pos;
844                 self.err_span_char(
845                     start, last_pos,
846                     if ascii_only { "byte constant must be escaped" }
847                     else { "character constant must be escaped" },
848                     first_source_char);
849                 return false;
850             }
851             '\r' => {
852                 if self.curr_is('\n') {
853                     self.bump();
854                     return true;
855                 } else {
856                     self.err_span_(start, self.last_pos,
857                                    "bare CR not allowed in string, use \\r instead");
858                     return false;
859                 }
860             }
861             _ => if ascii_only && first_source_char > '\x7F' {
862                 let last_pos = self.last_pos;
863                 self.err_span_char(
864                     start, last_pos,
865                     "byte constant must be ASCII. \
866                      Use a \\xHH escape for a non-ASCII byte", first_source_char);
867                 return false;
868             }
869         }
870         true
871     }
872
873     /// Scan over a \u{...} escape
874     ///
875     /// At this point, we have already seen the \ and the u, the { is the current character. We
876     /// will read at least one digit, and up to 6, and pass over the }.
877     fn scan_unicode_escape(&mut self, delim: char) -> bool {
878         self.bump(); // past the {
879         let start_bpos = self.last_pos;
880         let mut count = 0;
881         let mut accum_int = 0;
882
883         while !self.curr_is('}') && count <= 6 {
884             let c = match self.curr {
885                 Some(c) => c,
886                 None => {
887                     self.fatal_span_(start_bpos, self.last_pos,
888                                      "unterminated unicode escape (found EOF)");
889                 }
890             };
891             accum_int *= 16;
892             accum_int += c.to_digit(16).unwrap_or_else(|| {
893                 if c == delim {
894                     self.fatal_span_(self.last_pos, self.pos,
895                                      "unterminated unicode escape (needed a `}`)");
896                 } else {
897                     self.fatal_span_char(self.last_pos, self.pos,
898                                    "illegal character in unicode escape", c);
899                 }
900             }) as u32;
901             self.bump();
902             count += 1;
903         }
904
905         if count > 6 {
906             self.fatal_span_(start_bpos, self.last_pos,
907                           "overlong unicode escape (can have at most 6 hex digits)");
908         }
909
910         self.bump(); // past the ending }
911
912         let mut valid = count >= 1 && count <= 6;
913         if char::from_u32(accum_int).is_none() {
914             valid = false;
915         }
916
917         if !valid {
918             self.fatal_span_(start_bpos, self.last_pos, "illegal unicode character escape");
919         }
920         valid
921     }
922
923     /// Scan over a float exponent.
924     fn scan_float_exponent(&mut self) {
925         if self.curr_is('e') || self.curr_is('E') {
926             self.bump();
927             if self.curr_is('-') || self.curr_is('+') {
928                 self.bump();
929             }
930             if self.scan_digits(10) == 0 {
931                 self.err_span_(self.last_pos, self.pos, "expected at least one digit in exponent")
932             }
933         }
934     }
935
936     /// Check that a base is valid for a floating literal, emitting a nice
937     /// error if it isn't.
938     fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
939         match base {
940             16 => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \
941                                    supported"),
942             8 => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"),
943             2 => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"),
944             _   => ()
945         }
946     }
947
948     fn binop(&mut self, op: token::BinOpToken) -> token::Token {
949         self.bump();
950         if self.curr_is('=') {
951             self.bump();
952             return token::BinOpEq(op);
953         } else {
954             return token::BinOp(op);
955         }
956     }
957
958     /// Return the next token from the string, advances the input past that
959     /// token, and updates the interner
960     fn next_token_inner(&mut self) -> token::Token {
961         let c = self.curr;
962         if ident_start(c) && match (c.unwrap(), self.nextch(), self.nextnextch()) {
963             // Note: r as in r" or r#" is part of a raw string literal,
964             // b as in b' is part of a byte literal.
965             // They are not identifiers, and are handled further down.
966            ('r', Some('"'), _) | ('r', Some('#'), _) |
967            ('b', Some('"'), _) | ('b', Some('\''), _) |
968            ('b', Some('r'), Some('"')) | ('b', Some('r'), Some('#')) => false,
969            _ => true
970         } {
971             let start = self.last_pos;
972             while ident_continue(self.curr) {
973                 self.bump();
974             }
975
976             return self.with_str_from(start, |string| {
977                 if string == "_" {
978                     token::Underscore
979                 } else {
980                     // FIXME: perform NFKC normalization here. (Issue #2253)
981                     if self.curr_is(':') && self.nextch_is(':') {
982                         token::Ident(str_to_ident(string), token::ModName)
983                     } else {
984                         token::Ident(str_to_ident(string), token::Plain)
985                     }
986                 }
987             });
988         }
989
990         if is_dec_digit(c) {
991             let num = self.scan_number(c.unwrap());
992             let suffix = self.scan_optional_raw_name();
993             debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
994             return token::Literal(num, suffix)
995         }
996
997         if self.read_embedded_ident {
998             match (c.unwrap(), self.nextch(), self.nextnextch()) {
999                 ('\x00', Some('n'), Some('a')) => {
1000                     let ast_ident = self.scan_embedded_hygienic_ident();
1001                     return if self.curr_is(':') && self.nextch_is(':') {
1002                         token::Ident(ast_ident, token::ModName)
1003                     } else {
1004                         token::Ident(ast_ident, token::Plain)
1005                     };
1006                 }
1007                 _ => {}
1008             }
1009         }
1010
1011         match c.expect("next_token_inner called at EOF") {
1012           // One-byte tokens.
1013           ';' => { self.bump(); return token::Semi; }
1014           ',' => { self.bump(); return token::Comma; }
1015           '.' => {
1016               self.bump();
1017               return if self.curr_is('.') {
1018                   self.bump();
1019                   if self.curr_is('.') {
1020                       self.bump();
1021                       token::DotDotDot
1022                   } else {
1023                       token::DotDot
1024                   }
1025               } else {
1026                   token::Dot
1027               };
1028           }
1029           '(' => { self.bump(); return token::OpenDelim(token::Paren); }
1030           ')' => { self.bump(); return token::CloseDelim(token::Paren); }
1031           '{' => { self.bump(); return token::OpenDelim(token::Brace); }
1032           '}' => { self.bump(); return token::CloseDelim(token::Brace); }
1033           '[' => { self.bump(); return token::OpenDelim(token::Bracket); }
1034           ']' => { self.bump(); return token::CloseDelim(token::Bracket); }
1035           '@' => { self.bump(); return token::At; }
1036           '#' => { self.bump(); return token::Pound; }
1037           '~' => { self.bump(); return token::Tilde; }
1038           '?' => { self.bump(); return token::Question; }
1039           ':' => {
1040             self.bump();
1041             if self.curr_is(':') {
1042                 self.bump();
1043                 return token::ModSep;
1044             } else {
1045                 return token::Colon;
1046             }
1047           }
1048
1049           '$' => { self.bump(); return token::Dollar; }
1050
1051           // Multi-byte tokens.
1052           '=' => {
1053             self.bump();
1054             if self.curr_is('=') {
1055                 self.bump();
1056                 return token::EqEq;
1057             } else if self.curr_is('>') {
1058                 self.bump();
1059                 return token::FatArrow;
1060             } else {
1061                 return token::Eq;
1062             }
1063           }
1064           '!' => {
1065             self.bump();
1066             if self.curr_is('=') {
1067                 self.bump();
1068                 return token::Ne;
1069             } else { return token::Not; }
1070           }
1071           '<' => {
1072             self.bump();
1073             match self.curr.unwrap_or('\x00') {
1074               '=' => { self.bump(); return token::Le; }
1075               '<' => { return self.binop(token::Shl); }
1076               '-' => {
1077                 self.bump();
1078                 match self.curr.unwrap_or('\x00') {
1079                   _ => { return token::LArrow; }
1080                 }
1081               }
1082               _ => { return token::Lt; }
1083             }
1084           }
1085           '>' => {
1086             self.bump();
1087             match self.curr.unwrap_or('\x00') {
1088               '=' => { self.bump(); return token::Ge; }
1089               '>' => { return self.binop(token::Shr); }
1090               _ => { return token::Gt; }
1091             }
1092           }
1093           '\'' => {
1094             // Either a character constant 'a' OR a lifetime name 'abc
1095             self.bump();
1096             let start = self.last_pos;
1097
1098             // the eof will be picked up by the final `'` check below
1099             let c2 = self.curr.unwrap_or('\x00');
1100             self.bump();
1101
1102             // If the character is an ident start not followed by another single
1103             // quote, then this is a lifetime name:
1104             if ident_start(Some(c2)) && !self.curr_is('\'') {
1105                 while ident_continue(self.curr) {
1106                     self.bump();
1107                 }
1108
1109                 // Include the leading `'` in the real identifier, for macro
1110                 // expansion purposes. See #12512 for the gory details of why
1111                 // this is necessary.
1112                 let ident = self.with_str_from(start, |lifetime_name| {
1113                     str_to_ident(&format!("'{}", lifetime_name)[])
1114                 });
1115
1116                 // Conjure up a "keyword checking ident" to make sure that
1117                 // the lifetime name is not a keyword.
1118                 let keyword_checking_ident =
1119                     self.with_str_from(start, |lifetime_name| {
1120                         str_to_ident(lifetime_name)
1121                     });
1122                 let keyword_checking_token =
1123                     &token::Ident(keyword_checking_ident, token::Plain);
1124                 let last_bpos = self.last_pos;
1125                 if keyword_checking_token.is_keyword(token::keywords::SelfValue) {
1126                     self.err_span_(start,
1127                                    last_bpos,
1128                                    "invalid lifetime name: 'self \
1129                                     is no longer a special lifetime");
1130                 } else if keyword_checking_token.is_any_keyword() &&
1131                     !keyword_checking_token.is_keyword(token::keywords::Static)
1132                 {
1133                     self.err_span_(start,
1134                                    last_bpos,
1135                                    "invalid lifetime name");
1136                 }
1137                 return token::Lifetime(ident);
1138             }
1139
1140             // Otherwise it is a character constant:
1141             let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ false, '\'');
1142             if !self.curr_is('\'') {
1143                 let last_bpos = self.last_pos;
1144                 self.fatal_span_verbose(
1145                                    // Byte offsetting here is okay because the
1146                                    // character before position `start` is an
1147                                    // ascii single quote.
1148                                    start - BytePos(1), last_bpos,
1149                                    "unterminated character constant".to_string());
1150             }
1151             let id = if valid { self.name_from(start) } else { token::intern("0") };
1152             self.bump(); // advance curr past token
1153             let suffix = self.scan_optional_raw_name();
1154             return token::Literal(token::Char(id), suffix);
1155           }
1156           'b' => {
1157             self.bump();
1158             let lit = match self.curr {
1159                 Some('\'') => self.scan_byte(),
1160                 Some('"') => self.scan_byte_string(),
1161                 Some('r') => self.scan_raw_byte_string(),
1162                 _ => unreachable!()  // Should have been a token::Ident above.
1163             };
1164             let suffix = self.scan_optional_raw_name();
1165             return token::Literal(lit, suffix);
1166           }
1167           '"' => {
1168             let start_bpos = self.last_pos;
1169             let mut valid = true;
1170             self.bump();
1171             while !self.curr_is('"') {
1172                 if self.is_eof() {
1173                     let last_bpos = self.last_pos;
1174                     self.fatal_span_(start_bpos, last_bpos, "unterminated double quote string");
1175                 }
1176
1177                 let ch_start = self.last_pos;
1178                 let ch = self.curr.unwrap();
1179                 self.bump();
1180                 valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ false, '"');
1181             }
1182             // adjust for the ASCII " at the start of the literal
1183             let id = if valid { self.name_from(start_bpos + BytePos(1)) }
1184                      else { token::intern("??") };
1185             self.bump();
1186             let suffix = self.scan_optional_raw_name();
1187             return token::Literal(token::Str_(id), suffix);
1188           }
1189           'r' => {
1190             let start_bpos = self.last_pos;
1191             self.bump();
1192             let mut hash_count = 0;
1193             while self.curr_is('#') {
1194                 self.bump();
1195                 hash_count += 1;
1196             }
1197
1198             if self.is_eof() {
1199                 let last_bpos = self.last_pos;
1200                 self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
1201             } else if !self.curr_is('"') {
1202                 let last_bpos = self.last_pos;
1203                 let curr_char = self.curr.unwrap();
1204                 self.fatal_span_char(start_bpos, last_bpos,
1205                                 "only `#` is allowed in raw string delimitation; \
1206                                  found illegal character",
1207                                 curr_char);
1208             }
1209             self.bump();
1210             let content_start_bpos = self.last_pos;
1211             let mut content_end_bpos;
1212             let mut valid = true;
1213             'outer: loop {
1214                 if self.is_eof() {
1215                     let last_bpos = self.last_pos;
1216                     self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
1217                 }
1218                 //if self.curr_is('"') {
1219                     //content_end_bpos = self.last_pos;
1220                     //for _ in 0..hash_count {
1221                         //self.bump();
1222                         //if !self.curr_is('#') {
1223                             //continue 'outer;
1224                 let c = self.curr.unwrap();
1225                 match c {
1226                     '"' => {
1227                         content_end_bpos = self.last_pos;
1228                         for _ in 0..hash_count {
1229                             self.bump();
1230                             if !self.curr_is('#') {
1231                                 continue 'outer;
1232                             }
1233                         }
1234                         break;
1235                     },
1236                     '\r' => {
1237                         if !self.nextch_is('\n') {
1238                             let last_bpos = self.last_pos;
1239                             self.err_span_(start_bpos, last_bpos, "bare CR not allowed in raw \
1240                                            string, use \\r instead");
1241                             valid = false;
1242                         }
1243                     }
1244                     _ => ()
1245                 }
1246                 self.bump();
1247             }
1248             self.bump();
1249             let id = if valid {
1250                 self.name_from_to(content_start_bpos, content_end_bpos)
1251             } else {
1252                 token::intern("??")
1253             };
1254             let suffix = self.scan_optional_raw_name();
1255             return token::Literal(token::StrRaw(id, hash_count), suffix);
1256           }
1257           '-' => {
1258             if self.nextch_is('>') {
1259                 self.bump();
1260                 self.bump();
1261                 return token::RArrow;
1262             } else { return self.binop(token::Minus); }
1263           }
1264           '&' => {
1265             if self.nextch_is('&') {
1266                 self.bump();
1267                 self.bump();
1268                 return token::AndAnd;
1269             } else { return self.binop(token::And); }
1270           }
1271           '|' => {
1272             match self.nextch() {
1273               Some('|') => { self.bump(); self.bump(); return token::OrOr; }
1274               _ => { return self.binop(token::Or); }
1275             }
1276           }
1277           '+' => { return self.binop(token::Plus); }
1278           '*' => { return self.binop(token::Star); }
1279           '/' => { return self.binop(token::Slash); }
1280           '^' => { return self.binop(token::Caret); }
1281           '%' => { return self.binop(token::Percent); }
1282           c => {
1283               let last_bpos = self.last_pos;
1284               let bpos = self.pos;
1285               self.fatal_span_char(last_bpos, bpos, "unknown start of token", c);
1286           }
1287         }
1288     }
1289
1290     fn consume_whitespace(&mut self) {
1291         while is_whitespace(self.curr) && !self.is_eof() { self.bump(); }
1292     }
1293
1294     fn read_to_eol(&mut self) -> String {
1295         let mut val = String::new();
1296         while !self.curr_is('\n') && !self.is_eof() {
1297             val.push(self.curr.unwrap());
1298             self.bump();
1299         }
1300         if self.curr_is('\n') { self.bump(); }
1301         return val
1302     }
1303
1304     fn read_one_line_comment(&mut self) -> String {
1305         let val = self.read_to_eol();
1306         assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/')
1307              || (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1308         return val;
1309     }
1310
1311     fn consume_non_eol_whitespace(&mut self) {
1312         while is_whitespace(self.curr) && !self.curr_is('\n') && !self.is_eof() {
1313             self.bump();
1314         }
1315     }
1316
1317     fn peeking_at_comment(&self) -> bool {
1318         (self.curr_is('/') && self.nextch_is('/'))
1319      || (self.curr_is('/') && self.nextch_is('*'))
1320      // consider shebangs comments, but not inner attributes
1321      || (self.curr_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1322     }
1323
1324     fn scan_byte(&mut self) -> token::Lit {
1325         self.bump();
1326         let start = self.last_pos;
1327
1328         // the eof will be picked up by the final `'` check below
1329         let c2 = self.curr.unwrap_or('\x00');
1330         self.bump();
1331
1332         let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ true, '\'');
1333         if !self.curr_is('\'') {
1334             // Byte offsetting here is okay because the
1335             // character before position `start` are an
1336             // ascii single quote and ascii 'b'.
1337             let last_pos = self.last_pos;
1338             self.fatal_span_verbose(
1339                 start - BytePos(2), last_pos,
1340                 "unterminated byte constant".to_string());
1341         }
1342
1343         let id = if valid { self.name_from(start) } else { token::intern("??") };
1344         self.bump(); // advance curr past token
1345         return token::Byte(id);
1346     }
1347
1348     fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1349         self.scan_hex_digits(2, delim, below_0x7f_only)
1350     }
1351
1352     fn scan_byte_string(&mut self) -> token::Lit {
1353         self.bump();
1354         let start = self.last_pos;
1355         let mut valid = true;
1356
1357         while !self.curr_is('"') {
1358             if self.is_eof() {
1359                 let last_pos = self.last_pos;
1360                 self.fatal_span_(start, last_pos,
1361                                   "unterminated double quote byte string");
1362             }
1363
1364             let ch_start = self.last_pos;
1365             let ch = self.curr.unwrap();
1366             self.bump();
1367             valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ true, '"');
1368         }
1369         let id = if valid { self.name_from(start) } else { token::intern("??") };
1370         self.bump();
1371         return token::Binary(id);
1372     }
1373
1374     fn scan_raw_byte_string(&mut self) -> token::Lit {
1375         let start_bpos = self.last_pos;
1376         self.bump();
1377         let mut hash_count = 0;
1378         while self.curr_is('#') {
1379             self.bump();
1380             hash_count += 1;
1381         }
1382
1383         if self.is_eof() {
1384             let last_pos = self.last_pos;
1385             self.fatal_span_(start_bpos, last_pos, "unterminated raw string");
1386         } else if !self.curr_is('"') {
1387             let last_pos = self.last_pos;
1388             let ch = self.curr.unwrap();
1389             self.fatal_span_char(start_bpos, last_pos,
1390                             "only `#` is allowed in raw string delimitation; \
1391                              found illegal character",
1392                             ch);
1393         }
1394         self.bump();
1395         let content_start_bpos = self.last_pos;
1396         let mut content_end_bpos;
1397         'outer: loop {
1398             match self.curr {
1399                 None => {
1400                     let last_pos = self.last_pos;
1401                     self.fatal_span_(start_bpos, last_pos, "unterminated raw string")
1402                 },
1403                 Some('"') => {
1404                     content_end_bpos = self.last_pos;
1405                     for _ in 0..hash_count {
1406                         self.bump();
1407                         if !self.curr_is('#') {
1408                             continue 'outer;
1409                         }
1410                     }
1411                     break;
1412                 },
1413                 Some(c) => if c > '\x7F' {
1414                     let last_pos = self.last_pos;
1415                     self.err_span_char(
1416                         last_pos, last_pos, "raw byte string must be ASCII", c);
1417                 }
1418             }
1419             self.bump();
1420         }
1421         self.bump();
1422         return token::BinaryRaw(self.name_from_to(content_start_bpos,
1423                                                   content_end_bpos),
1424                                 hash_count);
1425     }
1426 }
1427
1428 pub fn is_whitespace(c: Option<char>) -> bool {
1429     match c.unwrap_or('\x00') { // None can be null for now... it's not whitespace
1430         ' ' | '\n' | '\t' | '\r' => true,
1431         _ => false
1432     }
1433 }
1434
1435 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1436     match c {
1437         Some(c) => lo <= c && c <= hi,
1438         _ => false
1439     }
1440 }
1441
1442 fn is_dec_digit(c: Option<char>) -> bool { return in_range(c, '0', '9'); }
1443
1444 pub fn is_doc_comment(s: &str) -> bool {
1445     let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/')
1446               || s.starts_with("//!");
1447     debug!("is {:?} a doc comment? {}", s, res);
1448     res
1449 }
1450
1451 pub fn is_block_doc_comment(s: &str) -> bool {
1452     let res = (s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*')
1453               || s.starts_with("/*!");
1454     debug!("is {:?} a doc comment? {}", s, res);
1455     res
1456 }
1457
1458 fn ident_start(c: Option<char>) -> bool {
1459     let c = match c { Some(c) => c, None => return false };
1460
1461     (c >= 'a' && c <= 'z')
1462         || (c >= 'A' && c <= 'Z')
1463         || c == '_'
1464         || (c > '\x7f' && c.is_xid_start())
1465 }
1466
1467 fn ident_continue(c: Option<char>) -> bool {
1468     let c = match c { Some(c) => c, None => return false };
1469
1470     (c >= 'a' && c <= 'z')
1471         || (c >= 'A' && c <= 'Z')
1472         || (c >= '0' && c <= '9')
1473         || c == '_'
1474         || (c > '\x7f' && c.is_xid_continue())
1475 }
1476
1477 #[cfg(test)]
1478 mod test {
1479     use super::*;
1480
1481     use codemap::{BytePos, CodeMap, Span, NO_EXPANSION};
1482     use diagnostic;
1483     use parse::token;
1484     use parse::token::{str_to_ident};
1485     use std::old_io::util;
1486
1487     fn mk_sh() -> diagnostic::SpanHandler {
1488         let emitter = diagnostic::EmitterWriter::new(box util::NullWriter, None);
1489         let handler = diagnostic::mk_handler(true, box emitter);
1490         diagnostic::mk_span_handler(handler, CodeMap::new())
1491     }
1492
1493     // open a string reader for the given string
1494     fn setup<'a>(span_handler: &'a diagnostic::SpanHandler,
1495                  teststr: String) -> StringReader<'a> {
1496         let fm = span_handler.cm.new_filemap("zebra.rs".to_string(), teststr);
1497         StringReader::new(span_handler, fm)
1498     }
1499
1500     #[test] fn t1 () {
1501         let span_handler = mk_sh();
1502         let mut string_reader = setup(&span_handler,
1503             "/* my source file */ \
1504              fn main() { println!(\"zebra\"); }\n".to_string());
1505         let id = str_to_ident("fn");
1506         assert_eq!(string_reader.next_token().tok, token::Comment);
1507         assert_eq!(string_reader.next_token().tok, token::Whitespace);
1508         let tok1 = string_reader.next_token();
1509         let tok2 = TokenAndSpan{
1510             tok:token::Ident(id, token::Plain),
1511             sp:Span {lo:BytePos(21),hi:BytePos(23),expn_id: NO_EXPANSION}};
1512         assert_eq!(tok1,tok2);
1513         assert_eq!(string_reader.next_token().tok, token::Whitespace);
1514         // the 'main' id is already read:
1515         assert_eq!(string_reader.last_pos.clone(), BytePos(28));
1516         // read another token:
1517         let tok3 = string_reader.next_token();
1518         let tok4 = TokenAndSpan{
1519             tok:token::Ident(str_to_ident("main"), token::Plain),
1520             sp:Span {lo:BytePos(24),hi:BytePos(28),expn_id: NO_EXPANSION}};
1521         assert_eq!(tok3,tok4);
1522         // the lparen is already read:
1523         assert_eq!(string_reader.last_pos.clone(), BytePos(29))
1524     }
1525
1526     // check that the given reader produces the desired stream
1527     // of tokens (stop checking after exhausting the expected vec)
1528     fn check_tokenization (mut string_reader: StringReader, expected: Vec<token::Token> ) {
1529         for expected_tok in &expected {
1530             assert_eq!(&string_reader.next_token().tok, expected_tok);
1531         }
1532     }
1533
1534     // make the identifier by looking up the string in the interner
1535     fn mk_ident(id: &str, style: token::IdentStyle) -> token::Token {
1536         token::Ident(str_to_ident(id), style)
1537     }
1538
1539     #[test] fn doublecolonparsing () {
1540         check_tokenization(setup(&mk_sh(), "a b".to_string()),
1541                            vec![mk_ident("a", token::Plain),
1542                                 token::Whitespace,
1543                                 mk_ident("b", token::Plain)]);
1544     }
1545
1546     #[test] fn dcparsing_2 () {
1547         check_tokenization(setup(&mk_sh(), "a::b".to_string()),
1548                            vec![mk_ident("a",token::ModName),
1549                                 token::ModSep,
1550                                 mk_ident("b", token::Plain)]);
1551     }
1552
1553     #[test] fn dcparsing_3 () {
1554         check_tokenization(setup(&mk_sh(), "a ::b".to_string()),
1555                            vec![mk_ident("a", token::Plain),
1556                                 token::Whitespace,
1557                                 token::ModSep,
1558                                 mk_ident("b", token::Plain)]);
1559     }
1560
1561     #[test] fn dcparsing_4 () {
1562         check_tokenization(setup(&mk_sh(), "a:: b".to_string()),
1563                            vec![mk_ident("a",token::ModName),
1564                                 token::ModSep,
1565                                 token::Whitespace,
1566                                 mk_ident("b", token::Plain)]);
1567     }
1568
1569     #[test] fn character_a() {
1570         assert_eq!(setup(&mk_sh(), "'a'".to_string()).next_token().tok,
1571                    token::Literal(token::Char(token::intern("a")), None));
1572     }
1573
1574     #[test] fn character_space() {
1575         assert_eq!(setup(&mk_sh(), "' '".to_string()).next_token().tok,
1576                    token::Literal(token::Char(token::intern(" ")), None));
1577     }
1578
1579     #[test] fn character_escaped() {
1580         assert_eq!(setup(&mk_sh(), "'\\n'".to_string()).next_token().tok,
1581                    token::Literal(token::Char(token::intern("\\n")), None));
1582     }
1583
1584     #[test] fn lifetime_name() {
1585         assert_eq!(setup(&mk_sh(), "'abc".to_string()).next_token().tok,
1586                    token::Lifetime(token::str_to_ident("'abc")));
1587     }
1588
1589     #[test] fn raw_string() {
1590         assert_eq!(setup(&mk_sh(),
1591                          "r###\"\"#a\\b\x00c\"\"###".to_string()).next_token()
1592                                                                  .tok,
1593                    token::Literal(token::StrRaw(token::intern("\"#a\\b\x00c\""), 3), None));
1594     }
1595
1596     #[test] fn literal_suffixes() {
1597         macro_rules! test {
1598             ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1599                 assert_eq!(setup(&mk_sh(), format!("{}suffix", $input)).next_token().tok,
1600                            token::Literal(token::$tok_type(token::intern($tok_contents)),
1601                                           Some(token::intern("suffix"))));
1602                 // with a whitespace separator:
1603                 assert_eq!(setup(&mk_sh(), format!("{} suffix", $input)).next_token().tok,
1604                            token::Literal(token::$tok_type(token::intern($tok_contents)),
1605                                           None));
1606             }}
1607         }
1608
1609         test!("'a'", Char, "a");
1610         test!("b'a'", Byte, "a");
1611         test!("\"a\"", Str_, "a");
1612         test!("b\"a\"", Binary, "a");
1613         test!("1234", Integer, "1234");
1614         test!("0b101", Integer, "0b101");
1615         test!("0xABC", Integer, "0xABC");
1616         test!("1.0", Float, "1.0");
1617         test!("1.0e10", Float, "1.0e10");
1618
1619         assert_eq!(setup(&mk_sh(), "2us".to_string()).next_token().tok,
1620                    token::Literal(token::Integer(token::intern("2")),
1621                                   Some(token::intern("us"))));
1622         assert_eq!(setup(&mk_sh(), "r###\"raw\"###suffix".to_string()).next_token().tok,
1623                    token::Literal(token::StrRaw(token::intern("raw"), 3),
1624                                   Some(token::intern("suffix"))));
1625         assert_eq!(setup(&mk_sh(), "br###\"raw\"###suffix".to_string()).next_token().tok,
1626                    token::Literal(token::BinaryRaw(token::intern("raw"), 3),
1627                                   Some(token::intern("suffix"))));
1628     }
1629
1630     #[test] fn line_doc_comments() {
1631         assert!(is_doc_comment("///"));
1632         assert!(is_doc_comment("/// blah"));
1633         assert!(!is_doc_comment("////"));
1634     }
1635
1636     #[test] fn nested_block_comments() {
1637         let sh = mk_sh();
1638         let mut lexer = setup(&sh, "/* /* */ */'a'".to_string());
1639         match lexer.next_token().tok {
1640             token::Comment => { },
1641             _ => panic!("expected a comment!")
1642         }
1643         assert_eq!(lexer.next_token().tok, token::Literal(token::Char(token::intern("a")), None));
1644     }
1645
1646 }