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