]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/lib.rs
Rollup merge of #101166 - GuillaumeGomez:error-index-mdbook, r=notriddle
[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_chains)]
7 #![feature(let_else)]
8 #![feature(never_type)]
9 #![feature(rustc_attrs)]
10 #![recursion_limit = "256"]
11
12 #[macro_use]
13 extern crate tracing;
14
15 use rustc_ast as ast;
16 use rustc_ast::token;
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};
25
26 use std::path::Path;
27
28 pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
29
30 #[macro_use]
31 pub mod parser;
32 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
33 pub mod lexer;
34 pub mod validate_attr;
35
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
39 // `source_str`.
40
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};
46         match $e {
47             Ok(e) => e,
48             Err(errs) => {
49                 for mut e in errs {
50                     $handler.emit_diagnostic(&mut e);
51                 }
52                 FatalError.raise()
53             }
54         }
55     }};
56 }
57
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()
61 }
62
63 pub fn parse_crate_attrs_from_file<'a>(
64     input: &Path,
65     sess: &'a ParseSess,
66 ) -> PResult<'a, ast::AttrVec> {
67     let mut parser = new_parser_from_file(sess, input, None);
68     parser.parse_inner_attributes()
69 }
70
71 pub fn parse_crate_from_source_str(
72     name: FileName,
73     source: String,
74     sess: &ParseSess,
75 ) -> PResult<'_, ast::Crate> {
76     new_parser_from_source_str(sess, name, source).parse_crate_mod()
77 }
78
79 pub fn parse_crate_attrs_from_source_str(
80     name: FileName,
81     source: String,
82     sess: &ParseSess,
83 ) -> PResult<'_, ast::AttrVec> {
84     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
85 }
86
87 pub fn parse_stream_from_source_str(
88     name: FileName,
89     source: String,
90     sess: &ParseSess,
91     override_span: Option<Span>,
92 ) -> TokenStream {
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);
96     stream
97 }
98
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))
102 }
103
104 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
105 /// token stream.
106 pub fn maybe_new_parser_from_source_str(
107     sess: &ParseSess,
108     name: FileName,
109     source: String,
110 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
111     maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
112 }
113
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))
118 }
119
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))
123 }
124
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(
128     sess: &ParseSess,
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);
137     }
138
139     Ok(parser)
140 }
141
142 // Base abstractions
143
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(
148     sess: &ParseSess,
149     path: &Path,
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 {
156             diag.set_span(sp);
157         }
158         diag
159     })
160 }
161
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,
167         Err(mut d) => {
168             sess.span_diagnostic.emit_diagnostic(&mut d);
169             FatalError.raise();
170         }
171     }
172 }
173
174 /// Given a `source_file`, produces a sequence of token trees.
175 pub fn source_file_to_stream(
176     sess: &ParseSess,
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))
181 }
182
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(
186     sess: &ParseSess,
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)
194         ));
195     });
196
197     let (token_trees, unmatched_braces) =
198         lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
199
200     match token_trees {
201         Ok(stream) => Ok((stream, unmatched_braces)),
202         Err(err) => {
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);
209                 }
210             }
211             Err(buffer)
212         }
213     }
214 }
215
216 /// Given a stream and the `ParseSess`, produces a parser.
217 pub fn stream_to_parser<'a>(
218     sess: &'a ParseSess,
219     stream: TokenStream,
220     subparser_name: Option<&'static str>,
221 ) -> Parser<'a> {
222     Parser::new(sess, stream, false, subparser_name)
223 }
224
225 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
226 pub fn parse_in<'a, T>(
227     sess: &'a ParseSess,
228     tts: TokenStream,
229     name: &'static str,
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()?;
236     }
237     Ok(result)
238 }
239
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))
244 }
245
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))
250 }
251
252 pub fn parse_cfg_attr(
253     attr: &Attribute,
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),
262                 Err(mut e) => {
263                     e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
264                         .note(CFG_ATTR_NOTE_REF)
265                         .emit();
266                 }
267             }
268         }
269         _ => error_malformed_cfg_attr_missing(attr.span, parse_sess),
270     }
271     None
272 }
273
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>";
278
279 fn error_malformed_cfg_attr_missing(span: Span, parse_sess: &ParseSess) {
280     parse_sess
281         .span_diagnostic
282         .struct_span_err(span, "malformed `cfg_attr` attribute input")
283         .span_suggestion(
284             span,
285             "missing condition and attribute",
286             CFG_ATTR_GRAMMAR_HELP,
287             Applicability::HasPlaceholders,
288         )
289         .note(CFG_ATTR_NOTE_REF)
290         .emit();
291 }