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