Skip to content

Commit 94b4de0

Browse files
committed
Auto merge of #75800 - Aaron1011:feature/full-nt-tokens, r=petrochenkov
Attach tokens to all AST types used in `Nonterminal` We perform token capturing when we have outer attributes (for nonterminals that support attributes - e.g. `Stmt`), or when we parse a `Nonterminal` for a `macro_rules!` argument. The full list of `Nonterminals` affected by this PR is: * `NtBlock` * `NtStmt` * `NtTy` * `NtMeta` * `NtPath` * `NtVis` * `NtLiteral` Of these nonterminals, only `NtStmt` and `NtLiteral` (which is actually just an `Expr`), support outer attributes - the rest only ever have token capturing perform when they match a `macro_rules!` argument. This makes progress towards solving #43081 - we now collect tokens for everything that might need them. However, we still need to handle `#[cfg]`, inner attributes, and misc pretty-printing issues (e.g. #75734) I've separated the changes into (mostly) independent commits, which could be split into individual PRs for each `Nonterminal` variant. The purpose of having them all in one PR is to do a single Crater run for all of them. Most of the changes in this PR are trivial (adding `tokens: None` everywhere we construct the various AST structs). The significant changes are: * `ast::Visibility` is changed from `type Visibility = Spanned<VisibilityKind>` to a `struct Visibility { kind, span, tokens }`. * `maybe_collect_tokens` is made generic, and used for both `ast::Expr` and `ast::Stmt`. * Some of the statement-parsing functions are refactored so that we can capture the trailing semicolon. * `Nonterminal` and `Expr` both grew by 8 bytes, as some of the structs which are stored inline (rather than behind a `P`) now have an `Option<TokenStream>` field. Hopefully the performance impact of doing this is negligible.
2 parents ee04f9a + fec0479 commit 94b4de0

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+645
-135
lines changed

compiler/rustc_ast/src/ast.rs

+17-6
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ pub struct Path {
9696
/// The segments in the path: the things separated by `::`.
9797
/// Global paths begin with `kw::PathRoot`.
9898
pub segments: Vec<PathSegment>,
99+
pub tokens: Option<TokenStream>,
99100
}
100101

101102
impl PartialEq<Symbol> for Path {
@@ -117,7 +118,7 @@ impl Path {
117118
// Convert a span and an identifier to the corresponding
118119
// one-segment path.
119120
pub fn from_ident(ident: Ident) -> Path {
120-
Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span }
121+
Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
121122
}
122123

123124
pub fn is_global(&self) -> bool {
@@ -540,6 +541,7 @@ pub struct Block {
540541
/// Distinguishes between `unsafe { ... }` and `{ ... }`.
541542
pub rules: BlockCheckMode,
542543
pub span: Span,
544+
pub tokens: Option<TokenStream>,
543545
}
544546

545547
/// A match pattern.
@@ -586,7 +588,7 @@ impl Pat {
586588
_ => return None,
587589
};
588590

589-
Some(P(Ty { kind, id: self.id, span: self.span }))
591+
Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
590592
}
591593

592594
/// Walk top-down and call `it` in each place where a pattern occurs
@@ -916,6 +918,7 @@ pub struct Stmt {
916918
pub id: NodeId,
917919
pub kind: StmtKind,
918920
pub span: Span,
921+
pub tokens: Option<TokenStream>,
919922
}
920923

921924
impl Stmt {
@@ -1068,7 +1071,7 @@ pub struct Expr {
10681071

10691072
// `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
10701073
#[cfg(target_arch = "x86_64")]
1071-
rustc_data_structures::static_assert_size!(Expr, 104);
1074+
rustc_data_structures::static_assert_size!(Expr, 112);
10721075

10731076
impl Expr {
10741077
/// Returns `true` if this expression would be valid somewhere that expects a value;
@@ -1168,7 +1171,7 @@ impl Expr {
11681171
_ => return None,
11691172
};
11701173

1171-
Some(P(Ty { kind, id: self.id, span: self.span }))
1174+
Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
11721175
}
11731176

11741177
pub fn precedence(&self) -> ExprPrecedence {
@@ -1866,6 +1869,7 @@ pub struct Ty {
18661869
pub id: NodeId,
18671870
pub kind: TyKind,
18681871
pub span: Span,
1872+
pub tokens: Option<TokenStream>,
18691873
}
18701874

18711875
#[derive(Clone, Encodable, Decodable, Debug)]
@@ -2144,7 +2148,7 @@ impl Param {
21442148
/// Builds a `Param` object from `ExplicitSelf`.
21452149
pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
21462150
let span = eself.span.to(eself_ident.span);
2147-
let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span });
2151+
let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
21482152
let param = |mutbl, ty| Param {
21492153
attrs,
21502154
pat: P(Pat {
@@ -2167,6 +2171,7 @@ impl Param {
21672171
id: DUMMY_NODE_ID,
21682172
kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
21692173
span,
2174+
tokens: None,
21702175
}),
21712176
),
21722177
}
@@ -2416,6 +2421,7 @@ impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
24162421
pub struct AttrItem {
24172422
pub path: Path,
24182423
pub args: MacArgs,
2424+
pub tokens: Option<TokenStream>,
24192425
}
24202426

24212427
/// A list of attributes.
@@ -2485,7 +2491,12 @@ pub enum CrateSugar {
24852491
JustCrate,
24862492
}
24872493

2488-
pub type Visibility = Spanned<VisibilityKind>;
2494+
#[derive(Clone, Encodable, Decodable, Debug)]
2495+
pub struct Visibility {
2496+
pub kind: VisibilityKind,
2497+
pub span: Span,
2498+
pub tokens: Option<TokenStream>,
2499+
}
24892500

24902501
#[derive(Clone, Encodable, Decodable, Debug)]
24912502
pub enum VisibilityKind {

compiler/rustc_ast/src/attr/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,7 @@ crate fn mk_attr_id() -> AttrId {
330330
}
331331

332332
pub fn mk_attr(style: AttrStyle, path: Path, args: MacArgs, span: Span) -> Attribute {
333-
mk_attr_from_item(style, AttrItem { path, args }, span)
333+
mk_attr_from_item(style, AttrItem { path, args, tokens: None }, span)
334334
}
335335

336336
pub fn mk_attr_from_item(style: AttrStyle, item: AttrItem, span: Span) -> Attribute {
@@ -415,7 +415,7 @@ impl MetaItem {
415415
}
416416
}
417417
let span = span.with_hi(segments.last().unwrap().ident.span.hi());
418-
Path { span, segments }
418+
Path { span, segments, tokens: None }
419419
}
420420
Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. })) => match *nt {
421421
token::Nonterminal::NtMeta(ref item) => return item.meta(item.path.span),

compiler/rustc_ast/src/mut_visit.rs

+17-12
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use crate::tokenstream::*;
1414

1515
use rustc_data_structures::map_in_place::MapInPlace;
1616
use rustc_data_structures::sync::Lrc;
17-
use rustc_span::source_map::{respan, Spanned};
17+
use rustc_span::source_map::Spanned;
1818
use rustc_span::symbol::Ident;
1919
use rustc_span::Span;
2020

@@ -451,7 +451,7 @@ pub fn noop_visit_ty_constraint<T: MutVisitor>(
451451
}
452452

453453
pub fn noop_visit_ty<T: MutVisitor>(ty: &mut P<Ty>, vis: &mut T) {
454-
let Ty { id, kind, span } = ty.deref_mut();
454+
let Ty { id, kind, span, tokens: _ } = ty.deref_mut();
455455
vis.visit_id(id);
456456
match kind {
457457
TyKind::Infer | TyKind::ImplicitSelf | TyKind::Err | TyKind::Never | TyKind::CVarArgs => {}
@@ -513,7 +513,7 @@ pub fn noop_visit_ident<T: MutVisitor>(Ident { name: _, span }: &mut Ident, vis:
513513
vis.visit_span(span);
514514
}
515515

516-
pub fn noop_visit_path<T: MutVisitor>(Path { segments, span }: &mut Path, vis: &mut T) {
516+
pub fn noop_visit_path<T: MutVisitor>(Path { segments, span, tokens: _ }: &mut Path, vis: &mut T) {
517517
vis.visit_span(span);
518518
for PathSegment { ident, id, args } in segments {
519519
vis.visit_ident(ident);
@@ -579,7 +579,7 @@ pub fn noop_visit_local<T: MutVisitor>(local: &mut P<Local>, vis: &mut T) {
579579
pub fn noop_visit_attribute<T: MutVisitor>(attr: &mut Attribute, vis: &mut T) {
580580
let Attribute { kind, id: _, style: _, span } = attr;
581581
match kind {
582-
AttrKind::Normal(AttrItem { path, args }) => {
582+
AttrKind::Normal(AttrItem { path, args, tokens: _ }) => {
583583
vis.visit_path(path);
584584
visit_mac_args(args, vis);
585585
}
@@ -709,7 +709,7 @@ pub fn noop_visit_interpolated<T: MutVisitor>(nt: &mut token::Nonterminal, vis:
709709
token::NtLifetime(ident) => vis.visit_ident(ident),
710710
token::NtLiteral(expr) => vis.visit_expr(expr),
711711
token::NtMeta(item) => {
712-
let AttrItem { path, args } = item.deref_mut();
712+
let AttrItem { path, args, tokens: _ } = item.deref_mut();
713713
vis.visit_path(path);
714714
visit_mac_args(args, vis);
715715
}
@@ -871,7 +871,7 @@ pub fn noop_visit_mt<T: MutVisitor>(MutTy { ty, mutbl: _ }: &mut MutTy, vis: &mu
871871
}
872872

873873
pub fn noop_visit_block<T: MutVisitor>(block: &mut P<Block>, vis: &mut T) {
874-
let Block { id, stmts, rules: _, span } = block.deref_mut();
874+
let Block { id, stmts, rules: _, span, tokens: _ } = block.deref_mut();
875875
vis.visit_id(id);
876876
stmts.flat_map_in_place(|stmt| vis.flat_map_stmt(stmt));
877877
vis.visit_span(span);
@@ -978,11 +978,13 @@ pub fn noop_visit_mod<T: MutVisitor>(module: &mut Mod, vis: &mut T) {
978978

979979
pub fn noop_visit_crate<T: MutVisitor>(krate: &mut Crate, vis: &mut T) {
980980
visit_clobber(krate, |Crate { module, attrs, span, proc_macros }| {
981+
let item_vis =
982+
Visibility { kind: VisibilityKind::Public, span: span.shrink_to_lo(), tokens: None };
981983
let item = P(Item {
982984
ident: Ident::invalid(),
983985
attrs,
984986
id: DUMMY_NODE_ID,
985-
vis: respan(span.shrink_to_lo(), VisibilityKind::Public),
987+
vis: item_vis,
986988
span,
987989
kind: ItemKind::Mod(module),
988990
tokens: None,
@@ -1284,12 +1286,15 @@ pub fn noop_filter_map_expr<T: MutVisitor>(mut e: P<Expr>, vis: &mut T) -> Optio
12841286
}
12851287

12861288
pub fn noop_flat_map_stmt<T: MutVisitor>(
1287-
Stmt { kind, mut span, mut id }: Stmt,
1289+
Stmt { kind, mut span, mut id, tokens }: Stmt,
12881290
vis: &mut T,
12891291
) -> SmallVec<[Stmt; 1]> {
12901292
vis.visit_id(&mut id);
12911293
vis.visit_span(&mut span);
1292-
noop_flat_map_stmt_kind(kind, vis).into_iter().map(|kind| Stmt { id, kind, span }).collect()
1294+
noop_flat_map_stmt_kind(kind, vis)
1295+
.into_iter()
1296+
.map(|kind| Stmt { id, kind, span, tokens: tokens.clone() })
1297+
.collect()
12931298
}
12941299

12951300
pub fn noop_flat_map_stmt_kind<T: MutVisitor>(
@@ -1314,13 +1319,13 @@ pub fn noop_flat_map_stmt_kind<T: MutVisitor>(
13141319
}
13151320
}
13161321

1317-
pub fn noop_visit_vis<T: MutVisitor>(Spanned { node, span }: &mut Visibility, vis: &mut T) {
1318-
match node {
1322+
pub fn noop_visit_vis<T: MutVisitor>(visibility: &mut Visibility, vis: &mut T) {
1323+
match &mut visibility.kind {
13191324
VisibilityKind::Public | VisibilityKind::Crate(_) | VisibilityKind::Inherited => {}
13201325
VisibilityKind::Restricted { path, id } => {
13211326
vis.visit_path(path);
13221327
vis.visit_id(id);
13231328
}
13241329
}
1325-
vis.visit_span(span);
1330+
vis.visit_span(&mut visibility.span);
13261331
}

compiler/rustc_ast/src/token.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,7 @@ pub enum Nonterminal {
700700

701701
// `Nonterminal` is used a lot. Make sure it doesn't unintentionally get bigger.
702702
#[cfg(target_arch = "x86_64")]
703-
rustc_data_structures::static_assert_size!(Nonterminal, 40);
703+
rustc_data_structures::static_assert_size!(Nonterminal, 48);
704704

705705
#[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable)]
706706
pub enum NonterminalKind {

compiler/rustc_ast/src/visit.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -879,7 +879,7 @@ pub fn walk_arm<'a, V: Visitor<'a>>(visitor: &mut V, arm: &'a Arm) {
879879
}
880880

881881
pub fn walk_vis<'a, V: Visitor<'a>>(visitor: &mut V, vis: &'a Visibility) {
882-
if let VisibilityKind::Restricted { ref path, id } = vis.node {
882+
if let VisibilityKind::Restricted { ref path, id } = vis.kind {
883883
visitor.visit_path(path, id);
884884
}
885885
}

compiler/rustc_ast_lowering/src/item.rs

+9-6
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
251251
ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
252252
ItemKind::Use(ref use_tree) => {
253253
// Start with an empty prefix.
254-
let prefix = Path { segments: vec![], span: use_tree.span };
254+
let prefix = Path { segments: vec![], span: use_tree.span, tokens: None };
255255

256256
self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
257257
}
@@ -488,7 +488,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
488488
*ident = tree.ident();
489489

490490
// First, apply the prefix to the path.
491-
let mut path = Path { segments, span: path.span };
491+
let mut path = Path { segments, span: path.span, tokens: None };
492492

493493
// Correctly resolve `self` imports.
494494
if path.segments.len() > 1
@@ -540,8 +540,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
540540
hir::ItemKind::Use(path, hir::UseKind::Single)
541541
}
542542
UseTreeKind::Glob => {
543-
let path =
544-
self.lower_path(id, &Path { segments, span: path.span }, ParamMode::Explicit);
543+
let path = self.lower_path(
544+
id,
545+
&Path { segments, span: path.span, tokens: None },
546+
ParamMode::Explicit,
547+
);
545548
hir::ItemKind::Use(path, hir::UseKind::Glob)
546549
}
547550
UseTreeKind::Nested(ref trees) => {
@@ -569,7 +572,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
569572
// for that we return the `{}` import (called the
570573
// `ListStem`).
571574

572-
let prefix = Path { segments, span: prefix.span.to(path.span) };
575+
let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
573576

574577
// Add all the nested `PathListItem`s to the HIR.
575578
for &(ref use_tree, id) in trees {
@@ -927,7 +930,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
927930
v: &Visibility,
928931
explicit_owner: Option<NodeId>,
929932
) -> hir::Visibility<'hir> {
930-
let node = match v.node {
933+
let node = match v.kind {
931934
VisibilityKind::Public => hir::VisibilityKind::Public,
932935
VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
933936
VisibilityKind::Restricted { ref path, id } => {

compiler/rustc_ast_lowering/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -967,6 +967,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
967967
AttrKind::Normal(ref item) => AttrKind::Normal(AttrItem {
968968
path: item.path.clone(),
969969
args: self.lower_mac_args(&item.args),
970+
tokens: None,
970971
}),
971972
AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
972973
};
@@ -1106,6 +1107,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
11061107
id: node_id,
11071108
kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
11081109
span: constraint.span,
1110+
tokens: None,
11091111
},
11101112
itctx,
11111113
);

compiler/rustc_ast_passes/src/ast_validation.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -198,13 +198,13 @@ impl<'a> AstValidator<'a> {
198198
}
199199

200200
fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
201-
if let VisibilityKind::Inherited = vis.node {
201+
if let VisibilityKind::Inherited = vis.kind {
202202
return;
203203
}
204204

205205
let mut err =
206206
struct_span_err!(self.session, vis.span, E0449, "unnecessary visibility qualifier");
207-
if vis.node.is_pub() {
207+
if vis.kind.is_pub() {
208208
err.span_label(vis.span, "`pub` not permitted here because it's implied");
209209
}
210210
if let Some(note) = note {

compiler/rustc_ast_passes/src/feature_gate.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
594594
}
595595

596596
fn visit_vis(&mut self, vis: &'a ast::Visibility) {
597-
if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
597+
if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.kind {
598598
gate_feature_post!(
599599
&self,
600600
crate_visibility_modifier,

compiler/rustc_ast_pretty/src/pprust.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1359,7 +1359,7 @@ impl<'a> State<'a> {
13591359
}
13601360

13611361
crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1362-
match vis.node {
1362+
match vis.kind {
13631363
ast::VisibilityKind::Public => self.word_nbsp("pub"),
13641364
ast::VisibilityKind::Crate(sugar) => match sugar {
13651365
ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),

compiler/rustc_ast_pretty/src/pprust/tests.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use super::*;
22

33
use rustc_ast as ast;
4-
use rustc_span::source_map::respan;
54
use rustc_span::symbol::Ident;
65
use rustc_span::with_default_session_globals;
76

@@ -45,7 +44,11 @@ fn test_variant_to_string() {
4544

4645
let var = ast::Variant {
4746
ident,
48-
vis: respan(rustc_span::DUMMY_SP, ast::VisibilityKind::Inherited),
47+
vis: ast::Visibility {
48+
span: rustc_span::DUMMY_SP,
49+
kind: ast::VisibilityKind::Inherited,
50+
tokens: None,
51+
},
4952
attrs: Vec::new(),
5053
id: ast::DUMMY_NODE_ID,
5154
data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),

compiler/rustc_builtin_macros/src/cmdline_attrs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ pub fn inject(mut krate: ast::Crate, parse_sess: &ParseSess, attrs: &[String]) -
1515
);
1616

1717
let start_span = parser.token.span;
18-
let AttrItem { path, args } = match parser.parse_attr_item() {
18+
let AttrItem { path, args, tokens: _ } = match parser.parse_attr_item() {
1919
Ok(ai) => ai,
2020
Err(mut err) => {
2121
err.emit();

compiler/rustc_builtin_macros/src/concat_idents.rs

+1
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ pub fn expand_concat_idents<'cx>(
6161
id: ast::DUMMY_NODE_ID,
6262
kind: ast::TyKind::Path(None, ast::Path::from_ident(self.ident)),
6363
span: self.ident.span,
64+
tokens: None,
6465
}))
6566
}
6667
}

compiler/rustc_builtin_macros/src/deriving/debug.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -133,5 +133,5 @@ fn stmt_let_underscore(cx: &mut ExtCtxt<'_>, sp: Span, expr: P<ast::Expr>) -> as
133133
span: sp,
134134
attrs: ast::AttrVec::new(),
135135
});
136-
ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Local(local), span: sp }
136+
ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Local(local), span: sp, tokens: None }
137137
}

0 commit comments

Comments
 (0)