Skip to content

Commit fb31b3c

Browse files
committed
Auto merge of #114353 - nnethercote:parser-ast-cleanups, r=petrochenkov
Some parser and AST cleanups Things I found while looking closely at this code. r? `@petrochenkov`
2 parents d8bbef5 + d75ee2a commit fb31b3c

File tree

17 files changed

+82
-146
lines changed

17 files changed

+82
-146
lines changed

compiler/rustc_ast/src/ast.rs

+3-29
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
//! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
1515
//! - [`EnumDef`] and [`Variant`]: Enum declaration.
1616
//! - [`MetaItemLit`] and [`LitKind`]: Literal expressions.
17-
//! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
17+
//! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`]: Macro definition and invocation.
1818
//! - [`Attribute`]: Metadata associated with item.
1919
//! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
2020
@@ -1693,15 +1693,15 @@ where
16931693
#[derive(Clone, Encodable, Decodable, Debug)]
16941694
pub struct DelimArgs {
16951695
pub dspan: DelimSpan,
1696-
pub delim: MacDelimiter,
1696+
pub delim: Delimiter, // Note: `Delimiter::Invisible` never occurs
16971697
pub tokens: TokenStream,
16981698
}
16991699

17001700
impl DelimArgs {
17011701
/// Whether a macro with these arguments needs a semicolon
17021702
/// when used as a standalone item or statement.
17031703
pub fn need_semicolon(&self) -> bool {
1704-
!matches!(self, DelimArgs { delim: MacDelimiter::Brace, .. })
1704+
!matches!(self, DelimArgs { delim: Delimiter::Brace, .. })
17051705
}
17061706
}
17071707

@@ -1717,32 +1717,6 @@ where
17171717
}
17181718
}
17191719

1720-
#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1721-
pub enum MacDelimiter {
1722-
Parenthesis,
1723-
Bracket,
1724-
Brace,
1725-
}
1726-
1727-
impl MacDelimiter {
1728-
pub fn to_token(self) -> Delimiter {
1729-
match self {
1730-
MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1731-
MacDelimiter::Bracket => Delimiter::Bracket,
1732-
MacDelimiter::Brace => Delimiter::Brace,
1733-
}
1734-
}
1735-
1736-
pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1737-
match delim {
1738-
Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1739-
Delimiter::Bracket => Some(MacDelimiter::Bracket),
1740-
Delimiter::Brace => Some(MacDelimiter::Brace),
1741-
Delimiter::Invisible => None,
1742-
}
1743-
}
1744-
}
1745-
17461720
/// Represents a macro definition.
17471721
#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
17481722
pub struct MacroDef {

compiler/rustc_ast/src/attr/mod.rs

+6-8
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
use crate::ast::{AttrArgs, AttrArgsEq, AttrId, AttrItem, AttrKind, AttrStyle, AttrVec, Attribute};
44
use crate::ast::{DelimArgs, Expr, ExprKind, LitKind, MetaItemLit};
5-
use crate::ast::{MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem, NormalAttr};
5+
use crate::ast::{MetaItem, MetaItemKind, NestedMetaItem, NormalAttr};
66
use crate::ast::{Path, PathSegment, DUMMY_NODE_ID};
77
use crate::ptr::P;
88
use crate::token::{self, CommentKind, Delimiter, Token};
@@ -196,7 +196,7 @@ impl AttrItem {
196196

197197
fn meta_item_list(&self) -> Option<ThinVec<NestedMetaItem>> {
198198
match &self.args {
199-
AttrArgs::Delimited(args) if args.delim == MacDelimiter::Parenthesis => {
199+
AttrArgs::Delimited(args) if args.delim == Delimiter::Parenthesis => {
200200
MetaItemKind::list_from_tokens(args.tokens.clone())
201201
}
202202
AttrArgs::Delimited(_) | AttrArgs::Eq(..) | AttrArgs::Empty => None,
@@ -402,11 +402,9 @@ impl MetaItemKind {
402402
fn from_attr_args(args: &AttrArgs) -> Option<MetaItemKind> {
403403
match args {
404404
AttrArgs::Empty => Some(MetaItemKind::Word),
405-
AttrArgs::Delimited(DelimArgs {
406-
dspan: _,
407-
delim: MacDelimiter::Parenthesis,
408-
tokens,
409-
}) => MetaItemKind::list_from_tokens(tokens.clone()).map(MetaItemKind::List),
405+
AttrArgs::Delimited(DelimArgs { dspan: _, delim: Delimiter::Parenthesis, tokens }) => {
406+
MetaItemKind::list_from_tokens(tokens.clone()).map(MetaItemKind::List)
407+
}
410408
AttrArgs::Delimited(..) => None,
411409
AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => match expr.kind {
412410
ExprKind::Lit(token_lit) => {
@@ -578,7 +576,7 @@ pub fn mk_attr_nested_word(
578576
let path = Path::from_ident(outer_ident);
579577
let attr_args = AttrArgs::Delimited(DelimArgs {
580578
dspan: DelimSpan::from_single(span),
581-
delim: MacDelimiter::Parenthesis,
579+
delim: Delimiter::Parenthesis,
582580
tokens: inner_tokens,
583581
});
584582
mk_attr(g, style, path, attr_args, span)

compiler/rustc_ast/src/token.rs

-2
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,6 @@ pub enum BinOpToken {
4141
/// Describes how a sequence of token trees is delimited.
4242
/// Cannot use `proc_macro::Delimiter` directly because this
4343
/// structure should implement some additional traits.
44-
/// The `None` variant is also renamed to `Invisible` to be
45-
/// less confusing and better convey the semantics.
4644
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
4745
#[derive(Encodable, Decodable, Hash, HashStable_Generic)]
4846
pub enum Delimiter {

compiler/rustc_ast_pretty/src/pprust/state.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
476476
Some(MacHeader::Path(&item.path)),
477477
false,
478478
None,
479-
delim.to_token(),
479+
*delim,
480480
tokens,
481481
true,
482482
span,
@@ -640,7 +640,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
640640
Some(MacHeader::Keyword(kw)),
641641
has_bang,
642642
Some(*ident),
643-
macro_def.body.delim.to_token(),
643+
macro_def.body.delim,
644644
&macro_def.body.tokens.clone(),
645645
true,
646646
sp,
@@ -1240,7 +1240,7 @@ impl<'a> State<'a> {
12401240
Some(MacHeader::Path(&m.path)),
12411241
true,
12421242
None,
1243-
m.args.delim.to_token(),
1243+
m.args.delim,
12441244
&m.args.tokens.clone(),
12451245
true,
12461246
m.span(),

compiler/rustc_builtin_macros/src/assert.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ use crate::edition_panic::use_panic_2021;
44
use crate::errors;
55
use rustc_ast::ptr::P;
66
use rustc_ast::token;
7+
use rustc_ast::token::Delimiter;
78
use rustc_ast::tokenstream::{DelimSpan, TokenStream};
8-
use rustc_ast::{DelimArgs, Expr, ExprKind, MacCall, MacDelimiter, Path, PathSegment, UnOp};
9+
use rustc_ast::{DelimArgs, Expr, ExprKind, MacCall, Path, PathSegment, UnOp};
910
use rustc_ast_pretty::pprust;
1011
use rustc_errors::PResult;
1112
use rustc_expand::base::{DummyResult, ExtCtxt, MacEager, MacResult};
@@ -58,7 +59,7 @@ pub fn expand_assert<'cx>(
5859
path: panic_path(),
5960
args: P(DelimArgs {
6061
dspan: DelimSpan::from_single(call_site_span),
61-
delim: MacDelimiter::Parenthesis,
62+
delim: Delimiter::Parenthesis,
6263
tokens,
6364
}),
6465
})),

compiler/rustc_builtin_macros/src/assert/context.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
use rustc_ast::{
22
ptr::P,
33
token,
4+
token::Delimiter,
45
tokenstream::{DelimSpan, TokenStream, TokenTree},
5-
BinOpKind, BorrowKind, DelimArgs, Expr, ExprKind, ItemKind, MacCall, MacDelimiter, MethodCall,
6-
Mutability, Path, PathSegment, Stmt, StructRest, UnOp, UseTree, UseTreeKind, DUMMY_NODE_ID,
6+
BinOpKind, BorrowKind, DelimArgs, Expr, ExprKind, ItemKind, MacCall, MethodCall, Mutability,
7+
Path, PathSegment, Stmt, StructRest, UnOp, UseTree, UseTreeKind, DUMMY_NODE_ID,
78
};
89
use rustc_ast_pretty::pprust;
910
use rustc_data_structures::fx::FxHashSet;
@@ -179,7 +180,7 @@ impl<'cx, 'a> Context<'cx, 'a> {
179180
path: panic_path,
180181
args: P(DelimArgs {
181182
dspan: DelimSpan::from_single(self.span),
182-
delim: MacDelimiter::Parenthesis,
183+
delim: Delimiter::Parenthesis,
183184
tokens: initial.into_iter().chain(captures).collect::<TokenStream>(),
184185
}),
185186
})),

compiler/rustc_builtin_macros/src/edition_panic.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use rustc_ast::ptr::P;
2+
use rustc_ast::token::Delimiter;
23
use rustc_ast::tokenstream::{DelimSpan, TokenStream};
34
use rustc_ast::*;
45
use rustc_expand::base::*;
@@ -60,7 +61,7 @@ fn expand<'cx>(
6061
},
6162
args: P(DelimArgs {
6263
dspan: DelimSpan::from_single(sp),
63-
delim: MacDelimiter::Parenthesis,
64+
delim: Delimiter::Parenthesis,
6465
tokens: tts,
6566
}),
6667
})),

compiler/rustc_expand/src/placeholders.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use crate::expand::{AstFragment, AstFragmentKind};
22
use rustc_ast as ast;
33
use rustc_ast::mut_visit::*;
44
use rustc_ast::ptr::P;
5+
use rustc_ast::token::Delimiter;
56
use rustc_data_structures::fx::FxHashMap;
67
use rustc_span::source_map::DUMMY_SP;
78
use rustc_span::symbol::Ident;
@@ -18,7 +19,7 @@ pub fn placeholder(
1819
path: ast::Path { span: DUMMY_SP, segments: ThinVec::new(), tokens: None },
1920
args: P(ast::DelimArgs {
2021
dspan: ast::tokenstream::DelimSpan::dummy(),
21-
delim: ast::MacDelimiter::Parenthesis,
22+
delim: Delimiter::Parenthesis,
2223
tokens: ast::tokenstream::TokenStream::new(Vec::new()),
2324
}),
2425
})

compiler/rustc_parse/src/parser/attr.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ impl<'a> Parser<'a> {
3636
pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, AttrWrapper> {
3737
let mut outer_attrs = ast::AttrVec::new();
3838
let mut just_parsed_doc_comment = false;
39-
let start_pos = self.token_cursor.num_next_calls;
39+
let start_pos = self.num_bump_calls;
4040
loop {
4141
let attr = if self.check(&token::Pound) {
4242
let prev_outer_attr_sp = outer_attrs.last().map(|attr| attr.span);
@@ -277,7 +277,7 @@ impl<'a> Parser<'a> {
277277
pub(crate) fn parse_inner_attributes(&mut self) -> PResult<'a, ast::AttrVec> {
278278
let mut attrs = ast::AttrVec::new();
279279
loop {
280-
let start_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
280+
let start_pos: u32 = self.num_bump_calls.try_into().unwrap();
281281
// Only try to parse if it is an inner attribute (has `!`).
282282
let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
283283
Some(self.parse_attribute(InnerAttrPolicy::Permitted)?)
@@ -298,7 +298,7 @@ impl<'a> Parser<'a> {
298298
None
299299
};
300300
if let Some(attr) = attr {
301-
let end_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
301+
let end_pos: u32 = self.num_bump_calls.try_into().unwrap();
302302
// If we are currently capturing tokens, mark the location of this inner attribute.
303303
// If capturing ends up creating a `LazyAttrTokenStream`, we will include
304304
// this replace range with it, removing the inner attribute from the final

compiler/rustc_parse/src/parser/attr_wrapper.rs

+9-13
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ impl<'a> Parser<'a> {
213213

214214
let start_token = (self.token.clone(), self.token_spacing);
215215
let cursor_snapshot = self.token_cursor.clone();
216+
let start_pos = self.num_bump_calls;
216217

217218
let has_outer_attrs = !attrs.attrs.is_empty();
218219
let prev_capturing = std::mem::replace(&mut self.capture_state.capturing, Capturing::Yes);
@@ -273,8 +274,7 @@ impl<'a> Parser<'a> {
273274

274275
let replace_ranges_end = self.capture_state.replace_ranges.len();
275276

276-
let cursor_snapshot_next_calls = cursor_snapshot.num_next_calls;
277-
let mut end_pos = self.token_cursor.num_next_calls;
277+
let mut end_pos = self.num_bump_calls;
278278

279279
let mut captured_trailing = false;
280280

@@ -301,12 +301,12 @@ impl<'a> Parser<'a> {
301301
// then extend the range of captured tokens to include it, since the parser
302302
// was not actually bumped past it. When the `LazyAttrTokenStream` gets converted
303303
// into an `AttrTokenStream`, we will create the proper token.
304-
if self.token_cursor.break_last_token {
304+
if self.break_last_token {
305305
assert!(!captured_trailing, "Cannot set break_last_token and have trailing token");
306306
end_pos += 1;
307307
}
308308

309-
let num_calls = end_pos - cursor_snapshot_next_calls;
309+
let num_calls = end_pos - start_pos;
310310

311311
// If we have no attributes, then we will never need to
312312
// use any replace ranges.
@@ -316,7 +316,7 @@ impl<'a> Parser<'a> {
316316
// Grab any replace ranges that occur *inside* the current AST node.
317317
// We will perform the actual replacement when we convert the `LazyAttrTokenStream`
318318
// to an `AttrTokenStream`.
319-
let start_calls: u32 = cursor_snapshot_next_calls.try_into().unwrap();
319+
let start_calls: u32 = start_pos.try_into().unwrap();
320320
self.capture_state.replace_ranges[replace_ranges_start..replace_ranges_end]
321321
.iter()
322322
.cloned()
@@ -331,7 +331,7 @@ impl<'a> Parser<'a> {
331331
start_token,
332332
num_calls,
333333
cursor_snapshot,
334-
break_last_token: self.token_cursor.break_last_token,
334+
break_last_token: self.break_last_token,
335335
replace_ranges,
336336
});
337337

@@ -359,14 +359,10 @@ impl<'a> Parser<'a> {
359359
// with a `FlatToken::AttrTarget`. If this AST node is inside an item
360360
// that has `#[derive]`, then this will allow us to cfg-expand this
361361
// AST node.
362-
let start_pos =
363-
if has_outer_attrs { attrs.start_pos } else { cursor_snapshot_next_calls };
362+
let start_pos = if has_outer_attrs { attrs.start_pos } else { start_pos };
364363
let new_tokens = vec![(FlatToken::AttrTarget(attr_data), Spacing::Alone)];
365364

366-
assert!(
367-
!self.token_cursor.break_last_token,
368-
"Should not have unglued last token with cfg attr"
369-
);
365+
assert!(!self.break_last_token, "Should not have unglued last token with cfg attr");
370366
let range: Range<u32> = (start_pos.try_into().unwrap())..(end_pos.try_into().unwrap());
371367
self.capture_state.replace_ranges.push((range, new_tokens));
372368
self.capture_state.replace_ranges.extend(inner_attr_replace_ranges);
@@ -464,6 +460,6 @@ mod size_asserts {
464460
use rustc_data_structures::static_assert_size;
465461
// tidy-alphabetical-start
466462
static_assert_size!(AttrWrapper, 16);
467-
static_assert_size!(LazyAttrTokenStreamImpl, 120);
463+
static_assert_size!(LazyAttrTokenStreamImpl, 104);
468464
// tidy-alphabetical-end
469465
}

compiler/rustc_parse/src/parser/expr.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1167,7 +1167,7 @@ impl<'a> Parser<'a> {
11671167
DestructuredFloat::TrailingDot(sym, sym_span, dot_span) => {
11681168
assert!(suffix.is_none());
11691169
// Analogous to `Self::break_and_eat`
1170-
self.token_cursor.break_last_token = true;
1170+
self.break_last_token = true;
11711171
// This might work, in cases like `1. 2`, and might not,
11721172
// in cases like `offset_of!(Ty, 1.)`. It depends on what comes
11731173
// after the float-like token, and therefore we have to make
@@ -2599,7 +2599,7 @@ impl<'a> Parser<'a> {
25992599

26002600
// Recover from missing expression in `for` loop
26012601
if matches!(expr.kind, ExprKind::Block(..))
2602-
&& !matches!(self.token.kind, token::OpenDelim(token::Delimiter::Brace))
2602+
&& !matches!(self.token.kind, token::OpenDelim(Delimiter::Brace))
26032603
&& self.may_recover()
26042604
{
26052605
self.sess

compiler/rustc_parse/src/parser/item.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ use rustc_ast::ptr::P;
99
use rustc_ast::token::{self, Delimiter, TokenKind};
1010
use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
1111
use rustc_ast::util::case::Case;
12+
use rustc_ast::MacCall;
1213
use rustc_ast::{self as ast, AttrVec, Attribute, DUMMY_NODE_ID};
1314
use rustc_ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind};
1415
use rustc_ast::{BindingAnnotation, Block, FnDecl, FnSig, Param, SelfKind};
1516
use rustc_ast::{EnumDef, FieldDef, Generics, TraitRef, Ty, TyKind, Variant, VariantData};
1617
use rustc_ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind};
17-
use rustc_ast::{MacCall, MacDelimiter};
1818
use rustc_ast_pretty::pprust;
1919
use rustc_errors::{
2020
struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, PResult,
@@ -1968,7 +1968,7 @@ impl<'a> Parser<'a> {
19681968
let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
19691969
let tokens = TokenStream::new(vec![params, arrow, body]);
19701970
let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1971-
P(DelimArgs { dspan, delim: MacDelimiter::Brace, tokens })
1971+
P(DelimArgs { dspan, delim: Delimiter::Brace, tokens })
19721972
} else {
19731973
return self.unexpected();
19741974
};

0 commit comments

Comments
 (0)