1 //! The main parser interface.
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;
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;
20 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
22 use std::path::{Path, PathBuf};
25 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
34 crate mod diagnostics;
36 crate mod unescape_error_reporting;
38 /// Info about a parsing session.
39 pub struct ParseSess {
40 pub span_diagnostic: Handler,
41 pub unstable_features: UnstableFeatures,
42 pub config: CrateConfig,
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
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>,
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,
72 ParseSess::with_span_handler(handler, cm)
75 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> 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![]),
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(),
96 pub fn source_map(&self) -> &SourceMap {
100 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
101 lint_id: BufferedEarlyLintId,
106 self.buffered_lints.with_lock(|buffered_lints| {
107 buffered_lints.push(BufferedEarlyLint{
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(
120 err: &mut DiagnosticBuilder<'_>,
122 alt_snippet: Option<String>,
124 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
127 "parentheses are required to parse this as an expression",
128 format!("({})", snippet),
129 Applicability::MachineApplicable,
136 pub struct Directory<'a> {
137 pub path: Cow<'a, Path>,
138 pub ownership: DirectoryOwnership,
141 #[derive(Copy, Clone)]
142 pub enum DirectoryOwnership {
144 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
145 relative: Option<ast::Ident>,
148 UnownedViaMod(bool /* legacy warnings? */),
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
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()
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()
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()
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()
177 pub fn parse_stream_from_source_str(
181 override_span: Option<Span>,
183 let (stream, mut errors) = source_file_to_stream(
185 sess.source_map().new_source_file(name, source),
188 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
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))
197 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
199 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
200 -> Result<Parser<'_>, Vec<Diagnostic>>
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;
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))
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)
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,
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;
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))
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(
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());
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)
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)
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 {
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>)
288 match try_file_to_source_file(sess, path, spanopt) {
289 Ok(source_file) => source_file,
291 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
297 /// Given a source_file, produces a sequence of token trees.
298 pub fn source_file_to_stream(
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))
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(
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();
317 Ok(stream) => Ok((stream, unmatched_braces)),
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)),
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");
331 if let Some(sp) = unmatched.unclosed_span {
332 db.span_label(sp, "un-closed delimiter");
334 db.buffer(&mut buffer);
341 /// Given stream and the `ParseSess`, produces a parser.
342 pub fn stream_to_parser<'a>(
345 subparser_name: Option<&'static str>,
347 Parser::new(sess, stream, None, true, false, subparser_name)
350 /// Given stream, the `ParseSess` and the base directory, produces a parser.
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).
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>(
364 base_dir: Directory<'a>,
366 Parser::new(sess, stream, Some(base_dir), true, false, None)
369 /// A sequence separator.
371 /// The seperator token.
372 pub sep: Option<TokenKind>,
373 /// `true` if a trailing separator is allowed.
374 pub trailing_sep_allowed: bool,
378 pub fn trailing_allowed(t: TokenKind) -> SeqSep {
381 trailing_sep_allowed: true,
385 pub fn none() -> SeqSep {
388 trailing_sep_allowed: false,
396 use crate::ast::{self, Name, PatKind};
397 use crate::attr::first_attr_value_str_by_name;
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};
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()
417 // produce a syntax_pos::span
418 fn sp(a: u32, b: u32) -> Span {
419 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
423 #[test] fn bad_path_expr_1() {
424 with_default_globals(|| {
425 string_to_expr("::abc::def::return".to_string());
429 // check the token-tree-ization of macros
431 fn string_to_tts_macro () {
432 with_default_globals(|| {
434 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
435 let tts: &[TokenTree] = &tts[..];
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)
444 if name_macro_rules == &sym::macro_rules && name_zip.as_str() == "zip" => {
445 let tts = ¯o_tts.trees().collect::<Vec<_>>();
448 TokenTree::Delimited(_, first_delim, first_tts),
449 TokenTree::Token(Token { kind: token::FatArrow, .. }),
450 TokenTree::Delimited(_, second_delim, second_tts),
452 if macro_delim == &token::Paren => {
453 let tts = &first_tts.trees().collect::<Vec<_>>();
456 TokenTree::Token(Token { kind: token::Dollar, .. }),
457 TokenTree::Token(Token { kind: token::Ident(name, false), .. }),
459 if first_delim == &token::Paren && name.as_str() == "a" => {},
460 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
462 let tts = &second_tts.trees().collect::<Vec<_>>();
465 TokenTree::Token(Token { kind: token::Dollar, .. }),
466 TokenTree::Token(Token { kind: token::Ident(name, false), .. }),
468 if second_delim == &token::Paren && name.as_str() == "a" => {},
469 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
472 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
475 _ => panic!("value: {:?}",tts),
481 fn string_to_tts_1() {
482 with_default_globals(|| {
483 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
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(),
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(),
507 assert_eq!(tts, expected);
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);
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);
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);
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);
539 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
540 let item = string_to_item(src.to_string()).unwrap();
542 struct PatIdentVisitor {
545 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
546 fn visit_pat(&mut self, p: &'a ast::Pat) {
548 PatKind::Ident(_ , ref spannedident, _) => {
549 self.spans.push(spannedident.span.clone());
552 crate::visit::walk_pat(self, p);
557 let mut v = PatIdentVisitor { spans: Vec::new() };
558 crate::visit::walk_item(&mut v, &item);
562 #[test] fn span_of_self_arg_pat_idents_are_correct() {
563 with_default_globals(|| {
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) {} }",
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)
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());
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> {
596 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
600 fn wb() -> c_int { O_WRONLY as c_int }
602 let mut fflags: c_int = wb();
607 #[test] fn crlf_doc_comments() {
608 with_default_globals(|| {
609 let sess = ParseSess::new(FilePathMapping::empty());
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)
615 let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
616 assert_eq!(doc.as_str(), "/// doc comment");
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)
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);
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 */");
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()
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();
648 let tts: Vec<_> = match expr.node {
649 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
650 _ => panic!("not a macro"),
653 let span = tts.iter().rev().next().unwrap().span();
655 match sess.source_map().span_to_snippet(span) {
656 Ok(s) => assert_eq!(&s[..], "{ body }"),
657 Err(_) => panic!("could not get snippet"),
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.
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(),
675 if let ast::ItemKind::Mod(ref m) = item.node {
676 assert!(m.items.len() == 2);