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