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