]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/lib.rs
Auto merge of #90716 - euclio:libloading, r=cjgillot
[rust.git] / compiler / rustc_parse / src / lib.rs
1 //! The main parser interface.
2
3 #![feature(array_windows)]
4 #![feature(crate_visibility_modifier)]
5 #![feature(if_let_guard)]
6 #![feature(box_patterns)]
7 #![recursion_limit = "256"]
8
9 #[macro_use]
10 extern crate tracing;
11
12 use rustc_ast as ast;
13 use rustc_ast::token::{self, Nonterminal, Token, TokenKind};
14 use rustc_ast::tokenstream::{self, AttributesData, CanSynthesizeMissingTokens, LazyTokenStream};
15 use rustc_ast::tokenstream::{AttrAnnotatedTokenStream, AttrAnnotatedTokenTree};
16 use rustc_ast::tokenstream::{Spacing, TokenStream};
17 use rustc_ast::AstLike;
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 use std::str;
28
29 pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
30
31 #[macro_use]
32 pub mod parser;
33 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
34 pub mod lexer;
35 pub mod validate_attr;
36
37 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
38 // where <thing> includes crate, expr, item, stmt, tts, and one that
39 // uses a HOF to parse anything, and <source> includes file and
40 // `source_str`.
41
42 /// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder.
43 macro_rules! panictry_buffer {
44     ($handler:expr, $e:expr) => {{
45         use rustc_errors::FatalError;
46         use std::result::Result::{Err, Ok};
47         match $e {
48             Ok(e) => e,
49             Err(errs) => {
50                 for e in errs {
51                     $handler.emit_diagnostic(&e);
52                 }
53                 FatalError.raise()
54             }
55         }
56     }};
57 }
58
59 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
60     let mut parser = new_parser_from_file(sess, input, None);
61     parser.parse_crate_mod()
62 }
63
64 pub fn parse_crate_attrs_from_file<'a>(
65     input: &Path,
66     sess: &'a ParseSess,
67 ) -> PResult<'a, Vec<ast::Attribute>> {
68     let mut parser = new_parser_from_file(sess, input, None);
69     parser.parse_inner_attributes()
70 }
71
72 pub fn parse_crate_from_source_str(
73     name: FileName,
74     source: String,
75     sess: &ParseSess,
76 ) -> PResult<'_, ast::Crate> {
77     new_parser_from_source_str(sess, name, source).parse_crate_mod()
78 }
79
80 pub fn parse_crate_attrs_from_source_str(
81     name: FileName,
82     source: String,
83     sess: &ParseSess,
84 ) -> PResult<'_, Vec<ast::Attribute>> {
85     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
86 }
87
88 pub fn parse_stream_from_source_str(
89     name: FileName,
90     source: String,
91     sess: &ParseSess,
92     override_span: Option<Span>,
93 ) -> TokenStream {
94     let (stream, mut errors) =
95         source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
96     emit_unclosed_delims(&mut errors, &sess);
97     stream
98 }
99
100 /// Creates a new parser from a source string.
101 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
102     panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
103 }
104
105 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
106 /// token stream.
107 pub fn maybe_new_parser_from_source_str(
108     sess: &ParseSess,
109     name: FileName,
110     source: String,
111 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
112     maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
113 }
114
115 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
116 /// If a span is given, that is used on an error as the source of the problem.
117 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
118     source_file_to_parser(sess, file_to_source_file(sess, path, sp))
119 }
120
121 /// Given a `source_file` and config, returns a parser.
122 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
123     panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
124 }
125
126 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
127 /// initial token stream.
128 fn maybe_source_file_to_parser(
129     sess: &ParseSess,
130     source_file: Lrc<SourceFile>,
131 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
132     let end_pos = source_file.end_pos;
133     let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
134     let mut parser = stream_to_parser(sess, stream, None);
135     parser.unclosed_delims = unclosed_delims;
136     if parser.token == token::Eof {
137         parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt(), None);
138     }
139
140     Ok(parser)
141 }
142
143 // Base abstractions
144
145 /// Given a session and a path and an optional span (for error reporting),
146 /// add the path to the session's source_map and return the new source_file or
147 /// error when a file can't be read.
148 fn try_file_to_source_file(
149     sess: &ParseSess,
150     path: &Path,
151     spanopt: Option<Span>,
152 ) -> Result<Lrc<SourceFile>, Diagnostic> {
153     sess.source_map().load_file(path).map_err(|e| {
154         let msg = format!("couldn't read {}: {}", path.display(), e);
155         let mut diag = Diagnostic::new(Level::Fatal, &msg);
156         if let Some(sp) = spanopt {
157             diag.set_span(sp);
158         }
159         diag
160     })
161 }
162
163 /// Given a session and a path and an optional span (for error reporting),
164 /// adds the path to the session's `source_map` and returns the new `source_file`.
165 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
166     match try_file_to_source_file(sess, path, spanopt) {
167         Ok(source_file) => source_file,
168         Err(d) => {
169             sess.span_diagnostic.emit_diagnostic(&d);
170             FatalError.raise();
171         }
172     }
173 }
174
175 /// Given a `source_file`, produces a sequence of token trees.
176 pub fn source_file_to_stream(
177     sess: &ParseSess,
178     source_file: Lrc<SourceFile>,
179     override_span: Option<Span>,
180 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
181     panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
182 }
183
184 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
185 /// parsing the token stream.
186 pub fn maybe_file_to_stream(
187     sess: &ParseSess,
188     source_file: Lrc<SourceFile>,
189     override_span: Option<Span>,
190 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
191     let src = source_file.src.as_ref().unwrap_or_else(|| {
192         sess.span_diagnostic.bug(&format!(
193             "cannot lex `source_file` without source: {}",
194             sess.source_map().filename_for_diagnostics(&source_file.name)
195         ));
196     });
197
198     let (token_trees, unmatched_braces) =
199         lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
200
201     match token_trees {
202         Ok(stream) => Ok((stream, unmatched_braces)),
203         Err(err) => {
204             let mut buffer = Vec::with_capacity(1);
205             err.buffer(&mut buffer);
206             // Not using `emit_unclosed_delims` to use `db.buffer`
207             for unmatched in unmatched_braces {
208                 if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
209                     err.buffer(&mut buffer);
210                 }
211             }
212             Err(buffer)
213         }
214     }
215 }
216
217 /// Given a stream and the `ParseSess`, produces a parser.
218 pub fn stream_to_parser<'a>(
219     sess: &'a ParseSess,
220     stream: TokenStream,
221     subparser_name: Option<&'static str>,
222 ) -> Parser<'a> {
223     Parser::new(sess, stream, false, subparser_name)
224 }
225
226 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
227 pub fn parse_in<'a, T>(
228     sess: &'a ParseSess,
229     tts: TokenStream,
230     name: &'static str,
231     mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
232 ) -> PResult<'a, T> {
233     let mut parser = Parser::new(sess, tts, false, Some(name));
234     let result = f(&mut parser)?;
235     if parser.token != token::Eof {
236         parser.unexpected()?;
237     }
238     Ok(result)
239 }
240
241 // NOTE(Centril): The following probably shouldn't be here but it acknowledges the
242 // fact that architecturally, we are using parsing (read on below to understand why).
243
244 pub fn nt_to_tokenstream(
245     nt: &Nonterminal,
246     sess: &ParseSess,
247     synthesize_tokens: CanSynthesizeMissingTokens,
248 ) -> TokenStream {
249     // A `Nonterminal` is often a parsed AST item. At this point we now
250     // need to convert the parsed AST to an actual token stream, e.g.
251     // un-parse it basically.
252     //
253     // Unfortunately there's not really a great way to do that in a
254     // guaranteed lossless fashion right now. The fallback here is to just
255     // stringify the AST node and reparse it, but this loses all span
256     // information.
257     //
258     // As a result, some AST nodes are annotated with the token stream they
259     // came from. Here we attempt to extract these lossless token streams
260     // before we fall back to the stringification.
261
262     let convert_tokens =
263         |tokens: Option<&LazyTokenStream>| Some(tokens?.create_token_stream().to_tokenstream());
264
265     let tokens = match *nt {
266         Nonterminal::NtItem(ref item) => prepend_attrs(&item.attrs, item.tokens.as_ref()),
267         Nonterminal::NtBlock(ref block) => convert_tokens(block.tokens.as_ref()),
268         Nonterminal::NtStmt(ref stmt) if let ast::StmtKind::Empty = stmt.kind => {
269             let tokens = AttrAnnotatedTokenStream::new(vec![(
270                 tokenstream::AttrAnnotatedTokenTree::Token(Token::new(
271                     TokenKind::Semi,
272                     stmt.span,
273                 )),
274                 Spacing::Alone,
275             )]);
276             prepend_attrs(&stmt.attrs(), Some(&LazyTokenStream::new(tokens)))
277         }
278         Nonterminal::NtStmt(ref stmt) => prepend_attrs(&stmt.attrs(), stmt.tokens()),
279         Nonterminal::NtPat(ref pat) => convert_tokens(pat.tokens.as_ref()),
280         Nonterminal::NtTy(ref ty) => convert_tokens(ty.tokens.as_ref()),
281         Nonterminal::NtIdent(ident, is_raw) => {
282             Some(tokenstream::TokenTree::token(token::Ident(ident.name, is_raw), ident.span).into())
283         }
284         Nonterminal::NtLifetime(ident) => {
285             Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into())
286         }
287         Nonterminal::NtMeta(ref attr) => convert_tokens(attr.tokens.as_ref()),
288         Nonterminal::NtPath(ref path) => convert_tokens(path.tokens.as_ref()),
289         Nonterminal::NtVis(ref vis) => convert_tokens(vis.tokens.as_ref()),
290         Nonterminal::NtTT(ref tt) => Some(tt.clone().into()),
291         Nonterminal::NtExpr(ref expr) | Nonterminal::NtLiteral(ref expr) => {
292             prepend_attrs(&expr.attrs, expr.tokens.as_ref())
293         }
294     };
295
296     if let Some(tokens) = tokens {
297         return tokens;
298     } else if matches!(synthesize_tokens, CanSynthesizeMissingTokens::Yes) {
299         return fake_token_stream(sess, nt);
300     } else {
301         panic!(
302             "Missing tokens for nt {:?} at {:?}: {:?}",
303             nt,
304             nt.span(),
305             pprust::nonterminal_to_string(nt)
306         );
307     }
308 }
309
310 fn prepend_attrs(attrs: &[Attribute], tokens: Option<&LazyTokenStream>) -> Option<TokenStream> {
311     let tokens = tokens?;
312     if attrs.is_empty() {
313         return Some(tokens.create_token_stream().to_tokenstream());
314     }
315     let attr_data = AttributesData { attrs: attrs.to_vec().into(), tokens: tokens.clone() };
316     let wrapped = AttrAnnotatedTokenStream::new(vec![(
317         AttrAnnotatedTokenTree::Attributes(attr_data),
318         Spacing::Alone,
319     )]);
320     Some(wrapped.to_tokenstream())
321 }
322
323 pub fn fake_token_stream(sess: &ParseSess, nt: &Nonterminal) -> TokenStream {
324     let source = pprust::nonterminal_to_string(nt);
325     let filename = FileName::macro_expansion_source_code(&source);
326     parse_stream_from_source_str(filename, source, sess, Some(nt.span()))
327 }
328
329 pub fn fake_token_stream_for_crate(sess: &ParseSess, krate: &ast::Crate) -> TokenStream {
330     let source = pprust::crate_to_string_for_macros(krate);
331     let filename = FileName::macro_expansion_source_code(&source);
332     parse_stream_from_source_str(filename, source, sess, Some(krate.span))
333 }
334
335 pub fn parse_cfg_attr(
336     attr: &Attribute,
337     parse_sess: &ParseSess,
338 ) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
339     match attr.get_normal_item().args {
340         ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
341             let msg = "wrong `cfg_attr` delimiters";
342             crate::validate_attr::check_meta_bad_delim(parse_sess, dspan, delim, msg);
343             match parse_in(parse_sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
344                 Ok(r) => return Some(r),
345                 Err(mut e) => {
346                     e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
347                         .note(CFG_ATTR_NOTE_REF)
348                         .emit();
349                 }
350             }
351         }
352         _ => error_malformed_cfg_attr_missing(attr.span, parse_sess),
353     }
354     None
355 }
356
357 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
358 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
359     <https://doc.rust-lang.org/reference/conditional-compilation.html\
360     #the-cfg_attr-attribute>";
361
362 fn error_malformed_cfg_attr_missing(span: Span, parse_sess: &ParseSess) {
363     parse_sess
364         .span_diagnostic
365         .struct_span_err(span, "malformed `cfg_attr` attribute input")
366         .span_suggestion(
367             span,
368             "missing condition and attribute",
369             CFG_ATTR_GRAMMAR_HELP.to_string(),
370             Applicability::HasPlaceholders,
371         )
372         .note(CFG_ATTR_NOTE_REF)
373         .emit();
374 }