Skip to content

Commit 310805d

Browse files
committed
Remove NtBlock, Nonterminal, and TokenKind::Interpolated.
`NtBlock` is the last remaining variant of `Nonterminal`, so once it is gone then `Nonterminal` can be removed as well.
1 parent 28452b6 commit 310805d

File tree

18 files changed

+107
-387
lines changed

18 files changed

+107
-387
lines changed

compiler/rustc_ast/src/ast_traits.rs

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ use std::fmt;
66
use std::marker::PhantomData;
77

88
use crate::ptr::P;
9-
use crate::token::Nonterminal;
109
use crate::tokenstream::LazyAttrTokenStream;
1110
use crate::{
1211
Arm, AssocItem, AttrItem, AttrKind, AttrVec, Attribute, Block, Crate, Expr, ExprField,
@@ -206,19 +205,6 @@ impl HasTokens for Attribute {
206205
}
207206
}
208207

209-
impl HasTokens for Nonterminal {
210-
fn tokens(&self) -> Option<&LazyAttrTokenStream> {
211-
match self {
212-
Nonterminal::NtBlock(block) => block.tokens(),
213-
}
214-
}
215-
fn tokens_mut(&mut self) -> Option<&mut Option<LazyAttrTokenStream>> {
216-
match self {
217-
Nonterminal::NtBlock(block) => block.tokens_mut(),
218-
}
219-
}
220-
}
221-
222208
/// A trait for AST nodes having (or not having) attributes.
223209
pub trait HasAttrs {
224210
/// This is `true` if this `HasAttrs` might support 'custom' (proc-macro) inner

compiler/rustc_ast/src/mut_visit.rs

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -840,9 +840,9 @@ fn visit_lazy_tts<T: MutVisitor>(vis: &mut T, lazy_tts: &mut Option<LazyAttrToke
840840
visit_lazy_tts_opt_mut(vis, lazy_tts.as_mut());
841841
}
842842

843-
/// Applies ident visitor if it's an ident; applies other visits to interpolated nodes.
844-
/// In practice the ident part is not actually used by specific visitors right now,
845-
/// but there's a test below checking that it works.
843+
/// Applies ident visitor if it's an ident. In practice this is not actually
844+
/// used by specific visitors right now, but there's a test below checking that
845+
/// it works.
846846
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
847847
pub fn visit_token<T: MutVisitor>(vis: &mut T, t: &mut Token) {
848848
let Token { kind, span } = t;
@@ -860,45 +860,11 @@ pub fn visit_token<T: MutVisitor>(vis: &mut T, t: &mut Token) {
860860
token::NtLifetime(ident, _is_raw) => {
861861
vis.visit_ident(ident);
862862
}
863-
token::Interpolated(nt) => {
864-
let nt = Arc::make_mut(nt);
865-
visit_nonterminal(vis, nt);
866-
}
867863
_ => {}
868864
}
869865
vis.visit_span(span);
870866
}
871867

872-
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
873-
/// Applies the visitor to elements of interpolated nodes.
874-
//
875-
// N.B., this can occur only when applying a visitor to partially expanded
876-
// code, where parsed pieces have gotten implanted ito *other* macro
877-
// invocations. This is relevant for macro hygiene, but possibly not elsewhere.
878-
//
879-
// One problem here occurs because the types for flat_map_item, flat_map_stmt,
880-
// etc., allow the visitor to return *multiple* items; this is a problem for the
881-
// nodes here, because they insist on having exactly one piece. One solution
882-
// would be to mangle the MutVisitor trait to include one-to-many and
883-
// one-to-one versions of these entry points, but that would probably confuse a
884-
// lot of people and help very few. Instead, I'm just going to put in dynamic
885-
// checks. I think the performance impact of this will be pretty much
886-
// nonexistent. The danger is that someone will apply a `MutVisitor` to a
887-
// partially expanded node, and will be confused by the fact that their
888-
// `flat_map_item` or `flat_map_stmt` isn't getting called on `NtItem` or `NtStmt`
889-
// nodes. Hopefully they'll wind up reading this comment, and doing something
890-
// appropriate.
891-
//
892-
// BTW, design choice: I considered just changing the type of, e.g., `NtItem` to
893-
// contain multiple items, but decided against it when I looked at
894-
// `parse_item_or_view_item` and tried to figure out what I would do with
895-
// multiple items there....
896-
fn visit_nonterminal<T: MutVisitor>(vis: &mut T, nt: &mut token::Nonterminal) {
897-
match nt {
898-
token::NtBlock(block) => vis.visit_block(block),
899-
}
900-
}
901-
902868
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
903869
fn visit_defaultness<T: MutVisitor>(vis: &mut T, defaultness: &mut Defaultness) {
904870
match defaultness {

compiler/rustc_ast/src/token.rs

Lines changed: 16 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
use std::borrow::Cow;
22
use std::fmt;
3-
use std::sync::Arc;
43

54
pub use LitKind::*;
6-
pub use Nonterminal::*;
75
pub use NtExprKind::*;
86
pub use NtPatKind::*;
97
pub use TokenKind::*;
10-
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
118
use rustc_macros::{Decodable, Encodable, HashStable_Generic};
129
use rustc_span::edition::Edition;
1310
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, kw, sym};
@@ -16,7 +13,6 @@ use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, kw, sym};
1613
use rustc_span::{Ident, Symbol};
1714

1815
use crate::ast;
19-
use crate::ptr::P;
2016
use crate::util::case::Case;
2117

2218
#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
@@ -35,8 +31,8 @@ pub enum InvisibleOrigin {
3531
// `proc_macro::Delimiter::to_internal`, i.e. returned by a proc macro.
3632
ProcMacro,
3733

38-
// Converted from `TokenKind::Interpolated` in
39-
// `TokenStream::flatten_token`. Treated similarly to `ProcMacro`.
34+
// Converted from `TokenKind::NtLifetime` in `TokenStream::flatten_token`.
35+
// Treated similarly to `ProcMacro`.
4036
FlattenToken,
4137
}
4238

@@ -337,9 +333,7 @@ impl From<IdentIsRaw> for bool {
337333
}
338334
}
339335

340-
// SAFETY: due to the `Clone` impl below, all fields of all variants other than
341-
// `Interpolated` must impl `Copy`.
342-
#[derive(PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
336+
#[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
343337
pub enum TokenKind {
344338
/* Expression-operator symbols. */
345339
/// `=`
@@ -466,21 +460,6 @@ pub enum TokenKind {
466460
/// the `lifetime` metavariable in the macro's RHS.
467461
NtLifetime(Ident, IdentIsRaw),
468462

469-
/// An embedded AST node, as produced by a macro. This only exists for
470-
/// historical reasons. We'd like to get rid of it, for multiple reasons.
471-
/// - It's conceptually very strange. Saying a token can contain an AST
472-
/// node is like saying, in natural language, that a word can contain a
473-
/// sentence.
474-
/// - It requires special handling in a bunch of places in the parser.
475-
/// - It prevents `Token` from implementing `Copy`.
476-
/// It adds complexity and likely slows things down. Please don't add new
477-
/// occurrences of this token kind!
478-
///
479-
/// The span in the surrounding `Token` is that of the metavariable in the
480-
/// macro's RHS. The span within the Nonterminal is that of the fragment
481-
/// passed to the macro at the call site.
482-
Interpolated(Arc<Nonterminal>),
483-
484463
/// A doc comment token.
485464
/// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc)
486465
/// similarly to symbols in string literal tokens.
@@ -490,19 +469,6 @@ pub enum TokenKind {
490469
Eof,
491470
}
492471

493-
impl Clone for TokenKind {
494-
fn clone(&self) -> Self {
495-
// `TokenKind` would impl `Copy` if it weren't for `Interpolated`. So
496-
// for all other variants, this implementation of `clone` is just like
497-
// a copy. This is faster than the `derive(Clone)` version which has a
498-
// separate path for every variant.
499-
match self {
500-
Interpolated(nt) => Interpolated(Arc::clone(nt)),
501-
_ => unsafe { std::ptr::read(self) },
502-
}
503-
}
504-
}
505-
506472
#[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
507473
pub struct Token {
508474
pub kind: TokenKind,
@@ -597,7 +563,6 @@ impl Token {
597563
pub fn uninterpolated_span(&self) -> Span {
598564
match self.kind {
599565
NtIdent(ident, _) | NtLifetime(ident, _) => ident.span,
600-
Interpolated(ref nt) => nt.use_span(),
601566
_ => self.span,
602567
}
603568
}
@@ -615,7 +580,7 @@ impl Token {
615580
| FatArrow | Pound | Dollar | Question | SingleQuote => true,
616581

617582
OpenDelim(..) | CloseDelim(..) | Literal(..) | DocComment(..) | Ident(..)
618-
| NtIdent(..) | Lifetime(..) | NtLifetime(..) | Interpolated(..) | Eof => false,
583+
| NtIdent(..) | Lifetime(..) | NtLifetime(..) | Eof => false,
619584
}
620585
}
621586

@@ -646,7 +611,6 @@ impl Token {
646611
PathSep | // global path
647612
Lifetime(..) | // labeled loop
648613
Pound => true, // expression attributes
649-
Interpolated(ref nt) => matches!(&**nt, NtBlock(..)),
650614
OpenDelim(Delimiter::Invisible(InvisibleOrigin::MetaVar(
651615
MetaVarKind::Block |
652616
MetaVarKind::Expr { .. } |
@@ -718,7 +682,6 @@ impl Token {
718682
match self.kind {
719683
OpenDelim(Delimiter::Brace) | Literal(..) | Minus => true,
720684
Ident(name, IdentIsRaw::No) if name.is_bool_lit() => true,
721-
Interpolated(ref nt) => matches!(&**nt, NtBlock(..)),
722685
OpenDelim(Delimiter::Invisible(InvisibleOrigin::MetaVar(
723686
MetaVarKind::Expr { .. } | MetaVarKind::Block | MetaVarKind::Literal,
724687
))) => true,
@@ -846,31 +809,20 @@ impl Token {
846809
/// Is this a pre-parsed expression dropped into the token stream
847810
/// (which happens while parsing the result of macro expansion)?
848811
pub fn is_metavar_expr(&self) -> bool {
849-
#[allow(irrefutable_let_patterns)] // FIXME: temporary
850-
if let Interpolated(nt) = &self.kind
851-
&& let NtBlock(_) = &**nt
852-
{
853-
true
854-
} else if matches!(
812+
matches!(
855813
self.is_metavar_seq(),
856-
Some(MetaVarKind::Expr { .. } | MetaVarKind::Literal | MetaVarKind::Path)
857-
) {
858-
true
859-
} else {
860-
matches!(self.is_metavar_seq(), Some(MetaVarKind::Path))
861-
}
814+
Some(
815+
MetaVarKind::Expr { .. }
816+
| MetaVarKind::Literal
817+
| MetaVarKind::Path
818+
| MetaVarKind::Block
819+
)
820+
)
862821
}
863822

864-
/// Is the token an interpolated block (`$b:block`)?
865-
pub fn is_whole_block(&self) -> bool {
866-
#[allow(irrefutable_let_patterns)] // FIXME: temporary
867-
if let Interpolated(nt) = &self.kind
868-
&& let NtBlock(..) = &**nt
869-
{
870-
return true;
871-
}
872-
873-
false
823+
/// Are we at a block from a metavar (`$b:block`)?
824+
pub fn is_metavar_block(&self) -> bool {
825+
matches!(self.is_metavar_seq(), Some(MetaVarKind::Block))
874826
}
875827

876828
/// Returns `true` if the token is either the `mut` or `const` keyword.
@@ -1044,7 +996,7 @@ impl Token {
1044996
| PercentEq | CaretEq | AndEq | OrEq | ShlEq | ShrEq | At | DotDotDot | DotDotEq
1045997
| Comma | Semi | PathSep | RArrow | LArrow | FatArrow | Pound | Dollar | Question
1046998
| OpenDelim(..) | CloseDelim(..) | Literal(..) | Ident(..) | NtIdent(..)
1047-
| Lifetime(..) | NtLifetime(..) | Interpolated(..) | DocComment(..) | Eof,
999+
| Lifetime(..) | NtLifetime(..) | DocComment(..) | Eof,
10481000
_,
10491001
) => {
10501002
return None;
@@ -1083,12 +1035,6 @@ pub enum NtExprKind {
10831035
Expr2021 { inferred: bool },
10841036
}
10851037

1086-
#[derive(Clone, Encodable, Decodable)]
1087-
/// For interpolation during macro expansion.
1088-
pub enum Nonterminal {
1089-
NtBlock(P<ast::Block>),
1090-
}
1091-
10921038
#[derive(Debug, Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, HashStable_Generic)]
10931039
pub enum NonterminalKind {
10941040
Item,
@@ -1172,47 +1118,6 @@ impl fmt::Display for NonterminalKind {
11721118
}
11731119
}
11741120

1175-
impl Nonterminal {
1176-
pub fn use_span(&self) -> Span {
1177-
match self {
1178-
NtBlock(block) => block.span,
1179-
}
1180-
}
1181-
1182-
pub fn descr(&self) -> &'static str {
1183-
match self {
1184-
NtBlock(..) => "block",
1185-
}
1186-
}
1187-
}
1188-
1189-
impl PartialEq for Nonterminal {
1190-
fn eq(&self, _rhs: &Self) -> bool {
1191-
// FIXME: Assume that all nonterminals are not equal, we can't compare them
1192-
// correctly based on data from AST. This will prevent them from matching each other
1193-
// in macros. The comparison will become possible only when each nonterminal has an
1194-
// attached token stream from which it was parsed.
1195-
false
1196-
}
1197-
}
1198-
1199-
impl fmt::Debug for Nonterminal {
1200-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1201-
match *self {
1202-
NtBlock(..) => f.pad("NtBlock(..)"),
1203-
}
1204-
}
1205-
}
1206-
1207-
impl<CTX> HashStable<CTX> for Nonterminal
1208-
where
1209-
CTX: crate::HashStableContext,
1210-
{
1211-
fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) {
1212-
panic!("interpolated tokens should not be present in the HIR")
1213-
}
1214-
}
1215-
12161121
// Some types are used a lot. Make sure they don't unintentionally get bigger.
12171122
#[cfg(target_pointer_width = "64")]
12181123
mod size_asserts {
@@ -1222,7 +1127,6 @@ mod size_asserts {
12221127
// tidy-alphabetical-start
12231128
static_assert_size!(Lit, 12);
12241129
static_assert_size!(LitKind, 2);
1225-
static_assert_size!(Nonterminal, 8);
12261130
static_assert_size!(Token, 24);
12271131
static_assert_size!(TokenKind, 16);
12281132
// tidy-alphabetical-end

compiler/rustc_ast/src/tokenstream.rs

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use rustc_span::{DUMMY_SP, Span, SpanDecoder, SpanEncoder, Symbol, sym};
2525

2626
use crate::ast::AttrStyle;
2727
use crate::ast_traits::{HasAttrs, HasTokens};
28-
use crate::token::{self, Delimiter, InvisibleOrigin, Nonterminal, Token, TokenKind};
28+
use crate::token::{self, Delimiter, InvisibleOrigin, Token, TokenKind};
2929
use crate::{AttrVec, Attribute};
3030

3131
/// Part of a `TokenStream`.
@@ -305,11 +305,6 @@ pub struct AttrsTarget {
305305
}
306306

307307
/// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s.
308-
///
309-
/// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
310-
/// instead of a representation of the abstract syntax tree.
311-
/// Today's `TokenTree`s can still contain AST via `token::Interpolated` for
312-
/// backwards compatibility.
313308
#[derive(Clone, Debug, Default, Encodable, Decodable)]
314309
pub struct TokenStream(pub(crate) Arc<Vec<TokenTree>>);
315310

@@ -476,12 +471,6 @@ impl TokenStream {
476471
TokenStream::new(tts)
477472
}
478473

479-
pub fn from_nonterminal_ast(nt: &Nonterminal) -> TokenStream {
480-
match nt {
481-
Nonterminal::NtBlock(block) => TokenStream::from_ast(block),
482-
}
483-
}
484-
485474
fn flatten_token(token: &Token, spacing: Spacing) -> TokenTree {
486475
match token.kind {
487476
token::NtIdent(ident, is_raw) => {
@@ -493,12 +482,6 @@ impl TokenStream {
493482
Delimiter::Invisible(InvisibleOrigin::FlattenToken),
494483
TokenStream::token_alone(token::Lifetime(ident.name, is_raw), ident.span),
495484
),
496-
token::Interpolated(ref nt) => TokenTree::Delimited(
497-
DelimSpan::from_single(token.span),
498-
DelimSpacing::new(Spacing::JointHidden, spacing),
499-
Delimiter::Invisible(InvisibleOrigin::FlattenToken),
500-
TokenStream::from_nonterminal_ast(&nt).flattened(),
501-
),
502485
_ => TokenTree::Token(token.clone(), spacing),
503486
}
504487
}
@@ -516,10 +499,9 @@ impl TokenStream {
516499
pub fn flattened(&self) -> TokenStream {
517500
fn can_skip(stream: &TokenStream) -> bool {
518501
stream.iter().all(|tree| match tree {
519-
TokenTree::Token(token, _) => !matches!(
520-
token.kind,
521-
token::NtIdent(..) | token::NtLifetime(..) | token::Interpolated(..)
522-
),
502+
TokenTree::Token(token, _) => {
503+
!matches!(token.kind, token::NtIdent(..) | token::NtLifetime(..))
504+
}
523505
TokenTree::Delimited(.., inner) => can_skip(inner),
524506
})
525507
}

0 commit comments

Comments
 (0)