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