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