Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 9e136a3

Browse files
committedDec 19, 2024·
Auto merge of rust-lang#133793 - nnethercote:speed-up-expected_tokens, r=spastorino
Speed up `Parser::expected_tokens` The constant pushing/clearing of `Parser::expected_tokens` during parsing is slow. This PR speeds it up greatly. r? `@estebank`
2 parents 11663cd + 0f7dccf commit 9e136a3

File tree

22 files changed

+1415
-844
lines changed

22 files changed

+1415
-844
lines changed
 

‎compiler/rustc_builtin_macros/src/asm.rs

Lines changed: 56 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
use ast::token::IdentIsRaw;
22
use lint::BuiltinLintDiag;
3-
use rustc_ast::AsmMacro;
43
use rustc_ast::ptr::P;
5-
use rustc_ast::token::{self, Delimiter};
64
use rustc_ast::tokenstream::TokenStream;
5+
use rustc_ast::{AsmMacro, token};
76
use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
87
use rustc_errors::PResult;
98
use rustc_expand::base::*;
109
use rustc_index::bit_set::GrowableBitSet;
11-
use rustc_parse::parser::Parser;
10+
use rustc_parse::exp;
11+
use rustc_parse::parser::{ExpKeywordPair, Parser};
1212
use rustc_session::lint;
13-
use rustc_span::{ErrorGuaranteed, Ident, InnerSpan, Span, Symbol, kw, sym};
13+
use rustc_span::{ErrorGuaranteed, Ident, InnerSpan, Span, Symbol, kw};
1414
use rustc_target::asm::InlineAsmArch;
1515
use smallvec::smallvec;
1616
use {rustc_ast as ast, rustc_parse_format as parse};
@@ -38,16 +38,16 @@ pub struct AsmArgs {
3838
/// - `Err(_)` if the current token matches the keyword, but was not expected
3939
fn eat_operand_keyword<'a>(
4040
p: &mut Parser<'a>,
41-
symbol: Symbol,
41+
exp: ExpKeywordPair,
4242
asm_macro: AsmMacro,
4343
) -> PResult<'a, bool> {
4444
if matches!(asm_macro, AsmMacro::Asm) {
45-
Ok(p.eat_keyword(symbol))
45+
Ok(p.eat_keyword(exp))
4646
} else {
4747
let span = p.token.span;
48-
if p.eat_keyword_noexpect(symbol) {
48+
if p.eat_keyword_noexpect(exp.kw) {
4949
// in gets printed as `r#in` otherwise
50-
let symbol = if symbol == kw::In { "in" } else { symbol.as_str() };
50+
let symbol = if exp.kw == kw::In { "in" } else { exp.kw.as_str() };
5151
Err(p.dcx().create_err(errors::AsmUnsupportedOperand {
5252
span,
5353
symbol,
@@ -95,28 +95,28 @@ pub fn parse_asm_args<'a>(
9595

9696
let mut allow_templates = true;
9797
while p.token != token::Eof {
98-
if !p.eat(&token::Comma) {
98+
if !p.eat(exp!(Comma)) {
9999
if allow_templates {
100100
// After a template string, we always expect *only* a comma...
101101
return Err(dcx.create_err(errors::AsmExpectedComma { span: p.token.span }));
102102
} else {
103103
// ...after that delegate to `expect` to also include the other expected tokens.
104-
return Err(p.expect(&token::Comma).err().unwrap());
104+
return Err(p.expect(exp!(Comma)).err().unwrap());
105105
}
106106
}
107107
if p.token == token::Eof {
108108
break;
109109
} // accept trailing commas
110110

111111
// Parse clobber_abi
112-
if p.eat_keyword(sym::clobber_abi) {
112+
if p.eat_keyword(exp!(ClobberAbi)) {
113113
parse_clobber_abi(p, &mut args)?;
114114
allow_templates = false;
115115
continue;
116116
}
117117

118118
// Parse options
119-
if p.eat_keyword(sym::options) {
119+
if p.eat_keyword(exp!(Options)) {
120120
parse_options(p, &mut args, asm_macro)?;
121121
allow_templates = false;
122122
continue;
@@ -128,65 +128,65 @@ pub fn parse_asm_args<'a>(
128128
let name = if p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq) {
129129
let (ident, _) = p.token.ident().unwrap();
130130
p.bump();
131-
p.expect(&token::Eq)?;
131+
p.expect(exp!(Eq))?;
132132
allow_templates = false;
133133
Some(ident.name)
134134
} else {
135135
None
136136
};
137137

138138
let mut explicit_reg = false;
139-
let op = if eat_operand_keyword(p, kw::In, asm_macro)? {
139+
let op = if eat_operand_keyword(p, exp!(In), asm_macro)? {
140140
let reg = parse_reg(p, &mut explicit_reg)?;
141-
if p.eat_keyword(kw::Underscore) {
141+
if p.eat_keyword(exp!(Underscore)) {
142142
let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span });
143143
return Err(err);
144144
}
145145
let expr = p.parse_expr()?;
146146
ast::InlineAsmOperand::In { reg, expr }
147-
} else if eat_operand_keyword(p, sym::out, asm_macro)? {
147+
} else if eat_operand_keyword(p, exp!(Out), asm_macro)? {
148148
let reg = parse_reg(p, &mut explicit_reg)?;
149-
let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
149+
let expr = if p.eat_keyword(exp!(Underscore)) { None } else { Some(p.parse_expr()?) };
150150
ast::InlineAsmOperand::Out { reg, expr, late: false }
151-
} else if eat_operand_keyword(p, sym::lateout, asm_macro)? {
151+
} else if eat_operand_keyword(p, exp!(Lateout), asm_macro)? {
152152
let reg = parse_reg(p, &mut explicit_reg)?;
153-
let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
153+
let expr = if p.eat_keyword(exp!(Underscore)) { None } else { Some(p.parse_expr()?) };
154154
ast::InlineAsmOperand::Out { reg, expr, late: true }
155-
} else if eat_operand_keyword(p, sym::inout, asm_macro)? {
155+
} else if eat_operand_keyword(p, exp!(Inout), asm_macro)? {
156156
let reg = parse_reg(p, &mut explicit_reg)?;
157-
if p.eat_keyword(kw::Underscore) {
157+
if p.eat_keyword(exp!(Underscore)) {
158158
let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span });
159159
return Err(err);
160160
}
161161
let expr = p.parse_expr()?;
162-
if p.eat(&token::FatArrow) {
162+
if p.eat(exp!(FatArrow)) {
163163
let out_expr =
164-
if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
164+
if p.eat_keyword(exp!(Underscore)) { None } else { Some(p.parse_expr()?) };
165165
ast::InlineAsmOperand::SplitInOut { reg, in_expr: expr, out_expr, late: false }
166166
} else {
167167
ast::InlineAsmOperand::InOut { reg, expr, late: false }
168168
}
169-
} else if eat_operand_keyword(p, sym::inlateout, asm_macro)? {
169+
} else if eat_operand_keyword(p, exp!(Inlateout), asm_macro)? {
170170
let reg = parse_reg(p, &mut explicit_reg)?;
171-
if p.eat_keyword(kw::Underscore) {
171+
if p.eat_keyword(exp!(Underscore)) {
172172
let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span });
173173
return Err(err);
174174
}
175175
let expr = p.parse_expr()?;
176-
if p.eat(&token::FatArrow) {
176+
if p.eat(exp!(FatArrow)) {
177177
let out_expr =
178-
if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
178+
if p.eat_keyword(exp!(Underscore)) { None } else { Some(p.parse_expr()?) };
179179
ast::InlineAsmOperand::SplitInOut { reg, in_expr: expr, out_expr, late: true }
180180
} else {
181181
ast::InlineAsmOperand::InOut { reg, expr, late: true }
182182
}
183-
} else if eat_operand_keyword(p, sym::label, asm_macro)? {
183+
} else if eat_operand_keyword(p, exp!(Label), asm_macro)? {
184184
let block = p.parse_block()?;
185185
ast::InlineAsmOperand::Label { block }
186-
} else if p.eat_keyword(kw::Const) {
186+
} else if p.eat_keyword(exp!(Const)) {
187187
let anon_const = p.parse_expr_anon_const()?;
188188
ast::InlineAsmOperand::Const { anon_const }
189-
} else if p.eat_keyword(sym::sym) {
189+
} else if p.eat_keyword(exp!(Sym)) {
190190
let expr = p.parse_expr()?;
191191
let ast::ExprKind::Path(qself, path) = &expr.kind else {
192192
let err = dcx.create_err(errors::AsmSymNoPath { span: expr.span });
@@ -389,31 +389,31 @@ fn parse_options<'a>(
389389
) -> PResult<'a, ()> {
390390
let span_start = p.prev_token.span;
391391

392-
p.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
393-
394-
while !p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
395-
const OPTIONS: [(Symbol, ast::InlineAsmOptions); ast::InlineAsmOptions::COUNT] = [
396-
(sym::pure, ast::InlineAsmOptions::PURE),
397-
(sym::nomem, ast::InlineAsmOptions::NOMEM),
398-
(sym::readonly, ast::InlineAsmOptions::READONLY),
399-
(sym::preserves_flags, ast::InlineAsmOptions::PRESERVES_FLAGS),
400-
(sym::noreturn, ast::InlineAsmOptions::NORETURN),
401-
(sym::nostack, ast::InlineAsmOptions::NOSTACK),
402-
(sym::may_unwind, ast::InlineAsmOptions::MAY_UNWIND),
403-
(sym::att_syntax, ast::InlineAsmOptions::ATT_SYNTAX),
404-
(kw::Raw, ast::InlineAsmOptions::RAW),
392+
p.expect(exp!(OpenParen))?;
393+
394+
while !p.eat(exp!(CloseParen)) {
395+
const OPTIONS: [(ExpKeywordPair, ast::InlineAsmOptions); ast::InlineAsmOptions::COUNT] = [
396+
(exp!(Pure), ast::InlineAsmOptions::PURE),
397+
(exp!(Nomem), ast::InlineAsmOptions::NOMEM),
398+
(exp!(Readonly), ast::InlineAsmOptions::READONLY),
399+
(exp!(PreservesFlags), ast::InlineAsmOptions::PRESERVES_FLAGS),
400+
(exp!(Noreturn), ast::InlineAsmOptions::NORETURN),
401+
(exp!(Nostack), ast::InlineAsmOptions::NOSTACK),
402+
(exp!(MayUnwind), ast::InlineAsmOptions::MAY_UNWIND),
403+
(exp!(AttSyntax), ast::InlineAsmOptions::ATT_SYNTAX),
404+
(exp!(Raw), ast::InlineAsmOptions::RAW),
405405
];
406406

407407
'blk: {
408-
for (symbol, option) in OPTIONS {
408+
for (exp, option) in OPTIONS {
409409
let kw_matched = if asm_macro.is_supported_option(option) {
410-
p.eat_keyword(symbol)
410+
p.eat_keyword(exp)
411411
} else {
412-
p.eat_keyword_noexpect(symbol)
412+
p.eat_keyword_noexpect(exp.kw)
413413
};
414414

415415
if kw_matched {
416-
try_set_option(p, args, asm_macro, symbol, option);
416+
try_set_option(p, args, asm_macro, exp.kw, option);
417417
break 'blk;
418418
}
419419
}
@@ -422,10 +422,10 @@ fn parse_options<'a>(
422422
}
423423

424424
// Allow trailing commas
425-
if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
425+
if p.eat(exp!(CloseParen)) {
426426
break;
427427
}
428-
p.expect(&token::Comma)?;
428+
p.expect(exp!(Comma))?;
429429
}
430430

431431
let new_span = span_start.to(p.prev_token.span);
@@ -437,14 +437,14 @@ fn parse_options<'a>(
437437
fn parse_clobber_abi<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> PResult<'a, ()> {
438438
let span_start = p.prev_token.span;
439439

440-
p.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
440+
p.expect(exp!(OpenParen))?;
441441

442-
if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
442+
if p.eat(exp!(CloseParen)) {
443443
return Err(p.dcx().create_err(errors::NonABI { span: p.token.span }));
444444
}
445445

446446
let mut new_abis = Vec::new();
447-
while !p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
447+
while !p.eat(exp!(CloseParen)) {
448448
match p.parse_str_lit() {
449449
Ok(str_lit) => {
450450
new_abis.push((str_lit.symbol_unescaped, str_lit.span));
@@ -456,10 +456,10 @@ fn parse_clobber_abi<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> PResult<'a,
456456
};
457457

458458
// Allow trailing commas
459-
if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
459+
if p.eat(exp!(CloseParen)) {
460460
break;
461461
}
462-
p.expect(&token::Comma)?;
462+
p.expect(exp!(Comma))?;
463463
}
464464

465465
let full_span = span_start.to(p.prev_token.span);
@@ -482,7 +482,7 @@ fn parse_reg<'a>(
482482
p: &mut Parser<'a>,
483483
explicit_reg: &mut bool,
484484
) -> PResult<'a, ast::InlineAsmRegOrRegClass> {
485-
p.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
485+
p.expect(exp!(OpenParen))?;
486486
let result = match p.token.uninterpolate().kind {
487487
token::Ident(name, IdentIsRaw::No) => ast::InlineAsmRegOrRegClass::RegClass(name),
488488
token::Literal(token::Lit { kind: token::LitKind::Str, symbol, suffix: _ }) => {
@@ -496,7 +496,7 @@ fn parse_reg<'a>(
496496
}
497497
};
498498
p.bump();
499-
p.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
499+
p.expect(exp!(CloseParen))?;
500500
Ok(result)
501501
}
502502

‎compiler/rustc_builtin_macros/src/assert.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use rustc_ast::{DelimArgs, Expr, ExprKind, MacCall, Path, PathSegment, UnOp, tok
77
use rustc_ast_pretty::pprust;
88
use rustc_errors::PResult;
99
use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult};
10+
use rustc_parse::exp;
1011
use rustc_parse::parser::Parser;
1112
use rustc_span::{DUMMY_SP, Ident, Span, Symbol, sym};
1213
use thin_vec::thin_vec;
@@ -143,7 +144,7 @@ fn parse_assert<'a>(cx: &ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PResult<
143144
cx.dcx().emit_err(errors::AssertMissingComma { span: parser.token.span, comma });
144145

145146
parse_custom_message(&mut parser)
146-
} else if parser.eat(&token::Comma) {
147+
} else if parser.eat(exp!(Comma)) {
147148
parse_custom_message(&mut parser)
148149
} else {
149150
None

‎compiler/rustc_builtin_macros/src/cfg.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use rustc_ast::token;
66
use rustc_ast::tokenstream::TokenStream;
77
use rustc_errors::PResult;
88
use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult};
9+
use rustc_parse::exp;
910
use rustc_span::Span;
1011
use {rustc_ast as ast, rustc_attr_parsing as attr};
1112

@@ -48,9 +49,9 @@ fn parse_cfg<'a>(
4849

4950
let cfg = p.parse_meta_item_inner()?;
5051

51-
let _ = p.eat(&token::Comma);
52+
let _ = p.eat(exp!(Comma));
5253

53-
if !p.eat(&token::Eof) {
54+
if !p.eat(exp!(Eof)) {
5455
return Err(cx.dcx().create_err(errors::OneCfgPattern { span }));
5556
}
5657

‎compiler/rustc_builtin_macros/src/format.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use rustc_errors::{Applicability, Diag, MultiSpan, PResult, SingleLabelManySpans
1212
use rustc_expand::base::*;
1313
use rustc_lint_defs::builtin::NAMED_ARGUMENTS_USED_POSITIONALLY;
1414
use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiag, LintId};
15+
use rustc_parse::exp;
1516
use rustc_parse_format as parse;
1617
use rustc_span::{BytePos, ErrorGuaranteed, Ident, InnerSpan, Span, Symbol};
1718

@@ -93,12 +94,12 @@ fn parse_args<'a>(ecx: &ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<'a,
9394
let mut first = true;
9495

9596
while p.token != token::Eof {
96-
if !p.eat(&token::Comma) {
97+
if !p.eat(exp!(Comma)) {
9798
if first {
98-
p.clear_expected_tokens();
99+
p.clear_expected_token_types();
99100
}
100101

101-
match p.expect(&token::Comma) {
102+
match p.expect(exp!(Comma)) {
102103
Err(err) => {
103104
match token::TokenKind::Comma.similar_tokens() {
104105
Some(tks) if tks.contains(&p.token.kind) => {
@@ -122,7 +123,7 @@ fn parse_args<'a>(ecx: &ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<'a,
122123
match p.token.ident() {
123124
Some((ident, _)) if p.look_ahead(1, |t| *t == token::Eq) => {
124125
p.bump();
125-
p.expect(&token::Eq)?;
126+
p.expect(exp!(Eq))?;
126127
let expr = p.parse_expr()?;
127128
if let Some((_, prev)) = args.by_name(ident.name) {
128129
ecx.dcx().emit_err(errors::FormatDuplicateArg {

‎compiler/rustc_builtin_macros/src/pattern_type.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ use rustc_ast::tokenstream::TokenStream;
33
use rustc_ast::{Pat, Ty, ast};
44
use rustc_errors::PResult;
55
use rustc_expand::base::{self, DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult};
6-
use rustc_span::{Span, sym};
6+
use rustc_parse::exp;
7+
use rustc_span::Span;
78

89
pub(crate) fn expand<'cx>(
910
cx: &'cx mut ExtCtxt<'_>,
@@ -24,7 +25,7 @@ fn parse_pat_ty<'a>(cx: &mut ExtCtxt<'a>, stream: TokenStream) -> PResult<'a, (P
2425
let mut parser = cx.new_parser_from_tts(stream);
2526

2627
let ty = parser.parse_ty()?;
27-
parser.expect_keyword(sym::is)?;
28+
parser.expect_keyword(exp!(Is))?;
2829
let pat = parser.parse_pat_no_top_alt(None, None)?;
2930

3031
Ok((ty, pat))

‎compiler/rustc_builtin_macros/src/util.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_expand::expand::AstFragment;
77
use rustc_feature::AttributeTemplate;
88
use rustc_lint_defs::BuiltinLintDiag;
99
use rustc_lint_defs::builtin::DUPLICATE_MACRO_ATTRIBUTES;
10-
use rustc_parse::{parser, validate_attr};
10+
use rustc_parse::{exp, parser, validate_attr};
1111
use rustc_session::errors::report_lit_error;
1212
use rustc_span::{BytePos, Span, Symbol};
1313

@@ -204,7 +204,7 @@ pub(crate) fn get_single_expr_from_tts(
204204
Ok(ret) => ret,
205205
Err(guar) => return ExpandResult::Ready(Err(guar)),
206206
};
207-
let _ = p.eat(&token::Comma);
207+
let _ = p.eat(exp!(Comma));
208208

209209
if p.token != token::Eof {
210210
cx.dcx().emit_err(errors::OnlyOneArgument { span, name });
@@ -237,7 +237,7 @@ pub(crate) fn get_exprs_from_tts(
237237
let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
238238

239239
es.push(expr);
240-
if p.eat(&token::Comma) {
240+
if p.eat(exp!(Comma)) {
241241
continue;
242242
}
243243
if p.token != token::Eof {

‎compiler/rustc_expand/src/module.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ use std::iter::once;
22
use std::path::{self, Path, PathBuf};
33

44
use rustc_ast::ptr::P;
5-
use rustc_ast::{AttrVec, Attribute, Inline, Item, ModSpans, token};
5+
use rustc_ast::{AttrVec, Attribute, Inline, Item, ModSpans};
66
use rustc_errors::{Diag, ErrorGuaranteed};
7-
use rustc_parse::{new_parser_from_file, unwrap_or_emit_fatal, validate_attr};
7+
use rustc_parse::{exp, new_parser_from_file, unwrap_or_emit_fatal, validate_attr};
88
use rustc_session::Session;
99
use rustc_session::parse::ParseSess;
1010
use rustc_span::{Ident, Span, sym};
@@ -70,7 +70,7 @@ pub(crate) fn parse_external_mod(
7070
let mut parser =
7171
unwrap_or_emit_fatal(new_parser_from_file(&sess.psess, &mp.file_path, Some(span)));
7272
let (inner_attrs, items, inner_span) =
73-
parser.parse_mod(&token::Eof).map_err(|err| ModError::ParserError(err))?;
73+
parser.parse_mod(exp!(Eof)).map_err(|err| ModError::ParserError(err))?;
7474
attrs.extend(inner_attrs);
7575
(items, inner_span, mp.file_path)
7676
};

‎compiler/rustc_expand/src/proc_macro_server.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use rustc_data_structures::sync::Lrc;
1515
use rustc_errors::{Diag, ErrorGuaranteed, MultiSpan, PResult};
1616
use rustc_parse::lexer::nfc_normalize;
1717
use rustc_parse::parser::Parser;
18-
use rustc_parse::{new_parser_from_source_str, source_str_to_stream, unwrap_or_emit_fatal};
18+
use rustc_parse::{exp, new_parser_from_source_str, source_str_to_stream, unwrap_or_emit_fatal};
1919
use rustc_session::parse::ParseSess;
2020
use rustc_span::def_id::CrateNum;
2121
use rustc_span::{BytePos, FileName, Pos, SourceFile, Span, Symbol, sym};
@@ -473,7 +473,7 @@ impl server::FreeFunctions for Rustc<'_, '_> {
473473
unwrap_or_emit_fatal(new_parser_from_source_str(self.psess(), name, s.to_owned()));
474474

475475
let first_span = parser.token.span.data();
476-
let minus_present = parser.eat(&token::BinOp(token::Minus));
476+
let minus_present = parser.eat(exp!(Minus));
477477

478478
let lit_span = parser.token.span.data();
479479
let token::Literal(mut lit) = parser.token.kind else {

‎compiler/rustc_parse/src/parser/attr.rs

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
1-
use rustc_ast::token::{self, Delimiter};
2-
use rustc_ast::{self as ast, Attribute, attr};
1+
use rustc_ast::{self as ast, Attribute, attr, token};
32
use rustc_errors::codes::*;
43
use rustc_errors::{Diag, PResult};
5-
use rustc_span::{BytePos, Span, kw};
4+
use rustc_span::{BytePos, Span};
65
use thin_vec::ThinVec;
76
use tracing::debug;
87

98
use super::{
109
AttrWrapper, Capturing, FnParseMode, ForceCollect, Parser, ParserRange, PathStyle, Trailing,
1110
UsePreAttrPos,
1211
};
13-
use crate::{errors, fluent_generated as fluent, maybe_whole};
12+
use crate::{errors, exp, fluent_generated as fluent, maybe_whole};
1413

1514
// Public for rustfmt usage
1615
#[derive(Debug)]
@@ -45,7 +44,7 @@ impl<'a> Parser<'a> {
4544
let mut just_parsed_doc_comment = false;
4645
let start_pos = self.num_bump_calls;
4746
loop {
48-
let attr = if self.check(&token::Pound) {
47+
let attr = if self.check(exp!(Pound)) {
4948
let prev_outer_attr_sp = outer_attrs.last().map(|attr: &Attribute| attr.span);
5049

5150
let inner_error_reason = if just_parsed_doc_comment {
@@ -126,14 +125,14 @@ impl<'a> Parser<'a> {
126125
let lo = self.token.span;
127126
// Attributes can't have attributes of their own [Editor's note: not with that attitude]
128127
self.collect_tokens_no_attrs(|this| {
129-
assert!(this.eat(&token::Pound), "parse_attribute called in non-attribute position");
128+
assert!(this.eat(exp!(Pound)), "parse_attribute called in non-attribute position");
130129

131130
let style =
132-
if this.eat(&token::Not) { ast::AttrStyle::Inner } else { ast::AttrStyle::Outer };
131+
if this.eat(exp!(Not)) { ast::AttrStyle::Inner } else { ast::AttrStyle::Outer };
133132

134-
this.expect(&token::OpenDelim(Delimiter::Bracket))?;
133+
this.expect(exp!(OpenBracket))?;
135134
let item = this.parse_attr_item(ForceCollect::No)?;
136-
this.expect(&token::CloseDelim(Delimiter::Bracket))?;
135+
this.expect(exp!(CloseBracket))?;
137136
let attr_sp = lo.to(this.prev_token.span);
138137

139138
// Emit error if inner attribute is encountered and forbidden.
@@ -274,10 +273,10 @@ impl<'a> Parser<'a> {
274273

275274
// Attr items don't have attributes.
276275
self.collect_tokens(None, AttrWrapper::empty(), force_collect, |this, _empty_attrs| {
277-
let is_unsafe = this.eat_keyword(kw::Unsafe);
276+
let is_unsafe = this.eat_keyword(exp!(Unsafe));
278277
let unsafety = if is_unsafe {
279278
let unsafe_span = this.prev_token.span;
280-
this.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
279+
this.expect(exp!(OpenParen))?;
281280
ast::Safety::Unsafe(unsafe_span)
282281
} else {
283282
ast::Safety::Default
@@ -286,7 +285,7 @@ impl<'a> Parser<'a> {
286285
let path = this.parse_path(PathStyle::Mod)?;
287286
let args = this.parse_attr_args()?;
288287
if is_unsafe {
289-
this.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
288+
this.expect(exp!(CloseParen))?;
290289
}
291290
Ok((
292291
ast::AttrItem { unsafety, path, args, tokens: None },
@@ -306,7 +305,7 @@ impl<'a> Parser<'a> {
306305
loop {
307306
let start_pos = self.num_bump_calls;
308307
// Only try to parse if it is an inner attribute (has `!`).
309-
let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
308+
let attr = if self.check(exp!(Pound)) && self.look_ahead(1, |t| t == &token::Not) {
310309
Some(self.parse_attribute(InnerAttrPolicy::Permitted)?)
311310
} else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
312311
if attr_style == ast::AttrStyle::Inner {
@@ -358,15 +357,15 @@ impl<'a> Parser<'a> {
358357
&mut self,
359358
) -> PResult<'a, (ast::MetaItemInner, Vec<(ast::AttrItem, Span)>)> {
360359
let cfg_predicate = self.parse_meta_item_inner()?;
361-
self.expect(&token::Comma)?;
360+
self.expect(exp!(Comma))?;
362361

363362
// Presumably, the majority of the time there will only be one attr.
364363
let mut expanded_attrs = Vec::with_capacity(1);
365364
while self.token != token::Eof {
366365
let lo = self.token.span;
367366
let item = self.parse_attr_item(ForceCollect::Yes)?;
368367
expanded_attrs.push((item, lo.to(self.prev_token.span)));
369-
if !self.eat(&token::Comma) {
368+
if !self.eat(exp!(Comma)) {
370369
break;
371370
}
372371
}
@@ -380,7 +379,7 @@ impl<'a> Parser<'a> {
380379
let mut nmis = ThinVec::with_capacity(1);
381380
while self.token != token::Eof {
382381
nmis.push(self.parse_meta_item_inner()?);
383-
if !self.eat(&token::Comma) {
382+
if !self.eat(exp!(Comma)) {
384383
break;
385384
}
386385
}
@@ -413,13 +412,13 @@ impl<'a> Parser<'a> {
413412

414413
let lo = self.token.span;
415414
let is_unsafe = if unsafe_allowed == AllowLeadingUnsafe::Yes {
416-
self.eat_keyword(kw::Unsafe)
415+
self.eat_keyword(exp!(Unsafe))
417416
} else {
418417
false
419418
};
420419
let unsafety = if is_unsafe {
421420
let unsafe_span = self.prev_token.span;
422-
self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
421+
self.expect(exp!(OpenParen))?;
423422

424423
ast::Safety::Unsafe(unsafe_span)
425424
} else {
@@ -429,17 +428,17 @@ impl<'a> Parser<'a> {
429428
let path = self.parse_path(PathStyle::Mod)?;
430429
let kind = self.parse_meta_item_kind()?;
431430
if is_unsafe {
432-
self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
431+
self.expect(exp!(CloseParen))?;
433432
}
434433
let span = lo.to(self.prev_token.span);
435434

436435
Ok(ast::MetaItem { unsafety, path, kind, span })
437436
}
438437

439438
pub(crate) fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
440-
Ok(if self.eat(&token::Eq) {
439+
Ok(if self.eat(exp!(Eq)) {
441440
ast::MetaItemKind::NameValue(self.parse_unsuffixed_meta_item_lit()?)
442-
} else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
441+
} else if self.check(exp!(OpenParen)) {
443442
let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
444443
ast::MetaItemKind::List(list)
445444
} else {

‎compiler/rustc_parse/src/parser/diagnostics.rs

Lines changed: 61 additions & 95 deletions
Large diffs are not rendered by default.

‎compiler/rustc_parse/src/parser/expr.rs

Lines changed: 151 additions & 157 deletions
Large diffs are not rendered by default.

‎compiler/rustc_parse/src/parser/generics.rs

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use crate::errors::{
1313
UnexpectedSelfInGenericParameters, WhereClauseBeforeTupleStructBody,
1414
WhereClauseBeforeTupleStructBodySugg,
1515
};
16+
use crate::exp;
1617

1718
enum PredicateKindOrStructBody {
1819
PredicateKind(ast::WherePredicateKind),
@@ -52,7 +53,7 @@ impl<'a> Parser<'a> {
5253

5354
// Parse optional colon and param bounds.
5455
let mut colon_span = None;
55-
let bounds = if self.eat(&token::Colon) {
56+
let bounds = if self.eat(exp!(Colon)) {
5657
colon_span = Some(self.prev_token.span);
5758
// recover from `impl Trait` in type param bound
5859
if self.token.is_keyword(kw::Impl) {
@@ -89,7 +90,7 @@ impl<'a> Parser<'a> {
8990
Vec::new()
9091
};
9192

92-
let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
93+
let default = if self.eat(exp!(Eq)) { Some(self.parse_ty()?) } else { None };
9394
Ok(GenericParam {
9495
ident,
9596
id: ast::DUMMY_NODE_ID,
@@ -107,13 +108,13 @@ impl<'a> Parser<'a> {
107108
) -> PResult<'a, GenericParam> {
108109
let const_span = self.token.span;
109110

110-
self.expect_keyword(kw::Const)?;
111+
self.expect_keyword(exp!(Const))?;
111112
let ident = self.parse_ident()?;
112-
self.expect(&token::Colon)?;
113+
self.expect(exp!(Colon))?;
113114
let ty = self.parse_ty()?;
114115

115116
// Parse optional const generics default value.
116-
let default = if self.eat(&token::Eq) { Some(self.parse_const_arg()?) } else { None };
117+
let default = if self.eat(exp!(Eq)) { Some(self.parse_const_arg()?) } else { None };
117118

118119
Ok(GenericParam {
119120
ident,
@@ -132,11 +133,11 @@ impl<'a> Parser<'a> {
132133
mistyped_const_ident: Ident,
133134
) -> PResult<'a, GenericParam> {
134135
let ident = self.parse_ident()?;
135-
self.expect(&token::Colon)?;
136+
self.expect(exp!(Colon))?;
136137
let ty = self.parse_ty()?;
137138

138139
// Parse optional const generics default value.
139-
let default = if self.eat(&token::Eq) { Some(self.parse_const_arg()?) } else { None };
140+
let default = if self.eat(exp!(Eq)) { Some(self.parse_const_arg()?) } else { None };
140141

141142
self.dcx()
142143
.struct_span_err(
@@ -177,13 +178,13 @@ impl<'a> Parser<'a> {
177178
.emit_err(UnexpectedSelfInGenericParameters { span: this.prev_token.span });
178179

179180
// Eat a trailing comma, if it exists.
180-
let _ = this.eat(&token::Comma);
181+
let _ = this.eat(exp!(Comma));
181182
}
182183

183184
let param = if this.check_lifetime() {
184185
let lifetime = this.expect_lifetime();
185186
// Parse lifetime parameter.
186-
let (colon_span, bounds) = if this.eat(&token::Colon) {
187+
let (colon_span, bounds) = if this.eat(exp!(Colon)) {
187188
(Some(this.prev_token.span), this.parse_lt_param_bounds())
188189
} else {
189190
(None, Vec::new())
@@ -209,7 +210,7 @@ impl<'a> Parser<'a> {
209210
is_placeholder: false,
210211
colon_span,
211212
})
212-
} else if this.check_keyword(kw::Const) {
213+
} else if this.check_keyword(exp!(Const)) {
213214
// Parse const parameter.
214215
Some(this.parse_const_param(attrs)?)
215216
} else if this.check_ident() {
@@ -246,7 +247,7 @@ impl<'a> Parser<'a> {
246247
return Ok((None, Trailing::No, UsePreAttrPos::No));
247248
};
248249

249-
if !this.eat(&token::Comma) {
250+
if !this.eat(exp!(Comma)) {
250251
done = true;
251252
}
252253
// We just ate the comma, so no need to capture the trailing token.
@@ -324,7 +325,7 @@ impl<'a> Parser<'a> {
324325
};
325326
let mut tuple_struct_body = None;
326327

327-
if !self.eat_keyword(kw::Where) {
328+
if !self.eat_keyword(exp!(Where)) {
328329
return Ok((where_clause, None));
329330
}
330331
where_clause.has_where_token = true;
@@ -344,7 +345,7 @@ impl<'a> Parser<'a> {
344345
let kind = if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
345346
let lifetime = self.expect_lifetime();
346347
// Bounds starting with a colon are mandatory, but possibly empty.
347-
self.expect(&token::Colon)?;
348+
self.expect(exp!(Colon))?;
348349
let bounds = self.parse_lt_param_bounds();
349350
ast::WherePredicateKind::RegionPredicate(ast::WhereRegionPredicate {
350351
lifetime,
@@ -370,7 +371,7 @@ impl<'a> Parser<'a> {
370371
});
371372

372373
let prev_token = self.prev_token.span;
373-
let ate_comma = self.eat(&token::Comma);
374+
let ate_comma = self.eat(exp!(Comma));
374375

375376
if self.eat_keyword_noexpect(kw::Where) {
376377
self.dcx().emit_err(MultipleWhereClauses {
@@ -464,7 +465,7 @@ impl<'a> Parser<'a> {
464465
// Parse type with mandatory colon and (possibly empty) bounds,
465466
// or with mandatory equality sign and the second type.
466467
let ty = self.parse_ty_for_where_clause()?;
467-
if self.eat(&token::Colon) {
468+
if self.eat(exp!(Colon)) {
468469
let bounds = self.parse_generic_bounds()?;
469470
Ok(ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
470471
bound_generic_params: lifetime_defs,
@@ -473,7 +474,7 @@ impl<'a> Parser<'a> {
473474
}))
474475
// FIXME: Decide what should be used here, `=` or `==`.
475476
// FIXME: We are just dropping the binders in lifetime_defs on the floor here.
476-
} else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
477+
} else if self.eat(exp!(Eq)) || self.eat(exp!(EqEq)) {
477478
let rhs_ty = self.parse_ty()?;
478479
Ok(ast::WherePredicateKind::EqPredicate(ast::WhereEqPredicate { lhs_ty: ty, rhs_ty }))
479480
} else {

‎compiler/rustc_parse/src/parser/item.rs

Lines changed: 191 additions & 181 deletions
Large diffs are not rendered by default.

‎compiler/rustc_parse/src/parser/mod.rs

Lines changed: 136 additions & 169 deletions
Large diffs are not rendered by default.

‎compiler/rustc_parse/src/parser/pat.rs

Lines changed: 39 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use crate::errors::{
3030
UnexpectedVertVertInPattern, WrapInParens,
3131
};
3232
use crate::parser::expr::{DestructuredFloat, could_be_unclosed_char_literal};
33-
use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
33+
use crate::{exp, maybe_recover_from_interpolated_ty_qpath, maybe_whole};
3434

3535
#[derive(PartialEq, Copy, Clone)]
3636
pub enum Expected {
@@ -110,7 +110,7 @@ impl<'a> Parser<'a> {
110110
) -> PResult<'a, P<Pat>> {
111111
let pat = self.parse_pat_no_top_guard(expected, rc, ra, rt)?;
112112

113-
if self.eat_keyword(kw::If) {
113+
if self.eat_keyword(exp!(If)) {
114114
let cond = self.parse_expr()?;
115115
// Feature-gate guard patterns
116116
self.psess.gated_spans.gate(sym::guard_patterns, cond.span);
@@ -193,7 +193,7 @@ impl<'a> Parser<'a> {
193193

194194
// If the next token is not a `|`,
195195
// this is not an or-pattern and we should exit here.
196-
if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
196+
if !self.check(exp!(Or)) && self.token != token::OrOr {
197197
// If we parsed a leading `|` which should be gated,
198198
// then we should really gate the leading `|`.
199199
// This complicated procedure is done purely for diagnostics UX.
@@ -263,7 +263,7 @@ impl<'a> Parser<'a> {
263263
CommaRecoveryMode::LikelyTuple,
264264
Some(syntax_loc),
265265
)?;
266-
let colon = self.eat(&token::Colon);
266+
let colon = self.eat(exp!(Colon));
267267

268268
if let PatKind::Or(pats) = &pat.kind {
269269
let span = pat.span;
@@ -327,7 +327,7 @@ impl<'a> Parser<'a> {
327327
self.dcx().emit_err(UnexpectedVertVertInPattern { span: self.token.span, start: lo });
328328
self.bump();
329329
EatOrResult::AteOr
330-
} else if self.eat(&token::BinOp(token::Or)) {
330+
} else if self.eat(exp!(Or)) {
331331
EatOrResult::AteOr
332332
} else {
333333
EatOrResult::None
@@ -714,40 +714,41 @@ impl<'a> Parser<'a> {
714714
lo = self.token.span;
715715
}
716716

717-
let pat = if self.check(&token::BinOp(token::And)) || self.token == token::AndAnd {
717+
let pat = if self.check(exp!(And)) || self.token == token::AndAnd {
718718
self.parse_pat_deref(expected)?
719-
} else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
719+
} else if self.check(exp!(OpenParen)) {
720720
self.parse_pat_tuple_or_parens()?
721-
} else if self.check(&token::OpenDelim(Delimiter::Bracket)) {
721+
} else if self.check(exp!(OpenBracket)) {
722722
// Parse `[pat, pat,...]` as a slice pattern.
723-
let (pats, _) = self.parse_delim_comma_seq(Delimiter::Bracket, |p| {
724-
p.parse_pat_allow_top_guard(
725-
None,
726-
RecoverComma::No,
727-
RecoverColon::No,
728-
CommaRecoveryMode::EitherTupleOrPipe,
729-
)
730-
})?;
723+
let (pats, _) =
724+
self.parse_delim_comma_seq(exp!(OpenBracket), exp!(CloseBracket), |p| {
725+
p.parse_pat_allow_top_guard(
726+
None,
727+
RecoverComma::No,
728+
RecoverColon::No,
729+
CommaRecoveryMode::EitherTupleOrPipe,
730+
)
731+
})?;
731732
PatKind::Slice(pats)
732-
} else if self.check(&token::DotDot) && !self.is_pat_range_end_start(1) {
733+
} else if self.check(exp!(DotDot)) && !self.is_pat_range_end_start(1) {
733734
// A rest pattern `..`.
734735
self.bump(); // `..`
735736
PatKind::Rest
736-
} else if self.check(&token::DotDotDot) && !self.is_pat_range_end_start(1) {
737+
} else if self.check(exp!(DotDotDot)) && !self.is_pat_range_end_start(1) {
737738
self.recover_dotdotdot_rest_pat(lo)
738739
} else if let Some(form) = self.parse_range_end() {
739740
self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`.
740-
} else if self.eat(&token::Not) {
741+
} else if self.eat(exp!(Not)) {
741742
// Parse `!`
742743
self.psess.gated_spans.gate(sym::never_patterns, self.prev_token.span);
743744
PatKind::Never
744-
} else if self.eat_keyword(kw::Underscore) {
745+
} else if self.eat_keyword(exp!(Underscore)) {
745746
// Parse `_`
746747
PatKind::Wild
747-
} else if self.eat_keyword(kw::Mut) {
748+
} else if self.eat_keyword(exp!(Mut)) {
748749
self.parse_pat_ident_mut()?
749-
} else if self.eat_keyword(kw::Ref) {
750-
if self.check_keyword(kw::Box) {
750+
} else if self.eat_keyword(exp!(Ref)) {
751+
if self.check_keyword(exp!(Box)) {
751752
// Suggest `box ref`.
752753
let span = self.prev_token.span.to(self.token.span);
753754
self.bump();
@@ -756,7 +757,7 @@ impl<'a> Parser<'a> {
756757
// Parse ref ident @ pat / ref mut ident @ pat
757758
let mutbl = self.parse_mutability();
758759
self.parse_pat_ident(BindingMode(ByRef::Yes(mutbl), Mutability::Not), syntax_loc)?
759-
} else if self.eat_keyword(kw::Box) {
760+
} else if self.eat_keyword(exp!(Box)) {
760761
self.parse_pat_box()?
761762
} else if self.check_inline_const(0) {
762763
// Parse `const pat`
@@ -793,14 +794,14 @@ impl<'a> Parser<'a> {
793794
};
794795
let span = lo.to(self.prev_token.span);
795796

796-
if qself.is_none() && self.check(&token::Not) {
797+
if qself.is_none() && self.check(exp!(Not)) {
797798
self.parse_pat_mac_invoc(path)?
798799
} else if let Some(form) = self.parse_range_end() {
799800
let begin = self.mk_expr(span, ExprKind::Path(qself, path));
800801
self.parse_pat_range_begin_with(begin, form)?
801-
} else if self.check(&token::OpenDelim(Delimiter::Brace)) {
802+
} else if self.check(exp!(OpenBrace)) {
802803
self.parse_pat_struct(qself, path)?
803-
} else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
804+
} else if self.check(exp!(OpenParen)) {
804805
self.parse_pat_tuple_struct(qself, path)?
805806
} else {
806807
match self.maybe_recover_trailing_expr(span, false) {
@@ -1106,7 +1107,7 @@ impl<'a> Parser<'a> {
11061107
/// Eat any extraneous `mut`s and error + recover if we ate any.
11071108
fn recover_additional_muts(&mut self) {
11081109
let lo = self.token.span;
1109-
while self.eat_keyword(kw::Mut) {}
1110+
while self.eat_keyword(exp!(Mut)) {}
11101111
if lo == self.token.span {
11111112
return;
11121113
}
@@ -1147,11 +1148,11 @@ impl<'a> Parser<'a> {
11471148

11481149
/// Parses the range pattern end form `".." | "..." | "..=" ;`.
11491150
fn parse_range_end(&mut self) -> Option<Spanned<RangeEnd>> {
1150-
let re = if self.eat(&token::DotDotDot) {
1151+
let re = if self.eat(exp!(DotDotDot)) {
11511152
RangeEnd::Included(RangeSyntax::DotDotDot)
1152-
} else if self.eat(&token::DotDotEq) {
1153+
} else if self.eat(exp!(DotDotEq)) {
11531154
RangeEnd::Included(RangeSyntax::DotDotEq)
1154-
} else if self.eat(&token::DotDot) {
1155+
} else if self.eat(exp!(DotDot)) {
11551156
RangeEnd::Excluded
11561157
} else {
11571158
return None;
@@ -1271,7 +1272,7 @@ impl<'a> Parser<'a> {
12711272

12721273
// recover trailing `)`
12731274
if let Some(open_paren) = open_paren {
1274-
self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
1275+
self.expect(exp!(CloseParen))?;
12751276

12761277
self.dcx().emit_err(UnexpectedParenInRangePat {
12771278
span: vec![open_paren, self.prev_token.span],
@@ -1331,7 +1332,7 @@ impl<'a> Parser<'a> {
13311332
}));
13321333
}
13331334

1334-
let sub = if self.eat(&token::At) {
1335+
let sub = if self.eat(exp!(At)) {
13351336
Some(self.parse_pat_no_top_alt(Some(Expected::BindingPattern), None)?)
13361337
} else {
13371338
None
@@ -1447,7 +1448,7 @@ impl<'a> Parser<'a> {
14471448

14481449
// We cannot use `parse_pat_ident()` since it will complain `box`
14491450
// is not an identifier.
1450-
let sub = if self.eat(&token::At) {
1451+
let sub = if self.eat(exp!(At)) {
14511452
Some(self.parse_pat_no_top_alt(Some(Expected::BindingPattern), None)?)
14521453
} else {
14531454
None
@@ -1504,9 +1505,9 @@ impl<'a> Parser<'a> {
15041505
}
15051506
ate_comma = false;
15061507

1507-
if self.check(&token::DotDot)
1508+
if self.check(exp!(DotDot))
15081509
|| self.check_noexpect(&token::DotDotDot)
1509-
|| self.check_keyword(kw::Underscore)
1510+
|| self.check_keyword(exp!(Underscore))
15101511
{
15111512
etc = PatFieldsRest::Rest;
15121513
let mut etc_sp = self.token.span;
@@ -1594,7 +1595,7 @@ impl<'a> Parser<'a> {
15941595
return Err(err);
15951596
}
15961597
}?;
1597-
ate_comma = this.eat(&token::Comma);
1598+
ate_comma = this.eat(exp!(Comma));
15981599

15991600
last_non_comma_dotdot_span = Some(this.prev_token.span);
16001601

@@ -1706,7 +1707,7 @@ impl<'a> Parser<'a> {
17061707
(pat, fieldname, false)
17071708
} else {
17081709
// Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
1709-
let is_box = self.eat_keyword(kw::Box);
1710+
let is_box = self.eat_keyword(exp!(Box));
17101711
let boxed_span = self.token.span;
17111712
let mutability = self.parse_mutability();
17121713
let by_ref = self.parse_byref();

‎compiler/rustc_parse/src/parser/path.rs

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
1717
use super::{Parser, Restrictions, TokenType};
1818
use crate::errors::{PathSingleColon, PathTripleColon};
1919
use crate::parser::{CommaRecoveryMode, RecoverColon, RecoverComma};
20-
use crate::{errors, maybe_whole};
20+
use crate::{errors, exp, maybe_whole};
2121

2222
/// Specifies how to parse a path.
2323
#[derive(Copy, Clone, PartialEq)]
@@ -80,7 +80,7 @@ impl<'a> Parser<'a> {
8080
// above). `path_span` has the span of that path, or an empty
8181
// span in the case of something like `<T>::Bar`.
8282
let (mut path, path_span);
83-
if self.eat_keyword(kw::As) {
83+
if self.eat_keyword(exp!(As)) {
8484
let path_lo = self.token.span;
8585
path = self.parse_path(PathStyle::Type)?;
8686
path_span = path_lo.to(self.prev_token.span);
@@ -90,15 +90,15 @@ impl<'a> Parser<'a> {
9090
}
9191

9292
// See doc comment for `unmatched_angle_bracket_count`.
93-
self.expect(&token::Gt)?;
93+
self.expect(exp!(Gt))?;
9494
if self.unmatched_angle_bracket_count > 0 {
9595
self.unmatched_angle_bracket_count -= 1;
9696
debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
9797
}
9898

9999
let is_import_coupler = self.is_import_coupler();
100100
if !is_import_coupler && !self.recover_colon_before_qpath_proj() {
101-
self.expect(&token::PathSep)?;
101+
self.expect(exp!(PathSep))?;
102102
}
103103

104104
let qself = P(QSelf { ty, path_span, position: path.segments.len() });
@@ -242,7 +242,7 @@ impl<'a> Parser<'a> {
242242
// `PathStyle::Expr` is only provided at the root invocation and never in
243243
// `parse_path_segment` to recurse and therefore can be checked to maintain
244244
// this invariant.
245-
self.check_trailing_angle_brackets(&segment, &[&token::PathSep]);
245+
self.check_trailing_angle_brackets(&segment, &[exp!(PathSep)]);
246246
}
247247
segments.push(segment);
248248

@@ -275,7 +275,7 @@ impl<'a> Parser<'a> {
275275
/// Eat `::` or, potentially, `:::`.
276276
#[must_use]
277277
pub(super) fn eat_path_sep(&mut self) -> bool {
278-
let result = self.eat(&token::PathSep);
278+
let result = self.eat(exp!(PathSep));
279279
if result && self.may_recover() {
280280
if self.eat_noexpect(&token::Colon) {
281281
self.dcx().emit_err(PathTripleColon { span: self.prev_token.span });
@@ -300,10 +300,8 @@ impl<'a> Parser<'a> {
300300
)
301301
};
302302
let check_args_start = |this: &mut Self| {
303-
this.expected_tokens.extend_from_slice(&[
304-
TokenType::Token(token::Lt),
305-
TokenType::Token(token::OpenDelim(Delimiter::Parenthesis)),
306-
]);
303+
this.expected_token_types.insert(TokenType::Lt);
304+
this.expected_token_types.insert(TokenType::OpenParen);
307305
is_args_start(&this.token)
308306
};
309307

@@ -367,7 +365,7 @@ impl<'a> Parser<'a> {
367365
{
368366
self.bump(); // (
369367
self.bump(); // ..
370-
self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
368+
self.expect(exp!(CloseParen))?;
371369
let span = lo.to(self.prev_token.span);
372370

373371
self.psess.gated_spans.gate(sym::return_type_notation, span);
@@ -661,12 +659,12 @@ impl<'a> Parser<'a> {
661659
let mut args = ThinVec::new();
662660
while let Some(arg) = self.parse_angle_arg(ty_generics)? {
663661
args.push(arg);
664-
if !self.eat(&token::Comma) {
662+
if !self.eat(exp!(Comma)) {
665663
if self.check_noexpect(&TokenKind::Semi)
666664
&& self.look_ahead(1, |t| t.is_ident() || t.is_lifetime())
667665
{
668666
// Add `>` to the list of expected tokens.
669-
self.check(&token::Gt);
667+
self.check(exp!(Gt));
670668
// Handle `,` to `;` substitution
671669
let mut err = self.unexpected().unwrap_err();
672670
self.bump();
@@ -705,7 +703,7 @@ impl<'a> Parser<'a> {
705703
// is present and then use that info to push the other token onto the tokens list
706704
let separated =
707705
self.check_noexpect(&token::Colon) || self.check_noexpect(&token::Eq);
708-
if separated && (self.check(&token::Colon) | self.check(&token::Eq)) {
706+
if separated && (self.check(exp!(Colon)) | self.check(exp!(Eq))) {
709707
let arg_span = arg.span();
710708
let (binder, ident, gen_args) = match self.get_ident_from_generic_arg(&arg) {
711709
Ok(ident_gen_args) => ident_gen_args,
@@ -720,9 +718,9 @@ impl<'a> Parser<'a> {
720718
"`for<...>` is not allowed on associated type bounds",
721719
));
722720
}
723-
let kind = if self.eat(&token::Colon) {
721+
let kind = if self.eat(exp!(Colon)) {
724722
AssocItemConstraintKind::Bound { bounds: self.parse_generic_bounds()? }
725-
} else if self.eat(&token::Eq) {
723+
} else if self.eat(exp!(Eq)) {
726724
self.parse_assoc_equality_term(
727725
ident,
728726
gen_args.as_ref(),
@@ -743,8 +741,8 @@ impl<'a> Parser<'a> {
743741
if self.prev_token.is_ident()
744742
&& (self.token.is_ident() || self.look_ahead(1, |token| token.is_ident()))
745743
{
746-
self.check(&token::Colon);
747-
self.check(&token::Eq);
744+
self.check(exp!(Colon));
745+
self.check(exp!(Eq));
748746
}
749747
Ok(Some(AngleBracketedArg::Arg(arg)))
750748
}

‎compiler/rustc_parse/src/parser/stmt.rs

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use super::{
2424
Trailing, UsePreAttrPos,
2525
};
2626
use crate::errors::MalformedLoopLabel;
27-
use crate::{errors, maybe_whole};
27+
use crate::{errors, exp, maybe_whole};
2828

2929
impl<'a> Parser<'a> {
3030
/// Parses a statement. This stops just before trailing semicolons on everything but items.
@@ -71,7 +71,7 @@ impl<'a> Parser<'a> {
7171

7272
let stmt = if self.token.is_keyword(kw::Let) {
7373
self.collect_tokens(None, attrs, force_collect, |this, attrs| {
74-
this.expect_keyword(kw::Let)?;
74+
this.expect_keyword(exp!(Let))?;
7575
let local = this.parse_local(attrs)?;
7676
let trailing = Trailing::from(capture_semi && this.token == token::Semi);
7777
Ok((
@@ -140,7 +140,7 @@ impl<'a> Parser<'a> {
140140
force_collect,
141141
)? {
142142
self.mk_stmt(lo.to(item.span), StmtKind::Item(P(item)))
143-
} else if self.eat(&token::Semi) {
143+
} else if self.eat(exp!(Semi)) {
144144
// Do not attempt to parse an expression if we're done here.
145145
self.error_outer_attrs(attrs);
146146
self.mk_stmt(lo, StmtKind::Empty)
@@ -156,7 +156,7 @@ impl<'a> Parser<'a> {
156156
Ok((expr, Trailing::No, UsePreAttrPos::Yes))
157157
},
158158
)?;
159-
if matches!(e.kind, ExprKind::Assign(..)) && self.eat_keyword(kw::Else) {
159+
if matches!(e.kind, ExprKind::Assign(..)) && self.eat_keyword(exp!(Else)) {
160160
let bl = self.parse_block()?;
161161
// Destructuring assignment ... else.
162162
// This is not allowed, but point it out in a nice way.
@@ -176,7 +176,7 @@ impl<'a> Parser<'a> {
176176
let stmt = self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
177177
let path = this.parse_path(PathStyle::Expr)?;
178178

179-
if this.eat(&token::Not) {
179+
if this.eat(exp!(Not)) {
180180
let stmt_mac = this.parse_stmt_mac(lo, attrs, path)?;
181181
return Ok((
182182
stmt_mac,
@@ -185,7 +185,7 @@ impl<'a> Parser<'a> {
185185
));
186186
}
187187

188-
let expr = if this.eat(&token::OpenDelim(Delimiter::Brace)) {
188+
let expr = if this.eat(exp!(OpenBrace)) {
189189
this.parse_expr_struct(None, path, true)?
190190
} else {
191191
let hi = this.prev_token.span;
@@ -370,7 +370,7 @@ impl<'a> Parser<'a> {
370370
let kind = match init {
371371
None => LocalKind::Decl,
372372
Some(init) => {
373-
if self.eat_keyword(kw::Else) {
373+
if self.eat_keyword(exp!(Else)) {
374374
if self.token.is_keyword(kw::If) {
375375
// `let...else if`. Emit the same error that `parse_block()` would,
376376
// but explicitly point out that this pattern is not allowed.
@@ -449,7 +449,7 @@ impl<'a> Parser<'a> {
449449
self.bump();
450450
true
451451
}
452-
_ => self.eat(&token::Eq),
452+
_ => self.eat(exp!(Eq)),
453453
};
454454

455455
Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None })
@@ -509,7 +509,7 @@ impl<'a> Parser<'a> {
509509
Ok(Some(Stmt { kind: StmtKind::Empty, .. })) => {}
510510
Ok(Some(stmt)) => {
511511
let stmt_own_line = self.psess.source_map().is_line_before_span_empty(sp);
512-
let stmt_span = if stmt_own_line && self.eat(&token::Semi) {
512+
let stmt_span = if stmt_own_line && self.eat(exp!(Semi)) {
513513
// Expand the span to include the semicolon.
514514
stmt.span.with_hi(self.prev_token.span.hi())
515515
} else {
@@ -651,7 +651,7 @@ impl<'a> Parser<'a> {
651651

652652
let maybe_ident = self.prev_token.clone();
653653
self.maybe_recover_unexpected_block_label();
654-
if !self.eat(&token::OpenDelim(Delimiter::Brace)) {
654+
if !self.eat(exp!(OpenBrace)) {
655655
return self.error_block_no_opening_brace();
656656
}
657657

@@ -678,7 +678,7 @@ impl<'a> Parser<'a> {
678678
) -> PResult<'a, P<Block>> {
679679
let mut stmts = ThinVec::new();
680680
let mut snapshot = None;
681-
while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
681+
while !self.eat(exp!(CloseBrace)) {
682682
if self.token == token::Eof {
683683
break;
684684
}
@@ -781,8 +781,7 @@ impl<'a> Parser<'a> {
781781
{
782782
// Just check for errors and recover; do not eat semicolon yet.
783783

784-
let expect_result =
785-
self.expect_one_of(&[], &[token::Semi, token::CloseDelim(Delimiter::Brace)]);
784+
let expect_result = self.expect_one_of(&[], &[exp!(Semi), exp!(CloseBrace)]);
786785

787786
// Try to both emit a better diagnostic, and avoid further errors by replacing
788787
// the `expr` with `ExprKind::Err`.
@@ -930,7 +929,7 @@ impl<'a> Parser<'a> {
930929
}
931930
}
932931

933-
if add_semi_to_stmt || (eat_semi && self.eat(&token::Semi)) {
932+
if add_semi_to_stmt || (eat_semi && self.eat(exp!(Semi))) {
934933
stmt = stmt.add_trailing_semicolon();
935934
}
936935

‎compiler/rustc_parse/src/parser/token_type.rs

Lines changed: 631 additions & 0 deletions
Large diffs are not rendered by default.

‎compiler/rustc_parse/src/parser/ty.rs

Lines changed: 46 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate::errors::{
1818
HelpUseLatestEdition, InvalidDynKeyword, LifetimeAfterMut, NeedPlusAfterTraitObjectLifetime,
1919
NestedCVariadicType, ReturnTypesUseThinArrow,
2020
};
21-
use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
21+
use crate::{exp, maybe_recover_from_interpolated_ty_qpath, maybe_whole};
2222

2323
/// Signals whether parsing a type should allow `+`.
2424
///
@@ -203,7 +203,7 @@ impl<'a> Parser<'a> {
203203
recover_return_sign: RecoverReturnSign,
204204
) -> PResult<'a, FnRetTy> {
205205
let lo = self.prev_token.span;
206-
Ok(if self.eat(&token::RArrow) {
206+
Ok(if self.eat(exp!(RArrow)) {
207207
// FIXME(Centril): Can we unconditionally `allow_plus`?
208208
let ty = self.parse_ty_common(
209209
allow_plus,
@@ -251,28 +251,28 @@ impl<'a> Parser<'a> {
251251

252252
let lo = self.token.span;
253253
let mut impl_dyn_multi = false;
254-
let kind = if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
254+
let kind = if self.check(exp!(OpenParen)) {
255255
self.parse_ty_tuple_or_parens(lo, allow_plus)?
256-
} else if self.eat(&token::Not) {
256+
} else if self.eat(exp!(Not)) {
257257
// Never type `!`
258258
TyKind::Never
259-
} else if self.eat(&token::BinOp(token::Star)) {
259+
} else if self.eat(exp!(Star)) {
260260
self.parse_ty_ptr()?
261-
} else if self.eat(&token::OpenDelim(Delimiter::Bracket)) {
261+
} else if self.eat(exp!(OpenBracket)) {
262262
self.parse_array_or_slice_ty()?
263-
} else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
263+
} else if self.check(exp!(And)) || self.check(exp!(AndAnd)) {
264264
// Reference
265265
self.expect_and()?;
266266
self.parse_borrowed_pointee()?
267267
} else if self.eat_keyword_noexpect(kw::Typeof) {
268268
self.parse_typeof_ty()?
269-
} else if self.eat_keyword(kw::Underscore) {
269+
} else if self.eat_keyword(exp!(Underscore)) {
270270
// A type to be inferred `_`
271271
TyKind::Infer
272272
} else if self.check_fn_front_matter(false, Case::Sensitive) {
273273
// Function pointer type
274274
self.parse_ty_bare_fn(lo, ThinVec::new(), None, recover_return_sign)?
275-
} else if self.check_keyword(kw::For) {
275+
} else if self.check_keyword(exp!(For)) {
276276
// Function pointer type or bound list (trait object type) starting with a poly-trait.
277277
// `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
278278
// `for<'lt> Trait1<'lt> + Trait2 + 'a`
@@ -324,7 +324,7 @@ impl<'a> Parser<'a> {
324324
self.parse_remaining_bounds_path(lifetime_defs, path, lo, parse_plus)?
325325
}
326326
}
327-
} else if self.eat_keyword(kw::Impl) {
327+
} else if self.eat_keyword(exp!(Impl)) {
328328
self.parse_impl_ty(&mut impl_dyn_multi)?
329329
} else if self.is_explicit_dyn_type() {
330330
self.parse_dyn_ty(&mut impl_dyn_multi)?
@@ -336,7 +336,7 @@ impl<'a> Parser<'a> {
336336
self.parse_path_start_ty(lo, allow_plus, ty_generics)?
337337
} else if self.can_begin_bound() {
338338
self.parse_bare_trait_object(lo, allow_plus)?
339-
} else if self.eat(&token::DotDotDot) {
339+
} else if self.eat(exp!(DotDotDot)) {
340340
match allow_c_variadic {
341341
AllowCVariadic::Yes => TyKind::CVarArgs,
342342
AllowCVariadic::No => {
@@ -347,7 +347,7 @@ impl<'a> Parser<'a> {
347347
TyKind::Err(guar)
348348
}
349349
}
350-
} else if self.check_keyword(kw::Unsafe)
350+
} else if self.check_keyword(exp!(Unsafe))
351351
&& self.look_ahead(1, |tok| matches!(tok.kind, token::Lt))
352352
{
353353
self.parse_unsafe_binder_ty()?
@@ -374,7 +374,7 @@ impl<'a> Parser<'a> {
374374

375375
fn parse_unsafe_binder_ty(&mut self) -> PResult<'a, TyKind> {
376376
let lo = self.token.span;
377-
assert!(self.eat_keyword(kw::Unsafe));
377+
assert!(self.eat_keyword(exp!(Unsafe)));
378378
self.expect_lt()?;
379379
let generic_params = self.parse_generic_params()?;
380380
self.expect_gt()?;
@@ -487,16 +487,16 @@ impl<'a> Parser<'a> {
487487
Err(err) => return Err(err),
488488
};
489489

490-
let ty = if self.eat(&token::Semi) {
490+
let ty = if self.eat(exp!(Semi)) {
491491
let mut length = self.parse_expr_anon_const()?;
492-
if let Err(e) = self.expect(&token::CloseDelim(Delimiter::Bracket)) {
492+
if let Err(e) = self.expect(exp!(CloseBracket)) {
493493
// Try to recover from `X<Y, ...>` when `X::<Y, ...>` works
494494
self.check_mistyped_turbofish_with_multiple_type_params(e, &mut length.value)?;
495-
self.expect(&token::CloseDelim(Delimiter::Bracket))?;
495+
self.expect(exp!(CloseBracket))?;
496496
}
497497
TyKind::Array(elt_ty, length)
498498
} else {
499-
self.expect(&token::CloseDelim(Delimiter::Bracket))?;
499+
self.expect(exp!(CloseBracket))?;
500500
TyKind::Slice(elt_ty)
501501
};
502502

@@ -579,9 +579,9 @@ impl<'a> Parser<'a> {
579579
// Parses the `typeof(EXPR)`.
580580
// To avoid ambiguity, the type is surrounded by parentheses.
581581
fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
582-
self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
582+
self.expect(exp!(OpenParen))?;
583583
let expr = self.parse_expr_anon_const()?;
584-
self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
584+
self.expect(exp!(CloseParen))?;
585585
Ok(TyKind::Typeof(expr))
586586
}
587587

@@ -697,15 +697,15 @@ impl<'a> Parser<'a> {
697697
let lo = self.token.span;
698698
self.expect_lt()?;
699699
let (args, _, _) = self.parse_seq_to_before_tokens(
700-
&[&TokenKind::Gt],
700+
&[exp!(Gt)],
701701
&[
702702
&TokenKind::Ge,
703703
&TokenKind::BinOp(BinOpToken::Shr),
704704
&TokenKind::BinOpEq(BinOpToken::Shr),
705705
],
706-
SeqSep::trailing_allowed(token::Comma),
706+
SeqSep::trailing_allowed(exp!(Comma)),
707707
|self_| {
708-
if self_.check_keyword(kw::SelfUpper) {
708+
if self_.check_keyword(exp!(SelfUpper)) {
709709
self_.bump();
710710
Ok(PreciseCapturingArg::Arg(
711711
ast::Path::from_ident(self_.prev_token.ident().unwrap().0),
@@ -729,7 +729,7 @@ impl<'a> Parser<'a> {
729729

730730
/// Is a `dyn B0 + ... + Bn` type allowed here?
731731
fn is_explicit_dyn_type(&mut self) -> bool {
732-
self.check_keyword(kw::Dyn)
732+
self.check_keyword(exp!(Dyn))
733733
&& (self.token.uninterpolated_span().at_least_rust_2018()
734734
|| self.look_ahead(1, |t| {
735735
(can_begin_dyn_bound_in_edition_2015(t) || *t == TokenKind::BinOp(token::Star))
@@ -745,7 +745,7 @@ impl<'a> Parser<'a> {
745745
self.bump(); // `dyn`
746746

747747
// parse dyn* types
748-
let syntax = if self.eat(&TokenKind::BinOp(token::Star)) {
748+
let syntax = if self.eat(exp!(Star)) {
749749
self.psess.gated_spans.gate(sym::dyn_star, lo.to(self.prev_token.span));
750750
TraitObjectSyntax::DynStar
751751
} else {
@@ -772,7 +772,7 @@ impl<'a> Parser<'a> {
772772
) -> PResult<'a, TyKind> {
773773
// Simple path
774774
let path = self.parse_path_inner(PathStyle::Type, ty_generics)?;
775-
if self.eat(&token::Not) {
775+
if self.eat(exp!(Not)) {
776776
// Macro invocation in type position
777777
Ok(TyKind::MacCall(P(MacCall { path, args: self.parse_delim_args()? })))
778778
} else if allow_plus == AllowPlus::Yes && self.check_plus() {
@@ -825,14 +825,14 @@ impl<'a> Parser<'a> {
825825
fn can_begin_bound(&mut self) -> bool {
826826
self.check_path()
827827
|| self.check_lifetime()
828-
|| self.check(&token::Not)
829-
|| self.check(&token::Question)
830-
|| self.check(&token::Tilde)
831-
|| self.check_keyword(kw::For)
832-
|| self.check(&token::OpenDelim(Delimiter::Parenthesis))
833-
|| self.check_keyword(kw::Const)
834-
|| self.check_keyword(kw::Async)
835-
|| self.check_keyword(kw::Use)
828+
|| self.check(exp!(Not))
829+
|| self.check(exp!(Question))
830+
|| self.check(exp!(Tilde))
831+
|| self.check_keyword(exp!(For))
832+
|| self.check(exp!(OpenParen))
833+
|| self.check_keyword(exp!(Const))
834+
|| self.check_keyword(exp!(Async))
835+
|| self.check_keyword(exp!(Use))
836836
}
837837

838838
/// Parses a bound according to the grammar:
@@ -842,11 +842,11 @@ impl<'a> Parser<'a> {
842842
fn parse_generic_bound(&mut self) -> PResult<'a, GenericBound> {
843843
let lo = self.token.span;
844844
let leading_token = self.prev_token.clone();
845-
let has_parens = self.eat(&token::OpenDelim(Delimiter::Parenthesis));
845+
let has_parens = self.eat(exp!(OpenParen));
846846

847847
let bound = if self.token.is_lifetime() {
848848
self.parse_generic_lt_bound(lo, has_parens)?
849-
} else if self.eat_keyword(kw::Use) {
849+
} else if self.eat_keyword(exp!(Use)) {
850850
// parse precise captures, if any. This is `use<'lt, 'lt, P, P>`; a list of
851851
// lifetimes and ident params (including SelfUpper). These are validated later
852852
// for order, duplication, and whether they actually reference params.
@@ -919,7 +919,7 @@ impl<'a> Parser<'a> {
919919

920920
/// Recover on `('lifetime)` with `(` already eaten.
921921
fn recover_paren_lifetime(&mut self, lo: Span) -> PResult<'a, ()> {
922-
self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
922+
self.expect(exp!(CloseParen))?;
923923
let span = lo.to(self.prev_token.span);
924924
let sugg = errors::RemoveParens { lo, hi: self.prev_token.span };
925925

@@ -940,21 +940,21 @@ impl<'a> Parser<'a> {
940940
/// See `parse_generic_ty_bound` for the complete grammar of trait bound modifiers.
941941
fn parse_trait_bound_modifiers(&mut self) -> PResult<'a, TraitBoundModifiers> {
942942
let modifier_lo = self.token.span;
943-
let constness = if self.eat(&token::Tilde) {
943+
let constness = if self.eat(exp!(Tilde)) {
944944
let tilde = self.prev_token.span;
945-
self.expect_keyword(kw::Const)?;
945+
self.expect_keyword(exp!(Const))?;
946946
let span = tilde.to(self.prev_token.span);
947947
self.psess.gated_spans.gate(sym::const_trait_impl, span);
948948
BoundConstness::Maybe(span)
949-
} else if self.eat_keyword(kw::Const) {
949+
} else if self.eat_keyword(exp!(Const)) {
950950
self.psess.gated_spans.gate(sym::const_trait_impl, self.prev_token.span);
951951
BoundConstness::Always(self.prev_token.span)
952952
} else {
953953
BoundConstness::Never
954954
};
955955

956956
let asyncness = if self.token.uninterpolated_span().at_least_rust_2018()
957-
&& self.eat_keyword(kw::Async)
957+
&& self.eat_keyword(exp!(Async))
958958
{
959959
self.psess.gated_spans.gate(sym::async_trait_bounds, self.prev_token.span);
960960
BoundAsyncness::Async(self.prev_token.span)
@@ -974,9 +974,9 @@ impl<'a> Parser<'a> {
974974
};
975975
let modifier_hi = self.prev_token.span;
976976

977-
let polarity = if self.eat(&token::Question) {
977+
let polarity = if self.eat(exp!(Question)) {
978978
BoundPolarity::Maybe(self.prev_token.span)
979-
} else if self.eat(&token::Not) {
979+
} else if self.eat(exp!(Not)) {
980980
self.psess.gated_spans.gate(sym::negative_bounds, self.prev_token.span);
981981
BoundPolarity::Negative(self.prev_token.span)
982982
} else {
@@ -1122,7 +1122,7 @@ impl<'a> Parser<'a> {
11221122
if self.token.is_like_plus() && leading_token.is_keyword(kw::Dyn) {
11231123
let bounds = vec![];
11241124
self.parse_remaining_bounds(bounds, true)?;
1125-
self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
1125+
self.expect(exp!(CloseParen))?;
11261126
self.dcx().emit_err(errors::IncorrectParensTraitBounds {
11271127
span: vec![lo, self.prev_token.span],
11281128
sugg: errors::IncorrectParensTraitBoundsSugg {
@@ -1131,7 +1131,7 @@ impl<'a> Parser<'a> {
11311131
},
11321132
});
11331133
} else {
1134-
self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
1134+
self.expect(exp!(CloseParen))?;
11351135
}
11361136
}
11371137

@@ -1176,7 +1176,7 @@ impl<'a> Parser<'a> {
11761176
pub(super) fn parse_late_bound_lifetime_defs(
11771177
&mut self,
11781178
) -> PResult<'a, (ThinVec<GenericParam>, Option<Span>)> {
1179-
if self.eat_keyword(kw::For) {
1179+
if self.eat_keyword(exp!(For)) {
11801180
let lo = self.token.span;
11811181
self.expect_lt()?;
11821182
let params = self.parse_generic_params()?;
@@ -1280,7 +1280,7 @@ impl<'a> Parser<'a> {
12801280
}
12811281

12821282
pub(super) fn check_lifetime(&mut self) -> bool {
1283-
self.expected_tokens.push(TokenType::Lifetime);
1283+
self.expected_token_types.insert(TokenType::Lifetime);
12841284
self.token.is_lifetime()
12851285
}
12861286

‎src/tools/rustfmt/src/parse/macros/cfg_if.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::panic::{AssertUnwindSafe, catch_unwind};
22

33
use rustc_ast::ast;
44
use rustc_ast::token::{Delimiter, TokenKind};
5+
use rustc_parse::exp;
56
use rustc_parse::parser::ForceCollect;
67
use rustc_span::symbol::kw;
78

@@ -31,7 +32,7 @@ fn parse_cfg_if_inner<'a>(
3132

3233
while parser.token.kind != TokenKind::Eof {
3334
if process_if_cfg {
34-
if !parser.eat_keyword(kw::If) {
35+
if !parser.eat_keyword(exp!(If)) {
3536
return Err("Expected `if`");
3637
}
3738

@@ -55,7 +56,7 @@ fn parse_cfg_if_inner<'a>(
5556
})?;
5657
}
5758

58-
if !parser.eat(&TokenKind::OpenDelim(Delimiter::Brace)) {
59+
if !parser.eat(exp!(OpenBrace)) {
5960
return Err("Expected an opening brace");
6061
}
6162

@@ -78,15 +79,15 @@ fn parse_cfg_if_inner<'a>(
7879
}
7980
}
8081

81-
if !parser.eat(&TokenKind::CloseDelim(Delimiter::Brace)) {
82+
if !parser.eat(exp!(CloseBrace)) {
8283
return Err("Expected a closing brace");
8384
}
8485

85-
if parser.eat(&TokenKind::Eof) {
86+
if parser.eat(exp!(Eof)) {
8687
break;
8788
}
8889

89-
if !parser.eat_keyword(kw::Else) {
90+
if !parser.eat_keyword(exp!(Else)) {
9091
return Err("Expected `else`");
9192
}
9293

‎src/tools/rustfmt/src/parse/macros/lazy_static.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
use rustc_ast::ast;
22
use rustc_ast::ptr::P;
3-
use rustc_ast::token::TokenKind;
3+
use rustc_ast::token;
44
use rustc_ast::tokenstream::TokenStream;
5-
use rustc_span::symbol::{self, kw};
5+
use rustc_parse::exp;
6+
use rustc_span::symbol;
67

78
use crate::rewrite::RewriteContext;
89

@@ -31,19 +32,19 @@ pub(crate) fn parse_lazy_static(
3132
}
3233
}
3334
}
34-
while parser.token.kind != TokenKind::Eof {
35+
while parser.token.kind != token::Eof {
3536
// Parse a `lazy_static!` item.
3637
// FIXME: These `eat_*` calls should be converted to `parse_or` to avoid
3738
// silently formatting malformed lazy-statics.
3839
let vis = parse_or!(parse_visibility, rustc_parse::parser::FollowedByType::No);
39-
let _ = parser.eat_keyword(kw::Static);
40-
let _ = parser.eat_keyword(kw::Ref);
40+
let _ = parser.eat_keyword(exp!(Static));
41+
let _ = parser.eat_keyword(exp!(Ref));
4142
let id = parse_or!(parse_ident);
42-
let _ = parser.eat(&TokenKind::Colon);
43+
let _ = parser.eat(exp!(Colon));
4344
let ty = parse_or!(parse_ty);
44-
let _ = parser.eat(&TokenKind::Eq);
45+
let _ = parser.eat(exp!(Eq));
4546
let expr = parse_or!(parse_expr);
46-
let _ = parser.eat(&TokenKind::Semi);
47+
let _ = parser.eat(exp!(Semi));
4748
result.push((vis, id, ty, expr));
4849
}
4950

‎src/tools/rustfmt/src/parse/parser.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
use std::panic::{AssertUnwindSafe, catch_unwind};
22
use std::path::{Path, PathBuf};
33

4-
use rustc_ast::token::TokenKind;
54
use rustc_ast::{ast, attr, ptr};
65
use rustc_errors::Diag;
76
use rustc_parse::parser::Parser as RawParser;
8-
use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
7+
use rustc_parse::{exp, new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
98
use rustc_span::{Span, sym};
109
use thin_vec::ThinVec;
1110

@@ -107,7 +106,7 @@ impl<'a> Parser<'a> {
107106
let result = catch_unwind(AssertUnwindSafe(|| {
108107
let mut parser =
109108
unwrap_or_emit_fatal(new_parser_from_file(psess.inner(), path, Some(span)));
110-
match parser.parse_mod(&TokenKind::Eof) {
109+
match parser.parse_mod(exp!(Eof)) {
111110
Ok((a, i, spans)) => Some((a, i, spans.inner_span)),
112111
Err(e) => {
113112
e.emit();

0 commit comments

Comments
 (0)
This repository has been archived.