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