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