]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/mod.rs
Move token tree related lexer state to a separate struct
[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 stream.
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     let (token_trees, unmatched_braces) = srdr.into_token_trees();
307
308     match token_trees {
309         Ok(stream) => Ok((stream, unmatched_braces)),
310         Err(err) => {
311             let mut buffer = Vec::with_capacity(1);
312             err.buffer(&mut buffer);
313             // Not using `emit_unclosed_delims` to use `db.buffer`
314             for unmatched in unmatched_braces {
315                 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
316                     "incorrect close delimiter: `{}`",
317                     token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
318                 ));
319                 db.span_label(unmatched.found_span, "incorrect close delimiter");
320                 if let Some(sp) = unmatched.candidate_span {
321                     db.span_label(sp, "close delimiter possibly meant for this");
322                 }
323                 if let Some(sp) = unmatched.unclosed_span {
324                     db.span_label(sp, "un-closed delimiter");
325                 }
326                 db.buffer(&mut buffer);
327             }
328             Err(buffer)
329         }
330     }
331 }
332
333 /// Given stream and the `ParseSess`, produces a parser.
334 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
335     Parser::new(sess, stream, None, true, false)
336 }
337
338 /// Parses a string representing a raw string literal into its final form. The
339 /// only operation this does is convert embedded CRLF into a single LF.
340 fn raw_str_lit(lit: &str) -> String {
341     debug!("raw_str_lit: given {}", lit.escape_default());
342     let mut res = String::with_capacity(lit.len());
343
344     let mut chars = lit.chars().peekable();
345     while let Some(c) = chars.next() {
346         if c == '\r' {
347             if *chars.peek().unwrap() != '\n' {
348                 panic!("lexer accepted bare CR");
349             }
350             chars.next();
351             res.push('\n');
352         } else {
353             res.push(c);
354         }
355     }
356
357     res.shrink_to_fit();
358     res
359 }
360
361 // check if `s` looks like i32 or u1234 etc.
362 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
363     s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
364 }
365
366 macro_rules! err {
367     ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
368         match $opt_diag {
369             Some(($span, $diag)) => { $($body)* }
370             None => return None,
371         }
372     }
373 }
374
375 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
376                  -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
377     use ast::LitKind;
378
379     match lit {
380         token::Byte(i) => {
381             let lit_kind = match unescape_byte(&i.as_str()) {
382                 Ok(c) => LitKind::Byte(c),
383                 Err(_) => LitKind::Err(i),
384             };
385             (true, Some(lit_kind))
386         },
387         token::Char(i) => {
388             let lit_kind = match unescape_char(&i.as_str()) {
389                 Ok(c) => LitKind::Char(c),
390                 Err(_) => LitKind::Err(i),
391             };
392             (true, Some(lit_kind))
393         },
394         token::Err(i) => (true, Some(LitKind::Err(i))),
395
396         // There are some valid suffixes for integer and float literals,
397         // so all the handling is done internally.
398         token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
399         token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
400
401         token::Str_(mut sym) => {
402             // If there are no characters requiring special treatment we can
403             // reuse the symbol from the Token. Otherwise, we must generate a
404             // new symbol because the string in the LitKind is different to the
405             // string in the Token.
406             let mut has_error = false;
407             let s = &sym.as_str();
408             if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
409                 let mut buf = String::with_capacity(s.len());
410                 unescape_str(s, &mut |_, unescaped_char| {
411                     match unescaped_char {
412                         Ok(c) => buf.push(c),
413                         Err(_) => has_error = true,
414                     }
415                 });
416                 if has_error {
417                     return (true, Some(LitKind::Err(sym)));
418                 }
419                 sym = Symbol::intern(&buf)
420             }
421
422             (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
423         }
424         token::StrRaw(mut sym, n) => {
425             // Ditto.
426             let s = &sym.as_str();
427             if s.contains('\r') {
428                 sym = Symbol::intern(&raw_str_lit(s));
429             }
430             (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
431         }
432         token::ByteStr(i) => {
433             let s = &i.as_str();
434             let mut buf = Vec::with_capacity(s.len());
435             let mut has_error = false;
436             unescape_byte_str(s, &mut |_, unescaped_byte| {
437                 match unescaped_byte {
438                     Ok(c) => buf.push(c),
439                     Err(_) => has_error = true,
440                 }
441             });
442             if has_error {
443                 return (true, Some(LitKind::Err(i)));
444             }
445             buf.shrink_to_fit();
446             (true, Some(LitKind::ByteStr(Lrc::new(buf))))
447         }
448         token::ByteStrRaw(i, _) => {
449             (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
450         }
451     }
452 }
453
454 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
455                       -> Option<ast::LitKind> {
456     debug!("filtered_float_lit: {}, {:?}", data, suffix);
457     let suffix = match suffix {
458         Some(suffix) => suffix,
459         None => return Some(ast::LitKind::FloatUnsuffixed(data)),
460     };
461
462     Some(match &*suffix.as_str() {
463         "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
464         "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
465         suf => {
466             err!(diag, |span, diag| {
467                 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
468                     // if it looks like a width, lets try to be helpful.
469                     let msg = format!("invalid width `{}` for float literal", &suf[1..]);
470                     diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
471                 } else {
472                     let msg = format!("invalid suffix `{}` for float literal", suf);
473                     diag.struct_span_err(span, &msg)
474                         .span_label(span, format!("invalid suffix `{}`", suf))
475                         .help("valid suffixes are `f32` and `f64`")
476                         .emit();
477                 }
478             });
479
480             ast::LitKind::FloatUnsuffixed(data)
481         }
482     })
483 }
484 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
485                  -> Option<ast::LitKind> {
486     debug!("float_lit: {:?}, {:?}", s, suffix);
487     // FIXME #2252: bounds checking float literals is deferred until trans
488
489     // Strip underscores without allocating a new String unless necessary.
490     let s2;
491     let s = if s.chars().any(|c| c == '_') {
492         s2 = s.chars().filter(|&c| c != '_').collect::<String>();
493         &s2
494     } else {
495         s
496     };
497
498     filtered_float_lit(Symbol::intern(s), suffix, diag)
499 }
500
501 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
502                    -> Option<ast::LitKind> {
503     // s can only be ascii, byte indexing is fine
504
505     // Strip underscores without allocating a new String unless necessary.
506     let s2;
507     let mut s = if s.chars().any(|c| c == '_') {
508         s2 = s.chars().filter(|&c| c != '_').collect::<String>();
509         &s2
510     } else {
511         s
512     };
513
514     debug!("integer_lit: {}, {:?}", s, suffix);
515
516     let mut base = 10;
517     let orig = s;
518     let mut ty = ast::LitIntType::Unsuffixed;
519
520     if s.starts_with('0') && s.len() > 1 {
521         match s.as_bytes()[1] {
522             b'x' => base = 16,
523             b'o' => base = 8,
524             b'b' => base = 2,
525             _ => { }
526         }
527     }
528
529     // 1f64 and 2f32 etc. are valid float literals.
530     if let Some(suf) = suffix {
531         if looks_like_width_suffix(&['f'], &suf.as_str()) {
532             let err = match base {
533                 16 => Some("hexadecimal float literal is not supported"),
534                 8 => Some("octal float literal is not supported"),
535                 2 => Some("binary float literal is not supported"),
536                 _ => None,
537             };
538             if let Some(err) = err {
539                 err!(diag, |span, diag| {
540                     diag.struct_span_err(span, err)
541                         .span_label(span, "not supported")
542                         .emit();
543                 });
544             }
545             return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
546         }
547     }
548
549     if base != 10 {
550         s = &s[2..];
551     }
552
553     if let Some(suf) = suffix {
554         if suf.as_str().is_empty() {
555             err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
556         }
557         ty = match &*suf.as_str() {
558             "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
559             "i8"  => ast::LitIntType::Signed(ast::IntTy::I8),
560             "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
561             "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
562             "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
563             "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
564             "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
565             "u8"  => ast::LitIntType::Unsigned(ast::UintTy::U8),
566             "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
567             "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
568             "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
569             "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
570             suf => {
571                 // i<digits> and u<digits> look like widths, so lets
572                 // give an error message along those lines
573                 err!(diag, |span, diag| {
574                     if looks_like_width_suffix(&['i', 'u'], suf) {
575                         let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
576                         diag.struct_span_err(span, &msg)
577                             .help("valid widths are 8, 16, 32, 64 and 128")
578                             .emit();
579                     } else {
580                         let msg = format!("invalid suffix `{}` for numeric literal", suf);
581                         diag.struct_span_err(span, &msg)
582                             .span_label(span, format!("invalid suffix `{}`", suf))
583                             .help("the suffix must be one of the integral types \
584                                    (`u32`, `isize`, etc)")
585                             .emit();
586                     }
587                 });
588
589                 ty
590             }
591         }
592     }
593
594     debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
595            string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
596
597     Some(match u128::from_str_radix(s, base) {
598         Ok(r) => ast::LitKind::Int(r, ty),
599         Err(_) => {
600             // small bases are lexed as if they were base 10, e.g, the string
601             // might be `0b10201`. This will cause the conversion above to fail,
602             // but these cases have errors in the lexer: we don't want to emit
603             // two errors, and we especially don't want to emit this error since
604             // it isn't necessarily true.
605             let already_errored = base < 10 &&
606                 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
607
608             if !already_errored {
609                 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
610             }
611             ast::LitKind::Int(0, ty)
612         }
613     })
614 }
615
616 /// A sequence separator.
617 pub struct SeqSep {
618     /// The seperator token.
619     pub sep: Option<token::Token>,
620     /// `true` if a trailing separator is allowed.
621     pub trailing_sep_allowed: bool,
622 }
623
624 impl SeqSep {
625     pub fn trailing_allowed(t: token::Token) -> SeqSep {
626         SeqSep {
627             sep: Some(t),
628             trailing_sep_allowed: true,
629         }
630     }
631
632     pub fn none() -> SeqSep {
633         SeqSep {
634             sep: None,
635             trailing_sep_allowed: false,
636         }
637     }
638 }
639
640 #[cfg(test)]
641 mod tests {
642     use super::*;
643     use crate::ast::{self, Ident, PatKind};
644     use crate::attr::first_attr_value_str_by_name;
645     use crate::ptr::P;
646     use crate::print::pprust::item_to_string;
647     use crate::tokenstream::{DelimSpan, TokenTree};
648     use crate::util::parser_testing::string_to_stream;
649     use crate::util::parser_testing::{string_to_expr, string_to_item};
650     use crate::with_globals;
651     use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
652
653     /// Parses an item.
654     ///
655     /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
656     /// when a syntax error occurred.
657     fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
658                                         -> PResult<'_, Option<P<ast::Item>>> {
659         new_parser_from_source_str(sess, name, source).parse_item()
660     }
661
662     // produce a syntax_pos::span
663     fn sp(a: u32, b: u32) -> Span {
664         Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
665     }
666
667     #[should_panic]
668     #[test] fn bad_path_expr_1() {
669         with_globals(|| {
670             string_to_expr("::abc::def::return".to_string());
671         })
672     }
673
674     // check the token-tree-ization of macros
675     #[test]
676     fn string_to_tts_macro () {
677         with_globals(|| {
678             let tts: Vec<_> =
679                 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
680             let tts: &[TokenTree] = &tts[..];
681
682             match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
683                 (
684                     4,
685                     Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
686                     Some(&TokenTree::Token(_, token::Not)),
687                     Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
688                     Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
689                 )
690                 if name_macro_rules.name == "macro_rules"
691                 && name_zip.name == "zip" => {
692                     let tts = &macro_tts.trees().collect::<Vec<_>>();
693                     match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
694                         (
695                             3,
696                             Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
697                             Some(&TokenTree::Token(_, token::FatArrow)),
698                             Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
699                         )
700                         if macro_delim == token::Paren => {
701                             let tts = &first_tts.trees().collect::<Vec<_>>();
702                             match (tts.len(), tts.get(0), tts.get(1)) {
703                                 (
704                                     2,
705                                     Some(&TokenTree::Token(_, token::Dollar)),
706                                     Some(&TokenTree::Token(_, token::Ident(ident, false))),
707                                 )
708                                 if first_delim == token::Paren && ident.name == "a" => {},
709                                 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
710                             }
711                             let tts = &second_tts.trees().collect::<Vec<_>>();
712                             match (tts.len(), tts.get(0), tts.get(1)) {
713                                 (
714                                     2,
715                                     Some(&TokenTree::Token(_, token::Dollar)),
716                                     Some(&TokenTree::Token(_, token::Ident(ident, false))),
717                                 )
718                                 if second_delim == token::Paren && ident.name == "a" => {},
719                                 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
720                             }
721                         },
722                         _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
723                     }
724                 },
725                 _ => panic!("value: {:?}",tts),
726             }
727         })
728     }
729
730     #[test]
731     fn string_to_tts_1() {
732         with_globals(|| {
733             let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
734
735             let expected = TokenStream::new(vec![
736                 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
737                 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
738                 TokenTree::Delimited(
739                     DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
740                     token::DelimToken::Paren,
741                     TokenStream::new(vec![
742                         TokenTree::Token(sp(6, 7),
743                                          token::Ident(Ident::from_str("b"), false)).into(),
744                         TokenTree::Token(sp(8, 9), token::Colon).into(),
745                         TokenTree::Token(sp(10, 13),
746                                          token::Ident(Ident::from_str("i32"), false)).into(),
747                     ]).into(),
748                 ).into(),
749                 TokenTree::Delimited(
750                     DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
751                     token::DelimToken::Brace,
752                     TokenStream::new(vec![
753                         TokenTree::Token(sp(17, 18),
754                                          token::Ident(Ident::from_str("b"), false)).into(),
755                         TokenTree::Token(sp(18, 19), token::Semi).into(),
756                     ]).into(),
757                 ).into()
758             ]);
759
760             assert_eq!(tts, expected);
761         })
762     }
763
764     #[test] fn parse_use() {
765         with_globals(|| {
766             let use_s = "use foo::bar::baz;";
767             let vitem = string_to_item(use_s.to_string()).unwrap();
768             let vitem_s = item_to_string(&vitem);
769             assert_eq!(&vitem_s[..], use_s);
770
771             let use_s = "use foo::bar as baz;";
772             let vitem = string_to_item(use_s.to_string()).unwrap();
773             let vitem_s = item_to_string(&vitem);
774             assert_eq!(&vitem_s[..], use_s);
775         })
776     }
777
778     #[test] fn parse_extern_crate() {
779         with_globals(|| {
780             let ex_s = "extern crate foo;";
781             let vitem = string_to_item(ex_s.to_string()).unwrap();
782             let vitem_s = item_to_string(&vitem);
783             assert_eq!(&vitem_s[..], ex_s);
784
785             let ex_s = "extern crate foo as bar;";
786             let vitem = string_to_item(ex_s.to_string()).unwrap();
787             let vitem_s = item_to_string(&vitem);
788             assert_eq!(&vitem_s[..], ex_s);
789         })
790     }
791
792     fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
793         let item = string_to_item(src.to_string()).unwrap();
794
795         struct PatIdentVisitor {
796             spans: Vec<Span>
797         }
798         impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
799             fn visit_pat(&mut self, p: &'a ast::Pat) {
800                 match p.node {
801                     PatKind::Ident(_ , ref spannedident, _) => {
802                         self.spans.push(spannedident.span.clone());
803                     }
804                     _ => {
805                         crate::visit::walk_pat(self, p);
806                     }
807                 }
808             }
809         }
810         let mut v = PatIdentVisitor { spans: Vec::new() };
811         crate::visit::walk_item(&mut v, &item);
812         return v.spans;
813     }
814
815     #[test] fn span_of_self_arg_pat_idents_are_correct() {
816         with_globals(|| {
817
818             let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
819                         "impl z { fn a (&mut self, &myarg: i32) {} }",
820                         "impl z { fn a (&'a self, &myarg: i32) {} }",
821                         "impl z { fn a (self, &myarg: i32) {} }",
822                         "impl z { fn a (self: Foo, &myarg: i32) {} }",
823                         ];
824
825             for &src in &srcs {
826                 let spans = get_spans_of_pat_idents(src);
827                 let (lo, hi) = (spans[0].lo(), spans[0].hi());
828                 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
829                         "\"{}\" != \"self\". src=\"{}\"",
830                         &src[lo.to_usize()..hi.to_usize()], src)
831             }
832         })
833     }
834
835     #[test] fn parse_exprs () {
836         with_globals(|| {
837             // just make sure that they parse....
838             string_to_expr("3 + 4".to_string());
839             string_to_expr("a::z.froob(b,&(987+3))".to_string());
840         })
841     }
842
843     #[test] fn attrs_fix_bug () {
844         with_globals(|| {
845             string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
846                    -> Result<Box<Writer>, String> {
847     #[cfg(windows)]
848     fn wb() -> c_int {
849       (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
850     }
851
852     #[cfg(unix)]
853     fn wb() -> c_int { O_WRONLY as c_int }
854
855     let mut fflags: c_int = wb();
856 }".to_string());
857         })
858     }
859
860     #[test] fn crlf_doc_comments() {
861         with_globals(|| {
862             let sess = ParseSess::new(FilePathMapping::empty());
863
864             let name_1 = FileName::Custom("crlf_source_1".to_string());
865             let source = "/// doc comment\r\nfn foo() {}".to_string();
866             let item = parse_item_from_source_str(name_1, source, &sess)
867                 .unwrap().unwrap();
868             let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
869             assert_eq!(doc, "/// doc comment");
870
871             let name_2 = FileName::Custom("crlf_source_2".to_string());
872             let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
873             let item = parse_item_from_source_str(name_2, source, &sess)
874                 .unwrap().unwrap();
875             let docs = item.attrs.iter().filter(|a| a.path == "doc")
876                         .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
877             let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
878             assert_eq!(&docs[..], b);
879
880             let name_3 = FileName::Custom("clrf_source_3".to_string());
881             let source = "/** doc comment\r\n *  with CRLF */\r\nfn foo() {}".to_string();
882             let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
883             let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
884             assert_eq!(doc, "/** doc comment\n *  with CRLF */");
885         });
886     }
887
888     #[test]
889     fn ttdelim_span() {
890         fn parse_expr_from_source_str(
891             name: FileName, source: String, sess: &ParseSess
892         ) -> PResult<'_, P<ast::Expr>> {
893             new_parser_from_source_str(sess, name, source).parse_expr()
894         }
895
896         with_globals(|| {
897             let sess = ParseSess::new(FilePathMapping::empty());
898             let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
899                 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
900
901             let tts: Vec<_> = match expr.node {
902                 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
903                 _ => panic!("not a macro"),
904             };
905
906             let span = tts.iter().rev().next().unwrap().span();
907
908             match sess.source_map().span_to_snippet(span) {
909                 Ok(s) => assert_eq!(&s[..], "{ body }"),
910                 Err(_) => panic!("could not get snippet"),
911             }
912         });
913     }
914
915     // This tests that when parsing a string (rather than a file) we don't try
916     // and read in a file for a module declaration and just parse a stub.
917     // See `recurse_into_file_modules` in the parser.
918     #[test]
919     fn out_of_line_mod() {
920         with_globals(|| {
921             let sess = ParseSess::new(FilePathMapping::empty());
922             let item = parse_item_from_source_str(
923                 PathBuf::from("foo").into(),
924                 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
925                 &sess,
926             ).unwrap().unwrap();
927
928             if let ast::ItemKind::Mod(ref m) = item.node {
929                 assert!(m.items.len() == 2);
930             } else {
931                 panic!();
932             }
933         });
934     }
935 }