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::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;
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;
18 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
20 use std::path::{Path, PathBuf};
23 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
32 crate mod diagnostics;
35 crate mod unescape_error_reporting;
37 /// Info about a parsing session.
38 pub struct ParseSess {
39 pub span_diagnostic: Handler,
40 pub unstable_features: UnstableFeatures,
41 pub config: CrateConfig,
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
55 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
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,
65 ParseSess::with_span_handler(handler, cm)
68 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> 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![]),
78 buffered_lints: Lock::new(vec![]),
79 edition: Edition::from_session(),
80 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
85 pub fn source_map(&self) -> &SourceMap {
89 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
90 lint_id: BufferedEarlyLintId,
95 self.buffered_lints.with_lock(|buffered_lints| {
96 buffered_lints.push(BufferedEarlyLint{
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(
109 err: &mut DiagnosticBuilder<'_>,
111 alt_snippet: Option<String>,
113 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
116 "parentheses are required to parse this as an expression",
117 format!("({})", snippet),
118 Applicability::MachineApplicable,
125 pub struct Directory<'a> {
126 pub path: Cow<'a, Path>,
127 pub ownership: DirectoryOwnership,
130 #[derive(Copy, Clone)]
131 pub enum DirectoryOwnership {
133 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
134 relative: Option<ast::Ident>,
137 UnownedViaMod(bool /* legacy warnings? */),
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
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()
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()
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()
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()
166 pub fn parse_stream_from_source_str(
170 override_span: Option<Span>,
172 let (stream, mut errors) = source_file_to_stream(
174 sess.source_map().new_source_file(name, source),
177 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
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))
186 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
188 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
189 -> Result<Parser<'_>, Vec<Diagnostic>>
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;
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))
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)
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,
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;
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))
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(
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());
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)
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)
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 {
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>)
277 match try_file_to_source_file(sess, path, spanopt) {
278 Ok(source_file) => source_file,
280 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
286 /// Given a source_file, produces a sequence of token trees.
287 pub fn source_file_to_stream(
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))
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(
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();
306 Ok(stream) => Ok((stream, unmatched_braces)),
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)),
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");
320 if let Some(sp) = unmatched.unclosed_span {
321 db.span_label(sp, "un-closed delimiter");
323 db.buffer(&mut buffer);
330 /// Given stream and the `ParseSess`, produces a parser.
331 pub fn stream_to_parser<'a>(
334 subparser_name: Option<&'static str>,
336 Parser::new(sess, stream, None, true, false, subparser_name)
339 /// Given stream, the `ParseSess` and the base directory, produces a parser.
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).
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>(
353 base_dir: Directory<'a>,
355 Parser::new(sess, stream, Some(base_dir), true, false, None)
358 /// A sequence separator.
360 /// The seperator token.
361 pub sep: Option<token::TokenKind>,
362 /// `true` if a trailing separator is allowed.
363 pub trailing_sep_allowed: bool,
367 pub fn trailing_allowed(t: token::TokenKind) -> SeqSep {
370 trailing_sep_allowed: true,
374 pub fn none() -> SeqSep {
377 trailing_sep_allowed: false,
385 use crate::ast::{self, Ident, PatKind};
386 use crate::attr::first_attr_value_str_by_name;
388 use crate::print::pprust::item_to_string;
389 use crate::tokenstream::{DelimSpan, TokenTree};
390 use crate::util::parser_testing::string_to_stream;
391 use crate::util::parser_testing::{string_to_expr, string_to_item};
392 use crate::with_default_globals;
393 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
397 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
398 /// when a syntax error occurred.
399 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
400 -> PResult<'_, Option<P<ast::Item>>> {
401 new_parser_from_source_str(sess, name, source).parse_item()
404 // produce a syntax_pos::span
405 fn sp(a: u32, b: u32) -> Span {
406 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
410 #[test] fn bad_path_expr_1() {
411 with_default_globals(|| {
412 string_to_expr("::abc::def::return".to_string());
416 // check the token-tree-ization of macros
418 fn string_to_tts_macro () {
419 with_default_globals(|| {
420 use crate::symbol::sym;
423 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
424 let tts: &[TokenTree] = &tts[..];
426 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
429 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
430 Some(&TokenTree::Token(_, token::Not)),
431 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
432 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
434 if name_macro_rules.name == sym::macro_rules
435 && name_zip.name.as_str() == "zip" => {
436 let tts = ¯o_tts.trees().collect::<Vec<_>>();
437 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
440 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
441 Some(&TokenTree::Token(_, token::FatArrow)),
442 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
444 if macro_delim == token::Paren => {
445 let tts = &first_tts.trees().collect::<Vec<_>>();
446 match (tts.len(), tts.get(0), tts.get(1)) {
449 Some(&TokenTree::Token(_, token::Dollar)),
450 Some(&TokenTree::Token(_, token::Ident(ident, false))),
452 if first_delim == token::Paren && ident.name.as_str() == "a" => {},
453 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
455 let tts = &second_tts.trees().collect::<Vec<_>>();
456 match (tts.len(), tts.get(0), tts.get(1)) {
459 Some(&TokenTree::Token(_, token::Dollar)),
460 Some(&TokenTree::Token(_, token::Ident(ident, false))),
462 if second_delim == token::Paren && ident.name.as_str() == "a" => {},
463 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
466 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
469 _ => panic!("value: {:?}",tts),
475 fn string_to_tts_1() {
476 with_default_globals(|| {
477 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
479 let expected = TokenStream::new(vec![
480 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
481 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
482 TokenTree::Delimited(
483 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
484 token::DelimToken::Paren,
485 TokenStream::new(vec![
486 TokenTree::Token(sp(6, 7),
487 token::Ident(Ident::from_str("b"), false)).into(),
488 TokenTree::Token(sp(8, 9), token::Colon).into(),
489 TokenTree::Token(sp(10, 13),
490 token::Ident(Ident::from_str("i32"), false)).into(),
493 TokenTree::Delimited(
494 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
495 token::DelimToken::Brace,
496 TokenStream::new(vec![
497 TokenTree::Token(sp(17, 18),
498 token::Ident(Ident::from_str("b"), false)).into(),
499 TokenTree::Token(sp(18, 19), token::Semi).into(),
504 assert_eq!(tts, expected);
508 #[test] fn parse_use() {
509 with_default_globals(|| {
510 let use_s = "use foo::bar::baz;";
511 let vitem = string_to_item(use_s.to_string()).unwrap();
512 let vitem_s = item_to_string(&vitem);
513 assert_eq!(&vitem_s[..], use_s);
515 let use_s = "use foo::bar as baz;";
516 let vitem = string_to_item(use_s.to_string()).unwrap();
517 let vitem_s = item_to_string(&vitem);
518 assert_eq!(&vitem_s[..], use_s);
522 #[test] fn parse_extern_crate() {
523 with_default_globals(|| {
524 let ex_s = "extern crate foo;";
525 let vitem = string_to_item(ex_s.to_string()).unwrap();
526 let vitem_s = item_to_string(&vitem);
527 assert_eq!(&vitem_s[..], ex_s);
529 let ex_s = "extern crate foo as bar;";
530 let vitem = string_to_item(ex_s.to_string()).unwrap();
531 let vitem_s = item_to_string(&vitem);
532 assert_eq!(&vitem_s[..], ex_s);
536 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
537 let item = string_to_item(src.to_string()).unwrap();
539 struct PatIdentVisitor {
542 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
543 fn visit_pat(&mut self, p: &'a ast::Pat) {
545 PatKind::Ident(_ , ref spannedident, _) => {
546 self.spans.push(spannedident.span.clone());
549 crate::visit::walk_pat(self, p);
554 let mut v = PatIdentVisitor { spans: Vec::new() };
555 crate::visit::walk_item(&mut v, &item);
559 #[test] fn span_of_self_arg_pat_idents_are_correct() {
560 with_default_globals(|| {
562 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
563 "impl z { fn a (&mut self, &myarg: i32) {} }",
564 "impl z { fn a (&'a self, &myarg: i32) {} }",
565 "impl z { fn a (self, &myarg: i32) {} }",
566 "impl z { fn a (self: Foo, &myarg: i32) {} }",
570 let spans = get_spans_of_pat_idents(src);
571 let (lo, hi) = (spans[0].lo(), spans[0].hi());
572 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
573 "\"{}\" != \"self\". src=\"{}\"",
574 &src[lo.to_usize()..hi.to_usize()], src)
579 #[test] fn parse_exprs () {
580 with_default_globals(|| {
581 // just make sure that they parse....
582 string_to_expr("3 + 4".to_string());
583 string_to_expr("a::z.froob(b,&(987+3))".to_string());
587 #[test] fn attrs_fix_bug () {
588 with_default_globals(|| {
589 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
590 -> Result<Box<Writer>, String> {
593 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
597 fn wb() -> c_int { O_WRONLY as c_int }
599 let mut fflags: c_int = wb();
604 #[test] fn crlf_doc_comments() {
605 with_default_globals(|| {
606 use crate::symbol::sym;
608 let sess = ParseSess::new(FilePathMapping::empty());
610 let name_1 = FileName::Custom("crlf_source_1".to_string());
611 let source = "/// doc comment\r\nfn foo() {}".to_string();
612 let item = parse_item_from_source_str(name_1, source, &sess)
614 let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
615 assert_eq!(doc.as_str(), "/// doc comment");
617 let name_2 = FileName::Custom("crlf_source_2".to_string());
618 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
619 let item = parse_item_from_source_str(name_2, source, &sess)
621 let docs = item.attrs.iter().filter(|a| a.path == sym::doc)
622 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
623 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
624 assert_eq!(&docs[..], b);
626 let name_3 = FileName::Custom("clrf_source_3".to_string());
627 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
628 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
629 let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
630 assert_eq!(doc.as_str(), "/** doc comment\n * with CRLF */");
636 fn parse_expr_from_source_str(
637 name: FileName, source: String, sess: &ParseSess
638 ) -> PResult<'_, P<ast::Expr>> {
639 new_parser_from_source_str(sess, name, source).parse_expr()
642 with_default_globals(|| {
643 let sess = ParseSess::new(FilePathMapping::empty());
644 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
645 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
647 let tts: Vec<_> = match expr.node {
648 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
649 _ => panic!("not a macro"),
652 let span = tts.iter().rev().next().unwrap().span();
654 match sess.source_map().span_to_snippet(span) {
655 Ok(s) => assert_eq!(&s[..], "{ body }"),
656 Err(_) => panic!("could not get snippet"),
661 // This tests that when parsing a string (rather than a file) we don't try
662 // and read in a file for a module declaration and just parse a stub.
663 // See `recurse_into_file_modules` in the parser.
665 fn out_of_line_mod() {
666 with_default_globals(|| {
667 let sess = ParseSess::new(FilePathMapping::empty());
668 let item = parse_item_from_source_str(
669 PathBuf::from("foo").into(),
670 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
674 if let ast::ItemKind::Mod(ref m) = item.node {
675 assert!(m.items.len() == 2);