diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index c14ad62e9a60b..9191848aa2c26 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -378,6 +378,7 @@ impl ParenthesizedArgs { } pub use crate::node_id::{CRATE_NODE_ID, DUMMY_NODE_ID, NodeId}; +use crate::tokenarena::ArenaTokenStream; /// Modifiers on a trait bound like `[const]`, `?` and `!`. #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Walkable)] @@ -2093,7 +2094,7 @@ impl AttrArgs { pub fn inner_tokens(&self) -> TokenStream { match self { AttrArgs::Empty => TokenStream::default(), - AttrArgs::Delimited(args) => args.tokens.clone(), + AttrArgs::Delimited(args) => args.tokens.to_token_stream(), AttrArgs::Eq { expr, .. } => TokenStream::from_ast(expr), } } @@ -2104,7 +2105,7 @@ impl AttrArgs { pub struct DelimArgs { pub dspan: DelimSpan, pub delim: Delimiter, // Note: `Delimiter::Invisible` never occurs - pub tokens: TokenStream, + pub tokens: ArenaTokenStream, } impl DelimArgs { diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 40a1b4bd32218..12ed43d23c8dd 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -19,6 +19,7 @@ use crate::ast::{ use crate::token::{ self, CommentKind, Delimiter, DocFragmentKind, InvisibleOrigin, MetaVarKind, Token, }; +use crate::tokenarena::{ArenaTokenStream, ArenaTokenStreamBuilder}; use crate::tokenstream::{ AttrTokenStream, AttrTokenTree, DelimSpacing, DelimSpan, LazyAttrTokenStream, Spacing, TokenStream, TokenStreamIter, TokenTree, @@ -308,6 +309,28 @@ impl Attribute { } } + pub fn push_token_trees(&self, arena: &mut ArenaTokenStreamBuilder) { + match self.kind { + AttrKind::Normal(ref normal) => { + for token_tree in normal + .tokens + .as_ref() + .unwrap_or_else(|| panic!("attribute is missing tokens: {self:?}")) + .to_attr_token_stream() + .to_token_trees() + { + arena.push_token_tree(&token_tree); + } + } + // Empty tokens here ensures synthetic attributes are invisible to proc macros. + AttrKind::Synthetic(..) => {} + AttrKind::DocComment(comment_kind, data) => arena.push_token_alone(Token::new( + token::DocComment(comment_kind, self.style, data), + self.span, + )), + } + } + pub fn deprecation_note(&self) -> Option { match &self.kind { AttrKind::Normal(normal) if normal.item.path == sym::deprecated => { @@ -345,7 +368,7 @@ impl AttrItem { pub fn meta_item_list(&self) -> Option> { match &self.args { AttrArgs::Delimited(args) if args.delim == Delimiter::Parenthesis => { - MetaItemKind::list_from_tokens(args.tokens.clone()) + MetaItemKind::list_from_tokens(args.tokens.to_token_stream()) } AttrArgs::Delimited(_) | AttrArgs::Eq { .. } | AttrArgs::Empty => None, } @@ -590,7 +613,7 @@ impl MetaItemKind { match args { AttrArgs::Empty => Some(MetaItemKind::Word), AttrArgs::Delimited(DelimArgs { dspan: _, delim: Delimiter::Parenthesis, tokens }) => { - MetaItemKind::list_from_tokens(tokens.clone()).map(MetaItemKind::List) + MetaItemKind::list_from_tokens(tokens.to_token_stream()).map(MetaItemKind::List) } AttrArgs::Delimited(..) => None, AttrArgs::Eq { expr, .. } => match expr.kind { @@ -803,10 +826,10 @@ pub fn mk_attr_nested_word( inner: Symbol, span: Span, ) -> Attribute { - let inner_tokens = TokenStream::new(vec![TokenTree::Token( + let inner_tokens = ArenaTokenStream::from_token( Token::from_ast_ident(Ident::new(inner, span)), Spacing::Alone, - )]); + ); let outer_ident = Ident::new(outer, span); let path = Path::from_ident(outer_ident); let attr_args = AttrArgs::Delimited(DelimArgs { diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs index 46d8e11cc0931..e0a0a644cd926 100644 --- a/compiler/rustc_ast/src/lib.rs +++ b/compiler/rustc_ast/src/lib.rs @@ -31,6 +31,7 @@ pub mod format; pub mod mut_visit; pub mod node_id; pub mod token; +pub mod tokenarena; pub mod tokenstream; pub mod visit; diff --git a/compiler/rustc_ast/src/tokenarena.rs b/compiler/rustc_ast/src/tokenarena.rs new file mode 100644 index 0000000000000..0184ec49e056d --- /dev/null +++ b/compiler/rustc_ast/src/tokenarena.rs @@ -0,0 +1,363 @@ +use std::sync::Arc; + +use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher}; +use rustc_index::static_assert_size; +use rustc_macros::{Decodable, Encodable, StableHash}; +use rustc_span::Span; + +use crate::token::{Delimiter, Token, TokenKind}; +use crate::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; + +/// Part of a `TokenArena`. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable)] +#[derive(StableHash)] // FIXME: is this Ok? +pub enum ArenaTokenTree { + /// A single token. Should never be `OpenDelim` or `CloseDelim`, because + /// delimiters are implicitly represented by `DelimitedStart`/`DelimitedEnd`. + Token(Token, Spacing), + /// A delimited sequence of token trees. + DelimitedStart(DelimitedBounds, DelimitedData), +} + +impl ArenaTokenTree { + /// Create a `TokenTree::Token` with alone spacing. + pub fn token_alone(kind: TokenKind, span: Span) -> ArenaTokenTree { + ArenaTokenTree::Token(Token::new(kind, span), Spacing::Alone) + } + + /// Create a `TokenTree::Token` with joint spacing. + pub fn token_joint(kind: TokenKind, span: Span) -> ArenaTokenTree { + ArenaTokenTree::Token(Token::new(kind, span), Spacing::Joint) + } + + /// Convert an arena token tree to the tree-shaped token tree. + pub fn to_token_tree(&self, arena: &ArenaTokenStream) -> TokenTree { + match self { + ArenaTokenTree::Token(token, spacing) => TokenTree::Token(*token, *spacing), + ArenaTokenTree::DelimitedStart(bounds, data) => { + let tts = arena.iter_delimited(bounds).map(|tt| tt.to_token_tree(arena)).collect(); + TokenTree::Delimited(data.span, data.spacing, data.delimiter, TokenStream::new(tts)) + } + } + } + + /// Retrieves the `TokenTree`'s span. + pub fn span(&self) -> Span { + match self { + Self::Token(token, _) => token.span, + Self::DelimitedStart(_, data) => data.span.entire(), + } + } + + pub fn to_delimited_data(&self) -> Option<&DelimitedData> { + match self { + ArenaTokenTree::Token(_, _) => None, + ArenaTokenTree::DelimitedStart(_, data) => Some(data), + } + } + + pub fn to_delimited_bounds(&self) -> Option<&DelimitedBounds> { + match self { + ArenaTokenTree::Token(_, _) => None, + ArenaTokenTree::DelimitedStart(bounds, _) => Some(bounds), + } + } +} + +static_assert_size!(ArenaTokenTree, 40); + +#[derive(Debug, Default)] +pub struct ArenaTokenStreamBuilder { + tokens: Vec, + /// Index of the current delimited sequence + current_delimited_sequence: Option, +} + +impl ArenaTokenStreamBuilder { + pub fn with_capacity(capacity: usize) -> Self { + Self { tokens: Vec::with_capacity(capacity), current_delimited_sequence: None } + } + + pub fn push_token(&mut self, token: Token, spacing: Spacing) { + self.tokens.push(ArenaTokenTree::Token(token, spacing)); + } + + pub fn push_token_alone(&mut self, token: Token) { + self.tokens.push(ArenaTokenTree::Token(token, Spacing::Alone)); + } + + pub fn pop(&mut self) -> Option { + let tree = self.tokens.pop(); + if let Some(tree) = &tree { + assert!(matches!(tree, ArenaTokenTree::Token(..))); + } + tree + } + + pub fn push_token_tree(&mut self, tt: &TokenTree) { + match tt { + TokenTree::Token(token, spacing) => { + self.tokens.push(ArenaTokenTree::Token(*token, *spacing)); + } + TokenTree::Delimited(span, spacing, delimiter, stream) => { + let start = self.start_delimited(); + self.fill(stream); + self.close_delimited( + start, + DelimitedData { span: *span, spacing: *spacing, delimiter: *delimiter }, + ); + } + } + } + + pub fn start_delimited(&mut self) -> OpenDelimited { + let index = self.length(); + let parent = self.current_delimited_sequence.replace(index); + + self.tokens.push(ArenaTokenTree::DelimitedStart( + DelimitedBounds { start: index as u32, length: 0, parent: parent.map(|v| v as u32) }, + DelimitedData { + span: DelimSpan { open: Default::default(), close: Default::default() }, + spacing: DelimSpacing { open: Spacing::Alone, close: Spacing::Alone }, + delimiter: Delimiter::Parenthesis, + }, + )); + OpenDelimited { start: index } + } + + pub fn close_delimited(&mut self, open: OpenDelimited, delimited_data: DelimitedData) { + let length = self.length(); + match &mut self.tokens[open.start] { + ArenaTokenTree::Token(..) => { + unreachable!("Called finish_delimited on a token"); + } + ArenaTokenTree::DelimitedStart(bounds, data) => { + let len = length.saturating_sub(open.start); + bounds.length = len as u32; + *data = delimited_data; + self.current_delimited_sequence = bounds.parent.map(|v| v as usize); + } + } + } + + pub fn empty_delimited(&mut self, delimited_data: DelimitedData) { + let start = self.start_delimited(); + self.close_delimited(start, delimited_data); + } + + pub fn get_innermost_elem_at(&self, index: usize) -> Option<&ArenaTokenTree> { + self.tokens.get(index) + } + + pub fn finish(self) -> ArenaTokenStream { + ArenaTokenStream { tokens: Arc::new(self.tokens) } + } + + pub fn length(&self) -> usize { + self.tokens.len() + } + + fn fill(&mut self, stream: &TokenStream) { + for tt in stream.iter() { + self.push_token_tree(tt); + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Encodable, Decodable)] +pub struct ArenaTokenStream { + tokens: Arc>, +} + +impl ArenaTokenStream { + /// Note: using this function is potentially dangerous, because the caller has to ensure that + /// if `tokens` contains any delimited sequences, their indices are lined up and do not refer + /// to anything existing outside of the passed set of tokens. + /// That is why the function is private. + pub fn from_token_vec(tokens: Vec<(Token, Spacing)>) -> Self { + // FIXME: solve this in a better way + Self { + tokens: Arc::new( + tokens + .into_iter() + .map(|(token, spacing)| ArenaTokenTree::Token(token, spacing)) + .collect(), + ), + } + } + + /// Create a new stream out of the token trees. + /// We might need to copy out children trees out of `stream`, if `tokens` contains any + /// delimited sequences. + /// We also need to reparent those to fix-up the parent indices. + pub fn new_reparented(trees: &[ArenaTokenTree], stream: &ArenaTokenStream) -> Self { + let mut builder = ArenaTokenStreamBuilder::with_capacity(trees.len()); + // FIXME: implement this in a more performant way + for tree in trees { + let tree = tree.to_token_tree(stream); + builder.push_token_tree(&tree); + } + builder.finish() + } + + pub fn from_token(token: Token, spacing: Spacing) -> Self { + Self { tokens: Arc::new(vec![ArenaTokenTree::Token(token, spacing)]) } + } + + pub fn from_stream(stream: &TokenStream) -> Self { + let mut arena = ArenaTokenStreamBuilder { + tokens: Vec::with_capacity(stream.len()), + current_delimited_sequence: None, + }; + arena.fill(stream); + arena.finish() + } + + pub fn to_token_stream(&self) -> TokenStream { + let mut tokens = vec![]; + for tt in self.iter_top_level_trees() { + tokens.push(tt.to_token_tree(self)); + } + TokenStream::new(tokens) + } + + /// Extract **the contents** of a delimited sequence out of this token stream. + /// The delimited sequence start/end is **NOT** returend in the output. + /// `stream` is the original token stream that contains the delimited sequence identified by + /// `bounds`. + pub fn separate_delimited_inner( + bounds: DelimitedBounds, + stream: &ArenaTokenStream, + ) -> ArenaTokenStream { + // eprintln!("separate delimited"); + // This could be implemented in a smarter way by reusing the original allocation + // and storing an index with "view" into it. + let start = bounds.start as usize + 1; + let length = (bounds.length as usize).saturating_sub(1); + + let mut tokens = stream.tokens[start..start + length].to_vec(); + let start = start as u32; + + for tree in &mut tokens { + match tree { + ArenaTokenTree::Token(_, _) => {} + ArenaTokenTree::DelimitedStart(b, _) => { + b.start -= start; + b.parent = b.parent.and_then(|p| { + if p < start { + // Top-level, now we will have no parent + None + } else { + Some(p - start) + } + }); + } + } + } + Self { tokens: Arc::new(tokens) } + } + + pub fn length(&self) -> usize { + self.tokens.len() + } + + pub fn is_empty(&self) -> bool { + self.tokens.is_empty() + } + + pub fn get_parent_of(&self, bounds: DelimitedBounds) -> Option { + let parent = bounds.parent?; + match self.tokens.get(parent as usize).expect("Parent index was not found") { + ArenaTokenTree::Token(..) => { + panic!("DelimitedBounds parent index points to a token. This is a bug."); + } + ArenaTokenTree::DelimitedStart(bounds, _) => Some(*bounds), + } + } + + pub fn get_innermost_elem_at(&self, index: usize) -> Option<&ArenaTokenTree> { + self.tokens.get(index) + } + + /// Iter top-level token trees of a delimited token sequence. + pub fn iter_delimited(&self, bounds: &DelimitedBounds) -> impl Iterator { + let mut index = (bounds.start + 1) as usize; + let end = bounds.index_of_next_token_tree(); + std::iter::from_fn(move || { + if index >= end { + return None; + } + let item = self.get_innermost_elem_at(index)?; + match item { + token @ ArenaTokenTree::Token(..) => { + index += 1; + Some(*token) + } + tree @ ArenaTokenTree::DelimitedStart(bounds, _) => { + index = bounds.index_of_next_token_tree(); + Some(*tree) + } + } + }) + } + + pub fn iter_top_level_trees(&self) -> impl Iterator { + let mut index = 0; + let end = self.tokens.len(); + std::iter::from_fn(move || { + if index >= end { + return None; + } + let item = self.get_innermost_elem_at(index)?; + match item { + token @ ArenaTokenTree::Token(..) => { + index += 1; + Some(*token) + } + tree @ ArenaTokenTree::DelimitedStart(bounds, _) => { + index = bounds.index_of_next_token_tree(); + Some(*tree) + } + } + }) + } +} + +impl StableHash for ArenaTokenStream { + fn stable_hash(&self, hcx: &mut Hcx, hasher: &mut StableHasher) { + self.tokens.as_slice().stable_hash(hcx, hasher); + } +} + +pub struct OpenDelimited { + start: usize, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, StableHash)] +pub struct DelimitedBounds { + pub start: u32, + /// The length includes both the start and the end token. + /// So an empty delimited sequence has length 2. + pub length: u32, + /// Index of the parent of the current delimited sequence. + /// If this is the root delimited sequence, is `None`. + pub parent: Option, +} + +impl DelimitedBounds { + /// Return the index of the next token tree that follows this delimited token sequence. + pub fn index_of_next_token_tree(&self) -> usize { + (self.start + self.length) as usize + } + + pub fn is_empty(&self) -> bool { + self.length == 1 + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, StableHash)] +pub struct DelimitedData { + pub span: DelimSpan, + pub spacing: DelimSpacing, + pub delimiter: Delimiter, +} diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index df71aad0111cd..78c1190194d8f 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -20,6 +20,7 @@ use thin_vec::ThinVec; use crate::ast::AttrStyle; use crate::ast_traits::HasTokens; use crate::token::{self, Delimiter, Token, TokenKind}; +use crate::tokenarena::{ArenaTokenStream, ArenaTokenTree, DelimitedBounds, DelimitedData}; use crate::{AttrVec, Attribute}; #[cfg(test)] @@ -900,77 +901,23 @@ impl<'t> Iterator for TokenStreamIter<'t> { } } -#[derive(Clone, Debug)] -struct TokenTreeCursor { - stream: TokenStream, - /// Points to the next token tree (or one past the end of the stream). - next_idx: usize, -} - -impl TokenTreeCursor { - #[inline] - fn new(stream: TokenStream) -> Self { - TokenTreeCursor { stream, next_idx: 0 } - } - - /// Gets the current token tree within this cursor. In a debug build it panics on a cursor that - /// hasn't been bumped; in a release build it will return `None`. - #[inline] - fn curr(&self) -> Option<&TokenTree> { - debug_assert!(self.next_idx > 0); - self.stream.get(self.next_idx - 1) - } - - /// Gets the next token tree without advancing. - #[inline] - fn next(&self) -> Option<&TokenTree> { - self.stream.get(self.next_idx) - } - - /// Gets the token tree `n` ahead. `look_ahead(1)` is equivalent to `next()`. `look_ahead(0)` - /// isn't allowed and will panic. - #[inline] - fn look_ahead(&self, n: usize) -> Option<&TokenTree> { - assert_ne!(n, 0); - self.stream.get(self.next_idx + (n - 1)) - } - - /// Move the cursor to the next token tree. - #[inline] - fn bump(&mut self) { - self.next_idx += 1; - } - - /// For skipping ahead in rare circumstances. - #[inline] - fn bump_to_end(&mut self) { - self.next_idx = self.stream.len(); - } -} - -/// A `TokenStream` cursor that produces `Token`s. It's a bit odd that -/// we (a) lex tokens into a nice tree structure (`TokenStream`), and then (b) -/// use this type to emit them as a linear sequence. But a linear sequence is -/// what the parser expects, for the most part. +/// A `TokenArena` cursor that produces `Token`s. #[derive(Clone, Debug)] pub struct TokenCursor { - // Cursor for the current (innermost) token stream. The `next_idx` within the - // cursor can point to any token tree in the stream (or one past the end). - // The delimiters for this token stream are found in the current token tree - // in `self.stack.last()`; if that is `None` we are in the outermost token - // stream which never has delimiters. - curr: TokenTreeCursor, - - // Token streams surrounding the current one. The `next_idx` within each cursor - // is always greater than zero and always points one past the current - // `TokenTree::Delimited`. - stack: Vec, + pub stream: ArenaTokenStream, + /// Global index into the token arena. + index: usize, + delimited_sequence_end: usize, + depth: u32, + /// The current delimited sequence that we are inside of, if any. + parent: Option, } impl TokenCursor { #[inline] - pub fn new(stream: TokenStream) -> Self { - TokenCursor { curr: TokenTreeCursor::new(stream), stack: vec![] } + pub fn new(stream: ArenaTokenStream) -> Self { + let end = stream.length() + 1; + TokenCursor { stream, index: 0, delimited_sequence_end: end, depth: 0, parent: None } } /// Gets the next token and advances the cursor by one. @@ -979,86 +926,144 @@ impl TokenCursor { } /// An `n` of 1 is the next token tree in the current token stream; won't look outside the - /// current token stream. `look_ahead(0)` isn't allowed and will panic. + /// current delimited sequence. `look_ahead(0)` isn't allowed and will panic. #[inline] - pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { - self.curr.look_ahead(n) + pub fn look_ahead(&self, n: usize) -> Option<&ArenaTokenTree> { + assert_ne!(n, 0); + let mut index = self.index; + for _ in 0..n.saturating_sub(1) { + if index == self.delimited_sequence_end { + return None; + } + let elem = self.stream.get_innermost_elem_at(index); + match elem { + Some(ArenaTokenTree::Token(..)) => { + index += 1; + } + Some(ArenaTokenTree::DelimitedStart(bounds, ..)) => { + // Skip the whole delimited sequence + index = bounds.index_of_next_token_tree(); + } + None => { + // We reached the end of the arena + return None; + } + } + } + if index == self.delimited_sequence_end { + None + } else { + self.stream.get_innermost_elem_at(index) + } } /// Returns the first token tree (if there is one) past the close delimiter of the enclosing /// delimited sequence. Panics if we are not within a delimited sequence. #[inline] - pub fn look_ahead_past_close_delim(&self) -> Option<&TokenTree> { - self.stack.last().unwrap().next() + pub fn look_ahead_past_close_delim(&self) -> Option<&ArenaTokenTree> { + let bounds = self.parent.as_ref().unwrap(); + self.stream.get_innermost_elem_at(bounds.index_of_next_token_tree()) } /// Clones the `TokenTree::Delimited` that we are currently within. Panics if we are not within /// a delimited sequence. #[inline] - pub fn clone_enclosing_delim(&self) -> TokenTree { - self.stack.last().unwrap().curr().unwrap().clone() + pub fn clone_enclosing_delim(&self) -> ArenaTokenTree { + let bounds = self.parent.as_ref().unwrap(); + ArenaTokenTree::DelimitedStart(*bounds, self.get_delimited_data(bounds)) } /// For skipping to the end of the current sequence, in rare circumstances. #[inline] pub fn bump_to_end(&mut self) { - self.curr.bump_to_end() + if let Some(bounds) = self.parent.as_ref() { + self.index = bounds.index_of_next_token_tree(); + } else { + self.index = self.stream.length(); + } } /// Note: the outermost stream has depth of 0. #[inline] pub fn depth(&self) -> usize { - self.stack.len() + self.depth as usize } /// Returns details about the parent delimited sequence, if there is one. #[inline] pub fn parent_delim_and_span(&self) -> Option<(Delimiter, DelimSpan)> { - if let Some(last) = self.stack.last() - && let Some(TokenTree::Delimited(span, _, delim, _)) = last.curr() - { - Some((*delim, *span)) + if let Some(bounds) = self.parent.as_ref() { + let data = self.get_delimited_data(bounds); + Some((data.delimiter, data.span)) } else { None } } + fn get_delimited_data(&self, bounds: &DelimitedBounds) -> DelimitedData { + let Some(ArenaTokenTree::DelimitedStart(_, data)) = + self.stream.get_innermost_elem_at(bounds.start as usize) + else { + panic!("Delimited sequence not found at the provided bounds"); + }; + *data + } + /// This always-inlined version should only be used on hot code paths. #[inline(always)] pub fn inlined_next_and_bump(&mut self) -> (Token, Spacing) { loop { + if self.index == self.delimited_sequence_end { + let bounds = self.parent.take().unwrap(); + self.depth -= 1; + + // Find the previous parent + self.parent = self.stream.get_parent_of(bounds); + + // How much is left for the now-current sequence? + self.delimited_sequence_end = self + .parent + .as_ref() + .map(|bounds| bounds.index_of_next_token_tree()) + .unwrap_or(self.stream.length() + 1); + + let data = self.get_delimited_data(&bounds); + if !data.delimiter.skip() { + return ( + Token::new(data.delimiter.as_close_token_kind(), data.span.close), + data.spacing.close, + ); + } + continue; + } + // FIXME: we currently don't return `Delimiter::Invisible` open/close delims. To fix // #67062 we will need to, whereupon the `delim != Delimiter::Invisible` conditions // below can be removed. - if let Some(tree) = self.curr.next() { + if let Some(tree) = self.stream.get_innermost_elem_at(self.index) { match tree { - &TokenTree::Token(token, spacing) => { + &ArenaTokenTree::Token(token, spacing) => { debug_assert!(!token.kind.is_delim()); - let res = (token, spacing); - self.curr.bump(); - return res; + self.index += 1; + return (token, spacing); } - &TokenTree::Delimited(sp, spacing, delim, ref tts) => { - let trees = TokenTreeCursor::new(tts.clone()); - self.curr.bump(); // move past the `Delimited` - self.stack.push(mem::replace(&mut self.curr, trees)); - if !delim.skip() { - return (Token::new(delim.as_open_token_kind(), sp.open), spacing.open); + &ArenaTokenTree::DelimitedStart(bounds, data) => { + self.index += 1; + self.depth += 1; + self.delimited_sequence_end = bounds.index_of_next_token_tree(); + self.parent = Some(bounds); + if !data.delimiter.skip() { + return ( + Token::new(data.delimiter.as_open_token_kind(), data.span.open), + data.spacing.open, + ); } // No open delimiter to return; continue on to the next iteration. } - }; - } else if let Some(parent) = self.stack.pop() { - // We have exhausted this token stream. Move back to its parent token stream. - let Some(&TokenTree::Delimited(span, spacing, delim, _)) = parent.curr() else { - panic!("parent should be Delimited") - }; - self.curr = parent; - if !delim.skip() { - return (Token::new(delim.as_close_token_kind(), span.close), spacing.close); } - // No close delimiter to return; continue on to the next iteration. } else { + assert!(self.parent.is_none()); + // We have exhausted the outermost token stream. The use of // `Spacing::Alone` is arbitrary and immaterial, because the // `Eof` token's spacing is never used. @@ -1115,7 +1120,7 @@ mod size_asserts { static_assert_size!(AttrTokenStream, 8); static_assert_size!(AttrTokenTree, 32); static_assert_size!(LazyAttrTokenStream, 8); - static_assert_size!(LazyAttrTokenStreamInner, 88); + static_assert_size!(LazyAttrTokenStreamInner, 96); static_assert_size!(Option, 8); // must be small, used in many AST nodes static_assert_size!(TokenStream, 8); static_assert_size!(TokenTree, 32); diff --git a/compiler/rustc_ast/src/tokenstream/tests.rs b/compiler/rustc_ast/src/tokenstream/tests.rs index 6c7e82a97c58e..d3559777b7570 100644 --- a/compiler/rustc_ast/src/tokenstream/tests.rs +++ b/compiler/rustc_ast/src/tokenstream/tests.rs @@ -1,7 +1,8 @@ use rustc_span::DUMMY_SP; -use crate::token::TokenKind; -use crate::tokenstream::TokenStream; +use crate::token::{Delimiter, Token, TokenKind}; +use crate::tokenarena::{ArenaTokenStreamBuilder, DelimitedData}; +use crate::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenCursor, TokenStream}; #[test] fn test_token_stream_iter() { @@ -11,3 +12,33 @@ fn test_token_stream_iter() { let iter = ts.iter(); assert_eq!(iter.size_hint(), (1, Some(1))); } + +#[test] +fn foo() { + let mut arena = ArenaTokenStreamBuilder::default(); + let open1 = arena.start_delimited(); + arena.push_token_alone(Token::new(TokenKind::Plus, DUMMY_SP)); + let open2 = arena.start_delimited(); + arena.push_token_alone(Token::new(TokenKind::Plus, DUMMY_SP)); + arena.close_delimited( + open2, + DelimitedData { + span: DelimSpan::from_single(DUMMY_SP), + spacing: DelimSpacing { open: Spacing::Alone, close: Spacing::Alone }, + delimiter: Delimiter::Parenthesis, + }, + ); + arena.close_delimited( + open1, + DelimitedData { + span: DelimSpan::from_single(DUMMY_SP), + spacing: DelimSpacing { open: Spacing::Alone, close: Spacing::Alone }, + delimiter: Delimiter::Parenthesis, + }, + ); + + let mut cursor = TokenCursor::new(arena); + for _ in 0..100 { + cursor.next_and_bump(); + } +} diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index 14ef1c147f253..a4eedf71c630d 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -354,6 +354,7 @@ macro_rules! common_visitor_and_walkers { crate::token::LitKind, crate::tokenstream::LazyAttrTokenStream, crate::tokenstream::TokenStream, + crate::tokenarena::ArenaTokenStream, Movability, Mutability, Pinnedness, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index a27dc47bf27c3..849187e30ac57 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -43,6 +43,7 @@ use std::sync::Arc; use rustc_ast::mut_visit::{self, MutVisitor}; use rustc_ast::node_id::NodeMap; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::visit::{self, Visitor}; use rustc_ast::{self as ast, *}; use rustc_attr_parsing::{AttributeParser, Recovery, ShouldEmit}; @@ -631,7 +632,7 @@ fn index_ast<'tcx>( dummy: impl FnOnce(Box) -> K, ) -> Box> { use rustc_ast::token::Delimiter; - use rustc_ast::tokenstream::{DelimSpan, TokenStream}; + use rustc_ast::tokenstream::DelimSpan; use thin_vec::thin_vec; Box::new(Item { @@ -646,7 +647,7 @@ fn index_ast<'tcx>( args: Box::new(DelimArgs { dspan: DelimSpan::from_single(span), delim: Delimiter::Parenthesis, - tokens: TokenStream::new(Vec::new()), + tokens: ArenaTokenStream::default(), }), })), tokens: None, diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 977eb0ee4592d..040a53814343c 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -715,7 +715,7 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere None, *delim, None, - tokens, + &tokens.to_token_stream(), true, span, ), @@ -926,7 +926,7 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere Some(*ident), macro_def.body.delim, None, - ¯o_def.body.tokens, + ¯o_def.body.tokens.to_token_stream(), true, sp, ); @@ -1674,7 +1674,7 @@ impl<'a> State<'a> { None, m.args.delim, None, - &m.args.tokens, + &m.args.tokens.to_token_stream(), true, m.span(), ); diff --git a/compiler/rustc_attr_ir/src/attr.rs b/compiler/rustc_attr_ir/src/attr.rs index 6068c11590a23..5126edd8d8cf5 100644 --- a/compiler/rustc_attr_ir/src/attr.rs +++ b/compiler/rustc_attr_ir/src/attr.rs @@ -154,7 +154,7 @@ impl AttributeExt for Attribute { match &self { Attribute::Unparsed(n) => match n.as_ref() { AttrItem { args: AttrArgs::Delimited(d), .. } => { - ast::MetaItemKind::list_from_tokens(d.tokens.clone()) + ast::MetaItemKind::list_from_tokens(d.tokens.to_token_stream()) } _ => None, }, diff --git a/compiler/rustc_attr_parsing/src/parser.rs b/compiler/rustc_attr_parsing/src/parser.rs index 8efe5bf4f1f90..d3e029e52f99f 100644 --- a/compiler/rustc_attr_parsing/src/parser.rs +++ b/compiler/rustc_attr_parsing/src/parser.rs @@ -14,6 +14,7 @@ use std::fmt::{Debug, Display}; use std::sync::atomic::{AtomicBool, Ordering}; use rustc_ast::token::{self, Delimiter, MetaVarKind}; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::tokenstream::TokenStream; use rustc_ast::{ AttrArgs, Expr, ExprKind, LitKind, MetaItemLit, Path, PathSegment, StmtKind, UnOp, @@ -132,7 +133,7 @@ impl ArgParser { // Therefore we can substitute with a dummy value on invalid syntax. if matches!(parts, [sym::rustc_dummy] | [sym::diagnostic, ..]) { match MetaItemListParser::new( - &args.tokens, + &args.tokens.to_token_stream(), args.dspan.entire(), psess, ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden }, @@ -163,7 +164,7 @@ impl ArgParser { Self::List( MetaItemListParser::new( - &args.tokens, + &args.tokens.to_token_stream(), args.dspan.entire(), psess, should_emit, @@ -721,13 +722,13 @@ impl<'a, 'sess> MetaItemListParserContext<'a, 'sess> { } fn parse( - tokens: TokenStream, + stream: ArenaTokenStream, psess: &'sess ParseSess, span: Span, should_emit: ShouldEmit, allow_expr_metavar: AllowExprMetavar, ) -> PResult<'sess, MetaItemListParser> { - let mut parser = Parser::new(psess, tokens, None); + let mut parser = Parser::new(psess, stream, None); if let ShouldEmit::ErrorsAndLints { recovery } = should_emit { parser = parser.recovery(recovery); } @@ -764,7 +765,7 @@ impl MetaItemListParser { allow_expr_metavar: AllowExprMetavar, ) -> Result> { MetaItemListParserContext::parse( - tokens.clone(), + ArenaTokenStream::from_stream(tokens), psess, span, should_emit, diff --git a/compiler/rustc_builtin_macros/src/assert.rs b/compiler/rustc_builtin_macros/src/assert.rs index 106b67d1c8ec7..6c6f4aa404d57 100644 --- a/compiler/rustc_builtin_macros/src/assert.rs +++ b/compiler/rustc_builtin_macros/src/assert.rs @@ -1,6 +1,7 @@ mod context; use rustc_ast::token::Delimiter; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::tokenstream::{DelimSpan, TokenStream}; use rustc_ast::{DelimArgs, Expr, ExprKind, MacCall, Path, PathSegment, UnOp, token}; use rustc_ast_pretty::pprust; @@ -58,7 +59,7 @@ pub(crate) fn expand_assert<'cx>( args: Box::new(DelimArgs { dspan: DelimSpan::from_single(call_site_span), delim: Delimiter::Parenthesis, - tokens, + tokens: ArenaTokenStream::from_stream(&tokens), }), })), ); diff --git a/compiler/rustc_builtin_macros/src/assert/context.rs b/compiler/rustc_builtin_macros/src/assert/context.rs index 80ea2e3d877fc..987a8886117c1 100644 --- a/compiler/rustc_builtin_macros/src/assert/context.rs +++ b/compiler/rustc_builtin_macros/src/assert/context.rs @@ -1,5 +1,6 @@ -use rustc_ast::token::{self, Delimiter, IdentIsRaw}; -use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree}; +use rustc_ast::token::{self, Delimiter, IdentIsRaw, Token}; +use rustc_ast::tokenarena::ArenaTokenStream; +use rustc_ast::tokenstream::{DelimSpan, Spacing}; use rustc_ast::{ BinOpKind, BorrowKind, DUMMY_NODE_ID, DelimArgs, Expr, ExprKind, ItemKind, MacCall, MethodCall, Mutability, Path, PathSegment, Stmt, StructRest, UnOp, UseTree, UseTreeKind, @@ -145,30 +146,33 @@ impl<'cx, 'a> Context<'cx, 'a> { fn build_panic(&self, expr_str: &str, panic_path: Path) -> Box { let escaped_expr_str = escape_to_fmt(expr_str); let initial = [ - TokenTree::token_joint( - token::Literal(token::Lit { - kind: token::LitKind::Str, - symbol: Symbol::intern(&if self.fmt_string.is_empty() { - format!("Assertion failed: {escaped_expr_str}") - } else { - format!( - "Assertion failed: {escaped_expr_str}\nWith captures:\n{}", - self.fmt_string - ) + ( + Token::new( + token::Literal(token::Lit { + kind: token::LitKind::Str, + symbol: Symbol::intern(&if self.fmt_string.is_empty() { + format!("Assertion failed: {escaped_expr_str}") + } else { + format!( + "Assertion failed: {escaped_expr_str}\nWith captures:\n{}", + self.fmt_string + ) + }), + suffix: None, }), - suffix: None, - }), - self.span, + self.span, + ), + Spacing::Joint, ), - TokenTree::token_alone(token::Comma, self.span), + (Token::new(token::Comma, self.span), Spacing::Alone), ]; let captures = self.capture_decls.iter().flat_map(|cap| { [ - TokenTree::token_joint( - token::Ident(cap.ident.name, IdentIsRaw::No), - cap.ident.span, + ( + Token::new(token::Ident(cap.ident.name, IdentIsRaw::No), cap.ident.span), + Spacing::Joint, ), - TokenTree::token_alone(token::Comma, self.span), + (Token::new(token::Comma, self.span), Spacing::Alone), ] }); self.cx.expr( @@ -178,7 +182,9 @@ impl<'cx, 'a> Context<'cx, 'a> { args: Box::new(DelimArgs { dspan: DelimSpan::from_single(self.span), delim: Delimiter::Parenthesis, - tokens: initial.into_iter().chain(captures).collect::(), + tokens: ArenaTokenStream::from_token_vec( + initial.into_iter().chain(captures).collect(), + ), }), })), ) diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs index 5a9988e076b0d..d79ea09d563e4 100644 --- a/compiler/rustc_builtin_macros/src/autodiff.rs +++ b/compiler/rustc_builtin_macros/src/autodiff.rs @@ -11,6 +11,7 @@ mod llvm_enzyme { DiffActivity, DiffMode, valid_input_activity, valid_ret_activity, valid_ty_for_activity, }; use rustc_ast::token::{Lit, LitKind, Token, TokenKind}; + use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::tokenstream::*; use rustc_ast::visit::AssocCtxt::*; use rustc_ast::{ @@ -153,12 +154,12 @@ mod llvm_enzyme { } } - fn meta_item_inner_to_ts(t: &MetaItemInner, ts: &mut Vec) { + fn meta_item_inner_to_ts(t: &MetaItemInner, ts: &mut Vec<(Token, Spacing)>) { let comma: Token = Token::new(TokenKind::Comma, Span::default()); let val = first_ident(t); let t = Token::from_ast_ident(val); - ts.push(TokenTree::Token(t, Spacing::Joint)); - ts.push(TokenTree::Token(comma, Spacing::Alone)); + ts.push((t, Spacing::Joint)); + ts.push((comma, Spacing::Alone)); } pub(crate) fn expand_forward( @@ -250,7 +251,7 @@ mod llvm_enzyme { // create TokenStream from vec elemtents: // meta_item doesn't have a .tokens field - let mut ts: Vec = vec![]; + let mut ts: Vec<(Token, Spacing)> = vec![]; if meta_item_vec.is_empty() { // At the bare minimum, we need a fnc name. dcx.emit_err(diagnostics::AutoDiffMissingConfig { span: item.span() }); @@ -265,11 +266,8 @@ mod llvm_enzyme { // Insert mode token let mode_token = Token::new(TokenKind::Ident(mode_symbol, false.into()), Span::default()); - ts.insert(0, TokenTree::Token(mode_token, Spacing::Joint)); - ts.insert( - 1, - TokenTree::Token(Token::new(TokenKind::Comma, Span::default()), Spacing::Alone), - ); + ts.insert(0, (mode_token, Spacing::Joint)); + ts.insert(1, (Token::new(TokenKind::Comma, Span::default()), Spacing::Alone)); // Now, if the user gave a width (vector aka batch-mode ad), then we copy it. // If it is not given, we default to 1 (scalar mode). @@ -289,8 +287,8 @@ mod llvm_enzyme { let l: Lit = Lit { kind, symbol, suffix: None }; let t = Token::new(TokenKind::Literal(l), Span::default()); let comma = Token::new(TokenKind::Comma, Span::default()); - ts.push(TokenTree::Token(t, Spacing::Joint)); - ts.push(TokenTree::Token(comma, Spacing::Alone)); + ts.push((t, Spacing::Joint)); + ts.push((comma, Spacing::Alone)); for t in meta_item_vec.clone()[start_position..].iter() { meta_item_inner_to_ts(t, &mut ts); @@ -300,12 +298,11 @@ mod llvm_enzyme { // We don't want users to provide a return activity if the function doesn't return anything. // For simplicity, we just add a dummy token to the end of the list. let t = Token::new(TokenKind::Ident(sym::None, false.into()), Span::default()); - ts.push(TokenTree::Token(t, Spacing::Joint)); - ts.push(TokenTree::Token(comma, Spacing::Alone)); + ts.push((t, Spacing::Joint)); + ts.push((comma, Spacing::Alone)); } // We remove the last, trailing comma. ts.pop(); - let ts: TokenStream = TokenStream::from_iter(ts); let x: RustcAutodiff = from_ast(ecx, &meta_item_vec, has_ret, mode); if !x.is_active() { @@ -345,14 +342,13 @@ mod llvm_enzyme { let mut rustc_ad_attr = Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff))); - let ts2: Vec = vec![TokenTree::Token( - Token::new(TokenKind::Ident(sym::never, false.into()), span), - Spacing::Joint, - )]; let never_arg = ast::DelimArgs { dspan: DelimSpan::from_single(span), delim: ast::token::Delimiter::Parenthesis, - tokens: TokenStream::from_iter(ts2), + tokens: ArenaTokenStream::from_token( + Token::new(TokenKind::Ident(sym::never, false.into()), span), + Spacing::Joint, + ), }; let inline_item = ast::AttrItem { unsafety: ast::Safety::Default, @@ -423,7 +419,7 @@ mod llvm_enzyme { rustc_ad_attr.item.args = rustc_ast::AttrArgs::Delimited(rustc_ast::DelimArgs { dspan: DelimSpan::dummy(), delim: rustc_ast::token::Delimiter::Parenthesis, - tokens: ts, + tokens: ArenaTokenStream::from_token_vec(ts), }); let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id(); diff --git a/compiler/rustc_builtin_macros/src/cfg_eval.rs b/compiler/rustc_builtin_macros/src/cfg_eval.rs index 34ddd9427cdde..8ad47ea566a0e 100644 --- a/compiler/rustc_builtin_macros/src/cfg_eval.rs +++ b/compiler/rustc_builtin_macros/src/cfg_eval.rs @@ -2,6 +2,7 @@ use core::ops::ControlFlow; use rustc_ast as ast; use rustc_ast::mut_visit::MutVisitor; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::visit::{AssocCtxt, Visitor}; use rustc_ast::{Attribute, HasTokens, NodeId, mut_visit, visit}; use rustc_errors::PResult; @@ -105,7 +106,8 @@ impl CfgEval<'_> { // // After that we have our re-parsed `AttrTokenStream`, recursively configuring // our attribute target will correctly configure the tokens as well. - let mut parser = Parser::new(&self.0.sess.psess, orig_tokens, None); + let mut parser = + Parser::new(&self.0.sess.psess, ArenaTokenStream::from_stream(&orig_tokens), None); parser.capture_cfg = true; let res: PResult<'_, Option> = try { match &annotatable { diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index 6a53dafd396df..01ce5b3c5b083 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -180,7 +180,8 @@ use std::{iter, vec}; pub(crate) use StaticFields::*; pub(crate) use SubstructureFields::*; use rustc_ast::token::{IdentIsRaw, LitKind, Token, TokenKind}; -use rustc_ast::tokenstream::{DelimSpan, Spacing, TokenTree}; +use rustc_ast::tokenarena::ArenaTokenStream; +use rustc_ast::tokenstream::{DelimSpan, Spacing}; use rustc_ast::{ self as ast, AnonConst, AttrArgs, BindingMode, ByRef, DelimArgs, EnumDef, Expr, GenericArg, GenericParamKind, Generics, Mutability, PatKind, Safety, SelfKind, VariantData, @@ -806,20 +807,20 @@ impl<'a> TraitDef<'a> { args: AttrArgs::Delimited(DelimArgs { dspan: DelimSpan::from_single(self.span), delim: rustc_ast::token::Delimiter::Parenthesis, - tokens: [ - TokenKind::Ident(sym::feature, IdentIsRaw::No), - TokenKind::Eq, - TokenKind::lit(LitKind::Str, sym::derive_const, None), - TokenKind::Comma, - TokenKind::Ident(sym::issue, IdentIsRaw::No), - TokenKind::Eq, - TokenKind::lit(LitKind::Str, sym::derive_const_issue, None), - ] - .into_iter() - .map(|kind| { - TokenTree::Token(Token { kind, span: self.span }, Spacing::Alone) - }) - .collect(), + tokens: ArenaTokenStream::from_token_vec( + [ + TokenKind::Ident(sym::feature, IdentIsRaw::No), + TokenKind::Eq, + TokenKind::lit(LitKind::Str, sym::derive_const, None), + TokenKind::Comma, + TokenKind::Ident(sym::issue, IdentIsRaw::No), + TokenKind::Eq, + TokenKind::lit(LitKind::Str, sym::derive_const_issue, None), + ] + .into_iter() + .map(|kind| (Token { kind, span: self.span }, Spacing::Alone)) + .collect(), + ), }), span: self.span, }, diff --git a/compiler/rustc_builtin_macros/src/deriving/reborrow.rs b/compiler/rustc_builtin_macros/src/deriving/reborrow.rs index 9dc1ccf4fd8e6..e144d28770172 100644 --- a/compiler/rustc_builtin_macros/src/deriving/reborrow.rs +++ b/compiler/rustc_builtin_macros/src/deriving/reborrow.rs @@ -106,7 +106,7 @@ fn coerce_shared_target(cx: &ExtCtxt<'_>, span: Span, item: &Annotatable) -> Opt return None; } - let mut parser = cx.new_parser_from_tts(args.tokens.clone()); + let mut parser = cx.new_parser_from_tts(args.tokens.to_token_stream()); let target = match parser.parse_ty() { Ok(target) => target, Err(err) => { diff --git a/compiler/rustc_builtin_macros/src/edition_panic.rs b/compiler/rustc_builtin_macros/src/edition_panic.rs index ac5c43c660088..3fa49a3921d25 100644 --- a/compiler/rustc_builtin_macros/src/edition_panic.rs +++ b/compiler/rustc_builtin_macros/src/edition_panic.rs @@ -1,4 +1,5 @@ use rustc_ast::token::Delimiter; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::tokenstream::{DelimSpan, TokenStream}; use rustc_ast::*; use rustc_expand::base::*; @@ -59,7 +60,7 @@ fn expand<'cx>( args: Box::new(DelimArgs { dspan: DelimSpan::from_single(sp), delim: Delimiter::Parenthesis, - tokens: tts, + tokens: ArenaTokenStream::from_stream(&tts), }), })), ), diff --git a/compiler/rustc_builtin_macros/src/eii.rs b/compiler/rustc_builtin_macros/src/eii.rs index 89fc222def5ff..dca20522562da 100644 --- a/compiler/rustc_builtin_macros/src/eii.rs +++ b/compiler/rustc_builtin_macros/src/eii.rs @@ -1,5 +1,6 @@ -use rustc_ast::token::{Delimiter, TokenKind}; -use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; +use rustc_ast::token::{Delimiter, Token, TokenKind}; +use rustc_ast::tokenarena::{ArenaTokenStreamBuilder, DelimitedData}; +use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing}; use rustc_ast::{ AttrKind, Attribute, DUMMY_NODE_ID, EiiDecl, EiiImpl, ItemKind, MetaItem, Mutability, Path, StmtKind, SyntheticAttr, Visibility, ast, @@ -498,21 +499,21 @@ fn generate_attribute_macro_to_implement( body: Box::new(ast::DelimArgs { dspan: DelimSpan::from_single(span), delim: Delimiter::Brace, - tokens: TokenStream::from_iter([ - TokenTree::Delimited( - DelimSpan::from_single(span), - DelimSpacing::new(Spacing::Alone, Spacing::Alone), - Delimiter::Parenthesis, - TokenStream::default(), - ), - TokenTree::token_alone(TokenKind::FatArrow, span), - TokenTree::Delimited( - DelimSpan::from_single(span), - DelimSpacing::new(Spacing::Alone, Spacing::Alone), - Delimiter::Brace, - TokenStream::default(), - ), - ]), + tokens: { + let mut builder = ArenaTokenStreamBuilder::with_capacity(3); + builder.empty_delimited(DelimitedData { + span: DelimSpan::from_single(span), + spacing: DelimSpacing::new(Spacing::Alone, Spacing::Alone), + delimiter: Delimiter::Parenthesis, + }); + builder.push_token_alone(Token::new(TokenKind::FatArrow, span)); + builder.empty_delimited(DelimitedData { + span: DelimSpan::from_single(span), + spacing: DelimSpacing::new(Spacing::Alone, Spacing::Alone), + delimiter: Delimiter::Brace, + }); + builder.finish() + }, }), macro_rules: false, // #[eii_declaration(foreign_item_ident)] diff --git a/compiler/rustc_builtin_macros/src/offload.rs b/compiler/rustc_builtin_macros/src/offload.rs index 4111843b0c9d8..c8d170cc3e819 100644 --- a/compiler/rustc_builtin_macros/src/offload.rs +++ b/compiler/rustc_builtin_macros/src/offload.rs @@ -1,6 +1,7 @@ use rustc_ast::ast; use rustc_ast::token::{Delimiter, Token, TokenKind}; -use rustc_ast::tokenstream::{DelimSpan, Spacing, TokenStream, TokenTree}; +use rustc_ast::tokenarena::ArenaTokenStream; +use rustc_ast::tokenstream::{DelimSpan, Spacing}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_session::config::Offload; use rustc_span::{DUMMY_SP, Ident, Span, sym}; @@ -125,7 +126,7 @@ pub(crate) fn expand_kernel( [sym::core, sym::unimplemented].map(|s| Ident::new(s, span)).to_vec(), ), Delimiter::Parenthesis, - TokenStream::default(), + ArenaTokenStream::default(), ), ); let stmt = ecx.stmt_expr(macro_expr); @@ -148,15 +149,13 @@ pub(crate) fn expand_kernel( } // inline(never) attr - let ts: Vec = vec![TokenTree::Token( - Token::new(TokenKind::Ident(sym::never, false.into()), span), - Spacing::Joint, - )]; - let never_arg = ast::DelimArgs { dspan: DelimSpan::from_single(span), delim: Delimiter::Parenthesis, - tokens: TokenStream::from_iter(ts), + tokens: ArenaTokenStream::from_token( + Token::new(TokenKind::Ident(sym::never, false.into()), span), + Spacing::Joint, + ), }; let inline_item = ast::AttrItem { diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index fda75319b087b..def95be041f20 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -6,6 +6,7 @@ use std::rc::Rc; use std::sync::Arc; use rustc_ast::attr::MarkedAttrs; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::tokenstream::TokenStream; use rustc_ast::visit::{AssocCtxt, Visitor}; use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind, Safety}; @@ -1258,7 +1259,7 @@ impl<'a> ExtCtxt<'a> { expand::MacroExpander::new(self, true) } pub fn new_parser_from_tts(&self, stream: TokenStream) -> Parser<'a> { - Parser::new(&self.sess.psess, stream, MACRO_ARGUMENTS) + Parser::new(&self.sess.psess, ArenaTokenStream::from_stream(&stream), MACRO_ARGUMENTS) } pub fn source_map(&self) -> &'a SourceMap { self.sess.psess.source_map() diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index 2240fe115fde3..1545299f7a32e 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -1,5 +1,5 @@ use rustc_ast::token::Delimiter; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::util::literal; use rustc_ast::{ self as ast, AnonConst, AttrItem, AttrVec, BlockCheckMode, Expr, LocalKind, MatchKind, PatKind, @@ -56,7 +56,7 @@ impl<'a> ExtCtxt<'a> { span: Span, path: ast::Path, delim: Delimiter, - tokens: TokenStream, + tokens: ArenaTokenStream, ) -> Box { Box::new(ast::MacCall { path, @@ -486,7 +486,7 @@ impl<'a> ExtCtxt<'a> { [sym::std, sym::unreachable].map(|s| Ident::new(s, span)).to_vec(), ), Delimiter::Parenthesis, - TokenStream::default(), + ArenaTokenStream::default(), ), ) } diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index c58629111ac00..811c2c1e9d2f2 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -725,7 +725,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { ExpandResult::Ready(match invoc.kind { InvocationKind::Bang { mac, span } => { if let SyntaxExtensionKind::Bang(expander) = ext { - match expander.expand(self.cx, span, mac.args.tokens.clone()) { + match expander.expand(self.cx, span, mac.args.tokens.to_token_stream()) { Ok(tok_result) => { let fragment = self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span); @@ -743,16 +743,17 @@ impl<'a, 'b> MacroExpander<'a, 'b> { Err(guar) => return ExpandResult::Ready(fragment_kind.dummy(span, guar)), } } else if let Some(expander) = ext.as_legacy_bang() { - let tok_result = match expander.expand(self.cx, span, mac.args.tokens.clone()) { - ExpandResult::Ready(tok_result) => tok_result, - ExpandResult::Retry(_) => { - // retry the original - return ExpandResult::Retry(Invocation { - kind: InvocationKind::Bang { mac, span }, - ..invoc - }); - } - }; + let tok_result = + match expander.expand(self.cx, span, mac.args.tokens.to_token_stream()) { + ExpandResult::Ready(tok_result) => tok_result, + ExpandResult::Retry(_) => { + // retry the original + return ExpandResult::Retry(Invocation { + kind: InvocationKind::Bang { mac, span }, + ..invoc + }); + } + }; if let Some(fragment) = fragment_kind.make_from(tok_result) { if macro_stats { update_bang_macro_stats(self.cx, fragment_kind, span, mac, &fragment); @@ -777,6 +778,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { // we are invoking it on an out-of-line module or crate. Annotatable::Crate(krate) => { rustc_parse::fake_token_stream_for_crate(&self.cx.sess.psess, krate) + .to_token_stream() } Annotatable::Item(item_inner) if matches!(attr.style, AttrStyle::Inner) @@ -795,6 +797,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { item_inner, Some(&attr), ) + .to_token_stream() } Annotatable::Item(item_inner) if item_inner.tokens.is_none() => { rustc_parse::fake_token_stream_for_item( @@ -802,6 +805,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { item_inner, None, ) + .to_token_stream() } // When a function has EII implementations attached (via `eii_impl`), // use fake tokens so the pretty-printer re-emits the EII attribute @@ -818,12 +822,14 @@ impl<'a, 'b> MacroExpander<'a, 'b> { item_inner, None, ) + .to_token_stream() } Annotatable::ForeignItem(item_inner) if item_inner.tokens.is_none() => { rustc_parse::fake_token_stream_for_foreign_item( &self.cx.sess.psess, item_inner, ) + .to_token_stream() } _ => item.to_tokens(), }; diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index b268b8b767327..00a987f70fb3b 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -7,7 +7,8 @@ use ast::token::IdentIsRaw; use rustc_ast::token::NtPatKind::*; use rustc_ast::token::TokenKind::*; use rustc_ast::token::{self, Delimiter, NonterminalKind, Token, TokenKind}; -use rustc_ast::tokenstream::{self, DelimSpan, TokenStream}; +use rustc_ast::tokenarena::{ArenaTokenStream, DelimitedBounds, DelimitedData}; +use rustc_ast::tokenstream::{DelimSpan, TokenStream}; use rustc_ast::{self as ast, DUMMY_NODE_ID, NodeId, Safety}; use rustc_ast_pretty::pprust; use rustc_attr_ir::diagnostic::Directive; @@ -132,7 +133,7 @@ impl<'a, 'b> ParserAnyMacro<'a, 'b> { matched_rule_bindings: &'b [MatcherLoc], ) -> Self { Self { - parser: Parser::new(&cx.sess.psess, tts, None), + parser: Parser::new(&cx.sess.psess, ArenaTokenStream::from_stream(&tts), None), // Pass along the original expansion site and the name of the macro // so we can print a useful error message if the parse of the expanded @@ -822,9 +823,17 @@ pub fn compile_declarative_macro( if let Some(guar) = check_no_eof(sess, &p, "expected macro attr args") { return dummy_syn_ext(guar); } - let args = p.parse_token_tree(); - check_args_parens(sess, sym::attr, &args); - let args = parse_one_tt(args, RulePart::Pattern, sess, node_id, features, edition); + let tt = p.parse_token_tree(); + let args = tt.to_delimited_data(); + check_args_parens(sess, sym::attr, args); + let args = parse_one_tt( + tt.to_token_tree(p.token_stream()), + RulePart::Pattern, + sess, + node_id, + features, + edition, + ); check_emission(check_lhs(sess, features, node_id, &args)); if let Some(guar) = check_no_eof(sess, &p, "expected macro attr body") { return dummy_syn_ext(guar); @@ -844,9 +853,10 @@ pub fn compile_declarative_macro( if let Some(guar) = check_no_eof(sess, &p, "expected `()` after `derive`") { return dummy_syn_ext(guar); } - let args = p.parse_token_tree(); - check_args_parens(sess, sym::derive, &args); - let args_empty_result = check_args_empty(sess, &args); + let tt = p.parse_token_tree(); + let args = tt.to_delimited_data(); + check_args_parens(sess, sym::derive, args); + let args_empty_result = check_args_empty(sess, tt.to_delimited_bounds(), tt.span()); let args_not_empty = args_empty_result.is_err(); check_emission(args_empty_result); if let Some(guar) = check_no_eof(sess, &p, "expected macro derive body") { @@ -872,7 +882,7 @@ pub fn compile_declarative_macro( } (None, false) }; - let lhs_tt = p.parse_token_tree(); + let lhs_tt = p.parse_token_tree().to_token_tree(p.token_stream()); let lhs_tt = parse_one_tt(lhs_tt, RulePart::Pattern, sess, node_id, features, edition); check_emission(check_lhs(sess, features, node_id, &lhs_tt)); if let Err(e) = p.expect(exp!(FatArrow)) { @@ -881,7 +891,7 @@ pub fn compile_declarative_macro( if let Some(guar) = check_no_eof(sess, &p, "expected right-hand side of macro rule") { return dummy_syn_ext(guar); } - let rhs = p.parse_token_tree(); + let rhs = p.parse_token_tree().to_token_tree(p.token_stream()); let rhs = parse_one_tt(rhs, RulePart::Body, sess, node_id, features, edition); check_emission(check_rhs(sess, &rhs)); check_emission(check_meta_variables(&sess.psess, node_id, args.as_ref(), &lhs_tt, &rhs)); @@ -961,25 +971,32 @@ fn check_no_eof(sess: &Session, p: &Parser<'_>, msg: &'static str) -> Option) { // This does not handle the non-delimited case; that gets handled separately by `check_lhs`. - if let tokenstream::TokenTree::Delimited(dspan, _, delim, _) = args - && *delim != Delimiter::Parenthesis + if let Some(data) = args + && data.delimiter != Delimiter::Parenthesis { sess.dcx().emit_err(diagnostics::MacroArgsBadDelim { - span: dspan.entire(), - sugg: diagnostics::MacroArgsBadDelimSugg { open: dspan.open, close: dspan.close }, + span: data.span.entire(), + sugg: diagnostics::MacroArgsBadDelimSugg { + open: data.span.open, + close: data.span.close, + }, rule_kw, }); } } -fn check_args_empty(sess: &Session, args: &tokenstream::TokenTree) -> Result<(), ErrorGuaranteed> { +fn check_args_empty( + sess: &Session, + args: Option<&DelimitedBounds>, + span: Span, +) -> Result<(), ErrorGuaranteed> { match args { - tokenstream::TokenTree::Delimited(.., delimited) if delimited.is_empty() => Ok(()), + Some(bounds) if bounds.is_empty() => Ok(()), _ => { let msg = "`derive` rules do not accept arguments; `derive` must be followed by `()`"; - Err(sess.dcx().span_err(args.span(), msg)) + Err(sess.dcx().span_err(span, msg)) } } } @@ -1869,5 +1886,6 @@ pub(super) fn parser_from_cx( recovery: Recovery, ) -> Parser<'_> { tts.desugar_doc_comments(); - Parser::new(psess, tts, rustc_parse::MACRO_ARGUMENTS).recovery(recovery) + Parser::new(psess, ArenaTokenStream::from_stream(&tts), rustc_parse::MACRO_ARGUMENTS) + .recovery(recovery) } diff --git a/compiler/rustc_expand/src/placeholders.rs b/compiler/rustc_expand/src/placeholders.rs index ad6ae5481da39..3784ec1d25e7d 100644 --- a/compiler/rustc_expand/src/placeholders.rs +++ b/compiler/rustc_expand/src/placeholders.rs @@ -1,5 +1,6 @@ use rustc_ast::mut_visit::*; use rustc_ast::token::Delimiter; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::visit::AssocCtxt; use rustc_ast::{self as ast}; use rustc_data_structures::fx::FxHashMap; @@ -20,7 +21,7 @@ pub(crate) fn placeholder( args: Box::new(ast::DelimArgs { dspan: ast::tokenstream::DelimSpan::dummy(), delim: Delimiter::Parenthesis, - tokens: ast::tokenstream::TokenStream::new(Vec::new()), + tokens: ArenaTokenStream::default(), }), }) } diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 5e01b851b75c7..30c53b9f0604a 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -1,4 +1,5 @@ use rustc_ast as ast; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::tokenstream::TokenStream; use rustc_data_structures::AtomicRef; use rustc_data_structures::profiling::TimingGuard; @@ -124,7 +125,11 @@ impl MultiItemModifier for DeriveProcMacro { }; let error_count_before = ecx.dcx().err_count(); - let mut parser = Parser::new(&ecx.sess.psess, output, Some("proc-macro derive")); + let mut parser = Parser::new( + &ecx.sess.psess, + ArenaTokenStream::from_stream(&output), + Some("proc-macro derive"), + ); let mut items = vec![]; loop { diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index c522626b39562..00b851c94314b 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -2,6 +2,7 @@ use std::ops::{Bound, Range}; use rustc_ast as ast; use rustc_ast::token as tk; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::tokenstream::{self, DelimSpacing, Spacing, TokenStream}; use rustc_ast::util::literal::escape_byte_str_symbol; use rustc_ast_pretty::pprust; @@ -576,6 +577,7 @@ impl server::Server for Rustc<'_, '_> { src.to_string(), Some(self.call_site), ) + .map(|arena| arena.to_token_stream()) }) .map_err(|_| String::from("failed to parse to tokenstream"))? .map_err(cancel_diags_into_string) @@ -588,7 +590,11 @@ impl server::Server for Rustc<'_, '_> { fn ts_expand_expr(&mut self, stream: &Self::TokenStream) -> Result { // Parse the expression from our tokenstream. let expr = try { - let mut p = Parser::new(self.psess(), stream.clone(), Some("proc_macro expand expr")); + let mut p = Parser::new( + self.psess(), + ArenaTokenStream::from_stream(stream), + Some("proc_macro expand expr"), + ); let expr = p.parse_expr()?; if p.token != tk::Eof { p.unexpected()?; diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 6d1ae563a9fa2..59afae256bd58 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -153,7 +153,7 @@ impl<'a> State<'a> { None, *delim, None, - &tokens, + &tokens.to_token_stream(), true, span, ), diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index f85a14852d6cd..2078c550d92f6 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1826,10 +1826,10 @@ impl KeywordIdents { impl EarlyLintPass for KeywordIdents { fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef) { - self.check_tokens(cx, &mac_def.body.tokens); + self.check_tokens(cx, &mac_def.body.tokens.to_token_stream()); } fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) { - self.check_tokens(cx, &mac.args.tokens); + self.check_tokens(cx, &mac.args.tokens.to_token_stream()); } fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: &Ident) { if ident.name.as_str().starts_with('\'') { diff --git a/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs b/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs index 018b921a6b016..9419eee5df061 100644 --- a/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs +++ b/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs @@ -142,6 +142,6 @@ impl Expr2024 { impl EarlyLintPass for Expr2024 { fn check_mac_def(&mut self, cx: &crate::EarlyContext<'_>, mc: &rustc_ast::MacroDef) { - self.check_tokens(cx, &mc.body.tokens); + self.check_tokens(cx, &mc.body.tokens.to_token_stream()); } } diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index 6ed61a9f4e01d..554365c6fd9bf 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -1,7 +1,7 @@ use diagnostics::make_errors_for_mismatched_closing_delims; use rustc_ast::ast::{self, AttrStyle}; use rustc_ast::token::{self, CommentKind, Delimiter, IdentIsRaw, Token, TokenKind}; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStreamBuilder; use rustc_ast::util::unicode::{TEXT_FLOW_CONTROL_CHARS, contains_text_flow_control_chars}; use rustc_errors::codes::*; use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, StashKey}; @@ -67,9 +67,10 @@ pub(crate) fn lex_token_trees<'psess, 'src>( psess: &'psess ParseSess, mut src: &'src str, mut start_pos: BytePos, + arena: &mut ArenaTokenStreamBuilder, override_span: Option, strip_tokens: StripTokens, -) -> Result>> { +) -> Result<(), Vec>> { match strip_tokens { StripTokens::Shebang | StripTokens::ShebangAndFrontmatter => { if let Some(shebang_len) = rustc_lexer::strip_shebang(src) { @@ -98,15 +99,15 @@ pub(crate) fn lex_token_trees<'psess, 'src>( token: Token::dummy(), diag_info: TokenTreeDiagInfo::default(), }; - let res = lexer.lex_token_trees(/* is_delimited */ false); + let res = lexer.lex_token_trees(arena, /* is_delimited */ false); let mut unmatched_closing_delims: Vec<_> = make_errors_for_mismatched_closing_delims(&lexer.diag_info.unmatched_delims, psess); match res { - Ok((_open_spacing, stream)) => { + Ok(_) => { if unmatched_closing_delims.is_empty() { - Ok(stream) + Ok(()) } else { // Return error if there are unmatched delimiters or unclosed delimiters. Err(unmatched_closing_delims) diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs index 3455947471503..b9a62661bd788 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -1,5 +1,6 @@ use rustc_ast::token::{self, Delimiter, Token}; -use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; +use rustc_ast::tokenarena::{ArenaTokenStreamBuilder, ArenaTokenTree, DelimitedData}; +use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing}; use rustc_ast_pretty::pprust::token_to_string; use rustc_errors::Diag; @@ -13,48 +14,47 @@ impl<'psess, 'src> Lexer<'psess, 'src> { // opening delimiter. pub(super) fn lex_token_trees( &mut self, + arena: &mut ArenaTokenStreamBuilder, is_delimited: bool, - ) -> Result<(Spacing, TokenStream), Diag<'psess>> { + ) -> Result> { // Move past the opening delimiter. let open_spacing = self.bump_minimal(); - let mut buf = Vec::new(); loop { if let Some(delim) = self.token.kind.open_delim() { // Invisible delimiters cannot occur here because `TokenTreesReader` parses // code directly from strings, with no macro expansion involved. debug_assert!(!matches!(delim, Delimiter::Invisible(_))); - buf.push(match self.lex_token_tree_open_delim(delim) { - Ok(val) => val, + let delimited = arena.start_delimited(); + let value = match self.lex_token_tree_open_delim(arena, delim) { + Ok(value) => value, Err(errs) => return Err(errs), - }) + }; + arena.close_delimited(delimited, value); } else if let Some(delim) = self.token.kind.close_delim() { // Invisible delimiters cannot occur here because `TokenTreesReader` parses // code directly from strings, with no macro expansion involved. debug_assert!(!matches!(delim, Delimiter::Invisible(_))); return if is_delimited { - Ok((open_spacing, TokenStream::new(buf))) + Ok(open_spacing) } else { Err(self.close_delim_err(delim)) }; } else if self.token.kind == token::Eof { - return if is_delimited { - Err(self.eof_err()) - } else { - Ok((open_spacing, TokenStream::new(buf))) - }; + return if is_delimited { Err(self.eof_err()) } else { Ok(open_spacing) }; } else { // Get the next normal token. let (this_tok, this_spacing) = self.bump(); - buf.push(TokenTree::Token(this_tok, this_spacing)); + arena.push_token(this_tok, this_spacing); } } } fn lex_token_tree_open_delim( &mut self, + token_builder: &mut ArenaTokenStreamBuilder, open_delim: Delimiter, - ) -> Result> { + ) -> Result> { // The span for beginning of the delimited section. let pre_span = self.token.span; @@ -63,7 +63,11 @@ impl<'psess, 'src> Lexer<'psess, 'src> { // Lex the token trees within the delimiters. // We stop at any delimiter so we can try to recover if the user // uses an incorrect delimiter. - let (open_spacing, tts) = self.lex_token_trees(/* is_delimited */ true)?; + + // We remember where we were in the arena, so that we can check how many trees were parsed + let index = token_builder.length(); + let open_spacing = self.lex_token_trees(token_builder, /* is_delimited */ true)?; + let lexed_trees = token_builder.length() - index; // Expand to cover the entire delimited token tree. let delim_span = DelimSpan::from_pair(pre_span, self.token.span); @@ -75,7 +79,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { self.diag_info.open_delimiters.pop().unwrap(); let close_delimiter_span = self.token.span; - if tts.is_empty() && close_delim == Delimiter::Brace { + if lexed_trees == 0 && close_delim == Delimiter::Brace { let empty_block_span = pre_span.to(close_delimiter_span); if !sm.is_multiline(empty_block_span) { // Only track if the block is in the form of `{}`, otherwise it is @@ -93,7 +97,8 @@ impl<'psess, 'src> Lexer<'psess, 'src> { // A brace-delimited block whose first token is `&&`/`||` usually means // the user meant to continue an if-let chain, e.g. `if let P = e { && cond {`. if Delimiter::Brace == open_delim - && let Some(TokenTree::Token(tok, _)) = tts.iter().next() + && let Some(ArenaTokenTree::Token(tok, _)) = + token_builder.get_innermost_elem_at(index) && matches!(tok.kind, token::AndAnd | token::OrOr) { self.diag_info.if_let_chain_hint_spans.push(tok.span); @@ -159,7 +164,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { let spacing = DelimSpacing::new(open_spacing, close_spacing); - Ok(TokenTree::Delimited(delim_span, spacing, open_delim, tts)) + Ok(DelimitedData { span: delim_span, spacing, delimiter: open_delim }) } // Move on to the next token, returning the current token and its spacing. diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index 539c15f18a9a4..af2c37c619f10 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -15,7 +15,7 @@ use std::sync::Arc; use rustc_ast as ast; use rustc_ast::token; -use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; +use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing}; use rustc_ast_pretty::pprust; use rustc_errors::{Diag, EmissionGuarantee, FatalError, PResult, pluralize}; pub use rustc_lexer::UNICODE_VERSION; @@ -29,6 +29,9 @@ pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments"); #[macro_use] pub mod parser; use parser::Parser; +use rustc_ast::tokenarena::{ + ArenaTokenStream, ArenaTokenStreamBuilder, ArenaTokenTree, DelimitedData, +}; use crate::lexer::StripTokens; @@ -245,7 +248,7 @@ pub fn source_str_to_stream( name: FileName, source: String, override_span: Option, -) -> Result>> { +) -> Result>> { let source_file = psess.source_map().new_source_file(name, source); // FIXME(frontmatter): Consider stripping frontmatter in a future edition. We can't strip them // in the current edition since that would be breaking. @@ -262,7 +265,7 @@ fn source_file_to_stream<'psess>( source_file: Arc, override_span: Option, strip_tokens: StripTokens, -) -> Result>> { +) -> Result>> { let src = source_file.src.as_ref().unwrap_or_else(|| { psess.dcx().bug(format!( "cannot lex `source_file` without source: {}", @@ -270,17 +273,26 @@ fn source_file_to_stream<'psess>( )); }); - lexer::lex_token_trees(psess, src.as_str(), source_file.start_pos, override_span, strip_tokens) + let mut token_builder = ArenaTokenStreamBuilder::default(); + lexer::lex_token_trees( + psess, + src.as_str(), + source_file.start_pos, + &mut token_builder, + override_span, + strip_tokens, + )?; + Ok(token_builder.finish()) } /// Runs the given subparser `f` on the tokens of the given `attr`'s item. pub fn parse_in<'a, T>( psess: &'a ParseSess, - tts: TokenStream, + arena: ArenaTokenStream, name: &'static str, mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, ) -> PResult<'a, T> { - let mut parser = Parser::new(psess, tts, Some(name)); + let mut parser = Parser::new(psess, arena, Some(name)); let result = f(&mut parser)?; if parser.token != token::Eof { parser.unexpected()?; @@ -292,9 +304,9 @@ pub fn fake_token_stream_for_item( psess: &ParseSess, item: &ast::Item, attr_to_exclude: Option<&ast::Attribute>, -) -> TokenStream { - if let Some(tokens) = fake_token_stream_for_file_mod(psess, item, attr_to_exclude) { - return tokens; +) -> ArenaTokenStream { + if let Some(stream) = fake_token_stream_for_file_mod(psess, item, attr_to_exclude) { + return stream; } let source = pprust::item_to_string(item); @@ -306,7 +318,7 @@ fn fake_token_stream_for_file_mod( psess: &ParseSess, item: &ast::Item, attr_to_exclude: Option<&ast::Attribute>, -) -> Option { +) -> Option { let ast::ItemKind::Mod(_, _, ast::ModKind::Loaded(_, ast::Inline::No { .. }, spans)) = &item.kind else { @@ -316,59 +328,62 @@ fn fake_token_stream_for_file_mod( let attr = attr_to_exclude.expect("file modules must have an attribute to exclude"); assert_eq!(attr.style, ast::AttrStyle::Inner); - let mut body_tts = Vec::new(); - body_tts.extend(lex_token_trees_for_span(psess, spans.inner_span.until(attr.span))?); - body_tts.extend(lex_token_trees_for_span( - psess, - attr.span.between(spans.inner_span.shrink_to_hi()), - )?); + let mut arena = ArenaTokenStreamBuilder::default(); - let mut wrapper_tts = Vec::new(); for attr in item.attrs.iter().filter(|attr| attr.style == ast::AttrStyle::Outer) { - wrapper_tts.extend(attr.token_trees()); + attr.push_token_trees(&mut arena); } - wrapper_tts.extend(lex_token_trees_for_span(psess, item.span)?); - let Some(TokenTree::Token(semi, _)) = wrapper_tts.pop() else { + lex_token_trees_for_span(psess, item.span, &mut arena)?; + let Some(ArenaTokenTree::Token(semi, _)) = arena.pop() else { return None; }; if semi.kind != token::Semi { return None; } - wrapper_tts.push(TokenTree::Delimited( - DelimSpan::from_single(semi.span), - DelimSpacing::new(Spacing::Alone, Spacing::Alone), - token::Delimiter::Brace, - TokenStream::new(body_tts), - )); - - Some(TokenStream::new(wrapper_tts)) + + let start = arena.start_delimited(); + lex_token_trees_for_span(psess, spans.inner_span.until(attr.span), &mut arena)?; + lex_token_trees_for_span( + psess, + attr.span.between(spans.inner_span.shrink_to_hi()), + &mut arena, + )?; + arena.close_delimited( + start, + DelimitedData { + span: DelimSpan::from_single(semi.span), + spacing: DelimSpacing::new(Spacing::Alone, Spacing::Alone), + delimiter: token::Delimiter::Brace, + }, + ); + Some(arena.finish()) } fn lex_token_trees_for_span( psess: &ParseSess, span: Span, -) -> Option> { + arena: &mut ArenaTokenStreamBuilder, +) -> Option<()> { let src = psess.source_map().span_to_snippet(span).ok()?; - let stream = match lexer::lex_token_trees(psess, &src, span.lo(), None, StripTokens::Nothing) { - Ok(stream) => stream, + match lexer::lex_token_trees(psess, &src, span.lo(), arena, None, StripTokens::Nothing) { + Ok(_) => Some(()), Err(errs) => { errs.into_iter().for_each(|err| err.cancel()); - return None; + None } - }; - Some((0..).map_while(move |index| stream.get(index).cloned())) + } } pub fn fake_token_stream_for_foreign_item( psess: &ParseSess, item: &ast::ForeignItem, -) -> TokenStream { +) -> ArenaTokenStream { let source = pprust::foreign_item_to_string(item); let filename = FileName::macro_expansion_source_code(&source); unwrap_or_emit_fatal(source_str_to_stream(psess, filename, source, Some(item.span))) } -pub fn fake_token_stream_for_crate(psess: &ParseSess, krate: &ast::Crate) -> TokenStream { +pub fn fake_token_stream_for_crate(psess: &ParseSess, krate: &ast::Crate) -> ArenaTokenStream { let source = pprust::crate_to_string_for_macros(krate); let filename = FileName::macro_expansion_source_code(&source); unwrap_or_emit_fatal(source_str_to_stream( diff --git a/compiler/rustc_parse/src/parser/cfg_select.rs b/compiler/rustc_parse/src/parser/cfg_select.rs index cf1ef62e56d5a..0c447bffb0110 100644 --- a/compiler/rustc_parse/src/parser/cfg_select.rs +++ b/compiler/rustc_parse/src/parser/cfg_select.rs @@ -1,4 +1,5 @@ use rustc_ast::token; +use rustc_ast::tokenarena::ArenaTokenTree; use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_ast::util::classify; use rustc_errors::PResult; @@ -20,11 +21,14 @@ impl<'a> Parser<'a> { if self.token == token::OpenBrace { // Strip the outer '{' and '}'. match self.parse_token_tree() { - TokenTree::Token(..) => unreachable!("because the current token is a '{{'"), - TokenTree::Delimited(.., tts) => { + ArenaTokenTree::Token(..) => unreachable!("because the current token is a '{{'"), + tree @ ArenaTokenTree::DelimitedStart(..) => { // Optionally end with a comma. let _ = self.eat(exp!(Comma)); - return Ok(tts); + return Ok(match tree.to_token_tree(&self.token_cursor.stream) { + TokenTree::Token(_, _) => unreachable!(), + TokenTree::Delimited(_, _, _, tts) => tts, + }); } } } diff --git a/compiler/rustc_parse/src/parser/function.rs b/compiler/rustc_parse/src/parser/function.rs index 57fe19226066c..3af3a1931232d 100644 --- a/compiler/rustc_parse/src/parser/function.rs +++ b/compiler/rustc_parse/src/parser/function.rs @@ -2,7 +2,7 @@ use ast::token::IdentIsRaw; use rustc_ast as ast; use rustc_ast::ast::*; use rustc_ast::token::{self, InvisibleOrigin, MetaVarKind, TokenKind}; -use rustc_ast::tokenstream::TokenTree; +use rustc_ast::tokenarena::ArenaTokenTree; use rustc_ast::util::case::Case; use rustc_ast_pretty::pprust; use rustc_errors::{Applicability, PResult}; @@ -356,8 +356,8 @@ impl<'a> Parser<'a> { && self.look_ahead(1, |t| t.can_begin_string_literal()) && (self.tree_look_ahead(2, |tt| { match tt { - TokenTree::Token(t, _) => t.is_keyword_case(kw::Fn, case), - TokenTree::Delimited(..) => false, + ArenaTokenTree::Token(t, _) => t.is_keyword_case(kw::Fn, case), + ArenaTokenTree::DelimitedStart(..) => false, } }) == Some(true) || // This branch is only for better diagnostics; `pub`, `unsafe`, etc. are not @@ -365,17 +365,17 @@ impl<'a> Parser<'a> { (self.may_recover() && self.tree_look_ahead(2, |tt| { match tt { - TokenTree::Token(t, _) => + ArenaTokenTree::Token(t, _) => ALL_QUALS.iter().any(|exp| { t.is_keyword(exp.kw) }), - TokenTree::Delimited(..) => false, + ArenaTokenTree::DelimitedStart(..) => false, } }) == Some(true) && self.tree_look_ahead(3, |tt| { match tt { - TokenTree::Token(t, _) => t.is_keyword_case(kw::Fn, case), - TokenTree::Delimited(..) => false, + ArenaTokenTree::Token(t, _) => t.is_keyword_case(kw::Fn, case), + ArenaTokenTree::DelimitedStart(..) => false, } }) == Some(true) ) diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index b252a378722f3..0fda5e5a3d060 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -5,7 +5,8 @@ use ast::token::IdentIsRaw; use rustc_ast as ast; use rustc_ast::ast::*; use rustc_ast::token::{self, Delimiter, MetaVarKind, TokenKind}; -use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree}; +use rustc_ast::tokenarena::{ArenaTokenStream, ArenaTokenTree}; +use rustc_ast::tokenstream::DelimSpan; use rustc_ast::util::case::Case; use rustc_ast_pretty::pprust; use rustc_errors::codes::*; @@ -1116,7 +1117,7 @@ impl<'a> Parser<'a> { SUFFIXES.iter().any(|suffix| { suffix.iter().enumerate().all(|(i, kw)| { self.tree_look_ahead(i + 2, |t| { - if let TokenTree::Token(token, _) = t { + if let ArenaTokenTree::Token(token, _) = t { token.is_keyword(*kw) } else { false @@ -1661,7 +1662,7 @@ impl<'a> Parser<'a> { // might be a metavariable i.e. an invisible-delimited sequence, and // `tree_look_ahead` will consider that a single element when looking // ahead. - self.tree_look_ahead(n, |t| matches!(t, TokenTree::Delimited(_, _, Delimiter::Brace, _))) + self.tree_look_ahead(n, |t| matches!(t, ArenaTokenTree::DelimitedStart(_, data) if matches!(data.delimiter, Delimiter::Brace))) == Some(true) } @@ -2601,8 +2602,9 @@ impl<'a> Parser<'a> { let body = self.parse_token_tree(); // `MacBody` // Convert `MacParams MacBody` into `{ MacParams => MacBody }`. let bspan = body.span(); - let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>` - let tokens = TokenStream::new(vec![params, arrow, body]); + let arrow = ArenaTokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>` + let tokens = + ArenaTokenStream::new_reparented(&[params, arrow, body], &self.token_cursor.stream); let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi()); Box::new(DelimArgs { dspan, delim: Delimiter::Brace, tokens }) } else { diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 80c1eeb4ef041..d179b5f56718c 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -29,6 +29,7 @@ pub use path::PathStyle; use rustc_ast::token::{ self, IdentIsRaw, InvisibleOrigin, MetaVarKind, NtExprKind, NtPatKind, Token, TokenKind, }; +use rustc_ast::tokenarena::{ArenaTokenStream, ArenaTokenTree}; use rustc_ast::tokenstream::{ ParserRange, ParserReplacement, Spacing, TokenCursor, TokenStream, TokenTree, WithTokens, }; @@ -243,11 +244,17 @@ pub struct Parser<'a> { pub fn_body_missing_semi_guar: Option = None, } +impl<'a> Parser<'a> { + pub fn token_stream(&self) -> &ArenaTokenStream { + &self.token_cursor.stream + } +} + // This type is used a lot, e.g. it's cloned when matching many declarative macro rules with // nonterminals. Make sure it doesn't unintentionally get bigger. We only check a few arches // though, because `TokenTypeSet(u128)` alignment varies on others, changing the total size. #[cfg(all(target_pointer_width = "64", any(target_arch = "aarch64", target_arch = "x86_64")))] -rustc_data_structures::static_assert_size!(Parser<'_>, 288); +rustc_data_structures::static_assert_size!(Parser<'_>, 304); /// Stores span information about a closure. #[derive(Clone, Debug)] @@ -342,7 +349,7 @@ pub fn token_descr(token: &Token) -> String { impl<'a> Parser<'a> { pub fn new( psess: &'a ParseSess, - stream: TokenStream, + stream: ArenaTokenStream, subparser_name: Option<&'static str>, ) -> Self { let mut parser = Parser { @@ -503,7 +510,7 @@ impl<'a> Parser<'a> { fn check_noexpect_past_close_delim(&self, tok: &TokenKind) -> bool { matches!( self.token_cursor.look_ahead_past_close_delim(), - Some(TokenTree::Token(token::Token { kind, .. }, _)) if kind == tok + Some(ArenaTokenTree::Token(token::Token { kind, .. }, _)) if kind == tok ) } @@ -716,21 +723,21 @@ impl<'a> Parser<'a> { fn check_const_closure(&self) -> bool { self.is_keyword_ahead(0, &[kw::Const]) && self.look_ahead(1, |t| match &t.kind { - // async closures do not work with const closures, so we do not parse that here. - token::Ident(kw::Move | kw::Use | kw::Static, IdentIsRaw::No) - | token::OrOr - | token::Or => true, - _ => false, - }) + // async closures do not work with const closures, so we do not parse that here. + token::Ident(kw::Move | kw::Use | kw::Static, IdentIsRaw::No) + | token::OrOr + | token::Or => true, + _ => false, + }) } fn check_inline_const(&self, dist: usize) -> bool { self.is_keyword_ahead(dist, &[kw::Const]) && self.look_ahead(dist + 1, |t| match &t.kind { - token::OpenBrace => true, - token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Block)) => true, - _ => false, - }) + token::OpenBrace => true, + token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Block)) => true, + _ => false, + }) } /// Checks to see if the next token is either `+` or `+=`. @@ -1156,10 +1163,13 @@ impl<'a> Parser<'a> { Some(tree) => { // Indexing stayed within the current token tree. match tree { - TokenTree::Token(token, _) => return looker(token), - &TokenTree::Delimited(dspan, _, delim, _) => { - if !delim.skip() { - return looker(&Token::new(delim.as_open_token_kind(), dspan.open)); + ArenaTokenTree::Token(token, _) => return looker(token), + &ArenaTokenTree::DelimitedStart(_, data) => { + if !data.delimiter.skip() { + return looker(&Token::new( + data.delimiter.as_open_token_kind(), + data.span.open, + )); } } } @@ -1200,7 +1210,7 @@ impl<'a> Parser<'a> { pub fn tree_look_ahead( &self, dist: usize, - looker: impl FnOnce(&TokenTree) -> R, + looker: impl FnOnce(&ArenaTokenTree) -> R, ) -> Option { self.token_cursor.look_ahead(dist).map(looker) } @@ -1231,7 +1241,7 @@ impl<'a> Parser<'a> { } else { None } - .map(|(kind, span)| CoroutineMarker::new(kind, span)) + .map(|(kind, span)| CoroutineMarker::new(kind, span)) } /// Parses fn unsafety: `unsafe`, `safe` or nothing. @@ -1376,20 +1386,24 @@ impl<'a> Parser<'a> { || self.check(exp!(OpenBrace)); delimited.then(|| { - let TokenTree::Delimited(dspan, _, delim, tokens) = self.parse_token_tree() else { + let ArenaTokenTree::DelimitedStart(bounds, data) = self.parse_token_tree() else { unreachable!() }; - DelimArgs { dspan, delim, tokens } + DelimArgs { + dspan: data.span, + delim: data.delimiter, + tokens: ArenaTokenStream::separate_delimited_inner(bounds, &self.token_cursor.stream), + } }) } /// Parses a single token tree from the input. - pub fn parse_token_tree(&mut self) -> TokenTree { + pub fn parse_token_tree(&mut self) -> ArenaTokenTree { if self.token.kind.open_delim().is_some() { // Clone the `TokenTree::Delimited` that we are currently // within. That's what we are going to return. let tree = self.token_cursor.clone_enclosing_delim(); - debug_assert_matches!(tree, TokenTree::Delimited(..)); + debug_assert_matches!(tree, ArenaTokenTree::DelimitedStart(..)); // Advance the token cursor through the entire delimited // sequence. After getting the `OpenDelim` we are *within* the @@ -1425,7 +1439,7 @@ impl<'a> Parser<'a> { assert!(!self.token.kind.is_close_delim_or_eof()); let prev_spacing = self.token_spacing; self.bump(); - TokenTree::Token(self.prev_token, prev_spacing) + ArenaTokenTree::Token(self.prev_token, prev_spacing) } } @@ -1438,7 +1452,9 @@ impl<'a> Parser<'a> { result.push(self.parse_token_tree()); } } - TokenStream::new(result) + TokenStream::new( + result.into_iter().map(|tt| tt.to_token_tree(&self.token_cursor.stream)).collect(), + ) } /// Evaluates the closure with restrictions in place. diff --git a/compiler/rustc_parse/src/parser/nonterminal.rs b/compiler/rustc_parse/src/parser/nonterminal.rs index 9f9545c194082..f07792f23ef54 100644 --- a/compiler/rustc_parse/src/parser/nonterminal.rs +++ b/compiler/rustc_parse/src/parser/nonterminal.rs @@ -125,7 +125,9 @@ impl<'a> Parser<'a> { // we always capture tokens for any nonterminal that needs them. match kind { // Note that TT is treated differently to all the others. - NonterminalKind::TT => Ok(ParseNtResult::Tt(self.parse_token_tree())), + NonterminalKind::TT => Ok(ParseNtResult::Tt( + self.parse_token_tree().to_token_tree(&self.token_cursor.stream), + )), NonterminalKind::Item => match self .parse_item(ForceCollect::Yes, AllowConstBlockItems::Yes)? { diff --git a/src/librustdoc/clean/render_macro_matchers.rs b/src/librustdoc/clean/render_macro_matchers.rs index a69e3808bd7f7..444eafb2e7dc8 100644 --- a/src/librustdoc/clean/render_macro_matchers.rs +++ b/src/librustdoc/clean/render_macro_matchers.rs @@ -88,7 +88,11 @@ fn snippet_equal_to_token(tcx: TyCtxt<'_>, matcher: &TokenTree) -> Option, tt: &TokenTree) { diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 012c4997db9c1..e9cc246622fec 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -653,15 +653,16 @@ pub(super) fn display_macro_source(tcx: TyCtxt<'_>, name: Symbol, def: &ast::Mac if def.macro_rules { format!( "macro_rules! {name} {{\n{arms}}}", - arms = render_macro_arms(tcx, &def.body.tokens, ";") + arms = render_macro_arms(tcx, &def.body.tokens.to_token_stream(), ";") ) } else { - if def.body.tokens.len() <= 4 { + if def.body.tokens.to_token_stream().len() <= 4 { format!( "macro {name}{matchers} {{\n ...\n}}", matchers = def .body .tokens + .to_token_stream() .get(0) .map(|matcher| render_macro_matcher(tcx, matcher)) .unwrap_or_default(), @@ -669,7 +670,7 @@ pub(super) fn display_macro_source(tcx: TyCtxt<'_>, name: Symbol, def: &ast::Mac } else { format!( "macro {name} {{\n{arms}}}", - arms = render_macro_arms(tcx, &def.body.tokens, ",") + arms = render_macro_arms(tcx, &def.body.tokens.to_token_stream(), ",") ) } } diff --git a/src/librustdoc/doctest/make.rs b/src/librustdoc/doctest/make.rs index 1fe62015b2c55..f471a0eeeeca5 100644 --- a/src/librustdoc/doctest/make.rs +++ b/src/librustdoc/doctest/make.rs @@ -614,7 +614,8 @@ fn parse_source( // in the macro input (!) to crudely detect main functions "masked by a // wrapper macro". For the record, this is a horrible heuristic! // See . - let mut iter = mac_call.mac.args.tokens.iter(); + let iter = mac_call.mac.args.tokens.to_token_stream(); + let mut iter = iter.iter(); while let Some(token) = iter.next() { if let TokenTree::Token(token, _) = token && let TokenKind::Ident(kw::Fn, _) = token.kind