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