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