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