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