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