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