]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/lib.rs
Rollup merge of #100953 - joshtriplett:write-docs, r=Mark-Simulacrum
[rust.git] / compiler / rustc_parse / src / lib.rs
1 //! The main parser interface.
2
3 #![feature(array_windows)]
4 #![feature(box_patterns)]
5 #![feature(if_let_guard)]
6 #![feature(let_else)]
7 #![feature(never_type)]
8 #![feature(rustc_attrs)]
9 #![recursion_limit = "256"]
10
11 #[macro_use]
12 extern crate tracing;
13
14 use rustc_ast as ast;
15 use rustc_ast::token;
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};
24
25 use std::path::Path;
26
27 pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
28
29 #[macro_use]
30 pub mod parser;
31 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
32 pub mod lexer;
33 pub mod validate_attr;
34
35 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
36 // where <thing> includes crate, expr, item, stmt, tts, and one that
37 // uses a HOF to parse anything, and <source> includes file and
38 // `source_str`.
39
40 /// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder.
41 macro_rules! panictry_buffer {
42     ($handler:expr, $e:expr) => {{
43         use rustc_errors::FatalError;
44         use std::result::Result::{Err, Ok};
45         match $e {
46             Ok(e) => e,
47             Err(errs) => {
48                 for mut e in errs {
49                     $handler.emit_diagnostic(&mut e);
50                 }
51                 FatalError.raise()
52             }
53         }
54     }};
55 }
56
57 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
58     let mut parser = new_parser_from_file(sess, input, None);
59     parser.parse_crate_mod()
60 }
61
62 pub fn parse_crate_attrs_from_file<'a>(
63     input: &Path,
64     sess: &'a ParseSess,
65 ) -> PResult<'a, ast::AttrVec> {
66     let mut parser = new_parser_from_file(sess, input, None);
67     parser.parse_inner_attributes()
68 }
69
70 pub fn parse_crate_from_source_str(
71     name: FileName,
72     source: String,
73     sess: &ParseSess,
74 ) -> PResult<'_, ast::Crate> {
75     new_parser_from_source_str(sess, name, source).parse_crate_mod()
76 }
77
78 pub fn parse_crate_attrs_from_source_str(
79     name: FileName,
80     source: String,
81     sess: &ParseSess,
82 ) -> PResult<'_, ast::AttrVec> {
83     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
84 }
85
86 pub fn parse_stream_from_source_str(
87     name: FileName,
88     source: String,
89     sess: &ParseSess,
90     override_span: Option<Span>,
91 ) -> TokenStream {
92     let (stream, mut errors) =
93         source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
94     emit_unclosed_delims(&mut errors, &sess);
95     stream
96 }
97
98 /// Creates a new parser from a source string.
99 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
100     panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
101 }
102
103 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
104 /// token stream.
105 pub fn maybe_new_parser_from_source_str(
106     sess: &ParseSess,
107     name: FileName,
108     source: String,
109 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
110     maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
111 }
112
113 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
114 /// If a span is given, that is used on an error as the source of the problem.
115 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
116     source_file_to_parser(sess, file_to_source_file(sess, path, sp))
117 }
118
119 /// Given a session and a `source_file`, returns a parser.
120 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
121     panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
122 }
123
124 /// Given a session and a `source_file`, return a parser. Returns any buffered errors from lexing the
125 /// initial token stream.
126 fn maybe_source_file_to_parser(
127     sess: &ParseSess,
128     source_file: Lrc<SourceFile>,
129 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
130     let end_pos = source_file.end_pos;
131     let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
132     let mut parser = stream_to_parser(sess, stream, None);
133     parser.unclosed_delims = unclosed_delims;
134     if parser.token == token::Eof {
135         parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt(), None);
136     }
137
138     Ok(parser)
139 }
140
141 // Base abstractions
142
143 /// Given a session and a path and an optional span (for error reporting),
144 /// add the path to the session's source_map and return the new source_file or
145 /// error when a file can't be read.
146 fn try_file_to_source_file(
147     sess: &ParseSess,
148     path: &Path,
149     spanopt: Option<Span>,
150 ) -> Result<Lrc<SourceFile>, Diagnostic> {
151     sess.source_map().load_file(path).map_err(|e| {
152         let msg = format!("couldn't read {}: {}", path.display(), e);
153         let mut diag = Diagnostic::new(Level::Fatal, &msg);
154         if let Some(sp) = spanopt {
155             diag.set_span(sp);
156         }
157         diag
158     })
159 }
160
161 /// Given a session and a path and an optional span (for error reporting),
162 /// adds the path to the session's `source_map` and returns the new `source_file`.
163 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
164     match try_file_to_source_file(sess, path, spanopt) {
165         Ok(source_file) => source_file,
166         Err(mut d) => {
167             sess.span_diagnostic.emit_diagnostic(&mut d);
168             FatalError.raise();
169         }
170     }
171 }
172
173 /// Given a `source_file`, produces a sequence of token trees.
174 pub fn source_file_to_stream(
175     sess: &ParseSess,
176     source_file: Lrc<SourceFile>,
177     override_span: Option<Span>,
178 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
179     panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
180 }
181
182 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
183 /// parsing the token stream.
184 pub fn maybe_file_to_stream(
185     sess: &ParseSess,
186     source_file: Lrc<SourceFile>,
187     override_span: Option<Span>,
188 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
189     let src = source_file.src.as_ref().unwrap_or_else(|| {
190         sess.span_diagnostic.bug(&format!(
191             "cannot lex `source_file` without source: {}",
192             sess.source_map().filename_for_diagnostics(&source_file.name)
193         ));
194     });
195
196     let (token_trees, unmatched_braces) =
197         lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
198
199     match token_trees {
200         Ok(stream) => Ok((stream, unmatched_braces)),
201         Err(err) => {
202             let mut buffer = Vec::with_capacity(1);
203             err.buffer(&mut buffer);
204             // Not using `emit_unclosed_delims` to use `db.buffer`
205             for unmatched in unmatched_braces {
206                 if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
207                     err.buffer(&mut buffer);
208                 }
209             }
210             Err(buffer)
211         }
212     }
213 }
214
215 /// Given a stream and the `ParseSess`, produces a parser.
216 pub fn stream_to_parser<'a>(
217     sess: &'a ParseSess,
218     stream: TokenStream,
219     subparser_name: Option<&'static str>,
220 ) -> Parser<'a> {
221     Parser::new(sess, stream, false, subparser_name)
222 }
223
224 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
225 pub fn parse_in<'a, T>(
226     sess: &'a ParseSess,
227     tts: TokenStream,
228     name: &'static str,
229     mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
230 ) -> PResult<'a, T> {
231     let mut parser = Parser::new(sess, tts, false, Some(name));
232     let result = f(&mut parser)?;
233     if parser.token != token::Eof {
234         parser.unexpected()?;
235     }
236     Ok(result)
237 }
238
239 pub fn fake_token_stream_for_item(sess: &ParseSess, item: &ast::Item) -> TokenStream {
240     let source = pprust::item_to_string(item);
241     let filename = FileName::macro_expansion_source_code(&source);
242     parse_stream_from_source_str(filename, source, sess, Some(item.span))
243 }
244
245 pub fn fake_token_stream_for_crate(sess: &ParseSess, krate: &ast::Crate) -> TokenStream {
246     let source = pprust::crate_to_string_for_macros(krate);
247     let filename = FileName::macro_expansion_source_code(&source);
248     parse_stream_from_source_str(filename, source, sess, Some(krate.spans.inner_span))
249 }
250
251 pub fn parse_cfg_attr(
252     attr: &Attribute,
253     parse_sess: &ParseSess,
254 ) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
255     match attr.get_normal_item().args {
256         ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
257             let msg = "wrong `cfg_attr` delimiters";
258             crate::validate_attr::check_meta_bad_delim(parse_sess, dspan, delim, msg);
259             match parse_in(parse_sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
260                 Ok(r) => return Some(r),
261                 Err(mut e) => {
262                     e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
263                         .note(CFG_ATTR_NOTE_REF)
264                         .emit();
265                 }
266             }
267         }
268         _ => error_malformed_cfg_attr_missing(attr.span, parse_sess),
269     }
270     None
271 }
272
273 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
274 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
275     <https://doc.rust-lang.org/reference/conditional-compilation.html\
276     #the-cfg_attr-attribute>";
277
278 fn error_malformed_cfg_attr_missing(span: Span, parse_sess: &ParseSess) {
279     parse_sess
280         .span_diagnostic
281         .struct_span_err(span, "malformed `cfg_attr` attribute input")
282         .span_suggestion(
283             span,
284             "missing condition and attribute",
285             CFG_ATTR_GRAMMAR_HELP,
286             Applicability::HasPlaceholders,
287         )
288         .note(CFG_ATTR_NOTE_REF)
289         .emit();
290 }