1 //! The main parser interface.
3 #![feature(array_windows)]
4 #![feature(box_patterns)]
5 #![feature(if_let_guard)]
6 #![feature(let_chains)]
7 #![feature(never_type)]
8 #![feature(rustc_attrs)]
9 #![recursion_limit = "256"]
16 use rustc_ast::tokenstream::TokenStream;
17 use rustc_ast::Attribute;
18 use rustc_ast::{AttrItem, MetaItem};
19 use rustc_ast_pretty::pprust;
20 use rustc_data_structures::sync::Lrc;
21 use rustc_errors::{Applicability, Diagnostic, FatalError, Level, PResult};
22 use rustc_session::parse::ParseSess;
23 use rustc_span::{FileName, SourceFile, Span};
27 pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
31 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
33 pub mod validate_attr;
37 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
38 // where <thing> includes crate, expr, item, stmt, tts, and one that
39 // uses a HOF to parse anything, and <source> includes file and
42 /// A variant of 'panictry!' that works on a `Vec<Diagnostic>` instead of a single
43 /// `DiagnosticBuilder`.
44 macro_rules! panictry_buffer {
45 ($handler:expr, $e:expr) => {{
46 use rustc_errors::FatalError;
47 use std::result::Result::{Err, Ok};
52 $handler.emit_diagnostic(&mut e);
60 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
61 let mut parser = new_parser_from_file(sess, input, None);
62 parser.parse_crate_mod()
65 pub fn parse_crate_attrs_from_file<'a>(
68 ) -> PResult<'a, ast::AttrVec> {
69 let mut parser = new_parser_from_file(sess, input, None);
70 parser.parse_inner_attributes()
73 pub fn parse_crate_from_source_str(
77 ) -> PResult<'_, ast::Crate> {
78 new_parser_from_source_str(sess, name, source).parse_crate_mod()
81 pub fn parse_crate_attrs_from_source_str(
85 ) -> PResult<'_, ast::AttrVec> {
86 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
89 pub fn parse_stream_from_source_str(
93 override_span: Option<Span>,
95 let (stream, mut errors) =
96 source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
97 emit_unclosed_delims(&mut errors, &sess);
101 /// Creates a new parser from a source string.
102 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
103 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
106 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
108 pub fn maybe_new_parser_from_source_str(
112 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
113 maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
116 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
117 /// If a span is given, that is used on an error as the source of the problem.
118 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
119 source_file_to_parser(sess, file_to_source_file(sess, path, sp))
122 /// Given a session and a `source_file`, returns a parser.
123 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
124 panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
127 /// Given a session and a `source_file`, return a parser. Returns any buffered errors from lexing the
128 /// initial token stream.
129 fn maybe_source_file_to_parser(
131 source_file: Lrc<SourceFile>,
132 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
133 let end_pos = source_file.end_pos;
134 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
135 let mut parser = stream_to_parser(sess, stream, None);
136 parser.unclosed_delims = unclosed_delims;
137 if parser.token == token::Eof {
138 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt(), None);
146 /// Given a session and a path and an optional span (for error reporting),
147 /// add the path to the session's source_map and return the new source_file or
148 /// error when a file can't be read.
149 fn try_file_to_source_file(
152 spanopt: Option<Span>,
153 ) -> Result<Lrc<SourceFile>, Diagnostic> {
154 sess.source_map().load_file(path).map_err(|e| {
155 let msg = format!("couldn't read {}: {}", path.display(), e);
156 let mut diag = Diagnostic::new(Level::Fatal, &msg);
157 if let Some(sp) = spanopt {
164 /// Given a session and a path and an optional span (for error reporting),
165 /// adds the path to the session's `source_map` and returns the new `source_file`.
166 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
167 match try_file_to_source_file(sess, path, spanopt) {
168 Ok(source_file) => source_file,
170 sess.span_diagnostic.emit_diagnostic(&mut d);
176 /// Given a `source_file`, produces a sequence of token trees.
177 pub fn source_file_to_stream(
179 source_file: Lrc<SourceFile>,
180 override_span: Option<Span>,
181 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
182 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
185 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
186 /// parsing the token stream.
187 pub fn maybe_file_to_stream(
189 source_file: Lrc<SourceFile>,
190 override_span: Option<Span>,
191 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
192 let src = source_file.src.as_ref().unwrap_or_else(|| {
193 sess.span_diagnostic.bug(&format!(
194 "cannot lex `source_file` without source: {}",
195 sess.source_map().filename_for_diagnostics(&source_file.name)
199 let (token_trees, unmatched_braces) =
200 lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
203 Ok(stream) => Ok((stream, unmatched_braces)),
205 let mut buffer = Vec::with_capacity(1);
206 err.buffer(&mut buffer);
207 // Not using `emit_unclosed_delims` to use `db.buffer`
208 for unmatched in unmatched_braces {
209 if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
210 err.buffer(&mut buffer);
218 /// Given a stream and the `ParseSess`, produces a parser.
219 pub fn stream_to_parser<'a>(
222 subparser_name: Option<&'static str>,
224 Parser::new(sess, stream, false, subparser_name)
227 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
228 pub fn parse_in<'a, T>(
232 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
233 ) -> PResult<'a, T> {
234 let mut parser = Parser::new(sess, tts, false, Some(name));
235 let result = f(&mut parser)?;
236 if parser.token != token::Eof {
237 parser.unexpected()?;
242 pub fn fake_token_stream_for_item(sess: &ParseSess, item: &ast::Item) -> TokenStream {
243 let source = pprust::item_to_string(item);
244 let filename = FileName::macro_expansion_source_code(&source);
245 parse_stream_from_source_str(filename, source, sess, Some(item.span))
248 pub fn fake_token_stream_for_crate(sess: &ParseSess, krate: &ast::Crate) -> TokenStream {
249 let source = pprust::crate_to_string_for_macros(krate);
250 let filename = FileName::macro_expansion_source_code(&source);
251 parse_stream_from_source_str(filename, source, sess, Some(krate.spans.inner_span))
254 pub fn parse_cfg_attr(
256 parse_sess: &ParseSess,
257 ) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
258 match attr.get_normal_item().args {
259 ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
260 let msg = "wrong `cfg_attr` delimiters";
261 crate::validate_attr::check_meta_bad_delim(parse_sess, dspan, delim, msg);
262 match parse_in(parse_sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
263 Ok(r) => return Some(r),
265 e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
266 .note(CFG_ATTR_NOTE_REF)
271 _ => error_malformed_cfg_attr_missing(attr.span, parse_sess),
276 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
277 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
278 <https://doc.rust-lang.org/reference/conditional-compilation.html\
279 #the-cfg_attr-attribute>";
281 fn error_malformed_cfg_attr_missing(span: Span, parse_sess: &ParseSess) {
284 .struct_span_err(span, "malformed `cfg_attr` attribute input")
287 "missing condition and attribute",
288 CFG_ATTR_GRAMMAR_HELP,
289 Applicability::HasPlaceholders,
291 .note(CFG_ATTR_NOTE_REF)