]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/mod.rs
398b4b1da17b0ef74ab0c666b9d63fc311f09c0a
[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::parse::token::Token;
389     use crate::print::pprust::item_to_string;
390     use crate::tokenstream::{DelimSpan, TokenTree};
391     use crate::util::parser_testing::string_to_stream;
392     use crate::util::parser_testing::{string_to_expr, string_to_item};
393     use crate::with_default_globals;
394     use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
395
396     /// Parses an item.
397     ///
398     /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
399     /// when a syntax error occurred.
400     fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
401                                         -> PResult<'_, Option<P<ast::Item>>> {
402         new_parser_from_source_str(sess, name, source).parse_item()
403     }
404
405     // produce a syntax_pos::span
406     fn sp(a: u32, b: u32) -> Span {
407         Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
408     }
409
410     #[should_panic]
411     #[test] fn bad_path_expr_1() {
412         with_default_globals(|| {
413             string_to_expr("::abc::def::return".to_string());
414         })
415     }
416
417     // check the token-tree-ization of macros
418     #[test]
419     fn string_to_tts_macro () {
420         with_default_globals(|| {
421             use crate::symbol::sym;
422
423             let tts: Vec<_> =
424                 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
425             let tts: &[TokenTree] = &tts[..];
426
427             match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
428                 (
429                     4,
430                     Some(&TokenTree::Token(Token { kind: token::Ident(name_macro_rules, false), .. })),
431                     Some(&TokenTree::Token(Token { kind: token::Not, .. })),
432                     Some(&TokenTree::Token(Token { kind: token::Ident(name_zip, false), .. })),
433                     Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
434                 )
435                 if name_macro_rules.name == sym::macro_rules
436                 && name_zip.name.as_str() == "zip" => {
437                     let tts = &macro_tts.trees().collect::<Vec<_>>();
438                     match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
439                         (
440                             3,
441                             Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
442                             Some(&TokenTree::Token(Token { kind: token::FatArrow, .. })),
443                             Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
444                         )
445                         if macro_delim == token::Paren => {
446                             let tts = &first_tts.trees().collect::<Vec<_>>();
447                             match (tts.len(), tts.get(0), tts.get(1)) {
448                                 (
449                                     2,
450                                     Some(&TokenTree::Token(Token { kind: token::Dollar, .. })),
451                                     Some(&TokenTree::Token(Token { kind: token::Ident(ident, false), .. })),
452                                 )
453                                 if first_delim == token::Paren && ident.name.as_str() == "a" => {},
454                                 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
455                             }
456                             let tts = &second_tts.trees().collect::<Vec<_>>();
457                             match (tts.len(), tts.get(0), tts.get(1)) {
458                                 (
459                                     2,
460                                     Some(&TokenTree::Token(Token { kind: token::Dollar, .. })),
461                                     Some(&TokenTree::Token(Token { kind: token::Ident(ident, false), .. })),
462                                 )
463                                 if second_delim == token::Paren && ident.name.as_str() == "a" => {},
464                                 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
465                             }
466                         },
467                         _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
468                     }
469                 },
470                 _ => panic!("value: {:?}",tts),
471             }
472         })
473     }
474
475     #[test]
476     fn string_to_tts_1() {
477         with_default_globals(|| {
478             let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
479
480             let expected = TokenStream::new(vec![
481                 TokenTree::token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
482                 TokenTree::token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
483                 TokenTree::Delimited(
484                     DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
485                     token::DelimToken::Paren,
486                     TokenStream::new(vec![
487                         TokenTree::token(sp(6, 7),
488                                          token::Ident(Ident::from_str("b"), false)).into(),
489                         TokenTree::token(sp(8, 9), token::Colon).into(),
490                         TokenTree::token(sp(10, 13),
491                                          token::Ident(Ident::from_str("i32"), false)).into(),
492                     ]).into(),
493                 ).into(),
494                 TokenTree::Delimited(
495                     DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
496                     token::DelimToken::Brace,
497                     TokenStream::new(vec![
498                         TokenTree::token(sp(17, 18),
499                                          token::Ident(Ident::from_str("b"), false)).into(),
500                         TokenTree::token(sp(18, 19), token::Semi).into(),
501                     ]).into(),
502                 ).into()
503             ]);
504
505             assert_eq!(tts, expected);
506         })
507     }
508
509     #[test] fn parse_use() {
510         with_default_globals(|| {
511             let use_s = "use foo::bar::baz;";
512             let vitem = string_to_item(use_s.to_string()).unwrap();
513             let vitem_s = item_to_string(&vitem);
514             assert_eq!(&vitem_s[..], use_s);
515
516             let use_s = "use foo::bar as baz;";
517             let vitem = string_to_item(use_s.to_string()).unwrap();
518             let vitem_s = item_to_string(&vitem);
519             assert_eq!(&vitem_s[..], use_s);
520         })
521     }
522
523     #[test] fn parse_extern_crate() {
524         with_default_globals(|| {
525             let ex_s = "extern crate foo;";
526             let vitem = string_to_item(ex_s.to_string()).unwrap();
527             let vitem_s = item_to_string(&vitem);
528             assert_eq!(&vitem_s[..], ex_s);
529
530             let ex_s = "extern crate foo as bar;";
531             let vitem = string_to_item(ex_s.to_string()).unwrap();
532             let vitem_s = item_to_string(&vitem);
533             assert_eq!(&vitem_s[..], ex_s);
534         })
535     }
536
537     fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
538         let item = string_to_item(src.to_string()).unwrap();
539
540         struct PatIdentVisitor {
541             spans: Vec<Span>
542         }
543         impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
544             fn visit_pat(&mut self, p: &'a ast::Pat) {
545                 match p.node {
546                     PatKind::Ident(_ , ref spannedident, _) => {
547                         self.spans.push(spannedident.span.clone());
548                     }
549                     _ => {
550                         crate::visit::walk_pat(self, p);
551                     }
552                 }
553             }
554         }
555         let mut v = PatIdentVisitor { spans: Vec::new() };
556         crate::visit::walk_item(&mut v, &item);
557         return v.spans;
558     }
559
560     #[test] fn span_of_self_arg_pat_idents_are_correct() {
561         with_default_globals(|| {
562
563             let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
564                         "impl z { fn a (&mut self, &myarg: i32) {} }",
565                         "impl z { fn a (&'a self, &myarg: i32) {} }",
566                         "impl z { fn a (self, &myarg: i32) {} }",
567                         "impl z { fn a (self: Foo, &myarg: i32) {} }",
568                         ];
569
570             for &src in &srcs {
571                 let spans = get_spans_of_pat_idents(src);
572                 let (lo, hi) = (spans[0].lo(), spans[0].hi());
573                 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
574                         "\"{}\" != \"self\". src=\"{}\"",
575                         &src[lo.to_usize()..hi.to_usize()], src)
576             }
577         })
578     }
579
580     #[test] fn parse_exprs () {
581         with_default_globals(|| {
582             // just make sure that they parse....
583             string_to_expr("3 + 4".to_string());
584             string_to_expr("a::z.froob(b,&(987+3))".to_string());
585         })
586     }
587
588     #[test] fn attrs_fix_bug () {
589         with_default_globals(|| {
590             string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
591                    -> Result<Box<Writer>, String> {
592     #[cfg(windows)]
593     fn wb() -> c_int {
594       (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
595     }
596
597     #[cfg(unix)]
598     fn wb() -> c_int { O_WRONLY as c_int }
599
600     let mut fflags: c_int = wb();
601 }".to_string());
602         })
603     }
604
605     #[test] fn crlf_doc_comments() {
606         with_default_globals(|| {
607             use crate::symbol::sym;
608
609             let sess = ParseSess::new(FilePathMapping::empty());
610
611             let name_1 = FileName::Custom("crlf_source_1".to_string());
612             let source = "/// doc comment\r\nfn foo() {}".to_string();
613             let item = parse_item_from_source_str(name_1, source, &sess)
614                 .unwrap().unwrap();
615             let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
616             assert_eq!(doc.as_str(), "/// doc comment");
617
618             let name_2 = FileName::Custom("crlf_source_2".to_string());
619             let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
620             let item = parse_item_from_source_str(name_2, source, &sess)
621                 .unwrap().unwrap();
622             let docs = item.attrs.iter().filter(|a| a.path == sym::doc)
623                         .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
624             let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
625             assert_eq!(&docs[..], b);
626
627             let name_3 = FileName::Custom("clrf_source_3".to_string());
628             let source = "/** doc comment\r\n *  with CRLF */\r\nfn foo() {}".to_string();
629             let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
630             let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
631             assert_eq!(doc.as_str(), "/** doc comment\n *  with CRLF */");
632         });
633     }
634
635     #[test]
636     fn ttdelim_span() {
637         fn parse_expr_from_source_str(
638             name: FileName, source: String, sess: &ParseSess
639         ) -> PResult<'_, P<ast::Expr>> {
640             new_parser_from_source_str(sess, name, source).parse_expr()
641         }
642
643         with_default_globals(|| {
644             let sess = ParseSess::new(FilePathMapping::empty());
645             let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
646                 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
647
648             let tts: Vec<_> = match expr.node {
649                 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
650                 _ => panic!("not a macro"),
651             };
652
653             let span = tts.iter().rev().next().unwrap().span();
654
655             match sess.source_map().span_to_snippet(span) {
656                 Ok(s) => assert_eq!(&s[..], "{ body }"),
657                 Err(_) => panic!("could not get snippet"),
658             }
659         });
660     }
661
662     // This tests that when parsing a string (rather than a file) we don't try
663     // and read in a file for a module declaration and just parse a stub.
664     // See `recurse_into_file_modules` in the parser.
665     #[test]
666     fn out_of_line_mod() {
667         with_default_globals(|| {
668             let sess = ParseSess::new(FilePathMapping::empty());
669             let item = parse_item_from_source_str(
670                 PathBuf::from("foo").into(),
671                 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
672                 &sess,
673             ).unwrap().unwrap();
674
675             if let ast::ItemKind::Mod(ref m) = item.node {
676                 assert!(m.items.len() == 2);
677             } else {
678                 panic!();
679             }
680         });
681     }
682 }