]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/mod.rs
syntax: Rename `Token` into `TokenKind`
[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::syntax::parse::parser::emit_unclosed_delims;
9 use crate::tokenstream::{TokenStream, TokenTree};
10 use crate::diagnostics::plugin::ErrorMap;
11 use crate::print::pprust::token_to_string;
12
13 use errors::{Applicability, FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
14 use rustc_data_structures::sync::{Lrc, Lock};
15 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
16 use syntax_pos::edition::Edition;
17
18 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
19 use std::borrow::Cow;
20 use std::path::{Path, PathBuf};
21 use std::str;
22
23 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
24
25 #[macro_use]
26 pub mod parser;
27 pub mod attr;
28 pub mod lexer;
29 pub mod token;
30
31 crate mod classify;
32 crate mod diagnostics;
33 crate mod literal;
34 crate mod unescape;
35 crate mod unescape_error_reporting;
36
37 /// Info about a parsing session.
38 pub struct ParseSess {
39     pub span_diagnostic: Handler,
40     pub unstable_features: UnstableFeatures,
41     pub config: CrateConfig,
42     pub edition: Edition,
43     pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
44     /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
45     pub raw_identifier_spans: Lock<Vec<Span>>,
46     /// The registered diagnostics codes.
47     crate registered_diagnostics: Lock<ErrorMap>,
48     /// Used to determine and report recursive module inclusions.
49     included_mod_stack: Lock<Vec<PathBuf>>,
50     source_map: Lrc<SourceMap>,
51     pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
52     /// Contains the spans of block expressions that could have been incomplete based on the
53     /// operation token that followed it, but that the parser cannot identify without further
54     /// analysis.
55     pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
56 }
57
58 impl ParseSess {
59     pub fn new(file_path_mapping: FilePathMapping) -> Self {
60         let cm = Lrc::new(SourceMap::new(file_path_mapping));
61         let handler = Handler::with_tty_emitter(ColorConfig::Auto,
62                                                 true,
63                                                 None,
64                                                 Some(cm.clone()));
65         ParseSess::with_span_handler(handler, cm)
66     }
67
68     pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
69         ParseSess {
70             span_diagnostic: handler,
71             unstable_features: UnstableFeatures::from_environment(),
72             config: FxHashSet::default(),
73             missing_fragment_specifiers: Lock::new(FxHashSet::default()),
74             raw_identifier_spans: Lock::new(Vec::new()),
75             registered_diagnostics: Lock::new(ErrorMap::new()),
76             included_mod_stack: Lock::new(vec![]),
77             source_map,
78             buffered_lints: Lock::new(vec![]),
79             edition: Edition::from_session(),
80             ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
81         }
82     }
83
84     #[inline]
85     pub fn source_map(&self) -> &SourceMap {
86         &self.source_map
87     }
88
89     pub fn buffer_lint<S: Into<MultiSpan>>(&self,
90         lint_id: BufferedEarlyLintId,
91         span: S,
92         id: NodeId,
93         msg: &str,
94     ) {
95         self.buffered_lints.with_lock(|buffered_lints| {
96             buffered_lints.push(BufferedEarlyLint{
97                 span: span.into(),
98                 id,
99                 msg: msg.into(),
100                 lint_id,
101             });
102         });
103     }
104
105     /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
106     /// parser to continue parsing the following operation as part of the same expression.
107     pub fn expr_parentheses_needed(
108         &self,
109         err: &mut DiagnosticBuilder<'_>,
110         span: Span,
111         alt_snippet: Option<String>,
112     ) {
113         if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
114             err.span_suggestion(
115                 span,
116                 "parentheses are required to parse this as an expression",
117                 format!("({})", snippet),
118                 Applicability::MachineApplicable,
119             );
120         }
121     }
122 }
123
124 #[derive(Clone)]
125 pub struct Directory<'a> {
126     pub path: Cow<'a, Path>,
127     pub ownership: DirectoryOwnership,
128 }
129
130 #[derive(Copy, Clone)]
131 pub enum DirectoryOwnership {
132     Owned {
133         // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
134         relative: Option<ast::Ident>,
135     },
136     UnownedViaBlock,
137     UnownedViaMod(bool /* legacy warnings? */),
138 }
139
140 // a bunch of utility functions of the form parse_<thing>_from_<source>
141 // where <thing> includes crate, expr, item, stmt, tts, and one that
142 // uses a HOF to parse anything, and <source> includes file and
143 // source_str.
144
145 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
146     let mut parser = new_parser_from_file(sess, input);
147     parser.parse_crate_mod()
148 }
149
150 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
151                                        -> PResult<'a, Vec<ast::Attribute>> {
152     let mut parser = new_parser_from_file(sess, input);
153     parser.parse_inner_attributes()
154 }
155
156 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
157                                        -> PResult<'_, ast::Crate> {
158     new_parser_from_source_str(sess, name, source).parse_crate_mod()
159 }
160
161 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
162                                              -> PResult<'_, Vec<ast::Attribute>> {
163     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
164 }
165
166 pub fn parse_stream_from_source_str(
167     name: FileName,
168     source: String,
169     sess: &ParseSess,
170     override_span: Option<Span>,
171 ) -> TokenStream {
172     let (stream, mut errors) = source_file_to_stream(
173         sess,
174         sess.source_map().new_source_file(name, source),
175         override_span,
176     );
177     emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
178     stream
179 }
180
181 /// Creates a new parser from a source string.
182 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
183     panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
184 }
185
186 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
187 /// token stream.
188 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
189     -> Result<Parser<'_>, Vec<Diagnostic>>
190 {
191     let mut parser = maybe_source_file_to_parser(sess,
192                                                  sess.source_map().new_source_file(name, source))?;
193     parser.recurse_into_file_modules = false;
194     Ok(parser)
195 }
196
197 /// Creates a new parser, handling errors as appropriate
198 /// if the file doesn't exist
199 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
200     source_file_to_parser(sess, file_to_source_file(sess, path, None))
201 }
202
203 /// Creates a new parser, returning buffered diagnostics if the file doesn't
204 /// exist or from lexing the initial token stream.
205 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
206     -> Result<Parser<'a>, Vec<Diagnostic>> {
207     let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
208     maybe_source_file_to_parser(sess, file)
209 }
210
211 /// Given a session, a crate config, a path, and a span, add
212 /// the file at the given path to the source_map, and return a parser.
213 /// On an error, use the given span as the source of the problem.
214 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
215                                     path: &Path,
216                                     directory_ownership: DirectoryOwnership,
217                                     module_name: Option<String>,
218                                     sp: Span) -> Parser<'a> {
219     let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
220     p.directory.ownership = directory_ownership;
221     p.root_module_name = module_name;
222     p
223 }
224
225 /// Given a source_file and config, return a parser
226 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
227     panictry_buffer!(&sess.span_diagnostic,
228                      maybe_source_file_to_parser(sess, source_file))
229 }
230
231 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
232 /// initial token stream.
233 fn maybe_source_file_to_parser(
234     sess: &ParseSess,
235     source_file: Lrc<SourceFile>,
236 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
237     let end_pos = source_file.end_pos;
238     let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
239     let mut parser = stream_to_parser(sess, stream, None);
240     parser.unclosed_delims = unclosed_delims;
241     if parser.token == token::Eof && parser.span.is_dummy() {
242         parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
243     }
244
245     Ok(parser)
246 }
247
248 // must preserve old name for now, because quote! from the *existing*
249 // compiler expands into it
250 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
251     stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS)
252 }
253
254
255 // base abstractions
256
257 /// Given a session and a path and an optional span (for error reporting),
258 /// add the path to the session's source_map and return the new source_file or
259 /// error when a file can't be read.
260 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
261                    -> Result<Lrc<SourceFile>, Diagnostic> {
262     sess.source_map().load_file(path)
263     .map_err(|e| {
264         let msg = format!("couldn't read {}: {}", path.display(), e);
265         let mut diag = Diagnostic::new(Level::Fatal, &msg);
266         if let Some(sp) = spanopt {
267             diag.set_span(sp);
268         }
269         diag
270     })
271 }
272
273 /// Given a session and a path and an optional span (for error reporting),
274 /// add the path to the session's `source_map` and return the new `source_file`.
275 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
276                    -> Lrc<SourceFile> {
277     match try_file_to_source_file(sess, path, spanopt) {
278         Ok(source_file) => source_file,
279         Err(d) => {
280             DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
281             FatalError.raise();
282         }
283     }
284 }
285
286 /// Given a source_file, produces a sequence of token trees.
287 pub fn source_file_to_stream(
288     sess: &ParseSess,
289     source_file: Lrc<SourceFile>,
290     override_span: Option<Span>,
291 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
292     panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
293 }
294
295 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
296 /// parsing the token stream.
297 pub fn maybe_file_to_stream(
298     sess: &ParseSess,
299     source_file: Lrc<SourceFile>,
300     override_span: Option<Span>,
301 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
302     let srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
303     let (token_trees, unmatched_braces) = srdr.into_token_trees();
304
305     match token_trees {
306         Ok(stream) => Ok((stream, unmatched_braces)),
307         Err(err) => {
308             let mut buffer = Vec::with_capacity(1);
309             err.buffer(&mut buffer);
310             // Not using `emit_unclosed_delims` to use `db.buffer`
311             for unmatched in unmatched_braces {
312                 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
313                     "incorrect close delimiter: `{}`",
314                     token_to_string(&token::CloseDelim(unmatched.found_delim)),
315                 ));
316                 db.span_label(unmatched.found_span, "incorrect close delimiter");
317                 if let Some(sp) = unmatched.candidate_span {
318                     db.span_label(sp, "close delimiter possibly meant for this");
319                 }
320                 if let Some(sp) = unmatched.unclosed_span {
321                     db.span_label(sp, "un-closed delimiter");
322                 }
323                 db.buffer(&mut buffer);
324             }
325             Err(buffer)
326         }
327     }
328 }
329
330 /// Given stream and the `ParseSess`, produces a parser.
331 pub fn stream_to_parser<'a>(
332     sess: &'a ParseSess,
333     stream: TokenStream,
334     subparser_name: Option<&'static str>,
335 ) -> Parser<'a> {
336     Parser::new(sess, stream, None, true, false, subparser_name)
337 }
338
339 /// Given stream, the `ParseSess` and the base directory, produces a parser.
340 ///
341 /// Use this function when you are creating a parser from the token stream
342 /// and also care about the current working directory of the parser (e.g.,
343 /// you are trying to resolve modules defined inside a macro invocation).
344 ///
345 /// # Note
346 ///
347 /// The main usage of this function is outside of rustc, for those who uses
348 /// libsyntax as a library. Please do not remove this function while refactoring
349 /// just because it is not used in rustc codebase!
350 pub fn stream_to_parser_with_base_dir<'a>(
351     sess: &'a ParseSess,
352     stream: TokenStream,
353     base_dir: Directory<'a>,
354 ) -> Parser<'a> {
355     Parser::new(sess, stream, Some(base_dir), true, false, None)
356 }
357
358 /// A sequence separator.
359 pub struct SeqSep {
360     /// The seperator token.
361     pub sep: Option<token::TokenKind>,
362     /// `true` if a trailing separator is allowed.
363     pub trailing_sep_allowed: bool,
364 }
365
366 impl SeqSep {
367     pub fn trailing_allowed(t: token::TokenKind) -> SeqSep {
368         SeqSep {
369             sep: Some(t),
370             trailing_sep_allowed: true,
371         }
372     }
373
374     pub fn none() -> SeqSep {
375         SeqSep {
376             sep: None,
377             trailing_sep_allowed: false,
378         }
379     }
380 }
381
382 #[cfg(test)]
383 mod tests {
384     use super::*;
385     use crate::ast::{self, Ident, PatKind};
386     use crate::attr::first_attr_value_str_by_name;
387     use crate::ptr::P;
388     use crate::print::pprust::item_to_string;
389     use crate::tokenstream::{DelimSpan, TokenTree};
390     use crate::util::parser_testing::string_to_stream;
391     use crate::util::parser_testing::{string_to_expr, string_to_item};
392     use crate::with_default_globals;
393     use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
394
395     /// Parses an item.
396     ///
397     /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
398     /// when a syntax error occurred.
399     fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
400                                         -> PResult<'_, Option<P<ast::Item>>> {
401         new_parser_from_source_str(sess, name, source).parse_item()
402     }
403
404     // produce a syntax_pos::span
405     fn sp(a: u32, b: u32) -> Span {
406         Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
407     }
408
409     #[should_panic]
410     #[test] fn bad_path_expr_1() {
411         with_default_globals(|| {
412             string_to_expr("::abc::def::return".to_string());
413         })
414     }
415
416     // check the token-tree-ization of macros
417     #[test]
418     fn string_to_tts_macro () {
419         with_default_globals(|| {
420             use crate::symbol::sym;
421
422             let tts: Vec<_> =
423                 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
424             let tts: &[TokenTree] = &tts[..];
425
426             match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
427                 (
428                     4,
429                     Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
430                     Some(&TokenTree::Token(_, token::Not)),
431                     Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
432                     Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
433                 )
434                 if name_macro_rules.name == sym::macro_rules
435                 && name_zip.name.as_str() == "zip" => {
436                     let tts = &macro_tts.trees().collect::<Vec<_>>();
437                     match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
438                         (
439                             3,
440                             Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
441                             Some(&TokenTree::Token(_, token::FatArrow)),
442                             Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
443                         )
444                         if macro_delim == token::Paren => {
445                             let tts = &first_tts.trees().collect::<Vec<_>>();
446                             match (tts.len(), tts.get(0), tts.get(1)) {
447                                 (
448                                     2,
449                                     Some(&TokenTree::Token(_, token::Dollar)),
450                                     Some(&TokenTree::Token(_, token::Ident(ident, false))),
451                                 )
452                                 if first_delim == token::Paren && ident.name.as_str() == "a" => {},
453                                 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
454                             }
455                             let tts = &second_tts.trees().collect::<Vec<_>>();
456                             match (tts.len(), tts.get(0), tts.get(1)) {
457                                 (
458                                     2,
459                                     Some(&TokenTree::Token(_, token::Dollar)),
460                                     Some(&TokenTree::Token(_, token::Ident(ident, false))),
461                                 )
462                                 if second_delim == token::Paren && ident.name.as_str() == "a" => {},
463                                 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
464                             }
465                         },
466                         _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
467                     }
468                 },
469                 _ => panic!("value: {:?}",tts),
470             }
471         })
472     }
473
474     #[test]
475     fn string_to_tts_1() {
476         with_default_globals(|| {
477             let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
478
479             let expected = TokenStream::new(vec![
480                 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
481                 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
482                 TokenTree::Delimited(
483                     DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
484                     token::DelimToken::Paren,
485                     TokenStream::new(vec![
486                         TokenTree::Token(sp(6, 7),
487                                          token::Ident(Ident::from_str("b"), false)).into(),
488                         TokenTree::Token(sp(8, 9), token::Colon).into(),
489                         TokenTree::Token(sp(10, 13),
490                                          token::Ident(Ident::from_str("i32"), false)).into(),
491                     ]).into(),
492                 ).into(),
493                 TokenTree::Delimited(
494                     DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
495                     token::DelimToken::Brace,
496                     TokenStream::new(vec![
497                         TokenTree::Token(sp(17, 18),
498                                          token::Ident(Ident::from_str("b"), false)).into(),
499                         TokenTree::Token(sp(18, 19), token::Semi).into(),
500                     ]).into(),
501                 ).into()
502             ]);
503
504             assert_eq!(tts, expected);
505         })
506     }
507
508     #[test] fn parse_use() {
509         with_default_globals(|| {
510             let use_s = "use foo::bar::baz;";
511             let vitem = string_to_item(use_s.to_string()).unwrap();
512             let vitem_s = item_to_string(&vitem);
513             assert_eq!(&vitem_s[..], use_s);
514
515             let use_s = "use foo::bar as baz;";
516             let vitem = string_to_item(use_s.to_string()).unwrap();
517             let vitem_s = item_to_string(&vitem);
518             assert_eq!(&vitem_s[..], use_s);
519         })
520     }
521
522     #[test] fn parse_extern_crate() {
523         with_default_globals(|| {
524             let ex_s = "extern crate foo;";
525             let vitem = string_to_item(ex_s.to_string()).unwrap();
526             let vitem_s = item_to_string(&vitem);
527             assert_eq!(&vitem_s[..], ex_s);
528
529             let ex_s = "extern crate foo as bar;";
530             let vitem = string_to_item(ex_s.to_string()).unwrap();
531             let vitem_s = item_to_string(&vitem);
532             assert_eq!(&vitem_s[..], ex_s);
533         })
534     }
535
536     fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
537         let item = string_to_item(src.to_string()).unwrap();
538
539         struct PatIdentVisitor {
540             spans: Vec<Span>
541         }
542         impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
543             fn visit_pat(&mut self, p: &'a ast::Pat) {
544                 match p.node {
545                     PatKind::Ident(_ , ref spannedident, _) => {
546                         self.spans.push(spannedident.span.clone());
547                     }
548                     _ => {
549                         crate::visit::walk_pat(self, p);
550                     }
551                 }
552             }
553         }
554         let mut v = PatIdentVisitor { spans: Vec::new() };
555         crate::visit::walk_item(&mut v, &item);
556         return v.spans;
557     }
558
559     #[test] fn span_of_self_arg_pat_idents_are_correct() {
560         with_default_globals(|| {
561
562             let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
563                         "impl z { fn a (&mut self, &myarg: i32) {} }",
564                         "impl z { fn a (&'a self, &myarg: i32) {} }",
565                         "impl z { fn a (self, &myarg: i32) {} }",
566                         "impl z { fn a (self: Foo, &myarg: i32) {} }",
567                         ];
568
569             for &src in &srcs {
570                 let spans = get_spans_of_pat_idents(src);
571                 let (lo, hi) = (spans[0].lo(), spans[0].hi());
572                 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
573                         "\"{}\" != \"self\". src=\"{}\"",
574                         &src[lo.to_usize()..hi.to_usize()], src)
575             }
576         })
577     }
578
579     #[test] fn parse_exprs () {
580         with_default_globals(|| {
581             // just make sure that they parse....
582             string_to_expr("3 + 4".to_string());
583             string_to_expr("a::z.froob(b,&(987+3))".to_string());
584         })
585     }
586
587     #[test] fn attrs_fix_bug () {
588         with_default_globals(|| {
589             string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
590                    -> Result<Box<Writer>, String> {
591     #[cfg(windows)]
592     fn wb() -> c_int {
593       (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
594     }
595
596     #[cfg(unix)]
597     fn wb() -> c_int { O_WRONLY as c_int }
598
599     let mut fflags: c_int = wb();
600 }".to_string());
601         })
602     }
603
604     #[test] fn crlf_doc_comments() {
605         with_default_globals(|| {
606             use crate::symbol::sym;
607
608             let sess = ParseSess::new(FilePathMapping::empty());
609
610             let name_1 = FileName::Custom("crlf_source_1".to_string());
611             let source = "/// doc comment\r\nfn foo() {}".to_string();
612             let item = parse_item_from_source_str(name_1, source, &sess)
613                 .unwrap().unwrap();
614             let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
615             assert_eq!(doc.as_str(), "/// doc comment");
616
617             let name_2 = FileName::Custom("crlf_source_2".to_string());
618             let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
619             let item = parse_item_from_source_str(name_2, source, &sess)
620                 .unwrap().unwrap();
621             let docs = item.attrs.iter().filter(|a| a.path == sym::doc)
622                         .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
623             let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
624             assert_eq!(&docs[..], b);
625
626             let name_3 = FileName::Custom("clrf_source_3".to_string());
627             let source = "/** doc comment\r\n *  with CRLF */\r\nfn foo() {}".to_string();
628             let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
629             let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
630             assert_eq!(doc.as_str(), "/** doc comment\n *  with CRLF */");
631         });
632     }
633
634     #[test]
635     fn ttdelim_span() {
636         fn parse_expr_from_source_str(
637             name: FileName, source: String, sess: &ParseSess
638         ) -> PResult<'_, P<ast::Expr>> {
639             new_parser_from_source_str(sess, name, source).parse_expr()
640         }
641
642         with_default_globals(|| {
643             let sess = ParseSess::new(FilePathMapping::empty());
644             let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
645                 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
646
647             let tts: Vec<_> = match expr.node {
648                 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
649                 _ => panic!("not a macro"),
650             };
651
652             let span = tts.iter().rev().next().unwrap().span();
653
654             match sess.source_map().span_to_snippet(span) {
655                 Ok(s) => assert_eq!(&s[..], "{ body }"),
656                 Err(_) => panic!("could not get snippet"),
657             }
658         });
659     }
660
661     // This tests that when parsing a string (rather than a file) we don't try
662     // and read in a file for a module declaration and just parse a stub.
663     // See `recurse_into_file_modules` in the parser.
664     #[test]
665     fn out_of_line_mod() {
666         with_default_globals(|| {
667             let sess = ParseSess::new(FilePathMapping::empty());
668             let item = parse_item_from_source_str(
669                 PathBuf::from("foo").into(),
670                 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
671                 &sess,
672             ).unwrap().unwrap();
673
674             if let ast::ItemKind::Mod(ref m) = item.node {
675                 assert!(m.items.len() == 2);
676             } else {
677                 panic!();
678             }
679         });
680     }
681 }