Skip to content

Commit 4aceaaa

Browse files
authored
Rollup merge of #126052 - nnethercote:rustc_parse-more-cleanups, r=spastorino
More `rustc_parse` cleanups Following on from #125815. r? `@spastorino`
2 parents bc79329 + 4c731c2 commit 4aceaaa

File tree

9 files changed

+67
-72
lines changed

9 files changed

+67
-72
lines changed

compiler/rustc_parse/src/parser/diagnostics.rs

+15-11
Original file line numberDiff line numberDiff line change
@@ -130,14 +130,14 @@ pub enum AttemptLocalParseRecovery {
130130
}
131131

132132
impl AttemptLocalParseRecovery {
133-
pub fn yes(&self) -> bool {
133+
pub(super) fn yes(&self) -> bool {
134134
match self {
135135
AttemptLocalParseRecovery::Yes => true,
136136
AttemptLocalParseRecovery::No => false,
137137
}
138138
}
139139

140-
pub fn no(&self) -> bool {
140+
pub(super) fn no(&self) -> bool {
141141
match self {
142142
AttemptLocalParseRecovery::Yes => false,
143143
AttemptLocalParseRecovery::No => true,
@@ -891,7 +891,7 @@ impl<'a> Parser<'a> {
891891
}
892892
}
893893

894-
pub fn maybe_suggest_struct_literal(
894+
pub(super) fn maybe_suggest_struct_literal(
895895
&mut self,
896896
lo: Span,
897897
s: BlockCheckMode,
@@ -2459,7 +2459,7 @@ impl<'a> Parser<'a> {
24592459
/// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
24602460
/// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
24612461
/// like the user has forgotten them.
2462-
pub fn handle_ambiguous_unbraced_const_arg(
2462+
pub(super) fn handle_ambiguous_unbraced_const_arg(
24632463
&mut self,
24642464
args: &mut ThinVec<AngleBracketedArg>,
24652465
) -> PResult<'a, bool> {
@@ -2500,7 +2500,7 @@ impl<'a> Parser<'a> {
25002500
/// - Single-segment paths (i.e. standalone generic const parameters).
25012501
/// All other expressions that can be parsed will emit an error suggesting the expression be
25022502
/// wrapped in braces.
2503-
pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
2503+
pub(super) fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
25042504
let start = self.token.span;
25052505
let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
25062506
err.span_label(
@@ -2559,7 +2559,7 @@ impl<'a> Parser<'a> {
25592559
Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
25602560
}
25612561

2562-
pub fn recover_const_param_declaration(
2562+
pub(super) fn recover_const_param_declaration(
25632563
&mut self,
25642564
ty_generics: Option<&Generics>,
25652565
) -> PResult<'a, Option<GenericArg>> {
@@ -2589,7 +2589,11 @@ impl<'a> Parser<'a> {
25892589
/// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
25902590
/// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
25912591
/// if we think that the resulting expression would be well formed.
2592-
pub fn recover_const_arg(&mut self, start: Span, mut err: Diag<'a>) -> PResult<'a, GenericArg> {
2592+
pub(super) fn recover_const_arg(
2593+
&mut self,
2594+
start: Span,
2595+
mut err: Diag<'a>,
2596+
) -> PResult<'a, GenericArg> {
25932597
let is_op_or_dot = AssocOp::from_token(&self.token)
25942598
.and_then(|op| {
25952599
if let AssocOp::Greater
@@ -2690,7 +2694,7 @@ impl<'a> Parser<'a> {
26902694
}
26912695

26922696
/// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2693-
pub fn dummy_const_arg_needs_braces(&self, mut err: Diag<'a>, span: Span) -> GenericArg {
2697+
pub(super) fn dummy_const_arg_needs_braces(&self, mut err: Diag<'a>, span: Span) -> GenericArg {
26942698
err.multipart_suggestion(
26952699
"expressions must be enclosed in braces to be used as const generic \
26962700
arguments",
@@ -2961,7 +2965,7 @@ impl<'a> Parser<'a> {
29612965
/// * `=====`
29622966
/// * `<<<<<`
29632967
///
2964-
pub fn is_vcs_conflict_marker(
2968+
pub(super) fn is_vcs_conflict_marker(
29652969
&mut self,
29662970
long_kind: &TokenKind,
29672971
short_kind: &TokenKind,
@@ -2981,14 +2985,14 @@ impl<'a> Parser<'a> {
29812985
None
29822986
}
29832987

2984-
pub fn recover_vcs_conflict_marker(&mut self) {
2988+
pub(super) fn recover_vcs_conflict_marker(&mut self) {
29852989
if let Err(err) = self.err_vcs_conflict_marker() {
29862990
err.emit();
29872991
FatalError.raise();
29882992
}
29892993
}
29902994

2991-
pub fn err_vcs_conflict_marker(&mut self) -> PResult<'a, ()> {
2995+
pub(crate) fn err_vcs_conflict_marker(&mut self) -> PResult<'a, ()> {
29922996
let Some(start) = self.conflict_marker(&TokenKind::BinOp(token::Shl), &TokenKind::Lt)
29932997
else {
29942998
return Ok(());

compiler/rustc_parse/src/parser/expr.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ impl<'a> Parser<'a> {
431431
/// The method does not advance the current token.
432432
///
433433
/// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
434-
pub fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
434+
pub(super) fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
435435
let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
436436
// When parsing const expressions, stop parsing when encountering `>`.
437437
(
@@ -1006,7 +1006,11 @@ impl<'a> Parser<'a> {
10061006
}
10071007
}
10081008

1009-
pub fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1009+
pub(super) fn parse_dot_suffix_expr(
1010+
&mut self,
1011+
lo: Span,
1012+
base: P<Expr>,
1013+
) -> PResult<'a, P<Expr>> {
10101014
// At this point we've consumed something like `expr.` and `self.token` holds the token
10111015
// after the dot.
10121016
match self.token.uninterpolate().kind {

compiler/rustc_parse/src/parser/item.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2265,7 +2265,7 @@ pub(crate) struct FnParseMode {
22652265
/// to true.
22662266
/// * The span is from Edition 2015. In particular, you can get a
22672267
/// 2015 span inside a 2021 crate using macros.
2268-
pub req_name: ReqName,
2268+
pub(super) req_name: ReqName,
22692269
/// If this flag is set to `true`, then plain, semicolon-terminated function
22702270
/// prototypes are not allowed here.
22712271
///
@@ -2284,7 +2284,7 @@ pub(crate) struct FnParseMode {
22842284
/// This field should only be set to false if the item is inside of a trait
22852285
/// definition or extern block. Within an impl block or a module, it should
22862286
/// always be set to true.
2287-
pub req_body: bool,
2287+
pub(super) req_body: bool,
22882288
}
22892289

22902290
/// Parsing of functions and methods.

compiler/rustc_parse/src/parser/mod.rs

+22-21
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,13 @@ mod stmt;
1111
mod ty;
1212

1313
use crate::lexer::UnmatchedDelim;
14-
pub use attr_wrapper::AttrWrapper;
14+
use attr_wrapper::AttrWrapper;
1515
pub use diagnostics::AttemptLocalParseRecovery;
1616
pub(crate) use expr::ForbiddenLetReason;
1717
pub(crate) use item::FnParseMode;
1818
pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
19-
pub use path::PathStyle;
19+
use path::PathStyle;
2020

21-
use core::fmt;
2221
use rustc_ast::ptr::P;
2322
use rustc_ast::token::{self, Delimiter, IdentIsRaw, Nonterminal, Token, TokenKind};
2423
use rustc_ast::tokenstream::{AttributesData, DelimSpacing, DelimSpan, Spacing};
@@ -37,7 +36,7 @@ use rustc_session::parse::ParseSess;
3736
use rustc_span::symbol::{kw, sym, Ident, Symbol};
3837
use rustc_span::{Span, DUMMY_SP};
3938
use std::ops::Range;
40-
use std::{mem, slice};
39+
use std::{fmt, mem, slice};
4140
use thin_vec::ThinVec;
4241
use tracing::debug;
4342

@@ -146,7 +145,7 @@ pub struct Parser<'a> {
146145
/// The current token.
147146
pub token: Token,
148147
/// The spacing for the current token.
149-
pub token_spacing: Spacing,
148+
token_spacing: Spacing,
150149
/// The previous token.
151150
pub prev_token: Token,
152151
pub capture_cfg: bool,
@@ -187,7 +186,7 @@ pub struct Parser<'a> {
187186
current_closure: Option<ClosureSpans>,
188187
/// Whether the parser is allowed to do recovery.
189188
/// This is disabled when parsing macro arguments, see #103534
190-
pub recovery: Recovery,
189+
recovery: Recovery,
191190
}
192191

193192
// This type is used a lot, e.g. it's cloned when matching many declarative macro rules with nonterminals. Make sure
@@ -197,10 +196,10 @@ rustc_data_structures::static_assert_size!(Parser<'_>, 264);
197196

198197
/// Stores span information about a closure.
199198
#[derive(Clone, Debug)]
200-
pub struct ClosureSpans {
201-
pub whole_closure: Span,
202-
pub closing_pipe: Span,
203-
pub body: Span,
199+
struct ClosureSpans {
200+
whole_closure: Span,
201+
closing_pipe: Span,
202+
body: Span,
204203
}
205204

206205
/// Indicates a range of tokens that should be replaced by
@@ -220,13 +219,13 @@ pub struct ClosureSpans {
220219
/// the first macro inner attribute to invoke a proc-macro).
221220
/// When create a `TokenStream`, the inner attributes get inserted
222221
/// into the proper place in the token stream.
223-
pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
222+
type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
224223

225224
/// Controls how we capture tokens. Capturing can be expensive,
226225
/// so we try to avoid performing capturing in cases where
227226
/// we will never need an `AttrTokenStream`.
228227
#[derive(Copy, Clone, Debug)]
229-
pub enum Capturing {
228+
enum Capturing {
230229
/// We aren't performing any capturing - this is the default mode.
231230
No,
232231
/// We are capturing tokens
@@ -374,21 +373,21 @@ pub enum FollowedByType {
374373
}
375374

376375
#[derive(Copy, Clone, Debug)]
377-
pub enum Trailing {
376+
enum Trailing {
378377
No,
379378
Yes,
380379
}
381380

382381
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
383-
pub enum TokenDescription {
382+
pub(super) enum TokenDescription {
384383
ReservedIdentifier,
385384
Keyword,
386385
ReservedKeyword,
387386
DocComment,
388387
}
389388

390389
impl TokenDescription {
391-
pub fn from_token(token: &Token) -> Option<Self> {
390+
pub(super) fn from_token(token: &Token) -> Option<Self> {
392391
match token.kind {
393392
_ if token.is_special_ident() => Some(TokenDescription::ReservedIdentifier),
394393
_ if token.is_used_keyword() => Some(TokenDescription::Keyword),
@@ -502,7 +501,7 @@ impl<'a> Parser<'a> {
502501
/// Expect next token to be edible or inedible token. If edible,
503502
/// then consume it; if inedible, then return without consuming
504503
/// anything. Signal a fatal error if next token is unexpected.
505-
pub fn expect_one_of(
504+
fn expect_one_of(
506505
&mut self,
507506
edible: &[TokenKind],
508507
inedible: &[TokenKind],
@@ -572,7 +571,7 @@ impl<'a> Parser<'a> {
572571
/// the main purpose of this function is to reduce the cluttering of the suggestions list
573572
/// which using the normal eat method could introduce in some cases.
574573
#[inline]
575-
pub fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
574+
fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
576575
let is_present = self.check_noexpect(tok);
577576
if is_present {
578577
self.bump()
@@ -1520,7 +1519,7 @@ impl<'a> Parser<'a> {
15201519
}
15211520
}
15221521

1523-
pub fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1522+
fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
15241523
&mut self,
15251524
f: impl FnOnce(&mut Self) -> PResult<'a, R>,
15261525
) -> PResult<'a, R> {
@@ -1541,8 +1540,10 @@ impl<'a> Parser<'a> {
15411540
})
15421541
}
15431542

1544-
// debug view of the parser's token stream, up to `{lookahead}` tokens
1545-
pub fn debug_lookahead(&self, lookahead: usize) -> impl fmt::Debug + '_ {
1543+
// Debug view of the parser's token stream, up to `{lookahead}` tokens.
1544+
// Only used when debugging.
1545+
#[allow(unused)]
1546+
pub(crate) fn debug_lookahead(&self, lookahead: usize) -> impl fmt::Debug + '_ {
15461547
struct DebugParser<'dbg> {
15471548
parser: &'dbg Parser<'dbg>,
15481549
lookahead: usize,
@@ -1618,7 +1619,7 @@ pub(crate) fn make_unclosed_delims_error(
16181619
/// is then 'parsed' to build up an `AttrTokenStream` with nested
16191620
/// `AttrTokenTree::Delimited` tokens.
16201621
#[derive(Debug, Clone)]
1621-
pub enum FlatToken {
1622+
enum FlatToken {
16221623
/// A token - this holds both delimiter (e.g. '{' and '}')
16231624
/// and non-delimiter tokens
16241625
Token(Token),

compiler/rustc_parse/src/parser/mut_visit/tests.rs

+6-12
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,12 @@ impl MutVisitor for ToZzIdentMutVisitor {
2121
}
2222
}
2323

24-
// Maybe add to `expand.rs`.
25-
macro_rules! assert_pred {
26-
($pred:expr, $predname:expr, $a:expr , $b:expr) => {{
27-
let pred_val = $pred;
24+
macro_rules! assert_matches_codepattern {
25+
($a:expr , $b:expr) => {{
2826
let a_val = $a;
2927
let b_val = $b;
30-
if !(pred_val(&a_val, &b_val)) {
31-
panic!("expected args satisfying {}, got {} and {}", $predname, a_val, b_val);
28+
if !matches_codepattern(&a_val, &b_val) {
29+
panic!("expected args satisfying `matches_codepattern`, got {} and {}", a_val, b_val);
3230
}
3331
}};
3432
}
@@ -41,9 +39,7 @@ fn ident_transformation() {
4139
let mut krate =
4240
string_to_crate("#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
4341
zz_visitor.visit_crate(&mut krate);
44-
assert_pred!(
45-
matches_codepattern,
46-
"matches_codepattern",
42+
assert_matches_codepattern!(
4743
print_crate_items(&krate),
4844
"#[zz]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string()
4945
);
@@ -61,9 +57,7 @@ fn ident_transformation_in_defs() {
6157
.to_string(),
6258
);
6359
zz_visitor.visit_crate(&mut krate);
64-
assert_pred!(
65-
matches_codepattern,
66-
"matches_codepattern",
60+
assert_matches_codepattern!(
6761
print_crate_items(&krate),
6862
"macro_rules! zz{(zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+))}".to_string()
6963
);

compiler/rustc_parse/src/parser/path.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use tracing::debug;
2020

2121
/// Specifies how to parse a path.
2222
#[derive(Copy, Clone, PartialEq)]
23-
pub enum PathStyle {
23+
pub(super) enum PathStyle {
2424
/// In some contexts, notably in expressions, paths with generic arguments are ambiguous
2525
/// with something else. For example, in expressions `segment < ....` can be interpreted
2626
/// as a comparison and `segment ( ....` can be interpreted as a function call.

compiler/rustc_parse/src/parser/stmt.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ impl<'a> Parser<'a> {
3131
/// Parses a statement. This stops just before trailing semicolons on everything but items.
3232
/// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3333
// Public for rustfmt usage.
34-
pub fn parse_stmt(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<Stmt>> {
34+
pub(super) fn parse_stmt(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<Stmt>> {
3535
Ok(self.parse_stmt_without_recovery(false, force_collect).unwrap_or_else(|e| {
3636
e.emit();
3737
self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);

compiler/rustc_parse/src/parser/ty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ impl<'a> Parser<'a> {
127127
/// Parse a type suitable for a field definition.
128128
/// The difference from `parse_ty` is that this version
129129
/// allows anonymous structs and unions.
130-
pub fn parse_ty_for_field_def(&mut self) -> PResult<'a, P<Ty>> {
130+
pub(super) fn parse_ty_for_field_def(&mut self) -> PResult<'a, P<Ty>> {
131131
if self.can_begin_anon_struct_or_union() {
132132
self.parse_anon_struct_or_union()
133133
} else {

0 commit comments

Comments
 (0)