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