2019-02-08 13:53:55 +00:00
|
|
|
//! The main parser interface.
|
2012-11-29 00:20:41 +00:00
|
|
|
|
2020-11-28 23:33:17 +00:00
|
|
|
#![feature(array_windows)]
|
2022-02-28 10:49:56 +00:00
|
|
|
#![feature(box_patterns)]
|
2019-10-15 20:48:13 +00:00
|
|
|
#![feature(crate_visibility_modifier)]
|
2021-08-16 15:29:49 +00:00
|
|
|
#![feature(if_let_guard)]
|
2022-02-28 10:49:56 +00:00
|
|
|
#![feature(let_chains)]
|
2022-02-15 04:58:25 +00:00
|
|
|
#![feature(let_else)]
|
2021-03-14 18:12:04 +00:00
|
|
|
#![recursion_limit = "256"]
|
2019-10-15 20:48:13 +00:00
|
|
|
|
2021-09-20 15:24:47 +00:00
|
|
|
#[macro_use]
|
|
|
|
extern crate tracing;
|
|
|
|
|
2020-04-27 17:56:11 +00:00
|
|
|
use rustc_ast as ast;
|
2020-11-28 23:33:17 +00:00
|
|
|
use rustc_ast::token::{self, Nonterminal, Token, TokenKind};
|
|
|
|
use rustc_ast::tokenstream::{self, AttributesData, CanSynthesizeMissingTokens, LazyTokenStream};
|
|
|
|
use rustc_ast::tokenstream::{AttrAnnotatedTokenStream, AttrAnnotatedTokenTree};
|
|
|
|
use rustc_ast::tokenstream::{Spacing, TokenStream};
|
2021-02-23 15:21:20 +00:00
|
|
|
use rustc_ast::AstLike;
|
2020-11-28 23:33:17 +00:00
|
|
|
use rustc_ast::Attribute;
|
2021-07-29 17:00:41 +00:00
|
|
|
use rustc_ast::{AttrItem, MetaItem};
|
2020-01-11 16:02:46 +00:00
|
|
|
use rustc_ast_pretty::pprust;
|
2020-01-11 14:03:15 +00:00
|
|
|
use rustc_data_structures::sync::Lrc;
|
2021-07-29 17:00:41 +00:00
|
|
|
use rustc_errors::{Applicability, Diagnostic, FatalError, Level, PResult};
|
2020-01-11 14:03:15 +00:00
|
|
|
use rustc_session::parse::ParseSess;
|
2020-11-23 06:43:55 +00:00
|
|
|
use rustc_span::{FileName, SourceFile, Span};
|
2019-02-06 17:33:01 +00:00
|
|
|
|
2020-03-08 21:10:37 +00:00
|
|
|
use std::path::Path;
|
2013-10-14 01:48:47 +00:00
|
|
|
use std::str;
|
2012-12-23 22:41:37 +00:00
|
|
|
|
2020-10-18 15:28:00 +00:00
|
|
|
pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
|
2015-03-28 21:58:51 +00:00
|
|
|
|
2015-01-06 17:24:46 +00:00
|
|
|
#[macro_use]
|
2013-01-09 03:37:25 +00:00
|
|
|
pub mod parser;
|
2019-12-22 22:42:04 +00:00
|
|
|
use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
|
2014-12-19 04:09:57 +00:00
|
|
|
pub mod lexer;
|
2019-10-11 19:00:09 +00:00
|
|
|
pub mod validate_attr;
|
2019-04-25 08:48:25 +00:00
|
|
|
|
2019-09-06 02:56:45 +00:00
|
|
|
// A bunch of utility functions of the form `parse_<thing>_from_<source>`
|
2013-02-11 21:36:24 +00:00
|
|
|
// where <thing> includes crate, expr, item, stmt, tts, and one that
|
|
|
|
// uses a HOF to parse anything, and <source> includes file and
|
2019-09-06 02:56:45 +00:00
|
|
|
// `source_str`.
|
2013-02-11 21:36:24 +00:00
|
|
|
|
2019-10-11 16:52:09 +00:00
|
|
|
/// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder.
|
|
|
|
macro_rules! panictry_buffer {
|
2019-12-22 22:42:04 +00:00
|
|
|
($handler:expr, $e:expr) => {{
|
2019-12-05 05:38:06 +00:00
|
|
|
use rustc_errors::FatalError;
|
2019-12-22 22:42:04 +00:00
|
|
|
use std::result::Result::{Err, Ok};
|
2019-10-11 16:52:09 +00:00
|
|
|
match $e {
|
|
|
|
Ok(e) => e,
|
|
|
|
Err(errs) => {
|
2022-03-20 17:26:09 +00:00
|
|
|
for mut e in errs {
|
|
|
|
$handler.emit_diagnostic(&mut e);
|
2019-10-11 16:52:09 +00:00
|
|
|
}
|
|
|
|
FatalError.raise()
|
|
|
|
}
|
|
|
|
}
|
2019-12-22 22:42:04 +00:00
|
|
|
}};
|
2019-10-11 16:52:09 +00:00
|
|
|
}
|
|
|
|
|
2016-10-27 06:36:56 +00:00
|
|
|
pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
|
2020-03-21 22:10:10 +00:00
|
|
|
let mut parser = new_parser_from_file(sess, input, None);
|
2016-02-13 17:05:16 +00:00
|
|
|
parser.parse_crate_mod()
|
2012-11-29 00:20:41 +00:00
|
|
|
}
|
|
|
|
|
2019-12-22 22:42:04 +00:00
|
|
|
pub fn parse_crate_attrs_from_file<'a>(
|
|
|
|
input: &Path,
|
|
|
|
sess: &'a ParseSess,
|
|
|
|
) -> PResult<'a, Vec<ast::Attribute>> {
|
2020-03-21 22:10:10 +00:00
|
|
|
let mut parser = new_parser_from_file(sess, input, None);
|
2016-02-13 17:05:16 +00:00
|
|
|
parser.parse_inner_attributes()
|
2013-12-19 20:23:39 +00:00
|
|
|
}
|
|
|
|
|
2019-12-22 22:42:04 +00:00
|
|
|
pub fn parse_crate_from_source_str(
|
|
|
|
name: FileName,
|
|
|
|
source: String,
|
|
|
|
sess: &ParseSess,
|
|
|
|
) -> PResult<'_, ast::Crate> {
|
2016-10-27 06:36:56 +00:00
|
|
|
new_parser_from_source_str(sess, name, source).parse_crate_mod()
|
2012-11-29 00:20:41 +00:00
|
|
|
}
|
|
|
|
|
2019-12-22 22:42:04 +00:00
|
|
|
pub fn parse_crate_attrs_from_source_str(
|
|
|
|
name: FileName,
|
|
|
|
source: String,
|
|
|
|
sess: &ParseSess,
|
|
|
|
) -> PResult<'_, Vec<ast::Attribute>> {
|
2016-10-27 06:36:56 +00:00
|
|
|
new_parser_from_source_str(sess, name, source).parse_inner_attributes()
|
2013-12-19 20:23:39 +00:00
|
|
|
}
|
|
|
|
|
2019-01-28 05:04:50 +00:00
|
|
|
pub fn parse_stream_from_source_str(
|
|
|
|
name: FileName,
|
|
|
|
source: String,
|
|
|
|
sess: &ParseSess,
|
|
|
|
override_span: Option<Span>,
|
2019-03-04 20:59:43 +00:00
|
|
|
) -> TokenStream {
|
2019-12-22 22:42:04 +00:00
|
|
|
let (stream, mut errors) =
|
|
|
|
source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
|
2019-10-29 00:44:20 +00:00
|
|
|
emit_unclosed_delims(&mut errors, &sess);
|
2019-03-04 20:59:43 +00:00
|
|
|
stream
|
2012-11-29 00:20:41 +00:00
|
|
|
}
|
|
|
|
|
2019-02-08 13:53:55 +00:00
|
|
|
/// Creates a new parser from a source string.
|
2019-01-28 05:04:50 +00:00
|
|
|
pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
|
2018-11-01 21:01:38 +00:00
|
|
|
panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
|
2012-11-29 00:20:41 +00:00
|
|
|
}
|
|
|
|
|
2019-02-08 13:53:55 +00:00
|
|
|
/// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
|
2018-11-01 16:57:29 +00:00
|
|
|
/// token stream.
|
2019-12-22 22:42:04 +00:00
|
|
|
pub fn maybe_new_parser_from_source_str(
|
|
|
|
sess: &ParseSess,
|
|
|
|
name: FileName,
|
|
|
|
source: String,
|
|
|
|
) -> Result<Parser<'_>, Vec<Diagnostic>> {
|
2020-03-08 12:36:20 +00:00
|
|
|
maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
|
2012-11-29 00:20:41 +00:00
|
|
|
}
|
|
|
|
|
2019-09-06 02:56:45 +00:00
|
|
|
/// Creates a new parser, handling errors as appropriate if the file doesn't exist.
|
2020-09-10 09:56:11 +00:00
|
|
|
/// If a span is given, that is used on an error as the source of the problem.
|
2020-03-21 22:10:10 +00:00
|
|
|
pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
|
|
|
|
source_file_to_parser(sess, file_to_source_file(sess, path, sp))
|
2012-11-29 00:20:41 +00:00
|
|
|
}
|
|
|
|
|
2019-09-06 02:56:45 +00:00
|
|
|
/// Given a `source_file` and config, returns a parser.
|
2019-02-06 17:33:01 +00:00
|
|
|
fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
|
2019-12-22 22:42:04 +00:00
|
|
|
panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
|
2013-04-23 17:57:41 +00:00
|
|
|
}
|
|
|
|
|
2019-09-06 02:56:45 +00:00
|
|
|
/// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
|
2018-11-01 16:57:29 +00:00
|
|
|
/// initial token stream.
|
2019-01-28 05:04:50 +00:00
|
|
|
fn maybe_source_file_to_parser(
|
|
|
|
sess: &ParseSess,
|
|
|
|
source_file: Lrc<SourceFile>,
|
|
|
|
) -> Result<Parser<'_>, Vec<Diagnostic>> {
|
2018-08-18 10:13:56 +00:00
|
|
|
let end_pos = source_file.end_pos;
|
2019-01-28 05:04:50 +00:00
|
|
|
let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
|
2019-05-22 00:47:23 +00:00
|
|
|
let mut parser = stream_to_parser(sess, stream, None);
|
2019-01-28 05:04:50 +00:00
|
|
|
parser.unclosed_delims = unclosed_delims;
|
2020-02-16 20:19:51 +00:00
|
|
|
if parser.token == token::Eof {
|
2021-04-18 12:27:04 +00:00
|
|
|
parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt(), None);
|
2015-07-06 02:13:19 +00:00
|
|
|
}
|
|
|
|
|
2018-11-01 16:57:29 +00:00
|
|
|
Ok(parser)
|
2013-04-23 17:57:41 +00:00
|
|
|
}
|
|
|
|
|
2019-09-06 02:56:45 +00:00
|
|
|
// Base abstractions
|
2013-04-23 17:57:41 +00:00
|
|
|
|
2018-12-09 21:53:00 +00:00
|
|
|
/// Given a session and a path and an optional span (for error reporting),
|
|
|
|
/// add the path to the session's source_map and return the new source_file or
|
|
|
|
/// error when a file can't be read.
|
2019-12-22 22:42:04 +00:00
|
|
|
fn try_file_to_source_file(
|
|
|
|
sess: &ParseSess,
|
|
|
|
path: &Path,
|
|
|
|
spanopt: Option<Span>,
|
|
|
|
) -> Result<Lrc<SourceFile>, Diagnostic> {
|
|
|
|
sess.source_map().load_file(path).map_err(|e| {
|
2018-12-09 21:53:00 +00:00
|
|
|
let msg = format!("couldn't read {}: {}", path.display(), e);
|
|
|
|
let mut diag = Diagnostic::new(Level::Fatal, &msg);
|
|
|
|
if let Some(sp) = spanopt {
|
|
|
|
diag.set_span(sp);
|
|
|
|
}
|
|
|
|
diag
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2013-04-23 17:57:41 +00:00
|
|
|
/// Given a session and a path and an optional span (for error reporting),
|
2019-09-06 02:56:45 +00:00
|
|
|
/// adds the path to the session's `source_map` and returns the new `source_file`.
|
2019-12-22 22:42:04 +00:00
|
|
|
fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
|
2018-12-09 21:53:00 +00:00
|
|
|
match try_file_to_source_file(sess, path, spanopt) {
|
2018-08-18 10:13:56 +00:00
|
|
|
Ok(source_file) => source_file,
|
2022-03-20 17:26:09 +00:00
|
|
|
Err(mut d) => {
|
|
|
|
sess.span_diagnostic.emit_diagnostic(&mut d);
|
2018-12-09 21:53:00 +00:00
|
|
|
FatalError.raise();
|
2014-05-16 17:45:16 +00:00
|
|
|
}
|
2012-11-29 00:20:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-06 02:56:45 +00:00
|
|
|
/// Given a `source_file`, produces a sequence of token trees.
|
2019-01-28 05:04:50 +00:00
|
|
|
pub fn source_file_to_stream(
|
|
|
|
sess: &ParseSess,
|
|
|
|
source_file: Lrc<SourceFile>,
|
|
|
|
override_span: Option<Span>,
|
|
|
|
) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
|
2018-11-01 21:01:38 +00:00
|
|
|
panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
|
2013-04-23 17:57:41 +00:00
|
|
|
}
|
|
|
|
|
2019-02-08 13:53:55 +00:00
|
|
|
/// Given a source file, produces a sequence of token trees. Returns any buffered errors from
|
2019-05-12 16:55:16 +00:00
|
|
|
/// parsing the token stream.
|
2019-01-28 05:04:50 +00:00
|
|
|
pub fn maybe_file_to_stream(
|
|
|
|
sess: &ParseSess,
|
|
|
|
source_file: Lrc<SourceFile>,
|
|
|
|
override_span: Option<Span>,
|
|
|
|
) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
|
2020-09-03 13:37:03 +00:00
|
|
|
let src = source_file.src.as_ref().unwrap_or_else(|| {
|
2021-04-19 22:27:02 +00:00
|
|
|
sess.span_diagnostic.bug(&format!(
|
|
|
|
"cannot lex `source_file` without source: {}",
|
2021-08-26 10:46:01 +00:00
|
|
|
sess.source_map().filename_for_diagnostics(&source_file.name)
|
2021-04-19 22:27:02 +00:00
|
|
|
));
|
2020-09-03 13:37:03 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
let (token_trees, unmatched_braces) =
|
|
|
|
lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
|
2018-11-01 16:57:29 +00:00
|
|
|
|
2019-05-12 16:55:16 +00:00
|
|
|
match token_trees {
|
|
|
|
Ok(stream) => Ok((stream, unmatched_braces)),
|
2018-11-01 16:57:29 +00:00
|
|
|
Err(err) => {
|
|
|
|
let mut buffer = Vec::with_capacity(1);
|
|
|
|
err.buffer(&mut buffer);
|
2019-02-05 09:35:25 +00:00
|
|
|
// Not using `emit_unclosed_delims` to use `db.buffer`
|
2019-05-12 16:55:16 +00:00
|
|
|
for unmatched in unmatched_braces {
|
2019-10-29 00:44:20 +00:00
|
|
|
if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
|
2019-10-26 01:30:02 +00:00
|
|
|
err.buffer(&mut buffer);
|
2019-01-28 05:04:50 +00:00
|
|
|
}
|
|
|
|
}
|
2018-11-01 16:57:29 +00:00
|
|
|
Err(buffer)
|
|
|
|
}
|
|
|
|
}
|
2013-04-23 17:57:41 +00:00
|
|
|
}
|
|
|
|
|
2019-09-06 02:56:45 +00:00
|
|
|
/// Given a stream and the `ParseSess`, produces a parser.
|
2019-05-22 00:47:23 +00:00
|
|
|
pub fn stream_to_parser<'a>(
|
|
|
|
sess: &'a ParseSess,
|
|
|
|
stream: TokenStream,
|
2019-05-22 05:17:53 +00:00
|
|
|
subparser_name: Option<&'static str>,
|
2019-05-22 00:47:23 +00:00
|
|
|
) -> Parser<'a> {
|
2020-03-08 12:36:20 +00:00
|
|
|
Parser::new(sess, stream, false, subparser_name)
|
2012-11-29 00:20:41 +00:00
|
|
|
}
|
2013-01-30 17:56:33 +00:00
|
|
|
|
2019-10-09 11:19:15 +00:00
|
|
|
/// Runs the given subparser `f` on the tokens of the given `attr`'s item.
|
2019-12-05 05:45:50 +00:00
|
|
|
pub fn parse_in<'a, T>(
|
2019-10-09 11:19:15 +00:00
|
|
|
sess: &'a ParseSess,
|
2019-12-05 05:45:50 +00:00
|
|
|
tts: TokenStream,
|
|
|
|
name: &'static str,
|
2019-10-09 11:19:15 +00:00
|
|
|
mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
|
|
|
|
) -> PResult<'a, T> {
|
2020-03-08 12:36:20 +00:00
|
|
|
let mut parser = Parser::new(sess, tts, false, Some(name));
|
2019-10-09 11:19:15 +00:00
|
|
|
let result = f(&mut parser)?;
|
|
|
|
if parser.token != token::Eof {
|
|
|
|
parser.unexpected()?;
|
|
|
|
}
|
|
|
|
Ok(result)
|
|
|
|
}
|
|
|
|
|
2019-10-09 00:34:22 +00:00
|
|
|
// NOTE(Centril): The following probably shouldn't be here but it acknowledges the
|
|
|
|
// fact that architecturally, we are using parsing (read on below to understand why).
|
|
|
|
|
2020-11-23 06:43:55 +00:00
|
|
|
pub fn nt_to_tokenstream(
|
|
|
|
nt: &Nonterminal,
|
|
|
|
sess: &ParseSess,
|
|
|
|
synthesize_tokens: CanSynthesizeMissingTokens,
|
|
|
|
) -> TokenStream {
|
2019-10-09 00:34:22 +00:00
|
|
|
// A `Nonterminal` is often a parsed AST item. At this point we now
|
|
|
|
// need to convert the parsed AST to an actual token stream, e.g.
|
|
|
|
// un-parse it basically.
|
|
|
|
//
|
|
|
|
// Unfortunately there's not really a great way to do that in a
|
|
|
|
// guaranteed lossless fashion right now. The fallback here is to just
|
|
|
|
// stringify the AST node and reparse it, but this loses all span
|
|
|
|
// information.
|
|
|
|
//
|
|
|
|
// As a result, some AST nodes are annotated with the token stream they
|
|
|
|
// came from. Here we attempt to extract these lossless token streams
|
|
|
|
// before we fall back to the stringification.
|
Rewrite `collect_tokens` implementations to use a flattened buffer
Instead of trying to collect tokens at each depth, we 'flatten' the
stream as we go allong, pushing open/close delimiters to our buffer
just like regular tokens. One capturing is complete, we reconstruct a
nested `TokenTree::Delimited` structure, producing a normal
`TokenStream`.
The reconstructed `TokenStream` is not created immediately - instead, it is
produced on-demand by a closure (wrapped in a new `LazyTokenStream` type). This
closure stores a clone of the original `TokenCursor`, plus a record of the
number of calls to `next()/next_desugared()`. This is sufficient to reconstruct
the tokenstream seen by the callback without storing any additional state. If
the tokenstream is never used (e.g. when a captured `macro_rules!` argument is
never passed to a proc macro), we never actually create a `TokenStream`.
This implementation has a number of advantages over the previous one:
* It is significantly simpler, with no edge cases around capturing the
start/end of a delimited group.
* It can be easily extended to allow replacing tokens an an arbitrary
'depth' by just using `Vec::splice` at the proper position. This is
important for PR #76130, which requires us to track information about
attributes along with tokens.
* The lazy approach to `TokenStream` construction allows us to easily
parse an AST struct, and then decide after the fact whether we need a
`TokenStream`. This will be useful when we start collecting tokens for
`Attribute` - we can discard the `LazyTokenStream` if the parsed
attribute doesn't need tokens (e.g. is a builtin attribute).
The performance impact seems to be neglibile (see
https://github.com/rust-lang/rust/pull/77250#issuecomment-703960604). There is a
small slowdown on a few benchmarks, but it only rises above 1% for incremental
builds, where it represents a larger fraction of the much smaller instruction
count. There a ~1% speedup on a few other incremental benchmarks - my guess is
that the speedups and slowdowns will usually cancel out in practice.
2020-09-27 01:56:29 +00:00
|
|
|
|
2020-10-30 21:40:41 +00:00
|
|
|
let convert_tokens =
|
2020-11-28 23:33:17 +00:00
|
|
|
|tokens: Option<&LazyTokenStream>| Some(tokens?.create_token_stream().to_tokenstream());
|
Rewrite `collect_tokens` implementations to use a flattened buffer
Instead of trying to collect tokens at each depth, we 'flatten' the
stream as we go allong, pushing open/close delimiters to our buffer
just like regular tokens. One capturing is complete, we reconstruct a
nested `TokenTree::Delimited` structure, producing a normal
`TokenStream`.
The reconstructed `TokenStream` is not created immediately - instead, it is
produced on-demand by a closure (wrapped in a new `LazyTokenStream` type). This
closure stores a clone of the original `TokenCursor`, plus a record of the
number of calls to `next()/next_desugared()`. This is sufficient to reconstruct
the tokenstream seen by the callback without storing any additional state. If
the tokenstream is never used (e.g. when a captured `macro_rules!` argument is
never passed to a proc macro), we never actually create a `TokenStream`.
This implementation has a number of advantages over the previous one:
* It is significantly simpler, with no edge cases around capturing the
start/end of a delimited group.
* It can be easily extended to allow replacing tokens an an arbitrary
'depth' by just using `Vec::splice` at the proper position. This is
important for PR #76130, which requires us to track information about
attributes along with tokens.
* The lazy approach to `TokenStream` construction allows us to easily
parse an AST struct, and then decide after the fact whether we need a
`TokenStream`. This will be useful when we start collecting tokens for
`Attribute` - we can discard the `LazyTokenStream` if the parsed
attribute doesn't need tokens (e.g. is a builtin attribute).
The performance impact seems to be neglibile (see
https://github.com/rust-lang/rust/pull/77250#issuecomment-703960604). There is a
small slowdown on a few benchmarks, but it only rises above 1% for incremental
builds, where it represents a larger fraction of the much smaller instruction
count. There a ~1% speedup on a few other incremental benchmarks - my guess is
that the speedups and slowdowns will usually cancel out in practice.
2020-09-27 01:56:29 +00:00
|
|
|
|
2019-10-09 00:34:22 +00:00
|
|
|
let tokens = match *nt {
|
2020-11-28 23:33:17 +00:00
|
|
|
Nonterminal::NtItem(ref item) => prepend_attrs(&item.attrs, item.tokens.as_ref()),
|
2020-11-17 19:27:44 +00:00
|
|
|
Nonterminal::NtBlock(ref block) => convert_tokens(block.tokens.as_ref()),
|
2021-08-16 15:29:49 +00:00
|
|
|
Nonterminal::NtStmt(ref stmt) if let ast::StmtKind::Empty = stmt.kind => {
|
|
|
|
let tokens = AttrAnnotatedTokenStream::new(vec![(
|
|
|
|
tokenstream::AttrAnnotatedTokenTree::Token(Token::new(
|
|
|
|
TokenKind::Semi,
|
|
|
|
stmt.span,
|
|
|
|
)),
|
|
|
|
Spacing::Alone,
|
|
|
|
)]);
|
|
|
|
prepend_attrs(&stmt.attrs(), Some(&LazyTokenStream::new(tokens)))
|
2021-01-07 16:43:21 +00:00
|
|
|
}
|
2021-08-16 15:29:49 +00:00
|
|
|
Nonterminal::NtStmt(ref stmt) => prepend_attrs(&stmt.attrs(), stmt.tokens()),
|
2020-11-17 19:27:44 +00:00
|
|
|
Nonterminal::NtPat(ref pat) => convert_tokens(pat.tokens.as_ref()),
|
|
|
|
Nonterminal::NtTy(ref ty) => convert_tokens(ty.tokens.as_ref()),
|
2019-10-09 00:34:22 +00:00
|
|
|
Nonterminal::NtIdent(ident, is_raw) => {
|
|
|
|
Some(tokenstream::TokenTree::token(token::Ident(ident.name, is_raw), ident.span).into())
|
|
|
|
}
|
|
|
|
Nonterminal::NtLifetime(ident) => {
|
|
|
|
Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into())
|
|
|
|
}
|
2020-11-17 19:27:44 +00:00
|
|
|
Nonterminal::NtMeta(ref attr) => convert_tokens(attr.tokens.as_ref()),
|
|
|
|
Nonterminal::NtPath(ref path) => convert_tokens(path.tokens.as_ref()),
|
|
|
|
Nonterminal::NtVis(ref vis) => convert_tokens(vis.tokens.as_ref()),
|
2019-12-22 22:42:04 +00:00
|
|
|
Nonterminal::NtTT(ref tt) => Some(tt.clone().into()),
|
2020-08-21 22:28:47 +00:00
|
|
|
Nonterminal::NtExpr(ref expr) | Nonterminal::NtLiteral(ref expr) => {
|
2020-11-28 23:33:17 +00:00
|
|
|
prepend_attrs(&expr.attrs, expr.tokens.as_ref())
|
2020-05-19 20:56:20 +00:00
|
|
|
}
|
2019-10-09 00:34:22 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
if let Some(tokens) = tokens {
|
2020-11-23 06:43:55 +00:00
|
|
|
return tokens;
|
|
|
|
} else if matches!(synthesize_tokens, CanSynthesizeMissingTokens::Yes) {
|
2021-01-07 13:43:22 +00:00
|
|
|
return fake_token_stream(sess, nt);
|
2020-11-23 06:43:55 +00:00
|
|
|
} else {
|
2020-11-28 23:33:17 +00:00
|
|
|
panic!(
|
|
|
|
"Missing tokens for nt {:?} at {:?}: {:?}",
|
|
|
|
nt,
|
|
|
|
nt.span(),
|
|
|
|
pprust::nonterminal_to_string(nt)
|
|
|
|
);
|
2020-08-01 11:59:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-28 23:33:17 +00:00
|
|
|
fn prepend_attrs(attrs: &[Attribute], tokens: Option<&LazyTokenStream>) -> Option<TokenStream> {
|
|
|
|
let tokens = tokens?;
|
|
|
|
if attrs.is_empty() {
|
|
|
|
return Some(tokens.create_token_stream().to_tokenstream());
|
|
|
|
}
|
|
|
|
let attr_data = AttributesData { attrs: attrs.to_vec().into(), tokens: tokens.clone() };
|
|
|
|
let wrapped = AttrAnnotatedTokenStream::new(vec![(
|
|
|
|
AttrAnnotatedTokenTree::Attributes(attr_data),
|
|
|
|
Spacing::Alone,
|
|
|
|
)]);
|
|
|
|
Some(wrapped.to_tokenstream())
|
|
|
|
}
|
|
|
|
|
2021-01-07 13:43:22 +00:00
|
|
|
pub fn fake_token_stream(sess: &ParseSess, nt: &Nonterminal) -> TokenStream {
|
2020-11-23 06:43:55 +00:00
|
|
|
let source = pprust::nonterminal_to_string(nt);
|
|
|
|
let filename = FileName::macro_expansion_source_code(&source);
|
2021-01-07 13:43:22 +00:00
|
|
|
parse_stream_from_source_str(filename, source, sess, Some(nt.span()))
|
2020-08-01 11:59:02 +00:00
|
|
|
}
|
2021-07-29 17:00:41 +00:00
|
|
|
|
2021-10-17 16:32:34 +00:00
|
|
|
pub fn fake_token_stream_for_crate(sess: &ParseSess, krate: &ast::Crate) -> TokenStream {
|
|
|
|
let source = pprust::crate_to_string_for_macros(krate);
|
|
|
|
let filename = FileName::macro_expansion_source_code(&source);
|
2022-03-03 23:45:25 +00:00
|
|
|
parse_stream_from_source_str(filename, source, sess, Some(krate.spans.inner_span))
|
2021-10-17 16:32:34 +00:00
|
|
|
}
|
|
|
|
|
2021-07-29 17:00:41 +00:00
|
|
|
pub fn parse_cfg_attr(
|
|
|
|
attr: &Attribute,
|
|
|
|
parse_sess: &ParseSess,
|
|
|
|
) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
|
|
|
|
match attr.get_normal_item().args {
|
|
|
|
ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
|
|
|
|
let msg = "wrong `cfg_attr` delimiters";
|
|
|
|
crate::validate_attr::check_meta_bad_delim(parse_sess, dspan, delim, msg);
|
|
|
|
match parse_in(parse_sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
|
|
|
|
Ok(r) => return Some(r),
|
|
|
|
Err(mut e) => {
|
|
|
|
e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
|
|
|
|
.note(CFG_ATTR_NOTE_REF)
|
|
|
|
.emit();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => error_malformed_cfg_attr_missing(attr.span, parse_sess),
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
|
|
|
|
const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
|
|
|
|
<https://doc.rust-lang.org/reference/conditional-compilation.html\
|
|
|
|
#the-cfg_attr-attribute>";
|
|
|
|
|
|
|
|
fn error_malformed_cfg_attr_missing(span: Span, parse_sess: &ParseSess) {
|
|
|
|
parse_sess
|
|
|
|
.span_diagnostic
|
|
|
|
.struct_span_err(span, "malformed `cfg_attr` attribute input")
|
|
|
|
.span_suggestion(
|
|
|
|
span,
|
|
|
|
"missing condition and attribute",
|
|
|
|
CFG_ATTR_GRAMMAR_HELP.to_string(),
|
|
|
|
Applicability::HasPlaceholders,
|
|
|
|
)
|
|
|
|
.note(CFG_ATTR_NOTE_REF)
|
|
|
|
.emit();
|
|
|
|
}
|