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};
17 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
19 use std::path::{Path, PathBuf};
22 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
31 crate mod diagnostics;
34 crate mod unescape_error_reporting;
36 /// Info about a parsing session.
37 pub struct ParseSess {
38 pub span_diagnostic: Handler,
39 pub unstable_features: UnstableFeatures,
40 pub config: CrateConfig,
41 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
42 /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
43 pub raw_identifier_spans: Lock<Vec<Span>>,
44 /// The registered diagnostics codes.
45 crate registered_diagnostics: Lock<ErrorMap>,
46 /// Used to determine and report recursive module inclusions.
47 included_mod_stack: Lock<Vec<PathBuf>>,
48 source_map: Lrc<SourceMap>,
49 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
50 /// Contains the spans of block expressions that could have been incomplete based on the
51 /// operation token that followed it, but that the parser cannot identify without further
53 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
57 pub fn new(file_path_mapping: FilePathMapping) -> Self {
58 let cm = Lrc::new(SourceMap::new(file_path_mapping));
59 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
63 ParseSess::with_span_handler(handler, cm)
66 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
68 span_diagnostic: handler,
69 unstable_features: UnstableFeatures::from_environment(),
70 config: FxHashSet::default(),
71 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
72 raw_identifier_spans: Lock::new(Vec::new()),
73 registered_diagnostics: Lock::new(ErrorMap::new()),
74 included_mod_stack: Lock::new(vec![]),
76 buffered_lints: Lock::new(vec![]),
77 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
82 pub fn source_map(&self) -> &SourceMap {
86 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
87 lint_id: BufferedEarlyLintId,
92 self.buffered_lints.with_lock(|buffered_lints| {
93 buffered_lints.push(BufferedEarlyLint{
102 /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
103 /// parser to continue parsing the following operation as part of the same expression.
104 pub fn expr_parentheses_needed(
106 err: &mut DiagnosticBuilder<'_>,
108 alt_snippet: Option<String>,
110 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
113 "parentheses are required to parse this as an expression",
114 format!("({})", snippet),
115 Applicability::MachineApplicable,
122 pub struct Directory<'a> {
123 pub path: Cow<'a, Path>,
124 pub ownership: DirectoryOwnership,
127 #[derive(Copy, Clone)]
128 pub enum DirectoryOwnership {
130 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
131 relative: Option<ast::Ident>,
134 UnownedViaMod(bool /* legacy warnings? */),
137 // a bunch of utility functions of the form parse_<thing>_from_<source>
138 // where <thing> includes crate, expr, item, stmt, tts, and one that
139 // uses a HOF to parse anything, and <source> includes file and
142 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
143 let mut parser = new_parser_from_file(sess, input);
144 parser.parse_crate_mod()
147 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
148 -> PResult<'a, Vec<ast::Attribute>> {
149 let mut parser = new_parser_from_file(sess, input);
150 parser.parse_inner_attributes()
153 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
154 -> PResult<'_, ast::Crate> {
155 new_parser_from_source_str(sess, name, source).parse_crate_mod()
158 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
159 -> PResult<'_, Vec<ast::Attribute>> {
160 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
163 pub fn parse_stream_from_source_str(
167 override_span: Option<Span>,
169 let (stream, mut errors) = source_file_to_stream(
171 sess.source_map().new_source_file(name, source),
174 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
178 /// Creates a new parser from a source string.
179 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
180 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
183 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
185 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
186 -> Result<Parser<'_>, Vec<Diagnostic>>
188 let mut parser = maybe_source_file_to_parser(sess,
189 sess.source_map().new_source_file(name, source))?;
190 parser.recurse_into_file_modules = false;
194 /// Creates a new parser, handling errors as appropriate
195 /// if the file doesn't exist
196 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
197 source_file_to_parser(sess, file_to_source_file(sess, path, None))
200 /// Creates a new parser, returning buffered diagnostics if the file doesn't
201 /// exist or from lexing the initial token stream.
202 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
203 -> Result<Parser<'a>, Vec<Diagnostic>> {
204 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
205 maybe_source_file_to_parser(sess, file)
208 /// Given a session, a crate config, a path, and a span, add
209 /// the file at the given path to the source_map, and return a parser.
210 /// On an error, use the given span as the source of the problem.
211 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
213 directory_ownership: DirectoryOwnership,
214 module_name: Option<String>,
215 sp: Span) -> Parser<'a> {
216 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
217 p.directory.ownership = directory_ownership;
218 p.root_module_name = module_name;
222 /// Given a source_file and config, return a parser
223 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
224 panictry_buffer!(&sess.span_diagnostic,
225 maybe_source_file_to_parser(sess, source_file))
228 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
229 /// initial token stream.
230 fn maybe_source_file_to_parser(
232 source_file: Lrc<SourceFile>,
233 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
234 let end_pos = source_file.end_pos;
235 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
236 let mut parser = stream_to_parser(sess, stream);
237 parser.unclosed_delims = unclosed_delims;
238 if parser.token == token::Eof && parser.span.is_dummy() {
239 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
245 // must preserve old name for now, because quote! from the *existing*
246 // compiler expands into it
247 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
248 stream_to_parser(sess, tts.into_iter().collect())
254 /// Given a session and a path and an optional span (for error reporting),
255 /// add the path to the session's source_map and return the new source_file or
256 /// error when a file can't be read.
257 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
258 -> Result<Lrc<SourceFile>, Diagnostic> {
259 sess.source_map().load_file(path)
261 let msg = format!("couldn't read {}: {}", path.display(), e);
262 let mut diag = Diagnostic::new(Level::Fatal, &msg);
263 if let Some(sp) = spanopt {
270 /// Given a session and a path and an optional span (for error reporting),
271 /// add the path to the session's `source_map` and return the new `source_file`.
272 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
274 match try_file_to_source_file(sess, path, spanopt) {
275 Ok(source_file) => source_file,
277 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
283 /// Given a source_file, produces a sequence of token trees.
284 pub fn source_file_to_stream(
286 source_file: Lrc<SourceFile>,
287 override_span: Option<Span>,
288 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
289 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
292 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
293 /// parsing the token stream.
294 pub fn maybe_file_to_stream(
296 source_file: Lrc<SourceFile>,
297 override_span: Option<Span>,
298 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
299 let srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
300 let (token_trees, unmatched_braces) = srdr.into_token_trees();
303 Ok(stream) => Ok((stream, unmatched_braces)),
305 let mut buffer = Vec::with_capacity(1);
306 err.buffer(&mut buffer);
307 // Not using `emit_unclosed_delims` to use `db.buffer`
308 for unmatched in unmatched_braces {
309 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
310 "incorrect close delimiter: `{}`",
311 token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
313 db.span_label(unmatched.found_span, "incorrect close delimiter");
314 if let Some(sp) = unmatched.candidate_span {
315 db.span_label(sp, "close delimiter possibly meant for this");
317 if let Some(sp) = unmatched.unclosed_span {
318 db.span_label(sp, "un-closed delimiter");
320 db.buffer(&mut buffer);
327 /// Given stream and the `ParseSess`, produces a parser.
328 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
329 Parser::new(sess, stream, None, true, false)
332 /// A sequence separator.
334 /// The seperator token.
335 pub sep: Option<token::Token>,
336 /// `true` if a trailing separator is allowed.
337 pub trailing_sep_allowed: bool,
341 pub fn trailing_allowed(t: token::Token) -> SeqSep {
344 trailing_sep_allowed: true,
348 pub fn none() -> SeqSep {
351 trailing_sep_allowed: false,
359 use crate::ast::{self, Ident, PatKind};
360 use crate::attr::first_attr_value_str_by_name;
362 use crate::print::pprust::item_to_string;
363 use crate::tokenstream::{DelimSpan, TokenTree};
364 use crate::util::parser_testing::string_to_stream;
365 use crate::util::parser_testing::{string_to_expr, string_to_item};
366 use crate::with_globals;
367 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
371 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
372 /// when a syntax error occurred.
373 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
374 -> PResult<'_, Option<P<ast::Item>>> {
375 new_parser_from_source_str(sess, name, source).parse_item()
378 // produce a syntax_pos::span
379 fn sp(a: u32, b: u32) -> Span {
380 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
384 #[test] fn bad_path_expr_1() {
386 string_to_expr("::abc::def::return".to_string());
390 // check the token-tree-ization of macros
392 fn string_to_tts_macro () {
394 use crate::symbol::sym;
397 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
398 let tts: &[TokenTree] = &tts[..];
400 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
403 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
404 Some(&TokenTree::Token(_, token::Not)),
405 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
406 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
408 if name_macro_rules.name == sym::macro_rules
409 && name_zip.name.as_str() == "zip" => {
410 let tts = ¯o_tts.trees().collect::<Vec<_>>();
411 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
414 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
415 Some(&TokenTree::Token(_, token::FatArrow)),
416 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
418 if macro_delim == token::Paren => {
419 let tts = &first_tts.trees().collect::<Vec<_>>();
420 match (tts.len(), tts.get(0), tts.get(1)) {
423 Some(&TokenTree::Token(_, token::Dollar)),
424 Some(&TokenTree::Token(_, token::Ident(ident, false))),
426 if first_delim == token::Paren && ident.name.as_str() == "a" => {},
427 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
429 let tts = &second_tts.trees().collect::<Vec<_>>();
430 match (tts.len(), tts.get(0), tts.get(1)) {
433 Some(&TokenTree::Token(_, token::Dollar)),
434 Some(&TokenTree::Token(_, token::Ident(ident, false))),
436 if second_delim == token::Paren && ident.name.as_str() == "a" => {},
437 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
440 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
443 _ => panic!("value: {:?}",tts),
449 fn string_to_tts_1() {
451 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
453 let expected = TokenStream::new(vec![
454 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
455 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
456 TokenTree::Delimited(
457 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
458 token::DelimToken::Paren,
459 TokenStream::new(vec![
460 TokenTree::Token(sp(6, 7),
461 token::Ident(Ident::from_str("b"), false)).into(),
462 TokenTree::Token(sp(8, 9), token::Colon).into(),
463 TokenTree::Token(sp(10, 13),
464 token::Ident(Ident::from_str("i32"), false)).into(),
467 TokenTree::Delimited(
468 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
469 token::DelimToken::Brace,
470 TokenStream::new(vec![
471 TokenTree::Token(sp(17, 18),
472 token::Ident(Ident::from_str("b"), false)).into(),
473 TokenTree::Token(sp(18, 19), token::Semi).into(),
478 assert_eq!(tts, expected);
482 #[test] fn parse_use() {
484 let use_s = "use foo::bar::baz;";
485 let vitem = string_to_item(use_s.to_string()).unwrap();
486 let vitem_s = item_to_string(&vitem);
487 assert_eq!(&vitem_s[..], use_s);
489 let use_s = "use foo::bar as baz;";
490 let vitem = string_to_item(use_s.to_string()).unwrap();
491 let vitem_s = item_to_string(&vitem);
492 assert_eq!(&vitem_s[..], use_s);
496 #[test] fn parse_extern_crate() {
498 let ex_s = "extern crate foo;";
499 let vitem = string_to_item(ex_s.to_string()).unwrap();
500 let vitem_s = item_to_string(&vitem);
501 assert_eq!(&vitem_s[..], ex_s);
503 let ex_s = "extern crate foo as bar;";
504 let vitem = string_to_item(ex_s.to_string()).unwrap();
505 let vitem_s = item_to_string(&vitem);
506 assert_eq!(&vitem_s[..], ex_s);
510 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
511 let item = string_to_item(src.to_string()).unwrap();
513 struct PatIdentVisitor {
516 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
517 fn visit_pat(&mut self, p: &'a ast::Pat) {
519 PatKind::Ident(_ , ref spannedident, _) => {
520 self.spans.push(spannedident.span.clone());
523 crate::visit::walk_pat(self, p);
528 let mut v = PatIdentVisitor { spans: Vec::new() };
529 crate::visit::walk_item(&mut v, &item);
533 #[test] fn span_of_self_arg_pat_idents_are_correct() {
536 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
537 "impl z { fn a (&mut self, &myarg: i32) {} }",
538 "impl z { fn a (&'a self, &myarg: i32) {} }",
539 "impl z { fn a (self, &myarg: i32) {} }",
540 "impl z { fn a (self: Foo, &myarg: i32) {} }",
544 let spans = get_spans_of_pat_idents(src);
545 let (lo, hi) = (spans[0].lo(), spans[0].hi());
546 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
547 "\"{}\" != \"self\". src=\"{}\"",
548 &src[lo.to_usize()..hi.to_usize()], src)
553 #[test] fn parse_exprs () {
555 // just make sure that they parse....
556 string_to_expr("3 + 4".to_string());
557 string_to_expr("a::z.froob(b,&(987+3))".to_string());
561 #[test] fn attrs_fix_bug () {
563 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
564 -> Result<Box<Writer>, String> {
567 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
571 fn wb() -> c_int { O_WRONLY as c_int }
573 let mut fflags: c_int = wb();
578 #[test] fn crlf_doc_comments() {
580 use crate::symbol::sym;
582 let sess = ParseSess::new(FilePathMapping::empty());
584 let name_1 = FileName::Custom("crlf_source_1".to_string());
585 let source = "/// doc comment\r\nfn foo() {}".to_string();
586 let item = parse_item_from_source_str(name_1, source, &sess)
588 let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
589 assert_eq!(doc.as_str(), "/// doc comment");
591 let name_2 = FileName::Custom("crlf_source_2".to_string());
592 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
593 let item = parse_item_from_source_str(name_2, source, &sess)
595 let docs = item.attrs.iter().filter(|a| a.path == sym::doc)
596 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
597 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
598 assert_eq!(&docs[..], b);
600 let name_3 = FileName::Custom("clrf_source_3".to_string());
601 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
602 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
603 let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
604 assert_eq!(doc.as_str(), "/** doc comment\n * with CRLF */");
610 fn parse_expr_from_source_str(
611 name: FileName, source: String, sess: &ParseSess
612 ) -> PResult<'_, P<ast::Expr>> {
613 new_parser_from_source_str(sess, name, source).parse_expr()
617 let sess = ParseSess::new(FilePathMapping::empty());
618 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
619 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
621 let tts: Vec<_> = match expr.node {
622 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
623 _ => panic!("not a macro"),
626 let span = tts.iter().rev().next().unwrap().span();
628 match sess.source_map().span_to_snippet(span) {
629 Ok(s) => assert_eq!(&s[..], "{ body }"),
630 Err(_) => panic!("could not get snippet"),
635 // This tests that when parsing a string (rather than a file) we don't try
636 // and read in a file for a module declaration and just parse a stub.
637 // See `recurse_into_file_modules` in the parser.
639 fn out_of_line_mod() {
641 let sess = ParseSess::new(FilePathMapping::empty());
642 let item = parse_item_from_source_str(
643 PathBuf::from("foo").into(),
644 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
648 if let ast::ItemKind::Mod(ref m) = item.node {
649 assert!(m.items.len() == 2);