]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/lexer/mod.rs
Auto merge of #42394 - ollie27:rustdoc_deref_box, r=QuietMisdreavus
[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::{self, Ident};
12 use syntax_pos::{self, BytePos, CharPos, Pos, Span, NO_EXPANSION};
13 use codemap::{CodeMap, FilePathMapping};
14 use errors::{FatalError, DiagnosticBuilder};
15 use parse::{token, ParseSess};
16 use str::char_at;
17 use symbol::{Symbol, keywords};
18 use std_unicode::property::Pattern_White_Space;
19
20 use std::borrow::Cow;
21 use std::char;
22 use std::mem::replace;
23 use std::rc::Rc;
24
25 pub mod comments;
26 mod tokentrees;
27 mod unicode_chars;
28
29 #[derive(Clone, PartialEq, Eq, Debug)]
30 pub struct TokenAndSpan {
31     pub tok: token::Token,
32     pub sp: Span,
33 }
34
35 impl Default for TokenAndSpan {
36     fn default() -> Self {
37         TokenAndSpan { tok: token::Underscore, sp: syntax_pos::DUMMY_SP }
38     }
39 }
40
41 pub struct StringReader<'a> {
42     pub sess: &'a ParseSess,
43     /// The absolute offset within the codemap of the next character to read
44     pub next_pos: BytePos,
45     /// The absolute offset within the codemap of the current character
46     pub pos: BytePos,
47     /// The column of the next character to read
48     pub col: CharPos,
49     /// The current character (which has been read from self.pos)
50     pub ch: Option<char>,
51     pub filemap: Rc<syntax_pos::FileMap>,
52     /// If Some, stop reading the source at this position (inclusive).
53     pub terminator: Option<BytePos>,
54     /// Whether to record new-lines and multibyte chars in filemap.
55     /// This is only necessary the first time a filemap is lexed.
56     /// If part of a filemap is being re-lexed, this should be set to false.
57     pub save_new_lines_and_multibyte: bool,
58     // cached:
59     pub peek_tok: token::Token,
60     pub peek_span: Span,
61     pub fatal_errs: Vec<DiagnosticBuilder<'a>>,
62     // cache a direct reference to the source text, so that we don't have to
63     // retrieve it via `self.filemap.src.as_ref().unwrap()` all the time.
64     source_text: Rc<String>,
65     /// Stack of open delimiters and their spans. Used for error message.
66     token: token::Token,
67     span: Span,
68     open_braces: Vec<(token::DelimToken, Span)>,
69 }
70
71 fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
72     Span { lo: lo, hi: hi, ctxt: NO_EXPANSION }
73 }
74
75 impl<'a> StringReader<'a> {
76     fn next_token(&mut self) -> TokenAndSpan {
77         let res = self.try_next_token();
78         self.unwrap_or_abort(res)
79     }
80     fn unwrap_or_abort(&mut self, res: Result<TokenAndSpan, ()>) -> TokenAndSpan {
81         match res {
82             Ok(tok) => tok,
83             Err(_) => {
84                 self.emit_fatal_errors();
85                 panic!(FatalError);
86             }
87         }
88     }
89     fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> {
90         let mut t = self.try_next_token()?;
91         loop {
92             match t.tok {
93                 token::Whitespace | token::Comment | token::Shebang(_) => {
94                     t = self.try_next_token()?;
95                 }
96                 _ => break,
97             }
98         }
99         self.token = t.tok.clone();
100         self.span = t.sp;
101         Ok(t)
102     }
103     pub fn real_token(&mut self) -> TokenAndSpan {
104         let res = self.try_real_token();
105         self.unwrap_or_abort(res)
106     }
107     fn is_eof(&self) -> bool {
108         if self.ch.is_none() {
109             return true;
110         }
111
112         match self.terminator {
113             Some(t) => self.next_pos > t,
114             None => false,
115         }
116     }
117     /// Return the next token. EFFECT: advances the string_reader.
118     pub fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> {
119         assert!(self.fatal_errs.is_empty());
120         let ret_val = TokenAndSpan {
121             tok: replace(&mut self.peek_tok, token::Underscore),
122             sp: self.peek_span,
123         };
124         self.advance_token()?;
125         Ok(ret_val)
126     }
127     fn fatal(&self, m: &str) -> FatalError {
128         self.fatal_span(self.peek_span, m)
129     }
130     pub fn emit_fatal_errors(&mut self) {
131         for err in &mut self.fatal_errs {
132             err.emit();
133         }
134         self.fatal_errs.clear();
135     }
136     pub fn peek(&self) -> TokenAndSpan {
137         // FIXME(pcwalton): Bad copy!
138         TokenAndSpan {
139             tok: self.peek_tok.clone(),
140             sp: self.peek_span,
141         }
142     }
143 }
144
145 impl<'a> StringReader<'a> {
146     /// For comments.rs, which hackily pokes into next_pos and ch
147     pub fn new_raw(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self {
148         let mut sr = StringReader::new_raw_internal(sess, filemap);
149         sr.bump();
150         sr
151     }
152
153     fn new_raw_internal(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self {
154         if filemap.src.is_none() {
155             sess.span_diagnostic.bug(&format!("Cannot lex filemap without source: {}",
156                                               filemap.name));
157         }
158
159         let source_text = (*filemap.src.as_ref().unwrap()).clone();
160
161         StringReader {
162             sess: sess,
163             next_pos: filemap.start_pos,
164             pos: filemap.start_pos,
165             col: CharPos(0),
166             ch: Some('\n'),
167             filemap: filemap,
168             terminator: None,
169             save_new_lines_and_multibyte: true,
170             // dummy values; not read
171             peek_tok: token::Eof,
172             peek_span: syntax_pos::DUMMY_SP,
173             source_text: source_text,
174             fatal_errs: Vec::new(),
175             token: token::Eof,
176             span: syntax_pos::DUMMY_SP,
177             open_braces: Vec::new(),
178         }
179     }
180
181     pub fn new(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self {
182         let mut sr = StringReader::new_raw(sess, filemap);
183         if sr.advance_token().is_err() {
184             sr.emit_fatal_errors();
185             panic!(FatalError);
186         }
187         sr
188     }
189
190     pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
191         let begin = sess.codemap().lookup_byte_offset(span.lo);
192         let end = sess.codemap().lookup_byte_offset(span.hi);
193
194         // Make the range zero-length if the span is invalid.
195         if span.lo > span.hi || begin.fm.start_pos != end.fm.start_pos {
196             span.hi = span.lo;
197         }
198
199         let mut sr = StringReader::new_raw_internal(sess, begin.fm);
200
201         // Seek the lexer to the right byte range.
202         sr.save_new_lines_and_multibyte = false;
203         sr.next_pos = span.lo;
204         sr.terminator = Some(span.hi);
205
206         sr.bump();
207
208         if sr.advance_token().is_err() {
209             sr.emit_fatal_errors();
210             panic!(FatalError);
211         }
212         sr
213     }
214
215     pub fn ch_is(&self, c: char) -> bool {
216         self.ch == Some(c)
217     }
218
219     /// Report a fatal lexical error with a given span.
220     pub fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
221         self.sess.span_diagnostic.span_fatal(sp, m)
222     }
223
224     /// Report a lexical error with a given span.
225     pub fn err_span(&self, sp: Span, m: &str) {
226         self.sess.span_diagnostic.span_err(sp, m)
227     }
228
229
230     /// Report a fatal error spanning [`from_pos`, `to_pos`).
231     fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
232         self.fatal_span(mk_sp(from_pos, to_pos), m)
233     }
234
235     /// Report a lexical error spanning [`from_pos`, `to_pos`).
236     fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
237         self.err_span(mk_sp(from_pos, to_pos), m)
238     }
239
240     /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
241     /// escaped character to the error message
242     fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError {
243         let mut m = m.to_string();
244         m.push_str(": ");
245         for c in c.escape_default() {
246             m.push(c)
247         }
248         self.fatal_span_(from_pos, to_pos, &m[..])
249     }
250     fn struct_fatal_span_char(&self,
251                               from_pos: BytePos,
252                               to_pos: BytePos,
253                               m: &str,
254                               c: char)
255                               -> DiagnosticBuilder<'a> {
256         let mut m = m.to_string();
257         m.push_str(": ");
258         for c in c.escape_default() {
259             m.push(c)
260         }
261         self.sess.span_diagnostic.struct_span_fatal(mk_sp(from_pos, to_pos), &m[..])
262     }
263
264     /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
265     /// escaped character to the error message
266     fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
267         let mut m = m.to_string();
268         m.push_str(": ");
269         for c in c.escape_default() {
270             m.push(c)
271         }
272         self.err_span_(from_pos, to_pos, &m[..]);
273     }
274     fn struct_err_span_char(&self,
275                             from_pos: BytePos,
276                             to_pos: BytePos,
277                             m: &str,
278                             c: char)
279                             -> DiagnosticBuilder<'a> {
280         let mut m = m.to_string();
281         m.push_str(": ");
282         for c in c.escape_default() {
283             m.push(c)
284         }
285         self.sess.span_diagnostic.struct_span_err(mk_sp(from_pos, to_pos), &m[..])
286     }
287
288     /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
289     /// offending string to the error message
290     fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> FatalError {
291         m.push_str(": ");
292         let from = self.byte_offset(from_pos).to_usize();
293         let to = self.byte_offset(to_pos).to_usize();
294         m.push_str(&self.source_text[from..to]);
295         self.fatal_span_(from_pos, to_pos, &m[..])
296     }
297
298     /// Advance peek_tok and peek_span to refer to the next token, and
299     /// possibly update the interner.
300     fn advance_token(&mut self) -> Result<(), ()> {
301         match self.scan_whitespace_or_comment() {
302             Some(comment) => {
303                 self.peek_span = comment.sp;
304                 self.peek_tok = comment.tok;
305             }
306             None => {
307                 if self.is_eof() {
308                     self.peek_tok = token::Eof;
309                     self.peek_span = mk_sp(self.filemap.end_pos, self.filemap.end_pos);
310                 } else {
311                     let start_bytepos = self.pos;
312                     self.peek_tok = self.next_token_inner()?;
313                     self.peek_span = mk_sp(start_bytepos, self.pos);
314                 };
315             }
316         }
317         Ok(())
318     }
319
320     fn byte_offset(&self, pos: BytePos) -> BytePos {
321         (pos - self.filemap.start_pos)
322     }
323
324     /// Calls `f` with a string slice of the source text spanning from `start`
325     /// up to but excluding `self.pos`, meaning the slice does not include
326     /// the character `self.ch`.
327     pub fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T
328         where F: FnOnce(&str) -> T
329     {
330         self.with_str_from_to(start, self.pos, f)
331     }
332
333     /// Create a Name from a given offset to the current offset, each
334     /// adjusted 1 towards each other (assumes that on either side there is a
335     /// single-byte delimiter).
336     pub fn name_from(&self, start: BytePos) -> ast::Name {
337         debug!("taking an ident from {:?} to {:?}", start, self.pos);
338         self.with_str_from(start, Symbol::intern)
339     }
340
341     /// As name_from, with an explicit endpoint.
342     pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
343         debug!("taking an ident from {:?} to {:?}", start, end);
344         self.with_str_from_to(start, end, Symbol::intern)
345     }
346
347     /// Calls `f` with a string slice of the source text spanning from `start`
348     /// up to but excluding `end`.
349     fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T
350         where F: FnOnce(&str) -> T
351     {
352         f(&self.source_text[self.byte_offset(start).to_usize()..self.byte_offset(end).to_usize()])
353     }
354
355     /// Converts CRLF to LF in the given string, raising an error on bare CR.
356     fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
357         let mut i = 0;
358         while i < s.len() {
359             let ch = char_at(s, i);
360             let next = i + ch.len_utf8();
361             if ch == '\r' {
362                 if next < s.len() && char_at(s, next) == '\n' {
363                     return translate_crlf_(self, start, s, errmsg, i).into();
364                 }
365                 let pos = start + BytePos(i as u32);
366                 let end_pos = start + BytePos(next as u32);
367                 self.err_span_(pos, end_pos, errmsg);
368             }
369             i = next;
370         }
371         return s.into();
372
373         fn translate_crlf_(rdr: &StringReader,
374                            start: BytePos,
375                            s: &str,
376                            errmsg: &str,
377                            mut i: usize)
378                            -> String {
379             let mut buf = String::with_capacity(s.len());
380             let mut j = 0;
381             while i < s.len() {
382                 let ch = char_at(s, i);
383                 let next = i + ch.len_utf8();
384                 if ch == '\r' {
385                     if j < i {
386                         buf.push_str(&s[j..i]);
387                     }
388                     j = next;
389                     if next >= s.len() || char_at(s, next) != '\n' {
390                         let pos = start + BytePos(i as u32);
391                         let end_pos = start + BytePos(next as u32);
392                         rdr.err_span_(pos, end_pos, errmsg);
393                     }
394                 }
395                 i = next;
396             }
397             if j < s.len() {
398                 buf.push_str(&s[j..]);
399             }
400             buf
401         }
402     }
403
404
405     /// Advance the StringReader by one character. If a newline is
406     /// discovered, add it to the FileMap's list of line start offsets.
407     pub fn bump(&mut self) {
408         let new_pos = self.next_pos;
409         let new_byte_offset = self.byte_offset(new_pos).to_usize();
410         let end = self.terminator.map_or(self.source_text.len(), |t| {
411             self.byte_offset(t).to_usize()
412         });
413         if new_byte_offset < end {
414             let old_ch_is_newline = self.ch.unwrap() == '\n';
415             let new_ch = char_at(&self.source_text, new_byte_offset);
416             let new_ch_len = new_ch.len_utf8();
417
418             self.ch = Some(new_ch);
419             self.pos = new_pos;
420             self.next_pos = new_pos + Pos::from_usize(new_ch_len);
421             if old_ch_is_newline {
422                 if self.save_new_lines_and_multibyte {
423                     self.filemap.next_line(self.pos);
424                 }
425                 self.col = CharPos(0);
426             } else {
427                 self.col = self.col + CharPos(1);
428             }
429             if new_ch_len > 1 {
430                 if self.save_new_lines_and_multibyte {
431                     self.filemap.record_multibyte_char(self.pos, new_ch_len);
432                 }
433             }
434         } else {
435             self.ch = None;
436             self.pos = new_pos;
437         }
438     }
439
440     pub fn nextch(&self) -> Option<char> {
441         let offset = self.byte_offset(self.next_pos).to_usize();
442         if offset < self.source_text.len() {
443             Some(char_at(&self.source_text, offset))
444         } else {
445             None
446         }
447     }
448
449     pub fn nextch_is(&self, c: char) -> bool {
450         self.nextch() == Some(c)
451     }
452
453     pub fn nextnextch(&self) -> Option<char> {
454         let offset = self.byte_offset(self.next_pos).to_usize();
455         let s = &self.source_text[..];
456         if offset >= s.len() {
457             return None;
458         }
459         let next = offset + char_at(s, offset).len_utf8();
460         if next < s.len() {
461             Some(char_at(s, next))
462         } else {
463             None
464         }
465     }
466
467     pub fn nextnextch_is(&self, c: char) -> bool {
468         self.nextnextch() == Some(c)
469     }
470
471     /// Eats <XID_start><XID_continue>*, if possible.
472     fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
473         if !ident_start(self.ch) {
474             return None;
475         }
476         let start = self.pos;
477         while ident_continue(self.ch) {
478             self.bump();
479         }
480
481         self.with_str_from(start, |string| {
482             if string == "_" {
483                 self.sess.span_diagnostic
484                     .struct_span_warn(mk_sp(start, self.pos),
485                                       "underscore literal suffix is not allowed")
486                     .warn("this was previously accepted by the compiler but is \
487                           being phased out; it will become a hard error in \
488                           a future release!")
489                     .note("for more information, see issue #42326 \
490                           <https://github.com/rust-lang/rust/issues/42326>")
491                     .emit();
492                 None
493             } else {
494                 Some(Symbol::intern(string))
495             }
496         })
497     }
498
499     /// PRECONDITION: self.ch is not whitespace
500     /// Eats any kind of comment.
501     fn scan_comment(&mut self) -> Option<TokenAndSpan> {
502         if let Some(c) = self.ch {
503             if c.is_whitespace() {
504                 let msg = "called consume_any_line_comment, but there was whitespace";
505                 self.sess.span_diagnostic.span_err(mk_sp(self.pos, self.pos), msg);
506             }
507         }
508
509         if self.ch_is('/') {
510             match self.nextch() {
511                 Some('/') => {
512                     self.bump();
513                     self.bump();
514
515                     // line comments starting with "///" or "//!" are doc-comments
516                     let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!');
517                     let start_bpos = self.pos - BytePos(2);
518
519                     while !self.is_eof() {
520                         match self.ch.unwrap() {
521                             '\n' => break,
522                             '\r' => {
523                                 if self.nextch_is('\n') {
524                                     // CRLF
525                                     break;
526                                 } else if doc_comment {
527                                     self.err_span_(self.pos,
528                                                    self.next_pos,
529                                                    "bare CR not allowed in doc-comment");
530                                 }
531                             }
532                             _ => (),
533                         }
534                         self.bump();
535                     }
536
537                     if doc_comment {
538                         self.with_str_from(start_bpos, |string| {
539                             // comments with only more "/"s are not doc comments
540                             let tok = if is_doc_comment(string) {
541                                 token::DocComment(Symbol::intern(string))
542                             } else {
543                                 token::Comment
544                             };
545
546                             Some(TokenAndSpan {
547                                 tok: tok,
548                                 sp: mk_sp(start_bpos, self.pos),
549                             })
550                         })
551                     } else {
552                         Some(TokenAndSpan {
553                             tok: token::Comment,
554                             sp: mk_sp(start_bpos, self.pos),
555                         })
556                     }
557                 }
558                 Some('*') => {
559                     self.bump();
560                     self.bump();
561                     self.scan_block_comment()
562                 }
563                 _ => None,
564             }
565         } else if self.ch_is('#') {
566             if self.nextch_is('!') {
567
568                 // Parse an inner attribute.
569                 if self.nextnextch_is('[') {
570                     return None;
571                 }
572
573                 // I guess this is the only way to figure out if
574                 // we're at the beginning of the file...
575                 let cmap = CodeMap::new(FilePathMapping::empty());
576                 cmap.files.borrow_mut().push(self.filemap.clone());
577                 let loc = cmap.lookup_char_pos_adj(self.pos);
578                 debug!("Skipping a shebang");
579                 if loc.line == 1 && loc.col == CharPos(0) {
580                     // FIXME: Add shebang "token", return it
581                     let start = self.pos;
582                     while !self.ch_is('\n') && !self.is_eof() {
583                         self.bump();
584                     }
585                     return Some(TokenAndSpan {
586                         tok: token::Shebang(self.name_from(start)),
587                         sp: mk_sp(start, self.pos),
588                     });
589                 }
590             }
591             None
592         } else {
593             None
594         }
595     }
596
597     /// If there is whitespace, shebang, or a comment, scan it. Otherwise,
598     /// return None.
599     fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
600         match self.ch.unwrap_or('\0') {
601             // # to handle shebang at start of file -- this is the entry point
602             // for skipping over all "junk"
603             '/' | '#' => {
604                 let c = self.scan_comment();
605                 debug!("scanning a comment {:?}", c);
606                 c
607             },
608             c if is_pattern_whitespace(Some(c)) => {
609                 let start_bpos = self.pos;
610                 while is_pattern_whitespace(self.ch) {
611                     self.bump();
612                 }
613                 let c = Some(TokenAndSpan {
614                     tok: token::Whitespace,
615                     sp: mk_sp(start_bpos, self.pos),
616                 });
617                 debug!("scanning whitespace: {:?}", c);
618                 c
619             }
620             _ => None,
621         }
622     }
623
624     /// Might return a sugared-doc-attr
625     fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
626         // block comments starting with "/**" or "/*!" are doc-comments
627         let is_doc_comment = self.ch_is('*') || self.ch_is('!');
628         let start_bpos = self.pos - BytePos(2);
629
630         let mut level: isize = 1;
631         let mut has_cr = false;
632         while level > 0 {
633             if self.is_eof() {
634                 let msg = if is_doc_comment {
635                     "unterminated block doc-comment"
636                 } else {
637                     "unterminated block comment"
638                 };
639                 let last_bpos = self.pos;
640                 panic!(self.fatal_span_(start_bpos, last_bpos, msg));
641             }
642             let n = self.ch.unwrap();
643             match n {
644                 '/' if self.nextch_is('*') => {
645                     level += 1;
646                     self.bump();
647                 }
648                 '*' if self.nextch_is('/') => {
649                     level -= 1;
650                     self.bump();
651                 }
652                 '\r' => {
653                     has_cr = true;
654                 }
655                 _ => (),
656             }
657             self.bump();
658         }
659
660         self.with_str_from(start_bpos, |string| {
661             // but comments with only "*"s between two "/"s are not
662             let tok = if is_block_doc_comment(string) {
663                 let string = if has_cr {
664                     self.translate_crlf(start_bpos,
665                                         string,
666                                         "bare CR not allowed in block doc-comment")
667                 } else {
668                     string.into()
669                 };
670                 token::DocComment(Symbol::intern(&string[..]))
671             } else {
672                 token::Comment
673             };
674
675             Some(TokenAndSpan {
676                 tok: tok,
677                 sp: mk_sp(start_bpos, self.pos),
678             })
679         })
680     }
681
682     /// Scan through any digits (base `scan_radix`) or underscores,
683     /// and return how many digits there were.
684     ///
685     /// `real_radix` represents the true radix of the number we're
686     /// interested in, and errors will be emitted for any digits
687     /// between `real_radix` and `scan_radix`.
688     fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
689         assert!(real_radix <= scan_radix);
690         let mut len = 0;
691         loop {
692             let c = self.ch;
693             if c == Some('_') {
694                 debug!("skipping a _");
695                 self.bump();
696                 continue;
697             }
698             match c.and_then(|cc| cc.to_digit(scan_radix)) {
699                 Some(_) => {
700                     debug!("{:?} in scan_digits", c);
701                     // check that the hypothetical digit is actually
702                     // in range for the true radix
703                     if c.unwrap().to_digit(real_radix).is_none() {
704                         self.err_span_(self.pos,
705                                        self.next_pos,
706                                        &format!("invalid digit for a base {} literal", real_radix));
707                     }
708                     len += 1;
709                     self.bump();
710                 }
711                 _ => return len,
712             }
713         }
714     }
715
716     /// Lex a LIT_INTEGER or a LIT_FLOAT
717     fn scan_number(&mut self, c: char) -> token::Lit {
718         let num_digits;
719         let mut base = 10;
720         let start_bpos = self.pos;
721
722         self.bump();
723
724         if c == '0' {
725             match self.ch.unwrap_or('\0') {
726                 'b' => {
727                     self.bump();
728                     base = 2;
729                     num_digits = self.scan_digits(2, 10);
730                 }
731                 'o' => {
732                     self.bump();
733                     base = 8;
734                     num_digits = self.scan_digits(8, 10);
735                 }
736                 'x' => {
737                     self.bump();
738                     base = 16;
739                     num_digits = self.scan_digits(16, 16);
740                 }
741                 '0'...'9' | '_' | '.' | 'e' | 'E' => {
742                     num_digits = self.scan_digits(10, 10) + 1;
743                 }
744                 _ => {
745                     // just a 0
746                     return token::Integer(self.name_from(start_bpos));
747                 }
748             }
749         } else if c.is_digit(10) {
750             num_digits = self.scan_digits(10, 10) + 1;
751         } else {
752             num_digits = 0;
753         }
754
755         if num_digits == 0 {
756             self.err_span_(start_bpos,
757                            self.pos,
758                            "no valid digits found for number");
759             return token::Integer(Symbol::intern("0"));
760         }
761
762         // might be a float, but don't be greedy if this is actually an
763         // integer literal followed by field/method access or a range pattern
764         // (`0..2` and `12.foo()`)
765         if self.ch_is('.') && !self.nextch_is('.') &&
766            !ident_start(self.nextch()) {
767             // might have stuff after the ., and if it does, it needs to start
768             // with a number
769             self.bump();
770             if self.ch.unwrap_or('\0').is_digit(10) {
771                 self.scan_digits(10, 10);
772                 self.scan_float_exponent();
773             }
774             let pos = self.pos;
775             self.check_float_base(start_bpos, pos, base);
776             token::Float(self.name_from(start_bpos))
777         } else {
778             // it might be a float if it has an exponent
779             if self.ch_is('e') || self.ch_is('E') {
780                 self.scan_float_exponent();
781                 let pos = self.pos;
782                 self.check_float_base(start_bpos, pos, base);
783                 return token::Float(self.name_from(start_bpos));
784             }
785             // but we certainly have an integer!
786             token::Integer(self.name_from(start_bpos))
787         }
788     }
789
790     /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
791     /// error if too many or too few digits are encountered.
792     fn scan_hex_digits(&mut self, n_digits: usize, delim: char, below_0x7f_only: bool) -> bool {
793         debug!("scanning {} digits until {:?}", n_digits, delim);
794         let start_bpos = self.pos;
795         let mut accum_int = 0;
796
797         let mut valid = true;
798         for _ in 0..n_digits {
799             if self.is_eof() {
800                 let last_bpos = self.pos;
801                 panic!(self.fatal_span_(start_bpos,
802                                         last_bpos,
803                                         "unterminated numeric character escape"));
804             }
805             if self.ch_is(delim) {
806                 let last_bpos = self.pos;
807                 self.err_span_(start_bpos,
808                                last_bpos,
809                                "numeric character escape is too short");
810                 valid = false;
811                 break;
812             }
813             let c = self.ch.unwrap_or('\x00');
814             accum_int *= 16;
815             accum_int += c.to_digit(16).unwrap_or_else(|| {
816                 self.err_span_char(self.pos,
817                                    self.next_pos,
818                                    "invalid character in numeric character escape",
819                                    c);
820
821                 valid = false;
822                 0
823             });
824             self.bump();
825         }
826
827         if below_0x7f_only && accum_int >= 0x80 {
828             self.err_span_(start_bpos,
829                            self.pos,
830                            "this form of character escape may only be used with characters in \
831                             the range [\\x00-\\x7f]");
832             valid = false;
833         }
834
835         match char::from_u32(accum_int) {
836             Some(_) => valid,
837             None => {
838                 let last_bpos = self.pos;
839                 self.err_span_(start_bpos, last_bpos, "invalid numeric character escape");
840                 false
841             }
842         }
843     }
844
845     /// Scan for a single (possibly escaped) byte or char
846     /// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
847     /// `start` is the position of `first_source_char`, which is already consumed.
848     ///
849     /// Returns true if there was a valid char/byte, false otherwise.
850     fn scan_char_or_byte(&mut self,
851                          start: BytePos,
852                          first_source_char: char,
853                          ascii_only: bool,
854                          delim: char)
855                          -> bool {
856         match first_source_char {
857             '\\' => {
858                 // '\X' for some X must be a character constant:
859                 let escaped = self.ch;
860                 let escaped_pos = self.pos;
861                 self.bump();
862                 match escaped {
863                     None => {}  // EOF here is an error that will be checked later.
864                     Some(e) => {
865                         return match e {
866                             'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
867                             'x' => self.scan_byte_escape(delim, !ascii_only),
868                             'u' => {
869                                 let valid = if self.ch_is('{') {
870                                     self.scan_unicode_escape(delim) && !ascii_only
871                                 } else {
872                                     let span = mk_sp(start, self.pos);
873                                     self.sess.span_diagnostic
874                                         .struct_span_err(span, "incorrect unicode escape sequence")
875                                         .span_help(span,
876                                                    "format of unicode escape sequences is \
877                                                     `\\u{…}`")
878                                         .emit();
879                                     false
880                                 };
881                                 if ascii_only {
882                                     self.err_span_(start,
883                                                    self.pos,
884                                                    "unicode escape sequences cannot be used as a \
885                                                     byte or in a byte string");
886                                 }
887                                 valid
888
889                             }
890                             '\n' if delim == '"' => {
891                                 self.consume_whitespace();
892                                 true
893                             }
894                             '\r' if delim == '"' && self.ch_is('\n') => {
895                                 self.consume_whitespace();
896                                 true
897                             }
898                             c => {
899                                 let pos = self.pos;
900                                 let mut err = self.struct_err_span_char(escaped_pos,
901                                                                         pos,
902                                                                         if ascii_only {
903                                                                             "unknown byte escape"
904                                                                         } else {
905                                                                             "unknown character \
906                                                                              escape"
907                                                                         },
908                                                                         c);
909                                 if e == '\r' {
910                                     err.span_help(mk_sp(escaped_pos, pos),
911                                                   "this is an isolated carriage return; consider \
912                                                    checking your editor and version control \
913                                                    settings");
914                                 }
915                                 if (e == '{' || e == '}') && !ascii_only {
916                                     err.span_help(mk_sp(escaped_pos, pos),
917                                                   "if used in a formatting string, curly braces \
918                                                    are escaped with `{{` and `}}`");
919                                 }
920                                 err.emit();
921                                 false
922                             }
923                         }
924                     }
925                 }
926             }
927             '\t' | '\n' | '\r' | '\'' if delim == '\'' => {
928                 let pos = self.pos;
929                 self.err_span_char(start,
930                                    pos,
931                                    if ascii_only {
932                                        "byte constant must be escaped"
933                                    } else {
934                                        "character constant must be escaped"
935                                    },
936                                    first_source_char);
937                 return false;
938             }
939             '\r' => {
940                 if self.ch_is('\n') {
941                     self.bump();
942                     return true;
943                 } else {
944                     self.err_span_(start,
945                                    self.pos,
946                                    "bare CR not allowed in string, use \\r instead");
947                     return false;
948                 }
949             }
950             _ => {
951                 if ascii_only && first_source_char > '\x7F' {
952                     let pos = self.pos;
953                     self.err_span_(start,
954                                    pos,
955                                    "byte constant must be ASCII. Use a \\xHH escape for a \
956                                     non-ASCII byte");
957                     return false;
958                 }
959             }
960         }
961         true
962     }
963
964     /// Scan over a \u{...} escape
965     ///
966     /// At this point, we have already seen the \ and the u, the { is the current character. We
967     /// will read at least one digit, and up to 6, and pass over the }.
968     fn scan_unicode_escape(&mut self, delim: char) -> bool {
969         self.bump(); // past the {
970         let start_bpos = self.pos;
971         let mut count = 0;
972         let mut accum_int = 0;
973         let mut valid = true;
974
975         while !self.ch_is('}') && count <= 6 {
976             let c = match self.ch {
977                 Some(c) => c,
978                 None => {
979                     panic!(self.fatal_span_(start_bpos,
980                                             self.pos,
981                                             "unterminated unicode escape (found EOF)"));
982                 }
983             };
984             accum_int *= 16;
985             accum_int += c.to_digit(16).unwrap_or_else(|| {
986                 if c == delim {
987                     panic!(self.fatal_span_(self.pos,
988                                             self.next_pos,
989                                             "unterminated unicode escape (needed a `}`)"));
990                 } else {
991                     self.err_span_char(self.pos,
992                                        self.next_pos,
993                                        "invalid character in unicode escape",
994                                        c);
995                 }
996                 valid = false;
997                 0
998             });
999             self.bump();
1000             count += 1;
1001         }
1002
1003         if count > 6 {
1004             self.err_span_(start_bpos,
1005                            self.pos,
1006                            "overlong unicode escape (can have at most 6 hex digits)");
1007             valid = false;
1008         }
1009
1010         if valid && (char::from_u32(accum_int).is_none() || count == 0) {
1011             self.err_span_(start_bpos,
1012                            self.pos,
1013                            "invalid unicode character escape");
1014             valid = false;
1015         }
1016
1017         self.bump(); // past the ending }
1018         valid
1019     }
1020
1021     /// Scan over a float exponent.
1022     fn scan_float_exponent(&mut self) {
1023         if self.ch_is('e') || self.ch_is('E') {
1024             self.bump();
1025             if self.ch_is('-') || self.ch_is('+') {
1026                 self.bump();
1027             }
1028             if self.scan_digits(10, 10) == 0 {
1029                 self.err_span_(self.pos,
1030                                self.next_pos,
1031                                "expected at least one digit in exponent")
1032             }
1033         }
1034     }
1035
1036     /// Check that a base is valid for a floating literal, emitting a nice
1037     /// error if it isn't.
1038     fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
1039         match base {
1040             16 => {
1041                 self.err_span_(start_bpos,
1042                                last_bpos,
1043                                "hexadecimal float literal is not supported")
1044             }
1045             8 => {
1046                 self.err_span_(start_bpos,
1047                                last_bpos,
1048                                "octal float literal is not supported")
1049             }
1050             2 => {
1051                 self.err_span_(start_bpos,
1052                                last_bpos,
1053                                "binary float literal is not supported")
1054             }
1055             _ => (),
1056         }
1057     }
1058
1059     fn binop(&mut self, op: token::BinOpToken) -> token::Token {
1060         self.bump();
1061         if self.ch_is('=') {
1062             self.bump();
1063             token::BinOpEq(op)
1064         } else {
1065             token::BinOp(op)
1066         }
1067     }
1068
1069     /// Return the next token from the string, advances the input past that
1070     /// token, and updates the interner
1071     fn next_token_inner(&mut self) -> Result<token::Token, ()> {
1072         let c = self.ch;
1073         if ident_start(c) &&
1074            match (c.unwrap(), self.nextch(), self.nextnextch()) {
1075             // Note: r as in r" or r#" is part of a raw string literal,
1076             // b as in b' is part of a byte literal.
1077             // They are not identifiers, and are handled further down.
1078             ('r', Some('"'), _) |
1079             ('r', Some('#'), _) |
1080             ('b', Some('"'), _) |
1081             ('b', Some('\''), _) |
1082             ('b', Some('r'), Some('"')) |
1083             ('b', Some('r'), Some('#')) => false,
1084             _ => true,
1085         } {
1086             let start = self.pos;
1087             while ident_continue(self.ch) {
1088                 self.bump();
1089             }
1090
1091             return Ok(self.with_str_from(start, |string| {
1092                 if string == "_" {
1093                     token::Underscore
1094                 } else {
1095                     // FIXME: perform NFKC normalization here. (Issue #2253)
1096                     token::Ident(Ident::from_str(string))
1097                 }
1098             }));
1099         }
1100
1101         if is_dec_digit(c) {
1102             let num = self.scan_number(c.unwrap());
1103             let suffix = self.scan_optional_raw_name();
1104             debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
1105             return Ok(token::Literal(num, suffix));
1106         }
1107
1108         match c.expect("next_token_inner called at EOF") {
1109             // One-byte tokens.
1110             ';' => {
1111                 self.bump();
1112                 Ok(token::Semi)
1113             }
1114             ',' => {
1115                 self.bump();
1116                 Ok(token::Comma)
1117             }
1118             '.' => {
1119                 self.bump();
1120                 if self.ch_is('.') {
1121                     self.bump();
1122                     if self.ch_is('.') {
1123                         self.bump();
1124                         Ok(token::DotDotDot)
1125                     } else {
1126                         Ok(token::DotDot)
1127                     }
1128                 } else {
1129                     Ok(token::Dot)
1130                 }
1131             }
1132             '(' => {
1133                 self.bump();
1134                 Ok(token::OpenDelim(token::Paren))
1135             }
1136             ')' => {
1137                 self.bump();
1138                 Ok(token::CloseDelim(token::Paren))
1139             }
1140             '{' => {
1141                 self.bump();
1142                 Ok(token::OpenDelim(token::Brace))
1143             }
1144             '}' => {
1145                 self.bump();
1146                 Ok(token::CloseDelim(token::Brace))
1147             }
1148             '[' => {
1149                 self.bump();
1150                 Ok(token::OpenDelim(token::Bracket))
1151             }
1152             ']' => {
1153                 self.bump();
1154                 Ok(token::CloseDelim(token::Bracket))
1155             }
1156             '@' => {
1157                 self.bump();
1158                 Ok(token::At)
1159             }
1160             '#' => {
1161                 self.bump();
1162                 Ok(token::Pound)
1163             }
1164             '~' => {
1165                 self.bump();
1166                 Ok(token::Tilde)
1167             }
1168             '?' => {
1169                 self.bump();
1170                 Ok(token::Question)
1171             }
1172             ':' => {
1173                 self.bump();
1174                 if self.ch_is(':') {
1175                     self.bump();
1176                     Ok(token::ModSep)
1177                 } else {
1178                     Ok(token::Colon)
1179                 }
1180             }
1181
1182             '$' => {
1183                 self.bump();
1184                 Ok(token::Dollar)
1185             }
1186
1187             // Multi-byte tokens.
1188             '=' => {
1189                 self.bump();
1190                 if self.ch_is('=') {
1191                     self.bump();
1192                     Ok(token::EqEq)
1193                 } else if self.ch_is('>') {
1194                     self.bump();
1195                     Ok(token::FatArrow)
1196                 } else {
1197                     Ok(token::Eq)
1198                 }
1199             }
1200             '!' => {
1201                 self.bump();
1202                 if self.ch_is('=') {
1203                     self.bump();
1204                     Ok(token::Ne)
1205                 } else {
1206                     Ok(token::Not)
1207                 }
1208             }
1209             '<' => {
1210                 self.bump();
1211                 match self.ch.unwrap_or('\x00') {
1212                     '=' => {
1213                         self.bump();
1214                         Ok(token::Le)
1215                     }
1216                     '<' => {
1217                         Ok(self.binop(token::Shl))
1218                     }
1219                     '-' => {
1220                         self.bump();
1221                         match self.ch.unwrap_or('\x00') {
1222                             _ => {
1223                                 Ok(token::LArrow)
1224                             }
1225                         }
1226                     }
1227                     _ => {
1228                         Ok(token::Lt)
1229                     }
1230                 }
1231             }
1232             '>' => {
1233                 self.bump();
1234                 match self.ch.unwrap_or('\x00') {
1235                     '=' => {
1236                         self.bump();
1237                         Ok(token::Ge)
1238                     }
1239                     '>' => {
1240                         Ok(self.binop(token::Shr))
1241                     }
1242                     _ => {
1243                         Ok(token::Gt)
1244                     }
1245                 }
1246             }
1247             '\'' => {
1248                 // Either a character constant 'a' OR a lifetime name 'abc
1249                 let start_with_quote = self.pos;
1250                 self.bump();
1251                 let start = self.pos;
1252
1253                 // the eof will be picked up by the final `'` check below
1254                 let c2 = self.ch.unwrap_or('\x00');
1255                 self.bump();
1256
1257                 // If the character is an ident start not followed by another single
1258                 // quote, then this is a lifetime name:
1259                 if ident_start(Some(c2)) && !self.ch_is('\'') {
1260                     while ident_continue(self.ch) {
1261                         self.bump();
1262                     }
1263                     // lifetimes shouldn't end with a single quote
1264                     // if we find one, then this is an invalid character literal
1265                     if self.ch_is('\'') {
1266                         panic!(self.fatal_span_verbose(
1267                                start_with_quote, self.next_pos,
1268                                String::from("character literal may only contain one codepoint")));
1269
1270                     }
1271
1272                     // Include the leading `'` in the real identifier, for macro
1273                     // expansion purposes. See #12512 for the gory details of why
1274                     // this is necessary.
1275                     let ident = self.with_str_from(start, |lifetime_name| {
1276                         Ident::from_str(&format!("'{}", lifetime_name))
1277                     });
1278
1279                     // Conjure up a "keyword checking ident" to make sure that
1280                     // the lifetime name is not a keyword.
1281                     let keyword_checking_ident = self.with_str_from(start, |lifetime_name| {
1282                         Ident::from_str(lifetime_name)
1283                     });
1284                     let keyword_checking_token = &token::Ident(keyword_checking_ident);
1285                     let last_bpos = self.pos;
1286                     if keyword_checking_token.is_any_keyword() &&
1287                        !keyword_checking_token.is_keyword(keywords::Static) {
1288                         self.err_span_(start, last_bpos, "lifetimes cannot use keyword names");
1289                     }
1290
1291                     return Ok(token::Lifetime(ident));
1292                 }
1293
1294                 let valid = self.scan_char_or_byte(start,
1295                                                    c2,
1296                                                    // ascii_only =
1297                                                    false,
1298                                                    '\'');
1299
1300                 if !self.ch_is('\'') {
1301                     panic!(self.fatal_span_verbose(
1302                            start_with_quote, self.pos,
1303                            String::from("character literal may only contain one codepoint")));
1304                 }
1305
1306                 let id = if valid {
1307                     self.name_from(start)
1308                 } else {
1309                     Symbol::intern("0")
1310                 };
1311                 self.bump(); // advance ch past token
1312                 let suffix = self.scan_optional_raw_name();
1313                 Ok(token::Literal(token::Char(id), suffix))
1314             }
1315             'b' => {
1316                 self.bump();
1317                 let lit = match self.ch {
1318                     Some('\'') => self.scan_byte(),
1319                     Some('"') => self.scan_byte_string(),
1320                     Some('r') => self.scan_raw_byte_string(),
1321                     _ => unreachable!(),  // Should have been a token::Ident above.
1322                 };
1323                 let suffix = self.scan_optional_raw_name();
1324                 Ok(token::Literal(lit, suffix))
1325             }
1326             '"' => {
1327                 let start_bpos = self.pos;
1328                 let mut valid = true;
1329                 self.bump();
1330                 while !self.ch_is('"') {
1331                     if self.is_eof() {
1332                         let last_bpos = self.pos;
1333                         panic!(self.fatal_span_(start_bpos,
1334                                                 last_bpos,
1335                                                 "unterminated double quote string"));
1336                     }
1337
1338                     let ch_start = self.pos;
1339                     let ch = self.ch.unwrap();
1340                     self.bump();
1341                     valid &= self.scan_char_or_byte(ch_start,
1342                                                     ch,
1343                                                     // ascii_only =
1344                                                     false,
1345                                                     '"');
1346                 }
1347                 // adjust for the ASCII " at the start of the literal
1348                 let id = if valid {
1349                     self.name_from(start_bpos + BytePos(1))
1350                 } else {
1351                     Symbol::intern("??")
1352                 };
1353                 self.bump();
1354                 let suffix = self.scan_optional_raw_name();
1355                 Ok(token::Literal(token::Str_(id), suffix))
1356             }
1357             'r' => {
1358                 let start_bpos = self.pos;
1359                 self.bump();
1360                 let mut hash_count = 0;
1361                 while self.ch_is('#') {
1362                     self.bump();
1363                     hash_count += 1;
1364                 }
1365
1366                 if self.is_eof() {
1367                     let last_bpos = self.pos;
1368                     panic!(self.fatal_span_(start_bpos, last_bpos, "unterminated raw string"));
1369                 } else if !self.ch_is('"') {
1370                     let last_bpos = self.pos;
1371                     let curr_char = self.ch.unwrap();
1372                     panic!(self.fatal_span_char(start_bpos,
1373                                                 last_bpos,
1374                                                 "found invalid character; only `#` is allowed \
1375                                                  in raw string delimitation",
1376                                                 curr_char));
1377                 }
1378                 self.bump();
1379                 let content_start_bpos = self.pos;
1380                 let mut content_end_bpos;
1381                 let mut valid = true;
1382                 'outer: loop {
1383                     if self.is_eof() {
1384                         let last_bpos = self.pos;
1385                         panic!(self.fatal_span_(start_bpos, last_bpos, "unterminated raw string"));
1386                     }
1387                     // if self.ch_is('"') {
1388                     // content_end_bpos = self.pos;
1389                     // for _ in 0..hash_count {
1390                     // self.bump();
1391                     // if !self.ch_is('#') {
1392                     // continue 'outer;
1393                     let c = self.ch.unwrap();
1394                     match c {
1395                         '"' => {
1396                             content_end_bpos = self.pos;
1397                             for _ in 0..hash_count {
1398                                 self.bump();
1399                                 if !self.ch_is('#') {
1400                                     continue 'outer;
1401                                 }
1402                             }
1403                             break;
1404                         }
1405                         '\r' => {
1406                             if !self.nextch_is('\n') {
1407                                 let last_bpos = self.pos;
1408                                 self.err_span_(start_bpos,
1409                                                last_bpos,
1410                                                "bare CR not allowed in raw string, use \\r \
1411                                                 instead");
1412                                 valid = false;
1413                             }
1414                         }
1415                         _ => (),
1416                     }
1417                     self.bump();
1418                 }
1419                 self.bump();
1420                 let id = if valid {
1421                     self.name_from_to(content_start_bpos, content_end_bpos)
1422                 } else {
1423                     Symbol::intern("??")
1424                 };
1425                 let suffix = self.scan_optional_raw_name();
1426                 Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
1427             }
1428             '-' => {
1429                 if self.nextch_is('>') {
1430                     self.bump();
1431                     self.bump();
1432                     Ok(token::RArrow)
1433                 } else {
1434                     Ok(self.binop(token::Minus))
1435                 }
1436             }
1437             '&' => {
1438                 if self.nextch_is('&') {
1439                     self.bump();
1440                     self.bump();
1441                     Ok(token::AndAnd)
1442                 } else {
1443                     Ok(self.binop(token::And))
1444                 }
1445             }
1446             '|' => {
1447                 match self.nextch() {
1448                     Some('|') => {
1449                         self.bump();
1450                         self.bump();
1451                         Ok(token::OrOr)
1452                     }
1453                     _ => {
1454                         Ok(self.binop(token::Or))
1455                     }
1456                 }
1457             }
1458             '+' => {
1459                 Ok(self.binop(token::Plus))
1460             }
1461             '*' => {
1462                 Ok(self.binop(token::Star))
1463             }
1464             '/' => {
1465                 Ok(self.binop(token::Slash))
1466             }
1467             '^' => {
1468                 Ok(self.binop(token::Caret))
1469             }
1470             '%' => {
1471                 Ok(self.binop(token::Percent))
1472             }
1473             c => {
1474                 let last_bpos = self.pos;
1475                 let bpos = self.next_pos;
1476                 let mut err = self.struct_fatal_span_char(last_bpos,
1477                                                           bpos,
1478                                                           "unknown start of token",
1479                                                           c);
1480                 unicode_chars::check_for_substitution(self, c, &mut err);
1481                 self.fatal_errs.push(err);
1482                 Err(())
1483             }
1484         }
1485     }
1486
1487     fn consume_whitespace(&mut self) {
1488         while is_pattern_whitespace(self.ch) && !self.is_eof() {
1489             self.bump();
1490         }
1491     }
1492
1493     fn read_to_eol(&mut self) -> String {
1494         let mut val = String::new();
1495         while !self.ch_is('\n') && !self.is_eof() {
1496             val.push(self.ch.unwrap());
1497             self.bump();
1498         }
1499         if self.ch_is('\n') {
1500             self.bump();
1501         }
1502         val
1503     }
1504
1505     fn read_one_line_comment(&mut self) -> String {
1506         let val = self.read_to_eol();
1507         assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
1508                 (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
1509         val
1510     }
1511
1512     fn consume_non_eol_whitespace(&mut self) {
1513         while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() {
1514             self.bump();
1515         }
1516     }
1517
1518     fn peeking_at_comment(&self) -> bool {
1519         (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) ||
1520         // consider shebangs comments, but not inner attributes
1521         (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
1522     }
1523
1524     fn scan_byte(&mut self) -> token::Lit {
1525         self.bump();
1526         let start = self.pos;
1527
1528         // the eof will be picked up by the final `'` check below
1529         let c2 = self.ch.unwrap_or('\x00');
1530         self.bump();
1531
1532         let valid = self.scan_char_or_byte(start,
1533                                            c2,
1534                                            // ascii_only =
1535                                            true,
1536                                            '\'');
1537         if !self.ch_is('\'') {
1538             // Byte offsetting here is okay because the
1539             // character before position `start` are an
1540             // ascii single quote and ascii 'b'.
1541             let pos = self.pos;
1542             panic!(self.fatal_span_verbose(start - BytePos(2),
1543                                            pos,
1544                                            "unterminated byte constant".to_string()));
1545         }
1546
1547         let id = if valid {
1548             self.name_from(start)
1549         } else {
1550             Symbol::intern("?")
1551         };
1552         self.bump(); // advance ch past token
1553         token::Byte(id)
1554     }
1555
1556     fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
1557         self.scan_hex_digits(2, delim, below_0x7f_only)
1558     }
1559
1560     fn scan_byte_string(&mut self) -> token::Lit {
1561         self.bump();
1562         let start = self.pos;
1563         let mut valid = true;
1564
1565         while !self.ch_is('"') {
1566             if self.is_eof() {
1567                 let pos = self.pos;
1568                 panic!(self.fatal_span_(start, pos, "unterminated double quote byte string"));
1569             }
1570
1571             let ch_start = self.pos;
1572             let ch = self.ch.unwrap();
1573             self.bump();
1574             valid &= self.scan_char_or_byte(ch_start,
1575                                             ch,
1576                                             // ascii_only =
1577                                             true,
1578                                             '"');
1579         }
1580         let id = if valid {
1581             self.name_from(start)
1582         } else {
1583             Symbol::intern("??")
1584         };
1585         self.bump();
1586         token::ByteStr(id)
1587     }
1588
1589     fn scan_raw_byte_string(&mut self) -> token::Lit {
1590         let start_bpos = self.pos;
1591         self.bump();
1592         let mut hash_count = 0;
1593         while self.ch_is('#') {
1594             self.bump();
1595             hash_count += 1;
1596         }
1597
1598         if self.is_eof() {
1599             let pos = self.pos;
1600             panic!(self.fatal_span_(start_bpos, pos, "unterminated raw string"));
1601         } else if !self.ch_is('"') {
1602             let pos = self.pos;
1603             let ch = self.ch.unwrap();
1604             panic!(self.fatal_span_char(start_bpos,
1605                                         pos,
1606                                         "found invalid character; only `#` is allowed in raw \
1607                                          string delimitation",
1608                                         ch));
1609         }
1610         self.bump();
1611         let content_start_bpos = self.pos;
1612         let mut content_end_bpos;
1613         'outer: loop {
1614             match self.ch {
1615                 None => {
1616                     let pos = self.pos;
1617                     panic!(self.fatal_span_(start_bpos, pos, "unterminated raw string"))
1618                 }
1619                 Some('"') => {
1620                     content_end_bpos = self.pos;
1621                     for _ in 0..hash_count {
1622                         self.bump();
1623                         if !self.ch_is('#') {
1624                             continue 'outer;
1625                         }
1626                     }
1627                     break;
1628                 }
1629                 Some(c) => {
1630                     if c > '\x7F' {
1631                         let pos = self.pos;
1632                         self.err_span_char(pos, pos, "raw byte string must be ASCII", c);
1633                     }
1634                 }
1635             }
1636             self.bump();
1637         }
1638         self.bump();
1639         token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos),
1640                                  hash_count)
1641     }
1642 }
1643
1644 // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which
1645 // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3
1646 pub fn is_pattern_whitespace(c: Option<char>) -> bool {
1647     c.map_or(false, Pattern_White_Space)
1648 }
1649
1650 fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
1651     match c {
1652         Some(c) => lo <= c && c <= hi,
1653         _ => false,
1654     }
1655 }
1656
1657 fn is_dec_digit(c: Option<char>) -> bool {
1658     in_range(c, '0', '9')
1659 }
1660
1661 pub fn is_doc_comment(s: &str) -> bool {
1662     let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') ||
1663               s.starts_with("//!");
1664     debug!("is {:?} a doc comment? {}", s, res);
1665     res
1666 }
1667
1668 pub fn is_block_doc_comment(s: &str) -> bool {
1669     // Prevent `/**/` from being parsed as a doc comment
1670     let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') ||
1671                s.starts_with("/*!")) && s.len() >= 5;
1672     debug!("is {:?} a doc comment? {}", s, res);
1673     res
1674 }
1675
1676 fn ident_start(c: Option<char>) -> bool {
1677     let c = match c {
1678         Some(c) => c,
1679         None => return false,
1680     };
1681
1682     (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start())
1683 }
1684
1685 fn ident_continue(c: Option<char>) -> bool {
1686     let c = match c {
1687         Some(c) => c,
1688         None => return false,
1689     };
1690
1691     (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
1692     (c > '\x7f' && c.is_xid_continue())
1693 }
1694
1695 #[cfg(test)]
1696 mod tests {
1697     use super::*;
1698
1699     use ast::{Ident, CrateConfig};
1700     use symbol::Symbol;
1701     use syntax_pos::{BytePos, Span, NO_EXPANSION};
1702     use codemap::CodeMap;
1703     use errors;
1704     use feature_gate::UnstableFeatures;
1705     use parse::token;
1706     use std::cell::RefCell;
1707     use std::collections::HashSet;
1708     use std::io;
1709     use std::rc::Rc;
1710
1711     fn mk_sess(cm: Rc<CodeMap>) -> ParseSess {
1712         let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()), Some(cm.clone()));
1713         ParseSess {
1714             span_diagnostic: errors::Handler::with_emitter(true, false, Box::new(emitter)),
1715             unstable_features: UnstableFeatures::from_environment(),
1716             config: CrateConfig::new(),
1717             included_mod_stack: RefCell::new(Vec::new()),
1718             code_map: cm,
1719             missing_fragment_specifiers: RefCell::new(HashSet::new()),
1720         }
1721     }
1722
1723     // open a string reader for the given string
1724     fn setup<'a>(cm: &CodeMap,
1725                  sess: &'a ParseSess,
1726                  teststr: String)
1727                  -> StringReader<'a> {
1728         let fm = cm.new_filemap("zebra.rs".to_string(), teststr);
1729         StringReader::new(sess, fm)
1730     }
1731
1732     #[test]
1733     fn t1() {
1734         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1735         let sh = mk_sess(cm.clone());
1736         let mut string_reader = setup(&cm,
1737                                       &sh,
1738                                       "/* my source file */ fn main() { println!(\"zebra\"); }\n"
1739                                           .to_string());
1740         let id = Ident::from_str("fn");
1741         assert_eq!(string_reader.next_token().tok, token::Comment);
1742         assert_eq!(string_reader.next_token().tok, token::Whitespace);
1743         let tok1 = string_reader.next_token();
1744         let tok2 = TokenAndSpan {
1745             tok: token::Ident(id),
1746             sp: Span {
1747                 lo: BytePos(21),
1748                 hi: BytePos(23),
1749                 ctxt: NO_EXPANSION,
1750             },
1751         };
1752         assert_eq!(tok1, tok2);
1753         assert_eq!(string_reader.next_token().tok, token::Whitespace);
1754         // the 'main' id is already read:
1755         assert_eq!(string_reader.pos.clone(), BytePos(28));
1756         // read another token:
1757         let tok3 = string_reader.next_token();
1758         let tok4 = TokenAndSpan {
1759             tok: token::Ident(Ident::from_str("main")),
1760             sp: Span {
1761                 lo: BytePos(24),
1762                 hi: BytePos(28),
1763                 ctxt: NO_EXPANSION,
1764             },
1765         };
1766         assert_eq!(tok3, tok4);
1767         // the lparen is already read:
1768         assert_eq!(string_reader.pos.clone(), BytePos(29))
1769     }
1770
1771     // check that the given reader produces the desired stream
1772     // of tokens (stop checking after exhausting the expected vec)
1773     fn check_tokenization(mut string_reader: StringReader, expected: Vec<token::Token>) {
1774         for expected_tok in &expected {
1775             assert_eq!(&string_reader.next_token().tok, expected_tok);
1776         }
1777     }
1778
1779     // make the identifier by looking up the string in the interner
1780     fn mk_ident(id: &str) -> token::Token {
1781         token::Ident(Ident::from_str(id))
1782     }
1783
1784     #[test]
1785     fn doublecolonparsing() {
1786         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1787         let sh = mk_sess(cm.clone());
1788         check_tokenization(setup(&cm, &sh, "a b".to_string()),
1789                            vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
1790     }
1791
1792     #[test]
1793     fn dcparsing_2() {
1794         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1795         let sh = mk_sess(cm.clone());
1796         check_tokenization(setup(&cm, &sh, "a::b".to_string()),
1797                            vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
1798     }
1799
1800     #[test]
1801     fn dcparsing_3() {
1802         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1803         let sh = mk_sess(cm.clone());
1804         check_tokenization(setup(&cm, &sh, "a ::b".to_string()),
1805                            vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
1806     }
1807
1808     #[test]
1809     fn dcparsing_4() {
1810         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1811         let sh = mk_sess(cm.clone());
1812         check_tokenization(setup(&cm, &sh, "a:: b".to_string()),
1813                            vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
1814     }
1815
1816     #[test]
1817     fn character_a() {
1818         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1819         let sh = mk_sess(cm.clone());
1820         assert_eq!(setup(&cm, &sh, "'a'".to_string()).next_token().tok,
1821                    token::Literal(token::Char(Symbol::intern("a")), None));
1822     }
1823
1824     #[test]
1825     fn character_space() {
1826         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1827         let sh = mk_sess(cm.clone());
1828         assert_eq!(setup(&cm, &sh, "' '".to_string()).next_token().tok,
1829                    token::Literal(token::Char(Symbol::intern(" ")), None));
1830     }
1831
1832     #[test]
1833     fn character_escaped() {
1834         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1835         let sh = mk_sess(cm.clone());
1836         assert_eq!(setup(&cm, &sh, "'\\n'".to_string()).next_token().tok,
1837                    token::Literal(token::Char(Symbol::intern("\\n")), None));
1838     }
1839
1840     #[test]
1841     fn lifetime_name() {
1842         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1843         let sh = mk_sess(cm.clone());
1844         assert_eq!(setup(&cm, &sh, "'abc".to_string()).next_token().tok,
1845                    token::Lifetime(Ident::from_str("'abc")));
1846     }
1847
1848     #[test]
1849     fn raw_string() {
1850         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1851         let sh = mk_sess(cm.clone());
1852         assert_eq!(setup(&cm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
1853                        .next_token()
1854                        .tok,
1855                    token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
1856     }
1857
1858     #[test]
1859     fn literal_suffixes() {
1860         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1861         let sh = mk_sess(cm.clone());
1862         macro_rules! test {
1863             ($input: expr, $tok_type: ident, $tok_contents: expr) => {{
1864                 assert_eq!(setup(&cm, &sh, format!("{}suffix", $input)).next_token().tok,
1865                            token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
1866                                           Some(Symbol::intern("suffix"))));
1867                 // with a whitespace separator:
1868                 assert_eq!(setup(&cm, &sh, format!("{} suffix", $input)).next_token().tok,
1869                            token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
1870                                           None));
1871             }}
1872         }
1873
1874         test!("'a'", Char, "a");
1875         test!("b'a'", Byte, "a");
1876         test!("\"a\"", Str_, "a");
1877         test!("b\"a\"", ByteStr, "a");
1878         test!("1234", Integer, "1234");
1879         test!("0b101", Integer, "0b101");
1880         test!("0xABC", Integer, "0xABC");
1881         test!("1.0", Float, "1.0");
1882         test!("1.0e10", Float, "1.0e10");
1883
1884         assert_eq!(setup(&cm, &sh, "2us".to_string()).next_token().tok,
1885                    token::Literal(token::Integer(Symbol::intern("2")),
1886                                   Some(Symbol::intern("us"))));
1887         assert_eq!(setup(&cm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
1888                    token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
1889                                   Some(Symbol::intern("suffix"))));
1890         assert_eq!(setup(&cm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
1891                    token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
1892                                   Some(Symbol::intern("suffix"))));
1893     }
1894
1895     #[test]
1896     fn line_doc_comments() {
1897         assert!(is_doc_comment("///"));
1898         assert!(is_doc_comment("/// blah"));
1899         assert!(!is_doc_comment("////"));
1900     }
1901
1902     #[test]
1903     fn nested_block_comments() {
1904         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1905         let sh = mk_sess(cm.clone());
1906         let mut lexer = setup(&cm, &sh, "/* /* */ */'a'".to_string());
1907         match lexer.next_token().tok {
1908             token::Comment => {}
1909             _ => panic!("expected a comment!"),
1910         }
1911         assert_eq!(lexer.next_token().tok,
1912                    token::Literal(token::Char(Symbol::intern("a")), None));
1913     }
1914
1915     #[test]
1916     fn crlf_comments() {
1917         let cm = Rc::new(CodeMap::new(FilePathMapping::empty()));
1918         let sh = mk_sess(cm.clone());
1919         let mut lexer = setup(&cm, &sh, "// test\r\n/// test\r\n".to_string());
1920         let comment = lexer.next_token();
1921         assert_eq!(comment.tok, token::Comment);
1922         assert_eq!((comment.sp.lo, comment.sp.hi), (BytePos(0), BytePos(7)));
1923         assert_eq!(lexer.next_token().tok, token::Whitespace);
1924         assert_eq!(lexer.next_token().tok,
1925                    token::DocComment(Symbol::intern("/// test")));
1926     }
1927 }