Skip to content

Commit d72a442

Browse files
committed
Remove NtItem and NtStmt.
This involves replacing `nt_pretty_printing_compatibility_hack` with `stream_pretty_printing_compatibility_hack`. The handling of statements in `transcribe` is slightly different to other nonterminal kinds, due to the lack of `from_ast` implementation for empty statements. Notable test changes: - `tests/ui/proc-macro/expand-to-derive.rs`: the diff looks large but the only difference is the insertion of a single invisible-delimited group around a metavar.
1 parent f886199 commit d72a442

File tree

18 files changed

+193
-139
lines changed

18 files changed

+193
-139
lines changed

compiler/rustc_ast/src/ast_traits.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,6 @@ impl HasTokens for Attribute {
199199
impl HasTokens for Nonterminal {
200200
fn tokens(&self) -> Option<&LazyAttrTokenStream> {
201201
match self {
202-
Nonterminal::NtItem(item) => item.tokens(),
203-
Nonterminal::NtStmt(stmt) => stmt.tokens(),
204202
Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => expr.tokens(),
205203
Nonterminal::NtMeta(attr_item) => attr_item.tokens(),
206204
Nonterminal::NtPath(path) => path.tokens(),
@@ -209,8 +207,6 @@ impl HasTokens for Nonterminal {
209207
}
210208
fn tokens_mut(&mut self) -> Option<&mut Option<LazyAttrTokenStream>> {
211209
match self {
212-
Nonterminal::NtItem(item) => item.tokens_mut(),
213-
Nonterminal::NtStmt(stmt) => stmt.tokens_mut(),
214210
Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => expr.tokens_mut(),
215211
Nonterminal::NtMeta(attr_item) => attr_item.tokens_mut(),
216212
Nonterminal::NtPath(path) => path.tokens_mut(),

compiler/rustc_ast/src/mut_visit.rs

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -796,19 +796,7 @@ pub fn visit_token<T: MutVisitor>(vis: &mut T, t: &mut Token) {
796796
// multiple items there....
797797
fn visit_nonterminal<T: MutVisitor>(vis: &mut T, nt: &mut token::Nonterminal) {
798798
match nt {
799-
token::NtItem(item) => visit_clobber(item, |item| {
800-
// This is probably okay, because the only visitors likely to
801-
// peek inside interpolated nodes will be renamings/markings,
802-
// which map single items to single items.
803-
vis.flat_map_item(item).expect_one("expected visitor to produce exactly one item")
804-
}),
805799
token::NtBlock(block) => vis.visit_block(block),
806-
token::NtStmt(stmt) => visit_clobber(stmt, |stmt| {
807-
// See reasoning above.
808-
stmt.map(|stmt| {
809-
vis.flat_map_stmt(stmt).expect_one("expected visitor to produce exactly one item")
810-
})
811-
}),
812800
token::NtExpr(expr) => vis.visit_expr(expr),
813801
token::NtLiteral(expr) => vis.visit_expr(expr),
814802
token::NtMeta(item) => {

compiler/rustc_ast/src/token.rs

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1063,9 +1063,7 @@ pub enum NtExprKind {
10631063
#[derive(Clone, Encodable, Decodable)]
10641064
/// For interpolation during macro expansion.
10651065
pub enum Nonterminal {
1066-
NtItem(P<ast::Item>),
10671066
NtBlock(P<ast::Block>),
1068-
NtStmt(P<ast::Stmt>),
10691067
NtExpr(P<ast::Expr>),
10701068
NtLiteral(P<ast::Expr>),
10711069
/// Stuff inside brackets for attributes
@@ -1159,9 +1157,7 @@ impl fmt::Display for NonterminalKind {
11591157
impl Nonterminal {
11601158
pub fn use_span(&self) -> Span {
11611159
match self {
1162-
NtItem(item) => item.span,
11631160
NtBlock(block) => block.span,
1164-
NtStmt(stmt) => stmt.span,
11651161
NtExpr(expr) | NtLiteral(expr) => expr.span,
11661162
NtMeta(attr_item) => attr_item.span(),
11671163
NtPath(path) => path.span,
@@ -1170,9 +1166,7 @@ impl Nonterminal {
11701166

11711167
pub fn descr(&self) -> &'static str {
11721168
match self {
1173-
NtItem(..) => "item",
11741169
NtBlock(..) => "block",
1175-
NtStmt(..) => "statement",
11761170
NtExpr(..) => "expression",
11771171
NtLiteral(..) => "literal",
11781172
NtMeta(..) => "attribute",
@@ -1194,9 +1188,7 @@ impl PartialEq for Nonterminal {
11941188
impl fmt::Debug for Nonterminal {
11951189
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11961190
match *self {
1197-
NtItem(..) => f.pad("NtItem(..)"),
11981191
NtBlock(..) => f.pad("NtBlock(..)"),
1199-
NtStmt(..) => f.pad("NtStmt(..)"),
12001192
NtExpr(..) => f.pad("NtExpr(..)"),
12011193
NtLiteral(..) => f.pad("NtLiteral(..)"),
12021194
NtMeta(..) => f.pad("NtMeta(..)"),

compiler/rustc_ast/src/tokenstream.rs

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use rustc_macros::{Decodable, Encodable, HashStable_Generic};
2222
use rustc_serialize::{Decodable, Encodable};
2323
use rustc_span::{DUMMY_SP, Span, SpanDecoder, SpanEncoder, Symbol, sym};
2424

25-
use crate::ast::{AttrStyle, StmtKind};
25+
use crate::ast::AttrStyle;
2626
use crate::ast_traits::{HasAttrs, HasTokens};
2727
use crate::token::{self, Delimiter, InvisibleOrigin, Nonterminal, Token, TokenKind};
2828
use crate::{AttrVec, Attribute};
@@ -461,13 +461,7 @@ impl TokenStream {
461461

462462
pub fn from_nonterminal_ast(nt: &Nonterminal) -> TokenStream {
463463
match nt {
464-
Nonterminal::NtItem(item) => TokenStream::from_ast(item),
465464
Nonterminal::NtBlock(block) => TokenStream::from_ast(block),
466-
Nonterminal::NtStmt(stmt) if let StmtKind::Empty = stmt.kind => {
467-
// FIXME: Properly collect tokens for empty statements.
468-
TokenStream::token_alone(token::Semi, stmt.span)
469-
}
470-
Nonterminal::NtStmt(stmt) => TokenStream::from_ast(stmt),
471465
Nonterminal::NtMeta(attr) => TokenStream::from_ast(attr),
472466
Nonterminal::NtPath(path) => TokenStream::from_ast(path),
473467
Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => TokenStream::from_ast(expr),

compiler/rustc_builtin_macros/src/cfg_eval.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ impl CfgEval<'_> {
164164
},
165165
Annotatable::Stmt(_) => |parser| {
166166
Ok(Annotatable::Stmt(P(parser
167-
.parse_stmt_without_recovery(false, ForceCollect::Yes)?
167+
.parse_stmt_without_recovery(false, ForceCollect::Yes, false)?
168168
.unwrap())))
169169
},
170170
Annotatable::Expr(_) => {

compiler/rustc_expand/src/base.rs

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::rc::Rc;
66

77
use rustc_ast::attr::MarkedAttrs;
88
use rustc_ast::ptr::P;
9-
use rustc_ast::token::Nonterminal;
9+
use rustc_ast::token::MetaVarKind;
1010
use rustc_ast::tokenstream::TokenStream;
1111
use rustc_ast::visit::{AssocCtxt, Visitor};
1212
use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind};
@@ -17,7 +17,7 @@ use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, PResult};
1717
use rustc_feature::Features;
1818
use rustc_lint_defs::{BufferedEarlyLint, RegisteredTools};
1919
use rustc_parse::MACRO_ARGUMENTS;
20-
use rustc_parse::parser::Parser;
20+
use rustc_parse::parser::{ForceCollect, Parser};
2121
use rustc_session::config::CollapseMacroDebuginfo;
2222
use rustc_session::parse::ParseSess;
2323
use rustc_session::{Limit, Session};
@@ -1382,13 +1382,13 @@ pub fn parse_macro_name_and_helper_attrs(
13821382
/// If this item looks like a specific enums from `rental`, emit a fatal error.
13831383
/// See #73345 and #83125 for more details.
13841384
/// FIXME(#73933): Remove this eventually.
1385-
fn pretty_printing_compatibility_hack(item: &Item, sess: &Session) {
1385+
fn pretty_printing_compatibility_hack(item: &Item, psess: &ParseSess) {
13861386
let name = item.ident.name;
13871387
if name == sym::ProceduralMasqueradeDummyType
13881388
&& let ast::ItemKind::Enum(enum_def, _) = &item.kind
13891389
&& let [variant] = &*enum_def.variants
13901390
&& variant.ident.name == sym::Input
1391-
&& let FileName::Real(real) = sess.source_map().span_to_filename(item.ident.span)
1391+
&& let FileName::Real(real) = psess.source_map().span_to_filename(item.ident.span)
13921392
&& let Some(c) = real
13931393
.local_path()
13941394
.unwrap_or(Path::new(""))
@@ -1406,15 +1406,15 @@ fn pretty_printing_compatibility_hack(item: &Item, sess: &Session) {
14061406
};
14071407

14081408
if crate_matches {
1409-
sess.dcx().emit_fatal(errors::ProcMacroBackCompat {
1409+
psess.dcx().emit_fatal(errors::ProcMacroBackCompat {
14101410
crate_name: "rental".to_string(),
14111411
fixed_version: "0.5.6".to_string(),
14121412
});
14131413
}
14141414
}
14151415
}
14161416

1417-
pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, sess: &Session) {
1417+
pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, psess: &ParseSess) {
14181418
let item = match ann {
14191419
Annotatable::Item(item) => item,
14201420
Annotatable::Stmt(stmt) => match &stmt.kind {
@@ -1423,17 +1423,36 @@ pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, sess: &S
14231423
},
14241424
_ => return,
14251425
};
1426-
pretty_printing_compatibility_hack(item, sess)
1426+
pretty_printing_compatibility_hack(item, psess)
14271427
}
14281428

1429-
pub(crate) fn nt_pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &Session) {
1430-
let item = match nt {
1431-
Nonterminal::NtItem(item) => item,
1432-
Nonterminal::NtStmt(stmt) => match &stmt.kind {
1433-
ast::StmtKind::Item(item) => item,
1434-
_ => return,
1435-
},
1429+
pub(crate) fn stream_pretty_printing_compatibility_hack(
1430+
kind: MetaVarKind,
1431+
stream: &TokenStream,
1432+
psess: &ParseSess,
1433+
) {
1434+
let item = match kind {
1435+
MetaVarKind::Item => {
1436+
let mut parser = Parser::new(psess, stream.clone(), None);
1437+
// No need to collect tokens for this simple check.
1438+
parser
1439+
.parse_item(ForceCollect::No)
1440+
.expect("failed to reparse item")
1441+
.expect("an actual item")
1442+
}
1443+
MetaVarKind::Stmt => {
1444+
let mut parser = Parser::new(psess, stream.clone(), None);
1445+
// No need to collect tokens for this simple check.
1446+
let stmt = parser
1447+
.parse_stmt(ForceCollect::No)
1448+
.expect("failed to reparse")
1449+
.expect("an actual stmt");
1450+
match &stmt.kind {
1451+
ast::StmtKind::Item(item) => item.clone(),
1452+
_ => return,
1453+
}
1454+
}
14361455
_ => return,
14371456
};
1438-
pretty_printing_compatibility_hack(item, sess)
1457+
pretty_printing_compatibility_hack(&item, psess)
14391458
}

compiler/rustc_expand/src/mbe/transcribe.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
use std::mem;
22

3-
use rustc_ast::ExprKind;
43
use rustc_ast::mut_visit::{self, MutVisitor};
54
use rustc_ast::token::{
65
self, Delimiter, IdentIsRaw, InvisibleOrigin, Lit, LitKind, MetaVarKind, Nonterminal, Token,
76
TokenKind,
87
};
98
use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree};
9+
use rustc_ast::{ExprKind, StmtKind};
1010
use rustc_data_structures::fx::FxHashMap;
1111
use rustc_errors::{Diag, DiagCtxtHandle, PResult, pluralize};
1212
use rustc_parse::lexer::nfc_normalize;
@@ -317,6 +317,18 @@ pub(super) fn transcribe<'a>(
317317
let kind = token::NtLifetime(*ident, *is_raw);
318318
TokenTree::token_alone(kind, sp)
319319
}
320+
MatchedSingle(ParseNtResult::Item(item)) => {
321+
mk_delimited(MetaVarKind::Item, TokenStream::from_ast(item))
322+
}
323+
MatchedSingle(ParseNtResult::Stmt(stmt)) => {
324+
let stream = if let StmtKind::Empty = stmt.kind {
325+
// FIXME: Properly collect tokens for empty statements.
326+
TokenStream::token_alone(token::Semi, stmt.span)
327+
} else {
328+
TokenStream::from_ast(stmt)
329+
};
330+
mk_delimited(MetaVarKind::Stmt, stream)
331+
}
320332
MatchedSingle(ParseNtResult::Pat(pat, pat_kind)) => {
321333
mk_delimited(MetaVarKind::Pat(*pat_kind), TokenStream::from_ast(pat))
322334
}

compiler/rustc_expand/src/proc_macro.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ impl MultiItemModifier for DeriveProcMacro {
122122
// We had a lint for a long time, but now we just emit a hard error.
123123
// Eventually we might remove the special case hard error check
124124
// altogether. See #73345.
125-
crate::base::ann_pretty_printing_compatibility_hack(&item, &ecx.sess);
125+
crate::base::ann_pretty_printing_compatibility_hack(&item, &ecx.sess.psess);
126126
let input = item.to_tokens();
127127
let stream = {
128128
let _timer =

compiler/rustc_expand/src/proc_macro_server.rs

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,25 @@ impl FromInternal<(TokenStream, &mut Rustc<'_, '_>)> for Vec<TokenTree<TokenStre
116116

117117
while let Some(tree) = cursor.next() {
118118
let (Token { kind, span }, joint) = match tree.clone() {
119-
tokenstream::TokenTree::Delimited(span, _, delim, tts) => {
120-
let delimiter = pm::Delimiter::from_internal(delim);
119+
tokenstream::TokenTree::Delimited(span, _, delim, stream) => {
120+
// We used to have an alternative behaviour for crates that
121+
// needed it: a hack used to pass AST fragments to
122+
// attribute and derive macros as a single nonterminal
123+
// token instead of a token stream. Such token needs to be
124+
// "unwrapped" and not represented as a delimited group. We
125+
// had a lint for a long time, but now we just emit a hard
126+
// error. Eventually we might remove the special case hard
127+
// error check altogether. See #73345.
128+
if let Delimiter::Invisible(InvisibleOrigin::MetaVar(kind)) = delim {
129+
crate::base::stream_pretty_printing_compatibility_hack(
130+
kind,
131+
&stream,
132+
rustc.psess(),
133+
);
134+
}
121135
trees.push(TokenTree::Group(Group {
122-
delimiter,
123-
stream: Some(tts),
136+
delimiter: pm::Delimiter::from_internal(delim),
137+
stream: Some(stream),
124138
span: DelimSpan {
125139
open: span.open,
126140
close: span.close,
@@ -280,15 +294,6 @@ impl FromInternal<(TokenStream, &mut Rustc<'_, '_>)> for Vec<TokenTree<TokenStre
280294

281295
Interpolated(nt) => {
282296
let stream = TokenStream::from_nonterminal_ast(&nt);
283-
// We used to have an alternative behaviour for crates that
284-
// needed it: a hack used to pass AST fragments to
285-
// attribute and derive macros as a single nonterminal
286-
// token instead of a token stream. Such token needs to be
287-
// "unwrapped" and not represented as a delimited group. We
288-
// had a lint for a long time, but now we just emit a hard
289-
// error. Eventually we might remove the special case hard
290-
// error check altogether. See #73345.
291-
crate::base::nt_pretty_printing_compatibility_hack(&nt, rustc.ecx.sess);
292297
trees.push(TokenTree::Group(Group {
293298
delimiter: pm::Delimiter::None,
294299
stream: Some(stream),

compiler/rustc_parse/src/parser/expr.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3063,7 +3063,7 @@ impl<'a> Parser<'a> {
30633063
}
30643064

30653065
self.restore_snapshot(pre_pat_snapshot);
3066-
match self.parse_stmt_without_recovery(true, ForceCollect::No) {
3066+
match self.parse_stmt_without_recovery(true, ForceCollect::No, false) {
30673067
// Consume statements for as long as possible.
30683068
Ok(Some(stmt)) => {
30693069
stmts.push(stmt);

0 commit comments

Comments
 (0)