]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/lib.rs
Auto merge of #77853 - ijackson:slice-strip-stab, r=Amanieu
[rust.git] / compiler / rustc_parse / src / lib.rs
1 //! The main parser interface.
2
3 #![feature(crate_visibility_modifier)]
4 #![feature(bindings_after_at)]
5 #![feature(iter_order_by)]
6 #![feature(or_patterns)]
7
8 use rustc_ast as ast;
9 use rustc_ast::attr::HasAttrs;
10 use rustc_ast::token::{self, Nonterminal};
11 use rustc_ast::tokenstream::{self, CanSynthesizeMissingTokens, LazyTokenStream, TokenStream};
12 use rustc_ast_pretty::pprust;
13 use rustc_data_structures::sync::Lrc;
14 use rustc_errors::{Diagnostic, FatalError, Level, PResult};
15 use rustc_session::parse::ParseSess;
16 use rustc_span::{FileName, SourceFile, Span};
17
18 use std::path::Path;
19 use std::str;
20
21 use tracing::debug;
22
23 pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
24
25 #[macro_use]
26 pub mod parser;
27 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
28 pub mod lexer;
29 pub mod validate_attr;
30
31 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
32 // where <thing> includes crate, expr, item, stmt, tts, and one that
33 // uses a HOF to parse anything, and <source> includes file and
34 // `source_str`.
35
36 /// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder.
37 macro_rules! panictry_buffer {
38     ($handler:expr, $e:expr) => {{
39         use rustc_errors::FatalError;
40         use std::result::Result::{Err, Ok};
41         match $e {
42             Ok(e) => e,
43             Err(errs) => {
44                 for e in errs {
45                     $handler.emit_diagnostic(&e);
46                 }
47                 FatalError.raise()
48             }
49         }
50     }};
51 }
52
53 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
54     let mut parser = new_parser_from_file(sess, input, None);
55     parser.parse_crate_mod()
56 }
57
58 pub fn parse_crate_attrs_from_file<'a>(
59     input: &Path,
60     sess: &'a ParseSess,
61 ) -> PResult<'a, Vec<ast::Attribute>> {
62     let mut parser = new_parser_from_file(sess, input, None);
63     parser.parse_inner_attributes()
64 }
65
66 pub fn parse_crate_from_source_str(
67     name: FileName,
68     source: String,
69     sess: &ParseSess,
70 ) -> PResult<'_, ast::Crate> {
71     new_parser_from_source_str(sess, name, source).parse_crate_mod()
72 }
73
74 pub fn parse_crate_attrs_from_source_str(
75     name: FileName,
76     source: String,
77     sess: &ParseSess,
78 ) -> PResult<'_, Vec<ast::Attribute>> {
79     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
80 }
81
82 pub fn parse_stream_from_source_str(
83     name: FileName,
84     source: String,
85     sess: &ParseSess,
86     override_span: Option<Span>,
87 ) -> TokenStream {
88     let (stream, mut errors) =
89         source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
90     emit_unclosed_delims(&mut errors, &sess);
91     stream
92 }
93
94 /// Creates a new parser from a source string.
95 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
96     panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
97 }
98
99 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
100 /// token stream.
101 pub fn maybe_new_parser_from_source_str(
102     sess: &ParseSess,
103     name: FileName,
104     source: String,
105 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
106     maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
107 }
108
109 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
110 /// If a span is given, that is used on an error as the source of the problem.
111 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
112     source_file_to_parser(sess, file_to_source_file(sess, path, sp))
113 }
114
115 /// Given a `source_file` and config, returns a parser.
116 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
117     panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
118 }
119
120 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
121 /// initial token stream.
122 fn maybe_source_file_to_parser(
123     sess: &ParseSess,
124     source_file: Lrc<SourceFile>,
125 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
126     let end_pos = source_file.end_pos;
127     let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
128     let mut parser = stream_to_parser(sess, stream, None);
129     parser.unclosed_delims = unclosed_delims;
130     if parser.token == token::Eof {
131         parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
132     }
133
134     Ok(parser)
135 }
136
137 // Base abstractions
138
139 /// Given a session and a path and an optional span (for error reporting),
140 /// add the path to the session's source_map and return the new source_file or
141 /// error when a file can't be read.
142 fn try_file_to_source_file(
143     sess: &ParseSess,
144     path: &Path,
145     spanopt: Option<Span>,
146 ) -> Result<Lrc<SourceFile>, Diagnostic> {
147     sess.source_map().load_file(path).map_err(|e| {
148         let msg = format!("couldn't read {}: {}", path.display(), e);
149         let mut diag = Diagnostic::new(Level::Fatal, &msg);
150         if let Some(sp) = spanopt {
151             diag.set_span(sp);
152         }
153         diag
154     })
155 }
156
157 /// Given a session and a path and an optional span (for error reporting),
158 /// adds the path to the session's `source_map` and returns the new `source_file`.
159 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
160     match try_file_to_source_file(sess, path, spanopt) {
161         Ok(source_file) => source_file,
162         Err(d) => {
163             sess.span_diagnostic.emit_diagnostic(&d);
164             FatalError.raise();
165         }
166     }
167 }
168
169 /// Given a `source_file`, produces a sequence of token trees.
170 pub fn source_file_to_stream(
171     sess: &ParseSess,
172     source_file: Lrc<SourceFile>,
173     override_span: Option<Span>,
174 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
175     panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
176 }
177
178 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
179 /// parsing the token stream.
180 pub fn maybe_file_to_stream(
181     sess: &ParseSess,
182     source_file: Lrc<SourceFile>,
183     override_span: Option<Span>,
184 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
185     let src = source_file.src.as_ref().unwrap_or_else(|| {
186         sess.span_diagnostic
187             .bug(&format!("cannot lex `source_file` without source: {}", source_file.name));
188     });
189
190     let (token_trees, unmatched_braces) =
191         lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
192
193     match token_trees {
194         Ok(stream) => Ok((stream, unmatched_braces)),
195         Err(err) => {
196             let mut buffer = Vec::with_capacity(1);
197             err.buffer(&mut buffer);
198             // Not using `emit_unclosed_delims` to use `db.buffer`
199             for unmatched in unmatched_braces {
200                 if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
201                     err.buffer(&mut buffer);
202                 }
203             }
204             Err(buffer)
205         }
206     }
207 }
208
209 /// Given a stream and the `ParseSess`, produces a parser.
210 pub fn stream_to_parser<'a>(
211     sess: &'a ParseSess,
212     stream: TokenStream,
213     subparser_name: Option<&'static str>,
214 ) -> Parser<'a> {
215     Parser::new(sess, stream, false, subparser_name)
216 }
217
218 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
219 pub fn parse_in<'a, T>(
220     sess: &'a ParseSess,
221     tts: TokenStream,
222     name: &'static str,
223     mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
224 ) -> PResult<'a, T> {
225     let mut parser = Parser::new(sess, tts, false, Some(name));
226     let result = f(&mut parser)?;
227     if parser.token != token::Eof {
228         parser.unexpected()?;
229     }
230     Ok(result)
231 }
232
233 // NOTE(Centril): The following probably shouldn't be here but it acknowledges the
234 // fact that architecturally, we are using parsing (read on below to understand why).
235
236 pub fn nt_to_tokenstream(
237     nt: &Nonterminal,
238     sess: &ParseSess,
239     span: Span,
240     synthesize_tokens: CanSynthesizeMissingTokens,
241 ) -> TokenStream {
242     // A `Nonterminal` is often a parsed AST item. At this point we now
243     // need to convert the parsed AST to an actual token stream, e.g.
244     // un-parse it basically.
245     //
246     // Unfortunately there's not really a great way to do that in a
247     // guaranteed lossless fashion right now. The fallback here is to just
248     // stringify the AST node and reparse it, but this loses all span
249     // information.
250     //
251     // As a result, some AST nodes are annotated with the token stream they
252     // came from. Here we attempt to extract these lossless token streams
253     // before we fall back to the stringification.
254
255     let convert_tokens =
256         |tokens: Option<&LazyTokenStream>| tokens.as_ref().map(|t| t.create_token_stream());
257
258     let tokens = match *nt {
259         Nonterminal::NtItem(ref item) => {
260             prepend_attrs(sess, &item.attrs, nt, span, item.tokens.as_ref())
261         }
262         Nonterminal::NtBlock(ref block) => convert_tokens(block.tokens.as_ref()),
263         Nonterminal::NtStmt(ref stmt) => prepend_attrs(sess, stmt.attrs(), nt, span, stmt.tokens()),
264         Nonterminal::NtPat(ref pat) => convert_tokens(pat.tokens.as_ref()),
265         Nonterminal::NtTy(ref ty) => convert_tokens(ty.tokens.as_ref()),
266         Nonterminal::NtIdent(ident, is_raw) => {
267             Some(tokenstream::TokenTree::token(token::Ident(ident.name, is_raw), ident.span).into())
268         }
269         Nonterminal::NtLifetime(ident) => {
270             Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into())
271         }
272         Nonterminal::NtMeta(ref attr) => convert_tokens(attr.tokens.as_ref()),
273         Nonterminal::NtPath(ref path) => convert_tokens(path.tokens.as_ref()),
274         Nonterminal::NtVis(ref vis) => convert_tokens(vis.tokens.as_ref()),
275         Nonterminal::NtTT(ref tt) => Some(tt.clone().into()),
276         Nonterminal::NtExpr(ref expr) | Nonterminal::NtLiteral(ref expr) => {
277             if expr.tokens.is_none() {
278                 debug!("missing tokens for expr {:?}", expr);
279             }
280             prepend_attrs(sess, &expr.attrs, nt, span, expr.tokens.as_ref())
281         }
282     };
283
284     if let Some(tokens) = tokens {
285         return tokens;
286     } else if matches!(synthesize_tokens, CanSynthesizeMissingTokens::Yes) {
287         return fake_token_stream(sess, nt, span);
288     } else {
289         let pretty = rustc_ast_pretty::pprust::nonterminal_to_string_no_extra_parens(&nt);
290         panic!("Missing tokens at {:?} for nt {:?}", span, pretty);
291     }
292 }
293
294 pub fn fake_token_stream(sess: &ParseSess, nt: &Nonterminal, span: Span) -> TokenStream {
295     let source = pprust::nonterminal_to_string(nt);
296     let filename = FileName::macro_expansion_source_code(&source);
297     parse_stream_from_source_str(filename, source, sess, Some(span))
298 }
299
300 fn prepend_attrs(
301     sess: &ParseSess,
302     attrs: &[ast::Attribute],
303     nt: &Nonterminal,
304     span: Span,
305     tokens: Option<&tokenstream::LazyTokenStream>,
306 ) -> Option<tokenstream::TokenStream> {
307     if attrs.is_empty() {
308         return Some(tokens?.create_token_stream());
309     }
310     let mut builder = tokenstream::TokenStreamBuilder::new();
311     for attr in attrs {
312         // FIXME: Correctly handle tokens for inner attributes.
313         // For now, we fall back to reparsing the original AST node
314         if attr.style == ast::AttrStyle::Inner {
315             return Some(fake_token_stream(sess, nt, span));
316         }
317         builder.push(attr.tokens());
318     }
319     builder.push(tokens?.create_token_stream());
320     Some(builder.build())
321 }