1 //! The main parser interface.
3 #![feature(array_windows)]
4 #![feature(box_patterns)]
5 #![feature(if_let_guard)]
6 #![cfg_attr(bootstrap, feature(let_chains))]
8 #![feature(never_type)]
9 #![feature(rustc_attrs)]
10 #![recursion_limit = "256"]
17 use rustc_ast::tokenstream::TokenStream;
18 use rustc_ast::Attribute;
19 use rustc_ast::{AttrItem, MetaItem};
20 use rustc_ast_pretty::pprust;
21 use rustc_data_structures::sync::Lrc;
22 use rustc_errors::{Applicability, Diagnostic, FatalError, Level, PResult};
23 use rustc_session::parse::ParseSess;
24 use rustc_span::{FileName, SourceFile, Span};
28 pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
32 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
34 pub mod validate_attr;
36 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
37 // where <thing> includes crate, expr, item, stmt, tts, and one that
38 // uses a HOF to parse anything, and <source> includes file and
41 /// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder.
42 macro_rules! panictry_buffer {
43 ($handler:expr, $e:expr) => {{
44 use rustc_errors::FatalError;
45 use std::result::Result::{Err, Ok};
50 $handler.emit_diagnostic(&mut e);
58 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
59 let mut parser = new_parser_from_file(sess, input, None);
60 parser.parse_crate_mod()
63 pub fn parse_crate_attrs_from_file<'a>(
66 ) -> PResult<'a, Vec<ast::Attribute>> {
67 let mut parser = new_parser_from_file(sess, input, None);
68 parser.parse_inner_attributes()
71 pub fn parse_crate_from_source_str(
75 ) -> PResult<'_, ast::Crate> {
76 new_parser_from_source_str(sess, name, source).parse_crate_mod()
79 pub fn parse_crate_attrs_from_source_str(
83 ) -> PResult<'_, Vec<ast::Attribute>> {
84 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
87 pub fn parse_stream_from_source_str(
91 override_span: Option<Span>,
93 let (stream, mut errors) =
94 source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
95 emit_unclosed_delims(&mut errors, &sess);
99 /// Creates a new parser from a source string.
100 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
101 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
104 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
106 pub fn maybe_new_parser_from_source_str(
110 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
111 maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
114 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
115 /// If a span is given, that is used on an error as the source of the problem.
116 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
117 source_file_to_parser(sess, file_to_source_file(sess, path, sp))
120 /// Given a session and a `source_file`, returns a parser.
121 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
122 panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
125 /// Given a session and a `source_file`, return a parser. Returns any buffered errors from lexing the
126 /// initial token stream.
127 fn maybe_source_file_to_parser(
129 source_file: Lrc<SourceFile>,
130 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
131 let end_pos = source_file.end_pos;
132 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
133 let mut parser = stream_to_parser(sess, stream, None);
134 parser.unclosed_delims = unclosed_delims;
135 if parser.token == token::Eof {
136 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt(), None);
144 /// Given a session and a path and an optional span (for error reporting),
145 /// add the path to the session's source_map and return the new source_file or
146 /// error when a file can't be read.
147 fn try_file_to_source_file(
150 spanopt: Option<Span>,
151 ) -> Result<Lrc<SourceFile>, Diagnostic> {
152 sess.source_map().load_file(path).map_err(|e| {
153 let msg = format!("couldn't read {}: {}", path.display(), e);
154 let mut diag = Diagnostic::new(Level::Fatal, &msg);
155 if let Some(sp) = spanopt {
162 /// Given a session and a path and an optional span (for error reporting),
163 /// adds the path to the session's `source_map` and returns the new `source_file`.
164 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
165 match try_file_to_source_file(sess, path, spanopt) {
166 Ok(source_file) => source_file,
168 sess.span_diagnostic.emit_diagnostic(&mut d);
174 /// Given a `source_file`, produces a sequence of token trees.
175 pub fn source_file_to_stream(
177 source_file: Lrc<SourceFile>,
178 override_span: Option<Span>,
179 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
180 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
183 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
184 /// parsing the token stream.
185 pub fn maybe_file_to_stream(
187 source_file: Lrc<SourceFile>,
188 override_span: Option<Span>,
189 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
190 let src = source_file.src.as_ref().unwrap_or_else(|| {
191 sess.span_diagnostic.bug(&format!(
192 "cannot lex `source_file` without source: {}",
193 sess.source_map().filename_for_diagnostics(&source_file.name)
197 let (token_trees, unmatched_braces) =
198 lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
201 Ok(stream) => Ok((stream, unmatched_braces)),
203 let mut buffer = Vec::with_capacity(1);
204 err.buffer(&mut buffer);
205 // Not using `emit_unclosed_delims` to use `db.buffer`
206 for unmatched in unmatched_braces {
207 if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
208 err.buffer(&mut buffer);
216 /// Given a stream and the `ParseSess`, produces a parser.
217 pub fn stream_to_parser<'a>(
220 subparser_name: Option<&'static str>,
222 Parser::new(sess, stream, false, subparser_name)
225 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
226 pub fn parse_in<'a, T>(
230 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
231 ) -> PResult<'a, T> {
232 let mut parser = Parser::new(sess, tts, false, Some(name));
233 let result = f(&mut parser)?;
234 if parser.token != token::Eof {
235 parser.unexpected()?;
240 pub fn fake_token_stream_for_item(sess: &ParseSess, item: &ast::Item) -> TokenStream {
241 let source = pprust::item_to_string(item);
242 let filename = FileName::macro_expansion_source_code(&source);
243 parse_stream_from_source_str(filename, source, sess, Some(item.span))
246 pub fn fake_token_stream_for_crate(sess: &ParseSess, krate: &ast::Crate) -> TokenStream {
247 let source = pprust::crate_to_string_for_macros(krate);
248 let filename = FileName::macro_expansion_source_code(&source);
249 parse_stream_from_source_str(filename, source, sess, Some(krate.spans.inner_span))
252 pub fn parse_cfg_attr(
254 parse_sess: &ParseSess,
255 ) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
256 match attr.get_normal_item().args {
257 ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
258 let msg = "wrong `cfg_attr` delimiters";
259 crate::validate_attr::check_meta_bad_delim(parse_sess, dspan, delim, msg);
260 match parse_in(parse_sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
261 Ok(r) => return Some(r),
263 e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
264 .note(CFG_ATTR_NOTE_REF)
269 _ => error_malformed_cfg_attr_missing(attr.span, parse_sess),
274 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
275 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
276 <https://doc.rust-lang.org/reference/conditional-compilation.html\
277 #the-cfg_attr-attribute>";
279 fn error_malformed_cfg_attr_missing(span: Span, parse_sess: &ParseSess) {
282 .struct_span_err(span, "malformed `cfg_attr` attribute input")
285 "missing condition and attribute",
286 CFG_ATTR_GRAMMAR_HELP,
287 Applicability::HasPlaceholders,
289 .note(CFG_ATTR_NOTE_REF)