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