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