Skip to content

Commit 6913c74

Browse files
committed
Auto merge of rust-lang#97114 - klensy:cursor-ref, r=petrochenkov
use CursorRef more This allows skipping clone of `TreeAndSpacing` (and `TokenTree`).
2 parents 67a9bcb + 05f459e commit 6913c74

File tree

11 files changed

+37
-26
lines changed

11 files changed

+37
-26
lines changed

compiler/rustc_ast/src/attr/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -552,7 +552,7 @@ impl MetaItemKind {
552552
) -> Option<MetaItemKind> {
553553
match tokens.next() {
554554
Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
555-
MetaItemKind::name_value_from_tokens(&mut inner_tokens.trees())
555+
MetaItemKind::name_value_from_tokens(&mut inner_tokens.into_trees())
556556
}
557557
Some(TokenTree::Token(token)) => {
558558
Lit::from_token(&token).ok().map(MetaItemKind::NameValue)

compiler/rustc_ast/src/tokenstream.rs

+11-2
Original file line numberDiff line numberDiff line change
@@ -442,8 +442,8 @@ impl TokenStream {
442442
}
443443
}
444444

445-
pub fn trees(&self) -> Cursor {
446-
self.clone().into_trees()
445+
pub fn trees(&self) -> CursorRef<'_> {
446+
CursorRef::new(self)
447447
}
448448

449449
pub fn into_trees(self) -> Cursor {
@@ -538,12 +538,21 @@ pub struct CursorRef<'t> {
538538
}
539539

540540
impl<'t> CursorRef<'t> {
541+
fn new(stream: &'t TokenStream) -> Self {
542+
CursorRef { stream, index: 0 }
543+
}
544+
545+
#[inline]
541546
fn next_with_spacing(&mut self) -> Option<&'t TreeAndSpacing> {
542547
self.stream.0.get(self.index).map(|tree| {
543548
self.index += 1;
544549
tree
545550
})
546551
}
552+
553+
pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
554+
self.stream.0[self.index..].get(n).map(|(tree, _)| tree)
555+
}
547556
}
548557

549558
impl<'t> Iterator for CursorRef<'t> {

compiler/rustc_ast_pretty/src/pprust/state.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -550,9 +550,9 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
550550
fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) {
551551
let mut iter = tts.trees().peekable();
552552
while let Some(tt) = iter.next() {
553-
self.print_tt(&tt, convert_dollar_crate);
553+
self.print_tt(tt, convert_dollar_crate);
554554
if let Some(next) = iter.peek() {
555-
if tt_prepend_space(next, &tt) {
555+
if tt_prepend_space(next, tt) {
556556
self.space();
557557
}
558558
}

compiler/rustc_expand/src/config.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ impl<'a> StripUnconfigured<'a> {
400400

401401
// Use the `#` in `#[cfg_attr(pred, attr)]` as the `#` token
402402
// for `attr` when we expand it to `#[attr]`
403-
let mut orig_trees = orig_tokens.trees();
403+
let mut orig_trees = orig_tokens.into_trees();
404404
let TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }) = orig_trees.next().unwrap() else {
405405
panic!("Bad tokens for attribute {:?}", attr);
406406
};

compiler/rustc_expand/src/mbe/metavar_expr.rs

+14-12
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use rustc_ast::token::{self, Delimiter};
2-
use rustc_ast::tokenstream::{Cursor, TokenStream, TokenTree};
2+
use rustc_ast::tokenstream::{CursorRef, TokenStream, TokenTree};
33
use rustc_ast::{LitIntType, LitKind};
44
use rustc_ast_pretty::pprust;
55
use rustc_errors::{Applicability, PResult};
@@ -71,12 +71,14 @@ impl MetaVarExpr {
7171
}
7272

7373
// Checks if there are any remaining tokens. For example, `${ignore(ident ... a b c ...)}`
74-
fn check_trailing_token<'sess>(iter: &mut Cursor, sess: &'sess ParseSess) -> PResult<'sess, ()> {
74+
fn check_trailing_token<'sess>(
75+
iter: &mut CursorRef<'_>,
76+
sess: &'sess ParseSess,
77+
) -> PResult<'sess, ()> {
7578
if let Some(tt) = iter.next() {
76-
let mut diag = sess.span_diagnostic.struct_span_err(
77-
tt.span(),
78-
&format!("unexpected token: {}", pprust::tt_to_string(&tt)),
79-
);
79+
let mut diag = sess
80+
.span_diagnostic
81+
.struct_span_err(tt.span(), &format!("unexpected token: {}", pprust::tt_to_string(tt)));
8082
diag.span_note(tt.span(), "meta-variable expression must not have trailing tokens");
8183
Err(diag)
8284
} else {
@@ -86,7 +88,7 @@ fn check_trailing_token<'sess>(iter: &mut Cursor, sess: &'sess ParseSess) -> PRe
8688

8789
/// Parse a meta-variable `count` expression: `count(ident[, depth])`
8890
fn parse_count<'sess>(
89-
iter: &mut Cursor,
91+
iter: &mut CursorRef<'_>,
9092
sess: &'sess ParseSess,
9193
span: Span,
9294
) -> PResult<'sess, MetaVarExpr> {
@@ -97,7 +99,7 @@ fn parse_count<'sess>(
9799

98100
/// Parses the depth used by index(depth) and length(depth).
99101
fn parse_depth<'sess>(
100-
iter: &mut Cursor,
102+
iter: &mut CursorRef<'_>,
101103
sess: &'sess ParseSess,
102104
span: Span,
103105
) -> PResult<'sess, usize> {
@@ -110,7 +112,7 @@ fn parse_depth<'sess>(
110112
"meta-variable expression depth must be a literal"
111113
));
112114
};
113-
if let Ok(lit_kind) = LitKind::from_lit_token(lit)
115+
if let Ok(lit_kind) = LitKind::from_lit_token(*lit)
114116
&& let LitKind::Int(n_u128, LitIntType::Unsuffixed) = lit_kind
115117
&& let Ok(n_usize) = usize::try_from(n_u128)
116118
{
@@ -124,15 +126,15 @@ fn parse_depth<'sess>(
124126

125127
/// Parses an generic ident
126128
fn parse_ident<'sess>(
127-
iter: &mut Cursor,
129+
iter: &mut CursorRef<'_>,
128130
sess: &'sess ParseSess,
129131
span: Span,
130132
) -> PResult<'sess, Ident> {
131133
if let Some(tt) = iter.next() && let TokenTree::Token(token) = tt {
132134
if let Some((elem, false)) = token.ident() {
133135
return Ok(elem);
134136
}
135-
let token_str = pprust::token_to_string(&token);
137+
let token_str = pprust::token_to_string(token);
136138
let mut err = sess.span_diagnostic.struct_span_err(
137139
span,
138140
&format!("expected identifier, found `{}`", &token_str)
@@ -150,7 +152,7 @@ fn parse_ident<'sess>(
150152

151153
/// Tries to move the iterator forward returning `true` if there is a comma. If not, then the
152154
/// iterator is not modified and the result is `false`.
153-
fn try_eat_comma(iter: &mut Cursor) -> bool {
155+
fn try_eat_comma(iter: &mut CursorRef<'_>) -> bool {
154156
if let Some(TokenTree::Token(token::Token { kind: token::Comma, .. })) = iter.look_ahead(0) {
155157
let _ = iter.next();
156158
return true;

compiler/rustc_expand/src/mbe/quoted.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ pub(super) fn parse(
4848

4949
// For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
5050
// additional trees if need be.
51-
let mut trees = input.trees();
51+
let mut trees = input.into_trees();
5252
while let Some(tree) = trees.next() {
5353
// Given the parsed tree, if there is a metavar and we are expecting matchers, actually
5454
// parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).

compiler/rustc_expand/src/parse/tests.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ fn bad_path_expr_1() {
6161
fn string_to_tts_macro() {
6262
create_default_session_globals_then(|| {
6363
let tts: Vec<_> =
64-
string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
64+
string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).into_trees().collect();
6565
let tts: &[TokenTree] = &tts[..];
6666

6767
match tts {
@@ -293,7 +293,7 @@ fn ttdelim_span() {
293293
.unwrap();
294294

295295
let tts: Vec<_> = match expr.kind {
296-
ast::ExprKind::MacCall(ref mac) => mac.args.inner_tokens().trees().collect(),
296+
ast::ExprKind::MacCall(ref mac) => mac.args.inner_tokens().into_trees().collect(),
297297
_ => panic!("not a macro"),
298298
};
299299

compiler/rustc_expand/src/proc_macro_server.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -484,7 +484,7 @@ impl server::TokenStream for Rustc<'_, '_> {
484484
tree.to_internal()
485485
}
486486
fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
487-
TokenStreamIter { cursor: stream.trees(), stack: vec![] }
487+
TokenStreamIter { cursor: stream.into_trees(), stack: vec![] }
488488
}
489489
}
490490

compiler/rustc_expand/src/tokenstream/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ fn test_concat() {
3535
fn test_to_from_bijection() {
3636
create_default_session_globals_then(|| {
3737
let test_start = string_to_ts("foo::bar(baz)");
38-
let test_end = test_start.trees().collect();
38+
let test_end = test_start.trees().cloned().collect();
3939
assert_eq!(test_start, test_end)
4040
})
4141
}

compiler/rustc_session/src/utils.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ impl<'a> FlattenNonterminals<'a> {
108108
fn can_skip(stream: &TokenStream) -> bool {
109109
stream.trees().all(|tree| match tree {
110110
TokenTree::Token(token) => !matches!(token.kind, token::Interpolated(_)),
111-
TokenTree::Delimited(_, _, inner) => can_skip(&inner),
111+
TokenTree::Delimited(_, _, inner) => can_skip(inner),
112112
})
113113
}
114114

src/tools/rustfmt/src/macros.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ fn rewrite_macro_inner(
226226
}
227227
// Format well-known macros which cannot be parsed as a valid AST.
228228
if macro_name == "lazy_static!" && !has_comment {
229-
if let success @ Some(..) = format_lazy_static(context, shape, ts.trees().collect()) {
229+
if let success @ Some(..) = format_lazy_static(context, shape, ts.clone()) {
230230
return success;
231231
}
232232
}
@@ -855,7 +855,7 @@ impl MacroArgParser {
855855

856856
/// Returns a collection of parsed macro def's arguments.
857857
fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
858-
let mut iter = tokens.trees();
858+
let mut iter = tokens.into_trees();
859859

860860
while let Some(tok) = iter.next() {
861861
match tok {

0 commit comments

Comments
 (0)