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