Skip to content

Commit 7fdb2f5

Browse files
authored
Rollup merge of #127233 - nnethercote:parser-cleanups, r=petrochenkov
Some parser cleanups Cleanups I made while looking closely at this code. r? ``@petrochenkov``
2 parents 9b05e7b + edeebe6 commit 7fdb2f5

File tree

8 files changed

+98
-120
lines changed

8 files changed

+98
-120
lines changed

compiler/rustc_ast/src/attr/mod.rs

+8-6
Original file line numberDiff line numberDiff line change
@@ -204,12 +204,14 @@ impl Attribute {
204204

205205
pub fn tokens(&self) -> TokenStream {
206206
match &self.kind {
207-
AttrKind::Normal(normal) => normal
208-
.tokens
209-
.as_ref()
210-
.unwrap_or_else(|| panic!("attribute is missing tokens: {self:?}"))
211-
.to_attr_token_stream()
212-
.to_tokenstream(),
207+
AttrKind::Normal(normal) => TokenStream::new(
208+
normal
209+
.tokens
210+
.as_ref()
211+
.unwrap_or_else(|| panic!("attribute is missing tokens: {self:?}"))
212+
.to_attr_token_stream()
213+
.to_token_trees(),
214+
),
213215
&AttrKind::DocComment(comment_kind, data) => TokenStream::token_alone(
214216
token::DocComment(comment_kind, self.style, data),
215217
self.span,

compiler/rustc_ast/src/tokenstream.rs

+18-31
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ use rustc_data_structures::sync::{self, Lrc};
2323
use rustc_macros::{Decodable, Encodable, HashStable_Generic};
2424
use rustc_serialize::{Decodable, Encodable};
2525
use rustc_span::{sym, Span, SpanDecoder, SpanEncoder, Symbol, DUMMY_SP};
26-
use smallvec::{smallvec, SmallVec};
2726

2827
use std::borrow::Cow;
2928
use std::{cmp, fmt, iter};
@@ -180,42 +179,33 @@ impl AttrTokenStream {
180179
AttrTokenStream(Lrc::new(tokens))
181180
}
182181

183-
/// Converts this `AttrTokenStream` to a plain `TokenStream`.
182+
/// Converts this `AttrTokenStream` to a plain `Vec<TokenTree>`.
184183
/// During conversion, `AttrTokenTree::Attributes` get 'flattened'
185184
/// back to a `TokenStream` of the form `outer_attr attr_target`.
186185
/// If there are inner attributes, they are inserted into the proper
187186
/// place in the attribute target tokens.
188-
pub fn to_tokenstream(&self) -> TokenStream {
189-
let trees: Vec<_> = self
190-
.0
191-
.iter()
192-
.flat_map(|tree| match &tree {
187+
pub fn to_token_trees(&self) -> Vec<TokenTree> {
188+
let mut res = Vec::with_capacity(self.0.len());
189+
for tree in self.0.iter() {
190+
match tree {
193191
AttrTokenTree::Token(inner, spacing) => {
194-
smallvec![TokenTree::Token(inner.clone(), *spacing)].into_iter()
192+
res.push(TokenTree::Token(inner.clone(), *spacing));
195193
}
196194
AttrTokenTree::Delimited(span, spacing, delim, stream) => {
197-
smallvec![TokenTree::Delimited(
195+
res.push(TokenTree::Delimited(
198196
*span,
199197
*spacing,
200198
*delim,
201-
stream.to_tokenstream()
202-
),]
203-
.into_iter()
199+
TokenStream::new(stream.to_token_trees()),
200+
))
204201
}
205202
AttrTokenTree::Attributes(data) => {
206203
let idx = data
207204
.attrs
208205
.partition_point(|attr| matches!(attr.style, crate::AttrStyle::Outer));
209206
let (outer_attrs, inner_attrs) = data.attrs.split_at(idx);
210207

211-
let mut target_tokens: Vec<_> = data
212-
.tokens
213-
.to_attr_token_stream()
214-
.to_tokenstream()
215-
.0
216-
.iter()
217-
.cloned()
218-
.collect();
208+
let mut target_tokens = data.tokens.to_attr_token_stream().to_token_trees();
219209
if !inner_attrs.is_empty() {
220210
let mut found = false;
221211
// Check the last two trees (to account for a trailing semi)
@@ -251,17 +241,14 @@ impl AttrTokenStream {
251241
"Failed to find trailing delimited group in: {target_tokens:?}"
252242
);
253243
}
254-
let mut flat: SmallVec<[_; 1]> =
255-
SmallVec::with_capacity(target_tokens.len() + outer_attrs.len());
256244
for attr in outer_attrs {
257-
flat.extend(attr.tokens().0.iter().cloned());
245+
res.extend(attr.tokens().0.iter().cloned());
258246
}
259-
flat.extend(target_tokens);
260-
flat.into_iter()
247+
res.extend(target_tokens);
261248
}
262-
})
263-
.collect();
264-
TokenStream::new(trees)
249+
}
250+
}
251+
res
265252
}
266253
}
267254

@@ -409,8 +396,8 @@ impl PartialEq<TokenStream> for TokenStream {
409396
}
410397

411398
impl TokenStream {
412-
pub fn new(streams: Vec<TokenTree>) -> TokenStream {
413-
TokenStream(Lrc::new(streams))
399+
pub fn new(tts: Vec<TokenTree>) -> TokenStream {
400+
TokenStream(Lrc::new(tts))
414401
}
415402

416403
pub fn is_empty(&self) -> bool {
@@ -461,7 +448,7 @@ impl TokenStream {
461448
AttributesData { attrs: attrs.iter().cloned().collect(), tokens: tokens.clone() };
462449
AttrTokenStream::new(vec![AttrTokenTree::Attributes(attr_data)])
463450
};
464-
attr_stream.to_tokenstream()
451+
TokenStream::new(attr_stream.to_token_trees())
465452
}
466453

467454
pub fn from_nonterminal_ast(nt: &Nonterminal) -> TokenStream {

compiler/rustc_builtin_macros/src/cfg_eval.rs

+8-10
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,14 @@ pub(crate) fn cfg_eval(
3838
lint_node_id: NodeId,
3939
) -> Annotatable {
4040
let features = Some(features);
41-
CfgEval { cfg: &mut StripUnconfigured { sess, features, config_tokens: true, lint_node_id } }
41+
CfgEval(StripUnconfigured { sess, features, config_tokens: true, lint_node_id })
4242
.configure_annotatable(annotatable)
4343
// Since the item itself has already been configured by the `InvocationCollector`,
4444
// we know that fold result vector will contain exactly one element.
4545
.unwrap()
4646
}
4747

48-
struct CfgEval<'a, 'b> {
49-
cfg: &'a mut StripUnconfigured<'b>,
50-
}
48+
struct CfgEval<'a>(StripUnconfigured<'a>);
5149

5250
fn flat_map_annotatable(
5351
vis: &mut impl MutVisitor,
@@ -125,9 +123,9 @@ fn has_cfg_or_cfg_attr(annotatable: &Annotatable) -> bool {
125123
res.is_break()
126124
}
127125

128-
impl CfgEval<'_, '_> {
126+
impl CfgEval<'_> {
129127
fn configure<T: HasAttrs + HasTokens>(&mut self, node: T) -> Option<T> {
130-
self.cfg.configure(node)
128+
self.0.configure(node)
131129
}
132130

133131
fn configure_annotatable(&mut self, mut annotatable: Annotatable) -> Option<Annotatable> {
@@ -196,7 +194,7 @@ impl CfgEval<'_, '_> {
196194
// Re-parse the tokens, setting the `capture_cfg` flag to save extra information
197195
// to the captured `AttrTokenStream` (specifically, we capture
198196
// `AttrTokenTree::AttributesData` for all occurrences of `#[cfg]` and `#[cfg_attr]`)
199-
let mut parser = Parser::new(&self.cfg.sess.psess, orig_tokens, None);
197+
let mut parser = Parser::new(&self.0.sess.psess, orig_tokens, None);
200198
parser.capture_cfg = true;
201199
match parse_annotatable_with(&mut parser) {
202200
Ok(a) => annotatable = a,
@@ -212,16 +210,16 @@ impl CfgEval<'_, '_> {
212210
}
213211
}
214212

215-
impl MutVisitor for CfgEval<'_, '_> {
213+
impl MutVisitor for CfgEval<'_> {
216214
#[instrument(level = "trace", skip(self))]
217215
fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
218-
self.cfg.configure_expr(expr, false);
216+
self.0.configure_expr(expr, false);
219217
mut_visit::noop_visit_expr(expr, self);
220218
}
221219

222220
#[instrument(level = "trace", skip(self))]
223221
fn visit_method_receiver_expr(&mut self, expr: &mut P<ast::Expr>) {
224-
self.cfg.configure_expr(expr, true);
222+
self.0.configure_expr(expr, true);
225223
mut_visit::noop_visit_expr(expr, self);
226224
}
227225

compiler/rustc_expand/src/mbe/diagnostics.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -120,21 +120,21 @@ struct CollectTrackerAndEmitter<'a, 'cx, 'matcher> {
120120

121121
struct BestFailure {
122122
token: Token,
123-
position_in_tokenstream: usize,
123+
position_in_tokenstream: u32,
124124
msg: &'static str,
125125
remaining_matcher: MatcherLoc,
126126
}
127127

128128
impl BestFailure {
129-
fn is_better_position(&self, position: usize) -> bool {
129+
fn is_better_position(&self, position: u32) -> bool {
130130
position > self.position_in_tokenstream
131131
}
132132
}
133133

134134
impl<'a, 'cx, 'matcher> Tracker<'matcher> for CollectTrackerAndEmitter<'a, 'cx, 'matcher> {
135-
type Failure = (Token, usize, &'static str);
135+
type Failure = (Token, u32, &'static str);
136136

137-
fn build_failure(tok: Token, position: usize, msg: &'static str) -> Self::Failure {
137+
fn build_failure(tok: Token, position: u32, msg: &'static str) -> Self::Failure {
138138
(tok, position, msg)
139139
}
140140

@@ -211,9 +211,9 @@ impl<'matcher> FailureForwarder<'matcher> {
211211
}
212212

213213
impl<'matcher> Tracker<'matcher> for FailureForwarder<'matcher> {
214-
type Failure = (Token, usize, &'static str);
214+
type Failure = (Token, u32, &'static str);
215215

216-
fn build_failure(tok: Token, position: usize, msg: &'static str) -> Self::Failure {
216+
fn build_failure(tok: Token, position: u32, msg: &'static str) -> Self::Failure {
217217
(tok, position, msg)
218218
}
219219

compiler/rustc_expand/src/mbe/macro_parser.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ impl TtParser {
452452
&mut self,
453453
matcher: &'matcher [MatcherLoc],
454454
token: &Token,
455-
approx_position: usize,
455+
approx_position: u32,
456456
track: &mut T,
457457
) -> Option<NamedParseResult<T::Failure>> {
458458
// Matcher positions that would be valid if the macro invocation was over now. Only

compiler/rustc_expand/src/mbe/macro_rules.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ pub(super) trait Tracker<'matcher> {
153153
/// Arm failed to match. If the token is `token::Eof`, it indicates an unexpected
154154
/// end of macro invocation. Otherwise, it indicates that no rules expected the given token.
155155
/// The usize is the approximate position of the token in the input token stream.
156-
fn build_failure(tok: Token, position: usize, msg: &'static str) -> Self::Failure;
156+
fn build_failure(tok: Token, position: u32, msg: &'static str) -> Self::Failure;
157157

158158
/// This is called before trying to match next MatcherLoc on the current token.
159159
fn before_match_loc(&mut self, _parser: &TtParser, _matcher: &'matcher MatcherLoc) {}
@@ -182,7 +182,7 @@ pub(super) struct NoopTracker;
182182
impl<'matcher> Tracker<'matcher> for NoopTracker {
183183
type Failure = ();
184184

185-
fn build_failure(_tok: Token, _position: usize, _msg: &'static str) -> Self::Failure {}
185+
fn build_failure(_tok: Token, _position: u32, _msg: &'static str) -> Self::Failure {}
186186

187187
fn description() -> &'static str {
188188
"none"

0 commit comments

Comments
 (0)