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