]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/mod.rs
Rollup merge of #58273 - taiki-e:rename-dependency, r=matthewjasper
[rust.git] / src / libsyntax / parse / mod.rs
1 //! The main parser interface.
2
3 use crate::ast::{self, CrateConfig, NodeId};
4 use crate::early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
5 use crate::source_map::{SourceMap, FilePathMapping};
6 use crate::feature_gate::UnstableFeatures;
7 use crate::parse::parser::Parser;
8 use crate::symbol::Symbol;
9 use crate::tokenstream::{TokenStream, TokenTree};
10 use crate::diagnostics::plugin::ErrorMap;
11 use crate::print::pprust::token_to_string;
12
13 use errors::{FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
14 use rustc_data_structures::sync::{Lrc, Lock};
15 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
16 use log::debug;
17
18 use rustc_data_structures::fx::FxHashSet;
19 use std::borrow::Cow;
20 use std::iter;
21 use std::path::{Path, PathBuf};
22 use std::str;
23
24 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
25
26 #[macro_use]
27 pub mod parser;
28
29 pub mod lexer;
30 pub mod token;
31 pub mod attr;
32
33 pub mod classify;
34
35 /// Info about a parsing session.
36 pub struct ParseSess {
37     pub span_diagnostic: Handler,
38     pub unstable_features: UnstableFeatures,
39     pub config: CrateConfig,
40     pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
41     /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
42     pub raw_identifier_spans: Lock<Vec<Span>>,
43     /// The registered diagnostics codes.
44     crate registered_diagnostics: Lock<ErrorMap>,
45     /// Used to determine and report recursive module inclusions.
46     included_mod_stack: Lock<Vec<PathBuf>>,
47     source_map: Lrc<SourceMap>,
48     pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
49 }
50
51 impl ParseSess {
52     pub fn new(file_path_mapping: FilePathMapping) -> Self {
53         let cm = Lrc::new(SourceMap::new(file_path_mapping));
54         let handler = Handler::with_tty_emitter(ColorConfig::Auto,
55                                                 true,
56                                                 false,
57                                                 Some(cm.clone()));
58         ParseSess::with_span_handler(handler, cm)
59     }
60
61     pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
62         ParseSess {
63             span_diagnostic: handler,
64             unstable_features: UnstableFeatures::from_environment(),
65             config: FxHashSet::default(),
66             missing_fragment_specifiers: Lock::new(FxHashSet::default()),
67             raw_identifier_spans: Lock::new(Vec::new()),
68             registered_diagnostics: Lock::new(ErrorMap::new()),
69             included_mod_stack: Lock::new(vec![]),
70             source_map,
71             buffered_lints: Lock::new(vec![]),
72         }
73     }
74
75     #[inline]
76     pub fn source_map(&self) -> &SourceMap {
77         &self.source_map
78     }
79
80     pub fn buffer_lint<S: Into<MultiSpan>>(&self,
81         lint_id: BufferedEarlyLintId,
82         span: S,
83         id: NodeId,
84         msg: &str,
85     ) {
86         self.buffered_lints.with_lock(|buffered_lints| {
87             buffered_lints.push(BufferedEarlyLint{
88                 span: span.into(),
89                 id,
90                 msg: msg.into(),
91                 lint_id,
92             });
93         });
94     }
95 }
96
97 #[derive(Clone)]
98 pub struct Directory<'a> {
99     pub path: Cow<'a, Path>,
100     pub ownership: DirectoryOwnership,
101 }
102
103 #[derive(Copy, Clone)]
104 pub enum DirectoryOwnership {
105     Owned {
106         // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
107         relative: Option<ast::Ident>,
108     },
109     UnownedViaBlock,
110     UnownedViaMod(bool /* legacy warnings? */),
111 }
112
113 // a bunch of utility functions of the form parse_<thing>_from_<source>
114 // where <thing> includes crate, expr, item, stmt, tts, and one that
115 // uses a HOF to parse anything, and <source> includes file and
116 // source_str.
117
118 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
119     let mut parser = new_parser_from_file(sess, input);
120     parser.parse_crate_mod()
121 }
122
123 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
124                                        -> PResult<'a, Vec<ast::Attribute>> {
125     let mut parser = new_parser_from_file(sess, input);
126     parser.parse_inner_attributes()
127 }
128
129 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
130                                        -> PResult<'_, ast::Crate> {
131     new_parser_from_source_str(sess, name, source).parse_crate_mod()
132 }
133
134 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
135                                              -> PResult<'_, Vec<ast::Attribute>> {
136     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
137 }
138
139 pub fn parse_stream_from_source_str(
140     name: FileName,
141     source: String,
142     sess: &ParseSess,
143     override_span: Option<Span>,
144 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
145     source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span)
146 }
147
148 /// Creates a new parser from a source string.
149 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
150     panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
151 }
152
153 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
154 /// token stream.
155 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
156     -> Result<Parser<'_>, Vec<Diagnostic>>
157 {
158     let mut parser = maybe_source_file_to_parser(sess,
159                                                  sess.source_map().new_source_file(name, source))?;
160     parser.recurse_into_file_modules = false;
161     Ok(parser)
162 }
163
164 /// Creates a new parser, handling errors as appropriate
165 /// if the file doesn't exist
166 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
167     source_file_to_parser(sess, file_to_source_file(sess, path, None))
168 }
169
170 /// Creates a new parser, returning buffered diagnostics if the file doesn't
171 /// exist or from lexing the initial token stream.
172 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
173     -> Result<Parser<'a>, Vec<Diagnostic>> {
174     let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
175     maybe_source_file_to_parser(sess, file)
176 }
177
178 /// Given a session, a crate config, a path, and a span, add
179 /// the file at the given path to the source_map, and return a parser.
180 /// On an error, use the given span as the source of the problem.
181 crate fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
182                                     path: &Path,
183                                     directory_ownership: DirectoryOwnership,
184                                     module_name: Option<String>,
185                                     sp: Span) -> Parser<'a> {
186     let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
187     p.directory.ownership = directory_ownership;
188     p.root_module_name = module_name;
189     p
190 }
191
192 /// Given a source_file and config, return a parser
193 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
194     panictry_buffer!(&sess.span_diagnostic,
195                      maybe_source_file_to_parser(sess, source_file))
196 }
197
198 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
199 /// initial token stream.
200 fn maybe_source_file_to_parser(
201     sess: &ParseSess,
202     source_file: Lrc<SourceFile>,
203 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
204     let end_pos = source_file.end_pos;
205     let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
206     let mut parser = stream_to_parser(sess, stream);
207     parser.unclosed_delims = unclosed_delims;
208     if parser.token == token::Eof && parser.span.is_dummy() {
209         parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
210     }
211
212     Ok(parser)
213 }
214
215 // must preserve old name for now, because quote! from the *existing*
216 // compiler expands into it
217 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
218     stream_to_parser(sess, tts.into_iter().collect())
219 }
220
221
222 // base abstractions
223
224 /// Given a session and a path and an optional span (for error reporting),
225 /// add the path to the session's source_map and return the new source_file or
226 /// error when a file can't be read.
227 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
228                    -> Result<Lrc<SourceFile>, Diagnostic> {
229     sess.source_map().load_file(path)
230     .map_err(|e| {
231         let msg = format!("couldn't read {}: {}", path.display(), e);
232         let mut diag = Diagnostic::new(Level::Fatal, &msg);
233         if let Some(sp) = spanopt {
234             diag.set_span(sp);
235         }
236         diag
237     })
238 }
239
240 /// Given a session and a path and an optional span (for error reporting),
241 /// add the path to the session's `source_map` and return the new `source_file`.
242 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
243                    -> Lrc<SourceFile> {
244     match try_file_to_source_file(sess, path, spanopt) {
245         Ok(source_file) => source_file,
246         Err(d) => {
247             DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
248             FatalError.raise();
249         }
250     }
251 }
252
253 /// Given a source_file, produces a sequence of token trees.
254 pub fn source_file_to_stream(
255     sess: &ParseSess,
256     source_file: Lrc<SourceFile>,
257     override_span: Option<Span>,
258 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
259     panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
260 }
261
262 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
263 /// parsing the token tream.
264 pub fn maybe_file_to_stream(
265     sess: &ParseSess,
266     source_file: Lrc<SourceFile>,
267     override_span: Option<Span>,
268 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
269     let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
270     srdr.real_token();
271
272     match srdr.parse_all_token_trees() {
273         Ok(stream) => Ok((stream, srdr.unmatched_braces)),
274         Err(err) => {
275             let mut buffer = Vec::with_capacity(1);
276             err.buffer(&mut buffer);
277             // Not using `emit_unclosed_delims` to use `db.buffer`
278             for unmatched in srdr.unmatched_braces {
279                 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
280                     "incorrect close delimiter: `{}`",
281                     token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
282                 ));
283                 db.span_label(unmatched.found_span, "incorrect close delimiter");
284                 if let Some(sp) = unmatched.candidate_span {
285                     db.span_label(sp, "close delimiter possibly meant for this");
286                 }
287                 if let Some(sp) = unmatched.unclosed_span {
288                     db.span_label(sp, "un-closed delimiter");
289                 }
290                 db.buffer(&mut buffer);
291             }
292             Err(buffer)
293         }
294     }
295 }
296
297 /// Given stream and the `ParseSess`, produces a parser.
298 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
299     Parser::new(sess, stream, None, true, false)
300 }
301
302 /// Parses a string representing a character literal into its final form.
303 /// Rather than just accepting/rejecting a given literal, unescapes it as
304 /// well. Can take any slice prefixed by a character escape. Returns the
305 /// character and the number of characters consumed.
306 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
307     use std::char;
308
309     // Handle non-escaped chars first.
310     if lit.as_bytes()[0] != b'\\' {
311         // If the first byte isn't '\\' it might part of a multi-byte char, so
312         // get the char with chars().
313         let c = lit.chars().next().unwrap();
314         return (c, 1);
315     }
316
317     // Handle escaped chars.
318     match lit.as_bytes()[1] as char {
319         '"' => ('"', 2),
320         'n' => ('\n', 2),
321         'r' => ('\r', 2),
322         't' => ('\t', 2),
323         '\\' => ('\\', 2),
324         '\'' => ('\'', 2),
325         '0' => ('\0', 2),
326         'x' => {
327             let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
328             let c = char::from_u32(v).unwrap();
329             (c, 4)
330         }
331         'u' => {
332             assert_eq!(lit.as_bytes()[2], b'{');
333             let idx = lit.find('}').unwrap();
334
335             // All digits and '_' are ascii, so treat each byte as a char.
336             let mut v: u32 = 0;
337             for c in lit[3..idx].bytes() {
338                 let c = char::from(c);
339                 if c != '_' {
340                     let x = c.to_digit(16).unwrap();
341                     v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
342                 }
343             }
344             let c = char::from_u32(v).unwrap_or_else(|| {
345                 if let Some((span, diag)) = diag {
346                     let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
347                     if v > 0x10FFFF {
348                         diag.help("unicode escape must be at most 10FFFF").emit();
349                     } else {
350                         diag.help("unicode escape must not be a surrogate").emit();
351                     }
352                 }
353                 '\u{FFFD}'
354             });
355             (c, (idx + 1) as isize)
356         }
357         _ => panic!("lexer should have rejected a bad character escape {}", lit)
358     }
359 }
360
361 /// Parses a string representing a string literal into its final form. Does unescaping.
362 pub fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
363     debug!("str_lit: given {}", lit.escape_default());
364     let mut res = String::with_capacity(lit.len());
365
366     let error = |i| format!("lexer should have rejected {} at {}", lit, i);
367
368     /// Eat everything up to a non-whitespace.
369     fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
370         loop {
371             match it.peek().map(|x| x.1) {
372                 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
373                     it.next();
374                 },
375                 _ => { break; }
376             }
377         }
378     }
379
380     let mut chars = lit.char_indices().peekable();
381     while let Some((i, c)) = chars.next() {
382         match c {
383             '\\' => {
384                 let ch = chars.peek().unwrap_or_else(|| {
385                     panic!("{}", error(i))
386                 }).1;
387
388                 if ch == '\n' {
389                     eat(&mut chars);
390                 } else if ch == '\r' {
391                     chars.next();
392                     let ch = chars.peek().unwrap_or_else(|| {
393                         panic!("{}", error(i))
394                     }).1;
395
396                     if ch != '\n' {
397                         panic!("lexer accepted bare CR");
398                     }
399                     eat(&mut chars);
400                 } else {
401                     // otherwise, a normal escape
402                     let (c, n) = char_lit(&lit[i..], diag);
403                     for _ in 0..n - 1 { // we don't need to move past the first \
404                         chars.next();
405                     }
406                     res.push(c);
407                 }
408             },
409             '\r' => {
410                 let ch = chars.peek().unwrap_or_else(|| {
411                     panic!("{}", error(i))
412                 }).1;
413
414                 if ch != '\n' {
415                     panic!("lexer accepted bare CR");
416                 }
417                 chars.next();
418                 res.push('\n');
419             }
420             c => res.push(c),
421         }
422     }
423
424     res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
425     debug!("parse_str_lit: returning {}", res);
426     res
427 }
428
429 /// Parses a string representing a raw string literal into its final form. The
430 /// only operation this does is convert embedded CRLF into a single LF.
431 fn raw_str_lit(lit: &str) -> String {
432     debug!("raw_str_lit: given {}", lit.escape_default());
433     let mut res = String::with_capacity(lit.len());
434
435     let mut chars = lit.chars().peekable();
436     while let Some(c) = chars.next() {
437         if c == '\r' {
438             if *chars.peek().unwrap() != '\n' {
439                 panic!("lexer accepted bare CR");
440             }
441             chars.next();
442             res.push('\n');
443         } else {
444             res.push(c);
445         }
446     }
447
448     res.shrink_to_fit();
449     res
450 }
451
452 // check if `s` looks like i32 or u1234 etc.
453 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
454     s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
455 }
456
457 macro_rules! err {
458     ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
459         match $opt_diag {
460             Some(($span, $diag)) => { $($body)* }
461             None => return None,
462         }
463     }
464 }
465
466 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
467                  -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
468     use ast::LitKind;
469
470     match lit {
471        token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
472        token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
473        token::Err(i) => (true, Some(LitKind::Err(i))),
474
475         // There are some valid suffixes for integer and float literals,
476         // so all the handling is done internally.
477         token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
478         token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
479
480         token::Str_(mut sym) => {
481             // If there are no characters requiring special treatment we can
482             // reuse the symbol from the Token. Otherwise, we must generate a
483             // new symbol because the string in the LitKind is different to the
484             // string in the Token.
485             let s = &sym.as_str();
486             if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
487                 sym = Symbol::intern(&str_lit(s, diag));
488             }
489             (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
490         }
491         token::StrRaw(mut sym, n) => {
492             // Ditto.
493             let s = &sym.as_str();
494             if s.contains('\r') {
495                 sym = Symbol::intern(&raw_str_lit(s));
496             }
497             (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
498         }
499         token::ByteStr(i) => {
500             (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
501         }
502         token::ByteStrRaw(i, _) => {
503             (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
504         }
505     }
506 }
507
508 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
509                       -> Option<ast::LitKind> {
510     debug!("filtered_float_lit: {}, {:?}", data, suffix);
511     let suffix = match suffix {
512         Some(suffix) => suffix,
513         None => return Some(ast::LitKind::FloatUnsuffixed(data)),
514     };
515
516     Some(match &*suffix.as_str() {
517         "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
518         "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
519         suf => {
520             err!(diag, |span, diag| {
521                 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
522                     // if it looks like a width, lets try to be helpful.
523                     let msg = format!("invalid width `{}` for float literal", &suf[1..]);
524                     diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
525                 } else {
526                     let msg = format!("invalid suffix `{}` for float literal", suf);
527                     diag.struct_span_err(span, &msg)
528                         .span_label(span, format!("invalid suffix `{}`", suf))
529                         .help("valid suffixes are `f32` and `f64`")
530                         .emit();
531                 }
532             });
533
534             ast::LitKind::FloatUnsuffixed(data)
535         }
536     })
537 }
538 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
539                  -> Option<ast::LitKind> {
540     debug!("float_lit: {:?}, {:?}", s, suffix);
541     // FIXME #2252: bounds checking float literals is deferred until trans
542
543     // Strip underscores without allocating a new String unless necessary.
544     let s2;
545     let s = if s.chars().any(|c| c == '_') {
546         s2 = s.chars().filter(|&c| c != '_').collect::<String>();
547         &s2
548     } else {
549         s
550     };
551
552     filtered_float_lit(Symbol::intern(s), suffix, diag)
553 }
554
555 /// Parses a string representing a byte literal into its final form. Similar to `char_lit`.
556 fn byte_lit(lit: &str) -> (u8, usize) {
557     let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
558
559     if lit.len() == 1 {
560         (lit.as_bytes()[0], 1)
561     } else {
562         assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
563         let b = match lit.as_bytes()[1] {
564             b'"' => b'"',
565             b'n' => b'\n',
566             b'r' => b'\r',
567             b't' => b'\t',
568             b'\\' => b'\\',
569             b'\'' => b'\'',
570             b'0' => b'\0',
571             _ => {
572                 match u64::from_str_radix(&lit[2..4], 16).ok() {
573                     Some(c) =>
574                         if c > 0xFF {
575                             panic!(err(2))
576                         } else {
577                             return (c as u8, 4)
578                         },
579                     None => panic!(err(3))
580                 }
581             }
582         };
583         (b, 2)
584     }
585 }
586
587 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
588     let mut res = Vec::with_capacity(lit.len());
589
590     let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
591
592     /// Eat everything up to a non-whitespace.
593     fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
594         loop {
595             match it.peek().map(|x| x.1) {
596                 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
597                     it.next();
598                 },
599                 _ => { break; }
600             }
601         }
602     }
603
604     // byte string literals *must* be ASCII, but the escapes don't have to be
605     let mut chars = lit.bytes().enumerate().peekable();
606     loop {
607         match chars.next() {
608             Some((i, b'\\')) => {
609                 match chars.peek().unwrap_or_else(|| error(i)).1 {
610                     b'\n' => eat(&mut chars),
611                     b'\r' => {
612                         chars.next();
613                         if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
614                             panic!("lexer accepted bare CR");
615                         }
616                         eat(&mut chars);
617                     }
618                     _ => {
619                         // otherwise, a normal escape
620                         let (c, n) = byte_lit(&lit[i..]);
621                         // we don't need to move past the first \
622                         for _ in 0..n - 1 {
623                             chars.next();
624                         }
625                         res.push(c);
626                     }
627                 }
628             },
629             Some((i, b'\r')) => {
630                 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
631                     panic!("lexer accepted bare CR");
632                 }
633                 chars.next();
634                 res.push(b'\n');
635             }
636             Some((_, c)) => res.push(c),
637             None => break,
638         }
639     }
640
641     Lrc::new(res)
642 }
643
644 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
645                    -> Option<ast::LitKind> {
646     // s can only be ascii, byte indexing is fine
647
648     // Strip underscores without allocating a new String unless necessary.
649     let s2;
650     let mut s = if s.chars().any(|c| c == '_') {
651         s2 = s.chars().filter(|&c| c != '_').collect::<String>();
652         &s2
653     } else {
654         s
655     };
656
657     debug!("integer_lit: {}, {:?}", s, suffix);
658
659     let mut base = 10;
660     let orig = s;
661     let mut ty = ast::LitIntType::Unsuffixed;
662
663     if s.starts_with('0') && s.len() > 1 {
664         match s.as_bytes()[1] {
665             b'x' => base = 16,
666             b'o' => base = 8,
667             b'b' => base = 2,
668             _ => { }
669         }
670     }
671
672     // 1f64 and 2f32 etc. are valid float literals.
673     if let Some(suf) = suffix {
674         if looks_like_width_suffix(&['f'], &suf.as_str()) {
675             let err = match base {
676                 16 => Some("hexadecimal float literal is not supported"),
677                 8 => Some("octal float literal is not supported"),
678                 2 => Some("binary float literal is not supported"),
679                 _ => None,
680             };
681             if let Some(err) = err {
682                 err!(diag, |span, diag| {
683                     diag.struct_span_err(span, err)
684                         .span_label(span, "not supported")
685                         .emit();
686                 });
687             }
688             return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
689         }
690     }
691
692     if base != 10 {
693         s = &s[2..];
694     }
695
696     if let Some(suf) = suffix {
697         if suf.as_str().is_empty() {
698             err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
699         }
700         ty = match &*suf.as_str() {
701             "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
702             "i8"  => ast::LitIntType::Signed(ast::IntTy::I8),
703             "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
704             "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
705             "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
706             "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
707             "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
708             "u8"  => ast::LitIntType::Unsigned(ast::UintTy::U8),
709             "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
710             "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
711             "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
712             "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
713             suf => {
714                 // i<digits> and u<digits> look like widths, so lets
715                 // give an error message along those lines
716                 err!(diag, |span, diag| {
717                     if looks_like_width_suffix(&['i', 'u'], suf) {
718                         let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
719                         diag.struct_span_err(span, &msg)
720                             .help("valid widths are 8, 16, 32, 64 and 128")
721                             .emit();
722                     } else {
723                         let msg = format!("invalid suffix `{}` for numeric literal", suf);
724                         diag.struct_span_err(span, &msg)
725                             .span_label(span, format!("invalid suffix `{}`", suf))
726                             .help("the suffix must be one of the integral types \
727                                    (`u32`, `isize`, etc)")
728                             .emit();
729                     }
730                 });
731
732                 ty
733             }
734         }
735     }
736
737     debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
738            string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
739
740     Some(match u128::from_str_radix(s, base) {
741         Ok(r) => ast::LitKind::Int(r, ty),
742         Err(_) => {
743             // small bases are lexed as if they were base 10, e.g, the string
744             // might be `0b10201`. This will cause the conversion above to fail,
745             // but these cases have errors in the lexer: we don't want to emit
746             // two errors, and we especially don't want to emit this error since
747             // it isn't necessarily true.
748             let already_errored = base < 10 &&
749                 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
750
751             if !already_errored {
752                 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
753             }
754             ast::LitKind::Int(0, ty)
755         }
756     })
757 }
758
759 /// A sequence separator.
760 pub struct SeqSep {
761     /// The seperator token.
762     pub sep: Option<token::Token>,
763     /// `true` if a trailing separator is allowed.
764     pub trailing_sep_allowed: bool,
765 }
766
767 impl SeqSep {
768     pub fn trailing_allowed(t: token::Token) -> SeqSep {
769         SeqSep {
770             sep: Some(t),
771             trailing_sep_allowed: true,
772         }
773     }
774
775     pub fn none() -> SeqSep {
776         SeqSep {
777             sep: None,
778             trailing_sep_allowed: false,
779         }
780     }
781 }
782
783 #[cfg(test)]
784 mod tests {
785     use super::*;
786     use crate::ast::{self, Ident, PatKind};
787     use crate::attr::first_attr_value_str_by_name;
788     use crate::ptr::P;
789     use crate::print::pprust::item_to_string;
790     use crate::tokenstream::{DelimSpan, TokenTree};
791     use crate::util::parser_testing::string_to_stream;
792     use crate::util::parser_testing::{string_to_expr, string_to_item};
793     use crate::with_globals;
794     use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
795
796     /// Parses an item.
797     ///
798     /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
799     /// when a syntax error occurred.
800     fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
801                                         -> PResult<'_, Option<P<ast::Item>>> {
802         new_parser_from_source_str(sess, name, source).parse_item()
803     }
804
805     // produce a syntax_pos::span
806     fn sp(a: u32, b: u32) -> Span {
807         Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
808     }
809
810     #[should_panic]
811     #[test] fn bad_path_expr_1() {
812         with_globals(|| {
813             string_to_expr("::abc::def::return".to_string());
814         })
815     }
816
817     // check the token-tree-ization of macros
818     #[test]
819     fn string_to_tts_macro () {
820         with_globals(|| {
821             let tts: Vec<_> =
822                 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
823             let tts: &[TokenTree] = &tts[..];
824
825             match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
826                 (
827                     4,
828                     Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
829                     Some(&TokenTree::Token(_, token::Not)),
830                     Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
831                     Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
832                 )
833                 if name_macro_rules.name == "macro_rules"
834                 && name_zip.name == "zip" => {
835                     let tts = &macro_tts.trees().collect::<Vec<_>>();
836                     match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
837                         (
838                             3,
839                             Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
840                             Some(&TokenTree::Token(_, token::FatArrow)),
841                             Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
842                         )
843                         if macro_delim == token::Paren => {
844                             let tts = &first_tts.trees().collect::<Vec<_>>();
845                             match (tts.len(), tts.get(0), tts.get(1)) {
846                                 (
847                                     2,
848                                     Some(&TokenTree::Token(_, token::Dollar)),
849                                     Some(&TokenTree::Token(_, token::Ident(ident, false))),
850                                 )
851                                 if first_delim == token::Paren && ident.name == "a" => {},
852                                 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
853                             }
854                             let tts = &second_tts.trees().collect::<Vec<_>>();
855                             match (tts.len(), tts.get(0), tts.get(1)) {
856                                 (
857                                     2,
858                                     Some(&TokenTree::Token(_, token::Dollar)),
859                                     Some(&TokenTree::Token(_, token::Ident(ident, false))),
860                                 )
861                                 if second_delim == token::Paren && ident.name == "a" => {},
862                                 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
863                             }
864                         },
865                         _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
866                     }
867                 },
868                 _ => panic!("value: {:?}",tts),
869             }
870         })
871     }
872
873     #[test]
874     fn string_to_tts_1() {
875         with_globals(|| {
876             let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
877
878             let expected = TokenStream::new(vec![
879                 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
880                 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
881                 TokenTree::Delimited(
882                     DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
883                     token::DelimToken::Paren,
884                     TokenStream::new(vec![
885                         TokenTree::Token(sp(6, 7),
886                                          token::Ident(Ident::from_str("b"), false)).into(),
887                         TokenTree::Token(sp(8, 9), token::Colon).into(),
888                         TokenTree::Token(sp(10, 13),
889                                          token::Ident(Ident::from_str("i32"), false)).into(),
890                     ]).into(),
891                 ).into(),
892                 TokenTree::Delimited(
893                     DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
894                     token::DelimToken::Brace,
895                     TokenStream::new(vec![
896                         TokenTree::Token(sp(17, 18),
897                                          token::Ident(Ident::from_str("b"), false)).into(),
898                         TokenTree::Token(sp(18, 19), token::Semi).into(),
899                     ]).into(),
900                 ).into()
901             ]);
902
903             assert_eq!(tts, expected);
904         })
905     }
906
907     #[test] fn parse_use() {
908         with_globals(|| {
909             let use_s = "use foo::bar::baz;";
910             let vitem = string_to_item(use_s.to_string()).unwrap();
911             let vitem_s = item_to_string(&vitem);
912             assert_eq!(&vitem_s[..], use_s);
913
914             let use_s = "use foo::bar as baz;";
915             let vitem = string_to_item(use_s.to_string()).unwrap();
916             let vitem_s = item_to_string(&vitem);
917             assert_eq!(&vitem_s[..], use_s);
918         })
919     }
920
921     #[test] fn parse_extern_crate() {
922         with_globals(|| {
923             let ex_s = "extern crate foo;";
924             let vitem = string_to_item(ex_s.to_string()).unwrap();
925             let vitem_s = item_to_string(&vitem);
926             assert_eq!(&vitem_s[..], ex_s);
927
928             let ex_s = "extern crate foo as bar;";
929             let vitem = string_to_item(ex_s.to_string()).unwrap();
930             let vitem_s = item_to_string(&vitem);
931             assert_eq!(&vitem_s[..], ex_s);
932         })
933     }
934
935     fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
936         let item = string_to_item(src.to_string()).unwrap();
937
938         struct PatIdentVisitor {
939             spans: Vec<Span>
940         }
941         impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
942             fn visit_pat(&mut self, p: &'a ast::Pat) {
943                 match p.node {
944                     PatKind::Ident(_ , ref spannedident, _) => {
945                         self.spans.push(spannedident.span.clone());
946                     }
947                     _ => {
948                         crate::visit::walk_pat(self, p);
949                     }
950                 }
951             }
952         }
953         let mut v = PatIdentVisitor { spans: Vec::new() };
954         crate::visit::walk_item(&mut v, &item);
955         return v.spans;
956     }
957
958     #[test] fn span_of_self_arg_pat_idents_are_correct() {
959         with_globals(|| {
960
961             let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
962                         "impl z { fn a (&mut self, &myarg: i32) {} }",
963                         "impl z { fn a (&'a self, &myarg: i32) {} }",
964                         "impl z { fn a (self, &myarg: i32) {} }",
965                         "impl z { fn a (self: Foo, &myarg: i32) {} }",
966                         ];
967
968             for &src in &srcs {
969                 let spans = get_spans_of_pat_idents(src);
970                 let (lo, hi) = (spans[0].lo(), spans[0].hi());
971                 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
972                         "\"{}\" != \"self\". src=\"{}\"",
973                         &src[lo.to_usize()..hi.to_usize()], src)
974             }
975         })
976     }
977
978     #[test] fn parse_exprs () {
979         with_globals(|| {
980             // just make sure that they parse....
981             string_to_expr("3 + 4".to_string());
982             string_to_expr("a::z.froob(b,&(987+3))".to_string());
983         })
984     }
985
986     #[test] fn attrs_fix_bug () {
987         with_globals(|| {
988             string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
989                    -> Result<Box<Writer>, String> {
990     #[cfg(windows)]
991     fn wb() -> c_int {
992       (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
993     }
994
995     #[cfg(unix)]
996     fn wb() -> c_int { O_WRONLY as c_int }
997
998     let mut fflags: c_int = wb();
999 }".to_string());
1000         })
1001     }
1002
1003     #[test] fn crlf_doc_comments() {
1004         with_globals(|| {
1005             let sess = ParseSess::new(FilePathMapping::empty());
1006
1007             let name_1 = FileName::Custom("crlf_source_1".to_string());
1008             let source = "/// doc comment\r\nfn foo() {}".to_string();
1009             let item = parse_item_from_source_str(name_1, source, &sess)
1010                 .unwrap().unwrap();
1011             let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1012             assert_eq!(doc, "/// doc comment");
1013
1014             let name_2 = FileName::Custom("crlf_source_2".to_string());
1015             let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1016             let item = parse_item_from_source_str(name_2, source, &sess)
1017                 .unwrap().unwrap();
1018             let docs = item.attrs.iter().filter(|a| a.path == "doc")
1019                         .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1020             let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1021             assert_eq!(&docs[..], b);
1022
1023             let name_3 = FileName::Custom("clrf_source_3".to_string());
1024             let source = "/** doc comment\r\n *  with CRLF */\r\nfn foo() {}".to_string();
1025             let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
1026             let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1027             assert_eq!(doc, "/** doc comment\n *  with CRLF */");
1028         });
1029     }
1030
1031     #[test]
1032     fn ttdelim_span() {
1033         fn parse_expr_from_source_str(
1034             name: FileName, source: String, sess: &ParseSess
1035         ) -> PResult<'_, P<ast::Expr>> {
1036             new_parser_from_source_str(sess, name, source).parse_expr()
1037         }
1038
1039         with_globals(|| {
1040             let sess = ParseSess::new(FilePathMapping::empty());
1041             let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
1042                 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1043
1044             let tts: Vec<_> = match expr.node {
1045                 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1046                 _ => panic!("not a macro"),
1047             };
1048
1049             let span = tts.iter().rev().next().unwrap().span();
1050
1051             match sess.source_map().span_to_snippet(span) {
1052                 Ok(s) => assert_eq!(&s[..], "{ body }"),
1053                 Err(_) => panic!("could not get snippet"),
1054             }
1055         });
1056     }
1057
1058     // This tests that when parsing a string (rather than a file) we don't try
1059     // and read in a file for a module declaration and just parse a stub.
1060     // See `recurse_into_file_modules` in the parser.
1061     #[test]
1062     fn out_of_line_mod() {
1063         with_globals(|| {
1064             let sess = ParseSess::new(FilePathMapping::empty());
1065             let item = parse_item_from_source_str(
1066                 PathBuf::from("foo").into(),
1067                 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1068                 &sess,
1069             ).unwrap().unwrap();
1070
1071             if let ast::ItemKind::Mod(ref m) = item.node {
1072                 assert!(m.items.len() == 2);
1073             } else {
1074                 panic!();
1075             }
1076         });
1077     }
1078 }