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